comment
stringlengths
16
255
code
stringlengths
52
3.87M
Handle "end of data" situations @param context the encoder context @param buffer the buffer with the remaining encoded characters
void handleEOD(EncoderContext context, StringBuilder buffer) { int unwritten = (buffer.length() / 3) * 2; int rest = buffer.length() % 3; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount; if (rest == 2) { buffer.append('\0'); //Shift 1 while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else if (available == 1 && rest == 1) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } // else no unlatch context.pos--; } else if (rest == 0) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (available > 0 || context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else { throw new IllegalStateException("Unexpected case. Please report!"); } context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); }
Called when a key is pressed.
@Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_ENTER: case KeyEvent.VK_DELETE: case KeyEvent.VK_TAB: e.consume(); break; } }
// String colorized service status message.
func (u configGetMessage) String() string { config, e := json.MarshalIndent(u.Config, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(config) }
gets rtf image height @return integer
private function getImageRtfHeight() { if ($this->_height > 0) { return PHPRtfLite_Unit::getUnitInTwips($this->_height); } $imageHeight = $this->_imageHeight ? $this->_imageHeight : 100; if ($this->_width > 0) { $imageWidth = $this->_imageWidth ? $this->_imageWidth : 100; $height = ($imageHeight /$imageWidth) * $this->_width; return PHPRtfLite_Unit::getUnitInTwips($height); } return PHPRtfLite_Unit::getPointsInTwips($imageHeight); }
Creates a new file client. @class The file client provides a convenience API for interacting with file services provided by plugins. This class handles authorization, and authentication-related error handling. @name orion.fileClient.FileClient
function FileClient(serviceRegistry, filter) { var _patterns; var _services; var _names; EventTarget.attach(this); /* @callback */ function _noMatch(loc) { var d = new Deferred(); d.reject(messages["No Matching FileService for location:"] + loc); return d; } var _fileSystemsRoots = []; var _allFileSystemsService = { /* @callback */ fetchChildren: function() { var d = new Deferred(); d.resolve(_fileSystemsRoots); return d; }, /* @callback */ createWorkspace: function() { var d = new Deferred(); d.reject(messages["no file service"]); return d; }, /* @callback */ loadWorkspaces: function() { var d = new Deferred(); d.reject(messages['no file service']); return d; }, /* @callback */ loadWorkspace: function(loc) { var d = new Deferred(); window.setTimeout(function() { d.resolve({ Directory: true, Length: 0, LocalTimeStamp: 0, Name: messages["File Servers"], Location: "/", Children: _fileSystemsRoots, ChildrenLocation: "/" }); }, 100); return d; }, /* @callback */ read: function(loc) { if (loc === "/") { return this.loadWorkspace(loc); } return _noMatch(loc); }, /** * @description Computes the project context from the given location * @param {String} context The resource context to find the project for * @since 14.0 */ getProject: _noMatch, search: _noMatch, createProject: _noMatch, createFolder: _noMatch, createFile: _noMatch, deleteFile: _noMatch, moveFile: _noMatch, copyFile: _noMatch, write: _noMatch }; /** * @description Initialize the service * @private */ function init() { if (_services) { return; } _patterns = []; _services = []; _names = []; var allReferences = serviceRegistry.getServiceReferences("orion.core.file"); //$NON-NLS-1$ var _references = allReferences; if (filter) { _references = []; for(var i = 0; i < allReferences.length; ++i) { if (filter(allReferences[i])) { _references.push(allReferences[i]); } } } _references.sort(function (ref1, ref2) { var ranking1 = ref1.getProperty("ranking") || 0; //$NON-NLS-1$ var ranking2 = ref2.getProperty("ranking") || 0; //$NON-NLS-1$ return ranking1 - ranking2; }); for(var j = 0; j < _references.length; ++j) { _fileSystemsRoots[j] = { Directory: true, Length: 0, LocalTimeStamp: 0, Location: _references[j].getProperty("top"), //$NON-NLS-1$ ChildrenLocation: _references[j].getProperty("top"), //$NON-NLS-1$ Name: _references[j].getProperty("Name") || _references[j].getProperty("NameKey") //$NON-NLS-1$ //$NON-NLS-2$ }; var filetop = _references[j].getProperty("top"); //$NON-NLS-1$ var patternStringArray = _references[j].getProperty("pattern") || (filetop ? filetop.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1") : ""); //$NON-NLS-1$ //$NON-NLS-2$ if (!Array.isArray(patternStringArray)) { patternStringArray = [patternStringArray]; } var patterns = []; for (var k = 0; k < patternStringArray.length; k++) { var patternString = patternStringArray[k]; if (patternString[0] !== "^") { patternString = "^" + patternString; } patterns.push(new RegExp(patternString)); } _patterns[j] = patterns; _services[j] = serviceRegistry.getService(_references[j]); _names[j] = _references[j].getProperty("Name") || _references[j].getProperty("NameKey"); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * @description Returns the index of the service for the given item location * @function * @private * @param {String} itemLocation * @returns returns */ this._getServiceIndex = function(itemLocation) { init(); // client must specify via "/" when a multi file service tree is truly wanted if (itemLocation === "/") { return -1; } else if (!itemLocation || itemLocation.length && itemLocation.length === 0) { // TODO we could make the default file service a preference but for now we use the first one return _services[0] ? 0 : -1; } for(var i = 0; i < _patterns.length; ++i) { for (var j = 0; j < _patterns[i].length; j++) { if (_patterns[i][j].test(itemLocation)) { return i; } } } throw new Error(i18nUtil.formatMessage(messages['NoFileSrv'], itemLocation)); }; /** * Returns the file service managing this location * @param {String} itemLocation The location of the item * @private * @returns {FileClient} The service for the given item */ this._getService = function(itemLocation) { var i = this._getServiceIndex(itemLocation); return i === -1 ? _allFileSystemsService : _services[i]; }; /** * Returns the name of the file service managing this location * @param {String} itemLocation The location of the item * @private * @return {String} The name of this file service */ this._getServiceName = function(itemLocation) { var i = this._getServiceIndex(itemLocation); return i === -1 ? _allFileSystemsService.Name : _names[i]; }; /** * Returns the root url of the file service managing this location * @param {String} itemLocation The location of the item * @private * @return {String} The root URL of the given item */ this._getServiceRootURL = function(itemLocation) { var i = this._getServiceIndex(itemLocation); return i === -1 ? _allFileSystemsService.Location : _fileSystemsRoots[i].Location; }; this._frozenEvent = {type: "Changed"}; this._eventFrozenMode = false; serviceRegistry.registerService("orion.core.file.client", this); //$NON-NLS-1$ }
// forceAdd is used to force a lookup of the given deployment object and create // a watcher. If the deployment does not exist or is terminal an error is // returned.
func (w *Watcher) forceAdd(dID string) (*deploymentWatcher, error) { snap, err := w.state.Snapshot() if err != nil { return nil, err } deployment, err := snap.DeploymentByID(nil, dID) if err != nil { return nil, err } if deployment == nil { return nil, fmt.Errorf("unknown deployment %q", dID) } return w.addLocked(deployment) }
// send sends a changed total capacity event to the subscribers
func (s tcSubs) send(tc uint64, underrun bool) { for sub := range s { select { case <-sub.rpcSub.Err(): delete(s, sub) case <-sub.notifier.Closed(): delete(s, sub) default: if underrun || !sub.onlyUnderrun { sub.notifier.Notify(sub.rpcSub.ID, tc) } } } }
Test limits and take actions if they have been exceeded @param MvcEvent $event
public function check(MvcEvent $event) { foreach ($this->limits as $limit) { if ($this->storage->check($this->remoteAddress->getIpAddress(), $limit)) { foreach ($limit->getActions() as $action) { $action($event); } } } }
// SetId sets the Id field's value.
func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyticsConfigurationInput { s.Id = &v return s }
// Update moves the camera to the center of the space component. // Values are automatically clamped to TrackingBounds by the camera.
func (c *EntityScroller) Update(dt float32) { if c.SpaceComponent == nil { return } width, height := c.SpaceComponent.Width, c.SpaceComponent.Height pos := c.SpaceComponent.Position trackToX := pos.X + width/2 trackToY := pos.Y + height/2 engo.Mailbox.Dispatch(CameraMessage{Axis: XAxis, Value: trackToX, Incremental: false}) engo.Mailbox.Dispatch(CameraMessage{Axis: YAxis, Value: trackToY, Incremental: false}) if c.Rotation { engo.Mailbox.Dispatch(CameraMessage{Axis: Angle, Value: c.SpaceComponent.Rotation, Incremental: false}) } }
Packages and submits a job, which is defined in a YAML file, to Spark. Parameters ---------- args (List): Command-line arguments
def _package_and_submit(args): args = _parse_and_validate_args(args) logging.debug(args) dist = __make_tmp_dir() try: __package_dependencies(dist_dir=dist, additional_reqs=args['requirements'], silent=args['silent']) __package_app(tasks_pkg=args['package'], dist_dir=dist, custom_main=args['main'], extra_data=args['extra_data']) __run_spark_submit(lane_yaml=args['yaml'], dist_dir=dist, spark_home=args['spark_home'], spark_args=args['spark_args'], silent=args['silent']) except Exception as exc: __clean_up(dist) raise exc __clean_up(dist)
Update constant variables. :return: None :rtype: :py:obj:`None`
def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg=""): nmrstar_constants = {} resonance_classes = {} spectrum_descriptions = {} this_directory = os.path.dirname(__file__) nmrstar2_config_filepath = os.path.join(this_directory, "conf/constants_nmrstar2.json") nmrstar3_config_filepath = os.path.join(this_directory, "conf/constants_nmrstar3.json") resonance_classes_config_filepath = os.path.join(this_directory, "conf/resonance_classes.json") spectrum_descriptions_config_filepath = os.path.join(this_directory, "conf/spectrum_descriptions.json") with open(nmrstar2_config_filepath, "r") as nmrstar2config, open(nmrstar3_config_filepath, "r") as nmrstar3config: nmrstar_constants["2"] = json.load(nmrstar2config) nmrstar_constants["3"] = json.load(nmrstar3config) with open(resonance_classes_config_filepath, "r") as config: resonance_classes.update(json.load(config)) with open(spectrum_descriptions_config_filepath, "r") as config: spectrum_descriptions.update(json.load(config)) if nmrstar2cfg: with open(nmrstar2cfg, "r") as nmrstar2config: nmrstar_constants["2"].update(json.load(nmrstar2config)) if nmrstar3cfg: with open(nmrstar2cfg, "r") as nmrstar3config: nmrstar_constants["3"].update(json.load(nmrstar3config)) if resonance_classes_cfg: with open(nmrstar2cfg, "r") as config: resonance_classes.update(json.load(config)) if spectrum_descriptions_cfg: with open(spectrum_descriptions_cfg, "r") as config: spectrum_descriptions.update(json.load(config)) NMRSTAR_CONSTANTS.update(nmrstar_constants) RESONANCE_CLASSES.update(resonance_classes) SPECTRUM_DESCRIPTIONS.update(spectrum_descriptions)
// Dial dials the handshake service in the hypervisor. If a connection has // already been established, this function returns it. Otherwise, a new // connection is created.
func Dial(hsAddress string) (*grpc.ClientConn, error) { mu.Lock() defer mu.Unlock() if hsConn == nil { // Create a new connection to the handshaker service. Note that // this connection stays open until the application is closed. var err error hsConn, err = hsDialer(hsAddress, grpc.WithInsecure()) if err != nil { return nil, err } } return hsConn, nil }
/plaid/authenticate
def authenticate begin client = Plaid::Client.new(env: PlaidRails.env, client_id: PlaidRails.client_id, secret: PlaidRails.secret, public_key: PlaidRails.public_key) @exchange_token = client.item.public_token.exchange(link_params[:public_token]) @params = link_params.merge!(token: link_params[:public_token]) rescue => e Rails.logger.error "Error: #{e}" render text: e.message, status: 500 end end
@param array[string]mixed $arguments extra arguments to be passed to the api call @param string $format override format (defaults to one specified in config file) @return mixed
public function getProvider($arguments = [], $format = null) { $options = $this->getOptions($format)->setArguments($arguments); return $this->request->send($options); }
Set the value of [version] column. @param int $v new value @return $this|\gossi\trixionary\model\Skill The current object (for fluent API support)
public function setVersion($v) { if ($v !== null) { $v = (int) $v; } if ($this->version !== $v) { $this->version = $v; $this->modifiedColumns[SkillTableMap::COL_VERSION] = true; } return $this; }
// SetStreamId sets the StreamId field's value.
func (s *SetSourceRequest) SetStreamId(v string) *SetSourceRequest { s.StreamId = &v return s }
Receive Payment and Return Payment Model. @return PayuPayment
public function capture() { $storage = new Storage(); $config = new Config($storage->getAccount()); if ($config->getDriver() == 'database') { return PayuPayment::find($storage->getPayment()); } return new PayuPayment($storage->getPayment()); }
Whether all conditions are met @param array $trigger @param array $data @return boolean
public function isMet(array $trigger, array $data) { $result = null; $this->hook->attach('condition.met.before', $trigger, $data, $result, $this); if (isset($result)) { return (bool) $result; } if (empty($trigger['data']['conditions'])) { return false; } $result = true; $this->processed = array(); foreach ($trigger['data']['conditions'] as $condition) { if ($this->callHandler($condition, $data) !== true) { $result = false; break; } $this->processed[] = $condition['id']; } $this->hook->attach('condition.met.after', $trigger, $data, $result, $this); return (bool) $result; }
Solves the formula on the solver and returns the result. @param handler a MaxSAT handler @return the result (SAT, UNSAT, Optimum found, or UNDEF if canceled by the handler)
public MaxSAT.MaxSATResult solve(final MaxSATHandler handler) { if (this.result != UNDEF) return this.result; if (this.solver.currentWeight() == 1) this.solver.setProblemType(MaxSAT.ProblemType.UNWEIGHTED); else this.solver.setProblemType(MaxSAT.ProblemType.WEIGHTED); this.result = this.solver.search(handler); return this.result; }
@function execute execute query @returns {Promise}
function execute () { // check access and set access params this.accessControl() // build select this.select = sql.select(this.model, this.args) // debug debug(this.select.sql, this.select.params) // do query defined(this.model.cache) && this.args.cache !== false && (!this.modelViewEngine || this.modelViewEngine.cache !== false) ? this.executeQueryCached() : this.executeQueryDirect() // add queries for related records if any this.executeRelated() // build result return this.result() }
Returns all the days for the given month. @param Month $month @return DayInterface[]
public function getDays(Month $month) { $days = array(); for ($dayNo = 1; $dayNo <= $month->numberOfDays(); $dayNo++) { $days[$dayNo] = $this->getDay($month, $dayNo); } return $days; }
Fire an event off up to the master server CLI Example: .. code-block:: bash salt '*' event.fire_master '{"data":"my event data"}' 'tag'
def fire_master(data, tag, preload=None, timeout=60): ''' ''' if (__opts__.get('local', None) or __opts__.get('file_client', None) == 'local') and not __opts__.get('use_master_when_local', False): # We can't send an event if we're in masterless mode log.warning('Local mode detected. Event with tag %s will NOT be sent.', tag) return False if preload or __opts__.get('__cli') == 'salt-call': # If preload is specified, we must send a raw event (this is # slower because it has to independently authenticate) if 'master_uri' not in __opts__: __opts__['master_uri'] = 'tcp://{ip}:{port}'.format( ip=salt.utils.zeromq.ip_bracket(__opts__['interface']), port=__opts__.get('ret_port', '4506') # TODO, no fallback ) masters = list() ret = None if 'master_uri_list' in __opts__: for master_uri in __opts__['master_uri_list']: masters.append(master_uri) else: masters.append(__opts__['master_uri']) auth = salt.crypt.SAuth(__opts__) load = {'id': __opts__['id'], 'tag': tag, 'data': data, 'tok': auth.gen_token(b'salt'), 'cmd': '_minion_event'} if isinstance(preload, dict): load.update(preload) for master in masters: channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master) try: channel.send(load, timeout=timeout) # channel.send was successful. # Ensure ret is True. ret = True except Exception: # only set a False ret if it hasn't been sent atleast once if ret is None: ret = False finally: channel.close() return ret else: # Usually, we can send the event via the minion, which is faster # because it is already authenticated try: me = salt.utils.event.MinionEvent(__opts__, listen=False, keep_loop=True) return me.fire_event({'data': data, 'tag': tag, 'events': None, 'pretag': None}, 'fire_master') except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) log.debug(lines) return False
// SetState will force a specific state in-memory for this local state.
func (s *LocalState) SetState(state *terraform.State) { s.mu.Lock() defer s.mu.Unlock() s.state = state.DeepCopy() s.readState = state.DeepCopy() }
The inverse operator.
def inverse(self): """""" op = self class ShearlabOperatorInverse(odl.Operator): """Inverse of the shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverse, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: x = np.moveaxis(x, 0, -1) return shearrec2D(x, op.shearlet_system) @property def adjoint(self): """""" op = self class ShearlabOperatorInverseAdjoint(odl.Operator): """ Adjoint of the inverse/Inverse of the adjoint of shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): """Initialize a new instance.""" self.mutex = op.mutex self.shearlet_system = op.shearlet_system super(ShearlabOperatorInverseAdjoint, self).__init__( op.range, op.domain, True) def _call(self, x): """``self(x)``.""" with op.mutex: result = shearrecadjoint2D(x, op.shearlet_system) return np.moveaxis(result, -1, 0) @property def adjoint(self): """The adjoint operator.""" return op @property def inverse(self): """""" return op.inverse.adjoint return ShearlabOperatorInverseAdjoint() @property def inverse(self): """""" return op return ShearlabOperatorInverse()
Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed)
def set_pair(self, term1, term2, value, **kwargs): key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = value
Add a label to specified cell in table.
def add_label_to_table(self, row, col, txt): """""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label)
// SetTaskToken sets the TaskToken field's value.
func (s *RespondActivityTaskCanceledInput) SetTaskToken(v string) *RespondActivityTaskCanceledInput { s.TaskToken = &v return s }
@param integer $page @return \PagerFanta\PagerFanta
public function getDisplayableWorkspacesPager($page, $max = 20) { $workspaces = $this->workspaceRepo->findDisplayableWorkspaces(); return $this->pagerFactory->createPagerFromArray($workspaces, $page, $max); }
Annex M placement alogorithm low level
function placeBit(&$array, $NR, $NC, $r, $c, $p, $b) { if ($r < 0) { $r += $NR; $c += 4 - (($NR + 4) % 8); } if ($c < 0) { $c += $NC; $r += 4 - (($NC + 4) % 8); } $array[$r * $NC + $c] = ($p << 3) + $b; }
Send a request to the DNS server
def send_request nameserver = @nameservers.shift @nameservers << nameserver # rotate them begin @socket.send request_message, 0, @nameservers.first, DNS_PORT rescue Errno::EHOSTUNREACH # TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one! end end
// Add appends a migration the list.
func (m *Migrations) Add(id int, stmts ...string) { *m = append(*m, Migration{ID: id, Stmts: stmts}) }
This function sets up a command-line option parser and then calls match_and_print to do all of the real work.
def main(argv): import argparse import codecs # have to be ready to deal with utf-8 names out = codecs.getwriter('utf-8')(sys.stdout) description = 'Uses Open Tree of Life web services to find information for each OTT ID.' parser = argparse.ArgumentParser(prog='ot-taxon-info', description=description) parser.add_argument('ids', nargs='+', type=int, help='OTT IDs') parser.add_argument('--include-lineage', action='store_true', default=False, required=False, help='list the IDs of the ancestors as well.') # uncomment when https://github.com/OpenTreeOfLife/taxomachine/issues/89 is fixed @TEMP # parser.add_argument('--list-tips', action='store_true', default=False, required=False, # help='list the tips in the subtree rooted by this taxon.') args = parser.parse_args(argv) id_list = args.ids list_tips = False # args.list_tips once https://github.com/OpenTreeOfLife/taxomachine/issues/89 is fixed @TEMP fetch_and_write_taxon_info(id_list, args.include_lineage, list_tips, out)
Finds and all persona for admin. @Route("admin/list/category") @Method("GET") @Template()
public function listAction() { $entities = $this->container->get("haven_core.category.read_handler")->getAll(); foreach ($entities as $entity) { $delete_forms[$entity->getId()] = $this->container->get("haven_core.category.form_handler")->createDeleteForm($entity->getId())->createView(); } return array("entities" => $entities , 'delete_forms' => isset($delete_forms) && is_array($delete_forms) ? $delete_forms : array() , "entities" => $entities); }
Fills the analysis' uncertainty to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row
def _folder_item_uncertainty(self, analysis_brain, item): item["Uncertainty"] = "" if not self.has_permission(ViewResults, analysis_brain): return result = analysis_brain.getResult obj = self.get_object(analysis_brain) formatted = format_uncertainty(obj, result, decimalmark=self.dmk, sciformat=int(self.scinot)) if formatted: item["Uncertainty"] = formatted else: item["Uncertainty"] = obj.getUncertainty(result) if self.is_uncertainty_edition_allowed(analysis_brain): item["allow_edit"].append("Uncertainty")
在使用本方法前,必须初始化AopClient且传入公私钥参数。 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
public function rsaEncrypt($data, $rsaPublicKeyPem, $charset) { if($this->checkEmpty($this->alipayPublicKey)){ //读取字符串 $pubKey= $this->alipayrsaPublicKey; $res = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($pubKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----"; }else { //读取公钥文件 $pubKey = file_get_contents($rsaPublicKeyFilePath); //转换为openssl格式密钥 $res = openssl_get_publickey($pubKey); } ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确'); $blocks = $this->splitCN($data, 0, 30, $charset); $chrtext  = null; $encodes  = array(); foreach ($blocks as $n => $block) { if (!openssl_public_encrypt($block, $chrtext , $res)) { echo "<br/>" . openssl_error_string() . "<br/>"; } $encodes[] = $chrtext ; } $chrtext = implode(",", $encodes); return base64_encode($chrtext); }
Returns a dictionary mapping a public identifier name to a Python object. This counts the `__init__` method as being public.
def __public_objs(self): _budoc = getattr(self.module.module, '__budoc__', {}) def forced_out(name): return _budoc.get('%s.%s' % (self.name, name), False) is None def exported(name): exported = name == '__init__' or _is_exported(name) return not forced_out(name) and exported idents = dict(inspect.getmembers(self.cls)) return dict([(n, o) for n, o in idents.items() if exported(n)])
whether the string is an serialized object or not @param string $string @return bool
public static function isSerialized(string $string): bool { $data = @unserialize($string); if (false === $data) { return false; } else { return true; } }
Request the browser to enter fullscreen mode. @returns {boolean} Indicating if the request was successful.
function PDFPresentationMode_request() { if (this.switchInProgress || this.active || !this.viewer.hasChildNodes()) { return false; } this._addFullscreenChangeListeners(); this._setSwitchInProgress(); this._notifyStateChange(); if (this.container.requestFullscreen) { this.container.requestFullscreen(); } else if (this.container.mozRequestFullScreen) { this.container.mozRequestFullScreen(); } else if (this.container.webkitRequestFullscreen) { this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } else if (this.container.msRequestFullscreen) { this.container.msRequestFullscreen(); } else { return false; } this.args = { page: PDFViewerApplication.page, previousScale: PDFViewerApplication.currentScaleValue }; return true; }
// SetEnabled sets the Enabled field's value.
func (s *ConnectionDraining) SetEnabled(v bool) *ConnectionDraining { s.Enabled = &v return s }
Sets the current item to be the item at currentIndex. Also select the row as to give consistent user feedback. See also the notes at the top of this module on current item vs selected item(s).
def setCurrentIndex(self, currentIndex): selectionModel = self.selectionModel() selectionFlags = (QtCore.QItemSelectionModel.ClearAndSelect | QtCore.QItemSelectionModel.Rows) selectionModel.setCurrentIndex(currentIndex, selectionFlags)
Deletes the file associated with the owner. @throws CException if the file cannot be deleted or if the file id cannot be removed from the owner model.
public function deleteFile() { if (!$this->getManager()->deleteModel($this->owner->{$this->idAttribute})) { throw new CException('Failed to delete file.'); } $this->owner->{$this->idAttribute} = null; if (!$this->owner->save(false)) { throw new CException('Failed to remove file id from owner.'); } }
Gets the adGroupEstimates value for this CampaignEstimate. @return adGroupEstimates * The estimates for the ad groups belonging to this campaign in the request. They will be returned in the same order that they were sent in the request.
public com.google.api.ads.adwords.axis.v201809.o.AdGroupEstimate[] getAdGroupEstimates() { return adGroupEstimates; }
// ApplySchema is part of the tmclient.TabletManagerClient interface.
func (client *FakeTabletManagerClient) ApplySchema(ctx context.Context, tablet *topodatapb.Tablet, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) { return &tabletmanagerdatapb.SchemaChangeResult{}, nil }
Create a copy of TokenMetadata with tokenToEndpointMap reflecting situation after all current leave, and move operations have finished. @return new token metadata
public TokenMetadata cloneAfterAllSettled() { lock.readLock().lock(); try { TokenMetadata metadata = cloneOnlyTokenMap(); for (InetAddress endpoint : leavingEndpoints) metadata.removeEndpoint(endpoint); for (Pair<Token, InetAddress> pair : movingEndpoints) metadata.updateNormalToken(pair.left, pair.right); return metadata; } finally { lock.readLock().unlock(); } }
Force item to be output as a binary literal.
public function forceBinary() { $this->_filter = $this->_filterParams(); $this->_filter->binary = true; $this->_filter->literal = true; $this->_filter->quoted = false; }
// LegendThin is a legend that doesn't obscure the chart area.
func LegendThin(c *Chart, userDefaults ...Style) Renderable { return func(r Renderer, cb Box, chartDefaults Style) { legendDefaults := Style{ FillColor: drawing.ColorWhite, FontColor: DefaultTextColor, FontSize: 8.0, StrokeColor: DefaultAxisColor, StrokeWidth: DefaultAxisLineWidth, Padding: Box{ Top: 2, Left: 7, Right: 7, Bottom: 5, }, } var legendStyle Style if len(userDefaults) > 0 { legendStyle = userDefaults[0].InheritFrom(chartDefaults.InheritFrom(legendDefaults)) } else { legendStyle = chartDefaults.InheritFrom(legendDefaults) } r.SetFont(legendStyle.GetFont()) r.SetFontColor(legendStyle.GetFontColor()) r.SetFontSize(legendStyle.GetFontSize()) var labels []string var lines []Style for index, s := range c.Series { if s.GetStyle().IsZero() || s.GetStyle().Show { if _, isAnnotationSeries := s.(AnnotationSeries); !isAnnotationSeries { labels = append(labels, s.GetName()) lines = append(lines, s.GetStyle().InheritFrom(c.styleDefaultsSeries(index))) } } } var textHeight int var textWidth int var textBox Box for x := 0; x < len(labels); x++ { if len(labels[x]) > 0 { textBox = r.MeasureText(labels[x]) textHeight = util.Math.MaxInt(textBox.Height(), textHeight) textWidth = util.Math.MaxInt(textBox.Width(), textWidth) } } legendBoxHeight := textHeight + legendStyle.Padding.Top + legendStyle.Padding.Bottom chartPadding := cb.Top legendYMargin := (chartPadding - legendBoxHeight) >> 1 legendBox := Box{ Left: cb.Left, Right: cb.Right, Top: legendYMargin, Bottom: legendYMargin + legendBoxHeight, } Draw.Box(r, legendBox, legendDefaults) r.SetFont(legendStyle.GetFont()) r.SetFontColor(legendStyle.GetFontColor()) r.SetFontSize(legendStyle.GetFontSize()) lineTextGap := 5 lineLengthMinimum := 25 tx := legendBox.Left + legendStyle.Padding.Left ty := legendYMargin + legendStyle.Padding.Top + textHeight var label string var lx, ly int th2 := textHeight >> 1 for index := range labels { label = labels[index] if len(label) > 0 { textBox = r.MeasureText(label) r.Text(label, tx, ty) lx = tx + textBox.Width() + lineTextGap ly = ty - th2 r.SetStrokeColor(lines[index].GetStrokeColor()) r.SetStrokeWidth(lines[index].GetStrokeWidth()) r.SetStrokeDashArray(lines[index].GetStrokeDashArray()) r.MoveTo(lx, ly) r.LineTo(lx+lineLengthMinimum, ly) r.Stroke() tx += textBox.Width() + DefaultMinimumTickHorizontalSpacing + lineTextGap + lineLengthMinimum } } } }
Transform block to string @param string|null $message Any message to pass to the page @param mixed $results If string will redirect otherwise pass this to page @return string
protected function success($message = null, $results = null) { if($message) { $_SESSION['flash']['message'] = $message; $_SESSION['flash']['type'] = 'success'; } $this->trigger('html-success', $this, $message, $results); $this->trigger('response-success', $this, $message, $results); if(is_string($results)) { //redirect will forcefully exit return (string) eve()->redirect($results); } if(!is_null($results)) { $this->body['results'] = $results; } return $this->build($this->getTemplate()); }
Stupidly simple function to fix any Items/Quantity disparities inside a DistributionConfig block before use. Since AWS only accepts JSON-encodable data types, this implementation is "good enough" for our purposes.
def _fix_quantities(tree): ''' ''' if isinstance(tree, dict): tree = {k: _fix_quantities(v) for k, v in tree.items()} if isinstance(tree.get('Items'), list): tree['Quantity'] = len(tree['Items']) if not tree['Items']: tree.pop('Items') # Silly, but AWS requires it.... return tree elif isinstance(tree, list): return [_fix_quantities(t) for t in tree] else: return tree
// SetSetup sets the Setup field's value.
func (s *Recipes) SetSetup(v []*string) *Recipes { s.Setup = v return s }
Updates all Locations of content identified with $contentId with $versionNo. @param mixed $contentId @param mixed $versionNo
public function updateLocationsContentVersionNo($contentId, $versionNo) { $query = $this->handler->createUpdateQuery(); $query->update( $this->handler->quoteTable('ezcontentobject_tree') )->set( $this->handler->quoteColumn('contentobject_version'), $query->bindValue($versionNo, null, \PDO::PARAM_INT) )->where( $query->expr->eq( $this->handler->quoteColumn('contentobject_id'), $contentId ) ); $query->prepare()->execute(); }
Connects to the configured PDO database and adds/updates table schema if required @return Result @api
public function setup(): Result { $result = new Result(); try { $this->connect(); $connection = DriverManager::getConnection(['pdo' => $this->databaseHandle]); } catch (Exception | FilesException |DBALException $exception) { $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed')); return $result; } try { $tablesExist = $connection->getSchemaManager()->tablesExist([$this->cacheTableName, $this->tagsTableName]); } /** @noinspection PhpRedundantCatchClauseInspection */ catch (DBALException $exception) { $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed')); return $result; } if ($tablesExist) { $result->addNotice(new Notice('Tables "%s" and "%s" (already exists)', null, [$this->cacheTableName, $this->tagsTableName])); } else { $result->addNotice(new Notice('Creating database tables "%s" & "%s"...', null, [$this->cacheTableName, $this->tagsTableName])); } $fromSchema = $connection->getSchemaManager()->createSchema(); $schemaDiff = (new Comparator())->compare($fromSchema, $this->getCacheTablesSchema()); try { $statements = $schemaDiff->toSaveSql($connection->getDatabasePlatform()); } catch (DBALException $exception) { $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed')); return $result; } if ($statements === []) { $result->addNotice(new Notice('Table schema is up to date, no migration required')); return $result; } $connection->beginTransaction(); try { foreach ($statements as $statement) { $result->addNotice(new Notice('<info>++</info> %s', null, [$statement])); $connection->exec($statement); } $connection->commit(); } catch (\Exception $exception) { try { $connection->rollBack(); } catch (\Exception $exception) { } $result->addError(new Error('Exception while trying to setup PdoBackend: %s', $exception->getCode(), [$exception->getMessage()])); } return $result; }
Decrypt a serialized value @param string $value @param string $key @param boolean $base64 Whether to base64 decode the value before decrypting @return mixed
public function decrypt(string $value, string $key, bool $base64 = false) { if ($base64) { $value = base64_decode($value); } $ret = $this->decryptBinary($value, $key); return unserialize($ret); }
Load xml from file.
def load(self): """""" lg.info('Loading ' + str(self.xml_file)) update_annotation_version(self.xml_file) xml = parse(self.xml_file) return xml.getroot()
Retrieves the data in a jsoned form
def export_data(self): def export_field(value): """ Export item """ try: return value.export_data() except AttributeError: return value if self.__modified_data__ is not None: return [export_field(value) for value in self.__modified_data__] return [export_field(value) for value in self.__original_data__]
/* Set the value of the last element returned by next or previous, discarding any version information
public void setValue(E element) { if(element == null) throw new NullPointerException("cannot set a null element"); if(_lastId == VStack.NULL_ID) throw new IllegalStateException("neither next() nor previous() has been called"); _stack.setById(_lastId, element); afterSet(element); }
get general component config variables or info about subcomponents @author Kjell-Inge Gustafsson <ical@kigkonsult.se> @since 2.2.13 - 2007-10-23 @param string $config @return value
function getConfig( $config ) { switch( strtoupper( $config )) { case 'ALLOWEMPTY': return $this->allowEmpty; break; case 'COMPSINFO': unset( $this->compix ); $info = array(); foreach( $this->components as $cix => $component ) { unset( $component->propix ); $info[$cix]['ordno'] = $cix + 1; $info[$cix]['type'] = $component->objName; $info[$cix]['uid'] = $component->getProperty( 'uid' ); $info[$cix]['props'] = $component->getConfig( 'propinfo' ); $info[$cix]['sub'] = $component->getConfig( 'compsinfo' ); unset( $component->propix ); } return $info; break; case 'FORMAT': return $this->format; break; case 'LANGUAGE': // get language for calendar component as defined in [RFC 1766] return $this->language; break; case 'NL': return $this->nl; break; case 'PROPINFO': $output = array(); if( 0 < count( $this->action )) $output['ACTION'] = count( $this->action ) / 2; if( 0 < count( $this->attach )) $output['ATTACH'] = count( $this->attach ); if( 0 < count( $this->attendee )) $output['ATTENDEE'] = count( $this->attendee ); if( 0 < count( $this->categories )) $output['CATEGORIES'] = count( $this->categories ); if( 0 < count( $this->class )) $output['CLASS'] = count( $this->class ) / 2; if( 0 < count( $this->comment )) $output['COMMENT'] = count( $this->comment ); if( 0 < count( $this->completed )) $output['COMPLETED'] = count( $this->completed ) / 2; if( 0 < count( $this->contact )) $output['CONTACT'] = count( $this->contact ); if( 0 < count( $this->created )) $output['CREATED'] = count( $this->created ) / 2; if( 0 < count( $this->description )) $output['DESCRIPTION'] = count( $this->description ); if( 0 < count( $this->dtend )) $output['DTEND'] = count( $this->dtend ) / 2; if( 0 < count( $this->dtstart )) $output['DTSTART'] = count( $this->dtstart ) / 2; if( 0 < count( $this->dtstamp )) $output['DTSTAMP'] = count( $this->dtstamp ) / 2; if( 0 < count( $this->due )) $output['DUE'] = count( $this->due ) / 2; if( 0 < count( $this->duration )) $output['DURATION'] = count( $this->duration ) / 2; if( 0 < count( $this->exdate )) $output['EXDATE'] = count( $this->exdate ); if( 0 < count( $this->exrule )) $output['EXRULE'] = count( $this->exrule ); if( 0 < count( $this->freebusy )) $output['FREEBUSY'] = count( $this->freebusy ); if( 0 < count( $this->geo )) $output['GEO'] = count( $this->geo ) / 2; if( 0 < count( $this->lastmodified )) $output['LAST-MODIFIED'] = count( $this->lastmodified ) / 2; if( 0 < count( $this->location )) $output['LOCATION'] = count( $this->location ) / 2; if( 0 < count( $this->organizer )) $output['ORGANIZER'] = count( $this->organizer ) / 2; if( 0 < count( $this->percentcomplete )) $output['PERCENT-COMPLETE'] = count( $this->percentcomplete ) / 2; if( 0 < count( $this->priority )) $output['PRIORITY'] = count( $this->priority ) / 2; if( 0 < count( $this->rdate )) $output['RDATE'] = count( $this->rdate ); if( 0 < count( $this->recurrenceid )) $output['RECURRENCE-ID'] = count( $this->recurrenceid ) / 2; if( 0 < count( $this->relatedto )) $output['RELATED-TO'] = count( $this->relatedto ); if( 0 < count( $this->repeat )) $output['REPEAT'] = count( $this->repeat ) / 2; if( 0 < count( $this->requeststatus )) $output['REQUEST-STATUS'] = count( $this->requeststatus ); if( 0 < count( $this->resources )) $output['RESOURCES'] = count( $this->resources ); if( 0 < count( $this->sequence )) $output['SEQUENCE'] = count( $this->sequence ) / 2; if( 0 < count( $this->rrule )) $output['RRULE'] = count( $this->rrule ); if( 0 < count( $this->status )) $output['STATUS'] = count( $this->status ) / 2; if( 0 < count( $this->summary )) $output['SUMMARY'] = count( $this->summary ) / 2; if( 0 < count( $this->transp )) $output['TRANSP'] = count( $this->transp ) / 2; if( 0 < count( $this->trigger )) $output['TRIGGER'] = count( $this->trigger ) / 2; if( 0 < count( $this->tzid )) $output['TZID'] = count( $this->tzid ) / 2; if( 0 < count( $this->tzname )) $output['TZNAME'] = count( $this->tzname ); if( 0 < count( $this->tzoffsetfrom )) $output['TZOFFSETTFROM'] = count( $this->tzoffsetfrom ) / 2; if( 0 < count( $this->tzoffsetto )) $output['TZOFFSETTO'] = count( $this->tzoffsetto ) / 2; if( 0 < count( $this->tzurl )) $output['TZURL'] = count( $this->tzurl ) / 2; if( !in_array( $this->objName, array( 'valarm', 'vtimezone' ))) { if( empty( $this->uid['value'] )) $this->_makeuid(); $output['UID'] = 1; } if( 0 < count( $this->url )) $output['URL'] = count( $this->url ) / 2; if( 0 < count( $this->xprop )) $output['X-PROP'] = count( $this->xprop ); return $output; break; case 'UNIQUE_ID': if( empty( $this->unique_id )) $this->unique_id = gethostbyname( $_SERVER['SERVER_NAME'] ); return $this->unique_id; break; } }
Assert that the given method returns the expected return type. @param method Method to assert. @param expectedReturnType Expected return type of the method. @throws IllegalArgumentException If the method's return type doesn't match the expected type.
public static void assertReturnValue(ReflectionMethod method, Class<?> expectedReturnType) { final Class<?> returnType = method.getReturnType(); if (returnType != expectedReturnType) { final String message = "Class='"+method.getDeclaringClass()+"', method='"+method.getName()+"': Must return a value of type '"+expectedReturnType+"'!"; throw new IllegalArgumentException(message); } }
Return classification accuracy of input
def _value_function(self, x_input, y_true, y_pred): if len(y_true.shape) == 1: return y_pred.argmax(1).eq(y_true).double().mean().item() else: raise NotImplementedError
Includes target contents into config. :param str|unicode|Section|list target: File path or Section to include.
def include(self, target): for target_ in listify(target): if isinstance(target_, Section): target_ = ':' + target_.name self._set('ini', target_, multi=True) return self
Add custom repositories
def command_repo_add(self): if len(self.args) == 3 and self.args[0] == "repo-add": Repo().add(self.args[1], self.args[2]) else: usage("")
renderer.insert function for rendering arrays, `this` bound to the input. @param {Table} table cli-table @param {Object} object renderer object @param {Array} fields fields to show
function insertArray (table, object, fields) { var input = this input.forEach(function addRow (entry, rowNo) { var tableRow = fields.map(function cell (fieldName) { return getCellContent.call(entry, object.fields[fieldName], rowNo) }) table.push(tableRow) }) }
Create the readable name for the pipeline name.
function prettyName(name, sidebar) { var adjustedName = name; if (sidebar) { var adjustedName = name; var parts = name.split('.'); if (parts.length > 0) { adjustedName = parts[parts.length - 1]; } } return adjustedName.replace(/\./, '.<wbr>'); }
Creates a {@code status} tag based on the response status of the given {@code exchange}. @param exchange the exchange @return the status tag derived from the response status
public static Tag status(ServerWebExchange exchange) { HttpStatus status = exchange.getResponse().getStatusCode(); if (status == null) { status = HttpStatus.OK; } return Tag.of("status", String.valueOf(status.value())); }
<code>repeated .google.privacy.dlp.v2.FieldId headers = 1;</code>
public com.google.privacy.dlp.v2.FieldIdOrBuilder getHeadersOrBuilder(int index) { return headers_.get(index); }
Only include rows which are missing this field, this was the only possible way to do it. @param fieldName The field which should be missing @return ScannerBuilder
public EntityScannerBuilder<E> addIsMissingFilter(String fieldName) { SingleFieldEntityFilter singleFieldEntityFilter = new SingleFieldEntityFilter( entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(), fieldName, "++++NON_SHALL_PASS++++", CompareFilter.CompareOp.EQUAL); SingleColumnValueFilter filter = (SingleColumnValueFilter) singleFieldEntityFilter .getFilter(); filter.setFilterIfMissing(false); filterList.add(filter); return this; }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public void setOBJTYPE(Integer newOBJTYPE) { Integer oldOBJTYPE = objtype; objtype = newOBJTYPE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BEGIN_IMAGE__OBJTYPE, oldOBJTYPE, objtype)); }
Validates to make sure all required services are defined @return void @throws \Exception
private function validateServicesDefined() { if(!$this->getDi()->has(AclInterface::DI_NAME)) { throw new \Exception('Service ' . AclInterface::class . '::DI_NAME must be defined with a type of: ' . AclInterface::class); } if(!$this->getDi()->has(OutputInterface::DI_NAME)) { throw new \Exception('Service ' . OutputInterface::class . '::DI_NAME must be defined with a type of: ' . OutputInterface::class); } }
// create body writer POST
func reqForm(r Request, params map[string]string, method string) (Request, error) { body := &bytes.Buffer{} writer := multipart.NewWriter(body) for key, val := range params { _ = writer.WriteField(key, val) } defer writer.Close() req, err := http.NewRequest(method, r.URI, body) req.Header.Add("Content-Type", writer.FormDataContentType()) if r.Headers != nil { for _, header := range r.Headers { req.Header.Add(header.Key, header.Value) } } if r.BasicAuth.Username != "" { r.Req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password) } r.Req = req return r, err }
// TexturedPolygon draws a polygon filled with the given texture. // (http://www.ferzkopp.net/Software/SDL_gfx-2.0/Docs/html/_s_d_l__gfx_primitives_8c.html#a65137af308ea878f28abc95419e8aef5)
func TexturedPolygon(renderer *sdl.Renderer, vx, vy []int16, surface *sdl.Surface, textureDX, textureDY int) bool { _len := C.int(min(len(vx), len(vy))) if _len == 0 { return true } _vx := (*C.Sint16)(unsafe.Pointer(&vx[0])) _vy := (*C.Sint16)(unsafe.Pointer(&vy[0])) _surface := (*C.SDL_Surface)(unsafe.Pointer(surface)) _textureDX := C.int(textureDX) _textureDY := C.int(textureDY) return C.texturedPolygon((*C.SDL_Renderer)(unsafe.Pointer(renderer)), _vx, _vy, _len, _surface, _textureDX, _textureDY) == 0 }
// SetNextToken sets the NextToken field's value.
func (s *ListTriggersInput) SetNextToken(v string) *ListTriggersInput { s.NextToken = &v return s }
// NewMockAccessTokenStorage creates a new mock instance
func NewMockAccessTokenStorage(ctrl *gomock.Controller) *MockAccessTokenStorage { mock := &MockAccessTokenStorage{ctrl: ctrl} mock.recorder = &MockAccessTokenStorageMockRecorder{mock} return mock }
// RetrieveCachedExternalFlowPolicy returns the policy for an external IP
func (p *PUContext) RetrieveCachedExternalFlowPolicy(id string) (interface{}, error) { return p.externalIPCache.Get(id) }
Bump version following semantic versioning rules.
def bump(self, level='patch', label=None): bump = self._bump_pre if level == 'pre' else self._bump bump(level, label)
// ParseAddr parses an address from its string format to a net.Addr.
func ParseAddr(address, socksAddr string) (net.Addr, error) { host, portStr, err := net.SplitHostPort(address) if err != nil { return nil, err } port, err := strconv.Atoi(portStr) if err != nil { return nil, err } if IsOnionHost(host) { return &OnionAddr{OnionService: host, Port: port}, nil } return ResolveTCPAddr(address, socksAddr) }
Checks if a table exists. @param string $table table name @return bool TRUE if table exists, else FALSE
public function tableExists( $table ) { $query = "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = ? AND table_name = ?"; $params = [ $this->name, $table ]; $statement = $this->database->prepare( $query ); $statement->execute( $params ); $results = $statement->fetchAll(); return ( 0 < ( int ) $results[ 0 ][ 'count' ] ); }
Check if a missing translation exists in collection. @param string $locale @param string $transKey @return bool
private function hasMissing($locale, $transKey) { if ( ! isset($this->missing[$locale])) return false; return in_array($transKey, $this->missing[$locale]); }
Utility that detects and returns the columns that are forward returns
def get_forward_returns_columns(columns): pattern = re.compile(r"^(\d+([Dhms]|ms|us|ns))+$", re.IGNORECASE) valid_columns = [(pattern.match(col) is not None) for col in columns] return columns[valid_columns]
// SetUserName sets the UserName field's value.
func (s *SigningCertificate) SetUserName(v string) *SigningCertificate { s.UserName = &v return s }
Marshall the given parameter object.
public void marshall(Player player, ProtocolMarshaller protocolMarshaller) { if (player == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(player.getPlayerId(), PLAYERID_BINDING); protocolMarshaller.marshall(player.getPlayerAttributes(), PLAYERATTRIBUTES_BINDING); protocolMarshaller.marshall(player.getTeam(), TEAM_BINDING); protocolMarshaller.marshall(player.getLatencyInMs(), LATENCYINMS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Returns the list of KNX devices currently attached to the host, based on known KNX vendor IDs. @return the list of found KNX devices
public static List<UsbDevice> getKnxDevices() { final List<UsbDevice> knx = new ArrayList<>(); for (final UsbDevice d : getDevices()) { final int vendor = d.getUsbDeviceDescriptor().idVendor() & 0xffff; for (final int v : vendorIds) if (v == vendor) knx.add(d); } return knx; }
Get this object properties REST: GET /sms/{serviceName}/virtualNumbers/{number} @param serviceName [required] The internal name of your SMS offer @param number [required] The virtual number
public OvhVirtualNumber serviceName_virtualNumbers_number_GET(String serviceName, String number) throws IOException { String qPath = "/sms/{serviceName}/virtualNumbers/{number}"; StringBuilder sb = path(qPath, serviceName, number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhVirtualNumber.class); }
Convert from AgMIP standard date string (YYMMDD) to a custom date string @param agmipDate AgMIP standard date string @param format Destination format @return a formatted date string or {@code null}
public synchronized static String formatAgmipDateString(String agmipDate, String format) { try { SimpleDateFormat fmt = new SimpleDateFormat(format); Date d = dateFormatter.parse(agmipDate); return fmt.format(d); } catch (Exception ex) { return null; } }
// ContainsShard returns true if either Left or Right lists contain // the provided Shard.
func (os *OverlappingShards) ContainsShard(shardName string) bool { for _, l := range os.Left { if l.ShardName() == shardName { return true } } for _, r := range os.Right { if r.ShardName() == shardName { return true } } return false }
See https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html#PO-Files for more information about this file format.
protected function load($filename) { $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if ($lines === false) { throw new \InvalidArgumentException('Invalid file'); } $entry = self::newEntry(); $lastKw = null; $lastIndex = null; foreach ($lines as $line) { if ($line[0] === '#') { $this->maybePushEntry($entry); if (strlen($line) === 1) { continue; } switch ($line[1]) { case ' ': # Translator comment break; case '.': # Extracted comment break; case ':': # File/line reference break; case ',': # Flags break; case "|": # Previous information # The initial marker is followed by a keyword # (either "msgid", "msgctxt" or "msgid_plural"), # detailing what the previous information was. break; } continue; } $line = ltrim($line, " \t"); $len = strlen($line); // Reset keyword index on new entry if (!count($entry['msgstr'])) { $lastIndex = null; } // Look for continuation strings. if (strlen($line) >= 2 && $line[0] === '"' && $line[$len-1] === '"') { // We found a string, but it has no predecessor. if ($lastKw === null) { throw new \InvalidArgumentException(); } $line = stripcslashes((string) substr($line, 1, -1)); if ($lastKw === 'msgstr') { $index = $lastIndex === null ? 0 : $lastIndex; } else { $index = null; } if ($index === null) { if (is_array($entry[$lastKw])) { throw new \InvalidArgumentException(); } else { $entry[$lastKw] .= $line; } } else { if (!is_array($entry[$lastKw])) { throw new \InvalidArgumentException(); } else { $entry[$lastKw][$index] .= $line; } } continue; } $kwLen = strcspn($line, " \t"); $kw = (string) substr($line, 0, $kwLen); $index = null; $line = ltrim((string) substr($line, $kwLen), " \t"); $brkOpen = strpos($kw, '['); $brkClose = strpos($kw, ']'); if ($brkOpen !== false || $brkClose !== false) { if ($brkOpen === false || $brkClose === false || $brkClose < $brkOpen) { throw new \InvalidArgumentException(); } $nlen = strspn($kw, '1234567890', $brkOpen + 1, $brkClose - $brkOpen - 1); if ($nlen === 0 || $nlen !== $brkClose - $brkOpen - 1) { throw new \InvalidArgumentException(); } $index = (int) substr($kw, $brkOpen + 1, $nlen); $kw = (string) substr($kw, 0, $brkOpen); } if (strlen($line) < 2 || $line[0] !== '"' || $line[strlen($line)-1] !== '"') { throw new \InvalidArgumentException(); } $line = stripcslashes((string) substr($line, 1, -1)); switch ($kw) { case "msgstr": if ($index === null) { if (isset($entry[$kw][0])) { throw new \InvalidArgumentException(); } $entry[$kw][0] = $line; } else { if (array_key_exists($index, $entry[$kw])) { throw new \InvalidArgumentException(); } $entry[$kw][$index] = $line; $lastIndex = $index; } break; case "msgctxt": // Intentional fall-through case "msgid": $this->maybePushEntry($entry); // Intentional fall-through case 'msgid_plural': if ($index !== null || isset($entry[$kw])) { throw new \InvalidArgumentException(); } $entry[$kw] = $line; break; default: throw new \InvalidArgumentException(); } $lastKw = $kw; } // Push the last entry. $this->maybePushEntry($entry); }
Alias for the `resourcesFolder` function. @param string $extensionKey The extension key @param string $prefix The optional prefix, defaults to `EXT:` @return string The resources folder
public static function getResourcesFolder(string $extensionKey, string $prefix = 'EXT:'): string { return self::resourcesFolder($extensionKey, $prefix); }
@param string $type @param string $serviceId @return bool
private function clearTypedCacheFromService($type, $serviceId) { /** @type \Psr\Cache\CacheItemPoolInterface $service */ $service = $this->getContainer()->get($serviceId); if ($service instanceof TaggablePoolInterface) { return $service->clearTags([$type]); } else { return $service->clear(); } }
Initializes the first map for data input.
private void initFirstMapForGrammarProductions() { for (Production production : grammar.getProductions().getList()) { if (!firstGrammar.containsKey(production.getName())) { firstGrammar.put(production.getName(), new LinkedHashSet<Terminal>()); } } }
Start the FTP Server for pulsar search.
def run(self): """""" self._log.info('Starting Pulsar Search Interface') # Instantiate a dummy authorizer for managing 'virtual' users authorizer = DummyAuthorizer() # Define a new user having full r/w permissions and a read-only # anonymous user authorizer.add_user(self._config['login']['user'], self._config['login']['psswd'], '.', perm=self._config['login']['perm']) authorizer.add_anonymous(os.getcwd()) # Instantiate FTP handler class handler = FTPHandler handler.authorizer = authorizer handler.abstracted_fs = PulsarFileSystem # Define a customized banner (string returned when client connects) handler.banner = "SKA SDP pulsar search interface." # Instantiate FTP server class and listen on 0.0.0.0:7878 address = (self._config['address']['listen'], self._config['address']['port']) server = FTPServer(address, handler) # set a limit for connections server.max_cons = 256 server.max_cons_per_ip = 5 # start ftp server server.serve_forever()
@param array $provider @throws ProviderException
private function resolveProviderAnnotation($provider) { if (is_array($provider)) { foreach ($provider as $item) { $this->resolveProviderAnnotation($item); } } else { if (false === $this->isProvided($provider)) { $this->addProvider($provider); } } }
// SetCdcStartTime sets the CdcStartTime field's value.
func (s *CreateReplicationTaskInput) SetCdcStartTime(v time.Time) *CreateReplicationTaskInput { s.CdcStartTime = &v return s }
Unprotects an RTP Packet by decrypting the payload. @param packet RTP Packet to be unprotected @return error code, 0 = success
public int unprotect(RtpPacket packet) { if (txSessAuthKey == null) { // Only the tx session key is set at session start, rx is done when // 1st packet received log("unprotect() called out of session"); return UNPROTECT_SESSION_NOT_STARTED; } if (packet == null) { logWarning("unprotect() called with null RtpPacket"); return UNPROTECT_NULL_PACKET; } if (previousSSRC != packet.getSscr()) { previousSSRC = packet.getSscr(); // reset indexes & Seq rxRoc = 0; rxSeq = packet.getSequenceNumber(); replayWindow.removeAllElements(); logWarning("New SSRC detected. Resetting SRTP replay protection"); } if (!receivedFirst) { receivedFirst = true; rxSeq = packet.getSequenceNumber(); if (VERBOSE) { log("unprotect() iRxSeq = " + rxSeq); } if (!rxSessionKeyDerivation()) { logWarning("unprotect() unable to create session keys"); return UNPROTECT_ERROR_DECRYPTING; } } // First need to work out the implicit srtp sequence number, // see rfc3711 appendix A & section 3.3.1 // Using same naming convention as in rfc for ROC estimate (v) // Needs to be done before authentication as v is used as part of auth long v; int seq = packet.getSequenceNumber(); if (rxSeq < 0x8000) { if ((seq - rxSeq) > 0x8000) { v = rxRoc - 0x10000L; } else { v = rxRoc; } } else { if ((rxSeq - 0x8000) > seq) { v = rxRoc + 0x10000L; } else { v = rxRoc; } } long index = v + seq; if (SUPER_VERBOSE) { log("unprotect(), seq = " + seq); logBuffer("unprotect(), rcvd pkt = ", packet.getPacket()); } if (isReplayedPacket(index)) { logWarning("Replayed packet received, sequence number=#" + seq + ", index=" + index); return UNPROTECT_REPLAYED_PACKET; } // Now need to check authentication & remove auth bytes from payload int originalLen = packet.getPayloadLength(); int newLen = originalLen - getHmacAuthSizeBytes(); // we'll reduce the payload length but the auth-code will still be // present after the payload for comparison int pktAuthCodePos = packet.getHeaderLength() + newLen; packet.setPayloadLength(newLen); byte[] authCode = null; try { authCode = getAuthentication(packet, v, false); // iRxSessAuthKey); } catch (Throwable e) { logError("unprotect() error getting authCode EX: " + e); e.printStackTrace(); return UNPROTECT_ERROR_DECRYPTING; } if (!platform.getUtils().equals(authCode, 0, packet.getPacket(), pktAuthCodePos, getHmacAuthSizeBytes())) { // Auth failed logWarning("unprotect() Authentication failed"); logBuffer("authCode:", authCode); byte[] pktAuthCode = new byte[getHmacAuthSizeBytes()]; System.arraycopy(packet.getPacket(), pktAuthCodePos, pktAuthCode, 0, getHmacAuthSizeBytes()); logBuffer("pktAuthCode:", pktAuthCode); logBuffer("iRxSessAuthKey:", rxSessAuthKey); log("v = " + Integer.toHexString((int) v) + " (" + v + ")"); return UNPROTECT_INVALID_PACKET; } if (VERBOSE) { log("unprotect() -------- Authenticated OK --------"); } // Authenticated, now unprotect the payload // Note the use of encryptIV() in transformPayload is correct // At 1st sight, might expect to use decrypt but unprotection consists // of XORing payload with an encrypted IV to obtain original payload // data if (!transformPayload(packet, v, seq, rxSessSaltKey, false)) { log("unprotect() transformPayload error, decryption failed"); return UNPROTECT_ERROR_DECRYPTING; } // Payload now unprotected. Update the latest seq & ROC ready for next // packet if (v == rxRoc) { if (seq > rxSeq) { rxSeq = seq; } } else if (v == rxRoc + 0x10000L) { rxRoc += 0x10000L; rxSeq = seq; } if (SUPER_VERBOSE) { logBuffer("unprotect(), new packet - ", packet.getPacket()); } return UNPROTECT_OK; }
Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException`
def initialize_communities_bucket(): bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID']) if Bucket.query.get(bucket_id): raise FilesException("Bucket with UUID {} already exists.".format( bucket_id)) else: storage_class = current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS'] location = Location.get_default() bucket = Bucket(id=bucket_id, location=location, default_storage_class=storage_class) db.session.add(bucket) db.session.commit()
// AppendUint encodes and inserts an unsigned integer value into the dst byte array.
func (e Encoder) AppendUint(dst []byte, val uint) []byte { return e.AppendInt64(dst, int64(val)) }
// GetKey implements KeyDB by returning the result of calling the closure.
func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey, bool, error) { return kc(address) }
/* Each category is surrounded by one or several square brackets. The number of brackets indicates the depth of the category. Options are `comment` Default to ";"
function(str, options = {}) { var comment, current, data, lines, stack; lines = string.lines(str); current = data = {}; stack = [current]; comment = options.comment || ';'; lines.forEach(function(line, _, __) { var depth, match, parent; if (!line || line.match(/^\s*$/)) { return; } // Category if (match = line.match(/^\s*(\[+)(.+?)(\]+)\s*$/)) { depth = match[1].length; // Add a child if (depth === stack.length) { parent = stack[depth - 1]; parent[match[2]] = current = {}; stack.push(current); } // Invalid child hierarchy if (depth > stack.length) { throw Error(`Invalid child ${match[2]}`); } // Move up or at the same level if (depth < stack.length) { stack.splice(depth, stack.length - depth); parent = stack[depth - 1]; parent[match[2]] = current = {}; return stack.push(current); } // comment } else if (comment && (match = line.match(RegExp(`^\\s*(${comment}.*)$`)))) { return current[match[1]] = null; // key value } else if (match = line.match(/^\s*(.+?)\s*=\s*(.+)\s*$/)) { return current[match[1]] = match[2]; // else } else if (match = line.match(/^\s*(.+?)\s*$/)) { return current[match[1]] = null; } }); return data; }
Displays a Bootstrap glyphicon. @param string $name The name. @return string Returns the Bootstrap glyphicon.
protected function bootstrapGlyphicon($name, $style) { $attributes = []; $attributes["class"][] = "glyphicon"; $attributes["class"][] = null !== $name ? "glyphicon-" . $name : null; $attributes["aria-hidden"] = "true"; $attributes["style"] = $style; return static::coreHTMLElement("span", null, $attributes); }
Validates data based on Joi schemas @param {Object} data the data to be validated @param {Object} schema the object schema specified in Joi against which data is validated
function validate (data, schema) { if (!data || !schema) { throw new Error('Trying to validate without passing data and schema') } return Joi.validate(data, schema) }
Specify camera calibration parameters @param fx Focal length x-axis in pixels @param fy Focal length y-axis in pixels @param skew skew in pixels @param cx camera center x-axis in pixels @param cy center center y-axis in pixels
public AddBrownPtoN_F64 setK( /**/double fx, /**/double fy, /**/double skew, /**/double cx, /**/double cy) { // analytic solution to matrix inverse a11 = (double)(1.0/fx); a12 = (double)(-skew/(fx*fy)); a13 = (double)((skew*cy - cx*fy)/(fx*fy)); a22 = (double)(1.0/fy); a23 = (double)(-cy/fy); return this; }
TODO: should this method be final?
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { preProcessRequest(request); DefaultServerDolphin serverDolphin = resolveServerDolphin(request); String input = readInput(request); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("received json: " + input); } List<Command> commands = decodeInput(serverDolphin.getServerConnector().getCodec(), input); List<Command> results = handleCommands(serverDolphin.getServerConnector(), commands); String output = encodeOutput(serverDolphin.getServerConnector().getCodec(), results); writeHeaders(request, response, results); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("sending json response: " + output); } writeOutput(response, output); postProcessResponse(response); }