language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public <X> DataSource<X> fromCollection(Collection<X> data, TypeInformation<X> type) { return fromCollection(data, type, Utils.getCallLocationName()); }
java
public static <T> boolean isDescendantOfOrEqualTo(TreeDef.Parented<T> treeDef, T child, T parent) { if (child.equals(parent)) { return true; } else { return isDescendantOf(treeDef, child, parent); } }
java
private void init(ExecutorService executorService, Configuration configuration) { cfg.getRequestContext().put(EXECUTOR_SERVICE_PROPERTY, executorService); cfg.getRequestContext().putAll(configuration.getProperties()); List<Interceptor<? extends Message>>inboundChain = cfg.getInInterceptors(); ...
java
private void initializeStage() { // Define the stage title this.stage.setTitle(applicationTitle()); // Define stage icons, the toolkit will use the best size final List<Image> stageIcons = stageIcons(); if (stageIcons != null && !stageIcons.isEmpty()) { this.stage.ge...
java
protected void onRPCComplete(int asyncHandle, String data) { IAsyncRPCEvent callback = getCallback(asyncHandle); if (callback != null) { callback.onRPCComplete(asyncHandle, data); } }
python
def destroy(self, request, pk=None): '''For DELETE actions, archive the organization, don't delete.''' org = self.get_object() org.archived = True org.save() return Response(status=status.HTTP_204_NO_CONTENT)
java
public static <T> Collector<T, ?, Boolean> allMatch(Predicate<? super T> predicate) { return Collector.of( () -> new Boolean[1], (a, t) -> { if (a[0] == null) a[0] = predicate.test(t); else a[0] = a[0] && predicate.t...
java
private static String byteArrayToString(byte[] bytes) { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < bytes.length; i++) { if (i > 0) { builder.append(", "); } builder.append(byteToString(bytes[i])); } return builder.append(']').toString(); }
python
def to_dict(self): """Convert to a ``dict`` Subclasses can override this function. Returns: Python dict with keys set from this Entity. """ entity_dict = {} for field, val in six.iteritems(self._fields): if field.multiple: if val...
java
public static CoreDictionary.Attribute get(String key) { if (HanLP.Config.Normalization) key = CharTable.convert(key); CoreDictionary.Attribute attribute = dat.get(key); if (attribute != null) return attribute; if (trie == null) return null; return trie.get(key); }
java
private void checkType(BtrpOperand e) { if (!(e instanceof BtrpNumber)) { throw new UnsupportedOperationException(e + " must be a '" + prettyType() + "' instead of a '" + e.prettyType() + "'"); } }
java
public void addRemoteRepository(RemoteRepository remoteRepository) { if (this.repositoryIds.add(remoteRepository.getId()) ) { getRemoteRepositories().add(remoteRepository); } }
python
def _random_stochastic_matrix(m, n, k=None, sparse=False, format='csr', random_state=None): """ Generate a "non-square stochastic matrix" of shape (m, n), which contains as rows m probability vectors of length n with k nonzero entries. For other parameters, see `random...
python
def sendTo(self, loc, usr=None): """ Transfer's an item from user's inventory to another inventory, returns result Parameters: loc (str) -- Location to send the item to (see Item.SHOP, Item.SDB, etc.) usr (User) -- User who has the item Returns ...
java
private void checkCallService( RequestCallInfo info ) { String service = info.request.service; String interfaceChecksum = info.request.interfaceChecksum; String key = getServiceKey( info ); if( usedServices.containsKey( key ) ) return; ServiceInfo serviceInfo = new ServiceInfo( service, interfaceChecks...
python
def offset(self): """ If this is a constant access (e.g. A(1)) return the offset in bytes from the beginning of the variable in memory. Otherwise, if it's not constant (e.g. A(i)) returns None """ offset = 0 # Now we must typecast each argument to a u16 (...
python
def rowmapmany(table, rowgenerator, header, failonerror=False): """ Map each input row to any number of output rows via an arbitrary function. E.g.:: >>> import petl as etl >>> table1 = [['id', 'sex', 'age', 'height', 'weight'], ... [1, 'male', 16, 1.45, 62.0], ......
java
public EClass getMMD() { if (mmdEClass == null) { mmdEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(299); } return mmdEClass; }
java
VirtualConnection parseResponseMessageAsync() { VirtualConnection readVC = null; try { do { if (parseMessage()) { // finished parsing the message return getVC(); } if (TraceComponent.isAnyTracingEnabled(...
python
def remove_collation(coltype: TypeEngine) -> TypeEngine: """ Returns a copy of the specific column type with any ``COLLATION`` removed. """ if not getattr(coltype, 'collation', None): return coltype newcoltype = copy.copy(coltype) newcoltype.collation = None return newcoltype
python
def set_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """ Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=['slug'])
python
def split_string(self, string, splitter='.', allow_empty=True): """Split the string with respect of quotes""" i = 0 rv = [] need_split = False while i < len(string): m = re.compile(_KEY_NAME).match(string, i) if not need_split and m: i = m....
python
def generate_search_space(code_dir): """Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files (str) """ search_space = {} if code_dir.endswith(slash): code_dir = code_dir[:-1] for subdir, _, files in o...
python
def history(directory=None, rev_range=None, verbose=False, indicate_current=False): """List changeset scripts in chronological order.""" config = current_app.extensions['migrate'].migrate.get_config(directory) if alembic_version >= (0, 9, 9): command.history(config, rev_range, verbose=verbose, indic...
python
def diff_commonPrefix(self, text1, text2): """Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string. """ # Quick check for common null cases. if not text1 or not text2 ...
python
def get_wharton_gsrs(self, sessionid, date=None): """ Make a request to retrieve Wharton GSR listings. """ if date: date += " {}".format(self.get_dst_gmt_timezone()) else: date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%S") resp = requests.get('https://ap...
python
def add_protein_sequence_args(parser): """ Extends an ArgumentParser instance with the following args: --max-protein-sequences-per-variant Also adds all translation arguments such as: --protein-sequence-length """ protein_sequence_group = parser.add_argument_group( "Protein s...
python
def wildcard_import_names(self): """The list of imported names when this module is 'wildcard imported'. It doesn't include the '__builtins__' name which is added by the current CPython implementation of wildcard imports. :returns: The list of imported names. :rtype: list(str) ...
python
def t_QUOTED_STRING(t): r'"([^"\\]|\\["\\])*"' # TODO: Add support for: # - An undefined escape sequence (such as "\a" in a context where "a" # has no special meaning) is interpreted as if there were no backslash # (in this case, "\a" is just "a"), though that may be changed by # extensions. ...
python
def init(self): """Extract some info from chunks""" for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
python
def build_payload(self, tag, message): """ Encode, sign payload(optional) and attach subscription tag """ message = self.encode(message) message = self.sign(message) payload = bytes(tag.encode('utf-8')) + message return payload
java
public Map<String, String> getGroupMappings() { return groupMappings != null ? Collections.unmodifiableMap(groupMappings) : null; }
java
protected static StringBuilder appendResourcePathPrefixFor(StringBuilder sb, Class<?> cls) { if(cls == null) throw new NullPointerException("cls is null"); return appendResourcePathPrefixFor(sb, getPackageName(cls)); }
python
def stack(self, slug, chart_obj=None, title=None): """ Get the html for a chart and store it """ if chart_obj is None: if self.chart_obj is None: self.err( self.stack, "No chart object set: please provide one in paramete...
python
def req(self, timeout): '''Re-queue a message''' self.connection.req(self.id, timeout) self.processed = True
python
def Pack(self, msg, type_url_prefix='type.googleapis.com/'): """Packs the specified message into current Any message.""" if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) else: self.type_url = '%s%s' % (type_url_prefi...
python
def begin(self, user_url, anonymous=False): """Start the OpenID authentication process. See steps 1-2 in the overview at the top of this file. @param user_url: Identity URL given by the user. This method performs a textual transformation of the URL to try and make sure i...
java
public Attribute.Compound attribute(Symbol anno) { for (Attribute.Compound a : getRawAttributes()) { if (a.type.tsym == anno) return a; } return null; }
python
def removeRef(self, doc): """Remove the given attribute from the Ref table maintained internally. """ if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlRemoveRef(doc__o, self._o) return ret
python
def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'): """Intended to be passed to the `remote` function as the xfer_func argument. Matches up with recv_file_from_host. """ bytes_remaining = filesize save_timeout = dev.timeout dev.timeout = 1 while bytes_remaining ...
java
protected void generateCharacterEvents( IPortletWindowId portletWindowId, XMLEventReader eventReader, StartElement event, Collection<CharacterEvent> eventBuffer) throws XMLStreamException { this.generateCharacterEvents(portletWindowId, event, eventBuff...
python
def create_gemini_db(gemini_vcf, data, gemini_db=None, ped_file=None): """Generalized vcfanno/vcf2db workflow for loading variants into a GEMINI database. """ if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not vcfutils.vcf_has_variants(gemini_vcf): return N...
java
public boolean canDecompress(final QuickTime.ImageDesc pDescription) { return QuickTime.VENDOR_APPLE.equals(pDescription.compressorVendor) && "raw ".equals(pDescription.compressorIdentifer) && (pDescription.depth == 24 || pDescription.depth == 32); }
python
def set_menu(self, menu): '''add a menu from the parent''' self.menu = menu wx_menu = menu.wx_menu() self.frame.SetMenuBar(wx_menu) self.frame.Bind(wx.EVT_MENU, self.on_menu)
python
def select_many_column(engine, *columns): """ Select data from multiple columns. Example:: >>> select_many_column(engine, table_user.c.id, table_user.c.name) :param columns: list of sqlalchemy.Column instance :returns headers: headers :returns data: list of row **中文文档** 返回...
java
public static final SerIterable grid(final Class<?> valueType, final List<Class<?>> valueTypeTypes) { return new SerIterable() { private final List<Grid.Cell<?>> cells = new ArrayList<>(); private int[] dimensions; @Override public SerIterator iterator() { ...
java
public static Map<String, ? extends CacheConfig> fromYAML(InputStream inputStream) throws IOException { return new CacheConfigSupport().fromYAML(inputStream); }
java
private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) { byte[] locBuffer = buffer; if (size <= 0) // This should never happen return; if (buffer.length != size) { locBuffer = new byte[size]; System.arraycopy(buffer, 0, lo...
python
def do_help(self, arg): """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command. """ if not arg: ...
java
public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException { if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) { throw new IllegalArgumentException("this method should only be called with a pre-hashed password"); } User user = User.ge...
python
def _path_factory(check): """Create a function that checks paths.""" @functools.wraps(check) def validator(paths): if isinstance(paths, str): check(paths) elif isinstance(paths, collections.Sequence): for path in paths: check(path) else: ...
python
def search(self, keyword, count=30): """ Search files or directories :param str keyword: keyword :param int count: number of entries to be listed """ kwargs = {} kwargs['search_value'] = keyword root = self.root_directory entries = root._load_entr...
python
def _resolve_widget(cls, file, widget): ''' Resolve widget callable properties into static ones. :param file: file will be used to resolve callable properties. :type file: browsepy.file.Node :param widget: widget instance optionally with callable properties :type widget:...
java
public List<String> getLockedResources(CmsRequestContext context, CmsResource resource, CmsLockFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<String> result = null; try { checkOfflineProject(dbc); checkPermissio...
java
public void marshall(WriteSegmentRequest writeSegmentRequest, ProtocolMarshaller protocolMarshaller) { if (writeSegmentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(writeSegmentRequest.ge...
java
public static long getCurrentSegmentGeneration(String[] files) { if (files == null) { return -1; } long max = -1; for (int i = 0; i < files.length; i++) { String file = files[i]; if (file.startsWith(IndexFileNames.SEGMENTS) && !file.equals(IndexFileNames.SEGMENTS_GEN)...
python
def decrypt(self, data): ''' verify HMAC-SHA256 signature and decrypt data with AES-CBC ''' aes_key, hmac_key = self.keys sig = data[-self.SIG_SIZE:] data = data[:-self.SIG_SIZE] if six.PY3 and not isinstance(data, bytes): data = salt.utils.stringutils...
python
def grouplabelencode(data, mapping, nacode=None, nastate=False): """Encode data array with grouped labels Parameters: ----------- data : list array with labels mapping : dict, list of list the index of each element is used as encoding. Each element is a single label (str) o...
python
def estimate_augmented_markov_model(dtrajs, ftrajs, lag, m, sigmas, count_mode='sliding', connectivity='largest', dt_traj='1 step', maxiter=1000000, eps=0.05, maxcache=3000): r""" Estimates an Augmented Markov model from discrete trajectories and experimental dat...
java
public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> RESP execute(REQ pRequest, Map<J4pQueryParameter,String> pProcessingOptions) throws J4pException { return this.<RESP, REQ>execute(pRequest,null,pProcessingOptions); ...
python
def getControlURL(self, serviceType, default=None): """Returns the control URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated control URL. If t...
java
private Map<String, Class<? extends RulePhase>> loadPhases() { Map<String, Class<? extends RulePhase>> phases; phases = new HashMap<>(); Furnace furnace = FurnaceHolder.getFurnace(); for (RulePhase phase : furnace.getAddonRegistry().getServices(RulePhase.class)) { ...
java
public static String durationToN1qlFormat(long duration, TimeUnit unit) { switch (unit) { case NANOSECONDS: return duration + "ns"; case MICROSECONDS: return duration + "us"; case MILLISECONDS: return duration + "ms"; ...
python
def _request(self, resource, action, data=None, headers=None): """ Send request Args: resource: resource action: action data: string or object which can be json.dumps headers: http headers """ url, httpmethod = res_to_url(resource,...
python
def _stack_format (stack): """Format a stack trace to a message. @return: formatted stack message @rtype: string """ s = StringIO() s.write('Traceback:') s.write(os.linesep) for frame, fname, lineno, method, lines, dummy in reversed(stack): s.write(' File %r, line %d, in %s' % ...
java
public ServiceFuture<PolicyEventsQueryResultsInner> listQueryResultsForResourceAsync(String resourceId, final ServiceCallback<PolicyEventsQueryResultsInner> serviceCallback) { return ServiceFuture.fromResponse(listQueryResultsForResourceWithServiceResponseAsync(resourceId), serviceCallback); }
python
def on_btn_thellier_gui(self, event): """ Open Thellier GUI """ if not self.check_for_meas_file(): return if not self.check_for_uncombined_files(): return outstring = "thellier_gui.py -WD %s"%self.WD print("-I- running python script:\n %s"%...
python
def get_local_key(module_and_var_name, default_module=None): """ Get local setting for the keys. :param module_and_var_name: for example: admin_account.admin_user, then you need to put admin_account.py in local/local_keys/ and add variable admin_user="real admin username", module_name_and_var_name s...
python
def params(self): """ A combined :class:`MultiDict` with values from :attr:`forms` and :attr:`GET`. File-uploads are not included. """ params = MultiDict(self.GET) for key, value in self.forms.iterallitems(): params[key] = value return params
java
private int determineHeartbeatTimeout(Map properties) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "determineHeartbeatTimeout", properties); // How often should we heartbeat? int heartbeatTimeout = JFapChannelConstants.DEFAULT_HEARTBEAT_TI...
java
public void setDecimals(final int DECIMALS) { if (null == decimals) { _decimals = clamp(0, MAX_NO_OF_DECIMALS, DECIMALS); fireTileEvent(REDRAW_EVENT); } else { decimals.set(DECIMALS); } }
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XtextPackage.NAMED_ARGUMENT__PARAMETER: setParameter((Parameter)newValue); return; case XtextPackage.NAMED_ARGUMENT__VALUE: setValue((Condition)newValue); return; case XtextPackage.NAMED_ARGUMENT__CALLED_B...
python
def create_child(args, merge_stdio=False, stderr_pipe=False, preexec_fn=None): """ Create a child process whose stdin/stdout is connected to a socket. :param args: Argument vector for execv() call. :param bool merge_stdio: If :data:`True`, arrange for `stderr` to be connected to the `st...
java
@NonNull public static AlterTableStart alterTable(@Nullable String keyspace, @NonNull String tableName) { return alterTable( keyspace == null ? null : CqlIdentifier.fromCql(keyspace), CqlIdentifier.fromCql(tableName)); }
java
@Nullable public static ImmutableWorkerInfo selectWorker( final Task task, final Map<String, ImmutableWorkerInfo> allWorkers, final WorkerTaskRunnerConfig workerTaskRunnerConfig, @Nullable final AffinityConfig affinityConfig, final Function<ImmutableMap<String, ImmutableWorkerInfo>, Immu...
python
def main(list_ids, model, contact_server, raw_data_id, show_raw, mysql_cfg='mysql_online'): """Main function of view.py.""" if list_ids: preprocessing_desc, _, _ = _get_system(model) raw_datapath = os.path.join(utils.get_project_root(), preprocessing_...
java
public void trace(Object message) { doLog(Level.TRACE, FQCN, message, null, null); }
python
def get_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs): # noqa: E501 """Get certificate issuer configuration. # noqa: E501 Provides the configured certificate issuer. # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
python
def geo_shape(self, sides=5, center=None, distance=None): """ Return a WKT string for a POLYGON with given amount of sides. The polygon is defined by its center (random point if not provided) and the distance (random distance if not provided; in km) of the points to its center. ...
python
def get_xml_root_from_str(xml_str): """Returns XML root from string.""" try: xml_root = etree.fromstring(xml_str.encode("utf-8"), NO_BLANKS_PARSER) # pylint: disable=broad-except except Exception as err: raise Dump2PolarionException("Failed to parse XML string: {}".format(err)) retur...
python
def to_date(value, default=None): """Tries to convert the passed in value to Zope's DateTime :param value: The value to be converted to a valid DateTime :type value: str, DateTime or datetime :return: The DateTime representation of the value passed in or default """ if isinstance(value, DateTim...
java
public WsByteBuffer allocateCommon(int entrySize, boolean direct) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "allocateCommon: " + entrySize); } // see if we should look for leaks if (trackingBuffers()) { lookForLeaks(false);...
java
@GwtIncompatible // com.google_voltpatches.common.math.DoubleUtils public static boolean isPowerOfTwo(double x) { return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x)); }
python
def delete(self, params, args, data): """Supports only singular delete and adds proper http status.""" ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id: deleted = self._delete_one(row_id, ctx) if deleted: return ...
java
public void setLineCap(int style) { if (style >= 0 && style <= 2) { content.append(style).append(" J").append_i(separator); } }
python
def ClaimNotificationsForCollection(cls, token=None, start_time=None, lease_time=200, collection=None): """Return unclaimed hunt result notifications for collection...
python
def refresh(self): """ Reloads the contents for this box based on the parameters. :return <bool> """ self.setDirty(False) self.blockSignals(True) self.setUpdatesEnabled(False) self.clear() locales = self._availableL...
java
@Override public void motionDetected(WebcamMotionEvent wme) { for (Point p : wme.getPoints()) { motionPoints.put(p, 0); } }
python
def __get_ssh_credentials(vm_): ''' Get configured SSH credentials. ''' ssh_user = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default=os.getenv('USER')) ssh_key = config.get_cloud_config_value( 'ssh_keyfile', vm_, __opts__, default=os.path.expanduser('~/.ss...
python
def write_attribute_adj_list(self, path): """Write the bipartite attribute graph to a file. :param str path: Path to the output file. """ att_mappings = self.get_attribute_mappings() with open(path, mode="w") as file: for k, v in att_mappings.items(): ...
java
static File openDirectoryDialog(Frame frame, File initialDir) { return openFileDialog(frame, null, initialDir, JFileChooser.DIRECTORIES_ONLY); }
python
def _delete_example(self, request): """Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'inva...
java
public Observable<Page<BillingMeterInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<BillingMeterInner>>, Page<BillingMeterInner>>() { @Override public Page<BillingMeterInner> call(ServiceResponse<Page<BillingMeterInner>> ...
python
def convert_coord_object(coord): """Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile""" assert isinstance(coord, Coordinate) coord = coord.container() return Tile(int(coord.zoom), int(coord.column), int(coord.row))
python
def prepare_model_data(self, packages, linked, pip=None, private_packages=None): """Prepare downloaded package info along with pip pacakges info.""" logger.debug('') return self._prepare_model_data(packages, linked, pip=pip, priv...
java
public StorageBatchResult<Blob> get(String bucket, String blob, BlobGetOption... options) { return get(BlobId.of(bucket, blob), options); }
python
def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' ...
python
def set_phases(self, literals=[]): """ Sets polarities of a given list of variables. """ if self.minicard: pysolvers.minicard_setphases(self.minicard, literals)
java
protected static String getStatusClass(RLOGLevel level) { String rowClass = ""; switch (level) { case WARN: rowClass = "warning"; break; case ERROR: rowClass = "danger"; break; case INFO: ...
java
public static String formatTypeName(final String elementName, final CobolDataItem cobolDataItem, final List < String > nonUniqueCobolNames, final Cob2XsdConfig config, final XsdDataItem parent, final int order) { StringBuilder sb = new StringBuilder(); sb...