language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Scale get(final int index, final DistanceUnit unit) { return new Scale(this.scaleDenominators[index], unit, PDF_DPI); }
java
private Map<String, Object> parseRequestParameters(String requestParameters) { Map<String, Object> parameterMap; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(requestParameters)) { parameterMap = new HashMap<String, Object>(); String[] params = requestParameters.split("&"); ...
python
def clean_cache_upstream(self): """Clean cache for all steps that are upstream to `self`. """ logger.info('Cleaning cache for the entire upstream pipeline') for step in self.all_upstream_steps.values(): logger.info('Step {}, cleaning cache'.format(step.name)) step...
python
def react(self, emojiname): """ React to a message using the web api """ self._client.react_to_message( emojiname=emojiname, channel=self._body['channel'], timestamp=self._body['ts'])
python
def subscribe_account(self, username, password, service): """Subscribe an account for a service. """ data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, ...
python
def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None): """ :param attributes_a: A dict of functions to their attributes :param attributes_b: A dict of functions to their attributes The following parameters are optional. :param filter_...
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<BatchPredictResult, OperationMetadata> batchPredictAsync( ModelName name, BatchPredictInputConfig inputConfig, BatchPredictOutputConfig outputConfig, Map<Stri...
python
def upsert(db, table, key_cols, update_dict): """Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: database :param str table: table to upsert into :param str key_cols: name of key columns :param dict update_dict: key-value pairs to upsert """ with...
python
def from_api_repr(cls, resource, client): """Factory: construct a job given its API representation .. note: This method assumes that the project found in the resource matches the client's project. :type resource: dict :param resource: dataset job representation ...
java
@Override public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { ProxyIoSession proxyIoSession = (ProxyIoSession) session .getAttribute(ProxyIoSession.PROXY_SESSION); proxyIoSession.getEventQueue().enqueueEventIfNecessary( ...
java
public static Object instantiateObject(String className, ClassLoader classLoader, Object...args) { Constructor c = (Constructor) constructors.get( className ); if ( c == null ) { c = loadClass(className, classLoader).getConstructors()[0]; ...
python
def get_value_from_environment( section_name, key_name, envname_pad=ENVNAME_PAD, logger=logging.getLogger('ProsperCommon'), ): """check environment for key/value pair Args: section_name (str): section name key_name (str): key to look up envname_pad (str):...
python
def add_peer_parser(subparsers, parent_parser): """Adds argument parser for the peer command Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add_parser( 'peer', help='Disp...
java
public static MultiValueMap asMultiValueMap(final Map innerMap) { return org.springframework.util.CollectionUtils.toMultiValueMap(innerMap); }
python
def coPrime(l): """returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'. """ for i, j in combinations(l, 2): if euclid(i, j) != 1: return False return True
java
private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation, ModelNode host) { final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR)); if (realAddress.size() == 0 &&...
java
@Requires({ "name != null", "!name.isEmpty()", "kind != null" }) public static URI getUriForClass(String name, Kind kind) { try { return new URI("com.google.java.contract://com.google.java.contract/" + name + kind.extension); } catch (URISyntaxException e) { throw new IllegalArgument...
java
public static AuditEntryBean planCreated(PlanBean bean, ISecurityContext securityContext) { AuditEntryBean entry = newEntry(bean.getOrganization().getId(), AuditEntityType.Plan, securityContext); entry.setEntityId(bean.getId()); entry.setEntityVersion(null); entry.setData(null); ...
python
def nvmlDeviceGetSerial(handle): r""" /** * Retrieves the globally unique board serial number associated with this device's board. * * For all products with an inforom. * * The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator). ...
java
private void fireNotAuthenticatedEvent(String userName) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "fireNotAuthenticatedEvent", userName); // Check that we have a RuntimeEventListener if (_runtimeEventListener != null) { ...
python
def btc_get_privkey_address(privkey_info, **blockchain_opts): """ Get the address for a given private key info bundle (be it multisig or singlesig) Return the address on success Raise exception on error """ from .multisig import make_multisig_segwit_address_from_witness_script if ...
java
protected boolean getBoolean(String key, boolean defaultValue) { try { return getConfig().getBoolean(key, defaultValue); } catch (ConversionException e) { logConversionException(key, e); } return defaultValue; }
python
def load_model_by_id(self, model_id): """Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : Graph the model graph representation """ with open(os.path.join(self...
python
def RIBVRFRouteLimitExceeded_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") o...
python
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): """ Compute the standard deviation along given axis while ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True ddof : int, default 1 Delta Degrees of Freedom. The divis...
python
def is_valid(arxiv_id): """ Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690...
java
public Set<MailAccount> getReservedMailAccountsForCurrentThread() { lock.lock(); try { Map<MailAccount, ThreadReservationKeyWrapper> accountsForThread = filterValues(usedAccounts, new CurrentThreadWrapperPredicate()); return ImmutableSet.copyOf(accountsForThread.keySet()); } finally { lock.unlock(); } ...
java
@Override public void setEnabled(boolean enabled) { if (this.enabled != enabled) { this.enabled = enabled; setProperty("enabled", Boolean.toString(enabled)); if (enabled && getAlertThreshold() == AlertThreshold.OFF) { setAlertThreshold(AlertThreshold...
python
def create_custom_views(name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionarie...
python
def vcf_writer(parser, keep, extract, args): """Writes the data in VCF format.""" # The output output = sys.stdout if args.output == "-" else open(args.output, "w") try: # Getting the samples samples = np.array(parser.get_samples(), dtype=str) k = _get_sample_select(samples=samp...
python
def _try_validate(cnf, schema, **options): """ :param cnf: Mapping object represents configuration data :param schema: JSON schema object :param options: Keyword options passed to :func:`jsonschema.validate` :return: Given 'cnf' as it is if validation succeeds else None """ valid = True ...
python
def pymmh3_hash128(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> int: """ Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: ...
java
private ReportEntry9 createLine(UmsLine line) throws Exception { ReportEntry9 entry = new ReportEntry9(); EntryDetails8 detail = new EntryDetails8(); entry.getNtryDtls().add(detail); EntryTransaction9 tx = new EntryTransaction9(); detail.getTxDtls().add(tx); // Checken...
java
private synchronized void init() { if (!initialized.compareAndSet(false, true)) { return; } LOG.debug("GStreamer webcam device initialization"); pipe = new Pipeline(getName()); source = ElementFactory.make(GStreamerDriver.getSourceBySystem(), "source"); if (Platform.isWindows()) { sour...
python
def is_between(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support compari...
python
async def sunionstore(self, dest, keys, *args): """ Store the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Cluster impl: Use sunion() --> Dlete dest key --> store result in dest key Operation is n...
java
public static boolean tryToClose(Closeable closeable) { Object token = ThreadIdentityManager.runAsServer(); try { if (closeable != null) { try { closeable.close(); return true; } catch (IOException e) { ...
java
public final B accessToken(String accessToken) { requireNonNull(accessToken, "accessToken"); checkArgument(!accessToken.isEmpty(), "accessToken is empty."); this.accessToken = accessToken; return self(); }
python
def release_downloads(request, package_name, version): """ Retrieve a list of files and download count for a given package and release version. """ session = DBSession() release_files = ReleaseFile.by_release(session, package_name, version) if release_files: release_files = [(f.relea...
java
private void updateFontButton(@Nonnull final MindMapPanelConfig config) { final String strStyle; final Font thefont = config.getFont(); if (thefont.isBold()) { strStyle = thefont.isItalic() ? "bolditalic" : "bold"; } else { strStyle = thefont.isItalic() ? "italic" : "plain"; } thi...
java
@Override public ListenersModel addListener(ListenerModel listener) { addChildModel(listener); _listeners.add(listener); return this; }
python
def coerce(self, value): """ Coerces value to location hash. """ return { 'lat': float(value.get('lat', value.get('latitude'))), 'lon': float(value.get('lon', value.get('longitude'))) }
python
def stats(self, date=None): '''Return the current statistics for a given queue on a given date. The results are returned are a JSON blob:: { 'total' : ..., 'mean' : ..., 'variance' : ..., 'histogram': [ ...
java
private boolean shrinkBlock() throws StructureException, RefinerFailedException { // Let shrink moves only if the repeat is larger enough if (repeatCore <= Lmin) return false; // Select column by maximum distance updateMultipleAlignment(); Matrix residueDistances = MultipleAlignmentTools .getAvera...
python
def _StrftimeLocal(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns local time. """ time_tuple = time.localtime(value) return _StrftimeHelper(args, time_tuple)
python
def upload_file_to_s3(awsclient, bucket, key, filename): """Upload a file to AWS S3 bucket. :param awsclient: :param bucket: :param key: :param filename: :return: """ client_s3 = awsclient.get_client('s3') transfer = S3Transfer(client_s3) # Upload /tmp/myfile to s3://bucket/key ...
java
public static ClientConfigurationBuilder builder(final String url, final String username, final String password) { return new ClientConfigurationBuilder(url, username, password); }
python
def _to_edit(self, infoid): ''' render the HTML page for post editing. ''' postinfo = MPost.get_by_uid(infoid) if postinfo: pass else: return self.show404() if 'def_cat_uid' in postinfo.extinfo: catid = postinfo.extinfo['def_...
java
public static DoublePredicate softenDoublePredicate(final CheckedDoublePredicate fn) { return t -> { try { return fn.test(t); } catch (final Throwable e) { throw throwSoftenedException(e); } }; }
python
def init_counts(self, counts_len): '''Called after instantiating with a compressed payload Params: counts_len counts size to use based on decoded settings in the header ''' assert self._data and counts_len and self.counts_len == 0 self.counts_len = counts_len ...
python
def print_frame( self, x: int, y: int, width: int, height: int, string: str = "", clear: bool = True, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a framed rectangle with optional text. This uses the default backgro...
java
@Override public Response sendFAX(String CorpNum, MgtKeyType KeyType, String MgtKey, String Sender, String Receiver) throws PopbillException { return sendFAX(CorpNum, KeyType, MgtKey, Sender, Receiver, null); }
java
public String getSectionId() { if (Section_Type.featOkTst && ((Section_Type)jcasType).casFeat_sectionId == null) jcasType.jcas.throwFeatMissing("sectionId", "de.julielab.jules.types.Section"); return jcasType.ll_cas.ll_getStringValue(addr, ((Section_Type)jcasType).casFeatCode_sectionId);}
python
def cmd_gimbal_status(self, args): '''show gimbal status''' master = self.master if 'GIMBAL_REPORT' in master.messages: print(master.messages['GIMBAL_REPORT']) else: print("No GIMBAL_REPORT messages")
python
def get_activities_by_genus_type(self, activity_genus_type): """Gets an ``ActivityList`` corresponding to the given activity genus ``Type`` which does not include activities of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known activities or a...
java
public static DirectionsApiRequest getDirections( GeoApiContext context, String origin, String destination) { return new DirectionsApiRequest(context).origin(origin).destination(destination); }
java
void writeBootstrapMethods() { int alenIdx = writeAttr(names.BootstrapMethods); databuf.appendChar(bootstrapMethods.size()); for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) { DynamicMethod dmeth = entry.getKey(); DynamicMethodSymbol dsym =...
java
static Set<String> labels(final ResultSet results) throws SQLException { final ResultSetMetaData metadata = results.getMetaData(); final int count = metadata.getColumnCount(); final Set<String> labels = new HashSet<>(count); for (int i = 1; i <= count; i++) { labels.add(metad...
java
public JsonBeanProcessor findJsonBeanProcessor( Class target ) { if( !beanProcessorMap.isEmpty() ) { Object key = jsonBeanProcessorMatcher.getMatch( target, beanProcessorMap.keySet() ); return (JsonBeanProcessor) beanProcessorMap.get( key ); } return null; }
python
def _build_lv_grid(ding0_grid, network): """ Build eDisGo LV grid from Ding0 data Parameters ---------- ding0_grid: ding0.MVGridDing0 Ding0 MV grid object Returns ------- list of LVGrid LV grids dict Dictionary containing a mapping of LV stations in Ding0 to...
java
public OvhFrontendUdp serviceName_udp_frontend_POST(String serviceName, String[] dedicatedIpfo, Long defaultFarmId, Boolean disabled, String displayName, String port, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/udp/frontend"; StringBuilder sb = path(qPath, serviceName); HashMa...
python
def _try_mask_first_value(value, row, all_close): ''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): ...
python
def singlerose(self, Width=1, Color=['red']): ''' draw the rose map of single sample with different items~ ''' self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1]) self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1] self.SingleRoseName =...
python
def merge_dicts(i): """ Input: { dict1 - merge this dict with dict2 (will be directly modified!) dict2 - dict Output: { return - return code = 0, if successful dict1 - output dict } """ a=i['dict1'] b=i['dict2'...
java
public void appendExists(Filter<S> filter) throws FetchException { mStatementBuilder.append(" WHERE "); mStatementBuilder.append("EXISTS (SELECT * FROM"); JDBCStorableInfo<S> info; final JDBCRepository repo = mStatementBuilder.getRepository(); try { info = r...
java
public static JPanel makeVBox (Policy policy, Justification justification) { return new JPanel(new VGroupLayout(policy, justification)); }
python
def invalidate(self, cls, id_field, id_val): """ Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag. """ cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_ke...
python
def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ mkdir_p('/tmp/test/test') source('/root/.bash_profile') yum_install(['httpd', 'git']) yum_install(['httpd', 'git'], dest_dir='/tmp/test/test...
java
public DoubleStreamEx mapFirst(DoubleUnaryOperator mapper) { return delegate(new PairSpliterator.PSOfDouble((a, b) -> b, mapper, spliterator(), PairSpliterator.MODE_MAP_FIRST)); }
java
public static <T> boolean compareLists(List<T> list1, List<T> list2) { if (list1 == list2) return true; if (list1 == null || list2 == null) return false; if (list1.size() != list2.size()) return false; for (int i = 0; i < list1.size(); i++) { ...
python
def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return: """ if path is None: path = [] for key in b: ...
java
protected List<ImageDTO> extractImagesFromCursor(Cursor cursor, int offset, int limit) { List<ImageDTO> images = new ArrayList<>(); int count = 0; int begin = offset > 0 ? offset : 0; if (cursor.moveToPosition(begin)) { do { ImageDTO image = extractOneImageFro...
python
def _filter(self, dict, keep): """ Remove any keys not in 'keep' """ if not keep: return dict result = {} for key, value in dict.iteritems(): if key in keep: result[key] = value return result
java
public static Seconds seconds(int seconds) { switch (seconds) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: r...
java
@Override public void execute() throws MojoExecutionException { try { ensureNotExisting(); createDirectories(); if ("blank".equalsIgnoreCase(skel)) { createApplicationConfiguration(); createBlankPomFile(); createPackageStru...
java
public void setWidth(int width) { this.width = width; getElement().getStyle().setWidth(width, Style.Unit.PX); }
python
def _check_pyopengl_3D(): """Helper to ensure users have OpenGL for 3D texture support (for now)""" global USE_TEX_3D USE_TEX_3D = True try: import OpenGL.GL as _gl except ImportError: raise ImportError('PyOpenGL is required for 3D texture support') return _gl
java
private void scan(final String targetPath, final String basePackageName, final String relativePackageName, final WildcardMatcher matcher, final SaveHandler saveHandler) { final File target = new File(targetPath); if (!target.exists()) { return; } target...
java
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int startX = 0; int endX = getWidth(); int lineHeight; int startYLine = getHeight() - getPaddingBottom() + underlineTopSpacing; int startYFloatingLabel = (int) (getPaddingTop() - floatingLabelPer...
java
public void send(String channel, String message) { // CAUSE: Assignment to method parameter Pair<Boolean, String> sendValidation = isSendValid(channel, message, null, null); //String lMessage = message.replace("\n", "\\n"); if (sendValidation != null && sendValidation.first) { try { String messageId = ...
python
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as ...
python
def _datetime_from_json(value, field): """Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from ``value`` if t...
python
def set_application(self, app, callback=None): """ Set ``CommandLineInterface`` instance for this connection. (This can be replaced any time.) :param cli: CommandLineInterface instance. :param callback: Callable that takes the result of the CLI. """ assert isinst...
java
public boolean isRadioButtonValueSelected(final String radioButtonName, final String value) { List<WebElement> radioGroup = driver.findElements(By .name(radioButtonName)); for (WebElement button : radioGroup) { if (button.getAttribute("value").equalsIgnoreCase(value) && button.isSelected()) { ret...
java
private void submitTaskStateEvent(TaskState taskState, Map<String, String> jobMetadata) { ImmutableMap.Builder<String, String> taskMetadataBuilder = new ImmutableMap.Builder<>(); taskMetadataBuilder.putAll(jobMetadata); taskMetadataBuilder.put(METADATA_TASK_ID, taskState.getTaskId()); taskMetadataBuild...
python
def slow_highlight(img1, img2, opts): """Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, smoothing it a bit to reduce spurious matches in areas that are perceptibly different (e.g. text), a...
python
def add(self, command, response): """ Register a command/response pair. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sen...
java
@Override public Object invoke(Object[] allVals) throws InvocationTargetException { Object[] vals; Object tmp; vals = new Object[paraParaCount]; System.arraycopy(allVals, idx, vals, 0, vals.length); tmp = para.invoke(vals); vals = new Object[baseParaCount]; ...
java
public TedTask getTask(Long taskId) { if (taskId == null) return null; return tedDriverImpl.getTask(taskId); }
java
public static String wrap(String line, int widthInCharacters, String indent) { StringBuilder buffer = new StringBuilder(); int lineCount = 1; int spaceIndex; // if indent is null, then do not indent the wrapped lines indent = (indent != null ? indent : EMPTY_STRING); while (line.length() > w...
java
public static void assertJsonPartNotEquals(Object expected, Object fullJson, String path, Configuration configuration) { Diff diff = create(expected, fullJson, FULL_JSON, path, configuration); if (diff.similar()) { if (ROOT.equals(path)) { doFail("Expected different values bu...
java
public void setResponses(Map<String, List<Map<String, AttributeValue>>> responses) { this.responses = responses; }
java
public List<EventData> parse(Long pipelineId, List<Entry> datas) throws SelectException { List<EventData> eventDatas = new ArrayList<EventData>(); Pipeline pipeline = configClientService.findPipeline(pipelineId); List<Entry> transactionDataBuffer = new ArrayList<Entry>(); // hz为主站点,us->h...
python
def scipy_constraints(self, constraints): """ Returns all constraints in a scipy compatible format. :param constraints: List of either MinimizeModel instances (this is what is provided by :class:`~symfit.core.fit.Fit`), :class:`~symfit.core.fit.BaseModel`, or :clas...
python
def _generate_permutation(self, npoints): """ Create shuffle and deshuffle vectors """ i = np.arange(0, npoints) # permutation p = np.random.permutation(npoints) ip = np.empty_like(p) # inverse permutation ip[p[i]] = i return p, ip
python
def eventFilter( self, object, event ): """ Filters the chart widget for the resize event to modify this scenes rect. :param object | <QObject> event | <QEvent> """ if ( event.type() != event.Resize ): return False ...
python
def setter_generator(field_name): """ Generate set_'field name' method for field field_name. """ def set_translation_field(cls, value, language_code=None): setattr(cls.get_translation(language_code, True), field_name, value) set_translation_field.short_description = "set " + ...
python
def _set_interface_ipv6(self, v, load=False): """ Setter method for interface_ipv6, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_ipv6 (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_ipv6 is considered as ...
java
public void setObjects(Object object) { if (Collection.class.isAssignableFrom(object.getClass())) { this.objects = (Collection) object; } }
python
def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g...