language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private static void setBasicValue(Object entity, Field member, String columnName, UDTValue row, CassandraType dataType, MetamodelImpl metamodel) { if(row.isNull(columnName)){ return; } Object retVal = null; switch (dataType) { case BYTES: ...
java
private void identifyBonds() { IAtomContainer spt = getSpanningTree(); IRing ring; int nBasicRings = 0; for (int i = 0; i < totalEdgeCount; i++) { if (!bondsInTree[i]) { ring = getRing(spt, molecule.getBond(i)); for (int b = 0; b < ring.getBond...
python
def webapi(i): """ Input: { from access function } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ ruoa=i.get('repo_uoa','') muoa=i.get('modul...
java
public Observable<AgentRegistrationInner> getAsync(String resourceGroupName, String automationAccountName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName).map(new Func1<ServiceResponse<AgentRegistrationInner>, AgentRegistrationInner>() { @Override public Ag...
java
private void initialize(NameNode nn, Configuration conf) throws IOException { // Register MBean first since pedingReplication refers to myFSMetrics this.registerMBean(conf); // register the MBean for the FSNamesystemStutus // This needs to be initialized first, since it is referenced by other // operati...
python
def _validate_handler(column_name, value, predicate_refs): """handle predicate's return value""" # only does validate when attribute value is not None # else, just return it, let sqlalchemy decide if the value was legal according to `nullable` argument's value if value is not None: for predicat...
python
def in_clear_absence_period(self): """Is the current date in the block's clear absence period? (Should info on clearing the absence show?) """ now = datetime.datetime.now() two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS) return now.date() <=...
python
def update_stats(self, stats, delta, sample_rate=1): """ Updates one or more stats counters by arbitrary amounts >>> statsd_client.update_stats('some.int',10) """ if not isinstance(stats, list): stats = [stats] data = dict((stat, "%s|c" % delta) for stat in s...
python
def record(self): # type: () -> bytes ''' A method to generate the string representing this UDF Logical Volume Implementation Use. Parameters: None. Returns: A string representing this UDF Logical Volume Implementation Use. ''' if not se...
java
public ModelAdapter<Model, Item> remove(int position) { mItems.remove(position, getFastAdapter().getPreItemCount(position)); return this; }
java
public void attachBones(final GVRPose savepose) { GVRSceneObject owner = getOwnerObject(); if (owner == null) { return; } GVRSceneObject.SceneVisitor visitor = new GVRSceneObject.SceneVisitor() { @Override public boolean visit(GVRS...
java
public long countInstallationOfEntityById(ModelId entityId) { final String field = String.format(Locale.ROOT, "%s.%s", ContentPackInstallation.FIELD_ENTITIES, NativeEntityDescriptor.FIELD_META_ID); return dbCollection.getCount(DBQuery.is(field, entityId)); }
java
public void addEvents(List<FlowEvent> events) throws IOException { List<Put> puts = new ArrayList<Put>(events.size()); for (FlowEvent e : events) { puts.add(createPutForEvent(e)); } Table eventTable = null; try { eventTable = hbaseConnection .getTable(TableName.valueOf(Constant...
python
def password(password_command): """Create a password prompt function.""" gui = lambda: has_Gtk() and get_password_gui tty = lambda: sys.stdin.isatty() and get_password_tty if password_command == 'builtin:gui': return gui() or tty() elif password_command == 'builtin:tty': return tty()...
python
def parse_http_scheme(uri): """ match on http scheme if no match is found will assume http """ regex = re.compile( r'^(?:http)s?://', flags=re.IGNORECASE ) match = regex.match(uri) return match.group(0) if match else 'http://'
java
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); ...
python
def manual_get_pfam_annotations(seq, outpath, searchtype='phmmer', force_rerun=False): """Retrieve and download PFAM results from the HMMER search tool. Args: seq: outpath: searchtype: force_rerun: Returns: Todo: * Document and test! """ if op.exists(o...
python
def total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """ sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: ...
python
def execute_tropo_program(self, program): """ Ask Tropo to execute a program for us. We can't do this directly; we have to ask Tropo to call us back and then give Tropo the program in the response body to that request from Tropo. But we can pass data to Tropo and ask Tr...
python
def run_command_orig(cmd): """ No idea how th f to get this to work """ process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode == 0: os.killpg(os.getpgid(pro.pid), signal.SIGTERM) else: ...
python
def handle(self, source, target, app=None, **options): """ command execution """ translation.activate(settings.LANGUAGE_CODE) if app: unpack = app.split('.') if len(unpack) == 2: models = [get_model(unpack[0], unpack[1])] elif len(unpack) == 1...
java
public final void deleteTransferRun(RunName name) { DeleteTransferRunRequest request = DeleteTransferRunRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); deleteTransferRun(request); }
python
async def status(dev: Device): """Display status information.""" power = await dev.get_power() click.echo(click.style("%s" % power, bold=power)) vol = await dev.get_volume_information() click.echo(vol.pop()) play_info = await dev.get_play_info() if not play_info.is_idle: click.echo...
python
def find(self, signature = None, order = 0, since = None, until = None, offset = None, limit = None): """ Retrieve all crash dumps in the database, optionally filtering them by signature and timestamp, and/or sorting them by timestamp. Resul...
python
def validate_session(self, session, latest_only=False): """ Check that a session is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid :param session: string representing session to check """ if latest_only: if ses...
java
private NamespaceContext buildNamespaceContext(Node node) { SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext(); Map<String, String> namespaces = XMLUtils.lookupNamespaces(node.getOwnerDocument()); // add default namespace mappings namespaces.putAll(namespaceCon...
python
def aggregate(variables, template): '''Generates a resolved "template" for **all** config sets and returns This function will extrapolate the ``template`` file using the contents of ``variables`` and will output a single (extrapolated, expanded) file. Parameters: variables (str): A string stream contain...
java
public void authenticateForRealm(String realm, String aLogin, char[] charArray) { rath.addRealm(realm, aLogin, charArray); }
python
def get_box_id(logger): """ retrieves box id from the /etc/synergy.conf configuration file :raise EnvironmentError: if the configuration file could not be opened :raise LookupError: if the configuration file does not define BOX_ID variable """ try: box_id = None config_file = set...
python
def deep_dependendants(self, target): """ Recursively finds the dependents of a given build target. Assumes the dependency graph is noncyclic """ direct_dependents = self._gettask(target).provides_for return (direct_dependents + reduce( la...
python
def set_contourf_properties(stroke_width, fcolor, fill_opacity, contour_levels, contourf_idx, unit): """Set property values for Polygon.""" return { "stroke": fcolor, "stroke-width": stroke_width, "stroke-opacity": 1, "fill": fcolor, "fill-opacity": fill_opacity, ...
python
async def dispatch(request): """ Routes commands to subhandlers based on the command field in the body. """ if session: message = '' data = await request.json() try: log.info("Dispatching {}".format(data)) _id = data.get('token') if not _id: ...
java
int nextChild(byte[] name) { if (name.length == 0) { // empty name return 0; } int nextPos = Collections.binarySearch(children, name) + 1; if (nextPos >= 0) { // the name is in the list of children return nextPos; } return -nextPos; // insert point }
java
public static S3Versions forKey(AmazonS3 s3, String bucketName, String key) { S3Versions versions = new S3Versions(s3, bucketName); versions.key = key; return versions; }
java
public Element appendElement(String tagName) { Element child = new Element(Tag.valueOf(tagName, NodeUtils.parser(this).settings()), baseUri()); appendChild(child); return child; }
java
public void set_polled_attr(final String[] s) { for (final String value : s) { ext.polled_attr.add(value); } }
java
public void apply(List target, List tmp) { if (target.size() != length()) throw new RuntimeException("target array does not have the same length as the index table"); //fill tmp with the original ordering or target, adding when needed for (int i = 0; i < target.size(); i++) ...
python
def value_to_datum(self, instance, value): """Convert a given Python-side value to a MAAS-side datum. :param instance: The `Object` instance on which this field is currently operating. This method should treat it as read-only, for example to perform validation with regards to ot...
python
def serialize(self, resources): """Serialize resource(s) according to json-api spec.""" serialized = { 'meta': { 'sqlalchemy_jsonapi_version': '4.0.9' }, 'jsonapi': { 'version': '1.0' } } # Determine multiple...
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_animation( # receiver, self.media, disable_notifica...
java
public void logout( String token ) { if( token != null ) { this.tokenToLoginTime.remove( token ); this.tokenToUsername.remove( token ); } }
java
@Override public DisassociateIpGroupsResult disassociateIpGroups(DisassociateIpGroupsRequest request) { request = beforeClientExecution(request); return executeDisassociateIpGroups(request); }
python
def on_created(self, event): """Function called everytime a new file is created. Args: event: Event to process. """ self._logger.debug('Detected create event on watched path: %s', event.src_path) self._process_event(event)
python
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
python
def find_resource_list_from_capability_list(self, uri): """Read capability list to find resource list. Raises a ClientError in cases where the client might look for a capability list in another location, but a ClientFatalError if a capability list is found but there is some problem usin...
python
def _run_on_chrom(chrom, work_bams, names, work_dir, items): """Run cn.mops on work BAMs for a specific chromosome. """ local_sitelib = utils.R_sitelib() batch = sshared.get_cur_batch(items) ext = "-%s-cnv" % batch if batch else "-cnv" out_file = os.path.join(work_dir, "%s%s-%s.bed" % (os.path.s...
python
def __check_equals(self, query): """Check if the query results on the two databases are equals. Returns ------- bool True if the results are the same False otherwise list A list with the differences """ ...
java
public void setConfig(Map<String, ? extends CacheConfig> config) { this.configMap = (Map<String, CacheConfig>) config; }
java
public Vector getVector(String term) { SparseDoubleVector v = termToVector.get(term); return (v == null) ? null : Vectors.immutable( Vectors.subview(v, 0, basisMapping.numDimensions())); }
java
@Override public BlogEntry getEntry(final String id) throws BlogClientException { try { final Object[] params = new Object[] { id, userName, password }; final Object response = getXmlRpcClient().execute("metaWeblog.getPost", params); @SuppressWarnings("unchecked") ...
java
JCExpression typeArgument() { List<JCAnnotation> annotations = typeAnnotationsOpt(); if (token.kind != QUES) return parseType(annotations); int pos = token.pos; nextToken(); JCExpression result; if (token.kind == EXTENDS) { TypeBoundKind t = to(F.at(pos).TypeB...
python
def get_info(self): """Returns a dict with the dialog PDF info Dict keys are: top_row, bottom_row, left_col, right_col, first_tab, last_tab, paper_width, paper_height """ info = {} info["top_row"] = self.top_row_text_ctrl.GetValue() info["bottom_row"] ...
python
def transloadsForPeer(self, peer): """ Returns an iterator of transloads that apply to a particular peer. """ for tl in self.transloads.itervalues(): if peer in tl.peers: yield tl
java
public static <K, V> Function<Map.Entry<K, V>, K> entryToKeyFunction() { return EntryToKeyFunction.getInstance(); }
java
public void setComputeEnvironments(java.util.Collection<ComputeEnvironmentDetail> computeEnvironments) { if (computeEnvironments == null) { this.computeEnvironments = null; return; } this.computeEnvironments = new java.util.ArrayList<ComputeEnvironmentDetail>(computeEnvi...
python
def validate_env(app): """Purge expired values from the environment. When certain configuration values change, related values in the environment must be cleared. While Sphinx can rebuild documents on configuration changes, it does not notify extensions when this happens. Instead, cache relevant val...
python
def mag_cal_report_encode(self, compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z): ''' Reports results of completed compass calibration. Sent until MAG_CAL_ACK received. com...
java
private void handleSslData(NextFilter nextFilter, SslHandler handler) throws SSLException { // Flush any buffered write requests occurred before handshaking. if (handler.isHandshakeComplete()) { handler.flushPreHandshakeEvents(); } // Write encrypted data to be w...
java
public PreferencesFx addEventHandler(EventType<PreferencesFxEvent> eventType, EventHandler<? super PreferencesFxEvent> eventHandler) { preferencesFxModel.addEventHandler(eventType, eventHandler); return this; }
python
def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: """ Returns the best finished states for each batch instance based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance. """ batch_...
java
public static Signature generateSignature(AsymmetricAlgorithm asymmetricAlgorithm, DigestAlgorithm digestAlgorithm) { try { return Signature.getInstance(generateAlgorithm(asymmetricAlgorithm, digestAlgorithm)); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } }
java
private void readCoordinate() throws IOException { for( int i = 0; i < inputDimension; i++ ) { if (i <= 1) { ordValues[i] = precisionModel.makePrecise(dis.readDouble()); } else { ordValues[i] = dis.readDouble(); } } }
java
public String convertToStringSilent(byte[] htmlInput) { try { return convertToString(htmlInput); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_CONVERSION_BYTE_FAILED_0), e); } try {...
java
public static Behavior getHeaderContributorForFavicon() { return new Behavior() { private static final long serialVersionUID = 1L; @Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); response.render(new ...
python
def JoinPath(stem="", *parts): """A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and di...
python
def cmd( name, fun=None, arg=(), **kwargs): ''' Execute a runner asynchronous: USAGE: .. code-block:: yaml run_cloud: wheel.cmd: - fun: key.delete - match: minion_id ''' ret = {'name': name, 'changes': {}, ...
java
@Override public String getMessage() { String msg = super.getMessage(); if (msg == null) { msg = "N/A"; } JsonLocation loc = getLocation(); if (loc != null) { StringBuilder sb = new StringBuilder(); sb.append(msg); sb.append...
java
@Nullable private RequiredType resolveTypeFromClass( Type calledType, ClassSymbol clazzSymbol, String typeArgName, VisitorState state) { // Try on the class int tyargIndex = findTypeArgInList(clazzSymbol, typeArgName); if (tyargIndex != -1) { return RequiredType.create( extractTypeAr...
python
def compute_ps_counts(ebins, exp, psf, bkg, fn, egy_dim=0, spatial_model='PointSource', spatial_size=1E-3): """Calculate the observed signal and background counts given models for the exposure, background intensity, PSF, and source flux. Parameters ---------- ebins : `~numpy.n...
python
def _GetAttributeContainerByIndex(self, container_type, index): """Retrieves a specific attribute container. Args: container_type (str): attribute container type. index (int): attribute container index. Returns: AttributeContainer: attribute container or None if not available. Raise...
python
def get_freesurfer_label(annot_input, verbose = True): """ Print freesurfer label names. """ labels, color_table, names = nib.freesurfer.read_annot(annot_input) if verbose: print(names) return names
java
void fileWriteCheck(String filePath, AddOnModel addOnModel) { File request; try { request = new File(filePath).getCanonicalFile(); } catch (IOException e) { error("Error getting canonical path", e); throw getException(filePath); } isForbidden...
python
def readinto(self, buff): """ Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the number of bytes read. :returns: The number of bytes read. """ data = self.read(len(buff)) buff[: len(data)] = data return len(data)
java
public Widget insert(Widget w, int beforeIndex) { FlowPanel widgetWrapper = new FlowPanel(); widgetWrapper.getElement().setId(Document.get().createUniqueId()); widgetWrapper.add(w); flow.insert(w, beforeIndex); JQMContext.render(widgetWrapper.getElement().getId()); reb...
java
public void init() { loader = ExtensionLoader.getExtensionLoader(OuterAdapter.class); String canalServerHost = this.canalClientConfig.getCanalServerHost(); SocketAddress sa = null; if (canalServerHost != null) { String[] ipPort = canalServerHost.split(":"); ...
python
def get_dt_list(fn_list): """Get list of datetime objects, extracted from a filename """ dt_list = np.array([fn_getdatetime(fn) for fn in fn_list]) return dt_list
python
def fit(self, SF, x_range, y_range, matrix_z): ''' #================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth f...
python
def get_api( profile=None, config_file=None, requirements=None): ''' Generate a datafs.DataAPI object from a config profile ``get_api`` generates a DataAPI object based on a pre-configured datafs profile specified in your datafs config file. To create a datafs config fi...
java
public void setSslManualOverride(com.google.api.ads.admanager.axis.v201805.SslManualOverride sslManualOverride) { this.sslManualOverride = sslManualOverride; }
java
private void upgradeLockIfNeeded() { // using clone to avoid ConcurentModificationException Iterator iter = ((List) mvOrderOfIds.clone()).iterator(); TransactionImpl tx = getTransaction(); ObjectEnvelope mod; while(iter.hasNext()) { mod = (ObjectEn...
python
def output_forward(gandi, domain, forward, justify=14): """ Helper to output a mail forward information.""" for dest in forward['destinations']: output_line(gandi, forward['source'], dest, justify)
java
public Where<T, ID> ge(String columnName, Object value) throws SQLException { addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, SimpleComparison.GREATER_THAN_EQUAL_TO_OPERATION)); return this; }
python
def _spawn_background_rendering(self, rate=5.0): """ Spawns a thread that updates the render window. Sometimes directly modifiying object data doesn't trigger Modified() and upstream objects won't be updated. This ensures the render window stays updated without consuming too ...
python
def safe_mkdir_for_all(paths): """Make directories which would contain all of the passed paths. This avoids attempting to re-make the same directories, which may be noticeably expensive if many paths mostly fall in the same set of directories. :param list of str paths: The paths for which containing directori...
python
def trim_iterable(iterable, limit, *, split=None, prefix='', postfix=''): """trim the list to make total length no more than limit.If split specified,a string is return. :return: """ if split is None: sl = 0 join = False else: sl = len(split) join = True result = ...
python
def next_paragraph_style(self): """ |_ParagraphStyle| object representing the style to be applied automatically to a new paragraph inserted after a paragraph of this style. Returns self if no next paragraph style is defined. Assigning |None| or *self* removes the setting such tha...
java
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException { validateUpdatedModel(context, model); }
python
def parse_mixed_delim_str(line): """Turns .obj face index string line into [verts, texcoords, normals] numeric tuples.""" arrs = [[], [], []] for group in line.split(' '): for col, coord in enumerate(group.split('/')): if coord: arrs[col].append(int(coord)) return [t...
python
def _string_find(self, substr, start=None, end=None): """ Returns position (0 indexed) of first occurence of substring, optionally after a particular position (0 indexed) Parameters ---------- substr : string start : int, default None end : int, default None Not currently implem...
java
public void purge(long seqno, boolean force) { lock.lock(); try { if(seqno - low <= 0) return; if(force) { if(seqno - hr > 0) seqno=hr; } else { if(seqno - hd > 0) // we cannot be higher t...
python
def free_support_barycenter(measures_locations, measures_weights, X_init, b=None, weights=None, numItermax=100, stopThr=1e-7, verbose=False, log=None): """ Solves the free support (locations of the barycenters are optimized, not the weights) Wasserstein barycenter problem (i.e. the weighted Frechet mean for the...
python
def list(ctx): """List all config values.""" log.debug('chemdataextractor.config.list') for k in config: click.echo('%s : %s' % (k, config[k]))
python
def query_names(self, name, like, kind): """ Query function declarations in the files. """ kind = self._make_kind_id(kind) sql = 'select id, name from files ' \ 'where leaf_name {} ?'.format('like' if like else '=') args = (name,) if like: ...
python
async def removeSecret(self, *args, **kwargs): """ Remove a Secret Remove a secret. After this call, a call to `getSecret` with the given token will return no information. It is very important that the consumer of a secret delete the secret from storage before handing ...
java
protected T cursorToObject(Cursor cursor) throws SQLException { return preparedQuery.mapRow(new AndroidDatabaseResults(cursor, null, true)); }
python
def convert_linalg_gemm2(node, **kwargs): """Map MXNet's _linalg_gemm2 operator attributes to onnx's MatMul and Transpose operators based on the values set for transpose_a, transpose_b attributes. Return multiple nodes created. """ name, input_nodes, attrs = get_inputs(node, kwargs) # Getti...
python
def num_in_memory(self): """Get number of values in memory.""" n = len(self._data) - 1 while n >= 0: if isinstance(self._data[n], _TensorValueDiscarded): break n -= 1 return len(self._data) - 1 - n
python
def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None): """ Computes the inverse kinematic on the specified target with an optimization method Parameters ---------- chain: ikpy.chain.Chain The chain used for the Inverse k...
java
public String getHTML(int index) { String raw=getRaw(index); if (raw==null) { return raw; } int[] style=getStyle(index); if (style==null) { return raw; } StringBuilder html=new StringBuilder(raw.length()+32); int offset=0; w...
python
def parse_networking_file(): """ Parse the VMware networking file. """ pairs = dict() allocated_subnets = [] try: with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f: version = f.readline() for line in f.read().splitlines(): try: ...