language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void logPurchase(BigDecimal purchaseAmount, Currency currency, Bundle parameters) { appEventsLogger.logPurchase(purchaseAmount, currency, parameters); }
python
def get_charset(message, default="utf-8"): """Get the message charset""" if message.get_content_charset(): return message.get_content_charset() if message.get_charset(): return message.get_charset() return default
python
def write_xpm(matrix, version, out, scale=1, border=None, color='#000', background='#fff', name='img'): """\ Serializes the matrix as `XPM <https://en.wikipedia.org/wiki/X_PixMap>`_ image. :param matrix: The matrix to serialize. :param int version: The (Micro) QR code version :param out: Filename or a file-like object supporting to write binary data. :param scale: Indicates the size of a single module (default: 1 which corresponds to 1 x 1 pixel per module). :param int border: Integer indicating the size of the quiet zone. If set to ``None`` (default), the recommended border size will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes). :param color: Color of the modules (default: black). The color can be provided as ``(R, G, B)`` tuple, as web color name (like "red") or in hexadecimal format (``#RGB`` or ``#RRGGBB``). :param background: Optional background color (default: white). See `color` for valid values. ``None`` indicates a transparent background. :param str name: Name of the image (must be a valid C-identifier). Default: "img". """ row_iter = matrix_iter(matrix, version, scale, border) width, height = get_symbol_size(version, scale=scale, border=border) stroke_color = colors.color_to_rgb_hex(color) bg_color = colors.color_to_rgb_hex(background) if background is not None else 'None' with writable(out, 'wt') as f: write = f.write write('/* XPM */\n' 'static char *{0}[] = {{\n' '"{1} {2} 2 1",\n' '" c {3}",\n' '"X c {4}",\n'.format(name, width, height, bg_color, stroke_color)) for i, row in enumerate(row_iter): write(''.join(chain(['"'], (' ' if not b else 'X' for b in row), ['"{0}\n'.format(',' if i < height - 1 else '')]))) write('};\n')
python
def clean_fsbackend(opts): ''' Clean out the old fileserver backends ''' # Clear remote fileserver backend caches so they get recreated for backend in ('git', 'hg', 'svn'): if backend in opts['fileserver_backend']: env_cache = os.path.join( opts['cachedir'], '{0}fs'.format(backend), 'envs.p' ) if os.path.isfile(env_cache): log.debug('Clearing %sfs env cache', backend) try: os.remove(env_cache) except OSError as exc: log.critical( 'Unable to clear env cache file %s: %s', env_cache, exc ) file_lists_dir = os.path.join( opts['cachedir'], 'file_lists', '{0}fs'.format(backend) ) try: file_lists_caches = os.listdir(file_lists_dir) except OSError: continue for file_lists_cache in fnmatch.filter(file_lists_caches, '*.p'): cache_file = os.path.join(file_lists_dir, file_lists_cache) try: os.remove(cache_file) except OSError as exc: log.critical( 'Unable to file_lists cache file %s: %s', cache_file, exc )
java
public void sign( SignConfig config, File jarFile, File signedJar ) throws MojoExecutionException { JarSignerRequest request = config.createSignRequest( jarFile, signedJar ); try { JavaToolResult result = jarSigner.execute( request ); CommandLineException exception = result.getExecutionException(); if ( exception != null ) { throw new MojoExecutionException( "Could not sign jar " + jarFile, exception ); } int exitCode = result.getExitCode(); if ( exitCode != 0 ) { throw new MojoExecutionException( "Could not sign jar " + jarFile + ", use -X to have detail of error" ); } } catch ( JavaToolException e ) { throw new MojoExecutionException( "Could not find jarSigner", e ); } }
java
final Transaction suspendGlobalTx(int action) throws CSIException //174358.1 //LIDB1673.2.1.5 { final Transaction result = txCtrl.suspendGlobalTx(action); //LIDB1673.2.1.5 // d165585 Begins if (TraceComponent.isAnyTracingEnabled() && // d527372 TETxLifeCycleInfo.isTraceEnabled()) // d171555 { TETxLifeCycleInfo.traceGlobalTxSuspend("NoTx", "Suspend Global Tx"); } // d165585 Ends return result; }
java
@Override public Temporal subtractFrom(Temporal temporal) { return temporal.minus(Period.of(0, months, days)).minus(Duration.ofNanos(nanoseconds)); }
java
private static REEFLauncher getREEFLauncher(final String clockConfigPath) { try { final Configuration clockArgConfig = TANG.newConfigurationBuilder() .bindNamedParameter(ClockConfigurationPath.class, clockConfigPath) .build(); return TANG.newInjector(clockArgConfig).getInstance(REEFLauncher.class); } catch (final BindException ex) { throw fatal("Error in parsing the command line", ex); } catch (final InjectionException ex) { throw fatal("Unable to instantiate REEFLauncher.", ex); } }
python
def get_current_state(self): """ Get current state for user session or None if session doesn't exist """ try: session_id = session.sessionId return self.session_machines.current_state(session_id) except UninitializedStateMachine as e: logger.error(e)
java
public Integer getIntReqPar(final String name) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return null; } return Integer.valueOf(reqpar); }
python
def pad_position_l(self, i): """ Determines the position of the ith pad in the length direction. Assumes equally spaced pads. :param i: ith number of pad in length direction (0-indexed) :return: """ if i >= self.n_pads_l: raise ModelError("pad index out-of-bounds") return (self.length - self.pad_length) / (self.n_pads_l - 1) * i + self.pad_length / 2
java
public static Text createTextElement(String tapLine) { Matcher m = Patterns.TEXT_PATTERN.matcher(tapLine); if (m.matches()) { Text result = new Text(tapLine); result.setIndentationString(m.group(1)); result.indentation = m.group(1).length(); return result; } return null; }
python
def design_delete(self, name, use_devmode=True, syncwait=0): """ Delete a design document :param string name: The name of the design document to delete :param bool use_devmode: Whether the design to delete is a development mode design doc. :param float syncwait: Timeout for operation verification. See :meth:`design_create` for more information on this parameter. :return: An :class:`HttpResult` object. :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the specified interval. .. seealso:: :meth:`design_create`, :meth:`design_get` """ name = self._mk_devmode(name, use_devmode) existing = None if syncwait: try: existing = self.design_get(name, use_devmode=False) except CouchbaseError: pass ret = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW, path="_design/" + name, method=_LCB.LCB_HTTP_METHOD_DELETE) self._design_poll(name, 'del', existing, syncwait) return ret
python
def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None): """Parallel calculation of motif statistics.""" try: stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1) except Exception as e: raise sys.stderr.write("ERROR: {}\n".format(str(e))) stats = {} if not bg_name: bg_name = "default" return bg_name, stats
java
public String addClass(String content, String selector, List<String> classNames) { return addClass(content, selector, classNames, -1); }
java
public InjectorConfiguration withDefined(Class classDefinition) { //noinspection unchecked return new InjectorConfiguration( scopes, definedClasses.withModified(value -> value.withPut( classDefinition, new ImmutableArrayList<>(Arrays.asList(classDefinition.getConstructors())) )), factories, factoryClasses, sharedClasses, sharedInstances, aliases, collectedAliases, namedParameterValues ); }
java
public static MediaInfo parseMediaInfo(String url) { if (StringUtils.isEmpty(url)) { return null; } Matcher matcher = PATTERN.matcher(url.trim()); if (!matcher.matches()) { return null; } if (matcher.groupCount() < 1) { throw new IllegalArgumentException(url + " is a media push datasource but have no enough info for groupKey."); } return new MediaInfo(matcher.group(1)); }
python
def supported_operations(self): """ All operations supported by the camera. """ return tuple(op for op in backend.CAM_OPS if self._abilities.operations & op)
python
def remove_client(self, client_identifier): """Remove a client.""" new_clients = self.clients new_clients.remove(client_identifier) yield from self._server.group_clients(self.identifier, new_clients) _LOGGER.info('removed %s from %s', client_identifier, self.identifier) self._server.client(client_identifier).callback() self.callback()
python
def handle_market_open(self, session_label, data_portal): """Handles the start of each session. Parameters ---------- session_label : Timestamp The label of the session that is about to begin. data_portal : DataPortal The current data portal. """ ledger = self._ledger ledger.start_of_session(session_label) adjustment_reader = data_portal.adjustment_reader if adjustment_reader is not None: # this is None when running with a dataframe source ledger.process_dividends( session_label, self._asset_finder, adjustment_reader, ) self._current_session = session_label cal = self._trading_calendar self._market_open, self._market_close = self._execution_open_and_close( cal, session_label, ) self.start_of_session(ledger, session_label, data_portal)
java
public void deleteAccount() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Map<String, String> attributes = new HashMap<>(); // To delete an account, we add a single attribute, "remove", that is blank. attributes.put("remove", ""); Registration reg = new Registration(attributes); reg.setType(IQ.Type.set); reg.setTo(connection().getXMPPServiceDomain()); createStanzaCollectorAndSend(reg).nextResultOrThrow(); }
java
public static int getPositionByIdentifier(DrawerBuilder drawer, long identifier) { if (identifier != -1) { for (int i = 0; i < drawer.getAdapter().getItemCount(); i++) { if (drawer.getAdapter().getItem(i).getIdentifier() == identifier) { return i; } } } return -1; }
java
private void setupPayloads() { payloads.add(new PayloadType.Audio(3, "gsm")); payloads.add(new PayloadType.Audio(4, "g723")); payloads.add(new PayloadType.Audio(0, "PCMU", 16000)); }
python
def can_read(self): """Check if the field is readable """ sm = getSecurityManager() if not sm.checkPermission(permissions.View, self.context): return False return True
python
def pop_all(self, event_name): """Return and remove all stored events of a specified name. Pops all events from their queue. May miss the latest ones. If no event is available, return immediately. Args: event_name: Name of the events to be popped. Returns: List of the desired events. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. """ if not self.started: raise IllegalStateError(("Dispatcher needs to be started before " "popping.")) results = [] try: self.lock.acquire() while True: e = self.event_dict[event_name].get(block=False) results.append(e) except (queue.Empty, KeyError): return results finally: self.lock.release()
java
public static <T> List<T> addAllNotNull(List<T> to, List<? extends T> what) { List<T> data = safeList(to); if (!isEmpty(what)) { for (T t : what) { if (t != null) { data.add(t); } } } return data; }
java
public EtcdResponse delete(final String key) throws EtcdException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE); builder.pathSegment(key); return execute(builder, HttpMethod.DELETE, null, EtcdResponse.class); }
java
public void execute() throws MojoExecutionException, MojoFailureException { try { for ( String name : getModules() ) { File output = new File( getOutputDirectory(), readModule( name ).getPath() ); clean( output ); } clean( new File( getOutputDirectory(), ".gwt-tmp" ) ); } catch ( GwtModuleReaderException e ) { throw new MojoExecutionException( e.getMessage(), e ); } }
python
def ko_bindings(model): """ Given a model, returns the Knockout data bindings. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#" + modelName.lower() + "s')[0]);" return modelBindingsString except Exception as e: logger.error(e) return ''
java
public void updatePreserveOrder(Class<? extends DbEntity> entityType, String statement, Object parameter) { performBulkOperationPreserveOrder(entityType, statement, parameter, UPDATE_BULK); }
python
def remove_series(self, series): """Removes a :py:class:`.Series` from the chart. :param Series series: The :py:class:`.Series` to remove. :raises ValueError: if you try to remove the last\ :py:class:`.Series`.""" if len(self.all_series()) == 1: raise ValueError("Cannot remove last series from %s" % str(self)) self._all_series.remove(series) series._chart = None
java
public static ExternalGraphicInfo createExternalGraphic(String href) { ExternalGraphicInfo externalGraphic = new ExternalGraphicInfo(); FormatInfo format = new FormatInfo(); format.setFormat("image/" + getExtension(href)); externalGraphic.setFormat(format); OnlineResourceInfo onlineResource = new OnlineResourceInfo(); onlineResource.setType("simple"); HrefInfo hrefInfo = new HrefInfo(); hrefInfo.setHref(href); onlineResource.setHref(hrefInfo); externalGraphic.setOnlineResource(onlineResource); return externalGraphic; }
python
def getClassInModuleFromName(className, module): """ get a class from name within a module """ n = getAvClassNamesInModule(module) i = n.index(className) c = getAvailableClassesInModule(module) return c[i]
java
private void checkByTargetFilterQueryAndAssignDS(final TargetFilterQuery targetFilterQuery) { try { final DistributionSet distributionSet = targetFilterQuery.getAutoAssignDistributionSet(); int count; do { count = runTransactionalAssignment(targetFilterQuery, distributionSet.getId()); } while (count == PAGE_SIZE); } catch (PersistenceException | AbstractServerRtException e) { LOGGER.error("Error during auto assign check of target filter query " + targetFilterQuery.getId(), e); } }
python
def process_metrics(self, snmp_data): "Build list with metrics" self.metrics = {} for i in range(0, len(snmp_data)): mib_name = self.models[self.modem_type]['metrics'][i] conv = metric_mib[mib_name]['conv'] self.metrics[mib_name] = conv(snmp_data[i])
python
def main(): ''' A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args. ''' import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher to Zookeeper") parser.add_argument('-f', '--file', action='store', required=True, help="The yaml file to use") parser.add_argument('-i', '--id', action='store', default="all", help="The crawler id to use in zookeeper") parser.add_argument('-p', '--path', action='store', default="/scrapy-cluster/crawler/", help="The zookeeper path to use") parser.add_argument('-w', '--wipe', action='store_const', const=True, help="Remove the current config") parser.add_argument('-z', '--zoo-keeper', action='store', required=True, help="The Zookeeper connection <host>:<port>") args = vars(parser.parse_args()) filename = args['file'] id = args['id'] wipe = args['wipe'] zoo = args['zoo_keeper'] path = args['path'] zk = KazooClient(hosts=zoo) zk.start() # ensure path exists zk.ensure_path(path) bytes = open(filename, 'rb').read() if zk.exists(path): # push the conf file if not zk.exists(path + id) and not wipe: print("creaing conf node") zk.create(path + id, bytes) elif not wipe: print("updating conf file") zk.set(path + id, bytes) if wipe: zk.set(path + id, None) zk.stop()
python
def connect(self): """Connect to MQTT server and wait for server to acknowledge""" if not self.connect_attempted: self.connect_attempted = True self.client.connect(self.host, port=self.port) self.client.loop_start() while not self.connected: log.info('waiting for MQTT connection...') time.sleep(1)
java
public void setReplicaGlobalSecondaryIndexSettingsUpdate( java.util.Collection<ReplicaGlobalSecondaryIndexSettingsUpdate> replicaGlobalSecondaryIndexSettingsUpdate) { if (replicaGlobalSecondaryIndexSettingsUpdate == null) { this.replicaGlobalSecondaryIndexSettingsUpdate = null; return; } this.replicaGlobalSecondaryIndexSettingsUpdate = new java.util.ArrayList<ReplicaGlobalSecondaryIndexSettingsUpdate>( replicaGlobalSecondaryIndexSettingsUpdate); }
python
def exon_by_id(self, exon_id): """Construct an Exon object from its ID by looking up the exon"s properties in the given Database. """ if exon_id not in self._exons: field_names = [ "seqname", "start", "end", "strand", "gene_name", "gene_id", ] contig, start, end, strand, gene_name, gene_id = self.db.query_one( select_column_names=field_names, filter_column="exon_id", filter_value=exon_id, feature="exon", distinct=True) self._exons[exon_id] = Exon( exon_id=exon_id, contig=contig, start=start, end=end, strand=strand, gene_name=gene_name, gene_id=gene_id) return self._exons[exon_id]
java
public static Set<DatastreamInfo> convertGenDatastreamArrayToDatastreamInfoSet(Datastream[] genDss) { Set<DatastreamInfo> set = new HashSet<DatastreamInfo>(genDss.length); for (Datastream ds : genDss) { set.add(convertGenDatastreamDefToDatastreamInfo(ds)); } return set; }
java
public static <T, K, V> MutableMap<K, V> toMap( T[] objectArray, Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction) { MutableMap<K, V> map = UnifiedMap.newMap(); Procedure<T> procedure = new MapCollectProcedure<T, K, V>(map, keyFunction, valueFunction); ArrayIterate.forEach(objectArray, procedure); return map; }
python
def table_names(self): """Returns names of all tables in the database""" query = "SELECT name FROM sqlite_master WHERE type='table'" cursor = self.connection.execute(query) results = cursor.fetchall() return [result_tuple[0] for result_tuple in results]
python
def _repo(self, args): ''' Process repo commands ''' args.pop(0) command = args[0] if command == 'list': self._repo_list(args) elif command == 'packages': self._repo_packages(args) elif command == 'search': self._repo_packages(args, search=True) elif command == 'update': self._download_repo_metadata(args) elif command == 'create': self._create_repo(args) else: raise SPMInvocationError('Invalid repo command \'{0}\''.format(command))
python
def ExportNEP2(self, passphrase): """ Export the encrypted private key in NEP-2 format. Args: passphrase (str): The password to encrypt the private key with, as unicode string Returns: str: The NEP-2 encrypted private key """ if len(passphrase) < 2: raise ValueError("Passphrase must have a minimum of 2 characters") # Hash address twice, then only use the first 4 bytes address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest() address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest() address_hash = address_hash_tmp2[:4] # Normalize password and run scrypt over it with the address_hash pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) # Split the scrypt-result into two parts derived1 = derived[:32] derived2 = derived[32:] # Run XOR and encrypt the derived parts with AES xor_ed = xor_bytes(bytes(self.PrivateKey), derived1) cipher = AES.new(derived2, AES.MODE_ECB) encrypted = cipher.encrypt(xor_ed) # Assemble the final result assembled = bytearray() assembled.extend(NEP_HEADER) assembled.extend(NEP_FLAG) assembled.extend(address_hash) assembled.extend(encrypted) # Finally, encode with Base58Check encrypted_key_nep2 = base58.b58encode_check(bytes(assembled)) return encrypted_key_nep2.decode("utf-8")
java
public static Phrase from(View v, @StringRes int patternResourceId) { return from(v.getResources(), patternResourceId); }
python
def unsubscribe_stratgy(self, strategy_id): """取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description] """ today = datetime.date.today() order_id = str(uuid.uuid1()) if strategy_id in self._subscribed_strategy.keys(): self._subscribed_strategy[strategy_id]['status'] = 'canceled' self.coins_history.append( [0, strategy_id, str(today), 0, order_id, 'unsubscribe'] )
java
@Override public WeightedGraph<WeightedEdge> copy(Set<Integer> toCopy) { // Special case for if the caller is requesting a copy of the entire // graph, which is more easily handled with the copy constructor if (toCopy.size() == order() && toCopy.equals(vertices())) return new SparseWeightedGraph(this); SparseWeightedGraph g = new SparseWeightedGraph(); for (int v : toCopy) { if (!contains(v)) throw new IllegalArgumentException( "Requested copy with non-existant vertex: " + v); g.add(v); SparseWeightedEdgeSet edges = getEdgeSet(v); for (int v2 : toCopy) { if (v == v2) break; if (edges.connects(v2)) { for (WeightedEdge e : edges.getEdges(v2)) g.add(e); } } // for (WeightedEdge e : getAdjacencyList(v)) // if (toCopy.contains(e.from()) && toCopy.contains(e.to())) // g.add(e); } return g; }
java
protected IWord getNextCJKWord(int c, int pos) throws IOException { char[] chars = nextCJKSentence(c); int cjkidx = 0; IWord w = null; while ( cjkidx < chars.length ) { /* * find the next CJK word. * the process will be different with the different algorithm * @see getBestCJKChunk() from SimpleSeg or ComplexSeg. */ w = null; /* * check if there is Chinese numeric. * make sure chars[cjkidx] is a Chinese numeric * and it is not the last word. */ if ( cjkidx + 1 < chars.length && NumericUtil.isCNNumeric(chars[cjkidx]) > -1 ) { //get the Chinese numeric chars String num = nextCNNumeric( chars, cjkidx ); int NUMLEN = num.length(); /* * check the Chinese fraction. * old logic: {{{ * cjkidx + 3 < chars.length && chars[cjkidx+1] == '分' * && chars[cjkidx+2] == '之' * && CNNMFilter.isCNNumeric(chars[cjkidx+3]) > -1. * }}} * * checkCF will be reset to be 'TRUE' it num is a Chinese fraction. * @added 2013-12-14. * */ if ( (ctrlMask & ISegment.CHECK_CF_MASK) != 0 ) { w = new Word(num, IWord.T_CN_NUMERIC); w.setPosition(pos+cjkidx); w.setPartSpeech(IWord.NUMERIC_POSPEECH); wordPool.add(w); /* * Here: * Convert the Chinese fraction to Arabic fraction, * if the Config.CNFRA_TO_ARABIC is true. */ if ( config.CNFRA_TO_ARABIC ) { String[] split = num.split("分之"); IWord wd = new Word( NumericUtil.cnNumericToArabic(split[1], true)+ "/"+NumericUtil.cnNumericToArabic(split[0], true), IWord.T_CN_NUMERIC ); wd.setPosition(w.getPosition()); wd.setPartSpeech(IWord.NUMERIC_POSPEECH); wordPool.add(wd); } } /* * check the Chinese numeric and single units. * type to find Chinese and unit composed word. */ else if ( NumericUtil.isCNNumeric(chars[cjkidx+1]) > -1 || dic.match(ILexicon.CJK_UNIT, chars[cjkidx+1]+"") ) { StringBuilder sb = new StringBuilder(); String temp = null; String ONUM = num; //backup the old numeric sb.append(num); boolean matched = false; int j; /* * find the word that made up with the numeric * like: "五四运动" */ for ( j = num.length(); (cjkidx + j) < chars.length && j < config.MAX_LENGTH; j++ ) { sb.append(chars[cjkidx + j]); temp = sb.toString(); if ( dic.match(ILexicon.CJK_WORD, temp) ) { w = dic.get(ILexicon.CJK_WORD, temp); num = temp; matched = true; } } /* * @Note: when matched is true, num maybe a word like '五月', * yat, this will make it skip the Chinese numeric to Arabic logic * so find the matched word that it maybe a single Chinese units word * * @added: 2014-06-06 */ if ( matched == true && num.length() - NUMLEN == 1 && dic.match(ILexicon.CJK_UNIT, num.substring(NUMLEN)) ) { num = ONUM; matched = false; //reset the matched } IWord wd = null; if ( matched == false && config.CNNUM_TO_ARABIC ) { String arabic = NumericUtil.cnNumericToArabic(num, true)+""; if ( (cjkidx + num.length()) < chars.length && dic.match(ILexicon.CJK_UNIT, chars[cjkidx + num.length()]+"") ) { char units = chars[ cjkidx + num.length() ]; num += units; arabic += units; } wd = new Word( arabic, IWord.T_CN_NUMERIC); wd.setPartSpeech(IWord.NUMERIC_POSPEECH); wd.setPosition(pos+cjkidx); } //clear the stop words as need if ( config.CLEAR_STOPWORD && dic.match(ILexicon.STOP_WORD, num) ) { cjkidx += num.length(); continue; } /* * @Note: added at 2016/07/19 * we cannot share the position with the original word item in the * global dictionary accessed with this.dic * * cuz at the concurrency that will lead to the position error * so, we clone it if the word is directly get from the dictionary */ if ( w == null ) { w = new Word(num, IWord.T_CN_NUMERIC); w.setPartSpeech(IWord.NUMERIC_POSPEECH); } else { w = w.clone(); } w.setPosition(pos + cjkidx); wordPool.add(w); if ( wd != null ) { wordPool.add(wd); } } if ( w != null ) { cjkidx += w.getLength(); appendWordFeatures(w); continue; } } IChunk chunk = getBestCJKChunk(chars, cjkidx); w = chunk.getWords()[0]; String wps = w.getPartSpeech()==null ? null : w.getPartSpeech()[0]; /* * check and try to find a Chinese name. * * @Note at 2017/05/19 * add the origin part of speech check, if the * w is a Chinese name already and just let it go */ int T = -1; if ( config.I_CN_NAME && (!"nr".equals(wps)) && w.getLength() <= 2 && chunk.getWords().length > 1 ) { StringBuilder sb = new StringBuilder(); sb.append(w.getValue()); String str = null; //the w is a Chinese last name. if ( dic.match(ILexicon.CN_LNAME, w.getValue()) && (str = findCHName(chars, 0, chunk)) != null) { T = IWord.T_CN_NAME; sb.append(str); } //the w is Chinese last name adorn else if ( dic.match(ILexicon.CN_LNAME_ADORN, w.getValue()) && chunk.getWords()[1].getLength() <= 2 && dic.match(ILexicon.CN_LNAME, chunk.getWords()[1].getValue())) { T = IWord.T_CN_NICKNAME; sb.append(chunk.getWords()[1].getValue()); } /* * the length of the w is 2: * the last name and the first char make up a word * for the double name. */ /*else if ( w.getLength() > 1 && findCHName( w, chunk )) { T = IWord.T_CN_NAME; sb.append(chunk.getWords()[1].getValue().charAt(0)); }*/ if ( T != -1 ) { w = new Word(sb.toString(), T); w.setPartSpeech(IWord.NAME_POSPEECH); } } //check and clear the stop words if ( config.CLEAR_STOPWORD && dic.match(ILexicon.STOP_WORD, w.getValue()) ) { cjkidx += w.getLength(); continue; } /* * reach the end of the chars - the last word. * check the existence of the Chinese and English mixed word */ IWord ce = null; if ( (ctrlMask & ISegment.CHECK_CE_MASk) != 0 && (chars.length - cjkidx) <= dic.mixPrefixLength ) { ce = getNextMixedWord(chars, cjkidx); if ( ce != null ) { T = -1; } } /* * @Note: added at 2016/07/19 * if the ce word is null and if the T is -1 * the w should be a word that clone from itself */ if ( ce == null ) { if ( T == -1 ) w = w.clone(); } else { w = ce.clone(); } w.setPosition(pos+cjkidx); wordPool.add(w); cjkidx += w.getLength(); /* * check and append the Pinyin and the synonyms words. */ if ( T == -1 ) { appendWordFeatures(w); } } if ( wordPool.size() == 0 ) { return null; } return wordPool.remove(); }
python
def strip_spaces(s): """ Strip excess spaces from a string """ return u" ".join([c for c in s.split(u' ') if c])
python
def _check_version(version): """Check whether the JSON version matches the PyPhi version.""" if version != pyphi.__version__: raise pyphi.exceptions.JSONVersionError( 'Cannot load JSON from a different version of PyPhi. ' 'JSON version = {0}, current version = {1}.'.format( version, pyphi.__version__))
java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { try { // /!!!! Map<String, String> attribute = new HashMap<String, String>(); for (int i = 0; i < atts.getLength(); i++) { attribute.put(atts.getQName(i), atts.getValue(i)); } importer.startElement(uri, localName, qName, attribute); } catch (RepositoryException e) { // e.printStackTrace(); throw new SAXException(e); } }
java
public final void update (final String targetName, final int connectionID, final SettingsMap response) throws NoSuchSessionException { final SessionConfiguration sc; synchronized (sessionConfigs) { sc = sessionConfigs.get(targetName); synchronized (sc) { if (sc == null) { throw new NoSuchSessionException("A session with the ID '" + targetName + "' does not exist."); } synchronized (response) { SettingEntry se; for (Map.Entry<OperationalTextKey , String> e : response.entrySet()) { synchronized (globalConfig) { se = globalConfig.get(e.getKey()); if (se == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("This key " + e.getKey() + " is not in the globalConfig."); } continue; } synchronized (se) { if (se.getScope().compareTo(VALUE_SCOPE_SESSION) == 0) { sc.updateSessionSetting(e.getKey(), e.getValue(), se.getResult()); } else if (se.getScope().compareTo(VALUE_SCOPE_CONNECTION) == 0) { sc.updateConnectionSetting(connectionID, e.getKey(), e.getValue(), se.getResult()); } } } } } } } }
python
def neighbours(self, word, size = 10): """ Get nearest words with KDTree, ranking by cosine distance """ word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(points), "distances and points should be in same shape." words, scores = [], {} for (x,y) in zip(points, distances): w = self.index2word[x] if w == word: s = 1.0 else: s = cosine(v, self.syn0[x]) if s < 0: s = abs(s) words.append(w) scores[w] = min(s, 1.0) for x in sorted(words, key=scores.get, reverse=True): yield x, scores[x]
java
public void postwrite(byte[] b,int offset, int length) throws IOException { System.arraycopy(b,offset,_buf,_pos,length); _pos+=length; }
python
def to_math_type(arr): """Convert an array from native integer dtype range to 0..1 scaling down linearly """ max_int = np.iinfo(arr.dtype).max return arr.astype(math_type) / max_int
java
public void delete(String resourceGroupName, String interfaceEndpointName) { deleteWithServiceResponseAsync(resourceGroupName, interfaceEndpointName).toBlocking().last().body(); }
python
def create_cells(headers, schema_fields, values=None, row_number=None): """Create list of cells from headers, fields and values. Args: headers (List[str]): The headers values. schema_fields (List[tableschema.field.Field]): The tableschema fields. values (List[Any], optional): The cells values. If not specified, the created cells will have the same values as their corresponding headers. This is useful for specifying headers cells. If the list has any `None` values, as is the case on empty cells, the resulting Cell will have an empty string value. If the `values` list has a different length than the `headers`, the resulting Cell will have value `None`. row_number (int, optional): The row number. Returns: List[dict]: List of cells. """ fillvalue = '_fillvalue' is_header_row = (values is None) cells = [] iterator = zip_longest(headers, schema_fields, values or [], fillvalue=fillvalue) for column_number, (header, field, value) in enumerate(iterator, start=1): if header == fillvalue: header = None elif is_header_row: value = header if field == fillvalue: field = None if value == fillvalue: value = None elif value is None: value = '' cell = create_cell(header, value, field, column_number, row_number) cells.append(cell) return cells
java
public ApiResponse<ApiSuccessResponse> initiateTransferWithHttpInfo(String id, InitiateTransferData initiateTransferData) throws ApiException { com.squareup.okhttp.Call call = initiateTransferValidateBeforeCall(id, initiateTransferData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public boolean isAllowed(String classname) { Objects.requireNonNull(classname); if (!restrictedClassnames.isEmpty()) { for (String restrictedClassname : restrictedClassnames) { if (classname.startsWith(restrictedClassname)) { return false; } } } if (!allowedClassnames.isEmpty()) { for (String allowedClassname : allowedClassnames) { if (classname.startsWith(allowedClassname)) { return true; } } return false; } return true; }
python
def render(n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Render frames from the viewer. Parameters ---------- n_frames : int Number of frames to render. If more than one, the scene will animate. axis : (3,) float or None If present, the animation will rotate about the given axis in world coordinates. Otherwise, the animation will rotate in azimuth. clf : bool If true, the Visualizer is cleared after rendering the figure. kwargs : dict Other keyword arguments for the SceneViewer instance. Returns ------- list of perception.ColorImage A list of ColorImages rendered from the viewer. """ v = SceneViewer(Visualizer3D._scene, size=Visualizer3D._init_size, animate=(n_frames > 1), animate_axis=axis, max_frames=n_frames, **kwargs) if clf: Visualizer3D.clf() return v.saved_frames
java
public Map<String, Object> getAdditionalInfoForLogin(String userName, String password) { Map<String, Object> additionalInfos = new HashMap<String, Object>(); if (m_hasJlan) { try { additionalInfos.put(CmsJlanUsers.JLAN_HASH, CmsJlanUsers.hashPassword(password)); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } return additionalInfos; }
python
def authorize_client_credentials( self, client_id, client_secret=None, scope="private_agent" ): """Authorize to platform with client credentials This should be used if you posses client_id/client_secret pair generated by platform. """ self.auth_data = { "grant_type": "client_credentials", "scope": [ scope ], "client_id": client_id, "client_secret": client_secret } self._do_authorize()
java
public BDDTYPE createBDDTYPEFromString(EDataType eDataType, String initialValue) { BDDTYPE result = BDDTYPE.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; }
java
private void makeTempChildPath(String path, String data) { String finerPrint = DisClientComConfig.getInstance().getInstanceFingerprint(); String mainTypeFullStr = path + "/" + finerPrint; try { ZookeeperMgr.getInstance().createEphemeralNode(mainTypeFullStr, data, CreateMode.EPHEMERAL); } catch (Exception e) { LOGGER.error("cannot create: " + mainTypeFullStr + "\t" + e.toString()); } }
java
public static final <T extends UIObject> void removeAnimationOnEnd(final T widget, final String animation) { if (widget != null && animation != null) { removeAnimationOnEnd(widget.getElement(), animation); } }
python
def run_in_buildenv( self, buildenv_target_name: str, cmd: list, cmd_env: dict=None, work_dir: str=None, auto_uid: bool=True, runtime: str=None, **kwargs): """Run a command in a named BuildEnv Docker image. :param buildenv_target_name: A named Docker image target in which the command should be run. :param cmd: The command to run, as you'd pass to subprocess.run() :param cmd_env: A dictionary of environment variables for the command. :param work_dir: A different work dir to run in. Either absolute path, or relative to project root. :param auto_uid: Whether to run as the active uid:gid, or as root. :param kwargs: Extra keyword arguments that are passed to the subprocess.run() call that runs the BuildEnv container (for, e.g. timeout arg, stdout/err redirection, etc.) :raises KeyError: If named BuildEnv is not a registered BuildEnv image """ buildenv_target = self.targets[buildenv_target_name] # TODO(itamar): Assert that buildenv_target is up to date redirection = any( stream_key in kwargs for stream_key in ('stdin', 'stdout', 'stderr', 'input')) docker_run = ['docker', 'run'] # if not self.conf.non_interactive: # docker_run.append('-i') if not redirection: docker_run.append('-t') project_vol = (self.conf.docker_volume if self.conf.docker_volume else self.conf.project_root) container_work_dir = PurePath('/project') if work_dir: container_work_dir /= work_dir if runtime: docker_run.extend([ '--runtime', runtime, ]) docker_run.extend([ '--rm', '-v', project_vol + ':/project', # TODO: windows containers? '-w', container_work_dir.as_posix(), ]) if cmd_env: for key, value in cmd_env.items(): # TODO(itamar): escaping docker_run.extend(['-e', '{}={}'.format(key, value)]) if platform.system() == 'Linux' and auto_uid: # Fix permissions for bind-mounted project dir # The fix is not needed when using Docker For Mac / Windows, # because it is somehow taken care of by the sharing mechanics docker_run.extend([ '-u', '{}:{}'.format(os.getuid(), os.getgid()), '-v', '/etc/shadow:/etc/shadow:ro', '-v', '/etc/group:/etc/group:ro', '-v', '/etc/passwd:/etc/passwd:ro', '-v', '/etc/sudoers:/etc/sudoers:ro', ]) docker_run.append(format_qualified_image_name(buildenv_target)) docker_run.extend(cmd) logger.info('Running command in build env "{}" using command {}', buildenv_target_name, docker_run) # TODO: Consider changing the PIPEs to temp files. if 'stderr' not in kwargs: kwargs['stderr'] = PIPE if 'stdout' not in kwargs: kwargs['stdout'] = PIPE result = run(docker_run, check=True, **kwargs) # TODO(Dana): Understand what is the right enconding and remove the # try except if kwargs['stdout'] is PIPE: try: sys.stdout.write(result.stdout.decode('utf-8')) except UnicodeEncodeError as e: sys.stderr.write('tried writing the stdout of {},\n but it ' 'has a problematic character:\n {}\n' 'hex dump of stdout:\n{}\n' .format(docker_run, str(e), codecs.encode( result.stdout, 'hex').decode('utf8'))) if kwargs['stderr'] is PIPE: try: sys.stderr.write(result.stderr.decode('utf-8')) except UnicodeEncodeError as e: sys.stderr.write('tried writing the stderr of {},\n but it ' 'has a problematic character:\n {}\n' 'hex dump of stderr:\n{}\n' .format(docker_run, str(e), codecs.encode( result.stderr, 'hex').decode('utf8'))) return result
java
public void setWaterMarks(String source, long lwmScn, long hwmScn) { WaterMarkEntry e = sourceWaterMarkMap.get(source); if (e == null) { e = new WaterMarkEntry(source); sourceWaterMarkMap.put(source, e); } e.setLWMScn(lwmScn); e.setHWMScn(hwmScn); }
python
def _read_body(stream, decoder, strict=False, logger=None): """ Read an AMF message body from the stream. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param decoder: An AMF0 decoder. @param strict: Use strict decoding policy. Default is `False`. @param logger: Used to log interesting events whilst reading a remoting body. @type logger: A C{logging.Logger} instance or C{None}. @return: A C{tuple} containing the C{id} of the request and the L{Request} or L{Response} """ def _read_args(): # we have to go through this insanity because it seems that amf0 # does not keep the array of args in the object references lookup type_byte = stream.peek(1) if type_byte == '\x11': if not decoder.use_amf3: raise pyamf.DecodeError( "Unexpected AMF3 type with incorrect message type") return decoder.readElement() if type_byte != '\x0a': raise pyamf.DecodeError("Array type required for request body") stream.read(1) x = stream.read_ulong() return [decoder.readElement() for i in xrange(x)] target = stream.read_utf8_string(stream.read_ushort()) response = stream.read_utf8_string(stream.read_ushort()) status = STATUS_OK is_request = True for code, s in STATUS_CODES.iteritems(): if not target.endswith(s): continue is_request = False status = code target = target[:0 - len(s)] if logger: logger.debug('Remoting target: %r' % (target,)) data_len = stream.read_ulong() pos = stream.tell() if is_request: data = _read_args() else: data = decoder.readElement() if strict and pos + data_len != stream.tell(): raise pyamf.DecodeError("Data read from stream does not match body " "length (%d != %d)" % (pos + data_len, stream.tell(),)) if is_request: return response, Request(target, body=data) if status == STATUS_ERROR and isinstance(data, pyamf.ASObject): data = get_fault(data) return target, Response(data, status)
python
def with_name(self, name): """Sets the name scope for future operations.""" with self.g.as_default(), tf.variable_scope(name) as var_scope: name_scope = scopes.get_current_name_scope() return _DeferredLayer(self.bookkeeper, None, (), {}, scope=(name_scope, var_scope), defaults=self._defaults, pass_through=self, partial_context=self._partial_context)
python
def _parse_tokenize(self, rule): """Tokenizer for the policy language.""" for token in self._TOKENIZE_RE.split(rule): # Skip empty tokens if not token or token.isspace(): continue # Handle leading parens on the token clean = token.lstrip('(') for i in range(len(token) - len(clean)): yield '(', '(' # If it was only parentheses, continue if not clean: continue else: token = clean # Handle trailing parens on the token clean = token.rstrip(')') trail = len(token) - len(clean) # Yield the cleaned token lowered = clean.lower() if lowered in ('and', 'or', 'not'): # Special tokens yield lowered, clean elif clean: # Not a special token, but not composed solely of ')' if len(token) >= 2 and ((token[0], token[-1]) in [('"', '"'), ("'", "'")]): # It's a quoted string yield 'string', token[1:-1] else: yield 'check', self._parse_check(clean) # Yield the trailing parens for i in range(trail): yield ')', ')'
java
void setStartTime(long startTime) { //Making the assumption of passed startTime to be a positive //long value explicit. if (startTime > 0) { this.startTime = startTime; } else { //Using String utils to get the stack trace. LOG.error("Trying to set illegal startTime for task : " + taskid + ".Stack trace is : " + StringUtils.stringifyException(new Exception())); } }
java
public static AppMsg makeText(Activity context, int resId, Style style) throws Resources.NotFoundException { return makeText(context, context.getResources().getText(resId), style); }
java
public void each(Consumer<T> operation) { for (T component : components) { operation.accept(component); } }
python
def run(self, stop): """ Run the pipeline. :param stop: Stop event """ _LOGGER.info("Starting a new pipeline on group %s", self._group) self._group.bridge.incr_active() for i, stage in enumerate(self._pipe): self._execute_stage(i, stage, stop) _LOGGER.info("Finished pipeline on group %s", self._group) self._group.bridge.decr_active()
java
public boolean remove(String field) { try { return getJedisCommands(groupName).hdel(key, field).equals(RESP_OK); } finally { getJedisProvider(groupName).release(); } }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "lineStringMember") public JAXBElement<LineStringPropertyType> createLineStringMember(LineStringPropertyType value) { return new JAXBElement<LineStringPropertyType>(_LineStringMember_QNAME, LineStringPropertyType.class, null, value); }
python
def _send(self, value, mode): """Send the specified value to the display with automatic 4bit / 8bit selection. The rs_mode is either ``RS_DATA`` or ``RS_INSTRUCTION``.""" # Assemble the parameters sent to the pigpio script params = [mode] params.extend([(value >> i) & 0x01 for i in range(8)]) # Switch off pigpio's exceptions, so that we get the return codes pigpio.exceptions = False while True: ret = self.pi.run_script(self._writescript, params) if ret >= 0: break elif ret != pigpio.PI_SCRIPT_NOT_READY: raise pigpio.error(pigpio.error_text(ret)) # If pigpio script is not ready, sleep and try again c.usleep(1) # Switch on pigpio's exceptions pigpio.exceptions = True
python
def install(name=None, refresh=False, version=None, pkgs=None, **kwargs): ''' Install packages using the pkgutil tool. CLI Example: .. code-block:: bash salt '*' pkg.install <package_name> salt '*' pkg.install SMClgcc346 Multiple Package Installation Options: pkgs A list of packages to install from OpenCSW. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]' Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' if refresh: refresh_db() try: # Ignore 'sources' argument pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0] except MinionError as exc: raise CommandExecutionError(exc) if not pkg_params: return {} if pkgs is None and version and len(pkg_params) == 1: pkg_params = {name: version} targets = [] for param, pkgver in six.iteritems(pkg_params): if pkgver is None: targets.append(param) else: targets.append('{0}-{1}'.format(param, pkgver)) cmd = '/opt/csw/bin/pkgutil -yu {0}'.format(' '.join(targets)) old = list_pkgs() __salt__['cmd.run_all'](cmd) __context__.pop('pkg.list_pkgs', None) new = list_pkgs() return salt.utils.data.compare_dicts(old, new)
python
def update_build_configuration(id, **kwargs): """ Update an existing BuildConfiguration with new information :param id: ID of BuildConfiguration to update :param name: Name of BuildConfiguration to update :return: """ data = update_build_configuration_raw(id, **kwargs) if data: return utils.format_json(data)
java
public static ci[] get(nitro_service service) throws Exception{ ci obj = new ci(); ci[] response = (ci[])obj.get_resources(service); return response; }
python
def config(*args, **attrs): """Override configuration""" attrs.setdefault("metavar", "KEY=VALUE") attrs.setdefault("multiple", True) return option(config, *args, **attrs)
python
def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.safe_trigger(*args) return self
java
@Override protected void configure() { bind(SwaggerServletContext.class).to(ServletContext.class).in(Singleton.class); bind(SwaggerServletConfig.class).to(ServletConfig.class).in(Singleton.class); }
python
def checkedItems( self ): """ Returns the checked items for this combobox. :return [<str>, ..] """ if not self.isCheckable(): return [] return [nativestring(self.itemText(i)) for i in self.checkedIndexes()]
java
@Override public ResultSet doQuery(final SqlContext sqlContext, final PreparedStatement preparedStatement, final ResultSet resultSet) throws SQLException { return resultSet; }
java
public CmsVisitEntryFilter filterResource(CmsUUID structureId) { CmsVisitEntryFilter filter = (CmsVisitEntryFilter)clone(); filter.m_structureId = structureId; return filter; }
python
def minimum(station_code): """Extreme Minimum Design Temperature for a location. Degrees in Celcius Args: station_code (str): Weather Station Code Returns: float degrees Celcius """ temp = None fin = None try: fin = open('%s/%s' % (env.WEATHER_DATA_PATH, _basename(station_code, 'ddy'))) except IOError: logger.info("File not found") download_extract(_eere_url(station_code)) fin = open('%s/%s' % (env.WEATHER_DATA_PATH, _basename(station_code, 'ddy'))) for line in fin: value = re.search('Max Drybulb=(-?\\d+\\.\\d*)', line) if value: temp = float(value.groups()[0]) if not temp: try: fin = open('%s/%s' % (env.WEATHER_DATA_PATH, _basename(station_code, 'stat'))) for line in fin: if line.find('Minimum Dry Bulb') is not -1: return float(line[37:-1].split('\xb0')[0]) except IOError: pass if temp: return temp else: raise Exception("Error: Minimum Temperature not found")
java
public void launchAddBufferPoolDialog() { if (addBufferPoolDialog == null) { addBufferPoolDialog = new AddResourceDialog( securityFramework.getSecurityContext(getProxy().getNameToken()), resourceDescriptionRegistry.lookup(bufferPoolAddressTemplate), new AddResourceDialog.Callback() { @Override public void onAdd(ModelNode payload) { window.hide(); circuit.dispatch(new AddBufferPool(payload)); } @Override public void onCancel() { window.hide(); } } ); } else { addBufferPoolDialog.clearValues(); } window = new DefaultWindow("Buffer Pool"); window.setWidth(480); window.setHeight(360); window.setWidget(addBufferPoolDialog); window.setGlassEnabled(true); window.center(); }
java
protected ArrayList<Snak> getQualifierList(PropertyIdValue propertyIdValue) { ArrayList<Snak> result = this.qualifiers.get(propertyIdValue); if (result == null) { result = new ArrayList<Snak>(); this.qualifiers.put(propertyIdValue, result); } return result; }
java
public void setIntegerReportOption(String propName, int propValue, SIBusMessage coreMsg)throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setIntegerReportOption", new Object[]{propName, propValue, coreMsg}); if(propName.equals(ApiJmsConstants.REPORT_EXCEPTION_PROPERTY)) { Byte newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_EXCEPTION: newVal = SIApiConstants.REPORT_NO_DATA; break; case ApiJmsConstants.MQRO_EXCEPTION_WITH_DATA: newVal = SIApiConstants.REPORT_WITH_DATA; break; case ApiJmsConstants.MQRO_EXCEPTION_WITH_FULL_DATA: newVal = SIApiConstants.REPORT_WITH_FULL_DATA; break; default: // d238447 FFDC review. No FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, "" + propValue }, tc); } coreMsg.setReportException(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_EXCEPTION set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_EXPIRATION_PROPERTY)) { Byte newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_EXPIRATION: newVal = SIApiConstants.REPORT_NO_DATA; break; case ApiJmsConstants.MQRO_EXPIRATION_WITH_DATA: newVal = SIApiConstants.REPORT_WITH_DATA; break; case ApiJmsConstants.MQRO_EXPIRATION_WITH_FULL_DATA: newVal = SIApiConstants.REPORT_WITH_FULL_DATA; break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportExpiry(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_EXPIRATION set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_COA_PROPERTY)) { Byte newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_COA: newVal = SIApiConstants.REPORT_NO_DATA; break; case ApiJmsConstants.MQRO_COA_WITH_DATA: newVal = SIApiConstants.REPORT_WITH_DATA; break; case ApiJmsConstants.MQRO_COA_WITH_FULL_DATA: newVal = SIApiConstants.REPORT_WITH_FULL_DATA; break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc); } coreMsg.setReportCOA(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_COA set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_COD_PROPERTY)) { Byte newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_COD: newVal = SIApiConstants.REPORT_NO_DATA; break; case ApiJmsConstants.MQRO_COD_WITH_DATA: newVal = SIApiConstants.REPORT_WITH_DATA; break; case ApiJmsConstants.MQRO_COD_WITH_FULL_DATA: newVal = SIApiConstants.REPORT_WITH_FULL_DATA; break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc); } coreMsg.setReportCOD(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_COD set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_PAN_PROPERTY)) { Boolean newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_PAN: newVal = Boolean.valueOf(true); break; case ApiJmsConstants.MQRO_NONE: newVal = Boolean.valueOf(false); break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportPAN(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_PAN set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_NAN_PROPERTY)) { Boolean newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_NAN: newVal = Boolean.valueOf(true); break; case ApiJmsConstants.MQRO_NONE: newVal = Boolean.valueOf(false); break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportNAN(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_NAN set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_MSGID_PROPERTY)) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.debug(this, tc, "propName equals REPORT_MSGID_PROPERTY"); Boolean newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_PASS_MSG_ID: newVal = Boolean.valueOf(true); break; case ApiJmsConstants.MQRO_NEW_MSG_ID: newVal = Boolean.valueOf(false); break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportPassMsgId(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_MSGID set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_CORRELID_PROPERTY)) { Boolean newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_PASS_CORREL_ID: newVal = Boolean.valueOf(true); break; case ApiJmsConstants.MQRO_COPY_MSG_ID_TO_CORREL_ID: newVal = Boolean.valueOf(false); break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportPassCorrelId(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_CORRELID set to : "+newVal); } else if(propName.equals(ApiJmsConstants.REPORT_DISCARD_PROPERTY)) { Boolean newVal = null; switch(propValue) { case ApiJmsConstants.MQRO_DISCARD_MSG: newVal = Boolean.valueOf(true); break; case ApiJmsConstants.MQRO_NONE: newVal = Boolean.valueOf(false); break; default: // d238447 FFDC review, no FFDC required. throw (JMSException) JmsErrorUtils.newThrowable( JMSException.class, "INVALID_VALUE_CWSIA0321", new Object[] { propName, ""+propValue }, tc ); } coreMsg.setReportDiscardMsg(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "REPORT_DISCARD set to : "+newVal); } else if(propName.equals(ApiJmsConstants.FEEDBACK_PROPERTY)) { // need to intialise the sharedUtils? if (utils == null) utils = JmsInternalsFactory.getSharedUtils(); Integer newVal = utils.convertMQFeedbackToJS(propValue); coreMsg.setReportFeedback(newVal); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "FEEDBACK_PROPERTY set to : "+newVal); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setIntegerReportOption"); }
python
def after(self, func): """ Returns a function that will only be executed after being called N times. """ ns = self.Namespace() ns.times = self.obj if ns.times <= 0: return func() def work_after(*args): if ns.times <= 1: return func(*args) ns.times -= 1 return self._wrap(work_after)
python
def rank_members_in(self, leaderboard_name, members_and_scores): ''' Rank an array of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members_and_scores [Array] Variable list of members and scores. ''' pipeline = self.redis_connection.pipeline() for member, score in grouper(2, members_and_scores): if isinstance(self.redis_connection, Redis): pipeline.zadd(leaderboard_name, member, score) else: pipeline.zadd(leaderboard_name, score, member) pipeline.execute()
java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static synchronized void register(android.app.Application application) { if (application == null) { Logger.i("Application instance is null/system API is too old"); return; } if (registered) { Logger.v("Lifecycle callbacks have already been registered"); return; } registered = true; application.registerActivityLifecycleCallbacks( new android.app.Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle bundle) { CleverTapAPI.onActivityCreated(activity); } @Override public void onActivityStarted(Activity activity) {} @Override public void onActivityResumed(Activity activity) { CleverTapAPI.onActivityResumed(activity); } @Override public void onActivityPaused(Activity activity) { CleverTapAPI.onActivityPaused(); } @Override public void onActivityStopped(Activity activity) {} @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {} @Override public void onActivityDestroyed(Activity activity) {} } ); Logger.i("Activity Lifecycle Callback successfully registered"); }
java
private void run(String key, ConcurrentLinkedQueue<Work> workQueue) { Work work = workQueue.poll(); CompletableFuture<Void> future; try { future = processEvent(work.getEvent()); } catch (Exception e) { future = Futures.failedFuture(e); } future.whenComplete((r, e) -> { if (e != null && toPostpone(work.getEvent(), work.getPickupTime(), e)) { handleWorkPostpone(key, workQueue, work); } else { if (e != null) { work.getResult().completeExceptionally(e); } else { work.getResult().complete(r); } handleWorkComplete(key, workQueue, work); } }); }
java
public FessMessages addConstraintsTypeDoubleMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeDouble_MESSAGE)); return this; }
python
def get_bytes(self): """client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data""" ret = struct.pack("<I16s16sQ", client_DH_inner_data.constructor, self.nonce, self.server_nonce, self.retry_id) bytes_io = BytesIO() bytes_io.write(ret) serialize_string(bytes_io, self.g_b) return bytes_io.getvalue()
java
private Map<String, ClassRef> getReferenceMap() { Map<String, ClassRef> mapping = new HashMap<String, ClassRef>(); List<ClassRef> refs = getReferences(); //It's best to have predictable order, so that we can generate uniform code. Collections.sort(refs, new Comparator<ClassRef>() { @Override public int compare(ClassRef o1, ClassRef o2) { return o1.getFullyQualifiedName().compareTo(o2.getFullyQualifiedName()); } }); for (ClassRef ref : refs) { String key = ref.getDefinition().getName(); if (!mapping.containsKey(key)) { mapping.put(key, ref); } } return mapping; }
java
@Override public boolean shouldPrintLoggingErrors() { return CONFIGURATION.getBooleanProperty( NETFLIX_BLITZ4J_PRINT_LOGGING_ERRORS, Boolean.valueOf(this.getPropertyValue( NETFLIX_BLITZ4J_PRINT_LOGGING_ERRORS, "false"))).get(); }
java
public static void lock(Lock lock, String callerClass, String callerMethod, Object... args) { final String sourceMethod = "lock"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[]{Thread.currentThread(), lock, callerClass, callerMethod, args}); } long start = System.currentTimeMillis(); boolean quiesced = false, logged = false; try { while (!lock.tryLock(SIGNAL_LOG_INTERVAL_SECONDS, TimeUnit.SECONDS)) { if (!quiesced) { quiesced = logWaiting(callerClass, callerMethod, lock, start, args); logged = true; } } } catch (InterruptedException ex) { // InterruptedException is not thrown by Lock.lock() so convert to a // RuntimeException. throw new RuntimeException(ex); } if (logged) { logResuming(callerClass, callerMethod, lock, start); } if (isTraceLogging) { log.exiting(sourceClass, sourceMethod, Arrays.asList(Thread.currentThread(), lock, callerClass, callerMethod)); } return; }
python
def clf(): """Clear the current figure """ Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color) Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)