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 o...
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'], ...
java
public void sign( SignConfig config, File jarFile, File signedJar ) throws MojoExecutionException { JarSignerRequest request = config.createSignRequest( jarFile, signedJar ); try { JavaToolResult result = jarSigner.execute( request ); CommandLineExcepti...
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()...
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(RE...
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.er...
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 o...
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 resul...
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: Tim...
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...
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.get...
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 Illeg...
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) s...
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. """ ...
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", ""); Registrat...
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; ...
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: ...
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 ); } ...
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(), $('#...
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("Ca...
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 OnlineResour...
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...
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...
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: ...
java
public void setReplicaGlobalSecondaryIndexSettingsUpdate( java.util.Collection<ReplicaGlobalSecondaryIndexSettingsUpdate> replicaGlobalSecondaryIndexSettingsUpdate) { if (replicaGlobalSecondaryIndexSettingsUpdate == null) { this.replicaGlobalSecondaryIndexSettingsUpdate = null; ...
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", "str...
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>(m...
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_pa...
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) <...
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...
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 SparseW...
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 differe...
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( ...
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.getQNam...
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 ...
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(p...
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)...
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<ApiSuccessResp...
java
public boolean isAllowed(String classname) { Objects.requireNonNull(classname); if (!restrictedClassnames.isEmpty()) { for (String restrictedClassname : restrictedClassnames) { if (classname.startsWith(restrictedClassname)) { return false; ...
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 a...
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)); ...
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 = { "...
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.EPHEMER...
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 ...
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...
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, (), ...
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(...
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 : " + taski...
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...
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...
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...
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: ...
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 ...
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, ...
java
public void launchAddBufferPoolDialog() { if (addBufferPoolDialog == null) { addBufferPoolDialog = new AddResourceDialog( securityFramework.getSecurityContext(getProxy().getNameToken()), resourceDescriptionRegistry.lookup(bufferPoolAddressTemplate), ...
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_...
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: ...
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.re...
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) { Logge...
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.wh...
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...
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>() { ...
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...
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)