language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def do_copy_file(self, args): """ Determine if file should be copied or not and handle exceptions. """ path, prefixed_path, source_storage = args reset_connection(self.storage) if self.collectfast_enabled and not self.dry_run: try: if not sho...
python
def set_sampling_interval(self, interval): """ This method sets the sampling interval for the Firmata loop method :param interval: time in milliseconds :returns: No return value """ task = asyncio.ensure_future(self.core.set_sampling_interval(interval)) self.loo...
java
public Pair<T> max() { int maxCount = 0; TLongIntIterator iter = counts.iterator(); long maxIndex = 0; while (!iter.hasNext()) { iter.advance(); int count = iter.value(); if (count > maxCount) { maxIndex = iter.key(); ...
java
public ScriptWrapper loadScript(ScriptWrapper script) throws IOException { try { return loadScript(script, DEFAULT_CHARSET); } catch (MalformedInputException e) { if (Charset.defaultCharset() == DEFAULT_CHARSET) { // No point trying the (JVM) default charset if it's the same... throw e; } ...
python
def make_std_api(python_version=sys.version_info, variant=VARIANT): """ Generate an object which can be used in the same way as the python standard dis module. The difference is that the generated 'module' can be used to disassemble byte / word code from a different python version than the version o...
python
def _walk_librispeech_dir(directory): """Walk a Librispeech directory and yield examples.""" directory = os.path.join(directory, "LibriSpeech") for path, _, files in tf.io.gfile.walk(directory): if not files: continue transcript_file = [f for f in files if f.endswith(".txt")] if not transcript_...
java
private void recycleViewsFromEndExpose(RecyclerView.Recycler recycler, int dt) { final int childCount = getChildCount(); if (dt < 0) { if (DEBUG) { Log.d(TAG, "Called recycle from end with a negative value. This might happen" + " during layout changes ...
python
def _update_val(self, val, result_score_list): """Update values in the list of result scores and self._pbar during pipeline evaluation. Parameters ---------- val: float or "Timeout" CV scores result_score_list: list A list of CV scores Returns ...
python
def load_config(self): """ Load the configuration from git config. """ for key in self.settings: value = self.config(key) # Parse true/false if value == '' or value is None: continue # Not set by user, go on if val...
java
public boolean isFeatureEnabled(com.ibm.websphere.servlet.container.WebContainer.Feature feature) { return this.features.contains(feature); }
python
def applyJSONFilters(actions, source, format=""): """Walk through JSON structure and apply filters This: * reads a JSON-formatted pandoc document from a source string * transforms it by walking the tree and performing the actions * returns a new JSON-formatted pandoc document as a string The ...
java
public V get(K key, int index) { final Collection<V> collection = get(key); return CollUtil.get(collection, index); }
java
public static synchronized LaContainer create(String path) { if (LdiStringUtil.isEmpty(path)) { throw new EmptyRuntimeException("path"); } return doCreate(path); }
java
public final EObject ruleAnnotationField() throws RecognitionException { EObject current = null; Token otherlv_7=null; Token otherlv_9=null; Token otherlv_11=null; Token otherlv_14=null; Token otherlv_16=null; Token otherlv_18=null; Token otherlv_20=null;...
java
public URLConnection asURLConnection() { URLConnection uc = getURLConnection(); if (uc != null) return uc; try { return new InputStreamURLConnection( getResourceURLOrSystemId(), this, getDefaultUrlConnectionHeader()...
python
def get_decompression_transform_files(self, offset=0): """Returns a list of dicts representing ``<mets:transformFile>`` elements with ``TRANSFORMTYPE="decompression"`` given ``compression_algorithm`` which is a comma-separated string of algorithms that must be used in the order provided ...
java
public void setBeta(double beta) { if(beta <= 0 || beta >= 1 || Double.isNaN(beta)) throw new IllegalArgumentException("shrinkage term must be in (0, 1), not " + beta); this.beta = beta; }
java
public Token createToken(String tokenType, Map<String, Object> tokenData) throws TokenCreationFailedException { try { TokenService tokenService = getTokenServiceForType(tokenType); return tokenService.createToken(tokenData); } catch (IllegalArgumentException e) { thro...
java
private static String decodeHTMLEntities(String string) { if (string == null) { return null; } try { return URLDecoder.decode(string, Charset.defaultCharset().displayName()); } catch (UnsupportedEncodingException exception) { return string; } }
java
public JobWorkspaceRestore getLastRestore(String repositoryName, String workspaceName) { for (int i = restoreJobs.size() - 1; i >= 0; i--) { JobWorkspaceRestore job = restoreJobs.get(i); if (repositoryName.equals(job.getRepositoryName()) && workspaceName.equals(job.getWorkspaceName()))...
java
public Injector createInjector() { for (final TypeLiteral<?> typeLiteral : _inheritedTypeLiterals) { final Key<?> key = Key.get(typeLiteral); final Binding<?> binding = _parentInjector.getExistingBinding(key); if (binding != null) { if (!_adHocModule.hasBindin...
java
@Override public void expire(K key, V val) { if (val == null) { return; } try { TupleInfo tupleInfo = (TupleInfo) val; FailSpoutMsg fail = new FailSpoutMsg(key, spout, tupleInfo, taskStats); disruptorEventQueue.publish(fail); } catch (...
java
protected Variable createVariable(final String name, final Class<?> type, final Object value, final Modifiers mods) throws UtilEvalError { return new Variable(name, type, value, mods); }
java
public void addRequestHandler(String clazz) { Object initClass; try { initClass = Class.forName(clazz).newInstance(); } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_INIT_REQUEST_HANDLER_FAILURE_1, clazz), t); return; } ...
java
public WebServiceTemplateBuilder interceptors( Collection<? extends ClientInterceptor> interceptors) { Assert.notNull(interceptors, "Interceptors must not be null"); return new WebServiceTemplateBuilder(this.detectHttpMessageSender, append(Collections.<ClientInterceptor>emptySet(), interceptors), this.in...
java
public final Promise set(String key, byte[] value, SetArgs args) { byte[] binaryKey = key.getBytes(StandardCharsets.UTF_8); if (client != null) { if (args == null) { return new Promise(client.set(binaryKey, value)); } return new Promise(client.set(binaryKey, value, args)); } if (clusteredCl...
python
def switch_on(self): """Turn the switch on.""" success = self.set_status(CONST.STATUS_OPEN_INT) if success: self._json_state['status'] = CONST.STATUS_OPEN return success
python
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set ...
python
def running_covar(xx=True, xy=False, yy=False, remove_mean=False, symmetrize=False, sparse_mode='auto', modify_data=False, column_selection=None, diag_only=False, nsave=5): """ Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and t...
java
public ServiceFuture<InputInner> getAsync(String resourceGroupName, String jobName, String inputName, final ServiceCallback<InputInner> serviceCallback) { return ServiceFuture.fromHeaderResponse(getWithServiceResponseAsync(resourceGroupName, jobName, inputName), serviceCallback); }
java
public void deliver(VoltMessage msg) { if (!m_isLeader && msg instanceof Iv2InitiateTaskMessage) { final Iv2InitiateTaskMessage m = (Iv2InitiateTaskMessage) msg; // We can't repair read only SP transactions. Just don't log them to the repair log. if (m.isReadOnly()) { ...
python
def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ ...
python
def capture(self): """ Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step payment flow, where first you created a charge with the capture option set to False. See https://stripe.com/docs/api#capture_charge """ captured_charge = self.api_retrieve().capture() ...
python
def REV(self, params): """ REV Ra, Rb Reverse the byte order in register Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers=(Ra, Rb)) def REV_func(): self...
java
@Override public EClass getIfcStairFlight() { if (ifcStairFlightEClass == null) { ifcStairFlightEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(625); } return ifcStairFlightEClass; }
java
public void setDate( String parameterName, Date value ) throws OdaException { // only applies to named input parameter parameters.put(parameterName, value); }
python
def size_r_img_inches(width, height): """Compute the width and height for an R image for display in IPython Neight width nor height can be null but should be integer pixel values > 0. Returns a tuple of (width, height) that should be used by ggsave in R to produce an appropriately sized jpeg/png/pdf i...
python
def from_triple(cls, triple): """ Create a Target instance for the given triple (a string). """ with ffi.OutputString() as outerr: target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'), outerr) if...
python
def backup(file_name, jail=None, chroot=None, root=None): ''' Export installed packages into yaml+mtree file CLI Example: .. code-block:: bash salt '*' pkg.backup /tmp/pkg jail Backup packages from the specified jail. Note that this will run the command within the jail, a...
python
async def server_stop(app, loop): """Sends a message to the webhook channel when server stops.""" em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
java
public SerializedState deconstruct(CoroutineRunner runner) { if (runner == null) { throw new NullPointerException(); } Coroutine coroutine = runner.getCoroutine(); Continuation cn = runner.getContinuation(); int size = cn.getSize(); VersionedFrame[] frames =...
java
public ServiceCall<CounterexampleCollection> listCounterexamples( ListCounterexamplesOptions listCounterexamplesOptions) { Validator.notNull(listCounterexamplesOptions, "listCounterexamplesOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "counterexamples" }; String[] pathParameters...
java
private String getAndValidateScriptName(JSONObject params) throws ApiException { String scriptName = params.getString(ACTION_PARAM_SCRIPT_NAME); if (extension.getScript(scriptName) == null) { throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME); } return scriptName; }
java
public Block getBlock(String sqlquery, Collection queryParams, int startIndex, int count) { Debug.logVerbose("[JdonFramework]enter getBlock .. ", module); if ((count > this.blockLength) || (count <= 0)) { // every query max // length must be // little than // blockLength count = this.blockLength; ...
python
def move(self, new_location): """Move resource to `new_location`""" self._perform_change(change.MoveResource(self, new_location), 'Moving <%s> to <%s>' % (self.path, new_location))
java
public HttpClientResponseBuilder withStatus(int statusCode) { Action lastAction = newRule.getLastAction(); StatusResponse statusAction = new StatusResponse(lastAction, statusCode); newRule.overrideLastAction(statusAction); return this; }
python
def write_matrix(outputfile, matrix): """ Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write. """ try: stream = open(outputfile, 'w') for row...
java
public EEnum getIfcFanTypeEnum() { if (ifcFanTypeEnumEEnum == null) { ifcFanTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(836); } return ifcFanTypeEnumEEnum; }
python
def full_route(self): '''The full :attr:`route` for this :class:`.Router`. It includes the :attr:`parent` portion of the route if a parent router is available. ''' if self._parent: return self._parent.full_route + self._route else: return self._ro...
java
public ChatMessage createFinalMessage(MessageSentResponse response) { return ChatMessage.builder() .setMessageId(response.getId()) .setSentEventId(response.getEventId()) .setConversationId(conversationId) .setSentBy(sender) .setFrom...
java
private void addWorker() { Throwable ex = null; ForkJoinWorkerThread wt = null; try { if ((wt = factory.newThread(this)) != null) { wt.start(); return; } } catch (Throwable e) { ex = e; } deregisterWorker...
java
public T itemClicked(AdapterView.OnItemClickListener listener) { if (view instanceof AdapterView) { AdapterView<?> alv = (AdapterView<?>) view; alv.setOnItemClickListener(listener); } return self(); }
java
private final void closeRAF() throws LockFile.UnexpectedFileIOException { if (raf != null) { try { raf.close(); } catch (IOException ex) { throw new UnexpectedFileIOException(this, "closeRAF", ex); } finally { raf = null; ...
java
@Override public Map<String, Long> getChildRequestsExecutionsByRequestId() { if (childRequestsExecutionsByRequestId == null) { return Collections.emptyMap(); } // pas de nouvelle instance de map ici pour raison de perf // (la méthode est utilisée sur un seul thread) return childRequestsExecutionsBy...
java
public com.google.api.ads.adwords.axis.v201809.cm.AssetType getAssetSubtype() { return assetSubtype; }
python
def parse_known_args(): """ Parse command line arguments """ parser = argparse.ArgumentParser() parser.add_argument('-V', '--version', action='store_true', dest='version', help='Print the version number and exit') mutually_exclu...
java
public static SelectOptions getViewSelectOptions(CmsObject cms, String value) { Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; List<I_C...
python
def chunked_X(self, chunk_size: Optional[int] = None): """Return an iterator over the rows of the data matrix :attr:`X`. Parameters ---------- chunk_size Row size of a single chunk. """ if chunk_size is None: # Should be some adaptive code ...
java
@Nullable public static StackTraceElement findCallerOf(Class<?> target, Throwable throwable, int skip) { checkNotNull(target, "target"); checkNotNull(throwable, "throwable"); if (skip < 0) { throw new IllegalArgumentException("skip count cannot be negative: " + skip); } // Getting the full s...
java
public Observable<ServiceResponse<UUID>> createPrebuiltEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, CreatePrebuiltEntityRoleOptionalParameter createPrebuiltEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Para...
java
public Sequence compile( String equation , boolean assignment, boolean debug ) { functions.setManagerTemp(managerTemp); Sequence sequence = new Sequence(); TokenList tokens = extractTokens(equation,managerTemp); if( tokens.size() < 3 ) throw new RuntimeException("Too few t...
python
def request_command_status(blink, network, command_id): """ Request command status. :param blink: Blink instance. :param network: Sync module network id. :param command_id: Command id to check. """ url = "{}/network/{}/command/{}".format(blink.urls.base_url, ...
python
def classify_imports(self, chunk): """ Possible import statements: import name from name import subname from name import subname1 as subname2 from name import * from name import tuple AST representations: ImportFrom: module=name names=[alias(name,...
java
private String valueOrBlank(Dataset dataset, int idx) { if (idx < dataset.numPoints()) { return Double.toString(dataset.get(idx)); } else { return ""; } }
java
public ModifyInstanceCreditSpecificationRequest withInstanceCreditSpecifications(InstanceCreditSpecificationRequest... instanceCreditSpecifications) { if (this.instanceCreditSpecifications == null) { setInstanceCreditSpecifications(new com.amazonaws.internal.SdkInternalList<InstanceCreditSpecificati...
python
def _set_pspf_timer(self, v, load=False): """ Setter method for pspf_timer, mapped from YANG variable /isis_state/router_isis_config/pspf_timer (container) If this variable is read-only (config: false) in the source YANG file, then _set_pspf_timer is considered as a private method. Backends looking ...
python
def in_distance(self, distance, fields, points, annotate='_ed_distance'): """Filter rows inside a circunference of radius distance `distance` :param distance: max distance to allow :param fields: `tuple` with the fields to filter (latitude, longitude) :param points: center o...
java
public static DMatrixRMaj identity(int width ) { DMatrixRMaj ret = new DMatrixRMaj(width,width); for( int i = 0; i < width; i++ ) { ret.set(i,i,1.0); } return ret; }
python
def decodetx(tx_hex, coin_symbol='btc', api_key=None): ''' Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON. Does NOT broadcast the transaction to the bitcoin network. Especially useful for testing/debugging and sanity checking ''' assert is_valid_coin_symbol(coin...
python
def find_simpleobject_file_occurrences(self, location) -> Dict[str, str]: """ Implementation of the parent abstract method. :param location: :return: a dictionary{ext : file_path} """ parent_dir = dirname(location) if parent_dir is '': parent_dir = '....
python
def writeList(self, n, is_proxy=False): """ Writes a C{tuple}, C{set} or C{list} to the stream. @type n: One of C{__builtin__.tuple}, C{__builtin__.set} or C{__builtin__.list} @param n: The C{list} data to be encoded to the AMF3 data stream. """ if self.use_p...
python
def padded_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels everywhere (non-0).""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list...
python
def get_forms(self): """ Initializes the forms defined in `form_classes` with initial data from `get_initial()`, kwargs from get_form_kwargs() and form instance object from `get_objects()`. """ forms = {} objects = self.get_objects() initial = self.get_initial() ...
python
def list(self): """List available reports from the server by returning a dictionary with reports classified by data model: .. doctest:: :options: +SKIP >>> odoo.report.list()['account.invoice'] [{'name': u'Duplicates', 'report_name': u'account....
java
public DnsNameAvailabilityResultInner checkDnsNameAvailability(String location, String domainNameLabel) { return checkDnsNameAvailabilityWithServiceResponseAsync(location, domainNameLabel).toBlocking().single().body(); }
java
@Override public Evaluator getAttributeEvaluator(String name, String mode, String value) { return new GroupMembershipEvaluator(mode, name); }
python
def order_target(self) -> Optional[Union[int, Point2]]: """ Returns the target tag (if it is a Unit) or Point2 (if it is a Position) from the first order, returns None if the unit is idle """ if self.orders: if isinstance(self.orders[0].target, int): return self.order...
java
public final AntlrDatatypeRuleToken ruleInnerVarID() throws RecognitionException { AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken(); Token this_ID_0=null; Token kw=null; enterRule(); try { // InternalSARL.g:9921:2: ( (this_ID_0= RULE_ID | kw= 'abstra...
java
@Override public ListCompatibleImagesResult listCompatibleImages(ListCompatibleImagesRequest request) { request = beforeClientExecution(request); return executeListCompatibleImages(request); }
python
def directed_bipartition_of_one(seq): """Generate directed bipartitions where one part is of length 1. Args: seq (Iterable): The sequence to partition. Returns: list[tuple[tuple]]: A list of tuples containing each of the two partitions. Example: >>> partitions = direct...
python
def collect(self, force=False): """ calls collect_impl and stores the results as the child changes of this super-change. Returns a tuple of the data generated from collect_impl. Caches the result rather than re-computing each time, unless force is True """ if for...
python
def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane| """ if sy is None: sy = sx ps = vtk...
java
public ClassInfoList getClassesImplementing(final String interfaceName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGr...
java
public List<Boolean> getBooleanList(final String param) { return getList(param, new StrictStringToBoolean(), new AlwaysValid<Boolean>(), "boolean"); }
python
def doc_to_html(doc, doc_format="ROBOT"): """Convert documentation to HTML""" from robot.libdocpkg.htmlwriter import DocToHtml return DocToHtml(doc_format)(doc)
java
@Override public java.util.concurrent.Future<UnsubscribeResult> unsubscribeAsync(String subscriptionArn, com.amazonaws.handlers.AsyncHandler<UnsubscribeRequest, UnsubscribeResult> asyncHandler) { return unsubscribeAsync(new UnsubscribeRequest().withSubscriptionArn(subscriptionArn), asyncHandler...
python
def delete(cls, app_id): """ Delete an app by issuing a DELETE request to the /apps/ID endpoint. """ conn = Qubole.agent() return conn.delete(cls.element_path(app_id))
java
private void insert(Geometry geom, GeometryIndex index, Coordinate coordinate) throws GeometryIndexNotFoundException { if (index.hasChild() && geom.getGeometries() != null && geom.getGeometries().length > index.getValue()) { insert(geom.getGeometries()[index.getValue()], index.getChild(), coordinate); } else ...
python
def remove_file(filepath): ''' Delete a file ''' try: os.remove(os.path.abspath(os.path.expanduser(filepath))) except OSError as e: if e.errno != errno.ENOENT: raise
java
public IfcReinforcingBarRoleEnum createIfcReinforcingBarRoleEnumFromString(EDataType eDataType, String initialValue) { IfcReinforcingBarRoleEnum result = IfcReinforcingBarRoleEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a va...
java
private int findSpanStart(TextCursor cursor, int limit) { for (int i = cursor.currentOffset; i < limit; i++) { char c = cursor.text.charAt(i); if (c == '*' || c == '_') { // Check prev and next symbols if (isGoodAnchor(cursor.text, i - 1) && isNotSymbol(cu...
java
private static void recordVariable(final TypeVariable var, final List<TypeVariable> found) { // prevent cycles if (!found.contains(var)) { found.add(var); for (Type type : var.getBounds()) { findVariables(type, found); } } }
java
public String addMpNews(MpNews mpNews) { String url = WxEndpoint.get("url.material.mpnews.add"); String json = JsonMapper.nonEmptyMapper().toJson(mpNews); logger.info("add mpnews: {}", json); String response = wxClient.post(url, json); Map<String, Object> result = JsonMap...
python
def drawBernoulli(N,p=0.5,seed=0): ''' Generates arrays of booleans drawn from a simple Bernoulli distribution. The input p can be a float or a list-like of floats; its length T determines the number of entries in the output. The t-th entry of the output is an array of N booleans which are True wit...
python
def _piped_bamprep_region_gatk(data, region, prep_params, out_file, tmp_dir): """Perform semi-piped BAM preparation using Picard/GATK tools. """ broad_runner = broad.runner_from_config(data["config"]) cur_bam, cl = _piped_input_cl(data, region, tmp_dir, out_file, prep_params) if not prep_params["rea...
python
def get_products_metadata_path(year, month, day): """ Get paths to multiple products metadata """ products = {} path = 'products/{0}/{1}/{2}/'.format(year, month, day) for key in bucket.objects.filter(Prefix=path): product_path = key.key.replace(path, '').split('/') name = product_path[...
python
def _ask_which_gist(self, matches): """ Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist """ # ask user which gist t...
java
@Override public List<CPInstance> findAll(int start, int end) { return findAll(start, end, null); }
java
private void removeAsyncListener() throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "removeAsyncListener"); // if the consumer is null, there is nothing to do if (consumer != null) { try { // sto...
java
public void post(Notification event) { for (Map.Entry<Object, List<SubscriberMethod>> entry : listeners.entrySet()) { for (SubscriberMethod method : entry.getValue()) { if (method.eventTypeToInvokeOn.isInstance(event)) { try { method.method...