language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def copy_files_to_folder(src, dest, xtn='*.txt'): """ copies all the files from src to dest folder """ try: all_files = glob.glob(os.path.join(src,xtn)) for f in all_files: copy_file(f, dest) except Exception as ex: print('ERROR copy_files_to_folder - ' + str(ex))
python
def addOntology(self): """ Adds a new Ontology to this repo. """ self._openRepo() name = self._args.name filePath = self._getFilePath(self._args.filePath, self._args.relativePath) if name is None: name = getNameFrom...
python
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
java
public static @CheckForNull String resolveOrNull(User u, String avatarSize) { Matcher matcher = iconSizeRegex.matcher(avatarSize); if (matcher.matches() && matcher.groupCount() == 2) { int width = Integer.parseInt(matcher.group(1)); int height = Integer.parseInt(matcher.group(2))...
python
def _safe_exit(start, output): """ exit without breaking pipes """ try: sys.stdout.write(output) sys.stdout.flush() except TypeError: # python3 sys.stdout.write(str(output, 'utf-8')) sys.stdout.flush() except IOError: pass seconds = time.time() - sta...
python
def fourier_segments(self): """ Return a list of the FFT'd segments. Return the list of FrequencySeries. Additional properties are added that describe the strain segment. The property 'analyze' is a slice corresponding to the portion of the time domain equivelant of the segment t...
python
def __rename_directory(self, source, target): """ Renames a directory using given source and target names. :param source: Source file. :type source: unicode :param target: Target file. :type target: unicode """ for node in itertools.chain(self.__script_e...
python
def _get_vm_info(self): """ Returns this VM info. :returns: dict of info """ vm_info = {} results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"]) for info in results: try: name, value = info.split(...
python
def volume_shell(f_dist, m_dist): """ Compute the sensitive volume using sum over spherical shells. Parameters ----------- f_dist: numpy.ndarray The distances of found injections m_dist: numpy.ndarray The distances of missed injections Returns -------- volume: float ...
java
public void bootstrap() throws ConfigurationException { XMLConfigurator configurator = new XMLConfigurator(); for (String config : configs) { log.debug("Loading XMLTooling configuration " + config); configurator.load(Configuration.class.getResourceAsStream(config)); } }
java
public Expression<Double> gte(double value) { String valueString = "'" + value + "'"; return new Expression<Double>(this, Operation.gte, valueString); }
python
def create_supervised_tbptt_trainer( model, optimizer, loss_fn, tbtt_step, dim=0, device=None, non_blocking=False, prepare_batch=_prepare_batch ): """Create a trainer for truncated backprop through time supervised models. Training recurrent model on long sequences is computation...
java
public UniformDistribution estimate(DoubleMinMax mm) { return new UniformDistribution(Math.max(mm.getMin(), -Double.MAX_VALUE), Math.min(mm.getMax(), Double.MAX_VALUE)); }
python
def labels(self): """All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels """ all_labels = set(self.token_patterns.keys()) all_labels.update(self.phrase_patterns.keys()) return tuple(all_labels...
python
def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return ...
python
def unregister(self, signal): """ Unregisters an existing signal :param signal: Name of the signal """ if signal in self.signals.keys(): del(self.signals[signal]) self.__log.debug("Signal %s unregisterd" % signal) else: self.__log.debu...
java
public void marshall(TerminateJobFlowsRequest terminateJobFlowsRequest, ProtocolMarshaller protocolMarshaller) { if (terminateJobFlowsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(termina...
python
def read_credentials(self, credentials): """ Reads credentials from configuration parameters. Each section represents an individual CredentialParams :param credentials: configuration parameters to be read """ self._items.clear() for key in credentials.get_key_nam...
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ for i in range( int(self.resolve_option("min")), int(self.resolve_option("max")) + 1, int(sel...
java
public Set<String> getGroupIds( String parentGroupId ) { File parentDir = StringUtils.isEmpty( parentGroupId ) ? root : new File( root, parentGroupId.replace( '.', '/' ) ); if ( !parentDir.isDirectory() ) { return Collections.emptySet(); } File[] group...
java
public YUVFrameGrabber getYUVFrameGrabber(int w, int h, int input, int std, ImageFormat imf) throws V4L4JException{ if(!supportYUV420 || deviceInfo==null) throw new ImageFormatException("This video device does not support " +"YUV-encoding of its frames."); if(imf!=null){ if(!deviceInfo.getFormat...
python
def report(usaf): """generate report for usaf base""" fig = plt.figure() ax = fig.add_subplot(111) station_info = geo.station_info(usaf) y = {} for i in range(1991, 2011): monthData = monthly(usaf, i) t = sum(monthData) y[i] = t print t tmy3tot = tmy3.total(us...
java
@Override public <E> E get(Class<E> clazz, Object key) throws ConcurrentModificationException { if (clazz == null) { throw new IllegalArgumentException("'clazz' must not be [" + clazz + "]"); } if (key == null) { throw new IllegalArgumentException("'id' must not be [" + key + "]"); } if (!isTrans...
python
def do_transition_for(brain_or_object, transition): """Performs a workflow transition for the passed in object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The object where the transtion was performed ...
java
public static <T> Predicates<T> attributeIn( Function<? super T, ?> function, Iterable<?> iterable) { return new AttributePredicate<T, Object>(function, Predicates.in(iterable)); }
python
def inspect(self, image=None, json=True, app=None, quiet=True): '''inspect will show labels, defile, runscript, and tests for an image Parameters ========== image: path of image to inspect json: print json instead of raw text (default True) quiet: Don't print result to the sc...
java
protected void showCustomSlideStep(final Node node) { addSubSlide(node); final Node nextSlide = this.subSlides.get(model().getStepPosition()); if (this.currentSubSlide == null || nextSlide == null) { // No Animation this.currentSubSlide = nextSlide; } else { ...
python
def _allocate_output(self, windows, shape): """ Override the default array allocation to produce a LabelArray when we have a string-like dtype. """ if self.dtype == int64_dtype: return super(CustomClassifier, self)._allocate_output( windows, ...
python
def plat_specific_errors(*errnames): """Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names. """...
java
@SuppressWarnings("unchecked") protected boolean bindingLogin(String username, Object password) throws LoginException, NamingException { final String cacheToken = Credential.MD5.digest(username + ":" + password.toString()); if (_cacheDuration > 0) { // only worry about caching if there i...
java
public void doAfterDeserialization() { if ( listeners == null ) { listeners = new ArrayList<SessionListener>(); } if ( notes == null ) { notes = new ConcurrentHashMap<String, Object>(); } }
python
def set_result(self, result): ''' Set the result to Future object, wake up all the waiters :param result: result to set ''' if hasattr(self, '_result'): raise ValueError('Cannot set the result twice') self._result = result self._scheduler.emer...
python
def float_input(message, low, high): ''' Ask a user for a float input between two values args: message (str): Prompt for user low (float): Low value, user entered value must be > this value to be accepted high (float): High value, user entered value must be < this value to be accept...
java
public void addMessage(String message) { ActionMessages messages = (ActionMessages) next.get(Flash.MESSAGES); if (null == messages) { messages = new ActionMessages(); put(Flash.MESSAGES, messages); } messages.getMessages().add(message); }
python
def get_conditional_probs(self, source=None): """Returns the full conditional probabilities table as a numpy array, where row i*(k+1) + ly is the conditional probabilities of source i emmiting label ly (including abstains 0), conditioned on different values of Y, i.e.: c_pro...
python
def _check_team_exists(team): """ Check that the team registry actually exists. """ if team is None: return hostname = urlparse(get_registry_url(team)).hostname try: socket.gethostbyname(hostname) except IOError: try: # Do we have internet? so...
java
protected String getFormattedNodeXml(final Node nodeToConvert, boolean formatXml) { String formattedNodeXml; try { final int numberOfBlanksToIndent = formatXml ? 2 : -1; final Transformer transformer = createXmlTransformer(numberOfBlanksToIndent); final StringWriter b...
java
public static void init(Context contextValue, ExecutorService service) { context = contextValue; if (service == null) { executerService = Executors.newFixedThreadPool(THREAD_POOL_SIZE_DEFAULT); } else { executerService = service; } }
java
protected int[] parseTime(CharSequenceScanner scanner) { int hour = read2Digits(scanner); boolean colon = scanner.expect(':'); int minute = read2Digits(scanner); int second = 0; if (minute == -1) { if (!colon) { minute = 0; } } else { colon = scanner.expect(':'); ...
python
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
python
def can_approve(self, user, **data): """ Only org admins can approve joining an organisation :param user: a User :param data: data that the user wants to update """ is_org_admin = user.is_org_admin(self.organisation_id) is_reseller_preverifying = user.is_reseller...
java
@Pure public static boolean intersectsCoplanarTriangleTriangle( double v1x, double v1y, double v1z, double v2x, double v2y, double v2z, double v3x, double v3y, double v3z, double u1x, double u1y, double u1z, double u2x, double u2y, double u2z, double u3x, double u3y, double u3z) { int i0, i1; ...
python
def _threads(self, handlers): """ Calculates maximum number of threads that will be started """ if self.threads < len(handlers): return self.threads return len(handlers)
java
public void encrypt(ByteBuffer src) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } if (!src.hasRemaining()) { if (outNetBuffer == null) { outNetBuffer = emptyBuffer; } return; } ...
python
def update(self, content): """Enumerates the bytes of the supplied bytearray and updates the CRC-64. No return value. """ for byte in content: self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte]
java
public static boolean isJSNode (@Nullable final IHCNode aNode) { final IHCNode aUnwrappedNode = HCHelper.getUnwrappedNode (aNode); return isDirectJSNode (aUnwrappedNode); }
java
public void registerDefinedSchema(DataSchema schema) { final ClassTemplateSpec spec = createFromDataSchema(schema); _schemaToClassMap.put(schema, spec); _classNameToSchemaMap.put(spec.getFullName(), schema); }
java
private Map<TemplateType, JSType> evaluateTypeTransformations( ImmutableList<TemplateType> templateTypes, Map<TemplateType, JSType> inferredTypes, FlowScope scope) { Map<String, JSType> typeVars = null; Map<TemplateType, JSType> result = null; TypeTransformation ttlObj = null; for (T...
java
protected void synchronizeFieldCaption(QueryPage queryPage, String fieldName, String fieldCaption) { QueryFieldDAO queryFieldDAO = new QueryFieldDAO(); QueryOptionField queryField = (QueryOptionField) queryFieldDAO.findByQueryPageAndName(queryPage, fieldName); if (queryField != null) queryFieldDAO.up...
java
private String getSign(String body) { String signNodeName = "<" + AlipayConstants.SIGN + ">"; String signEndNodeName = "</" + AlipayConstants.SIGN + ">"; int indexOfSignNode = body.indexOf(signNodeName); int indexOfSignEndNode = body.indexOf(signEndNodeName); if (indexOfSignNo...
java
public double getCount(F first, S second) { Counter<S> counter = maps.get(first); if (counter == null) return 0.0; return counter.getCount(second); }
python
def stop(self, *args): """ Stops the TendrilManager. Requires cooperation from the listener implementation, which must watch the ``running`` attribute and ensure that it stops accepting connections should that attribute become False. Note that some tendril managers will...
java
public boolean handleOption(Option option, String value) { switch (option) { case ENCODING: encodingName = value; return true; case MULTIRELEASE: multiReleaseValue = value; locations.setMultiReleaseValue(value); ...
python
def photo(self): """ Returns either the :tl:`WebDocument` thumbnail for normal results or the :tl:`Photo` for media results. """ if isinstance(self.result, types.BotInlineResult): return self.result.thumb elif isinstance(self.result, types.BotInlineMediaResult...
python
def _synchronize_node(configfile, node): """Performs the Synchronize step of a Chef run: Uploads all cookbooks, all roles and all databags to a node and add the patch for data bags Returns the node object of the node which is about to be configured, or None if this node object cannot be found. ...
java
@Override public String modifyDatastreamByValue(String pid, String dsID, org.fcrepo.server.types.gen.ArrayOfString altIDs, String dsLabel, String mi...
java
private static void verifyType(final WireFormat.FieldType type, final Object value) { if (value == null) { throw new NullPointerException(); } boolean isValid = false; switch (type.getJavaType()) { case INT: isValid = value instanceof Integer ; br...
java
public DecoratedKey partitionKey(Document document) { String string = document.get(FIELD_NAME); ByteBuffer partitionKey = ByteBufferUtils.fromString(string); return partitionKey(partitionKey); }
java
public CertificateBundle updateCertificate(UpdateCertificateRequest updateCertificateRequest) { return updateCertificate(updateCertificateRequest.vaultBaseUrl(), updateCertificateRequest.certificateName(), updateCertificateRequest.certificateVersion(), updateCertificateRequest.certificatePolicy(...
python
def ge(self, event_property, value): """A greater-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.ge('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).ge(elapsed_ms, 500) """ c = self...
java
public ISREInstall getSelectedSRE() { if (this.enableSystemWideSelector && this.systemSREButton.getSelection()) { return SARLRuntime.getDefaultSREInstall(); } if (!this.projectProviderFactories.isEmpty() && this.projectSREButton.getSelection()) { return retreiveProjectSRE(); } return getSpecificSRE(); ...
java
public boolean isSupportedLanguage(String language) { String lang = getLanguageComponent(language); return languageLookup.containsKey(lang); }
java
protected void remoteInit() throws JMSException { CreateBrowserQuery query = new CreateBrowserQuery(); query.setBrowserId(id); query.setSessionId(session.getId()); query.setQueue(queue); query.setMessageSelector(messageSelector); transportEndpoint.blockingRequest(quer...
java
public void propertyChange(PropertyChangeEvent evt) { String strProperty = evt.getPropertyName(); if (this.isValidProperty(strProperty)) { Object objCurrentValue = this.get(strProperty); if (evt.getNewValue() != objCurrentValue) { m_strCurr...
java
private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) { try { Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { public Void run() throws IOException { doHandle(pHttpExchange); return null; } }); ...
python
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._grade_system_default = self._mdata['grade_system']['default_id_values'][0]
java
protected HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Workaround for HttpURLConnection not observing the // HttpURLConnection.setFollowRedirects() property. // Happening in Android M release...
python
def get_deployment_targets(self, project, deployment_group_id, tags=None, name=None, partial_name_match=None, expand=None, agent_status=None, agent_job_result=None, continuation_token=None, top=None, enabled=None, property_filters=None): """GetDeploymentTargets. [Preview API] Get a list of deployment ta...
java
@Override public Message<?> preSend(Message<?> message, MessageChannel channel) { if (emptyMessage(message)) { return message; } Message<?> retrievedMessage = getMessage(message); MessageHeaderAccessor headers = mutableHeaderAccessor(retrievedMessage); TraceContextOrSamplingFlags extracted = this.extracto...
java
public static String message(String key, Locale locale, Object... params) { String pattern; try { pattern = ResourceBundle.getBundle(BUNDLE, locale == null ? Locale.getDefault() : locale).getString(key); } catch (MissingResourceException e) { pattern = key; } ...
java
private static void waiting(int milliseconds) { long t0, t1; t0 = System.currentTimeMillis(); do { t1 = System.currentTimeMillis(); } while ((t1 - t0) < milliseconds); }
python
def followers(self): """获取关注此问题的用户 :return: 关注此问题的用户 :rtype: Author.Iterable :问题: 要注意若执行过程中另外有人关注,可能造成重复获取到某些用户 """ self._make_soup() followers_url = self.url + 'followers' for x in common_follower(followers_url, self.xsrf, self._session): yie...
python
def absent(name, purge=False, force=False): ''' Ensure that the named user is absent name The name of the user to remove purge Set purge to True to delete all of the user's files as well as the user, Default is ``False``. force If the user is logged in, the absent ...
java
public Object get(int row, @NotNull String column) { return rows.get(row).get(column); }
java
public Release getReleaseInfo(String appName, String releaseName) { return connection.execute(new ReleaseInfo(appName, releaseName), apiKey); }
java
public Observable<Page<DetectorDefinitionInner>> listSiteDetectorsSlotAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory, final String slot) { return listSiteDetectorsSlotWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory, slot) .map(ne...
python
def nagios(self, stream=sys.stdout): """ return 0 (OK) if there are no errors in the state. return 1 (WARNING) if a backfill app only has 1 error. return 2 (CRITICAL) if a backfill app has > 1 error. return 2 (CRITICAL) if a non-backfill app has 1 error. """ warni...
java
public void parseArgument(Collection<String> args) throws CmdLineException { parseArgument(args.toArray(new String[args.size()])); }
java
void computePointsAndWeights(EllipseRotated_F64 ellipse) { // use the semi-major axis to scale the input points for numerical stability double localScale = ellipse.a; samplePts.reset(); weights.reset(); int numSamples = radialSamples * 2 + 2; int numPts = numSamples - 1; Point2D_F64 sample = new Point2...
java
public static long copy(File file, OutputStream outputStream) throws IOException { Params.notNull(file, "Input file"); return copy(new FileInputStream(file), outputStream); }
python
def _preloading_env(self): """ A "stripped" jinja environment. """ ctx = self.env.globals try: ctx['random_model'] = lambda *a, **kw: None ctx['random_models'] = lambda *a, **kw: None yield self.env finally: ctx['random_mode...
java
public void setValue(String newValue, @Nullable String newName) { if (isChecked()) { searcher.updateFacetRefinement(this.attribute, value, false) .updateFacetRefinement(newName != null ? newName : attribute, newValue, true) .search(); } this.va...
java
public alluxio.grpc.ScheduleAsyncPersistencePOptions getOptions() { return options_ == null ? alluxio.grpc.ScheduleAsyncPersistencePOptions.getDefaultInstance() : options_; }
java
@Override public void configure(Configuration parameters) { // enforce sequential configuration() calls synchronized (CONFIGURE_MUTEX) { if (mapreduceInputFormat instanceof Configurable) { ((Configurable) mapreduceInputFormat).setConf(configuration); } } }
python
def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False): """Get a dictionary of this object's attributes. Optional format for storage in a Pandas DataFrame. Args: only_attributes (str, list): Attributes that should be returned. If not provided, all are returned. ...
python
def highest_precedence_dtype(exprs): """Return the highest precedence type from the passed expressions Also verifies that there are valid implicit casts between any of the types and the selected highest precedence type. This is a thin wrapper around datatypes highest precedence check. Parameters ...
java
private MetricImpl getCommittedMetric(MetricImpl.MetricType metricType) { return (MetricImpl)committedMetrics.get(metricType.name()); }
python
def network(prefix, default_length=24): """ Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP ne...
python
def decompose_nfkd(text): """Perform unicode compatibility decomposition. This will replace some non-standard value representations in unicode and normalise them, while also separating characters and their diacritics into two separate codepoints. """ if text is None: return None if ...
java
public static br_restart[] restart(nitro_service client, br_restart[] resources) throws Exception { if(resources == null) throw new Exception("Null resource array"); if(resources.length == 1) return ((br_restart[]) resources[0].perform_operation(client, "restart")); return ((br_restart[])...
java
private IssueSeverity determineLevel(String path) { if (isGrandfathered(path)) return IssueSeverity.WARNING; else return IssueSeverity.ERROR; }
java
private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TableFilterDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. TableFilterDemo newContentPane = new TableFilterDemo(); newC...
java
public static void bindScheduled(Binder binder, Reflections reflections) { Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Scheduled.class, true); Set<Method> methods = reflections.getMethodsAnnotatedWith(Scheduled.class); Set<SchedulerTask> tasks = new HashSet<SchedulerTask>(); for(Class<?> c...
python
def client(self): """ :rtype: keycloak.client.KeycloakClient """ if self._client is None: self._client = KeycloakClient(server_url=self._server_url, headers=self._headers) return self._client
java
private ElasticSearchSetup.Connection legacyConfiguration(Configuration config) { Node node; Client client; if (config.get(LOCAL_MODE)) { log.debug("Configuring ES for JVM local transport"); boolean clientOnly = config.get(CLIENT_ONLY); boolean local = conf...
java
public void write(final ComponentDocumentationWrapper componentWrapper, final OutputStream outputStream) throws IOException { final Map<String, Object> data = new HashMap<>(); try { data.put("breadcrumbs", _breadcrumbs); data.put("component", componentWrapper); ...
python
def shapeexprlabel_to_IRI(self, shapeExprLabel: ShExDocParser.ShapeExprLabelContext) \ -> Union[ShExJ.BNODE, ShExJ.IRIREF]: """ shapeExprLabel: iri | blankNode """ if shapeExprLabel.iri(): return self.iri_to_iriref(shapeExprLabel.iri()) else: return ShExJ.BNOD...
python
def clear_trace_filter_cache(): ''' Clear the trace filter cache. Call this after reloading. ''' global should_trace_hook try: # Need to temporarily disable a hook because otherwise # _filename_to_ignored_lines.clear() will never complete. old_hook = should_trace_hook ...
java
public java.util.List<? extends com.google.javascript.jscomp.FunctionInformationMap.EntryOrBuilder> getEntryOrBuilderList() { return entry_; }
java
public Vector2d mul(double scalar, Vector2d dest) { dest.x = x * scalar; dest.y = y * scalar; return dest; }