language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public GetGeoMatchSetResult getGeoMatchSet(GetGeoMatchSetRequest request) { request = beforeClientExecution(request); return executeGetGeoMatchSet(request); }
java
public Float loadPreferenceAsFloat(String key, Float defaultValue) { Float value = defaultValue; if (hasPreference(key)) { value = getSharedPreferences().getFloat(key, 0); } logLoad(key, value); return value; }
java
public static CachedInstanceQuery get4Request(final Type _type) throws EFapsException { return new CachedInstanceQuery(Context.getThreadContext().getRequestId(), _type).setLifespan(5) .setLifespanUnit(TimeUnit.MINUTES); }
python
def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str] """Get country name from ISO3 code Args: iso3 (str): ISO3 code for which to get country name use_live (bool): Try to get use late...
python
def check_in_out_dates(self): """ When date_order is less then check-in date or Checkout date should be greater than the check-in date. """ if self.checkout and self.checkin: if self.checkin < self.date_order: raise ValidationError(_('Check-in date sho...
java
private void countPropertyQualifier(PropertyIdValue property, int count) { PropertyRecord propertyRecord = getPropertyRecord(property); propertyRecord.qualifierCount = propertyRecord.qualifierCount + count; }
java
public void beginStep(int step, String stepTitle, Logging logger) { setProcessed(step - 1); this.stepTitle = stepTitle; logger.progress(this); }
java
private SecureRandom createSecureRandom() { SecureRandom result; try { result = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { result = new SecureRandom(); } // Force seeding to take place. result.nextInt(); r...
python
def end(self): """Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp)""" with self.__lock: if self.__write: self.__write(compress_end(self.__ctx)) else: return compress_end(self.__ctx)
java
private void generateStaticInjection(TypeElement type, List<Element> fields) throws IOException { ClassName typeName = ClassName.get(type); ClassName adapterClassName = adapterName(ClassName.get(type), STATIC_INJECTION_SUFFIX); TypeSpec.Builder result = TypeSpec.classBuilder(adapterClassName.simpleName()) ...
java
public void register(Class<?> aClass) { List<ConstantField> tmp = inspector.getConstants(aClass); constantList.addAll(tmp); for (ConstantField constant : tmp) constants.put(constant.name, constant); }
java
public PropertyBuilder booleanType(final String name) { name(name); type(Property.Type.Boolean); return this; }
python
def partial_fit(self, X, y, classes=None): """ Runs a single epoch using the provided data :return: This instance """ return self.fit(X, y, epochs=1)
java
public void removeOverride(String operation) { if (this.overrideOnce.containsKey(operation) == true) { this.overrideOnce.remove(operation); } if (this.override.containsKey(operation) == true) { this.override.remove(operation); } }
python
def joint(letters, marks): """ joint the letters with the marks the length ot letters and marks must be equal return word @param letters: the word letters @type letters: unicode @param marks: the word marks @type marks: unicode @return: word @rtype: unicode """ # The length o...
python
def patch_lustre_path(f_path): """Patch any 60-character pathnames, to avoid a current Lustre bug.""" if CHECK_LUSTRE_PATH_LEN and len(f_path) == 60: if os.path.isabs(f_path): f_path = '/.' + f_path else: f_path = './' + f_path return f_path
java
private void createInstanceUsingConstructor() throws InvocationTargetException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "createInstanceUsingConstructor"); try { if (isTraceOn && tc.isDebugEnabled...
java
public void execNoOutput() throws Failure { String result; result = exec(); if (result.trim().length() > 0) { throw new Failure(this, builder.command().get(0) + ": unexpected output " + result); } }
java
public boolean revert() { try { setWrongValueMessage(null); setValue(propInfo.getPropertyValue(target)); updateValue(); return true; } catch (Exception e) { setWrongValueException(e); return false; } }
python
def md5(self): """ An MD5 hash of the current vertices and entities. Returns ------------ md5: str, two appended MD5 hashes """ # first MD5 the points in every entity target = '{}{}'.format( util.md5_object(bytes().join(e._bytes() ...
python
def system(session, py): """Run the system test suite.""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Run the system tests against late...
java
public void addTermReferences(TableDefinition tableDef, int shardNumber, Map<String, Set<String>> fieldTermsRefMap) { StringBuilder rowKey = new StringBuilder(); for (String fieldName : fieldTermsRefMap.keySet()) { for (String term : fieldTermsRefMap.get...
python
def salsa20_8(B, x, src, s_start, dest, d_start): """Salsa20/8 http://en.wikipedia.org/wiki/Salsa20""" # Merged blockxor for speed for i in xrange(16): x[i] = B[i] = B[i] ^ src[s_start + i] # This is the actual Salsa 20/8: four identical double rounds for i in xrange(4): a = (x[0]+...
java
public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{ aaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding(); obj.set_groupname(groupname); aaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.g...
java
public <U> BaseSimpleReactStream<U> from(final IntStream stream) { return (BaseSimpleReactStream<U>) from(stream.boxed()); }
java
public static Transport UDPInstance(SocketAddress addr) throws IOException { DatagramSocket sock = new DatagramSocket(); sock.setSoTimeout(getTimeout()); sock.connect(addr); StreamTransport trans = new StreamTransport(); trans.setStreams(new UDPInputStream(sock), new UDPOutputSt...
java
private View getNextView(RecyclerView parent) { View firstView = parent.getChildAt(0); // draw the first visible child's header at the top of the view int firstPosition = parent.getChildPosition(firstView); View firstHeader = getHeaderView(parent, firstPosition); for (int i = 0...
python
def load_config(): """ Validate the config """ configuration = MyParser() configuration.read(_config) d = configuration.as_dict() if 'jira' not in d: raise custom_exceptions.NotConfigured # Special handling of the boolean for error reporting d['jira']['error_reporting'] = ...
java
public static void encodeToFile(byte[] dataToEncode, String filename) throws IOException { if (dataToEncode == null) { throw new NullPointerException("Data to encode was null."); } Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); ...
java
public String getParameter( String name ) { if (_parameters == null || !_parameters.hasParameters()) return null; List parameters = _parameters.getParameterValues(name); if(parameters != null && parameters.size() > 0) return (String)parameters.get(0); else re...
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = GetObject.class) public JAXBElement<CmisExtensionType> createGetObjectExtension( CmisExtensionType value) { return new JAXBElement<CmisExtensionType>( _GetPropertiesExtension_QNAME, CmisExtensio...
java
@SuppressWarnings("unchecked") public static Object proprietaryEvaluate(final String expression, final Class expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; ExpressionFactory exprFactorySetInPageContext = (...
java
public void beginStop(String groupName, String serviceName) { beginStopWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body(); }
java
protected Object getValue( QueryContext context, StaticOperand operand ) { if (operand instanceof Literal) { Literal literal = (Literal)operand; return literal.value(); } BindVariableName variable = (BindVariableName)operand; return ...
java
public void requestValue(int nodeId, int endpoint) { ZWaveNode node = this.getNode(nodeId); ZWaveGetCommands zwaveCommandClass = null; SerialMessage serialMessage = null; for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SENSOR_BINARY, Z...
python
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python ...
java
public double getProd() { double prod = s.one(); for (int c = 0; c < this.values.length; c++) { prod = s.times(prod, values[c]); } return prod; }
python
def place_limit_order(self, side: Side, amount: Number, price: Number) -> Order: """Place a limit order.""" return self.place_order(side, OrderType.LIMIT, amount, price)
java
private Collection<FsItemEx> findRecursively(FsItemFilter filter, FsItem root) { List<FsItemEx> results = new ArrayList<FsItemEx>(); FsVolume vol = root.getVolume(); for (FsItem child : vol.listChildren(root)) { if (vol.isFolder(child)) { results.addAll(findRecursively(filter, child)); } els...
java
public void addExcludes(Set<String> properties) { String[] sa = new String[properties.size()]; addTo(excludes, properties.toArray(sa)); }
python
def get_command_class(self, cmd): """ Returns command class from the registry for a given ``cmd``. :param cmd: command to run (key at the registry) """ try: cmdpath = self.registry[cmd] except KeyError: raise CommandError("No such command %r" % cm...
java
public static boolean nullSafeEquals(@Nullable final Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { re...
python
def _json_default_encoder(func): """ Monkey-Patch the core json encoder library. This isn't as bad as it sounds. We override the default method so that if an object falls through and can't be encoded normally, we see if it is a Future object and return the result to be encoded. I set a spec...
java
public void removeConnection(WebSocketConnection conn) { if (conn != null) { WebSocketScope scope = getScope(conn); if (scope != null) { scope.removeConnection(conn); if (!scope.isValid()) { // scope is not valid. delete this. ...
python
def phenotype_to_res_set(phenotype, resources): """ Converts a binary string to a set containing the resources indicated by the bits in the string. Inputs: phenotype - a binary string resources - a list of string indicating which resources correspond to which indices...
java
public static int getHtmlCodeByWikiSymbol(String wikiEntity) { Entity entity = fWikiToHtml.get(wikiEntity); return entity != null ? entity.fHtmlCode : 0; }
python
def when_closed(self): """ Returns a Deferred that callback()'s (with this Circuit instance) when this circuit hits CLOSED or FAILED. """ if self.state in ['CLOSED', 'FAILED']: return defer.succeed(self) return self._when_closed.when_fired()
python
def update(self, new_details, old_details=None): ''' a method to upsert changes to a record in the table :param new_details: dictionary with updated record fields :param old_details: [optional] dictionary with original record fields :return: list of dictionaries with u...
java
public void theBestAttributes(Instance instance, AutoExpandVector<AttributeClassObserver> observersParameter) { for(int z = 0; z < instance.numAttributes() - 1; z++){ if(!instance.isMissing(z)){ int instAttIndex = modelAttIndexToInstanceAttIndex(z, instance); ArrayList<Double> attribBest = new ArrayList<...
python
def autocorrelation_plot(series, ax=None, **kwds): """ Autocorrelation plot for time series. Parameters: ----------- series: Time series ax: Matplotlib axis object, optional kwds : keywords Options to pass to matplotlib plotting method Returns: ----------- class:`matplo...
java
public static Builder overriding( ExecutableElement method, DeclaredType enclosing, Types types) { ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method); List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes(); List<? extends TypeMirror> re...
python
def module_selected(self, module_name, module_ui): """ Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI """ if self.current_button == self.module_buttons[module_name...
python
def find_vcs_root(cls, path): """Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many...
python
def delete_zombie_actions(self): """Remove actions that have a zombie status (usually timeouts) :return: None """ id_to_del = [] for act in list(self.actions.values()): if act.status == ACT_STATUS_ZOMBIE: id_to_del.append(act.uuid) # une petit...
python
def AddEventTag(self, event_tag): """Adds an event tag. Args: event_tag (EventTag): event tag. Raises: IOError: when the storage file is closed or read-only or if the event identifier type is not supported. OSError: when the storage file is closed or read-only or if t...
java
private List<OrcDataOutput> bufferFileFooter() throws IOException { List<OrcDataOutput> outputData = new ArrayList<>(); Metadata metadata = new Metadata(closedStripes.stream() .map(ClosedStripe::getStatistics) .collect(toList())); Slice metadataSl...
java
@Deprecated public static String encodeRFC2396(String url) { try { return new URI(null,url,null).toASCIIString(); } catch (URISyntaxException e) { LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen? return url; } }
python
def iso_abundance(self,isos): ''' This routine returns the abundance of a specific isotope. Isotope given as, e.g., 'Si-28' or as list ['Si-28','Si-29','Si-30'] ''' if type(isos) == list: dumb = [] for it in range(len(isos)): dumb....
java
@SuppressWarnings("rawtypes") private List<InetAddress> resolveCname(String hostname) throws NamingException { List<InetAddress> inetAddresses = new ArrayList<>(); Attributes attrs = context.getAttributes(hostname, new String[] { "CNAME" }); Attribute attr = attrs.get("CNAME"); if...
python
def update_devices(self, devices): """Update values from response of URL_DEVICES, callback if changed.""" for qspacket in devices: try: qsid = qspacket[QS_ID] except KeyError: _LOGGER.debug("Device without ID: %s", qspacket) continu...
java
public static boolean objectInstanceOf(Object object, String className) { AssertUtils.assertNotNull(object); boolean result = false; Class clazz = object.getClass(); if (clazz.getName().equals(className) == true) { result = true; } return result...
java
private void backupCoords(Point2d[] dest, IntStack stack) { for (int i = 0; i < stack.len; i++) { int v = stack.xs[i]; dest[v].x = atoms[v].getPoint2d().x; dest[v].y = atoms[v].getPoint2d().y; } }
python
def cut_value(graph, flow, cut): """ Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function on...
java
public ServiceFuture<AccountFilterInner> getAsync(String resourceGroupName, String accountName, String filterName, final ServiceCallback<AccountFilterInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, filterName), serviceCallback); }
java
public ServiceFuture<Void> exportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(exportDataWithServiceResponseAsync(resourceGroupName, name, parameters), serviceCallback); }
python
def delete(self, request, bot_id, id, format=None): """ Delete existing state --- responseMessages: - code: 401 message: Not authenticated """ return super(StateDetail, self).delete(request, bot_id, id, format)
python
def write_short_ascii(s): """ Encode a Kafka short string which represents text. :param str s: Text string (`str` on Python 3, `str` or `unicode` on Python 2) or ``None``. The string will be ASCII-encoded. :returns: length-prefixed `bytes` :raises: `struct.error` for string...
python
def create_or_update(cls, *props, **kwargs): """ Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated. Note that the post_creat...
java
public String getApplicationId() { String applicationId = null; Integer applicationIdObject = querySingleTypedResult( "PRAGMA application_id", null, GeoPackageDataType.MEDIUMINT); if (applicationIdObject != null) { try { applicationId = new String(ByteBuffer.allocate(4) .putInt(applicationIdObjec...
python
def from_array(array): """ Deserialize a new Update from a given dictionary. :return: new Update instance. :rtype: Update """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") ...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case OPERATION_ID: return isSetOperationId(); case HAS_RESULT_SET: return isSetHasResultSet(); } throw new IllegalStateException(); }
python
def _strip_invisible(s): "Remove invisible ANSI color codes." if isinstance(s, _text_type): return re.sub(_invisible_codes, "", s) else: # a bytestring return re.sub(_invisible_codes_bytes, "", s)
python
def union(self, other): """Constructs an unminimized DFA recognizing the union of the languages of two given DFAs. Args: other (DFA): The other DFA that will be used for the union operation Returns: DFA: The resulting DFA """ opera...
java
public static <T, U> void consumeIfTrue(T target1, U target2, BiPredicate<T, U> targetTester, BiConsumer<T, U> biConsumer) { consumeIfTrue(targetTester.test(target1, target2), target1, target2, biConsumer); }
python
def users(self, username=None, pk=None, **kwargs): """ Users of KE-chain. Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter. :param username: (optional) username to filter :type username: basestring or None :para...
java
private void saveParameters(String outputDir) throws IOException { logger.info("save parameters"); // save param File paramFile = new File(outputDir + "param"); //File paramFile = File.createTempFile("param", null); //paramFile.deleteOnExit(); //parameter.store(new FileOutputStream(paramFile), "model par...
python
def get_pty(self, term='vt100', width=80, height=24, width_pixels=0, height_pixels=0): """ Request a pseudo-terminal from the server. This is usually used right after creating a client channel, to ask the server to provide some basic terminal semantics for a shell invoke...
python
def get_assessment_part_item_design_session(self, proxy): """Gets the ``OsidSession`` associated with the assessment part item design service. return: (osid.assessment.authoring.AssessmentPartItemDesignSession) - an ``AssessmentPartItemDesignSession`` raise: OperationFailed - u...
java
public static DMatrixRMaj projectiveToFundamental( DMatrixRMaj P1 , DMatrixRMaj P2 , @Nullable DMatrixRMaj F21 ) { if( F21 == null ) F21 = new DMatrixRMaj(3,3); ProjectiveToIdentity p2i = new ProjectiveToIdentity(); if( !p2i.process(P1) ) throw new RuntimeException("Failed!"); DMatrixRMaj P1inv = p2i.g...
java
protected void registerSuperClassMultipleJoinedTables(ClassDescriptor cld) { /* arminw: Sadly, we can't map to sub class-descriptor, because it's not guaranteed that they exist when this method is called. Thus we map the class instance instead of the class-descriptor. *...
python
def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"): """ Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the filesystem """ value_to_set = value_to_set.strip("'").strip('"') ...
java
int CalcSubrOffsetSize(int Offset,int Size) { // Set the size to 0 int OffsetSize = 0; // Go to the beginning of the private dict seek(Offset); // Go until the end of the private dict while (getPosition() < Offset+Size) { int p1 = getPosition(); getDictItem(); int p2 = g...
java
public Schema flatten(Schema schema, boolean flattenComplexTypes) { Preconditions.checkNotNull(schema); // To help make it configurable later this.flattenedNameJoiner = FLATTENED_NAME_JOINER; this.flattenedSourceJoiner = FLATTENED_SOURCE_JOINER; Schema flattenedSchema = flatten(schema, false, flat...
java
public boolean containsMetrics( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetMetrics().getMap().containsKey(key); }
python
def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. An example configuration: ```json { "shared_id": [ "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", ...
java
public void update(final Throwable t) { // see if the exception indicates an authorization problem boolean isAuthorized = true; if (t instanceof HttpException) { HttpException httpException = (HttpException) t; if (httpException.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { isAu...
python
def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """ # Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_keys = list(VIEW_METHOD_DATA.keys())...
python
def load(fh, single=False, version=_default_version, strict=False, errors='warn'): """ Deserialize SimpleMRSs from a file (handle or filename) Args: fh (str, file): input filename or file object single: if `True`, only return the first read Xmrs object strict: deprecated; a...
java
public void voteFor(WeightedItem<T> weightedItem) { reorganizationCounter++; weightedItem.vote(); if (reorganizationCounter == maxVotesBeforeReorganization) { reorganizationCounter = 0; organizeAndAdd(null); } }
python
def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False): """ Returns desired confidence interval for provided KDE object """ if xmin is None: xmin = kde.dataset.min() if xmax is None: xmax = kde.dataset.max() x = np.linsp...
python
def box_ids(creds: dict, cred_ids: list = None) -> dict: """ Given a credentials structure and an optional list of credential identifiers (aka wallet cred-ids, referents; specify None to include all), return dict mapping each credential identifier to a box ids structure (i.e., a dict specifying its corr...
python
def main(): """ Prototype to see how an RPG simulation might be used in the AIKIF framework. The idea is to build a simple character and run a simulation to see how it succeeds in a random world against another players character character stats world locations ""...
python
def get_import_update_hash_from_outputs( outputs ): """ This is meant for NAME_IMPORT operations, which have five outputs: the OP_RETURN, the sender (i.e. the namespace owner), the name's recipient, the name's update hash, and the burn output. This method extracts the name update hash from ...
java
@Nonnull public BiMap<String, String> getOutputMapper() { final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap(); if (outputMapper == null) { return HashBiMap.create(); } return outputMapper; }
java
public Object getResultForContext(Context context) { if (context == null) { return null; } Object object = this.contextObjectResolver.resolveForObjectAndContext(null, context); if (object == null) { return null; } return object; }
python
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example...
python
def _find_neighbors(self, inst, avg_dist): """ Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN_near = [] NN_far = [] min_indices = [] max_indi...
java
protected ListenableFuture<Boolean> setData(String path, byte[] data, boolean overwrite) { final SettableFuture<Boolean> future = SettableFuture.create(); boolean ret = FileUtils.writeToFile(path, data, overwrite); safeSetFuture(future, ret); return future; }
java
public CreateGrantRequest withOperations(String... operations) { if (this.operations == null) { setOperations(new com.amazonaws.internal.SdkInternalList<String>(operations.length)); } for (String ele : operations) { this.operations.add(ele); } return this;...
java
public ResultList<Artwork> getEpisodeImages(int tvID, int seasonNumber, int episodeNumber) throws MovieDbException { return tmdbEpisodes.getEpisodeImages(tvID, seasonNumber, episodeNumber); }