language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public String getSubscribeId(String fname) throws PortalException { // see if a given subscribe id is already in the map String subId = mFnameMap.get(fname); if (subId == null) { // see if a given subscribe id is already in the layout subId = man.getSubscri...
java
public void marshall(WebhookAuthConfiguration webhookAuthConfiguration, ProtocolMarshaller protocolMarshaller) { if (webhookAuthConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(webhook...
java
public static boolean sdCardIsAvailable() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return Environment.getExternalStorageDirectory().canWrite(); } else return false; }
java
public boolean validate(URL url) throws SAXException { String xmlText = null; try { xmlText = IOUtils.toString(url.openStream()); } catch (IOException e) { throw new RuntimeException(e); } return validate(xmlText); }
java
void write(File f) throws FileNotFoundException, IOException { try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f))) { os.writeObject(this); } }
python
def format_explanation(explanation, original_msg=None): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visi...
java
@Override public List<CommerceDiscount> getCommerceDiscountsByUuidAndCompanyId( String uuid, long companyId) { return commerceDiscountPersistence.findByUuid_C(uuid, companyId); }
java
public static Object findEnumConstant(Class<?> type, String constantName) { return findEnumConstant(type, constantName, true); }
java
public void addParamPost(String name, String value) { addParam(name, value, NameValuePair.TYPE_POST_DATA); }
python
def parse_args(): """Parse the arguments to the application""" parser = argparse.ArgumentParser( description=HELPTEXT, epilog="This application is powered by elks with superpowers!") parser.add_argument('--version', action='store_true', help="Display elkme version and...
python
def untracable(object): """ Marks decorated object as non tracable. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def untracable_wrapper(*args, **kwargs): """ Marks decorated object as non tracab...
java
public synchronized XMLReader getXMLReader() throws SAXException { XMLReader reader; boolean readerInUse; if (m_readers == null) { // When the m_readers.get() method is called for the first time // on a thread, a new XMLReader will automatically be created. m...
python
def toXml(cls, data, xparent=None): """ Converts the inputted element to a Python object by looking through the IO addons for the element's tag. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <x...
python
def _generate_filter_ngrams(self, data, min_size): """Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` ...
java
public static snmpmanager[] get_filtered(nitro_service service, String filter) throws Exception{ snmpmanager obj = new snmpmanager(); options option = new options(); option.set_filter(filter); snmpmanager[] response = (snmpmanager[]) obj.getfiltered(service, option); return response; }
java
private EmoClientException asEmoClientException(UniformInterfaceException e) throws EmoClientException { throw new EmoClientException(e.getMessage(), e, toEmoResponse(e.getResponse())); }
java
public static void escapeHtml5Xml(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeHtml(text, offset, len, writer, HtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL, HtmlEscapeLevel.LEVEL_1_ONLY_MARKU...
python
def ws050(self, value=None): """ Corresponds to IDD Field `ws050` Wind speed corresponding 5.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws050` Unit: m/s if `value` is None it will not be checked against the...
java
@Override public DeleteIpGroupResult deleteIpGroup(DeleteIpGroupRequest request) { request = beforeClientExecution(request); return executeDeleteIpGroup(request); }
python
def get_labels(labels): """Create unique labels.""" label_u = unique_labels(labels) label_u_line = [i + "_line" for i in label_u] return label_u, label_u_line
java
public static void main(String[] args) { try { switch (args.length) { case 1: System.out.println(new fr.esrf.TangoApi.IORdump(args[0]).toString()); break; case 2: if (args[0].equals("-f")) { System.out.println(new fr.esrf.TangoApi.IORdump(null, getIor(args[1])).toString()); bre...
python
def mask_by_linear_ind(self, linear_inds): """Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Im...
python
def calc_circuit_breaker_position(self, debug=False): """ Calculates the optimal position of a circuit breaker on route. Parameters ---------- debug: bool, defaults to False If True, prints process information. Returns ------- int ...
java
public static File findAbsoluteAndRelative(final String fileLocation) { final File file = new File(fileLocation); if (file.isAbsolute()) { return file; } else { return new File(getHiveMQHomeFolder(), fileLocation); } }
python
def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=False, ): """Test whether file exists, and make its contents the student code. Note: this SCT fa...
python
def set_subpixel_order(self, subpixel_order): """Changes the :ref:`SUBPIXEL_ORDER` for the font options object. The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of :obj:`SUBPIXEL <ANTIALI...
python
async def _fair_get_out_peer(self): """ Get the first available peer, with non-blocking inbox or wait until one meets the condition. :returns: The peer whose outbox is ready to be written to. """ peer = None while not peer: await self._wait_peers() ...
python
def main(): """ Get arguments from get_args and create/send the number of indications defined. Each indication is created from a template. """ opts, argparser = get_args() start_time = time() url = opts.url if re.search(r":([0-9]+)$", opts.url): if opts.listenerPort is...
python
def walk_commands(self): """An iterator that recursively walks through all commands and subcommands.""" for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
java
protected static Long getUnusedExternalStorage() { try { if (isExternalStorageMounted()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long avail...
java
public static String getAnnotationString(Annotation annotation) throws ReflectiveOperationException { Class<? extends Annotation> annotationType = annotation.annotationType(); StringBuilder annotationString = new StringBuilder(); Method[] annotationElements = filterNonEmptyElements(annotation); if (annotationEl...
java
private BaseDescr conditionalBranch(CEDescrBuilder<?, ?> ce, ConditionalBranchDescrBuilder<?> conditionalBranch) throws RecognitionException { if (conditionalBranch == null) { conditionalBranch = helper.start((DescrBuilder<?, ?>) ce, ConditionalBranchDescrBuilder.class, ...
python
def populate_from_path(bucket, source, checksum=True, key_prefix='', chunk_size=None): """Populate a ``bucket`` from all files in path. :param bucket: The bucket (instance or id) to create the object in. :param source: The file or directory path. :param checksum: If ``True`` then...
python
def generate_samples(net: BayesNet, sample_from: Iterable[Vertex], sampling_algorithm: PosteriorSamplingAlgorithm = None, drop: int = 0, down_sample_interval: int = 1, live_plot: bool = False, r...
java
@XmlElementDecl(namespace = "urn:oasis:names:tc:xacml:2.0:policy:schema:os", name = "PolicyCombinerParameters", scope = PolicySetType.class) public JAXBElement<PolicyCombinerParametersType> createPolicySetTypePolicyCombinerParameters(PolicyCombinerParametersType value) { return new JAXBElement<PolicyCombine...
python
def set_channel(self, channel): """ set_channel: records progress from constructed channel Args: channel (Channel): channel Ricecooker is creating Returns: None """ self.channel = channel self.__record_progress(Status.CREATE_TREE)
java
public StreamEx<T> collapse(BiPredicate<? super T, ? super T> collapsible, BinaryOperator<T> merger) { return collapseInternal(collapsible, Function.identity(), merger, merger); }
python
def community_topic_posts(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/posts#list-posts" api_path = "/api/v2/community/topics/{id}/posts.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
java
public void setParameters(String nameParam, String typeParam, String value) { this.parameters.put(nameParam, typeParam); this.parametersValue.add(value); }
python
def add(self, abspath_or_winfile, enable_verbose=True): """Add absolute path or WinFile to FileCollection. """ if isinstance(abspath_or_winfile, str): # abspath if abspath_or_winfile in self.files: if enable_verbose: print("'%s' already in this col...
java
public static void writeLinesToFile(final Collection<String> collection, final File output, final String encoding) throws IOException { final StringBuffer sb = new StringBuffer(); for (final String element : collection) { sb.append(element); sb.append("\n"); } WriteFileExtensions.writeStringToFile(ou...
python
def download_file_with_progress_bar(url): """Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object """ request = requests.get(url, stream=True) if request.status_code == 404: msg = ('there was a 404 error trying to reach {} \nThis probably ' ...
java
private SkeletonAndItsBestMatch genIntervalPattern( int field, String skeleton, String bestSkeleton, int differenceInfo, Map<String, PatternInfo> intervalPatterns) { SkeletonAndItsBestMatch retValue = null; PatternInfo pattern = fInfo.getIntervalPattern( ...
python
def dz_fltr(dem_fn, refdem_fn, perc=None, rangelim=(0,30), smooth=False): """Absolute elevation difference range filter using values from a source raster file and a reference raster file """ try: open(refdem_fn) except IOError: sys.exit('Unable to open reference DEM: %s' % refdem_fn) ...
java
private static void appendTaskStateValues(List<TaskState> taskStates, StringBuffer sb, String key) { // Add task failure messages in a group followed by task failure exceptions for (TaskState taskState : taskStates) { if (taskState.contains(key)) { if (sb.length() != 0) { sb.append(",");...
java
private List<Results> process( FunctionStoS f , FunctionStoS g , double ...initSteps ) { List<Results> results = new ArrayList<Results>(); for( double step : initSteps ) { results.add(performTest(f,g,step,0,Double.POSITIVE_INFINITY)); } return results; }
java
@SuppressWarnings("unchecked") public static <B> Class<? extends Builder<B>> builderFor(B built) throws CacheConfigurationException { BuiltBy builtBy = built.getClass().getAnnotation(BuiltBy.class); if (builtBy == null) { throw new CacheConfigurationException("Missing BuiltBy annotation for conf...
python
def would_move_be_promotion(self): """ Finds if move from current location would be a promotion """ return (self._end_loc.rank == 0 and not self.color) or \ (self._end_loc.rank == 7 and self.color)
java
public void addBottom(Content body) { Content bottom = new RawHtml(replaceDocRootDir(configuration.bottom)); Content small = HtmlTree.SMALL(bottom); Content p = HtmlTree.P(HtmlStyle.legalCopy, small); body.addContent(p); }
python
def get_third_party(self, third_party): """Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.""" actual_account = third_party.get_account() assert actual_account.get_bookset() == self.get_bookset() return ProjectAccount(ac...
java
private static <T> void aggregateRoutes( String method, Map<PathPattern, T> routes, List<String> accMethods, List<String> accPatterns, List<String> accTargets) { for (Map.Entry<PathPattern, T> entry : routes.entrySet()) { accMethods.add(method); accPatterns.add("/" + entry.getKey().pattern()); accTargets...
java
protected final int getLineNumber(final String lineNumber) { if (StringUtils.isNotBlank(lineNumber)) { try { return Integer.parseInt(lineNumber); } catch (NumberFormatException exception) { // ignore and return 0 } } ...
java
public void initDriverFromFile(File dbfFile, String forceEncoding) throws IOException { // Read columns from files metadata this.dbfFile = dbfFile; FileInputStream fis = new FileInputStream(dbfFile); dbaseFileReader = new DbaseFileReader(fis.getChannel(), forceEncoding); }
java
public <V3, M4, C, N, Q> V3 getScaleKeyVector(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapVector3f(m_scaleKeys, SCALE_KEY_SIZE * keyIndex + 8, 3); }
java
public void setPolicyVersionList(java.util.Collection<PolicyVersion> policyVersionList) { if (policyVersionList == null) { this.policyVersionList = null; return; } this.policyVersionList = new com.amazonaws.internal.SdkInternalList<PolicyVersion>(policyVersionList); ...
python
def replaceNode(self, cur): """Unlink the old node from its current context, prune the new one at the same place. If @cur was already inserted in a document it is first unlinked from its existing context. """ if cur is None: cur__o = None else: cur__o = cur._o ret = ...
python
def humanize_seconds(total_seconds, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): """Given time in int(seconds), return a string representing the time. If negative_frmt is not given, a negative sign is prepended to frmt and the result is wrap...
python
def fix_text(s, ignore_sym_pat=False): if not ignore_sym_pat: # Fix descriptions like D7TDB1 ( s = re.sub("([A-Z0-9]){6} \(", "", s) s = s.split(";")[0] # Fix parantheses containing names s = s.translate(None, "[]") s = s.replace("(-)", "[-]") s = s.replace("(+)", "[+]") ...
java
@SuppressWarnings("resource") public static AsyncWork<MavenPOM, Exception> load(URL pomFile, byte priority, MavenPOMLoader pomLoader, boolean fromRepository) { AsyncWork<MavenPOM, Exception> result = new AsyncWork<>(); IOProvider p = IOProviderFromURL.getInstance().get(pomFile); if (p == null) return new...
python
def query(self, req, timeout=None, metadata=None, credentials=None): """Runs query operation.""" return self.stub.Query(req, timeout=timeout, metadata=metadata, credentials=credentials)
python
def trace_incoming_web_request( self, webapp_info, url, method, headers=None, remote_address=None, str_tag=None, byte_tag=None): '''Create a tracer for an incoming webrequest. :param WebapplicationInfoHandle...
java
public static InputStream asInputStream(File file) throws IOException { Validate.notNull(file, "file is null"); return asInputStream(file.toPath()); }
python
def posnegtoggle(number): """ Toggle a number between positive and negative. The converter works as follows: - 1 > -1 - -1 > 1 - 0 > 0 :type number: number :param number: The number to toggle. """ if bool(number > 0): return number - number * 2 elif bool(number < 0)...
python
def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.D...
java
private void onEndStepProgress(Object source) { // Try to find the right step based on the source DefaultJobProgressStep step = findStep(this.currentStep, source); if (step == null) { LOGGER.warn("Could not find any matching step for source [{}]. Ignoring EndStepProgress.", ...
java
public void setStrictlyCoLocatedWith(JobVertex strictlyCoLocatedWith) { if (this.slotSharingGroup == null || this.slotSharingGroup != strictlyCoLocatedWith.slotSharingGroup) { throw new IllegalArgumentException("Strict co-location requires that both vertices are in the same slot sharing group."); } CoLocation...
java
private boolean isPathContaining(String otherPath) { if (otherPath == null) { return false; } if (DatasetDescriptorConfigKeys.DATASET_DESCRIPTOR_CONFIG_ANY.equals(this.getPath())) { return true; } if (PathUtils.isGlob(new Path(otherPath))) { return false; } GlobPattern glob...
java
public static void checkPrivateKeyPermissions(String privateKeyFile) throws IOException { for (PosixFilePermission p : PRIVATE_KEY_PERMS) { try { matchesFilePermissions(privateKeyFile, p); return; } catch (FilePermissionError e) { } } final String errorMessage = Strin...
python
def F(self, value): """State Transition matrix""" self._F = value self._F_inv = self.inv(self._F)
python
def AdjustDescriptor(self, fields): """Payload-aware metadata processor.""" for f in fields: if f.name == "args_rdf_name": f.name = "payload_type" if f.name == "args": f.name = "payload" return fields
java
@Nullable public Date getGpsDate() { String date = getString(TAG_DATE_STAMP); Rational[] timeComponents = getRationalArray(TAG_TIME_STAMP); // Make sure we have the required values if (date == null) return null; if (timeComponents == null || timeComponents.le...
python
def s15f16l(s): """Convert sequence of ICC s15Fixed16 to list of float.""" # Note: As long as float has at least 32 bits of mantissa, all # values are preserved. n = len(s) // 4 t = struct.unpack('>%dl' % n, s) return map((2**-16).__mul__, t)
java
public void select(int index) { String action = SELECTING + index + " in " + prettyOutput(); String expected = prettyOutputStart() + PRESENT_DISPLAYED_AND_ENABLED + index + SELECTED; try { if (isNotPresentDisplayedEnabledSelect(action, expected)) { return; ...
python
def add_node(self, node, xtra=None, branch=None): """ Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``...
java
static Set<JClass> discoverDirectClasses(Outline outline, Set<ClassOutline> classes) throws IllegalAccessException { Set<String> directClassNames = new LinkedHashSet<>(); for(ClassOutline classOutline : classes) { // for each field, if it's a bean, then visit it List<FieldOutlin...
java
public void retrieveReferences(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException { Iterator i = cld.getObjectReferenceDescriptors().iterator(); // turn off auto prefetching for related proxies final Class saveClassToPrefetch = classToPrefetch; ...
java
public static int getFlowDirection( int i, int j ) { int flow = -1; for( int k = 1; k < 9; k++ ) { if (ModelsSupporter.DIR[k][0] == i && ModelsSupporter.DIR[k][1] == j) { flow = k; } } return flow; }
python
def get_failed_instruments(self): """Find invalid instruments - instruments who have failed QC tests - instruments whose certificate is out of date - instruments which are disposed until next calibration test Return a dictionary with all info about expired/invalid instruments ...
python
def p_factor_id(self, p): """ factor : ID """ def resolve_id(key, context): try: return context[key] except KeyError: raise NameError("name '{}' is not defined".format(key)) p[0] = Instruction('resolve_id(key, context)', c...
python
def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. I...
java
public void initConfiguration() throws CmsConfigurationException { for (I_CmsRepository rep : m_repositoryList) { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_ADD_REPOSITORY_2, ...
java
public void marshall(GetDomainRequest getDomainRequest, ProtocolMarshaller protocolMarshaller) { if (getDomainRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getDomainRequest.getDomainName(...
python
def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick))
python
def start_refresh(self): """Start redrawing the canvas at the previously set timed interval. """ self.logger.debug("starting timed refresh interval") self.rf_flags['done'] = False self.rf_draw_count = 0 self.rf_timer_count = 0 self.rf_late_count = 0 self.r...
python
def target(self): """Thread routine""" while self.event.wait(): self.event.clear() while True: with self.lock: if not self.count: break self.count -= 1 with self.condition: ...
java
public static File toJar(File sourceDir, String jarName) { if (!sourceDir.isAbsolute()) { throw new IllegalArgumentException("Source must be expressed through absolute path"); } Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); File jarFile = new...
java
public Pattern<T, T> followedBy(final String name) { return new Pattern<>(name, this, ConsumingStrategy.SKIP_TILL_NEXT, afterMatchSkipStrategy); }
python
def mdot(*args): """ Multiply all the arguments using matrix product rules. The output is equivalent to multiplying the arguments one by one from left to right using dot(). Precedence can be controlled by creating tuples of arguments, for instance mdot(a,((b,c),d)) multiplies a (a*((b*c)*d)). ...
python
def main(): """Main Function""" alphabet = list(string.lowercase) # + ["<", ">"] # Create an SFA for the regular expression .*<t>.* sfa = SFA(alphabet) # sfa.add_arc(0,0,SetPredicate([ i for i in alphabet if i != "<" ])) # sfa.add_arc(0,1,SetPredicate(list("<"))) # # sfa.add_arc(1,2,S...
python
def multiSMC(nruns=10, nprocs=0, out_func=None, **args): """Run SMC algorithms in parallel, for different combinations of parameters. `multiSMC` relies on the `multiplexer` utility, and obeys the same logic. A basic usage is:: results = multiSMC(fk=my_fk_model, N=100, nruns=20, nprocs=0) T...
java
public ServiceCall<Value> createValue(CreateValueOptions createValueOptions) { Validator.notNull(createValueOptions, "createValueOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "entities", "values" }; String[] pathParameters = { createValueOptions.workspaceId(), createValueOptions.entit...
java
public static String signUsingRsaSha256( PrivateKey privateKey, JsonFactory jsonFactory, JsonWebSignature.Header header, JsonWebToken.Payload payload) throws GeneralSecurityException, IOException { String content = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header...
java
public static void bootstrap(final String name, String host, int port, Optional<String> hostName, boolean cleanRootLogger) { // initially configure for WARN+ GELF logging final GelfAppenderFactory gelf = new GelfAppenderFactory(); gelf.setIncludeFullMDC(true); gelf.setThreshold("WARN"); ...
java
public static boolean equalsBottomElement(final LinkedList<String> stack, final String str) { if(stack.isEmpty()) { return false; } return stack.peekLast().equals(str); }
python
def send(self, user_id, total_amount, send_name, act_name, wishing, remark, total_num=1, client_ip=None, out_trade_no=None, scene_id=None, consume_mch_id=None): """ 发送现金红包 :param user_id: 接收红包的用户在公众号下的 openid :param total_amount: 红包金额,单位分 :param send_na...
java
public void initializeResources(final String[] packageNames) throws ClassNotFoundException, IOException, URISyntaxException { initializeResources(Arrays.asList(packageNames)); }
python
async def command_callback(self, ctx, *, command=None): """|coro| The actual implementation of the help command. It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched. - :meth:`send_bot_help` - :...
python
def _jar_id(jar): """Create a string identifier for the IvyModuleRef key. :param IvyModuleRef jar: key for a resolved jar :returns: String representing the key as a maven coordinate """ if jar.rev: return '{0}:{1}:{2}'.format(jar.org, jar.name, jar.rev) else: return '{0}:{1}'.format(...
java
private FastJsonWriter close(int empty, int nonempty, String closeBracket) { int context = peek(); if (context != nonempty && context != empty) { throw new IllegalStateException("Nesting problem."); } if (deferredUnescapeName != null || deferredName != null) { throw new IllegalStateExc...
java
@Override public LocatableInputSplit getNextInputSplit(String host, int taskId) { // for a null host, we return a remote split if (host == null) { synchronized (this.remoteSplitChooser) { synchronized (this.unassigned) { LocatableInputSplitWithCount split = this.remoteSplitChooser.getNextUnassignedMi...