language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void marshall(DeleteInventoryRequest deleteInventoryRequest, ProtocolMarshaller protocolMarshaller) { if (deleteInventoryRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteInvento...
java
private void setCommonHeaders() { String xPoweredByValue = null; if (!WCCustomProperties.DISABLE_X_POWERED_BY){ if (WCCustomProperties.X_POWERED_BY==null){ xPoweredByValue = getXPoweredbyHeader(); } else { xPoweredByValue = WCCustomProp...
python
def _handle_triple_refresh(self, auto_refresh): ''' method to refresh self.rdf.triples if auto_refresh or defaults set to True ''' # if auto_refresh set, and True, refresh if auto_refresh: self.parse_object_like_triples() # else, if auto_refresh is not set (None), check repository instance default e...
python
def normalize(self, inplace: bool = False, percent: bool = False) -> "HistogramBase": """Normalize the histogram, so that the total weight is equal to 1. Parameters ---------- inplace: If True, updates itself. If False (default), returns copy percent: If True, normalizes to perc...
java
public int convertInternalToExternal(Object recordOwner) { if (this.getConvertToNative() == null) { BaseMessageHeader trxMessageHeader = this.getMessage().getMessageHeader(); String strMessageClass = (String)trxMessageHeader.get(TrxMessageHeader.MESSAGE_MARSHALLER_CLASS); ...
java
public static void attach(final View panelLayout, /* Nullable **/final View switchPanelKeyboardBtn, /* Nullable **/final View focusView, /* Nullable **/final SwitchClickListener switchClickListener) { final Activity activi...
python
def delete_messages(self, ids): """ Delete selected messages for the current user :param ids: list of ids """ str_ids = self._return_comma_list(ids) return self.request('MsgAction', {'action': {'op': 'delete', 'id': str_ids}})
java
@SuppressWarnings("unchecked") public static List<Float> getAt(float[] array, Range range) { return primitiveArrayGet(array, range); }
python
def create_parser(self): """ Create and return the ``OptionParser`` which will be used to parse the arguments to the worker. """ return OptionParser(prog=self.prog_name, usage=self.usage(), version='%%prog %s' % self.get_ve...
python
def set_tile(self, codepoint: int, tile: np.array) -> None: """Upload a tile into this array. The tile can be in 32-bit color (height, width, rgba), or grey-scale (height, width). The tile should have a dtype of ``np.uint8``. This data may need to be sent to graphics card memory, this...
python
def _checkMemberName(name): """ See if a member name indicates that it should be private. Private variables in Python (starting with a double underscore but not ending in a double underscore) and bed lumps (variables that are not really private but are by common convention treat...
python
def _scheme_propagation(self, scheme, definitions): """ Will updated a scheme based on inheritance. This is defined in a scheme objects with ``'inherit': '$definition'``. Will also updated parent objects for nested inheritance. Usage:: >>> SCHEME = { >>> 'thing1': {...
python
def get_all_conda_bins(): """Retrieve all possible conda bin directories, including environments. """ bcbio_bin = get_bcbio_bin() conda_dir = os.path.dirname(bcbio_bin) if os.path.join("anaconda", "envs") in conda_dir: conda_dir = os.path.join(conda_dir[:conda_dir.rfind(os.path.join("anacond...
python
def bambus(args): """ %prog bambus bambus.bed bambus.mates total.fasta Insert unplaced scaffolds based on mates. """ from jcvi.utils.iter import pairwise from jcvi.formats.bed import BedLine from jcvi.formats.posmap import MatesFile p = OptionParser(bambus.__doc__) p.add_option("--...
python
def put(self, user_name: str) -> User: """ Updates the User Resource with the name. """ current = current_user() if current.name == user_name or current.is_admin: user = self._get_or_abort(user_name) self.update(user) session.commit() ...
python
def _clashes(self, startTime, duration): """ verifies that this measurement does not clash with an already scheduled measurement. :param startTime: the start time. :param duration: the duration. :return: true if the measurement is allowed. """ return [m for m in s...
python
def from_table(cls, table, length, prefix=0, flatten=False): """ Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :...
python
def list_blobs(kwargs=None, storage_conn=None, call=None): ''' .. versionadded:: 2015.8.0 List blobs associated with the container CLI Example: .. code-block:: bash salt-cloud -f list_blobs my-azure container=mycontainer container: The name of the storage container prefi...
java
public static void exportCSVSequenceLocal(File baseDir, JavaRDD<List<List<Writable>>> sequences, long seed) throws Exception { baseDir.mkdirs(); if (!baseDir.isDirectory()) throw new IllegalArgumentException("File is not a directory: " + baseDir.toString()); Strin...
java
public static base_responses add(nitro_service client, sslocspresponder resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { sslocspresponder addresources[] = new sslocspresponder[resources.length]; for (int i=0;i<resources.length;i++){ addresource...
java
public byte[] getChannelConfigurationSignature(ChannelConfiguration channelConfiguration, User signer) throws InvalidArgumentException { clientCheck(); Channel systemChannel = Channel.newSystemChannel(this); return systemChannel.getChannelConfigurationSignature(channelConfiguration...
java
@Override public void onClick(View v) { switch (v.getId()) { case R.id.openLog: ARouter.openLog(); break; case R.id.openDebug: ARouter.openDebug(); break; case R.id.init: // 调试模式不是必须开启,但是为了防止有...
python
def format_check(settings): """ Check the format of a osmnet_config object. Parameters ---------- settings : dict osmnet_config as a dictionary Returns ------- Nothing """ valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name', 'log_filenam...
python
def get(self, key, *, encoding=_NOTSET): """Get the value of a key.""" return self.execute(b'GET', key, encoding=encoding)
python
def is_opposite(self, ns1, id1, ns2, id2): """Return True if two entities are in an "is_opposite" relationship Parameters ---------- ns1 : str Namespace code for an entity. id1 : str URI for an entity. ns2 : str Namespace code for an e...
java
private boolean useNetworkInterface(NetworkInterface networkInterface) throws HarvestException { try { return !networkInterface.isLoopback() && networkInterface.isUp(); } catch (SocketException e) { throw new HarvestException("Could not evaluate whether network interface is loopback.", e); } }
java
@Override public void init(Configuration phoneNumberProvisioningConfiguration, Configuration telestaxProxyConfiguration, ContainerConfiguration containerConfiguration) { this.containerConfiguration = containerConfiguration; telestaxProxyEnabled = telestaxProxyConfiguration.getBoolean("enabled", fals...
python
def post_install_package(): """ Run any functions post install a matching package. Hook functions are in the form post_install_[package name] and are defined in a deploy.py file Will be executed post install_packages and upload_etc """ module_name = '.'.join([env.project_package_name,'...
java
public static <T> List<T> grep(List<T> self, Object filter) { return (List<T>) grep((Collection<T>) self, filter); }
java
private void resetControlID() { _controlID = null; for (Object child : this) { if (child instanceof ControlBeanContext) ((ControlBeanContext) child).resetControlID(); } }
python
def extract_name(self, data): """Extract man page name from web page.""" name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1) name = re.sub(r'<([^>]+)>', r'', name) name = re.sub(r'&gt;', r'>', name) name = re.sub(r'&lt;', r'<', name) return name
java
@SneakyThrows public static <T> T executeGroovyScript(final Resource groovyScript, final String methodName, final Object[] args, final Class<T> clazz, ...
python
def from_image(cls, image): """ Create a PrintableImage from a PIL Image :param image: a PIL Image :return: """ (w, h) = image.size # Thermal paper is 512 pixels wide if w > 512: ratio = 512. / w h = int(h * ratio) imag...
java
public static Measurement first(final Iterable<Measurement> ms, final String k, final String v) { return first(ms, value -> v.equals(getTagValue(value.id(), k))); }
java
@Override public void setUsers(final String[] theUsers) { mUsers = theUsers; // Cleanup new line and ws for (int i = 0; i < theUsers.length; i++) { mUsers[i] = mUsers[i].trim(); } }
python
def extract_builder_result(builder_result, toolchain_cls=Toolchain): """ Extract the builder result to produce a ``Toolchain`` and ``Spec`` instance. """ try: toolchain, spec = builder_result except Exception: return None, None if not isinstance(toolchain, toolchain_cls) or ...
python
def assignment_action(self, text, loc, assign): """Code executed after recognising an assignment statement""" exshared.setpos(loc, text) if DEBUG > 0: print("ASSIGN:",assign) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return var_index = ...
python
def init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
python
def destroy(self, eip_or_aid, disassociate=False): """Release an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. Setting disassociate to True will attempt to disassociate the IP before releasing it (required for associated no...
java
public SimpleListHolder<T> getFlatAbove() { if (flatAbove == null) { flatAbove = newSimpleListHolder(above, getSortProperty()); } return flatAbove; }
python
def plot_account(self, row, per_capita=False, sector=None, file_name=False, file_dpi=600, population=None, **kwargs): """ Plots D_pba, D_cba, D_imp and D_exp for the specified row (account) Plot either the total country accounts or for a specific sector, ...
java
public void setApiKeyIdPropertyName(String apiKeyIdPropertyName) { this.clientBuilder.setApiKey(ApiKeys.builder().setIdPropertyName(apiKeyIdPropertyName).build()); }
python
def reset_error_status(self): """ Check if the dyn_env has got any exception when executing the steps and restore the value of status to False. :return: True if any exception has been raised when executing steps """ try: return self.feature_error or self.scenario_erro...
python
def __callback (self, rgb, d): ''' Callback function to receive and save Rgbd Scans. @param rgb: ROS color Image to translate @param d: ROS depth image to translate @type rgb: ImageROS @type d: ImageROS ''' data = Images2Rgbd(rgb, d) self.lo...
java
public static <E> Iterator<E> dropWhile(Iterator<E> iterator, Predicate<E> predicate) { return new FilteringIterator<E>(iterator, new DropWhile<E>(predicate)); }
python
def _get_gene2pubmed(self, limit): """ Loops through the gene2pubmed file and adds a simple triple to say that a given publication is_about a gene. Publications are added as NamedIndividuals. These are filtered on the taxon. :param limit: :return: """ ...
python
def call_plac(f): "Decorator to create a simple CLI from `func` using `plac`" name = inspect.currentframe().f_back.f_globals['__name__'] if name == '__main__': import plac res = plac.call(f) if callable(res): res() else: return f
java
public void registerBufferPool(BufferPool bufferPool) { checkArgument(bufferPool.getNumberOfRequiredMemorySegments() >= getNumberOfSubpartitions(), "Bug in result partition setup logic: Buffer pool has not enough guaranteed buffers for this result partition."); checkState(this.bufferPool == null, "Bug in resul...
java
public static Method getSingleAbstractMethod(Class<?> baseClass) { if (!baseClass.isInterface()) { throw new InvalidTypesException("Given class: " + baseClass + "is not a FunctionalInterface."); } Method sam = null; for (Method method : baseClass.getMethods()) { if (Modifier.isAbstract(method.getModifie...
java
@VisibleForTesting HeaderCacheElement getHeaderUnsafe(long timeout, TimeUnit timeUnit) { // Optimize for the common case: do a volatile read to peek for a Good cache value HeaderCacheElement headerCacheUnsync = this.headerCache; // TODO(igorbernstein2): figure out how to make this work with appengine req...
python
def complete_classname(classname): """ Attempts to complete a partial classname like '.J48' and returns the full classname if a single match was found, otherwise an exception is raised. :param classname: the partial classname to expand :type classname: str :return: the full classname :rtype...
java
private int buildLookUpTable() { int i = 0; int incDen = Math.round(8F * radiusMinPixel); // increment denominator lut = new int[2][incDen][depth]; for( int radius = radiusMinPixel; radius <= radiusMaxPixel; radius = radius + radiusIncPixel ) { i = 0; for( int inc...
java
private ImmutableList<Function> getAtomsForGenerators(Collection<TreeWitnessGenerator> gens, Term r0) { return TreeWitnessGenerator.getMaximalBasicConcepts(gens, reasoner).stream() .map(con -> { log.debug(" BASIC CONCEPT: {}", con); if (con instanceof OClass) { return atomFactory.getMutableTripl...
python
def expand(self, msgpos): """expand message at given position""" MT = self._tree[msgpos] MT.expand(MT.root)
python
def _create_metadata_from_state(self, state, ts): """ state must be disired or reported stype dict object replces primitive type with {"timestamp": ts} in dict """ if state is None: return None def _f(elem, ts): if isinstance(elem, dict): ...
java
String getColIsNullable(int i) { ColumnSchema column = table.getColumn(i); return (column.isNullable() && !column.isPrimaryKey()) ? "YES" : "NO"; }
java
@Deprecated public void setCellMerge(final String pos, final int rowMerge, final int columnMerge) throws FastOdsException, IOException { this.builder.setCellMerge(this, this.appender, pos, rowMerge, columnMerge); }
java
@Override public String getValue() throws WidgetException { List<WebElement> elements = findElements(); for (WebElement we : elements) { if (we.getAttribute("checked") != null && we.getAttribute("checked").equalsIgnoreCase("true")) { return we.getAttri...
java
public static String getClassName(Class<?> c) { String name = c.getName(); return name.substring(name.lastIndexOf('.') + 1, name.length()); }
java
public MlsxEntry mlst(String fileName) throws IOException, ServerException { try { Reply reply = controlChannel.execute(new Command("MLST", fileName)); String replyMessage = reply.getMessage(); StringTokenizer replyLines = new StringTokenizer( ...
python
def next_frame_basic_recurrent(): """Basic 2-frame recurrent model with stochastic tower.""" hparams = basic_stochastic.next_frame_basic_stochastic_discrete() hparams.filter_double_steps = 2 hparams.hidden_size = 64 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concat_inte...
java
protected void handleUrlActivated(HyperlinkEvent e, URL url) { try { Desktop.getDesktop().browse(url.toURI()); } catch (Exception ex) { throw new ApplicationException("Error handling URL " + url, ex); } }
python
def infer(self, sequence, reset=True, sequenceNumber=None, burnIn=2, enableFeedback=True, apicalTiebreak=True, apicalModulationBasalThreshold=True, inertia=True): """ Infer on a single given sequence. Sequence format: sequence = [ set([16, 22, 32]), # Position 0 set([13...
java
private String findErrorPage(Throwable exception) { if (exception instanceof EJBException && exception.getCause() != null) { exception = exception.getCause(); } String errorPage = WebXml.INSTANCE.findErrorPageLocation(exception); return errorPage; }
java
public static boolean isEnabled (@Nonnull final Class <?> aLoggingClass, @Nonnull final IHasErrorLevel aErrorLevelProvider) { return isEnabled (LoggerFactory.getLogger (aLoggingClass), aErrorLevelProvider.getErrorLevel ()); }
java
public void addObjectResult(ObjectResult objResult) { m_objResultList.add(objResult); // Elevate batch-level status to warning if needed. Status batchResult = getStatus(); if (batchResult == Status.OK && objResult.getStatus() != ObjectResult.Status.OK) { setSta...
python
def is_descendant_of_bank(self, id_, bank_id): """Tests if an ``Id`` is a descendant of a bank. arg: id (osid.id.Id): an ``Id`` arg: bank_id (osid.id.Id): the ``Id`` of a bank return: (boolean) - ``true`` if the ``id`` is a descendant of the ``bank_id,`` ``false``...
python
def is_symbol_wildcard(term: Any) -> bool: """Return True iff the given term is a subclass of :class:`.Symbol`.""" return isinstance(term, type) and issubclass(term, Symbol)
java
public ServiceFuture<Void> disableAsync(String jobId, DisableJobOption disableTasks, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(disableWithServiceResponseAsync(jobId, disableTasks), serviceCallback); }
python
def name(self): """The data type name.""" if self._name is None: return re.sub(r"(?<=\w)([A-Z])", r" \1", self.__class__.__name__) else: return self._name
python
def get_veto_segs(workflow, ifo, category, start_time, end_time, out_dir, veto_gen_job, tags=None, execute_now=False): """ Obtain veto segments for the selected ifo and veto category and add the job to generate this to the workflow. Parameters ----------- workflow: pycbc.workf...
java
public static void copyReader(OutputStream outs, Reader reader) throws IOException { try { OutputStreamWriter writer = new OutputStreamWriter(outs, StandardCharsets.UTF_8); char[] bytes = new char[1024]; int r = reader.read(bytes); while (r > 0) { ...
java
public double getTorsionAngle(Point3d a, Point3d b, Point3d c, Point3d d) { Vector3d ab = new Vector3d(a.x - b.x, a.y - b.y, a.z - b.z); Vector3d cb = new Vector3d(c.x - b.x, c.y - b.y, c.z - b.z); Vector3d dc = new Vector3d(d.x - c.x, d.y - c.y, d.z - c.z); Vector3d bc = new Vector3d(b....
python
def base_query(cls, db_session=None): """ returns base query for specific service :param db_session: :return: query """ db_session = get_db_session(db_session) return db_session.query(cls.model)
java
@SafeVarargs public static Query query(DB db, String sql, Object... args) { return new Query(db, sql, args); }
python
def _encode_mapping(mapping, f): """Encodes the mapping items in lexical order (spec)""" f.write(_TYPE_DICT) for key, value in sorted(mapping.items()): _encode_buffer(key, f) bencode(value, f) f.write(_TYPE_END)
python
def decode_bu64(b): """Encode bytes to a URL safe flavor of Base64 used by JWTs. - Reverse of encode_bu64(). Args: b: bytes URL safe Base64 encoded bytes to encode. Returns: bytes: Decoded bytes. """ s = b s = s.replace(b'-', b'+') s = s.replace(b'_', b'/') p ...
java
public void terminateConnectionsAssociatedWithChain(String chainName) throws Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(this, tc, "terminateConnectionsAssociatedWithChain", chainName); synchronized (endPointToGroupMap) { try { ...
java
void rollback() { switch (data_type) { case Tango_DEV_BOOLEAN : bool_val = old_bool_val; break; case Tango_DEV_SHORT : short_val = old_short_val; break; case Tango_DEV_LONG : long_val = old_long_val; break; case Tango_DEV_LONG64 : long64_val = old_long64_val; break; ca...
java
@Override protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) throws SMBProtocolDecodingException { int start = bufferIndex; int structureSize = SMBUtil.readInt2(buffer, bufferIndex); if ( structureSize != 89 ) { throw new SMBProtocolDecodingException("Structure...
java
@VisibleForTesting void setAdditionalProperties(Map<String, String> props) { props.put(SonarProperties.INCLUDE_FILES, StringUtils.join(files, ", ")); props.put(SonarProperties.SCM_ENABLED, "false"); props.put(SonarProperties.SCM_STAT_ENABLED, "false"); props.put(SonarProperties.ISSUE...
java
@Override protected Operand createAndExpression(final Operand leftExpression, final Operand rightExpression) { if (leftExpression == null || rightExpression == null) { return null; } final Set<Operand> operands = new HashSet<Operand>(); operands.add(leftExpression); ...
python
def insert_file(self, f, namespace, timestamp): """Inserts a file to the doc dict. """ doc = f.get_metadata() doc["content"] = f.read() self.doc_dict[f._id] = Entry(doc=doc, ns=namespace, ts=timestamp)
python
def get_graphviz_dirtree(self, engine="automatic", **kwargs): """ Generate directory graph in the DOT language. The graph show the files and directories in the node workdir. Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph> """ if eng...
python
def wrapper(self, updateParams=None): """ create wrapper for flask app route """ def decorator(f): _headers = self._getHeaders(updateParams) """ flask decorator to include headers """ @wraps(f) def decorated_function(*args, **kwargs): resp = make_response(f(*args, **kwargs)) self._setRespHeader(...
python
def _stable_names(self): ''' This private method extracts the element names from stable_el. Note that stable_names is a misnomer as stable_el also contains unstable element names with a number 999 for the *stable* mass numbers. (?!??) ''' stable_names=[] ...
java
public Filter label(@Nonnull String label) { Preconditions.checkNotNull(label); return new SimpleFilter(RowFilter.newBuilder().setApplyLabelTransformer(label).build()); }
java
@Override public void onActivityDestroyed(Activity activity) { HMSAgentLog.d("onDestroyed:" + StrUtils.objDesc(activity)); removeActivity(activity); // activity onDestroyed 事件回调 | Activity Ondestroyed Event Callback List<IActivityDestroyedCallback> tmdCallbacks = new ArrayList...
python
def get_installed_distributions(local_only=True, skip=stdlib_pkgs, include_editables=True, editables_only=False, user_only=False): # type: (bool, Container[str], bool, bool, bool) -> List[...
python
def tree_attribute(identifier): """ Predicate that returns True for custom attributes added to AttrTrees that are not methods, properties or internal attributes. These custom attributes start with a capitalized character when applicable (not applicable to underscore or certain unicode characters) ...
python
def in_place( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, ): """ A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects,...
java
private HttpUriRequest createPostMethod(final ServerDetails serverDetails, final IndexCommand command) throws URISyntaxException { LOGGER.trace("createPostMethod() called..."); final HttpPost httpPost = new HttpPost(createIndexCommandURI(serverDetails, command)); httpPost.setEntity(new PostData...
java
public void marshall(SMSMessage sMSMessage, ProtocolMarshaller protocolMarshaller) { if (sMSMessage == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(sMSMessage.getBody(), BODY_BINDING); ...
java
public static <R> Stream<R> zip(final LongIterator a, final LongIterator b, final LongIterator c, final LongTriFunction<R> zipFunction) { return new IteratorStream<>(new ObjIteratorEx<R>() { @Override public boolean hasNext() { return a.hasNext() && b.hasNext() && c.h...
python
def sendEmail(self, emails, mass_type='SingleEmailMessage'): """ Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com ...
java
public com.google.api.ads.adwords.axis.v201809.cm.AppConversionAppPlatform getAppPlatform() { return appPlatform; }
java
public com.google.api.ads.admanager.axis.v201805.CompanionDeliveryOption getBuiltInCompanionDeliveryOption() { return builtInCompanionDeliveryOption; }
python
def RV_1(self): """Instantaneous RV of star 1 with respect to system center-of-mass """ return self.orbpop_long.RV * (self.orbpop_long.M2 / (self.orbpop_long.M1 + self.orbpop_long.M2))
java
public void unlink(Object source, CollectionDescriptor cds, Object referenceToUnlink) { if(cds.isMtoNRelation()) { m_broker.deleteMtoNImplementor(new MtoNImplementor(cds, source, referenceToUnlink)); } else { ClassDescriptor cld = m_broker.getC...
java
public final boolean isAccepted( String mimeType ) { if (mimeType != null && hasAcceptedMimeTypes()) { return getAcceptedMimeTypes().contains(mimeType.trim()); } return true; // accept all mime types }