language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def generateKey(password, bits=32): """ Generates a new encryption key based on the inputted password. :param password | <str> bits | <int> | 16 or 32 bits :return <str> """ if bits == 32: hasher = hashlib.sha256 elif bits == 16: ...
java
public static Class[] getCollectionType( PropertyDescriptor pd, boolean useGetter ) throws JSONException { Type type; if( useGetter ){ Method m = pd.getReadMethod(); type = m.getGenericReturnType(); }else{ Method m = pd.getWriteMethod(); Type[] gpts = m.ge...
java
private static void computeAnyMethodDifferences(MethodNode oMethod, MethodNode nMethod, TypeDelta td) { MethodDelta md = new MethodDelta(oMethod.name, oMethod.desc); if (oMethod.access != nMethod.access) { md.setAccessChanged(oMethod.access, nMethod.access); } // TODO annotations InsnList oInstructions = o...
python
def fetch(self, webfonts): """ Store every defined webfonts. Webfont are stored with sort on their name. Args: webfonts (dict): Dictionnary of webfont settings from ``settings.ICOMOON_WEBFONTS``. """ sorted_keys = sorted(webfonts.keys()) ...
java
private CatalogTable validatePartitionedTable(ObjectPath tablePath) throws TableNotExistException, TableNotPartitionedException { CatalogBaseTable baseTable = getTable(tablePath); if (!(baseTable instanceof CatalogTable)) { throw new CatalogException( String.format("%s in Catalog %s is not a CatalogTable...
java
public ServiceFuture<DataMigrationServiceInner> beginCreateOrUpdateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters, final ServiceCallback<DataMigrationServiceInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(groupName, servic...
python
def key(self, direction, mechanism, purviews=False, _prefix=None): """Cache key. This is the call signature of |Subsystem.find_mice()|.""" return "subsys:{}:{}:{}:{}:{}".format( self.subsystem_hash, _prefix, direction, mechanism, purviews)
java
public static IRubyObject makeTime(Ruby runtime, Pointer str, int len) { // System.err.println("makeTime(" + new String(str.buffer, str.start, len) + ")"); int ptr = str.start; int pend = ptr + len; IRubyObject year = runtime.newFixnum(0); IRubyObject mon = runtime.newFixnum(0); ...
python
def find_chunks(self, tokens, **kwargs): """ Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. """ # [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] => # [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", ...
python
def get_queryset(self): """Get queryset based on url params(<app>, <mode>) if model is not set on class""" if self.queryset is None and not self.model: try: return self.get_model_class()._default_manager.all() except LookupError: raise Http404() ...
java
public void startWithInitialObservation(O observation, Collection<S> candidates, Map<S, Double> emissionLogProbabilities) { initializeStateProbabilities(observation, candidates, emissionLogProbabilities); }
java
public List<Post> selectPosts(final Post.Type type, final Post.Status status, final Post.Sort sort, final Paging paging, final boolean withResolve) throws SQLException { return selec...
python
def from_file(self, vasprun_file): """Get a vasprun.xml file and return a VasprunLoader""" vrun_obj = Vasprun(vasprun_file, parse_projected_eigen=True) return VasprunLoader(vrun_obj)
python
def create_build_process(process_type, working_dir, build_system, package=None, vcs=None, ensure_latest=True, skip_repo_errors=False, ignore_existing_tag=False, verbose=False, quiet=False): """Create a `BuildProcess` instance.""" from rez.plugin_managers import ...
python
def make_auc_structure(score_structure): """ calculates ROC data points and returns roc_structure, a modified form of the score_structure format :param score_structure: list [(id, best_score, best_query, status, net decoy count, net active count), ..., ] :return auc_structure: list [(id, best_score, bes...
python
def find_files(self, word): """Yield matching directory or file names. :param word: :return: iterable """ base_path, last_path, position = parse_path(word) paths = suggest_path(word) for name in sorted(paths): suggestion = complete_path(name, last_path...
java
protected I_CmsContextMenuEntry createTemplateContextSelectionMenuEntry(CmsUUID structureId) { final CmsTemplateContextInfo info = m_controller.getData().getTemplateContextInfo(); if ((info.getCookieName() != null) && info.shouldShowTemplateContextContextMenuEntry()) { CmsContextMenuEntry p...
python
def draw(self, figure): """ Draw watermark Parameters ---------- figure : Matplotlib.figure.Figure Matplolib figure on which to draw """ X = mimage.imread(self.filename) figure.figimage(X, **self.kwargs)
java
public Content setImages(Map<String, Map<String, String>> images) { this.images = images; return this; }
python
def _init_metadata(self): """stub""" self._choice_ids_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'choice_ids'), 'element_label': 'response set', 'ins...
python
def _select_input(self): """Select current line (without selecting console prompt)""" line, index = self.get_position('eof') if self.current_prompt_pos is None: pline, pindex = line, index else: pline, pindex = self.current_prompt_pos self.setSelect...
java
@Override protected URL setURL(AnalyzedTokenReadings token) throws MalformedURLException { if (token != null) { List<AnalyzedToken> readings = token.getReadings(); List<String> lemmas = new ArrayList<>(); for (AnalyzedToken reading : readings) { String lemma = reading.getLemma(); ...
java
private boolean isCheckedException(TypeMirror t) { return !(env.types.isAssignable(t, env.java_lang_Error) || env.types.isAssignable(t, env.java_lang_RuntimeException)); }
java
public TerminalEmulatorDeviceConfiguration withClipboardAvailable(boolean clipboardAvailable) { if(this.clipboardAvailable == clipboardAvailable) { return this; } else { return new TerminalEmulatorDeviceConfiguration( this.lineBufferScrollbackSize, ...
python
def order_by_line_nos(objs, line_nos): """Orders the set of `objs` by `line_nos` """ ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__) return [objs[i] for i in ordering]
java
public static DesiredCapabilities retrieveCustomCapabilities(Class<? extends DefaultCapabilitiesBuilder> builder) { logger.entering(builder); DesiredCapabilities caps = new DesiredCapabilities(); if (builder != null && !builder.getName().equals(DefaultCapabilitiesBuilder.class.getName())) { ...
python
def _wrap_output(self, output, index, names=None): """ common agg/transform wrapping logic """ output = output[self._selection_name] if names is not None: return DataFrame(output, index=index, columns=names) else: name = self._selection_name if name i...
java
@Override protected void checkPath(Path path) { if (conf.getBoolean("client.configuration.lookup.done", false)) { URI uri = path.toUri(); String thisScheme = this.getUri().getScheme(); String thatScheme = uri.getScheme(); String thisHost = fsName.getHost(); String thatHost = uri.getH...
java
Session createSession(final DatabaseId db) throws SpannerException { final Map<SpannerRpc.Option, ?> options = optionMap(SessionOption.channelHint(random.nextLong())); Span span = tracer.spanBuilder(CREATE_SESSION).startSpan(); try (Scope s = tracer.withSpan(span)) { com.google.spanner.v1.Sess...
java
public static boolean isNullValue(Entity entity, Attribute attribute) { boolean isNullValue; String attributeName = attribute.getName(); AttributeType attributeType = attribute.getDataType(); switch (attributeType) { case BOOL: isNullValue = entity.getBoolean(attributeName) == null; ...
java
@Override public IndexFacesResult indexFaces(IndexFacesRequest request) { request = beforeClientExecution(request); return executeIndexFaces(request); }
java
@Override public EClass getIfcCsgSelect() { if (ifcCsgSelectEClass == null) { ifcCsgSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(1125); } return ifcCsgSelectEClass; }
java
public static vpnparameter get(nitro_service service, options option) throws Exception{ vpnparameter obj = new vpnparameter(); vpnparameter[] response = (vpnparameter[])obj.get_resources(service,option); return response[0]; }
java
@Override public boolean setReactantCoefficients(Double[] coefficients) { boolean result = reactants.setMultipliers(coefficients); notifyChanged(); return result; }
java
public void copyToLocalFile(Path src, Path dst, boolean copyCrc) throws IOException { if (!fs.isDirectory(src)) { // source is a file fs.copyToLocalFile(src, dst); FileSystem localFs = getLocal(getConf()).getRawFileSystem(); if (localFs.isDirectory(dst)) { dst = new Path(dst, src.getNa...
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectPropertyAssertionAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
public static ResourceLoader getModuleResourceLoader(final String rootPath, final String loaderPath, final String loaderName) { if (Holder.JAR_FILE != null) { return new JarFileResourceLoader(loaderName, Holder.JAR_FILE, Holder.FILE_SYSTEM.getPath(rootPath, loaderPath).toString()); } ...
python
def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copie...
java
public long size() { int size = 0; for (LogSegment seg : segments.getView()) { size += seg.size(); } return size; }
python
def send_message(self, message, all_credentials): """Send an unacknowledged message to MongoDB. Can raise ConnectionFailure. :Parameters: - `message`: (request_id, data). - `all_credentials`: dict, maps auth source to MongoCredential. """ _, data, max_doc_si...
java
protected void setWsMessageRouter(WsMessageRouter msgRouter) { internalMessageRouter.set(msgRouter); // Pass the earlierMessages queue to the router. // Now that the internalMessageRouter is non-null, this class will // NOT add any more messages to the earlierMessages queue. // ...
python
def generate_tokens(doc, regex=CRE_TOKEN, strip=True, nonwords=False): r"""Return a sequence of words or tokens, using a re.match iteratively through the str >>> doc = "John D. Rock\n\nObjective: \n\tSeeking a position as Software --Architect-- / _Project Lead_ that can utilize my expertise and" >>> doc +=...
python
def _prepdata(self): """Adds potentially missing items to the geojson dictionary""" # if missing, compute and add bbox if not self._data.get("bbox"): self.update_bbox() # if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html if...
python
def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """ assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
python
def cancel(self): """ Cancels the job. Functions should check the #Job.cancelled flag from time to time to be able to abort pre-emptively if the job was cancelled instead of running forever. """ with synchronized(self): cancelled = self.__cancelled if not cancelled: self.__c...
java
public OvhLoadBalancingTask loadBalancing_serviceName_importCustomSsl_POST(String serviceName, String certificate, String chain, String key) throws IOException { String qPath = "/ip/loadBalancing/{serviceName}/importCustomSsl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<St...
python
async def process(self, object_dict): '''[for internal use] convert json/dict into python object |coro| Parameters ---------- object_dict : dict json representation of object from emby Notes ----- if a string is given, it is assumed to be an id, obj is returned. if a list is...
python
def writeCsv(self, path): """ Writes data one or many streams into one CSV file. :param path: absolute or relative file path """ self._createConfluence() with open(path, "w") as outputFile: writer = csv.writer(outputFile) headers = self.getStreamIds() fieldNames = ["timestamp"]...
python
def clusterflow_commands_table (self): """ Make a table of the Cluster Flow commands """ # I wrote this when I was tired. Sorry if it's incomprehensible. desc = '''Every Cluster Flow run will have many different commands. MultiQC splits these by whitespace, collects by the tool nam...
python
def build(self, identity, modules, strategy=constants.DEFAULT_CONFIG): ''' Wrapper of zipline run() method. Use the configuration set so far to build up the trading environment ''' # TODO Catch a problem here self.engine = TradingEngine(identity, modules, strategy) ...
java
public static JettyBootstrap startSelf() throws JettyBootstrapException { final JettyBootstrap jettyBootstrap = new JettyBootstrap(); jettyBootstrap.addSelf(); return jettyBootstrap.startServer(); }
java
public ClinicalImpressionFindingComponent addFinding() { //3 ClinicalImpressionFindingComponent t = new ClinicalImpressionFindingComponent(); if (this.finding == null) this.finding = new ArrayList<ClinicalImpressionFindingComponent>(); this.finding.add(t); return t; }
java
protected static HttpEntity getHeaders(AuditSettings auditSettings) { HttpHeaders headers = new HttpHeaders(); if (!CollectionUtils.isEmpty(auditSettings.getUsernames()) && !CollectionUtils.isEmpty(auditSettings.getApiKeys())) { headers.set(STR_APIUSER, auditSettings.getUsernames().iterator(...
python
def mark_sacrificed(self,request,queryset): """An admin action for marking several animals as sacrificed. This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed. This admin act...
java
public DataMigrationServiceInner beginUpdate(String groupName, String serviceName, DataMigrationServiceInner parameters) { return beginUpdateWithServiceResponseAsync(groupName, serviceName, parameters).toBlocking().single().body(); }
python
def create_group(self, **kwargs): """ Create a group :calls: `POST /api/v1/groups/ \ <https://canvas.instructure.com/doc/api/groups.html#method.groups.create>`_ :rtype: :class:`canvasapi.group.Group` """ response = self.__requester.request( 'POST', ...
python
def md5sum(filen): '''Calculate the md5sum of a file. ''' with open(filen, 'rb') as fileh: md5 = hashlib.md5(fileh.read()) return md5.hexdigest()
java
private String executeScript(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream scriptStream) throws IOException { String result = ""; Map binding = new HashMap<>(); ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(Ext...
python
def channels_rename(self, room_id, name, **kwargs): """Changes the name of the channel.""" return self.__call_api_post('channels.rename', roomId=room_id, name=name, kwargs=kwargs)
java
protected LightweightTypeReference getActualType(/* @Nullable */ XExpression expression) { if (expression == null) return null; return state.getResolvedTypes().getActualType(expression); }
java
@Override public String getFilePath(String resourcePath) { String path = resourcePath.replace('/', File.separatorChar); return new File(baseDir, path).getAbsolutePath(); }
java
public static CharacterChromosome of( final CharSeq validCharacters, final IntRange lengthRange ) { return new CharacterChromosome( CharacterGene.seq(validCharacters, lengthRange), lengthRange ); }
python
def get_specification(version: str) -> Mapping[str, Any]: """Get BEL Specification The json file this depends on is generated by belspec_yaml2json as part of the update_specifications function Args: version: e.g. 2.0.0 where the filename """ spec_dir = config["bel"]["lang"]["specifica...
python
def asok(cluster, hostname): """ Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.asok('mycluster', 'myhostname') /var/run/ceph/mycluster-mon.myhostname.asok """ asok_file = '%s-mon.%s.asok' % (cluster, hostname) return join(constants.base_run_path, asok_fi...
python
def create_keys_in(): """ Create a grammer for the 'KEYS IN' clause used for queries """ keys = Group( Optional(Suppress("(")) + value + Optional(Suppress(",") + value) + Optional(Suppress(")")) ) return (Suppress(upkey("keys") + upkey("in")) + delimitedList(keys)).setRes...
java
public EquivalenceList deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { EquivalenceList equivalenceList = new EquivalenceList(); JsonArray jsonArrayOfEquivalences = json.getAsJsonArray(); for (int i = 0; i < jsonArr...
python
def getmlsthelper(referencefilepath, start, organism, update): """Prepares to run the getmlst.py script provided in SRST2""" from accessoryFunctions.accessoryFunctions import GenObject # Initialise a set to for the organism(s) for which new alleles and profiles are desired organismset = set() # Allo...
java
static Animation buildDefaultSlideOutUpAnimation(View croutonView) { if (!areLastMeasuredOutAnimationHeightAndCurrentEqual(croutonView) || (null == slideOutUpAnimation)) { slideOutUpAnimation = new TranslateAnimation( 0, 0, // X: from, to 0, -croutonView.getMeasur...
python
def stop(self): """ Stop the node gracefully. Raise if any stop-time error occurred on any subtask """ if self.stop_event.ready(): # not started return # Needs to come before any greenlets joining self.stop_event.set() # Filters must be uninstalled after the alarm ...
java
@Override public String getCode() { String pkg = getPackage(); if (!StringUtils.isEmpty(pkg)) { pkg = "package " + pkg + ";"; } // set package templator.setVariable("package", pkg); // add loop block for import packages genImportCode()...
java
public boolean isCompatible(Schema target) { if (equals(target)) { return true; } Multimap<String, String> recordCompared = HashMultimap.create(); return checkCompatible(target, recordCompared); }
python
def _make_sql_params(self,kw): """Make a list of strings to pass to an SQL statement from the dictionary kw with Python types""" return ['%s=?' %k for k in kw.keys() ] for k,v in kw.iteritems(): vals.append('%s=?' %k) return vals
java
private final void initialize_beanO_vectors() //d173022.2 { // ensure allocation not just done in another thread via an enlist call if (ivBeanOsEnlistedInTx == false) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(tc, "Lazy beanOs vect...
python
def symmetrize(W, method='average'): r""" Symmetrize a square matrix. Parameters ---------- W : array_like Square matrix to be symmetrized method : string * 'average' : symmetrize by averaging with the transpose. Most useful when transforming a directed graph to an und...
java
@When("^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')?( based on '([^:]+?)')?( as '(json|string|gov)')?$") public void sendRequestNoDataTable(String requestType, String endPoint, String foo, String loginInfo, String bar, String baseData, String baz, String type) throws Exception { ...
python
def GeneratePipPackage(args): """Generate a client as a pip-installable tarball.""" discovery_doc = _GetDiscoveryDocFromFlags(args) package = discovery_doc['name'] original_outdir = os.path.expanduser(args.outdir) args.outdir = os.path.join( args.outdir, 'apitools/clients/%s' % package) ...
python
def readElement(self): """ Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. """ pos = self.stream.tell() try: t = self.stream.read(1) except IO...
java
public static double add(Double v1, Double v2) { return add((Number) v1, (Number) v2).doubleValue(); }
python
def displayValue(self, vocab, value, widget): """Overwrite the Script (Python) `displayValue.py` located at `Products.Archetypes.skins.archetypes` to handle the references of our Picklist Widget (Methods) gracefully. This method gets called by the `picklist.pt` template like thi...
java
public CrawlDatum next(){ int topN = getConf().getTopN(); int maxExecuteCount = getConf().getOrDefault(Configuration.KEY_MAX_EXECUTE_COUNT, Integer.MAX_VALUE); if(topN > 0 && totalGenerate >= topN){ return null; } CrawlDatum datum; while (true) { ...
java
public static void createProjectSkeleton( File targetDirectory, CreationBean creationBean ) throws IOException { if( creationBean.isMavenProject()) createMavenProject( targetDirectory, creationBean ); else createSimpleProject( targetDirectory, creationBean ); }
java
@Override protected boolean attach(ISOBUSSocket sock) { Set<PGN> pgns; ISOBlueCommand cmd; StringBuilder s = new StringBuilder(); if (!super.attach(sock)) { return false; } pgns = sock.getPgns(); s.append(String.format("%05x", pgns.size())); ...
java
public Element createElementNS(String ns, String tag) { return createElementNS(ns, tag, null); }
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. ''' super(ColumnDataChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_column_data_changed'): receiver...
python
def get_report_html(self): """ formats the project into a report in MD format - WARNING - tables missing BR """ res = '<h2>Project:' + self.nme + '</h2>' res += '<p>' + self.desc + '</p>' res += '<p>' + self.fldr + '</p>' res += '<BR><h3>TABLES</h3>' ...
python
def paragraph(self, paragraph, prefix=""): """ process a pyth paragraph into the target """ content = [] for text in paragraph.content: content.append(self.text(text)) content = u"".join(content).encode("utf-8") for line in content.split("\n"): ...
python
def handle_node(pos, node): 'A node can either add B+W stones, play as B, or play as W.' props = node.properties black_stones_added = [coords.from_sgf( c) for c in props.get('AB', [])] white_stones_added = [coords.from_sgf( c) for c in props.get('AW', [])] if black_stones_added or wh...
java
public synchronized void shutdown() { shutdown.set(true); synchronized (activeWorkWrappers) { for (WorkWrapper ww : activeWorkWrappers) { ww.getWork().release(); } } if (scheduledExecutorService != null) { if (scheduledGraceful != ...
python
def args(self, args): '''Set additional arguments to be passed to the fitness function Args: args (dict): additional arguments ''' self._args = args self._logger.log('debug', 'Args set to {}'.format(args))
python
def get_self_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: return None
python
def new(self, length, fp, manage_fp, offset): # type: (int, BinaryIO, bool, int) -> None ''' Initialize a new Inode. Parameters: None. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('Inode is ...
java
public JSONObject makeHttpRequest(String url) throws IOException { InputStream is = null; JSONObject jObj = null; String json = null; // Making HTTP request try { is = new URL(url).openStream(); } catch (Exception ex) { Log.d("Networking", ex.g...
java
private void listContainer(File container, RelativeDirectory subdirectory, Set<JavaFileObject.Kind> fileKinds, boolean recurse, ListBuffer<JavaFileObject> resultList) { Archive archive = a...
java
public String[] getServiceDefinitions(Context context, String PID, Date asOfDateTime) throws ServerException { //m_ipRestriction.enforce(context); return da.getServiceDefinitions(context, PID, asOfDateTime)...
java
@Override public Object invoke(Object[] vals) { try { if (isStatic()) { return field.get(null); } else { return field.get(vals[0]); } } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessExceptio...
java
@SuppressWarnings("squid:S1698") private Expression literalAtom() { if (tokenizer.current().isSymbol("+") && tokenizer.next().isNumber()) { // Parse numbers with a leading + sign like +2.02 by simply ignoring the + tokenizer.consume(); } if (tokenizer.current().isNumb...
java
public static int wtf(String tag, Throwable tr) { return wtf(SUBSYSTEM.MAIN, tag, tr); }
python
def loadFile(self, fileName): """ Display the file ``fileName``. """ self.fileName = fileName # Assign QFile object with the current name. self.file = QtCore.QFile(fileName) if self.file.exists(): # Load the file into the widget and reset the undo sta...
java
public void bump(CmsClientSitemapEntry entry) { CmsDetailPageTable table = getDetailPageTable().copy(); table.bump(entry.getId()); CmsSitemapChange change = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.bumpDetailPage); change.setDetailPageInfos(table.toList()); ...
python
def basic_params1(): """A set of basic hyperparameters.""" return hparam.HParams( # If the problem consists of variable-length sequences # (see problem.batch_size_means_tokens()), then this is the number # of tokens per batch per GPU or per TPU core. Otherwise, this is # the number of examp...