language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_cou...
python
def init_session(self): """ Defines a session object for passing requests. """ if self.session: self.session.close() self.session = make_session(self.username, self.password, self.bearer_token, ...
python
def _write_source_code(tlobject, kind, builder, type_constructors): """ Writes the source code corresponding to the given TLObject by making use of the ``builder`` `SourceBuilder`. Additional information such as file path depth and the ``Type: [Constructors]`` must be given for proper importing...
java
HorizontalLayout addInfoLayout(String key, Object value, boolean editable) { HorizontalLayout res = new HorizontalLayout(); res.setWidth("100%"); res.setSpacing(true); TextField keyField = new TextField(); keyField.setValue(key); keyField.setEnabled(editable); k...
java
public java.util.List<String> getExecutableUsers() { if (executableUsers == null) { executableUsers = new com.amazonaws.internal.SdkInternalList<String>(); } return executableUsers; }
java
public UnsafeMappedBuffer map(long size, FileChannel.MapMode mode) { return map(position(), size, mode); }
python
def smoothing(self, f, w, sm, smtol, gstol): """ Smooths a surface f by choosing nodal function values and gradients to minimize the linearized curvature of F subject to a bound on the deviation from the data values. This is more appropriate than interpolation when significant er...
java
@SuppressWarnings("unchecked") private Set<String> getFieldsForIndex0(String index) { if(index == null) { return Collections.EMPTY_SET; } if(auditLogIndex != null && auditLogIndex.equalsIgnoreCase(index)) { return Collections.EMPTY_SET; } if(auditLo...
java
public void setValue(Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { setValue(valueFactory.createValue(value)); }
java
public static TraceFactory getTraceFactory(NLS nls) { return (TraceFactory) Utils.getImpl("com.ibm.ws.objectManager.utils.TraceFactoryImpl", new Class[] { NLS.class }, new Object[] { nls }); }
java
public void load() { PluginDefinition definition = getDefinition(); if (!initialized && definition != null) { BaseComponent top; try { initialized = true; top = container.getFirstChild(); if (top == null) { to...
java
@Override public HTableDescriptor[] listTables(String regex) throws IOException { return listTables(Pattern.compile(regex)); }
python
def create_from_url(self, url, params=None): ''' /vi/iso/create_from_url POST - account Create a new ISO image on the current account. The ISO image will be downloaded from a given URL. Download status can be checked with the v1/iso/list call. Link: https://www.vultr.com...
python
def startup(api=None): """Runs the provided function on startup, passing in an instance of the api""" def startup_wrapper(startup_function): apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function) apply_to_api.add_startup_handler(startup_function) return startup_fun...
python
def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs): """Process signals from dependencies. Remove signal is processed in two parts. For details see: :func:`~Dependency.connect` """ if action not in (None, 'post_add', 'pre_remove', '...
java
private Period setTimeUnitInternalValue(TimeUnit unit, int value) { int ord = unit.ordinal; if (counts[ord] != value) { int[] newCounts = new int[counts.length]; for (int i = 0; i < counts.length; ++i) { newCounts[i] = counts[i]; } newCounts[ord] = value; return new Period(...
python
def reconstruct_binary(self, attachments): """Reconstruct a decoded packet using the given list of binary attachments. """ self.data = self._reconstruct_binary_internal(self.data, self.attachments)
java
private ImageView createBlankSpace() { ImageView view = new ImageView(getContext()); TableRow.LayoutParams params = new TableRow.LayoutParams(mSwatchLength, mSwatchLength); params.setMargins(mMarginSize, mMarginSize, mMarginSize, mMarginSize); view.setLayoutParams(params); return...
java
public void setUsernames(java.util.Collection<String> usernames) { if (usernames == null) { this.usernames = null; return; } this.usernames = new java.util.ArrayList<String>(usernames); }
python
def _get_localized_fn(path, root_dir): """ Return absolute `path` relative to `root_dir`. When `path` == ``/home/xex/somefile.txt`` and `root_dir` == ``/home``, returned path will be ``/xex/somefile.txt``. Args: path (str): Absolute path beginning in `root_dir`. root_dir (str): Abs...
java
public static boolean isCompatibleSARLLibraryVersion(String version) { if (version != null) { final Version currentVersion = Version.parseVersion(SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING); final Version paramVersion = Version.parseVersion(version); return currentVersion.getMajor() == paramVersion.get...
python
def _load_playbook_from_file(self, path, vars={}): ''' run top level error checking on playbooks and allow them to include other playbooks. ''' playbook_data = utils.parse_yaml_from_file(path) accumulated_plays = [] play_basedirs = [] if type(playbook_data) != ...
java
public String getHeader(String name) { if (_header != null) { String strVal = _header.getHeader(name); if (strVal != null) return strVal; } if (this.headerTable != null) { int i = 0; for (Object obj : headerTable[0]) { String strVal = (String) obj; ...
python
def list_lzh (archive, compression, cmd, verbosity, interactive): """List a LZH archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
java
public static void sqlcurdate(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { zeroArgumentFunctionCall(buf, "current_date", "curdate", parsedArgs); }
python
def get_first(self, table=None): """Just the first entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
python
def list_instances_json(self, application=None, show_only_destroyed=False): """ Get list of instances in json format converted to list""" # todo: application should not be parameter here. Application should do its own list, just in sake of code reuse q_filter = {'sortBy': 'byCreation', 'descendi...
python
def connect(self, host, port): '''Connect to the provided host, port''' conn = connection.Connection(host, port, reconnection_backoff=self._reconnection_backoff, auth_secret=self._auth_secret, timeout=self._connect_timeout, **self._identify_options) ...
java
@Override public String convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException { return EnvelopeSchemaConverter.class.getName(); }
python
def _find_logs(self, compile_workunit): """Finds all logs under the given workunit.""" for idx, workunit in enumerate(compile_workunit.children): for output_name, outpath in workunit.output_paths().items(): if output_name in ('stdout', 'stderr'): yield idx, workunit.name, output_name, ou...
python
def replace(needle, with_=None, in_=None): """Replace occurrences of string(s) with other string(s) in (a) string(s). Unlike the built in :meth:`str.replace` method, this function provides clean API that clearly distinguishes the "needle" (string to replace), the replacement string, and the target stri...
python
def walkSignalPorts(rootPort: LPort): """ recursively walk ports without any children """ if rootPort.children: for ch in rootPort.children: yield from walkSignalPorts(ch) else: yield rootPort
java
public boolean deleteByIds(Object... idValues) { Table table = _getTable(); if (idValues == null || idValues.length != table.getPrimaryKey().length) throw new IllegalArgumentException("Primary key nubmer must equals id value number and can not be null"); return deleteById(table, idValues); }
python
def rm(pattern): """Recursively remove a file or dir by pattern.""" paths = glob.glob(pattern) for path in paths: if path.startswith('.git/'): continue if os.path.isdir(path): def onerror(fun, path, excinfo): exc = excinfo[1] if exc.err...
python
def assumption_list_string(assumptions, assumption_dict): ''' Takes in a list of short forms of assumptions and an assumption dictionary, and returns a "list" form of the long form of the assumptions. Raises ------ ValueError if one of the assumptions is not in assumption_dict. ''' if isinstance(assump...
java
double sparseProbabilisticAlgorithmCardinality() { final int m = this.m/*for performance*/; // compute the "indicator function" -- sum(2^(-M[j])) where M[j] is the // 'j'th register value double sum = 0; int numberOfZeroes = 0/*"V" in the paper*/; for(int j=0; j<m; j++) ...
python
def get_state(self, caller): """ Get per-program state. """ if caller in self.state: return self.state[caller] else: rv = self.state[caller] = DictObject() return rv
python
def update_aliases(self): """ Get aliases information from room state Returns: boolean: True if the aliases changed, False if not """ changed = False try: response = self.client.api.get_room_state(self.room_id) except MatrixRequestError: ...
java
public static String missingFieldName(ScmPluginException e) { if (isFieldMissing(e)) { return ((ScmUserInfoMissing) e).getFieldName(); } return null; }
java
public com.google.api.ads.admanager.axis.v201811.PlacementTargeting getPlacementSegment() { return placementSegment; }
java
public static MozuUrl getShippingInclusionRulesUrl(String profilecode, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions?responseFields={responseFields}"); formatter.formatUrl("profilecode", profilecode); formatter...
java
@Override public void onActivityStopped(final Activity activity) { if (foregroundActivities.decrementAndGet() < 0) { ApptentiveLog.e("Incorrect number of foreground Activities encountered. Resetting to 0."); foregroundActivities.set(0); } if (checkFgBgRoutine != null) { delayedChecker.removeCallbacks(c...
java
public DataSink<T> printOnTaskManager(String prefix) { return output(new PrintingOutputFormat<T>(prefix, false)); }
java
@Override public EClass getIfcSegmentIndexSelect() { if (ifcSegmentIndexSelectEClass == null) { ifcSegmentIndexSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1156); } return ifcSegmentIndexSelectEClass; }
java
public static String setParameters(String value, final Object[] params) { if (params != null) { for (int i = 0; i < params.length; i++) { value = value.replaceAll("\\{" + i + "\\}", params[i].toString()); } } return value; }
java
private static String decodeFormFields(final String content, final Charset charset) { if (content == null) { return null; } return urlDecode(content, (charset != null) ? charset : Charsets.UTF_8, true); }
python
def _filter_matching_lines(self, city_name, country, matching): """ Returns an iterable whose items are the lists of split tokens of every text line matched against the city ID files according to the provided combination of city_name, country and matching style :param city_name: ...
python
def mostCommonElement(elements: Iterable[T], to_hashable_f: Callable=None): """ Find the most frequent element of a collection. :param elements: An iterable of elements :param to_hashable_f: (optional) if defined will be used to get hashable presentation for non-hashable elements. Otherwise jso...
java
protected List<ENTITY> findColumns(List<Match> matches, String[] columns) { Query query = queryGenerator.getMiniSelectQuery(Arrays.asList(columns), matches); return findBySQL(query.getSql(), query.getParams()); }
python
def instance(self): """Content instance of the wrapped object """ if self._instance is None: logger.debug("SuperModel::instance: *Wakup object*") self._instance = api.get_object(self.brain) return self._instance
java
public static Set<IBond> findMappedBonds(IReaction reaction) { Set<IBond> mapped = new HashSet<>(); // first we collect the occurrance of mapped bonds from reacants then products Set<IntTuple> mappedReactantBonds = new HashSet<>(); Set<IntTuple> mappedProductBonds = new HashSet<>(); ...
python
def alias(ctx, search, backend): """ Searches for the given project and interactively add an alias for it. """ projects = ctx.obj['projects_db'].search(search, active_only=True) projects = sorted(projects, key=lambda project: project.name) if len(projects) == 0: ctx.obj['view'].msg( ...
python
def close_session_log(self): """Close the session_log file (if it is a file that we opened).""" if self.session_log is not None and self._session_log_close: self.session_log.close() self.session_log = None
python
def num_no_signups(self): """How many people have not signed up?""" signup_users_count = User.objects.get_students().count() return signup_users_count - self.num_signups()
java
public static int whichMax(double[] x) { double m = Double.NEGATIVE_INFINITY; int which = 0; for (int i = 0; i < x.length; i++) { if (x[i] > m) { m = x[i]; which = i; } } return which; }
python
def module_refresh(self, force_refresh=False, notify=False): ''' Refresh the functions and returners. ''' log.debug('Refreshing modules. Notify=%s', notify) self.functions, self.returners, _, self.executors = self._load_modules(force_refresh, notify=notify) self.schedule...
python
def authenticate(self): """Send login request and update User instance, login headers, and token expiration""" # Temporarily remove auth from Swimlane session for auth request to avoid recursive loop during login request self._swimlane._session.auth = None resp = self._swimlane.request(...
java
private LinkedHashMap<HypergraphNode<Variable>, Integer> createInitialOrdering(final Formula formula, final Map<Variable, HypergraphNode<Variable>> nodes) { final LinkedHashMap<HypergraphNode<Variable>, Integer> initialOrdering = new LinkedHashMap<>(); final List<Variable> dfsOrder = this.dfsOrdering.getOrder(f...
python
def gone_online(stream): """ Distributes the users online status to everyone he has dialog with """ while True: packet = yield from stream.get() session_id = packet.get('session_key') if session_id: user_owner = get_user_from_session(session_id) i...
java
@Override protected void submitFaxJobImpl(FaxJob faxJob) { //create command String command=this.createSubmitFaxCommand(faxJob); //execute process this.executeProcess(command,FaxActionType.SUBMIT_FAX_JOB); }
java
@Override public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId ) throws TargetException { boolean result = false; try { DockerClient dockerClient = DockerUtils.createDockerClient( parameters.getTargetProperties()); ContainerState state = DockerUtils.getContainerState( machi...
java
public static int copyWsByteBuffer(WsByteBuffer src, WsByteBuffer dst, int amount) { int amountCopied = amount; int dstRemaining = dst.remaining(); int srcRemaining = src.remaining(); if (amountCopied > dstRemaining) amountCopied = dstRemaining; if (amountCopied > srcRemaining) amountC...
java
@Contract(pure = true) public static ByteBuf empty() { assert EMPTY.head == 0; assert EMPTY.tail == 0; return EMPTY; }
java
public AttributedCharacterIterator formatToCharacterIterator(Object arguments) { StringBuffer result = new StringBuffer(); ArrayList iterators = new ArrayList(); if (arguments == null) { throw new NullPointerException( "formatToCharacterIterator must be passed non...
java
public String toBitString() { StringBuffer sb = new StringBuffer(); final int shift = this.bytes.length * 8 - this.bitLength; final byte[] shiftRight = shiftRight(this.bytes, shift); for (final byte b : shiftRight) { String asString = Integer.toBinaryString(b & 0xFF); while (asString.length(...
python
def clean_title(title): """ Clean title -> remove dates, remove duplicated spaces and strip title. Args: title (str): Title. Returns: str: Clean title without dates, duplicated, trailing and leading spaces. """ date_pattern = re.compile(r'\W*' r'\...
python
def currentMode( self ): """ Returns the current mode for this widget. :return <XOrbBrowserWidget.Mode> """ if ( self.uiCardACT.isChecked() ): return XOrbBrowserWidget.Mode.Card elif ( self.uiDetailsACT.isChecked() ): return X...
java
@SafeVarargs public static <T> Iterable<List<T>> cartesianProduct(final Iterable<T>... iterables) { if (iterables.length == 0) { return Collections.singletonList(Collections.emptyList()); } return () -> new AllCombinationsIterator<>(iterables); }
python
def collect(config, pconn): """ All the heavy lifting done here """ # initialize collection target # tar files if config.analyze_file: logger.debug("Client analyzing a compress filesystem.") target = {'type': 'compressed_file', 'name': os.path.splitext( ...
java
@Override public void remove(Class<? extends IBasicEntity> type, String key) throws CachingException { EntityCachingServiceLocator.getEntityCachingService().remove(type, key); }
java
public Set<String> getSkipBuildPhrases() { return new HashSet<String>(Arrays.asList(getTrigger().getSkipBuildPhrase().split("[\\r\\n]+"))); }
python
def main(argv=None): """ Run wake on lan as a CLI application. """ parser = argparse.ArgumentParser( description='Wake one or more computers using the wake on lan' ' protocol.') parser.add_argument( 'macs', metavar='mac address', nargs='+', ...
java
void consume(List<PassFactory> factories) { Loop currentLoop = new Loop(); for (PassFactory factory : factories) { if (factory.isOneTimePass()) { if (currentLoop.isPopulated()) { passes.add(currentLoop); currentLoop = new Loop(); } addOneTimePass(factory); ...
java
public MethodDoc wrap(MethodDoc source) { if (source == null || source instanceof Proxy<?> || !(source instanceof MethodDocImpl)) { return source; } return new MethodDocWrapper((MethodDocImpl) source); }
java
public static final <T,R> Function<T,R> ifNotNullThenElse( final Type<T> targetType, final IFunction<? super T,R> thenFunction, final IFunction<? super T,R> elseFunction) { return ifTrueThenElse(targetType, FnObject.isNotNull(), thenFunction, elseFunction); }
python
def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the...
java
public void addRouter(final Class<?> routeType, Object controller) { Method[] methods = routeType.getDeclaredMethods(); if (BladeKit.isEmpty(methods)) { return; } String nameSpace = null, suffix = null; if (null != routeType.getAnnotation(Path.class)) { ...
java
public static void v(String tag, String msg) { if (sLevel > LEVEL_VERBOSE) { return; } Log.v(tag, msg); }
java
@Override public OutlierResult run(Database database, Relation<O> relation) { StepProgress stepprog = LOG.isVerbose() ? new StepProgress("OnlineLOF", 3) : null; Pair<Pair<KNNQuery<O>, KNNQuery<O>>, Pair<RKNNQuery<O>, RKNNQuery<O>>> queries = getKNNAndRkNNQueries(database, relation, stepprog); KNNQuery<O>...
python
def read_local_manifest(self): """ Read the file manifest, or create a new one if there isn't one already """ manifest = file_or_default(self.get_full_file_path(self.manifest_file), { 'format_version' : 2, 'root' : '/', 'have_revision' : 'root', ...
python
def get_api_key_with_prefix(self, identifier): """ Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): retu...
java
public void replaceChild(int index, N newChild) { checkNotNull(newChild); tryRemoveFromOldParent(newChild); N oldChild = children.set(index, newChild); oldChild.setParent(null); newChild.setParent(master); }
java
public void addResourceClassPath(ClassLoader loader) { String classpath = null; if (loader instanceof DynamicClassLoader) classpath = ((DynamicClassLoader) loader).getResourcePathSpecificFirst(); else classpath = CauchoUtil.getClassPath(); addClassPath(classpath); }
python
def json_encode(obj, serialize): """ Handle encoding complex types. """ if hasattr(obj, 'to_dict'): return obj.to_dict(serialize=serialize) elif isinstance(obj, datetime): return obj.date().isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, Pr...
python
def unite_dict(a, b): """ >>> a = {'name': 'Sylvanas'} >>> b = {'gender': 'Man'} >>> unite_dict(a, b) {'name': 'Sylvanas', 'gender': 'Man'} """ c = {} c.update(a) c.update(b) return c
python
def reset_parcov(self,arg=None): """reset the parcov attribute to None Parameters ---------- arg : str or pyemu.Matrix the value to assign to the parcov attribute. If None, the private __parcov attribute is cleared but not reset """ self.logger.s...
python
def backends(self, back=None): ''' Return the backend list ''' if not back: back = self.opts['fileserver_backend'] else: if not isinstance(back, list): try: back = back.split(',') except AttributeError: ...
java
public boolean startsWith(PushbackReader in, int size) throws IOException { InputReader reader = Input.getInstance(in, size); boolean b = startsWith(reader); reader.release(); return b; }
java
@SuppressWarnings("unchecked") public static <T> Class<T> generate(final Class<T> type, final Class<? extends java.lang.annotation.Annotation> scope, final Class<?> anchor) { Preconditions.checkNotNull(type, "Original type requi...
java
private BigInteger evalUnaryExpression(AstNode exprAst) { // only 'unary-operator cast-expression' production is allowed in #if-context AstNode operator = exprAst.getFirstChild(); AstNode operand = operator.getNextSibling(); AstNodeType operatorType = operator.getFirstChild().getType(); if (operat...
java
@XmlElementDecl(namespace = "http://schema.intuit.com/finance/v3", name = "MasterAccount", substitutionHeadNamespace = "http://schema.intuit.com/finance/v3", substitutionHeadName = "IntuitObject") public JAXBElement<MasterAccount> createMasterAccount(MasterAccount value) { return new JAXBElement<MasterAccou...
java
private void updateCustomComponentBounds() { if (customComponents == null) { return; } if (table == null) { return; } for (int i = 0; i < customComponents.size(); i++) { JComponent component = customCompo...
java
public List<FaceletTaglibFunctionType<WebFacelettaglibraryDescriptor>> getAllFunction() { List<FaceletTaglibFunctionType<WebFacelettaglibraryDescriptor>> list = new ArrayList<FaceletTaglibFunctionType<WebFacelettaglibraryDescriptor>>(); List<Node> nodeList = model.get("function"); for(Node node: no...
java
private void push(char c) throws JSONException { if (m_top >= MAXDEPTH) { throw new JSONException("Nesting too deep."); } m_stack[m_top] = c; m_mode = c; m_top += 1; }
python
def pause_trial(self, trial): """Pauses the trial. We want to release resources (specifically GPUs) when pausing an experiment. This results in PAUSED state that similar to TERMINATED. """ assert trial.status == Trial.RUNNING, trial.status try: self.save(tria...
java
@Nullable @ObjectiveCName("loadDraftWithPeer:") public String loadDraft(Peer peer) { return modules.getMessagesModule().loadDraft(peer); }
python
def convert_trunc(trunc): """Convert BEL1 trunc() to BEL2 var()""" parent_fn_name = trunc.parent_function.name_short prefix_list = {"p": "p.", "r": "r.", "g": "c."} prefix = prefix_list[parent_fn_name] new_var_arg = f'"truncated at {trunc.args[0].value}"' new_var = bel.lang.ast.Function("var"...
java
private static InputStream getFileAsInputStream(String file) throws InitializationException { if (file == null) { throw new NullPointerException("File is null"); } try { return new FileInputStream(new File(file)); } catch (FileNotFoundException e) { throw new InitializationException("File not found: " ...
java
public void prepareCommit() { if (m_baseCollection instanceof List) { List<?> list = (List<?>)m_baseCollection; list.clear(); } else if (m_baseCollection instanceof SortedMap) { SortedMap<?, ?> map = (SortedMap<?, ?>)m_baseCollection; map.clear(); ...
java
protected AWSCredentials sanitizeCredentials(AWSCredentials credentials) { String accessKeyId = null; String secretKey = null; String token = null; synchronized (credentials) { accessKeyId = credentials.getAWSAccessKeyId(); secretKey = credentials.getAWSSecret...