language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def humanize_bytes(b, precision=1): """Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '...
python
def receive(self,message_type): """ Receive the message of the specified type and retun Args: - message_type: the type of the message to receive Returns: - the topic of the message - the message received fr...
python
def apply(self, cls, originalMemberNameList, memberName, classNamingConvention, getter, setter): """ :type cls: type :type originalMemberNameList: list(str) :type memberName: str :type classNamingConvention: INamingConvention|None """ accessorDict = self._accessorDict(memberName, classNa...
python
def get_armbian_release_field(self, field): """ Search /etc/armbian-release, if it exists, for a field and return its value, if found, otherwise None. """ field_value = None pattern = r'^' + field + r'=(.*)' try: with open("/etc/armbian-release", 'r') ...
python
def registerContract(self, contract): """ used for when callback receives a contract that isn't found in local database """ if contract.m_exchange == "": return """ if contract not in self.contracts.values(): contract_tuple = self.contract_to_tuple(contr...
python
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) ...
java
static JSType createType(boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName) { if (!shouldCreate) { return null; } return registry.getNativeType(typeName); }
python
def byte_to_channels(self, byte): """ :return: list(int) """ # pylint: disable-msg=R0201 assert isinstance(byte, int) assert byte >= 0 assert byte < 256 result = [] for offset in range(0, 8): if byte & (1 << offset): ...
java
public static MozuUrl deletePublishSetUrl(String code, String responseFields, Boolean shouldDiscard) { UrlFormatter formatter = new UrlFormatter("/api/content/publishsets/{code}?shouldDiscard={shouldDiscard}&responseFields={responseFields}"); formatter.formatUrl("code", code); formatter.formatUrl("responseFi...
java
public void add(IdentityByState param) { for (int i = 0; i < ibs.length; i++) { ibs[i] += param.ibs[i]; } }
java
public void setValidator(AutoCompleteTextView.Validator validator) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setValidator(validator); }
python
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' garden_requirements = self.config.getlist('app', 'garden_requirements', '') # have we installed the garden packages? if exists(self.gardenlibs_dir) and \ ...
java
private DataSink<T> setResources(ResourceSpec minResources, ResourceSpec preferredResources) { Preconditions.checkNotNull(minResources, "The min resources must be not null."); Preconditions.checkNotNull(preferredResources, "The preferred resources must be not null."); Preconditions.checkArgument(minResources.isVa...
java
public static Object callMethod(Object object, String methodName, Object[] parameters) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { MethodParameterPair pair = getMethodParameterPairIgnoreCase(object.getClass(), methodName, parameters); return pair.g...
java
protected TransportResult doit(String method, URI uri, String payload){ HttpURLConnection httpConnection = null; try { URL url = uri.toURL(); URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { httpConnection = (HttpURLConnection) connection; httpConnec...
java
public static Properties createPropertiesFromResource(Class<?> classObj, String resourceName) throws IOException { Properties result = new Properties(); readPropertiesFromResource(result, classObj, resourceName); return result; }
java
public static void assertTrueOrInvalidKindForAnnotationException(boolean expression, Element element, Class<? extends Annotation> annotationClazz) { if (!expression) { String msg = String.format("%s %s, only class can be annotated with @%s annotation", element.getKind(), element, annotationClazz.getSimpleN...
python
def global_logout(self, name_id, reason="", expire=None, sign=None, sign_alg=None, digest_alg=None): """ More or less a layer of indirection :-/ Bootstrapping the whole thing by finding all the IdPs that should be notified. :param name_id: The identifier of the sub...
java
public Reliability getMaxReliability() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getMaxReliability"); Reliability maxRel = aliasDest.getMaxReliability(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMa...
java
protected Object readResolve() throws InvalidObjectException { if (this.getClass() != TextAttribute.class) { throw new InvalidObjectException( "subclass didn't correctly implement readResolve"); } TextAttribute instance = (TextAttribute) instanceMap.get(getName()); ...
python
def after_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add an after request function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.after_request def func(response): return respo...
java
protected void createDtdSchema(final LmlParser parser, final Appendable appendable) throws Exception { Dtd.saveSchema(parser, appendable); }
java
public IfcConstraintEnum createIfcConstraintEnumFromString(EDataType eDataType, String initialValue) { IfcConstraintEnum result = IfcConstraintEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.get...
java
public void setVerboseDebug(final int level) { debugLevel = level; for (final String logName : logs.keySet()) { logs.get(logName).setVerboseDebug(level); } }
java
@Nonnull public static <T> LObjIntPredicateBuilder<T> objIntPredicate(Consumer<LObjIntPredicate<T>> consumer) { return new LObjIntPredicateBuilder(consumer); }
python
def depth_texture(self, size, data=None, *, samples=0, alignment=4) -> 'Texture': ''' Create a :py:class:`Texture` object. Args: size (tuple): The width and height of the texture. data (bytes): Content of the texture. Keyword Args: ...
java
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("suspensionState", this.suspensionState); persistentState.put("historyTimeToLive", this.historyTimeToLive); return persistentState; }
java
protected void configureCommandIcons(CommandIconConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); setIconInfo(configurable, objectName, false); setIconInfo(configurable, objectName, true); }
java
protected Point getTextBasePoint(String text, double xCoord, double yCoord, Graphics2D graphics) { FontMetrics fontMetrics = graphics.getFontMetrics(); Rectangle2D stringBounds = fontMetrics.getStringBounds(text, graphics); int[] point = this.transformPoint(xCoord, yCoord); int baseX = (...
python
def _update_imageinfo(self): """ calls get_imageinfo() if data image missing info """ missing = self._missing_imageinfo() deferred = self.flags.get('defer_imageinfo') continuing = self.data.get('continue') if missing and not deferred and not continuing: ...
java
public void marshall(RaidArray raidArray, ProtocolMarshaller protocolMarshaller) { if (raidArray == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(raidArray.getRaidArrayId(), RAIDARRAYID_BINDING); ...
java
public static void setPersonEmail(final String email) { dispatchConversationTask(new ConversationDispatchTask() { @Override protected boolean execute(Conversation conversation) { ApptentiveInternal.getInstance().getConversationProxy().setPersonEmail(email); return true; } }, "set person email"); }
java
public static Forest[] gets(Collection<String> keys) { return gets(keys.toArray(new String[keys.size()])); }
java
@Override public void removeAllResourses() throws Exception { synchronized (this) { if (!this.started) { throw new Exception(String.format("Management=%s not started", this.name)); } if (this.associations.size() == 0 && this.servers.size() == 0) ...
python
def generate_p_star(num_groups): """Describe the order in which groups move Arguments --------- num_groups : int Returns ------- np.ndarray Matrix P* - size (g-by-g) """ p_star = np.eye(num_groups, num_groups) rd.shuffle(p_star) return p_star
java
public <C extends Collection<? super T>> C into(C collection) { if (isParallel()) { @SuppressWarnings("unchecked") List<T> list = Arrays.asList((T[]) toArray()); collection.addAll(list); } else { Spliterator<T> spltr = spliterator(); if (collec...
java
private DeviceData checkWithHostAddress(DeviceData deviceData, DeviceProxy deviceProxy) throws DevFailed { // ToDo DevVarLongStringArray lsa = deviceData.extractLongStringArray(); try { java.net.InetAddress iadd = java.net.InetAddress.getByName(deviceProxy.get_host_name()...
python
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ ''' if get_tesseract_version() < '3.0...
python
def printer(self, message, color_level='info'): """Print Messages and Log it. :param message: item to print to screen """ if self.job_args.get('colorized'): print(cloud_utils.return_colorized(msg=message, color=color_level)) else: print(message)
python
def has_subkey(self, subkey): """ Return True if this AdfKey contains the given subkey. Parameters ---------- subkey : str or AdfKey A key name or an AdfKey object. Returns ------- has : bool True if this key contains the given ke...
python
def analyze(self, handle, filename): """Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File hash as a string """ ...
python
def assign_charge(mol, force_recalc=False): """Assign charges in physiological condition""" # TODO: not implemented yet mol.require("Aromatic") for i, nbrs in mol.neighbors_iter(): atom = mol.atom(i) nbrcnt = len(nbrs) if atom.symbol == "N": if not atom.pi: ...
python
def path( self, path=None, operations=None, summary=None, description=None, **kwargs ): """Add a new path object to the spec. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object :param str|None path: URL path component :param dict|Non...
java
public static PactDslJsonBody arrayMinLike(int minSize, int numberExamples) { if (numberExamples < minSize) { throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d", numberExamples, minSize)); } PactDslJsonArray parent = new PactDslJsonArray...
java
@Override public V putIfAbsentFailure(K key, V value, StoreAccessException e) { // FIXME: Should I care about useLoaderInAtomics? try { try { V loaded = loaderWriter.load(key); if (loaded != null) { return loaded; } } catch (Exception e1) { throw Exception...
python
def printc(cls, txt, color=colors.red): """Print in color.""" print(cls.color_txt(txt, color))
java
public boolean recordExpose() { if (!currentInfo.isExpose()) { currentInfo.setExpose(true); populated = true; return true; } else { return false; } }
java
public Context duplicate() { Context newContext = new Context(session, getIndex()); newContext.description = this.description; newContext.name = this.name; newContext.includeInRegexs = new ArrayList<>(this.includeInRegexs); newContext.includeInPatterns = new ArrayList<>(this.includeInPatterns); newCon...
java
public boolean fitsInside3D(Dimension dimension) { return fitsInside3D(dimension.getWidth(), dimension.getDepth(), dimension.getHeight()); }
python
def with_timeout(timeout, future, quiet_exceptions=()): """Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timed...
java
@Override public String getLocalHost() { if (_localName == null) { byte []localAddrBuffer = _localAddrBuffer; char []localAddrCharBuffer = _localAddrCharBuffer; if (_localAddrLength <= 0) { _localAddrLength = InetAddressUtil.createIpAddress(localAddrBuffer, ...
python
def runExperiment(): """ Experiment 1: Calculate error rate as a function of training sequence numbers :return: """ trainSeqN = [5, 10, 20, 50, 100, 200] rptPerCondition = 5 correctRateAll = np.zeros((len(trainSeqN), rptPerCondition)) missRateAll = np.zeros((len(trainSeqN), rptPerCondition)) fpRateAll...
java
void isLegal(boolean checkCdDaSubset) throws Violation { if (checkCdDaSubset) { if (leadIn < 2 * 44100) { throw new Violation("CD-DA cue sheet must have a lead-in length of at least 2 seconds"); } if (leadIn % 588 != 0) { throw new Violati...
java
@SuppressWarnings("restriction") public static long[] hash(final Memory mem, final long offsetBytes, final long lengthBytes, final long seed, final long[] hashOut) { if ((mem == null) || (mem.getCapacity() == 0L)) { return emptyOrNull(seed, hashOut); } final Object uObj = ((WritableMemory) mem...
java
private void fireOnMessage(ChannelEvent e) { List<EventListener> listeners = changes.getListenerList(AMQP); for (EventListener listener : listeners) { ChannelListener amqpListener = (ChannelListener)listener; amqpListener.onMessage(e); } }
java
@Override public void removeByCommerceNotificationTemplateId( long commerceNotificationTemplateId) { for (CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel : findByCommerceNotificationTemplateId( commerceNotificationTemplateId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)...
java
public void putObject(String bucketName, String objectName, String fileName) throws InvalidBucketNameException, NoSuchAlgorithmException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentExcepti...
python
def predict(self,function,args): """Make a prediction for the function, to which we will pass the additional arguments""" param = self.model.param_array fs = [] for p in self.chain: self.model.param_array = p fs.append(function(*args)) # reset model to sta...
java
@Override public void addField(final SchemaField field) { if (field instanceof FieldDefinition) { addField((FieldDefinition) field); } else if (field instanceof CopyFieldDefinition) { addCopyField((CopyFieldDefinition) field); } }
python
def filter_record(self, record): """ Filter a record, truncating or dropping at an 'N' """ nloc = record.seq.find('N') if nloc == -1: return record elif self.action == 'truncate': return record[:nloc] elif self.action == 'drop': ...
java
Rule Mixolydian() { return Sequence(IgnoreCase("mix"), Optional(Sequence(IgnoreCase("o"), Optional(Sequence(IgnoreCase("l"), Optional(Sequence(IgnoreCase("y"), Optional(Sequence(IgnoreCase("d"), Optional(Sequence(IgnoreCase("i"), Optional(Sequence(IgnoreCase("a"), Opt...
java
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { String keyBytes = Base64Utils.encode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes.getBytes()); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey ...
java
public static boolean doCheck(String noSignStr, String sign, String publicKey) { if (sign == null || noSignStr == null || publicKey == null) { return false; } try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64.dec...
java
public SubnetInner get(String resourceGroupName, String virtualNetworkName, String subnetName, String expand) { return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName, expand).toBlocking().single().body(); }
java
@Override public final PurchaseInvoiceLine process( final Map<String, Object> pReqVars, final PurchaseInvoiceLine pEntity, final IRequestData pRequestData) throws Exception { if (pEntity.getIsNew()) { // Beige-Orm refresh: pReqVars.put("DebtorCreditortaxDestinationdeepLevel", 2); ...
java
void choose_smartly(int ndocs, List<Document> docs) { int siz = size(); double[] closest = new double[siz]; if (siz < ndocs) ndocs = siz; int index, count = 0; index = random.nextInt(siz); // initial center docs.add(documents_.get(index)); ++coun...
python
def sense_tta(self, target): """Activate the RF field and probe for a Type A Target. The PN531 can discover some Type A Targets (Type 2 Tag and Type 4A Tag) at 106 kbps. Type 1 Tags (Jewel/Topaz) are completely unsupported. Because the firmware does not evaluate the SENS_RES bef...
python
def marginal_zero(repertoire, node_index): """Return the marginal probability that the node is OFF.""" index = [slice(None)] * repertoire.ndim index[node_index] = 0 return repertoire[tuple(index)].sum()
python
def __init_go2nt_w_usr(self, gos_all, usr_go2nt, prt_flds_all): """Combine GO object fields and format_txt.""" assert usr_go2nt, "go2nt HAS NO ELEMENTS" from goatools.nt_utils import get_unique_fields go2nts = [usr_go2nt, self.gosubdag.go2nt, self._get_go2nthdridx(gos_all)] usr_n...
python
def _ep_pairwise( n_items, comparisons, alpha, match_moments, max_iter, initial_state): """Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ # Static variable that a...
java
public Observable<List<SimilarFace>> findSimilarAsync(UUID faceId, FindSimilarOptionalParameter findSimilarOptionalParameter) { return findSimilarWithServiceResponseAsync(faceId, findSimilarOptionalParameter).map(new Func1<ServiceResponse<List<SimilarFace>>, List<SimilarFace>>() { @Override ...
java
public void putUnsignedInt(long i) { _buffer[_offset++] = (byte) (i >>> 24 & 0xff); _buffer[_offset++] = (byte) (i >> 16); _buffer[_offset++] = (byte) (i >> 8); _buffer[_offset++] = (byte) i; }
python
def enable_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supp...
python
def randomdate(year: int) -> datetime.date: """ gives random date in year""" if calendar.isleap(year): doy = random.randrange(366) else: doy = random.randrange(365) return datetime.date(year, 1, 1) + datetime.timedelta(days=doy)
python
def meaning(phrase, source_lang="en", dest_lang="en", format="json"): """ make calls to the glosbe API :param phrase: word for which meaning is to be found :param source_lang: Defaults to : "en" :param dest_lang: Defaults to : "en" For eg: "fr" for french :param format: ...
python
def sample_indexes(segyfile, t0=0.0, dt_override=None): """ Creates a list of values representing the samples in a trace at depth or time. The list starts at *t0* and is incremented with am*dt* for the number of samples. If a *dt_override* is not provided it will try to find a *dt* in the file. Pa...
python
def rmatrixquaternion(q): """Create a rotation matrix from q quaternion rotation. Quaternions are typed as Numeric Python numpy.arrays of length 4. """ assert np.allclose(math.sqrt(np.dot(q,q)), 1.0) x, y, z, w = q xx = x*x xy = x*y xz = x*z xw = x*w yy = y*y yz = y*z y...
java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { Map<String, String> argsMap = new HashMap<>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("help")) { printHelp(); } System.out.print...
java
@Override public RotateIngestEndpointCredentialsResult rotateIngestEndpointCredentials(RotateIngestEndpointCredentialsRequest request) { request = beforeClientExecution(request); return executeRotateIngestEndpointCredentials(request); }
python
def power(attrs, inputs, proto_obj): """Returns element-wise result of base element raised to powers from exp element.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'exponent':'exp'}) if 'broadcast' in attrs: new_attrs = translation_utils._remove_attributes(new_attrs, ['broadcast']) ...
java
public static Database change_db_obj(final String host, final String port) throws DevFailed { return apiutilDAO.change_db_obj(host, port); }
python
def make_plot( self, count, plot=None, show=False, plottype='probability', bar=dict(alpha=0.15, color='b', linewidth=1.0, edgecolor='b'), errorbar=dict(fmt='b.'), gaussian=dict(ls='--', c='r') ): """ Convert histogram counts in array ``count`` into a plot. Args: ...
python
def has_module (name, without_error=True): """Test if given module can be imported. @param without_error: True if module must not throw any errors when importing @return: flag if import is successful @rtype: bool """ try: importlib.import_module(name) return True except Impor...
java
public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) { return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types); }
python
def poll(self, poll_rate=None, timeout=None): """Return the status of a task or timeout. There are several API calls that trigger asynchronous tasks, such as synchronizing a repository, or publishing or promoting a content view. It is possible to check on the status of a task if you kno...
python
def _ensure_session(self, session=None): """If provided session is None, lend a temporary session.""" if session: return session try: # Don't make implicit sessions causally consistent. Applications # should always opt-in. return self.__start_sess...
java
public void set(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; }
java
public static Path get(String appName) { final Path applicationDataDirectory = getPath(appName); try { Files.createDirectories(applicationDataDirectory); } catch (IOException ioe) { throw new RuntimeException("Couldn't find/create AppDataDirectory", ioe); } ...
java
@Nonnull public static <T> T checkNotNull(T object, @Nonnull String message) { if (object == null) { throw new NullPointerException(message); } return object; }
java
public ClusterListener createClusterListener(boolean localOnly) { if (localOnly) return new NoClusterListener(); HazelcastInstance hazelcast = getHazelcastInstance(vertx); if (hazelcast != null) { return new HazelcastClusterListener(hazelcast, vertx); } else { return new NoClusterListener();...
python
def _start_watching_events(self, replace=False): """Start the events reflector If replace=False and the event reflector is already running, do nothing. If replace=True, a running pod reflector will be stopped and a new one started (for recovering from possible errors). ...
java
@Override public void sendSubscriptionRequest(String fromParticipantId, Set<DiscoveryEntryWithMetaInfo> toDiscoveryEntries, SubscriptionRequest subscriptionRequest, MessagingQos messagingQos) { ...
java
public static <K, V> KeyValueSink<K, V> asMapSink(ImmutableMultimap.Builder<K, V> multimapB) { return new ImmutableMultimapBuilderSink<>(multimapB); }
python
def variant(case_id, variant_id): """Show a single variant.""" case_obj = app.db.case(case_id) variant = app.db.variant(case_id, variant_id) if variant is None: return abort(404, "variant not found") comments = app.db.comments(variant_id=variant.md5) template = 'sv_variant.html' if app....
java
public BuildPhase withContexts(PhaseContext... contexts) { if (this.contexts == null) { setContexts(new java.util.ArrayList<PhaseContext>(contexts.length)); } for (PhaseContext ele : contexts) { this.contexts.add(ele); } return this; }
java
@Override public Trigger.TriggerState getTriggerState(TriggerKey triggerKey, Jedis jedis){ final String triggerHashKey = redisSchema.triggerHashKey(triggerKey); Pipeline pipe = jedis.pipelined(); Map<RedisTriggerState, Response<Double>> scores = new HashMap<>(RedisTriggerState.values().lengt...
python
async def xgroup_destroy(self, name: str, group: str) -> int: """ [NOTICE] Not officially released yet XGROUP is used in order to create, destroy and manage consumer groups. :param name: name of the stream :param group: name of the consumer group """ return await ...
java
@Override public EClass getIfcAirTerminalBoxType() { if (ifcAirTerminalBoxTypeEClass == null) { ifcAirTerminalBoxTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(12); } return ifcAirTerminalBoxTypeEClass; }
java
public Stream<BASE> getUnmatchedBases() { return bases.stream().filter(base -> !baseToRaw.containsKey(base)); }
java
public AptField getField(String name) { for (AptField field : _controls) if (field.getName().equals(name)) return field; return null; }