language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void close(Session session) { if (session != null && session.isConnected()) { session.disconnect(); } JschSessionPool.INSTANCE.remove(session); }
python
def dump_database(id): """Backup the Postgres database locally.""" log("Generating a backup of the database on Heroku...") dump_filename = "data.dump" data_directory = "data" dump_dir = os.path.join(data_directory, id) if not os.path.exists(dump_dir): os.makedirs(dump_dir) subproce...
java
public UISelect<T> setOptions(Collection<T> elements) { if (elements == null) elements = Collections.emptyList(); optionsContainer.setElements(elements); return this; }
java
public com.squareup.okhttp.Call getUniverseMoonsMoonIdAsync(Integer moonId, String datasource, String ifNoneMatch, final ApiCallback<MoonResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getUniverseMoonsMoonIdValidateBeforeCall(moonId, datasource, ifNoneMatch, ...
java
public void deleteResourceWithSiblings(String name) throws Exception { m_cms.lockResource(name); m_cms.deleteResource(name, CmsResource.DELETE_REMOVE_SIBLINGS); }
java
public TagResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def request(self, apdu): """This function is called by transaction functions to send to the application.""" if _debug: ServerSSM._debug("request %r", apdu) # make sure it has a good source and destination apdu.pduSource = self.pdu_address apdu.pduDestination = None ...
java
@Pure public static String getVMBinary() { final String javaHome = System.getProperty("java.home"); //$NON-NLS-1$ final File binDir = new File(new File(javaHome), "bin"); //$NON-NLS-1$ if (binDir.isDirectory()) { File exec = new File(binDir, getExecutableFilename("javaw")); //$NON-NLS-1$ if (exec.isFile())...
java
public static Long checkNull(Long value, long elseValue) { return checkNull(value, Long.valueOf(elseValue)); }
python
def AddRow(self, values): """Adds a row of values. Args: values (list[object]): values. Raises: ValueError: if the number of values is out of bounds. """ if self._number_of_columns and len(values) != self._number_of_columns: raise ValueError('Number of values is out of bounds.') ...
java
public AsyncWork<File, IOException> createDirectoryAsync(String prefix) { return new Task.OnFile<File, IOException>(tempDir, "Create temporary directory", Task.PRIORITY_NORMAL) { @Override public File run() throws IOException { return createDirectorySync(prefix); } }.start().getOutput(); }
python
def addCallback(cls, eventType, func, record=None, once=False): """ Adds a callback method to the class. When an event of the given type is triggered, any registered callback will be executed. :param eventType: <str> :param func: <callable> """ callbacks = cls...
java
@Indexable(type = IndexableType.REINDEX) @Override public CPDefinitionInventory updateCPDefinitionInventory( CPDefinitionInventory cpDefinitionInventory) { return cpDefinitionInventoryPersistence.update(cpDefinitionInventory); }
python
def main(): """ NAME zeq_magic_redo.py DESCRIPTION Calculate principal components through demagnetization data using bounds and calculation type stored in "redo" file SYNTAX zeq_magic_redo.py [command line options] OPTIONS -h prints help message -usr U...
python
def get(self, section, name, default=None, **kw): """Replacement for :func:`boto.pyami.config.Config.get()`.""" try: return self.unbound_method(self.instance, section, name, **kw) except Exception: return default
java
public void createOrMigrateSchemaFile(String tableName, File entitySchemaFile, boolean createTableAndFamilies) throws InterruptedException { createOrMigrateSchema(tableName, getSchemaStringFromFile(entitySchemaFile), createTableAndFamilies); }
python
def fast_rabi_terms(Ep, epsilonp, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Rabi frequency terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_con...
python
def share( self, share_id: str, token: dict = None, augment: bool = False, prot: str = "https", ) -> dict: """Get information about a specific share and its applications. :param str token: API auth token :param str share_id: share UUID :param ...
java
public static <T> Stream<T> buildReversedStream(Collection<T> collection) { return JMCollections.getReversed(collection).stream(); }
python
def tgread_object(self): """Reads a Telegram object.""" constructor_id = self.read_int(signed=False) clazz = tlobjects.get(constructor_id, None) if clazz is None: # The class was None, but there's still a # chance of it being a manually parsed value like bool! ...
python
def glyph_metrics_stats(ttFont): """Returns a dict containing whether the font seems_monospaced, what's the maximum glyph width and what's the most common width. For a font to be considered monospaced, at least 80% of the ascii glyphs must have the same width.""" glyph_metrics = ttFont['hmtx'].metrics asci...
python
def _addrs_belong_to_same_section(self, addr_a, addr_b): """ Test if two addresses belong to the same section. :param int addr_a: The first address to test. :param int addr_b: The second address to test. :return: True if the two addresses belong to the same section ...
python
def make_posts(generator, metadata, url): """ Make posts on reddit if it's not a draft, on whatever subs are specified """ reddit = generator.get_reddit() title = lxml.html.fromstring(metadata['title']).text_content() if reddit is None: log.info("Reddit plugin not enabled") retu...
java
public void readArduinoPowerState(final Callback<Boolean> callback) { addCallback(BeanMessageID.CC_GET_AR_POWER, callback); sendMessageWithoutPayload(BeanMessageID.CC_GET_AR_POWER); }
java
public java.lang.Object getTypeaheadValues() { return (java.lang.Object) getStateHelper().eval(PropertyKeys.typeaheadValues); }
java
public final Intent getIntent(IntentName name) { GetIntentRequest request = GetIntentRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getIntent(request); }
java
public static void writeTag(OutputStream out, Tag tag) throws IOException { writeTag(out, tag, false); }
python
def create_cone(cols, radius=1.0, length=1.0): """Create a cone Parameters ---------- cols : int Number of faces. radius : float Base cone radius. length : float Length of the cone. Returns ------- cone : MeshData Vertices and faces computed for a co...
java
protected boolean report(Message5WH message) { if(message==null){ return false; } E_MessageType type = message.getType(); if(!this.messageHandlers.containsKey(message.getType())){ return false; } MessageTypeHandler handler = this.messageHandlers.get(message.getType()); String template = this.rende...
python
def fundrefxml2json(self, node): """Convert a FundRef 'skos:Concept' node into JSON.""" doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node, 'rdf:about')) oaf_id = FundRefDOIResolver().resolve_by_doi( "http://dx.doi.org/" + doi...
python
def publisher(self_url=None, hub_url=None): """This decorator makes it easier to implement a websub publisher. You use it on an endpoint, and Link headers will automatically be added. To also include these links in your template html/atom/rss (and you should!) you can use the following to get the raw li...
java
public synchronized void timeout(long millis, Runnable callback) { if (isUnblocked()) return; Task<Void,NoException> task = new Task.Cpu<Void,NoException>("JoinPoint timeout", Task.PRIORITY_RATHER_LOW) { @Override public Void run() { synchronized (JoinPoint.this) { if (isUnblocked()) return nul...
java
@Override public CommerceAddress findByCommerceCountryId_Last( long commerceCountryId, OrderByComparator<CommerceAddress> orderByComparator) throws NoSuchAddressException { CommerceAddress commerceAddress = fetchByCommerceCountryId_Last(commerceCountryId, orderByComparator); if (commerceAddress != null)...
python
def seq_2_DbDevExportInfos(seq, vec=None): """Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos` :param seq: the sequence of DbDevExportInfo :type seq: sequence<DbDevExportInfo> :param vec: (optional, default is None) an :class:`tango.DbDevExportInfos` ...
java
public File generate(File outputDir, boolean pack, Properties properties) throws IOException { if (result == null) { throw new IllegalStateException("Check policies result is null"); } // prepare working directory File workDir = new File(outputDir, "whitesource"); ...
java
@Override public Set<Algorithm> readAlgorithms() throws AlgorithmSourceReadException { initializeIfNeeded(); if (algorithms != null) { if (!readAlgorithmsCalled && getBackends() != null) { for (AlgorithmSourceBackend backend : getBackends()) { backend....
python
def Bx(self): """Compute a stack of skew-symmetric matrices which can be multiplied by 'a' to get the cross product. See: http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication """ # 0 self.b3 -self.b2 # -self.b3 0 self...
python
def reload(self): """ Refreshes the file with the data from the server. """ try: data = self._api.get(self.href, append_base=False).json() resource = File(api=self._api, **data) except Exception: try: data = self._api.get( ...
python
def login(request): ''' Logs in the user via given login and password. ''' serializer_class = registration_settings.LOGIN_SERIALIZER_CLASS serializer = serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.get_authenticated_user() if not user: ...
java
public Observable<CognitiveServicesAccountInner> updateAsync(String resourceGroupName, String accountName) { return updateWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<CognitiveServicesAccountInner>, CognitiveServicesAccountInner>() { @Override pu...
java
@Override protected HttpURLConnection getConnection() throws HelloSignException { if (fields != null) { for (String key : fields.keySet()) { if (fields.get(key) instanceof File) { return postWithFile(); } } } return ...
python
def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for th...
java
public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException { for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++) { _curPairLeft = _curForeignkeyDef.getLocalColumn(idx); _curPairRight = _curForeignkeyDef.getR...
python
def value(self): """ gets the mosaic rule object as a dictionary """ if self.mosaicMethod == "esriMosaicNone" or\ self.mosaicMethod == "esriMosaicCenter" or \ self.mosaicMethod == "esriMosaicNorthwest" or \ self.mosaicMethod == "esriMosaicNadir": ...
python
def drop_column(self, name): """Drop the column ``name``. :: table.drop_column('created_at') """ if self.db.engine.dialect.name == 'sqlite': raise RuntimeError("SQLite does not support dropping columns.") name = normalize_column_name(name) with sel...
java
public T allowedUsers(long... userIds) { this.userPredicate = (user) -> { for (long id : userIds) { if (id == user.getId()) { return true; } }
python
def compareValues(self, a, b): """ Compares two values based on their values for this axis. :param a | <variant> b | <variant> """ values = self.values() try: return cmp(values.index(a), values.index(b)) exce...
python
def select_unaligned_read_pairs(in_bam, extra, out_dir, config): """Retrieve unaligned read pairs from input alignment BAM, as two fastq files. """ runner = broad.runner_from_config(config) base, ext = os.path.splitext(os.path.basename(in_bam)) nomap_bam = os.path.join(out_dir, "{}-{}{}".format(base...
python
def order_block_volume(self, storage_type, location, size, os_type, iops=None, tier_level=None, snapshot_size=None, service_offering='storage_as_a_service', hourly_billing_flag=False): """Places an order for a block volume. ...
python
def deleteFile(self, CorpNum, ItemCode, MgtKey, FileID, UserID=None): """ 첨부파일 삭제 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] ...
java
private static JNRPEConfiguration loadConfiguration(final String configurationFilePath) throws ConfigurationException { File confFile = new File(configurationFilePath); if (!confFile.exists() || !confFile.canRead()) { throw new ConfigurationException("Cannot access config file : " + configu...
python
def daemonize(stdin=os.devnull, stdout=os.devnull, stderr=os.devnull): ''' This forks the current process into a daemon. The stdin, stdout, and stderr arguments are file names that will be opened and be used to replace the standard file descriptors in sys.stdin, sys.stdout, and sys.stderr. These...
java
public void characters(char ch[], int start, int length) throws SAXException { String arg0 = new String(ch); arg0 = arg0.substring(start, start + length); // System.out.println(arg0); if (arg0.startsWith("\n")) return; this.processValue(arg0); }
java
public ServiceFuture<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> listRoutesTableSummaryAsync(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath, final ServiceCallback<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> serviceCallback) { ret...
java
public boolean recordXidGenerator() { if (!currentInfo.isXidGenerator()) { currentInfo.setXidGenerator(true); populated = true; return true; } else { return false; } }
java
private String [] generateArguments () { final List <String> argsList = new ArrayList <> (); argsList.add ("-np"); argsList.add (getEffectiveNodePackageName ()); argsList.add ("-vp"); argsList.add (getEffectiveVisitorPackageName ()); if (this.supressErrorChecking != null && this.supressErro...
java
@Override public Observable<Account> doLogin(AuthCredentials credentials) { return Observable.just(credentials).flatMap(new Func1<AuthCredentials, Observable<Account>>() { @Override public Observable<Account> call(AuthCredentials credentials) { try { // Simulate network delay Thr...
python
def is_instance_running(self, instance_id): """Checks if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise """ # Here, it's always better if we update the instance. instance = self._load_instanc...
python
def prepare_data_maybe_download(directory): """ Download and unpack dialogs if necessary. """ filename = 'ubuntu_dialogs.tgz' url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz' dialogs_path = os.path.join(directory, 'dialogs') # test it there are some dialogs...
java
public void stopService() throws Exception { Log.info(c, "stopService", "Stopping LdapServer"); this.server.stop(); Log.info(c, "stopService", "Stopping DirectoryService"); service.shutdown(); Log.info(c, "stopService", "Ldap stopped."); }
python
def local_exception_handler(handler=None, coro=None): """add a callback for when an exception occurs in a particular greenlet :param handler: the callback function, must be a function taking 3 arguments: - ``klass`` the exception class - ``exc`` the exception instance - ``tb`` ...
python
def run(): """Main entry point.""" import optparse parser = optparse.OptionParser(usage=r"%prog [<options>] [file ...]") parser.add_option( "-p", "--spread", type="float", default=3.0, help="Rainbow spread" ) parser.add_option( "-F", "--freq", type="float", default=0.1, help="Ra...
python
def _bind_to_schema(self, field_name, schema): """Update field with values from its parent schema. Called by :meth:`_bind_field<marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema schema: Parent schema. """ self.parent = s...
python
def restore_state(self, state): """Restore the current state of this emulated object. Args: state (dict): A previously dumped state produced by dump_state. """ config_vars = state.get('config_variables', {}) for str_name, str_value in config_vars.items(): ...
java
private void buttonExtensionsOpenInSystemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExtensionsOpenInSystemActionPerformed final SysFileExtensionEditorPanel dataPanel = new SysFileExtensionEditorPanel(SystemFileExtensionManager.getInstance().getExtensionsAsCommaSeparatedString()); i...
java
public void addDeleted(CmsClientSitemapEntry entry) { if (!(entry.isNew() && CmsStringUtil.isEmptyOrWhitespaceOnly(entry.getVfsPath()))) { removeDeleted(entry.getId().toString()); getDeleted().insertItem(createDeletedItem(entry), 0); } removeModified(entry.getId().toStri...
python
def create_vmfs_datastore(datastore_name, disk_id, vmfs_major_version, safety_checks=True, service_instance=None): ''' Creates a ESXi host disk group with the specified cache and capacity disks. datastore_name The name of the datastore to be created. disk_id T...
python
def _proj_l1_sortsum(v, gamma, axis=None): r"""Projection operator of the :math:`\ell_1` norm. The solution is computed via the method of :cite:`duchi-2008-efficient`. Parameters ---------- v : array_like Input array :math:`\mathbf{v}` gamma : float Parameter :math:`\gamma` axi...
java
@Override ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source) { ResolveContext newContext = context.addCycleMarker(this); AbstractConfigValue v; try { ResolveSource.ResultWithPath resultWithPath = source.lookupSubst(newC...
java
private Object getAvroPrimitiveType(final String avroFieldName, final XmlSchemaSimpleType xsdType, boolean isArray, boolean isOptional) throws Xsd2AvroTranslatorException { XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction) xsdType .getContent()...
python
def main(argv): """Play matches between two neural nets.""" _, black_model, white_model = argv utils.ensure_dir_exists(FLAGS.eval_sgf_dir) play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
python
def _init_content_type_params(self): """ Return the Content-Type request header parameters Convert all of the semi-colon separated parameters into a dict of key/vals. If for some stupid reason duplicate & conflicting params are present then the last one wins. If a parti...
python
def idxmin(self, axis=0, skipna=True): """ Return index of first occurrence of minimum over requested axis. NA/null values are excluded. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' for row-wise, 1 or 'columns' for colum...
python
def rename_workspace_config(namespace, workspace, cnamespace, config, new_namespace, new_name): """Rename a method configuration in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespa...
java
public ModuleInner createOrUpdate(String resourceGroupName, String automationAccountName, String moduleName, ModuleCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, parameters).toBlocking().single().body(); }
python
def reread(self): """ Read and parse credentials file. If something goes wrong, log exception and continue. """ logger.debug("Loading credentials from %s", os.path.abspath(self.creds_filename)) creds = {} try: with self.open_creds(...
java
public Binding createBoundShuttleList( String selectionFormProperty, Object selectableItems, String renderedProperty ) { return createBoundShuttleList(selectionFormProperty, new ValueHolder(selectableItems), renderedProperty); }
python
def stretch_histogram(img, dark_clip_percentile=None, bright_clip_percentile=None, dark_clip_value=None, bright_clip_value=None, ignore_zero=True): """Stretch img histogram. 2 possible modes: by percentile (pass dark/bright_clip_percentile), or by value (pass dark/bright_clip_value) :...
java
protected String createSubmitFaxCommand(FaxJob faxJob) { //init buffer StringBuilder buffer=new StringBuilder(); //create command buffer.append(this.submitCommand); buffer.append(" "); buffer.append(this.printQueueParameter); buffer.append(" "); ...
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataIntersectionOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
public TileResultSet queryByTileGrid(TileGrid tileGrid, long zoomLevel, String orderBy) { TileResultSet tileCursor = null; if (tileGrid != null) { StringBuilder where = new StringBuilder(); where.append(buildWhere(TileTable.COLUMN_ZOOM_LEVEL, zoomLevel)); where.append(" AND "); where.append(buil...
java
@Override public GetUserPoolMfaConfigResult getUserPoolMfaConfig(GetUserPoolMfaConfigRequest request) { request = beforeClientExecution(request); return executeGetUserPoolMfaConfig(request); }
java
public void addExtraInfo(String key, Object value) { // Turn extraInfo into map Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo); // Add value infoMap.put(key, value); // Turn back into string extraInfo = getJSONFromMap(infoMap); }
python
def _search(self, mdb, query, filename, season_num, episode_num, auto=False): """ Search the movie using all available datasources and let the user select a result. Return the choosen datasource and produced movie dict. If auto is enabled, directly returns the first movie found. """...
java
public static <E, S extends SortedSet<E>> SynchronizedSortedSet<E> of(S set) { return new SynchronizedSortedSet<E>(SortedSetAdapter.adapt(set)); }
python
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={}, blankIfNoMatch=False): """ Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: M...
java
static Collection<Collection<MeasurementDTO>> measurementDTOs(Results<Measurement> measurements) { return Lists.newArrayList(Iterables.transform(measurements, new Function<Results.Row<Measurement>, Collection<MeasurementDTO>>() { @Override public Collection<MeasurementDTO> apply(Row<Mea...
java
@SuppressWarnings("unchecked") public static void setIndex(Object array, int index, Object val) throws ReflectError, UtilTargetError { try { val = Primitive.unwrap(val); if ( array instanceof List ) ((List<Object>) array).set(index, val); else ...
python
def perform_kubelet_query(self, url, verbose=True, timeout=10, stream=False): """ Perform and return a GET request against kubelet. Support auth and TLS validation. """ return requests.get( url, timeout=timeout, verify=self.kubelet_credentials.verify()...
java
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) Object[] tab = tabl...
java
protected void trim(Queue<Notification> notifications, DateTime time) { while (!notifications.isEmpty() && !notifications.peek().getStartTime().isAfter(time)) { notifications.poll(); } }
python
def working_directory(path): """ A context manager that changes the working directory to the given path, and then changes it back to its previous value on exit. """ prev_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
java
@SuppressWarnings("unused") public void setRotationByAxis(float angle, float x, float y, float z) { getTransform().setRotationByAxis(angle, x, y, z); if (mTransformCache.setRotationByAxis(angle, x, y, z)) { onTransformChanged(); } }
java
public void BuildInteractiveObjectFromAnchor(Sensor anchorSensor, String anchorDestination) { InteractiveObject interactiveObject = new InteractiveObject(); interactiveObject.setSensor(anchorSensor, anchorDestination); interactiveObjects.add(interactiveObject); }
java
public GetInstancePortStatesResult withPortStates(InstancePortState... portStates) { if (this.portStates == null) { setPortStates(new java.util.ArrayList<InstancePortState>(portStates.length)); } for (InstancePortState ele : portStates) { this.portStates.add(ele); ...
java
private Map<PropertyKey, Map<Optional<String>, List<String>>> generateConfMap() { Map<PropertyKey, Map<Optional<String>, List<String>>> confMap = new HashMap<>(); fillConfMap(confMap, mMasterStore.getConfMap()); fillConfMap(confMap, mWorkerStore.getConfMap()); return confMap; }
java
public static LocalCall<String> mkdir(String path, String user, String group) { return mkdir(path, Optional.of(user), Optional.of(group), Optional.empty()); }
python
def constraints(self): """ Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after a successful :meth:`build` :return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances :rtype: :class:`list` For more i...
python
def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. """ url = self._generate...
java
@Override public Screen createScreen(Config config) { Check.notNull(config); final Screen screen; if (config.isWindowed()) { screen = new ScreenWindowedAwt(config); } else { screen = new ScreenFullAwt(config); ...