language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def pick_sdf(filename, directory=None): """Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned....
java
public String toAddressPathString() { if (isRoot()) { return "/"; } StringBuilder str = new StringBuilder(); List<Property> parts = addressNode.asPropertyList(); for (Property part : parts) { String name = part.getName(); String value = part.g...
python
def index(request, obj_id): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'PUT': getPutData(request) return put(request, obj_id)
java
public void readData(DataInput din) throws IOException { function = din.readUnsignedShort(); data = (short)(din.readShort() & 0xFFFF); }
java
public Future<ListTablesResult> listTablesAsync(final ListTablesRequest listTablesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListTablesResult>() { public ListTablesResult call() throws Exception { return lis...
java
public Observable<DeploymentExtendedInner> getByResourceGroupAsync(String resourceGroupName, String deploymentName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, deploymentName).map(new Func1<ServiceResponse<DeploymentExtendedInner>, DeploymentExtendedInner>() { @Override ...
python
def _execute_commands(self, commands, fails=False): """Execute commands and get list of failed commands and count of successful commands""" # Confirm that prepare_statements flag is on if self._prep_statements: prepared_commands = [prepare_sql(c) for c in tqdm(commands, total=len(com...
python
def price_and_currency(self): """Get Offer Price and Currency. Return price according to the following process: * If product has a sale return Sales Price, otherwise, * Return Price, otherwise, * Return lowest offer price, otherwise, * Return None. :return: ...
python
def executor_ips(sc): """ gets the unique ip addresses of the executors of the current application This uses the REST API of the status web UI on the driver (http://spark.apache.org/docs/latest/monitoring.html) :param sc: Spark context :return: set of ip addresses """ try: app_i...
java
@ExceptionHandler(ValidationException.class) public ResponseEntity<ExceptionInfo> handleValidationException(final HttpServletRequest request, final ValidationException ex) { logRequest(request, ex); final ExceptionInfo response = new ExceptionInfo(); response.setMessage(ex.getMe...
python
def get_member_device(self, device): """Returns the given virtual media device object. :param device: virtual media device to be queried :returns virtual media device object. """ for vmedia_device in self.get_members(): if device in vmedia_device.media_types: ...
java
private static final boolean nowAllSet(int before, int after, int mask) { return ((before & mask) != mask) && ((after & mask) == mask); }
java
public OvhBackendTCPServer serviceName_tcp_farm_farmId_server_POST(String serviceName, Long farmId, String address, Boolean backup, String chain, String displayName, Long port, Boolean probe, OvhProxyProtocolVersionEnum proxyProtocolVersion, Boolean ssl, OvhBackendCustomerServerStatusEnum status, Long weight) throws IO...
java
private static Type resolveWildcardTypeVariables(final WildcardType type, final Map<String, Type> generics, final boolean countPreservedVariables) { final Type res; if (type.getLowerBounds().length ...
python
def copysign(x, y, context=None): """ Return a new BigFloat object with the magnitude of x but the sign of y. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_copysign, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ...
python
def _import_csv(self, path): """CSV import workflow""" # If path is not set, do nothing if not path: return # Get csv info try: dialect, has_header, digest_types, encoding = \ self.main_window.interfaces.get_csv_import_info(path) ...
java
private CompletableFuture<LogicalSlot> allocateSharedSlot( SlotRequestId slotRequestId, ScheduledUnit scheduledUnit, SlotProfile slotProfile, boolean allowQueuedScheduling, Time allocationTimeout) { // allocate slot with slot sharing final SlotSharingManager multiTaskSlotManager = slotSharingManagers.comp...
java
public static InternalLogApi getLog(String name) { return factoryConfigured ? factory.doGetLog(name) : new InternalLog(name); // will look up actual logger per log }
java
public IVector add(IVector b) { IVector result = new IVector(size); add(b, result); return result; }
python
def _walk_breadth( self, fs, # type: FS path, # type: Text namespaces=None, # type: Optional[Collection[Text]] ): # type: (...) -> Iterator[Tuple[Text, Optional[Info]]] """Walk files using a *breadth first* search. """ queue = deque([path]) ...
python
def get_experiments(base, load=False): ''' get_experiments will return loaded json for all valid experiments from an experiment folder :param base: full path to the base folder with experiments inside :param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to...
java
@Override public void handleServerEvent(ISFSEvent event) throws SFSException { Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE); Room sfsRoom = (Room) event.getParameter(SFSEventParam.ROOM); notifyHandlers((ApiZone)sfsZone.getProperty(APIKey.ZONE), (ApiRoom)sfsRo...
python
def _prep_inputs(align_bams, ref_file, items): """Ensure inputs to calling are indexed as expected. """ broad_runner = broad.runner_from_path("picard", items[0]["config"]) broad_runner.run_fn("picard_index_ref", ref_file) for x in align_bams: bam.index(x, items[0]["config"])
python
def get_all_cloud_integration(self, **kwargs): # noqa: E501 """Get all cloud integrations for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_a...
java
public void registerChannel(FileChannel channel, boolean writable) { readableChannels.add(channel); if (writable) { writableChannels.add(channel); } }
java
public int getOverlapLength(HmmerResult other){ int overlap = 0; for ( HmmerDomain d1 : getDomains()){ for (HmmerDomain d2 : other.getDomains()){ overlap += getOverlap(d1, d2); } } return overlap; }
java
public long acquireExecutionMemory(long required, MemoryConsumer consumer) { assert(required >= 0); assert(consumer != null); MemoryMode mode = consumer.getMode(); // If we are allocating Tungsten pages off-heap and receive a request to allocate on-heap // memory here, then it may not make sense to ...
python
def ordering_url(self, field_name): """ Creates a url link for sorting the given field. The direction of sorting will be either ascending, if the field is not yet sorted, or the opposite of the current sorting if sorted. """ path = self.request.path direction = "...
python
def get_keywords(self): """Obtain the state of the dialog as a keywords dict. :returns: Keywords reflecting the state of the dialog. :rtype: dict """ keywords = {} inasafe_fields = {} keywords['layer_geometry'] = self.get_layer_geometry_key() if self.step...
python
def request_session(self): """ Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. """ concierge_request_header = self.construct_concierge_header( ...
java
@Override public ContactInfo[] listContact(String CorpNum) throws PopbillException { return httpget("/IDs", CorpNum, null, ContactInfo[].class); }
java
public static Field findField(TypeToken<?> classType, String fieldName, Predicate<Field> predicate) throws NoSuchFieldException { for (Class<?> clz : classType.getTypes().classes().rawTypes()) { try { Field field = clz.getDeclaredField(fieldName); if (predicate....
python
def forward(self, hidden, target=None, keep_order=False): ''' Params: hidden :: [len*bsz x d_proj] target :: [len*bsz] Return: if target is None: out :: [len*bsz] Negative log likelihood else: ...
python
def input_value(self, locator, text): """Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value See `introduction` for details about locating elements. """ self._info("Setting text '%s' into text field '%s'" % (...
python
def score( self, data, metric="accuracy", validation_task=None, reduce="mean", break_ties="random", verbose=True, print_confusion_matrix=False, **kwargs, ): """Scores the predictive performance of the Classifier on all tasks Arg...
java
public static Map<String, ? extends CacheConfig> fromYAML(Reader reader) throws IOException { return new CacheConfigSupport().fromYAML(reader); }
python
def get(self, uri): """ Return node for uri or None if not exists: {uri: x, content: y} """ cache_key = self._build_cache_key(uri) value = self._get(cache_key) if value is not None: return self._decode_node(uri, value)
java
public FSArray getDocuments() { if (SourceFile_Type.featOkTst && ((SourceFile_Type)jcasType).casFeat_documents == null) jcasType.jcas.throwFeatMissing("documents", "de.julielab.jules.types.ace.SourceFile"); return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((SourceFile_T...
java
public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq, final Decoder<T> resultDecoder) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonR...
java
public <T> void verifyAndUpload(T entity, PayloadType payloadType) { long threshold = 0L; long maxThreshold = 0L; Map<String, Object> payload = new HashMap<>(); String workflowId = ""; switch (payloadType) { case TASK_INPUT: threshold = configuration.g...
java
public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); this.context = context; mLogger = context.getLogger(); if (mLogger.isLoggable(Level.INFO)) { mLogger.log(Level.INFO, "Initializing the CoGrOO annotator."); } ComponentFactory factory = ...
python
def git_merge(base, head, no_ff=False): # type: (str, str, bool) -> None """ Merge *head* into *base*. Args: base (str): The base branch. *head* will be merged into this branch. head (str): The branch that will be merged into *base*. no_ff (bool): ...
python
def all(self): """ Returns a list of cached instances. """ class_list = list(self.get_class_list()) if not class_list: self.cache = [] return [] if self.cache is not None: return self.cache results = [] for cls_path in...
java
@Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { switch ((ChronoField) field) { case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); case YEAR: return year; case ERA: return (year < 1 ? 0 : 1); ...
python
def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None): """ Creates a Spot instance request. Spot instances are instances that Ama...
java
public static Map<String, String> createEnvironment(Map<String, String> environment) { Map<String, String> result = null; try { result = EnvironmentUtils.getProcEnvironment(); } catch (IOException ex) { throw new ElasticsearchSetupExce...
python
def parse_timemap_from_blocks(profile_block_list): """ Build a map from times to line_profile blocks """ prefix_list = [] timemap = ut.ddict(list) for ix in range(len(profile_block_list)): block = profile_block_list[ix] total_time = get_block_totaltime(block) # Blocks wit...
java
protected void scandir(File dir, String vpath, boolean fast) { if (dir == null) { throw new RuntimeException("dir must not be null."); } String[] newfiles = dir.list(); if (newfiles == null) { if (!dir.exists()) { throw new RuntimeException(dir + "...
python
def per_machine_target_cores(cores, num_jobs): """Select target cores on larger machines to leave room for batch script and controller. On resource constrained environments, we want to pack all bcbio submissions onto a specific number of machines. This gives up some cores to enable sharing cores with the c...
java
@Override public MavenVersionRangeResult resolveVersionRange(final String coordinate) throws IllegalArgumentException { Validate.isNullOrEmpty(coordinate); final MavenCoordinate mavenCoordinate = MavenCoordinates.createCoordinate(coordinate); return this.getMavenWorkingSession().resolveVers...
java
public SimonConsolePlugin getPluginById(String id) { for (SimonConsolePlugin plugin : plugins) { if (plugin.getId().equals(id)) { return plugin; } } return null; }
python
def logout(request, login_url=None, **kwargs): """Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters. ...
python
def post_request(self, url, params): """Send a post request. :return: a dict or raise Exception. """ data = encrypted_request(params) resp = self.session.post(url, data=data, timeout=self.timeout, proxies=self.proxies) result = resp.json...
python
def create_skydir_ltcube(self, skydir, tab_sc, tab_gti, zmax): """Create a new livetime cube by scaling this one by the observing profile ratio in the direction ``skydir``. This method can be used to generate an approximate livetime cube that is accurate in the vicinity of ``skydir``. ...
java
public long getFinalizedBlockLength(int namespaceId, Block b) throws IOException { DatanodeBlockInfo info = volumeMap.get(namespaceId, b); if (info == null) { throw new IOException("Can't find block " + b + " in volumeMap"); } return info.getFinalizedSize(); }
python
def get_user_log(self, language='da'): """Get the controller state""" payload = """<getUserLog1 xmlns="utcs" /> <getUserLog2 xmlns="utcs">0</getUserLog2> <getUserLog3 xmlns="utcs">{language}</getUserLog3> """.format(language=language) ...
python
def parse_optional(self, string): """Parse string into name, option, and value (if possible). If the string is a known option name, the string, the corresponding option, and ``None`` will be returned. If the string has the form ``--option=<value>`` or ``-o=<value>``, it will be...
java
public PackedDecimal subtract(Bruch operand) { AbstractNumber result = toBruch().subtract(operand); return PackedDecimal.valueOf(result); }
java
public boolean optBoolean(int index, boolean fallback) { Object object = opt(index); Boolean result = JSON.toBoolean(object); return result != null ? result : fallback; }
java
public synchronized void removeEvidence(EvidenceType type, Evidence e) { if (null != type) { switch (type) { case VENDOR: vendors.remove(e); break; case PRODUCT: products.remove(e); break;...
java
public void write(JsonWriter json, @Nullable UserDto user) { if (user == null) { json.beginObject().endObject(); } else { write(json, user, Collections.emptySet(), CONCISE_FIELDS); } }
java
protected void createExportBackupFolders( File staticExport, String exportPath, int exportBackups, String ruleBackupExtension) { if (staticExport.exists()) { String backupFolderName = exportPath.substring(0, exportPath.lastIndexOf(File.separator) + 1); if...
java
private ImageFormat getFormat(List<ImageFormat> l, int i){ for(ImageFormat f:l) if(f.getIndex()==i) return f; return null; }
python
def revoke_prefix(self, prefix): """Revoke all secrets (via a lease ID prefix) or tokens (via the tokens' path property) generated under a given prefix immediately. This requires sudo capability and access to it should be tightly controlled as it can be used to revoke very large numbers...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case XtypePackage.XFUNCTION_TYPE_REF__PARAM_TYPES: return getParamTypes(); case XtypePackage.XFUNCTION_TYPE_REF__RETURN_TYPE: return getReturnType(); case XtypePackage.XFUNCTION_TYPE_REF__TYPE: ...
python
def check_ellipsis(text): """Use an ellipsis instead of three dots.""" err = "typography.symbols.ellipsis" msg = u"'...' is an approximation, use the ellipsis symbol '…'." regex = "\.\.\." return existence_check(text, [regex], err, msg, max_errors=3, require_padding=False...
python
def until(name, m_args=None, m_kwargs=None, condition=None, period=0, timeout=604800): ''' Loop over an execution module until a condition is met. name The name of the execution module m_args The execution module's positional arguments ...
python
def do__relative_load(self, args: argparse.Namespace) -> None: """Run commands in script file that is encoded as either ASCII or UTF-8 text""" file_path = args.file_path # NOTE: Relative path is an absolute path, it is just relative to the current script directory relative_path = os.path...
python
def internal_evaluate_expression(dbg, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result): ''' gets the value of a variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: result = pydevd_vars.evaluate_expression(dbg, frame, ...
java
public Map<String, Object> determineHibernateProperties( Map<String, String> jpaProperties, HibernateSettings settings) { Assert.notNull(jpaProperties, "JpaProperties must not be null"); Assert.notNull(settings, "Settings must not be null"); return getAdditionalProperties(jpaProperties, settings); }
java
public static <T extends Comparable<?>> ComparablePath<T> comparablePath(Class<? extends T> type, Path<?> parent, String property) { return new ComparablePath<T>(type, PathMetadataFactory.forProperty(parent, property)); }
python
def coalesce(self): """ Coalesces any adjacent ScienceSegments. Returns the number of ScienceSegments in the coalesced list. """ # check for an empty list if len(self) == 0: return 0 # sort the list of science segments self.__sci_segs.sort() # coalesce the list, checking eac...
java
public static void multAddOuter( double alpha , DMatrix3x3 A , double beta , DMatrix3 u , DMatrix3 v , DMatrix3x3 C ) { C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a13 = alpha*A.a13 + beta*u.a1*v.a3; C.a21 = alpha*A.a21 + beta*u.a2*v.a1; C.a22 = ...
java
public void marshall(TagRequest tagRequest, ProtocolMarshaller protocolMarshaller) { if (tagRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tagRequest.getArn(), ARN_BINDING); pr...
python
def get_residue_id_to_type_map(self): '''Returns a dictionary mapping 6-character residue IDs (Chain, residue number, insertion code e.g. "A 123B") to the corresponding one-letter amino acid. Caveat: This function ignores occupancy - this function should be called once occupancy has been ...
java
public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new Malformed...
python
def crawl_fig(self, fig): """Crawl the figure and process all axes""" with self.renderer.draw_figure(fig=fig, props=utils.get_figure_properties(fig)): for ax in fig.axes: self.crawl_ax(ax)
python
def p_block_statements(self, p): 'block_statements : block_statements block_statement' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
python
def cancelAllPendingResults( self ): """Cancel all pending results. Note that this only affects the notebook's record, not any job running in a lab.""" for k in self._results.keys(): rs = self._results[k] self._results[k] = [ j for j in rs if isinstance(j, dict) ] ...
java
public static boolean isInstance(final Object value, final Type type) { if (type == null) { return false; } return value == null ? !(type instanceof Class<?>) || !((Class<?>) type).isPrimitive() : isAssignable(value.getClass(), type, null); }
python
def _get_first_all_link_record(self): """Request first ALL-Link record.""" _LOGGER.debug("Starting: _get_first_all_link_record") _LOGGER.info('Requesting ALL-Link Records') if self.aldb.status == ALDBStatus.LOADED: self._next_all_link_rec_nak_retries = 3 self._han...
java
public <S extends T> TypeDeserializationInfo<T> addTypeInfo( Class<S> clazz, String typeInfo ) { typeInfoToClass.put( typeInfo, clazz ); return this; }
java
@Override public List<CommerceTierPriceEntry> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public boolean addStylesFontFaceContainerStyle(final FontFaceContainerStyle ffcStyle) { final FontFace fontFace = ffcStyle.getFontFace(); if (fontFace != null) { this.fontFaces.add(fontFace); } return this.addStylesStyle(ffcStyle); }
java
public JobInformationRecorder withWriteBatcher(DataMovementManager dataMovementManager, WriteBatcher writeBatcher) { if(sourceBatcher.isStarted()) throw new IllegalStateException("Configuration cannot be changed after startJob has been called"); this.writeBatcher = writeBatcher; this.dataMovementManager = d...
java
public static final BigInteger printDurationTimeUnits(TimeUnit value, boolean estimated) { int result; if (value == null) { value = TimeUnit.HOURS; } switch (value) { case MINUTES: { result = (estimated ? 35 : 3); break; ...
java
public JSPStrBuffer replace(int start, int end, String string) { sb.replace(start, end, string); return this; }
java
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> rawArguments) { if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) { throw new IllegalArgumentException("Bootstrap method is no constructor or non-v...
python
def _is_domain_valid(self, url, tld): """ Checks if given URL has valid domain name (ignores subdomains) :param str url: complete URL that we want to check :param str tld: TLD that should be found at the end of URL (hostname) :return: True if URL is valid, False otherwise ...
python
def run(self): """Run the minimization. Returns ------- K : (N,N) ndarray the optimal rate matrix """ if self.verbose: self.selftest() self.count = 0 if self.verbose: logging.info('initial value of the objective functio...
java
public final EObject ruleEventMember() throws RecognitionException { EObject current = null; Token lv_modifiers_4_0=null; Token otherlv_8=null; Token lv_modifiers_12_0=null; Token otherlv_14=null; Token otherlv_17=null; Token otherlv_19=null; Token otherl...
java
private static File getExplodedWarFileDocumentRoot(File codeSourceFile) { log.debug("Code archive: " + codeSourceFile); if (codeSourceFile != null && codeSourceFile.exists()) { String path = codeSourceFile.getAbsolutePath(); int webInfPathIndex = path.indexOf(File.separatorChar +...
java
public static void main(String[] args) { System.out.println("Jaguar " + MAJOR + "." + MINER + BUILD); System.out.println("Copyright (C) 2009-2011 Eiichiro Uchiumi. All Rights Reserved."); }
java
public static MozuUrl executeUrl(String cardType, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/payments/tokens/{cardType}/execute?responseFields={responseFields}"); formatter.formatUrl("cardType", cardType); formatter.formatUrl("responseFields", responseFields); return new ...
java
@Override protected void serializeTo(RawDataBuffer out) { super.serializeTo(out); if (message != null) { out.writeBoolean(true); MessageSerializer.serializeTo(message, out); } else out.writeBoolean(false); }
python
def _pfp__snapshot(self, recurse=True): """Save off the current value of the field """ super(Struct, self)._pfp__snapshot(recurse=recurse) if recurse: for child in self._pfp__children: child._pfp__snapshot(recurse=recurse)
python
def snapshot(self): """Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it. """ # get if device co...
java
public AnnotationValueBuilder<T> value(@Nullable Class<?> type) { return member(AnnotationMetadata.VALUE_MEMBER, type); }
java
public static <E> MpscLinkedQueue<E> newMpscLinkedQueue() { if (UnsafeAccess.SUPPORTS_GET_AND_SET) { return new MpscLinkedQueue8<E>(); } else { return new MpscLinkedQueue7<E>(); } }
python
def autoprefixer(input, **kw): """Run autoprefixer""" cmd = '%s -b "%s" %s' % (current_app.config.get('AUTOPREFIXER_BIN'), current_app.config.get('AUTOPREFIXER_BROWSERS'), input) subprocess.call(cmd, shell=True)