Main method of the WorkerUpdates worker
772702
def start(self):
        """"""
        if is_anaconda():
            self.url = 'https://repo.anaconda.com/pkgs/main'
            if os.name == 'nt':
                self.url += '/win-64/repodata.json'
            elif sys.platform == 'darwin':
                self.url += '/osx-64/repodata.json'
            else:
                self.url += '/linux-64/repodata.json'
        else:
            self.url = ('https://api.github.com/repos/'
                        'spyder-ide/spyder/releases')
        self.update_available = False
        self.latest_release = __version__

        error_msg = None

        try:
            if hasattr(ssl, '_create_unverified_context'):
                # Fix for issue # 2685 [Works only with Python >=2.7.9]
                # More info: https://www.python.org/dev/peps/pep-0476/#opting-out
                context = ssl._create_unverified_context()
                page = urlopen(self.url, context=context)
            else:
                page = urlopen(self.url)
            try:
                data = page.read()

                # Needed step for python3 compatibility
                if not is_text_string(data):
                    data = data.decode()
                data = json.loads(data)

                if is_anaconda():
                    if self.releases is None:
                        self.releases = []
                        for item in data['packages']:
                            if ('spyder' in item and
                                    not re.search(r'spyder-[a-zA-Z]', item)):
                                self.releases.append(item.split('-')[1])
                    result = self.check_update_available()
                else:
                    if self.releases is None:
                        self.releases = [item['tag_name'].replace('v', '')
                                         for item in data]
                        self.releases = list(reversed(self.releases))

                result = self.check_update_available()
                self.update_available, self.latest_release = result
            except Exception:
                error_msg = _('Unable to retrieve information.')
        except HTTPError:
            error_msg = _('Unable to retrieve information.')
        except URLError:
            error_msg = _('Unable to connect to the internet. <br><br>Make '
                          'sure the connection is working properly.')
        except Exception:
            error_msg = _('Unable to check for updates.')

        # Don't show dialog when starting up spyder and an error occur
        if not (self.startup and error_msg is not None):
            self.error = error_msg
            self.sig_ready.emit()
1108168
public function main()
    {
        $pull = $this->getFactoryInstance('update');
        try {
            $pull->setBranch($this->getBranch());
        } catch (Exception $ex) {
            $this->log("Caught: " . $ex->getMessage(), Project::MSG_DEBUG);
        }
        $pull->setClean($this->getClean());
        $pull->setQuiet($this->getQuiet());

        $cwd = getcwd();

        if ($this->repository === '') {
            $prog = $this->getProject();
            $dir = $prog->getProperty('application.startdir');
        } else {
            $dir = $this->repository;
        }

        $this->checkRepositoryIsDirAndExists($dir);
        chdir($dir);
        try {
            $this->log("Executing: " . $pull->asString(), Project::MSG_INFO);
            $output = $pull->execute();
            if ($output !== '') {
                $this->log($output);
            }
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $p = strpos($msg, 'hg returned:');
            if ($p !== false) {
                $msg = substr($msg, $p + 13);
            }
            chdir($cwd);
            throw new BuildException($msg);
        }
        chdir($cwd);
    }
569558
public void updateTaskData() {
        // Only update the local task list of topologyContext here. Because
        // other
        // relative parts in context shall be updated while the updating of
        // WorkerData (Task2Component and Component2Task map)
        List<Integer> localTasks = JStormUtils.mk_list(workerData.getTaskIds());
        topologyContext.setThisWorkerTasks(localTasks);
        userContext.setThisWorkerTasks(localTasks);

        // Update the TaskSendTargets
        updateSendTargets();
    }
753041
def initialize_worker(self):
        """"""
        worker_thread = threading.Thread(
            name="WorkerThread", target=message_worker, args=(self,))
        worker_thread.setDaemon(True)
        worker_thread.start()
895103
def setupWorkerTransition():
    """"""

    default_warn_method = getWarningMethod()

    def custom_warn_method(message, category, stacklevel):
        if stacklevel is not None:
            stacklevel += 1
        if _WORKER_WARNING_MARK in message:
            # Message contains our mark - it's Worker API Renaming warning,
            # issue it appropriately.
            message = message.replace(_WORKER_WARNING_MARK, "")
            warnings.warn(
                DeprecatedWorkerNameWarning(message), message, stacklevel)
        else:
            # Other's warning message
            default_warn_method(message, category, stacklevel)

    setWarningMethod(custom_warn_method)
598864
function startWorkers() {
        _.range(0, numWorkers).forEach(function (index) {
            workers.push(startWorker(startPort + index));
        });
    }
47378
function spawnWorker() {

        // Create a new worker
        const worker = cluster.fork();

        // Automatically respawn the workers on exit
        worker.on("exit", function () {
            logger("Spawning new worker to replace", worker.process.pid);
            spawnWorker();
        });

        // Listen for messages from this worker
        worker.on("message", messageFromWorker);
    }
1265364
def main():
    """"""
    from docopt import docopt; arguments = docopt(__doc__, version=package.title() + " v" + version)
    global verbose
    verbose = arguments['--verbose']

    if verbose:
	print("target folder: " + target_folder + " (" + project_path +"/" + target_folder + ")")

    if arguments['init']:
	init_current_directory()

    if arguments['build']:
	if arguments['<file>']:
	    buildFile(arguments['<file>'])
	else:
	    buildAll()

    if arguments['watch']:
	if verbose:
	    print("Watching " + project_path)
        import time
	from watchdog.observers import Observer
	event_handler = MyWatchHandler()
	observer = Observer()
	observer.schedule(event_handler, project_path, recursive=True)
	observer.start()
	try:
	    while True:
	        time.sleep(1)
	except KeyboardInterrupt:
	    observer.stop()
	observer.join()

    if arguments['clean']:
	clean()
315700
public function run()
    {
        try {
            $this->loop->run();
        } catch (WorkerException $e) {
            $this->logger->error('Worker Error: ' . $e->getMessage());
        }
    }
662830
def run_updater_in_background(self):
        
        thread = threading.Thread(target=self.updater_loop())
        thread.daemon = True
        thread.start()
497281
function () {
        function checkUpdate() {
            var current = module.exports.current();
            if (current !== last) {
                last = current;
                events.trigger('update', current);
            }
        }

        // Do not run unless breakpoints are available.
        if (!running && breakpoints.length) {
            running = true;
            global.addEventListener('resize', function () {
                if (!working) {
                    working = true;
                    global.requestAnimationFrame(function () {
                        checkUpdate();
                        working = false;
                    });
                }
            });
        }
        checkUpdate();
    }
721712
public function run()
    {
        //Update process state.
        static::$_status = static::STATUS_RUNNING;

        // Register shutdown function for checking errors.
        register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));

        // Set autoload root path.
        Autoloader::setRootPath($this->_autoloadRootPath);

        // Create a global event loop.
        if (!static::$globalEvent) {
            $event_loop_class = static::getEventLoopName();
            static::$globalEvent = new $event_loop_class;
            $this->resumeAccept();
        }

        // Reinstall signal.
        static::reinstallSignal();

        // Init Timer.
        Timer::init(static::$globalEvent);

        // Set an empty onMessage callback.
        if (empty($this->onMessage)) {
            $this->onMessage = function () {};
        }

        restore_error_handler();
        
        // Try to emit onWorkerStart callback.
        if ($this->onWorkerStart) {
            try {
                call_user_func($this->onWorkerStart, $this);
            } catch (\Exception $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            } catch (\Error $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            }
        }

        // Main loop.
        static::$globalEvent->loop();
    }
1079703
def start_worker(self, row):
        ''''''
        def on_worker_started(worker, fs_id):
            pass

        def on_worker_received(worker, fs_id, received, received_total):
            GLib.idle_add(do_worker_received, fs_id, received, received_total)

        def do_worker_received(fs_id, received, received_total):
            self.download_speed_add(received)
            row = None
            if fs_id in self.workers:
                row = self.workers[fs_id][1]
            else:
                row = self.get_row_by_fsid(fs_id)
            if not row:
                return

            row[CURRSIZE_COL] = received_total
            curr_size = util.get_human_size(row[CURRSIZE_COL], False)[0]
            total_size = util.get_human_size(row[SIZE_COL])[0]
            row[PERCENT_COL] = int(row[CURRSIZE_COL] / row[SIZE_COL] * 100)
            row[HUMANSIZE_COL] = '{0} / {1}'.format(curr_size, total_size)
            self.update_task_db(row)

        def on_worker_downloaded(worker, fs_id):
            GLib.idle_add(do_worker_downloaded, fs_id)

        def do_worker_downloaded(fs_id):
            row = None
            if fs_id in self.workers:
                row = self.workers[fs_id][1]
            else:
                row = self.get_row_by_fsid(fs_id)
            if not row:
                return
            row[CURRSIZE_COL] = row[SIZE_COL]
            row[STATE_COL] = State.FINISHED
            row[PERCENT_COL] = 100
            total_size = util.get_human_size(row[SIZE_COL])[0]
            row[HUMANSIZE_COL] = '{0} / {1}'.format(total_size, total_size)
            row[STATENAME_COL] = StateNames[State.FINISHED]
            self.update_task_db(row)
            self.check_commit(force=True)
            self.workers.pop(row[FSID_COL], None)
            self.app.toast(_('{0} downloaded'.format(row[NAME_COL])))
            self.launch_app(fs_id)
            self.scan_tasks()

        def on_worker_network_error(worker, fs_id):
            GLib.idle_add(do_worker_network_error, fs_id)

        def do_worker_network_error(fs_id):
            row = self.workers.get(fs_id, None)
            if row:
                row = row[1]
            else:
                row = self.get_row_by_fsid(fs_id)
                if not row:
                    return
            row[STATE_COL] = State.ERROR
            row[STATENAME_COL] = StateNames[State.ERROR]
            self.update_task_db(row)
            self.remove_worker(row[FSID_COL], stop=False)
            if self.app.profile['retries-each']:
                GLib.timeout_add(self.app.profile['retries-each'] * 60000,
                                 self.restart_task, row)
            else:
                self.app.toast(_('Error occurs will downloading {0}').format(
                               row[NAME_COL]))
            self.scan_tasks()

        def do_worker_disk_error(fs_id, tmp_filepath):
            # do not retry on disk-error
            self.app.toast(_('Disk Error: failed to read/write {0}').format(
                           tmp_filepath))

        def on_worker_disk_error(worker, fs_id, tmp_filepath):
            GLib.idle_add(do_worker_disk_error, fs_id, tmp_filepath)

        if not row or row[FSID_COL] in self.workers:
            return
        row[STATE_COL] = State.DOWNLOADING
        row[STATENAME_COL] = StateNames[State.DOWNLOADING]
        worker = Downloader(self, row)
        self.workers[row[FSID_COL]] = (worker, row)
        worker.connect('started', on_worker_started)
        worker.connect('received', on_worker_received)
        worker.connect('downloaded', on_worker_downloaded)
        worker.connect('network-error', on_worker_network_error)
        worker.connect('disk-error', on_worker_disk_error)
        worker.start()
928368
public void start() {
		this.workerThread = new Thread(this);
		System.out.println("starting worker thread");
		this.workerThread.start();
		System.out.println("worker thread started");
	}
230107
function worker () {
  var indexedDB = self.indexedDB
  var db
  var methodMap = {
    connect: connect,
    disconnect: disconnect,
    create: create,
    update: update,
    delete: remove,
    deleteAll: removeAll
  }

  self.addEventListener('message', function (event) {
    var data = event.data
    var id = data.id
    var method = data.method

    methodMap[method](data, function (error, result, transfer) {
      if (error) {
        self.postMessage({
          id: id, error: '' + error
        })
        return
      }

      self.postMessage({
        id: id, result: result
      }, transfer)
    })
  })


  function connect (data, callback) {
    var request = indexedDB.open(data.name)
    var typesArray = data.typesArray

    request.onerror = errorConnection
    request.onupgradeneeded = handleUpgrade
    request.onsuccess = handleSuccess

    function handleSuccess (event) {
      var i, j

      db = event.target.result

      for (i = 0, j = typesArray.length; i < j; i++)
        if (!~Array.prototype.indexOf.call(
          db.objectStoreNames, typesArray[i])) {
          reconnect()
          return
        }

      loadRecords()
    }

    function handleUpgrade (event) {
      var i, j, type

      db = event.target.result

      for (i = 0, j = typesArray.length; i < j; i++) {
        type = typesArray[i]
        if (!~Array.prototype.indexOf.call(db.objectStoreNames, type))
          db.createObjectStore(type, { keyPath: primaryKey })
      }

      for (i = 0, j = db.objectStoreNames.length; i < j; i++) {
        type = db.objectStoreNames[i]
        if (!~Array.prototype.indexOf.call(typesArray, type))
          db.deleteObjectStore(type)
      }
    }

    function reconnect () {
      var version = (db.version || 1) + 1

      db.close()
      request = indexedDB.open(data.name, version)
      request.onerror = errorReconnection
      request.onupgradeneeded = handleUpgrade
      request.onsuccess = function (event) {
        db = event.target.result
        loadRecords(db)
      }
    }

    function loadRecords () {
      var counter = 0
      var payload = {}
      var transfer = []
      var i, j

      for (i = 0, j = typesArray.length; i < j; i++)
        loadType(typesArray[i])

      function loadType (type) {
        var transaction = db.transaction(type, 'readonly')
        var objectStore = transaction.objectStore(type)
        var cursor = objectStore.openCursor()

        payload[type] = []
        cursor.onsuccess = function (event) {
          var iterator = event.target.result
          if (iterator) {
            payload[type].push(iterator.value[dataKey])
            transfer.push(iterator.value[dataKey].buffer)
            iterator.continue()
            return
          }
          counter++
          if (counter === typesArray.length)
            callback(null, payload, transfer)
        }
        cursor.onerror = errorIteration
      }
    }

    function errorConnection () {
      callback('The database connection could not be established.')
    }

    function errorReconnection () {
      callback('An attempt to reconnect failed.')
    }

    function errorIteration () {
      callback('Failed to read record.')
    }
  }


  function disconnect () {
    db.close()
  }


  function create (data, callback) {
    var recordsLength = Object.keys(data.records).length
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var id, record, object, request, counter = 0

    for (id in data.records) {
      record = data.records[id]
      object = {}
      object[primaryKey] = type + delimiter + id
      object[dataKey] = record
      request = objectStore.add(object)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === recordsLength) callback()
    }

    function error () {
      callback('A record could not be created.')
    }
  }


  function update (data, callback) {
    var recordsLength = Object.keys(data.records).length
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var id, record, object, request, counter = 0

    for (id in data.records) {
      record = data.records[id]
      object = {}

      // Here it should be assumed that the type and delimiter are already
      // supplied, rather than needing to add it here.
      object[primaryKey] = id

      object[dataKey] = record
      request = objectStore.put(object)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === recordsLength) callback()
    }

    function error () {
      callback('A record could not be updated.')
    }
  }


  function remove (data, callback) {
    var type = data.type
    var ids = data.ids
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var i, j, id, request, counter = 0

    for (i = 0, j = ids.length; i < j; i++) {
      id = ids[i]
      request = objectStore.delete(type + delimiter + id)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === ids.length) callback()
    }

    function error () {
      callback('A record could not be deleted.')
    }
  }


  function removeAll (data, callback) {
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var request = objectStore.clear()
    request.onsuccess = function () { callback() }
    request.onerror = error

    function error () {
      callback('Not all records could be deleted.')
    }
  }
}
491910
def UpdateSNMPObjs():
	

	global threadingString

	LogMsg("Beginning data update.")
	data = ""

	# Obtain the data by calling an external command. We don't use
	# subprocess.check_output() here for compatibility with Python versions
	# older than 2.7.
	LogMsg("Calling external command \"sleep 5; date\".")
	proc = subprocess.Popen(
		"sleep 5; date", shell=True, env={ "LANG": "C" },
		stdout=subprocess.PIPE, stderr=subprocess.STDOUT
	)
	output = proc.communicate()[0].splitlines()[0]
	rc = proc.poll()
	if rc != 0:
		LogMsg("An error occured executing the command: {0}".format(output))
		return

	msg = "Updating \"threadingString\" object with data \"{0}\"."
	LogMsg(msg.format(output))
	threadingString.update(output)

	LogMsg("Data update done, exiting thread.")
1192657
private void updateWorker(final Worker worker)
  {
    final ZkWorker zkWorker = zkWorkers.get(worker.getHost());
    if (zkWorker != null) {
      log.info("Worker[%s] updated its announcement from[%s] to[%s].", worker.getHost(), zkWorker.getWorker(), worker);
      zkWorker.setWorker(worker);
    } else {
      log.warn(
          "WTF, worker[%s] updated its announcement but we didn't have a ZkWorker for it. Ignoring.",
          worker.getHost()
      );
    }
  }