language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _translate_dst_oprnd(self, operand): """Translate destination operand to a SMT expression. """ if isinstance(operand, ReilRegisterOperand): return self._translate_dst_register_oprnd(operand) else: raise Exception("Invalid operand type")
java
@SuppressWarnings("unused") public final void addItemDecoration(RecyclerView.ItemDecoration decor, int index) { getRvCategories().addItemDecoration(decor, index); }
java
public int getCertNum() { for (int i = this.certChain.length - 1; i >= 0; i--) { if (!this.certChain[i].getSubjectDN().equals(this.certChain[i].getIssuerDN())) { return i + 1; } } return this.certChain.length; }
python
def concat(input_layer, concat_dim, other_tensors=None): """Concatenates input PrettyTensor with other_tensors along the specified dim. This adds the Pretty Tensor passed via input_layer to the front of the list of tensors to concat. Args: input_layer: The input layer. concat_dim: The dimension along ...
java
public static double logpdf(double x, double sigma) { if(!(x > 0.) || x == Double.POSITIVE_INFINITY) { return x == x ? Double.NEGATIVE_INFINITY : Double.NaN; } final double xs = x / sigma, xs2 = xs * xs; return xs2 < Double.POSITIVE_INFINITY ? FastMath.log(xs / sigma) - .5 * xs2 : Double.NEGATIVE_...
java
public static XMLStreamException duplicateNamedElement(final XMLExtendedStreamReader reader, final String name) { final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.duplicateNamedElement(name, reader.getLocation()); return new XMLStreamValidationException(ex.getMessage(), ...
java
public com.google.protobuf.ByteString getFullNameBytes() { java.lang.Object ref = fullName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); fullName_ = b; return b; ...
python
def stop(*args): """Call to stop running, may be called with a signum and frame parameter if called as a signal handler.""" if _debug: stop._debug("stop") global running, taskManager if args: sys.stderr.write("===== TERM Signal, %s\n" % time.strftime("%d-%b-%Y %H:%M:%S")) sys.stderr...
java
public static String[] parseUri(final String uri) { final String[] res; if (uri.startsWith(MEMORY)) { res = new String[]{MEMORY, uri.substring(MEMORY.length())}; } else { final int idx = uri.lastIndexOf('/'); Preconditions.checkState(idx > 0, "Invalid database...
python
def run_false_positive_experiment_dim( numActive = 128, dim = 500, numSamples = 1000, numDendrites = 500, synapses = 24, numTrials = 10000, ...
python
def setup_formats(self): """ Inspects its methods to see what it can convert from and to """ methods = self.get_methods() for m in methods: #Methods named "from_X" will be assumed to convert from format X to the common format if m.startswith("from_"): ...
python
def requestCheckDockerIo(origAppliance, imageName, tag): """ Checks docker.io to see if an image exists using the requests library. URL is based on the docker v2 schema. Requires that an access token be fetched first. :param str origAppliance: The full url of the docker image originally ...
java
public synchronized void setLevel(Level newLevel) throws SecurityException { if (newLevel == null) { throw new NullPointerException(); } checkPermission(); logLevel = newLevel; }
python
def addattr(self, attrname, value=None, persistent=True): """Adds an attribute to self. If persistent is True, the attribute will be made a persistent attribute. Persistent attributes are copied whenever a view or copy of this array is created. Otherwise, new views or copies of this will...
python
def annotate_arg(arg_name, with_annotation): """Adds an annotation to an injected arg. arg_name must be one of the named args of the decorated function, i.e., @annotate_arg('foo', with_annotation='something') def a_function(foo): # ... is OK, but @annotate_arg('foo', with_annotation='som...
python
def tsplit(df, shape): """Split array into two parts.""" if isinstance(df, (pd.DataFrame, pd.Series)): return df.iloc[0:shape], df.iloc[shape:] else: return df[0:shape], df[shape:]
java
public long getByteBufferAddress(ByteBuffer byteBuffer) { /* * This only works for DIRECT byte buffers. Direct ByteBuffers have a field * called "address" which * holds the physical address of the start of the buffer contents in native * memory. * This method obtains...
java
private static AWSSecurityTokenService buildStsClient(Builder builder) throws IllegalArgumentException { /** * Passing two types of credential interfaces is not permitted */ if (builder.longLivedCredentials != n...
java
public static String toFirstLower(String string) { int c = ((int) string.charAt(0)); if (c >= 65 && c <=90) { // is upper char lower = (char) (((int) string.charAt(0)) + 32); return lower + string.substring(1); } return string; }
python
def until(timeout=10, step=0.5, action=None, silent=False): """Yield until timeout""" yield started = time.time() while True: if action and not silent: log.info(action) if time.time() - started > timeout: if action and not silent: log.error("Time...
python
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return No...
java
public static boolean toBoolean(Object obj) { if (obj != null) { if (obj instanceof Boolean) { return (Boolean)obj; } else { return toBoolean(obj.toString()); } } else { return false; } }
python
def has_item(self, item_url): """ Check if the metadata for the given item is present in the cache If the max_age attribute of this Cache is set to a nonzero value, entries older than the value of max_age in seconds will be ignored :type item_url: String or Item :param ...
python
def _main_loop(self): """ Run jobs until must_stop returns True """ fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay) fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay) while not self.must_stop(): self.set_status('waiting'...
java
@RequestMapping(value = "actions/{entityType}/{id}", method = RequestMethod.GET) public Resources<Action> getActions(@PathVariable ProjectEntityType entityType, @PathVariable ID id) { return Resources.of( extensionManager.getExtensions(ProjectEntityActionExtension.class).stream() ...
python
def makebranchcomponents(data, commdct, anode="epnode"): """return the edges jointing the components of a branch""" alledges = [] objkey = 'BRANCH' cnamefield = "Component %s Name" inletfield = "Component %s Inlet Node Name" outletfield = "Component %s Outlet Node Name" numobjects = len(da...
java
public static <T extends Comparable<?>> ComparableTemplate<T> comparableTemplate(Class<? extends T> cl, Template template, Object... args) { return comparableTemplate(cl, template, ImmutableList.copyOf(args)); }
java
@Override public void deleteObjects(List<StorageResourceId> fullObjectNames) throws IOException { logger.atFine().log("deleteObjects(%s)", fullObjectNames); if (fullObjectNames.isEmpty()) { return; } // Validate that all the elements represent StorageObjects. for (StorageResourceId fullObj...
java
public final void constantDeclaratorsRest() throws RecognitionException { int constantDeclaratorsRest_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 41) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:483:5: ( constantDeclaratorRe...
python
def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self....
python
def anlzd_stdev(self, ddof=0, freq=None, **kwargs): """Annualized standard deviation with `ddof` degrees of freedom. Parameters ---------- ddof : int, default 0 Degrees of freedom, passed to pd.Series.std(). freq : str or None, default None A frequency st...
python
def get_shift_by_data(temp_hourly, lon, lat, time_zone): '''function to get max temp shift (monthly) by hourly data Parameters ---- hourly_data_obs : observed hourly data lat : latitude in DezDeg lon : longitude in DezDeg time_zone: timezone ''' d...
java
public String getNextAvailableNodeId(final String nodeId) { String result = nodeId; do { result = _primaryNodeIds.getNextNodeId(result); if(result != null && result.equals(nodeId)) { result = null; } } while(result != null && !isNodeAvailable(result)); return ...
python
def generate(minimum, maximum, local_random=random.Random()): """ Generate a random date. The generated dates are uniformly distributed. Parameters ---------- minimum : datetime object maximum : datetime object local_random : random.Random Returns ------- generated_date : ...
python
def get_category_drilldown(parser, token): """ Retrieves the specified category, its ancestors and its immediate children as an iterable. Syntax:: {% get_category_drilldown "category name" [using "app.Model"] as varname %} Example:: {% get_category_drilldown "/Grandparent/Parent"...
python
async def movehere(self, channel): """ Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to """ self.logger.debug("movehere command") # Delete the old message...
python
def autodecode(b): """ Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string """ import warnings import chardet try: return b.decode() except UnicodeError: ...
python
def merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6} >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}} >>> c = merge(a, b) >>> from pprint import pprint; pprint(c) {'a': 1, 'b': {1...
python
def _find_home_or_away(self, row): """ Determine whether the player is on the home or away team. Next to every player is their school's name. This name can be matched with the previously parsed home team's name to determine if the player is a member of the home or away team. ...
java
private void addServer(CmsSiteMatcher matcher, CmsSite site) { Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites); siteMatcherSites.put(matcher, site); setSiteMatcherSites(siteMatcherSites); }
python
def rate_limit(self): """ Simple rate limit function using redis """ rate_limited_msg = False while True: is_rate_limited = self.limit.is_rate_limited(uuid) if is_rate_limited: time.sleep(0.3) # save hammering redis if not...
python
def commits(self, branch, since=0, to=int(time.time()) + 86400): """For given branch return a list of commits. Each commit contains basic information about itself. Raises GithubException if rate limit is exceeded :param branch: git branch :type branch: str :param since: minimal timestamp for commit's com...
java
static void validateShortOption (@Nonnull final String sOpt) { // handle the single character opt if (sOpt.length () == 1) { final char ch = sOpt.charAt (0); if (!_isValidShortOpt (ch)) throw new IllegalArgumentException ("Illegal option name '" + ch + "'"); } else { ...
python
def getEvent(self, dev_id, starttime, endtime): """Retrieve events for a device entity.""" path = 'device/%s/event?startTime=%s&endTime=%s' % \ (dev_id, starttime, endtime) return self.rachio.get(path)
java
private int modularExponentation(int a, int b, int n) throws IllegalArgumentException { int result = 1; int counter; int maxBinarySize = 32; boolean[] b2Binary = new boolean[maxBinarySize]; for (counter = 0; b > 0; counter++) { if (counter >= maxBinarySize){ ...
python
def get_scaled_bounds(ax, position, *, distance=0.1, factor=200): """Get scaled bounds. Parameters ---------- ax : Axes object Axes object. position : {'UL', 'LL', 'UR', 'LR'} Position. distance : number (optional) Distance. Default is 0.1. factor : number (optional)...
python
def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
java
public String convertOBPRefCSysToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public static boolean isInsideProject(List<String> projectResources, String resourcename) { for (int i = (projectResources.size() - 1); i >= 0; i--) { String projectResource = projectResources.get(i); if (CmsResource.isFolder(projectResource)) { if (resourcename.startsWi...
java
public HttpURLConnection buildConnection(URI baseServiceUri, String tail) { try { HttpURLConnection client = (HttpURLConnection) baseServiceUri.resolve(tail).toURL().openConnection(); return client; } catch(MalformedURLException mue) { throw new EFhirClientException("Invalid Service URL",...
java
public void visit(final WebAppListener webAppListener) { NullArgumentException.validateNotNull(webAppListener, "Web app listener"); try { final EventListener listener = RegisterWebAppVisitorHS.newInstance( EventListener.class, bundleClassLoader, webAppListener.getListenerClass()); webAppL...
java
TokenRange recover(int recoveryTokenType, ParseException p) { JavaToken begin = null; if (p.currentToken != null) { begin = token(); } Token t; do { t = getNextToken(); } while (t.kind != recoveryTokenType && t.kind != EOF); JavaToken end ...
java
protected void checkGETPUTSupport() throws ServerException, IOException { if (!isFeatureSupported(FeatureList.GETPUT)) { throw new ServerException(ServerException.UNSUPPORTED_FEATURE); } if (controlChannel.isIPv6()) { throw new ServerException(ServerException...
java
private boolean addInstanceOfElement(HeaderElement root, HeaderElement elem) { // first add to the overall sequence list if (null == this.hdrSequence) { this.hdrSequence = elem; this.lastHdrInSequence = elem; } else { // find the end of the list and append thi...
python
def repval(msmt, limitsok=False): """Get a best-effort representative value as a float. This is DANGEROUS because it discards limit information, which is rarely wise. m_liminfo() or m_unwrap() are recommended instead.""" if np.isscalar(msmt): return float(msmt) if isinstance(msmt, Uval): ...
python
def _cast_output_to_type(value, typ): '''cast the value depending on the terraform type''' if typ == 'b': return bool(value) if typ == 'i': return int(value) return value
java
public Class<?> getFieldType(final String field) { final String fieldPath = buildFieldPath(field); Class<?> type = propertyTypeNavigator.getPropertyType(target.getClass(), fieldPath); if(type != null) { return type; } return getActualFieldTyp...
python
def lessThan(self, value): """ Sets the operator type to Query.Op.LessThan and sets the value to the inputted value. :param value <variant> :return <Query> :sa lessThan :usage |>>> from orb import Que...
java
public TwoPhaseMove prepareMove(Path src, Path dst) throws FileAlreadyExistsException { return new TwoPhaseMove(src, dst); }
python
def alignment(self, align): '''Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invali...
python
def unshare_project(project_id, usernames,**kwargs): """ Un-share a project with a list of users, identified by their usernames. """ user_id = kwargs.get('user_id') proj_i = _get_project(project_id) proj_i.check_share_permission(user_id) for username in usernames: user_i = _get...
python
def iter_services(self, feature=None): """ Iterates over the root-level services on the server which provides the requested feature :param feature: Feature that the service must provide (optional) :return: A generator of services JID """ # Get the list of root se...
python
def clean(self, initial_epoch): """ Remove entries from database that would get overwritten """ self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}})
java
@Override protected void defineWidgets() { // initialize the object to use for the dialog initSynchronizeSettingsObject(); setKeyPrefix(KEY_PREFIX); addWidget(new CmsWidgetDialogParameter(m_synchronizeSettings, "enabled", PAGES[0], new CmsCheckboxWidget())); addWidget( ...
java
public boolean containsOutputs( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetOutputs().getMap().containsKey(key); }
java
public void delete(Collection collection) { pm.currentTransaction().begin(); pm.deletePersistentAll(collection); pm.currentTransaction().commit(); }
python
def fit_double_lorgauss(bins,h,Ntry=5): """Uses lmfit to fit a "Double LorGauss" distribution to a provided histogram. Uses a grid of starting guesses to try to avoid local minima. Parameters ---------- bins, h : array-like Bins and heights of a histogram, as returned by, e.g., `np.histogr...
python
def _is_pid_running_on_windows(pid): """ Check if PID is running for Windows systems """ import ctypes.wintypes kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) if handle == 0: return False exit_code = ctypes.wintypes.DWORD() ret = kernel32.GetExitC...
python
def from_array(array): """ Deserialize a new InlineKeyboardButton from a given dictionary. :return: new InlineKeyboardButton instance. :rtype: InlineKeyboardButton """ if array is None or not array: return None # end if assert_type_or_raise(ar...
java
synchronized Weight getMinimumStart() { if (calcMinStart == null) { // Find the shortest distance from a start to time zero. Weight result = WeightFactory.NEG_INFINITY; if (shortestDistancesFromTimeZeroDestination == null) { shortestDistancesFromTimeZeroDestin...
java
public long insert(String table, Object record, int conflictAlgorithm) { table = formatName(table); final ContentValues contentValues = record instanceof ContentValues ? (ContentValues) record : toContentValues(record, readOnlyPropNamesMap.get(record.getClass()), columnNamingPolicy, f...
java
public static int CrowdingDistanceCompare(Solution solution1, Solution solution2) { double crowding1 = solution1.getCrowdingDistance(); double crowding2 = solution2.getCrowdingDistance(); if (crowding1 > crowding2) { return -1; } else if (crowding1 < crowding2) { ...
python
def prototype_adjacency(self, n_block_features, alpha): """Build a new graph. Doc for ".create(n_features, alpha)" Parameters ----------- n_features : int alpha : float (0,1) The complexity / sparsity factor. Each graph will have a minimum of ...
python
def affiliation_history(self): """Unordered list of IDs of all affiliations the author was affiliated with acccording to Scopus. """ affs = self._json.get('affiliation-history', {}).get('affiliation') try: return [d['@id'] for d in affs] except TypeError: # N...
java
private QueryResultList<Entity> generateResults(QueryBuilder<?> builder, boolean keysOnly) throws FalsePredicateException { QueryResultList<Entity> queryResult = prepareQuery(builder, keysOnly).asQueryResultList(configureFetchOptions(builder)); setCursor(builder, queryResult); return queryResult...
python
def delete(self, symbol, date_range=None): """ Delete all chunks for a symbol. Which are, for the moment, fully contained in the passed in date_range. Parameters ---------- symbol : `str` symbol name for the item date_range : `date.DateRange`...
java
@Override protected void loadPlugins() { pickingPlugin = new PickingGraphMousePlugin<String,String>(); scalingPlugin = new ScalingGraphMousePlugin(new CrossoverScalingControl(), 0, in, out); editingPlugin = new RoleGraphEditingPlugin(); add(scalingPlugin); setMode(Mode.EDITING); }
python
def endpointlist_post_save(instance, *args, **kwargs): """ Used to process the lines of the endpoint list. """ with open(instance.upload.file.name, mode='rb') as f: lines = f.readlines() for url in lines: if len(url) > 255: LOGGER.debug('Skipping this endpoint, as it is m...
java
public StreamingEndpointInner beginCreate(String resourceGroupName, String accountName, String streamingEndpointName, StreamingEndpointInner parameters, Boolean autoStart) { return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName, parameters, autoStart).toBlocking().sing...
java
public List<MetadataDatabase> getMetadadaDatabasesSharedFolders(ResponseListNetworkSharedFolder responseNetworkSharedFolders){ //Init the list List<MetadataDatabase> databases = new ArrayList<MetadataDatabase>(); if (null != responseNetworkSharedFolders){ for(ObjectNetworkShare networkShare : responseNet...
java
public List<MetricsResultsItem> getMultiple(String appId, List<MetricsPostBodySchema> body) { return getMultipleWithServiceResponseAsync(appId, body).toBlocking().single().body(); }
python
def add_user( self, user, first_name=None, last_name=None, email=None, password=None): """Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_name (optional[string]): User's last name. Def...
java
private boolean isNsAware(Element mathNode) { Field field; Document document = mathNode.getOwnerDocument(); try { field = document.getClass().getDeclaredField("fNamespacesEnabled"); field.setAccessible(true); return (boolean) field.get(document); } cat...
java
public Geometry getPartialEnvelopeGeometry(int indexFrom, int indexTo) { Geometry onePoly = null; Geometry prevPoly = null; if (indexFrom > indexTo || indexFrom < 0 || indexFrom > this.trajectory.getPoseSteering().length-1 || indexTo < 0 || indexTo >= this.trajectory.getPoseSteering().length) throw new Error("Ind...
python
def push(self, dir): """Push cwd on stack and change to 'dir'. """ self.stack.append(os.getcwd()) os.chdir(dir or os.getcwd())
java
public static CMBlob buildCMFile( CMFolder folder, Element xmlEntry ) throws ParseException { final String name = xmlEntry.getElementsByTagNameNS( "*", "title" ).item( 0 ).getTextContent(); final String id = xmlEntry.getElementsByTagNameNS( "*", "document" ).item( 0 ).getTextContent(); ...
java
protected void switchFactories(Gson newGson) { final Field factoriesField = DfReflectionUtil.getWholeField(newGson.getClass(), "factories"); @SuppressWarnings("unchecked") final List<Object> factories = (List<Object>) DfReflectionUtil.getValueForcedly(factoriesField, newGson); final List...
java
public static int rsHash(String str) { int b = 378551; int a = 63689; int hash = 0; for (int i = 0; i < str.length(); i++) { hash = hash * a + str.charAt(i); a = a * b; } return hash & 0x7FFFFFFF; }
java
private void checkConstructor(Node n, FunctionType functionType) { FunctionType baseConstructor = functionType.getSuperClassConstructor(); if (!Objects.equals(baseConstructor, getNativeType(OBJECT_FUNCTION_TYPE)) && baseConstructor != null && baseConstructor.isInterface()) { // Warn if a c...
python
def get(key, profile=None): ''' Get a value from the Redis SDB. ''' if not profile: return False redis_kwargs = profile.copy() redis_kwargs.pop('driver') redis_conn = redis.StrictRedis(**redis_kwargs) return redis_conn.get(key)
java
@Override @SuppressWarnings("unchecked") public <E extends M> Updater<E> on(String server) { return new EbeanUpdater(server, getModelType(), getSqlOrName()); }
java
public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, File file) throws IOException { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { writeWordVectors(lookupTable, bos); } catch (Exception e) { ...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
python
def query_ssos(self, mpc_observations, lunation_count=None): """Send a query to the SSOS web service, looking for available observations using the given track. :param mpc_observations: a list of mpc.Observations :param lunation_count: how many dark runs (+ and -) to search into :return:...
java
public Class getExceptionClass() { Class exceptionClass = null; Throwable rootCause = this; do{ Throwable temp = ((ServletException)rootCause).getRootCause(); if(temp != null) { rootCause = temp; } else{ br...
python
def GetBEDnarrowPeakgz(URL_or_PATH_TO_file): """ Reads a gz compressed BED narrow peak file from a web address or local file :param URL_or_PATH_TO_file: web address of path to local file :returns: a Pandas dataframe """ if os.path.isfile(URL_or_PATH_TO_file): response=open(URL_or_PATH...
python
def connect(self, access_key_id=None, secret_access_key=None, **kwargs): """ Opens a connection to appropriate provider, depending on provider portion of URI. Requires Credentials defined in boto config file (see boto/pyami/config.py). @type storage_uri: StorageUri @param...
python
def _hash_url(self, url): """ Hash the URL to an md5sum. """ if isinstance(url, six.text_type): url = url.encode('utf-8') return hashlib.md5(url).hexdigest()
java
public Long getLong(int index) { Number n = (Number) content.get(index); if (n == null) { return null; } else if (n instanceof Long) { return (Long) n; } else { return n.longValue(); //autoboxing to Long } }
java
@Override public Response sendToNTS(String CorpNum, MgtKeyType KeyType, String MgtKey) throws PopbillException { return sendToNTS(CorpNum, KeyType, MgtKey, null); }