language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public WorkingWeek intersection(final WorkingWeek ww) { final byte combined = (byte) (this.workingDays & ww.workingDays); return new WorkingWeek(combined); }
java
public void send(Email email) throws EmailException { synchronized (this) { EmailConnection connection = openConnection(); connection.connect(); connection.send(email); connection.close(); } }
python
def pretty_coefs(c): """Prints out the first 2 modes of a ScalarCoeffs object. This is mostly used for instructional purposes. (*ScalarPatternUniform*) Example:: >>> spherepy.pretty_coefs(c) c[n, m] ======= 2: 0j 0j ...
python
def process_catalog(self, limit=None): """ :param limit: :return: """ raw = '/'.join((self.rawdir, self.files['catalog']['file'])) LOG.info("Processing Data from %s", raw) efo_ontology = RDFGraph(False, "EFO") LOG.info("Loading EFO ontology in separate rd...
java
private List<Entity> findAllBatch(List<Object> ids) { String entityTypeId = getEntityType().getId(); Multimap<Boolean, Object> partitionedIds = Multimaps.index( ids, id -> transactionInformation.isEntityDirty(EntityKey.create(entityTypeId, id))); Collection<Object> cleanIds = partitioned...
java
public VocabCache<T> buildMergedVocabulary(@NonNull VocabCache<T> vocabCache, boolean fetchLabels) { if (cache == null) cache = new AbstractCache.Builder<T>().build(); for (int t = 0; t < vocabCache.numWords(); t++) { String label = vocabCache.wordAtIndex(t); if (labe...
python
def load(obj, env=None, silent=True, key=None): """Reads and loads in to "settings" a single key or all keys from redis :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env ...
python
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True): """Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for properties such as ``idle_active`` indicating the player is done with regular playback and just idling around """...
java
public JQMRadio addRadio(String value, String text) { JQMRadio radio = new JQMRadio(value, text); addRadio(radio); return radio; }
python
def factory(data): """Tahoma Event factory.""" if data['name'] is "DeviceStateChangedEvent": return DeviceStateChangedEvent(data) elif data['name'] is "ExecutionStateChangedEvent": return ExecutionStateChangedEvent(data) elif data['name'] is "CommandExecutionState...
python
def save(self, file_path): """Save ddy object as a .ddy file. args: file_path: A string representing the path to write the ddy file to. """ # write all data into the file # write the file data = self.location.ep_style_location_string + '\n\n' for d_da...
java
private static boolean interiorEnvExteriorEnv_(Envelope2D env_a, Envelope2D env_b, double tolerance) { Envelope2D envBInflated = new Envelope2D(); envBInflated.setCoords(env_b); envBInflated.inflate(tolerance, tolerance); Point2D pt = new Point2D(); env_a.queryLowerLeft(pt); if (!envBInflated.contains(p...
python
def update_floatingip(floatingip_id, port=None, profile=None): ''' Updates a floatingIP CLI Example: .. code-block:: bash salt '*' neutron.update_floatingip network-name port-name :param floatingip_id: ID of floatingIP :param port: ID or name of port, to associate floatingip to `None...
python
def get_hdrs_len(self): # type: () -> int """ get_hdrs_len computes the length of the hdrs field To do this computation, the length of the padlen field, reserved, stream_id and the actual padding is subtracted to the string that was provided to the pre_dissect fun of the pkt par...
python
def add_histogram(self, tag, values, global_step=None, bins='default'): """Add histogram data to the event file. Note: This function internally calls `asnumpy()` if `values` is an MXNet NDArray. Since `asnumpy()` is a blocking function call, this function would block the main thread til...
java
public static @Nonnull XQuery parse(@WillClose InputStream in) throws IOException { return parse(new InputSource(in)); }
python
def setSNPFilter(self, chrom, start, stop): """ setSNPFilter(AGenotypeContainer self, std::string chrom, limix::muint_t start, limix::muint_t stop) Parameters ---------- chrom: std::string start: limix::muint_t stop: limix::muint_t """ return _co...
python
def howPlotAsk(goodFormat): '''plots using inquirer prompts Arguments: goodFormat {dict} -- module : [results for module] ''' plotAnswer = askPlot() if "Save" in plotAnswer['plotQ']: exportPlotsPath = pathlib.Path(askSave()) if "Show" in plotAnswer['plotQ']: plot...
python
def add_node(self, binary_descriptor): """Add a node to the sensor_graph using a binary node descriptor. Args: binary_descriptor (bytes): An encoded binary node descriptor. Returns: int: A packed error code. """ try: node_string = parse_bina...
java
public JsonNode wbRemoveClaims(List<String> statementIds, boolean bot, long baserevid, String summary) throws IOException, MediaWikiApiErrorException { Validate.notNull(statementIds, "statementIds parameter cannot be null when deleting statements"); Validate.notEmpty(statementIds, "statement ids to ...
java
private void updateIdleTask(final Task orig, Task mods) { // only allow transition to "starting" state String newState = StringUtil.normalize(mods.getState()); if (newState != null && !newState.equals(Task.IDLE) && !newState.equals(Task.STARTING)) { throw new IllegalArgumentException...
python
def repr2(obj_, **kwargs): """ Attempt to replace repr more configurable pretty version that works the same in both 2 and 3 """ kwargs['nl'] = kwargs.pop('nl', kwargs.pop('newlines', False)) val_str = _make_valstr(**kwargs) return val_str(obj_)
java
public ApiDescriptionBuilder operations(List<Operation> operations) { if (operations != null) { this.operations = operations.stream().sorted(operationOrdering).collect(toList()); } return this; }
python
def _UpdateUserGroups(self, user, groups): """Update group membership for a Linux user. Args: user: string, the name of the Linux user account. groups: list, the group names to add the user as a member. Returns: bool, True if user update succeeded. """ groups = ','.join(groups) ...
java
public static ConfigurationOption factoryConfiguration(String pid) { return new org.ops4j.pax.exam.cm.internal.ConfigurationProvisionOption(pid, new HashMap<String, Object>()).factory(true); }
python
def coerce(cls, key, value): """Ensure that loaded values are PasswordHashes.""" if isinstance(value, PasswordHash): return value return super(PasswordHash, cls).coerce(key, value)
java
public RestoreDBInstanceFromDBSnapshotRequest withVpcSecurityGroupIds(String... vpcSecurityGroupIds) { if (this.vpcSecurityGroupIds == null) { setVpcSecurityGroupIds(new com.amazonaws.internal.SdkInternalList<String>(vpcSecurityGroupIds.length)); } for (String ele : vpcSecurityGroupI...
java
@Override public synchronized Map<String, Collection<OutputRecord>> getAllRecords() { Map<String, Collection<OutputRecord>> out = new TreeMap<String, Collection<OutputRecord>>(); for (String recordName : bufferedData.keySet()) { RecordMap recordMap = bufferedData.get(recordName); synchronized...
python
def _find_closest(self, n0): """returns the node in the tree that is closest to n0, but not in the same observation """ dmin = np.inf nclose = None ds = [] nodes = [] ds.append(np.inf) nodes.append(self) for n in self: if n...
java
public Task revertToSnapshot_Task(HostSystem host, Boolean suppressPowerOn) throws VmConfigFault, TaskInProgress, FileFault, InvalidState, InsufficientResourcesFault, RuntimeFault, RemoteException { return new Task(getServerConnection(), getVimService().revertToSnapshot_Task(getMOR(), host == null...
java
public void setAdMarkers(java.util.Collection<String> adMarkers) { if (adMarkers == null) { this.adMarkers = null; return; } this.adMarkers = new java.util.ArrayList<String>(adMarkers); }
python
def upgrade(): """ This takes a *really* long time. Like, hours. """ config_paths = context.config.get_main_option('fedmsg_config_dir') filenames = fedmsg.config._gather_configs_in(config_paths) config = fedmsg.config.load_config(filenames=filenames) make_processors(**config) engine = op.ge...
python
def sbd_to_steem(self, sbd=0, price=0, account=None): ''' Uses the ticker to get the lowest ask and moves the sbd at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if sbd == 0: sbd = self.sbdbal ...
java
private static void init() { String pkgs = System.getProperty("java.protocol.handler.pkgs"); if (pkgs == null || pkgs.trim().length() == 0) { pkgs = "org.jboss.net.protocol|org.jboss.vfs.protocol"; System.setProperty("java.protocol.handler.pkgs", pkgs); } else if (pkgs.co...
java
protected void onServiceInstanceUnavailable(ServiceInstance instance){ if(instance == null){ return ; } String serviceName = instance.getServiceName(); List<NotificationHandler> handlerList = new ArrayList<NotificationHandler>(); synchronized (notificationHandlers) { ...
java
@Override public boolean getScrollableTracksViewportWidth() { Component parent = getParent(); ComponentUI myui = getUI(); return parent == null || (myui.getPreferredSize(this).width <= parent.getSize().width); }
java
public OvhDetailedRateCodeInformation billingAccount_rsva_serviceName_scheduleRateCode_POST(String billingAccount, String serviceName, String rateCode) throws IOException { String qPath = "/telephony/{billingAccount}/rsva/{serviceName}/scheduleRateCode"; StringBuilder sb = path(qPath, billingAccount, serviceName); ...
java
public void marshall(DescribeLocationNfsRequest describeLocationNfsRequest, ProtocolMarshaller protocolMarshaller) { if (describeLocationNfsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(d...
python
def angle(self, vertices): """ If Text is 2D, get the rotation angle in radians. Parameters ----------- vertices : (n, 2) float Vertices in space referenced by self.points Returns --------- angle : float Rotation angle in radians ...
java
public static <T> Size<T> of(Position.Readable<T> position) { return new Size<>(position); }
python
def toString(self): """ Connection information as a string. """ string = "" if self.toLayer._verbosity > 4: string += "wed: from '" + self.fromLayer.name + "' to '" + self.toLayer.name +"'\n" string += " " for j in range(self.toLaye...
python
def base64_decodefile(instr, outfile): r''' Decode a base64-encoded string and write the result to a file .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file' ''' encoded_f = Strin...
python
def rank(self, n, *args): """{0}""" return self.ppf((np.arange(1, n+1) - 0.5) / n, *args)
java
public Optional<Integer> intArg(final String name) { return arg(name) .flatMap(s -> parse(s, Integer::valueOf)); }
java
public static JoinPoint<Exception> fromTasks(Task<?,?>... tasks) { JoinPoint<Exception> jp = new JoinPoint<>(); for (Task<?,?> task : tasks) jp.addToJoin(task.getOutput()); jp.start(); return jp; }
java
public static boolean containsIgnoreCase(String[] array, String value) { for (String str : array) { if (value == null && str == null) return true; if (value != null && value.equalsIgnoreCase(str)) return true; } return false; }
python
def render_theming_css(): """ Template tag that renders the needed css files for the theming app. """ css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) if not css: css = '/'.join(['admin_tools', 'css', 'theming.css']) return mark_safe( '<link rel="stylesheet" type="text/c...
python
def i18n_system_locale(): """ Return the system locale :return: the system locale (as a string) """ log.debug('i18n_system_locale() called') lc, encoding = locale.getlocale() log.debug('locale.getlocale() = (lc="{lc}", encoding="{encoding}).'.format(lc=lc, encoding=encoding)) if lc is No...
python
def lookup_tlsa(hostname, port, transport="tcp", require_ad=True, **kwargs): """ Query the DNS for TLSA records describing the certificates and/or keys to expect when contacting `hostname` at the given `port` over the given `transport`. `hostname` must be an IDNA-encoded :class:`bytes` object. The ...
java
public void setLabels(List<String> labels) { if (labels.size() != this.labels.size()) { throw new IllegalArgumentException("You need to provide " + this.labels.size() + " labels."); } this.labels = labels; ((ArrayAdapter<String>) getAdapter()).notifyDataSetChanged(); }
java
private void reloadProxiesIfNecessary(String versionsuffix) { ReloadableType proxy = typeRegistry.cglibProxies.get(this.slashedtypename); if (proxy != null) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.log(Level.INFO, "Attempting reload of cglib proxy for type " + this.slas...
python
def from_config(cls, cp, **kwargs): r"""Initializes an instance of this class from the given config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All additional keyword arguments are passed to the class. Any...
java
public Account authenticate(AuthenticationToken authenticationToken) { if (accountCache != null) { Account account = accountCache.getIfPresent(authenticationToken); if (account != null) { return account; } } Account authenticatedAccount = nul...
python
def get(key, default=None): """ Searches os.environ. If a key is found try evaluating its type else; return the string. returns: k->value (type as defined by ast.literal_eval) """ try: # Attempt to evaluate into python literal return ast.literal_eval(os.environ.get(k...
java
public List<Image> getImagesByIds(UUID projectId, GetImagesByIdsOptionalParameter getImagesByIdsOptionalParameter) { return getImagesByIdsWithServiceResponseAsync(projectId, getImagesByIdsOptionalParameter).toBlocking().single().body(); }
python
def getFullname(self): """Person's Fullname """ fn = self.getFirstname() mi = self.getMiddleinitial() md = self.getMiddlename() sn = self.getSurname() fullname = "" if fn or sn: if mi and md: fullname = "%s %s %s %s" % ( ...
java
@GwtIncompatible("incompatible method") public static long getFragmentInMinutes(final Calendar calendar, final int fragment) { return getFragment(calendar, fragment, TimeUnit.MINUTES); }
java
@Override public synchronized void unschedule() { verifyCanUnscheduleState(); if (JobChangeLog.isEnabled()) { JobChangeLog.log("#job ...Unscheduling {}", toString()); } unscheduled = true; cron4jId.ifPresent(id -> { cron4jNow.getCron4jScheduler().desch...
java
@Override public FeatureState getFeatureState(final Feature feature) { final Optional<FeatureState> featureState = findOne(feature.name()); return featureState.orElse(null); }
java
@Override public ValNum apply(Env env, Env.StackHelp stk, AstRoot asts[]) { Frame fr = stk.track(asts[1].exec(env)).getFrame(); if (fr.numCols() != 1 || !fr.anyVec().isCategorical()) throw new IllegalArgumentException("mode only works on a single categorical column"); return new ValNum(mode(fr.anyVe...
python
def _fingerprint_target_specs(self, specs): """Returns a fingerprint of the targets resolved from given target specs.""" assert self._build_graph is not None, ( 'cannot fingerprint specs `{}` without a `BuildGraph`'.format(specs) ) hasher = sha1() for spec in sorted(specs): for target in...
python
def find_node_modules_basedir(self): """ Find all node_modules directories configured to be accessible through this driver instance. This is typically used for adding the direct instance, and does not traverse the parent directories like what Node.js does. Returns a lis...
java
private String getOldToken(Context appContext) { String jsonData = preferenceProvider.get(appContext).getString(String.format(REGISTRAR_PREFERENCE_TEMPLATE, senderId), ""); if (jsonData.isEmpty()) { return ""; } JsonObject jsonedPreferences = new JsonParser().parse(j...
python
def set_color(self, cell, color): """ Set the given color to the provided cell cell A xls cell object color A openpyxl color var """ cell.style = cell.style.copy(font=Font(color=Color(rgb=color)))
java
private void send(JainMgcpResponseEvent event) { cancelLongtranTimer(); // to send response we already should know the address and port // number from which the original request was received if (remoteAddress == null) { throw new IllegalArgumentException("Unknown orinator address"); } // restore the o...
java
public void stop() { if (server == null) { return; } logger.fine("Shutting down STP connection listener"); monitor.remove(server); try { server.close(); } catch (IOException e) { // ignored } finally { server = null; } }
java
public static String encodePath(String path) { if (path != null) { path = encodeUrl(path); path = path.replaceAll("/jcr:", "/_jcr_"); path = path.replaceAll("\\?", "%3F"); path = path.replaceAll("=", "%3D"); path = path.replaceAll(";", "%3B"); ...
java
private ParameterName[] parameterNames(Method method) { ParameterName[] parameterNames; if (method != null) { String[] annotatedNames = annotatedParameterNames(method); String[] paranamerNames = paranamerParameterNames(method); String[] contextNames = contextParameter...
python
def getPhoneInfo(numb): ''' Walk the phone info tree to find the best-match info for the given number. Example: info = getPhoneInfo(17035551212) country = info.get('cc') ''' text = str(numb) info = {} node = phonetree # make decisions down the tree (but only keep inf...
python
def miles(kilometers=0, meters=0, feet=0, nautical=0): """ TODO docs. """ ret = 0. if nautical: kilometers += nautical / nm(1.) if feet: kilometers += feet / ft(1.) if meters: kilometers += meters / 1000. ret += kilometers / 1.609344 return ret
python
def getHourTable(date, pos): """ Returns an HourTable object. """ table = hourTable(date, pos) return HourTable(table, date)
python
def deviation(reference_intervals, estimated_intervals, trim=False): """Compute the median deviations between reference and estimated boundary times. Examples -------- >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab') >>> est_intervals, _ = mir_eval.io.load_labeled_intervals(...
java
public static void checkAccessibility(String resourceName, String adapterName, String embeddedApp, String accessingApp, boolean isEndpoint) throws ResourceException { if (embeddedApp != null) { if (!embeddedApp.equals(accessingApp)) { String ...
java
@Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); List<QueryResult> counters = new ArrayList<QueryResult>(); List<QueryResult> gauges = new ArrayList<QueryResult>(); for (QueryResult result : result...
java
public Shard getShard(String docId) { assertNotEmpty(docId, "docId"); return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards") .path(docId).build(), Shard.class); }
java
public Chat createChat(EntityJid userJID, ChatMessageListener listener) { return createChat(userJID, null, listener); }
python
def post(self, request): '''Create a user and token, given an email. If user exists just provide the token.''' serializer = CreateUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data.get('email') try: u...
java
protected DeclarationMap assingDeclarationsToDOM(Document doc, MediaSpec media, final boolean inherit) { // classify the rules classifyAllSheets(media); // resulting map DeclarationMap declarations = new DeclarationMap(); // if the holder is empty skip evaluation if(rules!=null && !rul...
python
def setup_logger(log_file, level=logging.DEBUG): '''One function call to set up logging with some nice logs about the machine''' cfg = AppBuilder.get_pcfg() logger = cfg['log_module'] # todo make sure structlog is compliant and that logbook is also the correct name??? assert logger in ("logging", "l...
python
def lpush(self, key, *values): """ Insert all the specified values at the head of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each ...
java
public boolean isInside(AxisAlignedBB aabb) { return x >= aabb.minX && x <= aabb.maxX && y >= aabb.minY && y <= aabb.maxY && z >= aabb.minZ && z <= aabb.maxZ; }
python
def fit(self, X, num_epochs=10, updates_epoch=None, stop_param_updates=dict(), batch_size=1, show_progressbar=False, show_epoch=False, refit=True): """ Fit the learner to some data. Parameters ...
java
private static void displayRows(final JFrame frm, final Vector<Map.Entry<String,ColumnType>> cols, final Vector<Vector<Object>> data, final Charset charset, final Formatting fmt, final Callable<Void> end) { final UnaryFunction<Document,Callable<Void>> f = new UnaryFunction<Document,Callable<Void>>(...
python
def set_user_agent_component(self, key, value, sanitize=True): """Add or replace new user-agent component strings. Given strings are formatted along the format agreed upon by Mollie and implementers: - key and values are separated by a forward slash ("/"). - multiple key/values are sepa...
java
public static base_responses add(nitro_service client, snmpuser resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { snmpuser addresources[] = new snmpuser[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new snmpuser(); ...
python
def parse_validated_field(fld, selectable): """ Converts a validated field to sqlalchemy. Field references are looked up in selectable """ aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']] field = find_column(selectable, fld['value']) for operator in fld.get('operators', []): ...
java
@Override @Deprecated public PagedSearchResult similarProductsSearch(UploadSearchParams similarProductsSearchParams) { PagedSearchResult result = searchOperations.similarProductsSearch(similarProductsSearchParams); if(result!=null) { String reqId = result.getReqId(); this...
python
def _value_needs_quotes(val): """Return valid quotes for the given value, or None if unneeded.""" if not val: return None val = "".join(str(node) for node in val.filter_text(recursive=False)) if not any(char.isspace() for char in val): return None if "'" i...
java
public void marshall(AbortMultipartUploadRequest abortMultipartUploadRequest, ProtocolMarshaller protocolMarshaller) { if (abortMultipartUploadRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def update_case(case_obj, existing_case): """Update an existing case This will add paths to VCF files, individuals etc Args: case_obj(models.Case) existing_case(models.Case) Returns: updated_case(models.Case): Updated existing case """ variant_nrs = ['nr_va...
python
def main(_): """Run the sample attack""" # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size...
java
public com.google.privacy.dlp.v2.UnwrappedCryptoKeyOrBuilder getUnwrappedOrBuilder() { if (sourceCase_ == 2) { return (com.google.privacy.dlp.v2.UnwrappedCryptoKey) source_; } return com.google.privacy.dlp.v2.UnwrappedCryptoKey.getDefaultInstance(); }
python
def get(self, uri, query=None, **kwargs): """make a GET request""" return self.fetch('get', uri, query, **kwargs)
python
def community_colors(n): """ Returns a list of visually separable colors according to total communities """ if (n > 0): colors = cl.scales['12']['qual']['Paired'] shuffle(colors) return colors[:n] else: return choice(cl.scales['12']['qual']['Paired'])
python
def offer_random(pool, answer, rationale, student_id, options): """ The random selection algorithm. The same as simple algorithm """ offer_simple(pool, answer, rationale, student_id, options)
java
public void doHttpPost(String url, HttpResponse result, Map<String, Object> headers, String contentType) { httpClient.post(url, result, headers, contentType); }
python
def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the conte...
java
public static void useNioTransport(NettyChannelBuilder builder) { builder.channelType(NioSocketChannel.class); builder .eventLoopGroupPool(SharedResourcePool.forResource(Utils.NIO_WORKER_EVENT_LOOP_GROUP)); }
java
public boolean getBooleanProperty(String key, boolean defaultValue) { final String value = properties.getProperty(key, String.valueOf(defaultValue)); return Boolean.valueOf(value); }
python
def add(self, relation): """ relation is a string list, just like: ['User.id = Group.user', 'User.username = Group.username'] :param relation: :return: """ r = Relation(relation) key = r.relation_key[0] if key not in self.relations: sel...