language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public ObservableList<Item> getPropertySheetItems() { ObservableList<Item> items = super.getPropertySheetItems(); items.add(new Item() { @Override public Optional<ObservableValue<?>> getObservableValue() { return Optional.of(showNavigationProperty(...
python
def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count): """ Generate URLs for slice_count^2 subimages of a product. """ for x in range(slice_count): for y in range(slice_count): yield ("http://z2-ec2.images-amazon.com/R/1/a=" + product_id + "+c=" + dynapi_key + ...
java
private static float getHorizontalShadowWidth(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { ...
python
def get_ceiling_cloud_layer(self): """ Returns the lowest layer of broken or overcast clouds. :rtype: CloudLayer|None """ lowest_layer = None for layer in self.cloud_layers: if layer.coverage not in [CloudLayer.BROKEN, CloudLayer.OVERCAST]: con...
java
@Override public MtasSpanQuery rewrite(IndexReader reader) throws IOException { if (items.size() == 1) { MtasSpanQuery singleQuery = items.get(0).getQuery(); if (leftMaximum != 0 || rightMaximum != 0) { singleQuery = new MtasExpandSpanQuery(singleQuery, leftMinimum, leftMaximum, ri...
java
public static PushNotificationPayload sound(String sound) { if (sound == null) throw new IllegalArgumentException("Sound name cannot be null"); PushNotificationPayload payload = complex(); try { payload.addSound(sound); } catch (JSONException e) { } return payload; }
java
public void cleanup() { if (file != null && file.exists() && !file.delete()) { LOGGER.debug("Failed to delete first temporary file {}", file.toString()); file.deleteOnExit(); } }
java
@Override public ListSubscriptionsByTopicResult listSubscriptionsByTopic(ListSubscriptionsByTopicRequest request) { request = beforeClientExecution(request); return executeListSubscriptionsByTopic(request); }
java
static int targetDistance(NameConstraintsExtension constraints, X509Certificate cert, GeneralNameInterface target) throws IOException { /* ensure that certificate satisfies existing name constraints */ if (constraints != null && !constraints.verify(cert)) { ...
java
@Pure @Inline(value = "(-($1.intValue()))", constantExpression = true) public static int operator_minus(Integer number) { return -number.intValue(); }
python
def _merge_config(self, config_override): """ overrides and/or adds data to the current configuration file. ** This has not been implemented yet. :param config_override: A :string: config data to add to or override the current config. """ if not isinstance(config_override, dict...
python
def rename(self, core, other): """http://wiki.apache.org/solr/CoreAdmin#head-9473bee1abed39e8583ba45ef993bebb468e3afe""" params = { 'action': 'RENAME', 'core': core, 'other': other, } return self._get_url(self.url, params=params)
java
public void marshall(DescribeTransformJobRequest describeTransformJobRequest, ProtocolMarshaller protocolMarshaller) { if (describeTransformJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def IBA_alpha(self, alpha): """ Calculate IBA_alpha score. :param alpha: alpha parameter :type alpha: float :return: IBA_alpha score for classes as dict """ try: IBA_dict = {} for i in self.classes: IBA_dict[i] = IBA_calc(s...
java
@Override public void abortJob(JobContext context, JobStatus.State state) throws IOException { cleanupJob(context); }
java
private State checkA(State state) throws DatatypeException, IOException { if (state.context.length() == 0) { state = appendToContext(state); } state.current = state.reader.read(); state = appendToContext(state); state = skipSpaces(state); boolean expectNumber ...
python
def extract(filename_url_filelike_or_htmlstring): """An "improved" algorithm over the original eatiht algorithm """ html_tree = get_html_tree(filename_url_filelike_or_htmlstring) subtrees = get_textnode_subtrees(html_tree) #[iterable, cardinality, ttl across iterable, avg across iterable.]) ...
java
public EntityBuilder addAction(Action action) { if(action == null) { throw new IllegalArgumentException("action cannot be null."); } addStep("_addAction", new Object[] { action }, true); return this; }
java
public long getRateLimitReset() { if (retrofitError.getResponse() == null) { return -1; } for (Header header : retrofitError.getResponse().getHeaders()) { if ("X-RateLimit-Reset".equals(header.getName())) { return Long.parse...
python
def publish(self, message, routing_key, *, mandatory=True): """ Publish a message on the exchange, to be asynchronously delivered to queues. :param asynqp.Message message: the message to send :param str routing_key: the routing key with which to publish the message :param bool m...
python
def _get_descending_key(gettime=time.time): """Returns a key name lexically ordered by time descending. This lets us have a key name for use with Datastore entities which returns rows in time descending order when it is scanned in lexically ascending order, allowing us to bypass index building for descending i...
python
def environ_setting(name, default=None, required=True): """ Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default ...
java
public Observable<OperationStatusResponseInner> cancelAsync(String resourceGroupName, String vmScaleSetName) { return cancelWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override ...
python
def generate_nucmer_commands( filenames, outdir=".", nucmer_exe=pyani_config.NUCMER_DEFAULT, filter_exe=pyani_config.FILTER_DEFAULT, maxmatch=False, ): """Return a tuple of lists of NUCmer command-lines for ANIm The first element is a list of NUCmer commands, the second a list of delta_...
python
def find_model(self, constructor, constraints=None, *, columns=None, table_name=None, order_by=None): """Specialization of DataAccess.find that returns a model instead of cursor object.""" return self._find_model(constructor, table_name or constructor.table_name, constraints, ...
python
def do_matching(sorting1, sorting2, delta_tp, min_accuracy): """ This compute the matching between 2 sorters. Parameters ---------- sorting1: SortingExtractor instance sorting2: SortingExtractor instance delta_tp: int Output ---------- event_counts_1...
java
private ZooKeeper createZooKeeperClient() throws IOException { ZooClientConfig config = getZookeeperClientConfig(); return new ZooKeeper(config.getUrl(), config.getTimeout(), getConnectionWatcher()); }
java
@Deprecated public <T> Map<String, T> getMapAs(String field, final Class<T> clazz) { return getMapAs(field, clazz, null); }
python
def compute_all_metrics_statistics(all_results): """Computes statistics of metrics across multiple decodings. Args: all_results: dict of 3-D numpy arrays. Each array has shape=(num_decodes, num_samples, num_frames). Returns: statistics: dict of 1-D numpy arrays, shape=(num_frames). ...
python
def parse_requirements(file_name): """ from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy """ requirements = [] with open(file_name, 'r') as f: for line in f: if re.match(r'(\s*#)|(\s*$)', line): continue if re.match(r'\s*-e\s+', line): ...
python
def repository(self): """Repository.""" m = re.match("(.+)(_\d{4}_\d{2}_\d{2}_)(.+)", self.__module__) if m: return m.group(1) m = re.match("(.+)(_release_)(.+)", self.__module__) if m: return m.group(1)
python
def create_for_module_vars(cls, scope_vars): """ This was originally designed to be invoked at the module level for packages that implement specific support, but this can be used to create an instance that has the Node.js backed executable be found via current directory's node_mo...
python
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes d...
python
def inject(arg_names=None, all_except=None): """Marks an initializer explicitly as injectable. An initializer marked with @inject will be usable even when setting only_use_explicit_bindings=True when calling new_object_graph(). This decorator can be used on an initializer or provider method to sep...
java
protected String getLocationForCreatedResource(HttpServletRequest req, String objId) { StringBuffer url = req.getRequestURL(); UriTemplate template = new UriTemplate(url.append("/{objId}/").toString()); return template.expand(objId).toASCIIString(); }
python
def get_container(cls, scheduler): """ Create temporary instance for helper functions """ if scheduler in cls._container_cache: return cls._container_cache[scheduler] else: c = cls(scheduler) cls._container_cache[scheduler] = c retu...
java
final void buildBloomFilterForBucket(int bucketInSegmentPos, MemorySegment bucket, HashPartition<BT, PT> p) { final int count = bucket.getShort(bucketInSegmentPos + HEADER_COUNT_OFFSET); if (count <= 0) { return; } int[] hashCodes = new int[count]; // As the hashcode and bloom filter occupy same bytes, so...
java
public static Pin getPin(Class<? extends PinProvider> pinProviderClass, Pin defaultPin, String ... args){ // search all arguments for the "--pin" or "-p" option // we skip the last argument in the array because we expect a value defined after the option designator for(int index = 0; index < (arg...
java
public JenkinsServer renameJob(String oldJobName, String newJobName) throws IOException { return renameJob(null, oldJobName, newJobName, false); }
java
private void removeSporadic() { //System.out.println("REMOVE SPORADIC CALLED"); // 1. For each grid g in grid_list // a. If g is sporadic // i. If currTime - tg > gap, delete g from grid_list // ii. Else if (S1 && S2), mark as sporadic // iii. Else, mark as normal // b. Else // ...
java
@Override @Transactional(enabled = false) public CommerceRegion createCommerceRegion(long commerceRegionId) { return commerceRegionPersistence.create(commerceRegionId); }
java
private Shape combineSingle(Shape target, Shape missing, boolean subtract, int start) { Shape current = target; Shape other = missing; int point = start; int dir = 1; Polygon poly = new Polygon(); boolean first = true; int loop = 0; // while we've not reached the same point float ...
python
def rename(idf, objkey, objname, newname): """rename all the refrences to this objname""" refnames = getrefnames(idf, objkey) for refname in refnames: objlists = getallobjlists(idf, refname) # [('OBJKEY', refname, fieldindexlist), ...] for refname in refnames: # TODO : there ...
java
private static void initMiddleCert() { LogUtil.writeLog("加载中级证书==>"+SDKConfig.getConfig().getMiddleCertPath()); if (!isEmpty(SDKConfig.getConfig().getMiddleCertPath())) { middleCert = initCert(SDKConfig.getConfig().getMiddleCertPath()); LogUtil.writeLog("Load MiddleCert Successful"); } else { LogUtil.wri...
java
public boolean hasRoleForUser(String name, String role) { List<String> roles = getRolesForUser(name); boolean hasRole = false; for (String r : roles) { if (r.equals(role)) { hasRole = true; break; } } return hasRole; }
python
def find_indentation(node): """Find the indentation of *node*.""" while node is not None: if node.type == syms.suite and len(node.children) > 2: indent = node.children[1] if indent.type == token.INDENT: return indent.value node = node.parent return u""
java
private static ClassLoader getShadow(ClassLoader loader) { return loader instanceof AppClassLoader ? new ShadowClassLoader((AppClassLoader) loader) : loader; }
java
@Override public void handle(WebContext webContext) throws Exception { Request request = webContext.getRequest(); ChannelHandlerContext ctx = webContext.getChannelHandlerContext(); if (!HttpConst.METHOD_GET.equals(request.method())) { sendError(ctx, METHOD_NOT_ALLOWED); ...
python
def _get_addr(self, v): """ Get address of the basic block or CFG node specified by v. :param v: Can be one of the following: a CFGNode, or an address. :return: The address. :rtype: int """ if isinstance(v, CFGNode): return v.addr elif type(v)...
python
def get_reader_input_fn(train_config, preprocess_output_dir, model_type, data_paths, batch_size, shuffle, num_epochs=None): """Builds input layer for training.""" def get_input_features(): """Read the input features from the given data paths.""" _, examples = util.read_examples( ...
python
def connect(self, retry=0, delay=0): """Initiate connection to CM. Blocks until connected unless ``retry`` is specified. :param retry: number of retries before returning. Unlimited when set to ``None`` :type retry: :class:`int` :param delay: delay in secnds before connection attempt ...
python
def update_group(self, group_id, name): """ 修改分组名。 :param group_id: 分组 ID,由微信分配 :param name: 分组名字(30个字符以内) :return: 返回的 JSON 数据包 """ return self.post( url="https://api.weixin.qq.com/cgi-bin/groups/update", data={"group": { ...
java
final String getColumnDefaultValue(int index) { if (m_extraMetadata != null) { return m_extraMetadata.originalColumnInfos[index].defaultValue; } return null; }
java
public AzkabanClientStatus createProject(String projectName, String description) throws AzkabanClientException { AzkabanMultiCallables.CreateProjectCallable callable = AzkabanMultiCallables.CreateProjectCallable.builder() .client(this) .project...
java
public static <T> T loadUtf8(File file, ReaderHandler<T> readerHandler) throws IORuntimeException { return load(file, CharsetUtil.CHARSET_UTF_8, readerHandler); }
java
public void setAlarmHistoryItems(java.util.Collection<AlarmHistoryItem> alarmHistoryItems) { if (alarmHistoryItems == null) { this.alarmHistoryItems = null; return; } this.alarmHistoryItems = new com.amazonaws.internal.SdkInternalList<AlarmHistoryItem>(alarmHistoryItems)...
python
def _dimension(rank0, rankt, dim, singular_values): """ output dimension """ if dim is None or (isinstance(dim, float) and dim == 1.0): return min(rank0, rankt) if isinstance(dim, float): return np.searchsorted(VAMPModel._cumvar(singular_values), dim) + 1 else: ...
java
public static String digestToFileName(String digest) { if (StringUtils.startsWith(digest, "sha1")) { return "manifest.json"; } return getShaVersion(digest) + "__" + getShaValue(digest); }
java
private static File getPluginDir() { String dataDirPath = System.getProperty("jboss.server.data.dir"); //$NON-NLS-1$ File dataDir = new File(dataDirPath); if (!dataDir.isDirectory()) { throw new RuntimeException("Failed to find WildFly data directory at: " + dataDirPath); //$NON-NLS-...
java
public static snmp_manager add(nitro_service client, snmp_manager resource) throws Exception { resource.validate("add"); return ((snmp_manager[]) resource.perform_operation(client, "add"))[0]; }
java
public SheetPublish updatePublishStatus(long id, SheetPublish publish) throws SmartsheetException{ return this.updateResource("sheets/" + id + "/publish", SheetPublish.class, publish); }
python
def forward(self, x, **kwargs): """ Perform a forward pass through the network. The forward pass in recursive som is based on a combination between the activation in the last time-step and the current time-step. Parameters ---------- x : numpy array ...
python
def add_unique_template_variables(self, options): """Update map template variables specific to circle visual""" options.update(dict( geojson_data=json.dumps(self.data, ensure_ascii=False), colorProperty=self.color_property, colorType=self.color_function_type, ...
java
public BatchCreatePartitionRequest withPartitionInputList(PartitionInput... partitionInputList) { if (this.partitionInputList == null) { setPartitionInputList(new java.util.ArrayList<PartitionInput>(partitionInputList.length)); } for (PartitionInput ele : partitionInputList) { ...
java
public Config valideConfigExist(Long id) { // // config // Config config = configMgr.getConfigById(id); if (config == null) { throw new FieldException("configId", "config.id.not.exist", null); } // // validate app // validateA...
java
protected final SIBusMessage readAndDeleteMessage(SIMessageHandle handle, SITransaction transaction) throws ResourceException, SIMessageNotLockedException { final String methodName = "deleteMessage"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.ent...
java
public static void renameFile(File srcFile, File dstFile) throws IOException { // Rename the srcFile file to the new one. Unfortunately, the renameTo() // method does not work reliably under some JVMs. Therefore, if the // rename fails, we manually rename by copying the srcFile file to the new...
java
protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List<String> found = new ArrayList<>(); for (String location : this.resourceLocations) { Resource resource = context.getResourceLoader().getResource(location); if (resource != null && resource.exists()...
python
def _sorted_key_map(item, transform=to_bytes): """Creates a list of the item's key/value pairs as tuples, sorted by the keys transformed by transform. :param dict item: Source dictionary :param function transform: Transform function :returns: List of tuples containing transformed key, original value, a...
java
public static String getRelativeURI( HttpServletRequest request, String uri, PageFlowController relativeTo ) { String contextPath = request.getContextPath(); if ( relativeTo != null ) contextPath += relativeTo.getModulePath(); int overlap = uri.indexOf( contextPath + '/' ); if ( over...
python
def pids2ore(in_stream, fmt='xml', base_url='https://cn.dataone.org/cn'): """read pids from in_stream and generate a resource map. first pid is the ore_pid second is the sci meta pid remainder are data pids """ pids = [] for line in in_stream: pid = line.strip() if len(pid) > 0: ...
python
def all_subclasses(cls): """ Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on. """ subclasses = cls.__subclasses__() return subclasses + [g for s in subclasses for g in all_subclasses(s)]
python
def cells(self) -> Generator[Tuple[int, int], None, None]: """Generate cells in span.""" yield from itertools.product( range(self.row_start, self.row_end), range(self.column_start, self.column_end) )
python
def mid_pt(self): """Midpoint of this interval product.""" midp = (self.max_pt + self.min_pt) / 2. midp[~self.nondegen_byaxis] = self.min_pt[~self.nondegen_byaxis] return midp
python
def allKeys(self): """ Returns a list of all the keys for this settings instance. :return [<str>, ..] """ if self._customFormat: return self._customFormat.allKeys() else: return super(XSettings, self).allKeys()
java
public void marshall(CancelStepsInfo cancelStepsInfo, ProtocolMarshaller protocolMarshaller) { if (cancelStepsInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cancelStepsInfo.getStepId(), STEPI...
java
public Map<String, Object> selectOne(String sql) { List<Map<String, Object>> list = selectList(sql); return getOne(list); }
java
@Override @Deprecated public TableName[] listTableNames(String patternStr) throws IOException { return listTableNames(Pattern.compile(patternStr)); }
python
def init_app(self, app): """Configures the specified Flask app to enforce SSL.""" app.config.setdefault("SSLIFY_SUBDOMAINS", False) app.config.setdefault("SSLIFY_PERMANENT", False) app.config.setdefault("SSLIFY_SKIPS", None) self.hsts_include_subdomains = ( self.hsts...
python
def run_driz(imageObjectList,output_wcs,paramDict,single,build,wcsmap=None): """ Perform drizzle operation on input to create output. The input parameters originally was a list of dictionaries, one for each input, that matches the primary parameters for an ``IRAF`` `drizzle` task. This method would...
java
public <T> T[] noNullElements(final T[] array, final String message) { notNull(array); final int index = indexOfNullElement(array); if (index != -1) { fail(String.format(message, index)); } return array; }
java
@Override protected Content getNavLinkNext() { if (next == null) { return getNavLinkNext(null); } else { DocPath path = DocPath.relativePath(packageElement, next); return getNavLinkNext(path.resolve(DocPaths.PACKAGE_TREE)); } }
python
def _to_torch(Z, dtype=None): """Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor""" if isinstance(Z, list): return [Classifier._to_torch(z, dtype=dtype) for z in Z] else: return Classifier._to_torch(Z)
java
public static AiScene importFile(String filename, Set<AiPostProcessSteps> postProcessing, AiIOSystem<?> ioSystem) throws IOException { return aiImportFile(filename, AiPostProcessSteps.toRawValue( postProcessing), ioSystem); }
java
public Image createImage(String src, String alt) { return this.add(new Image(src, alt)); }
java
public static ImmutableSet<String> lowercaseWordSet(final Class<?> origin, final String resource, final boolean eliminatePrepAndConj) throws IOException { return ImmutableSet.copyOf(new HashSet<String>() {{ readResource(origin, resource, new Nu...
java
@Override public ActionCommand execute(ActionMapping mapping, FormBean formBean, HttpServletRequest request, HttpServletResponse response) throws Exception { // Getting parameters for new tag String tagName = request.getParameter(PARAM_TAG_NAME); String attributeSource = request.getParamete...
java
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { final RandomVariable one = model.getRandomVariableForConstant(1.0); final RandomVariable zero = model.getRandomVariableForConstant(0.0); // TODO >=? - if(evaluationTime > e...
python
def get_catalog(detections): """ Generate an :class:`obspy.core.event.Catalog` from list of \ :class:`Detection`'s. :type detections: list :param detections: list of :class:`eqcorrscan.core.match_filter.Detection` :returns: Catalog of detected events. :rtype: :class:`obspy.core.event.Catal...
java
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (propertyResolver == null) { try { MutablePropertySources sources = new MutablePropertySources(); PropertySource<?> localPropertySource...
java
public void closeChannel(StoredServerChannel channel) { lock.lock(); try { if (mapChannels.remove(channel.contract.getTxId()) == null) return; } finally { lock.unlock(); } synchronized (channel) { channel.closeConnectedHandler()...
python
def get_file_contents(self, project, provider_name, service_endpoint_id=None, repository=None, commit_or_branch=None, path=None, **kwargs): """GetFileContents. [Preview API] Gets the contents of a file in the given source code repository. :param str project: Project ID or project name :p...
python
def visit_compare(self, node): """return an astroid.Compare node as string""" rhs_str = " ".join( [ "%s %s" % (op, self._precedence_parens(node, expr, is_left=False)) for op, expr in node.ops ] ) return "%s %s" % (self._precedence_p...
java
final boolean transferForSignal(Node node) { /* * If cannot change waitStatus, the node has been cancelled. */ if (!node.compareAndSetWaitStatus(Node.CONDITION, 0)) return false; /* * Splice onto queue and try to set waitStatus of predecessor to *...
python
def train_language_model(self, customization_id, word_type_to_add=None, customization_weight=None, **kwargs): """ Train a custom language model. Initiates the training of a custom...
python
def get_dummy_run(nthread, nsamples, **kwargs): """Generate dummy data for a nested sampling run. Log-likelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each gener...
python
def header(self): """A list of text representing the full header (the first 8 lines) of the EPW.""" self._load_header_check() loc = self.location loc_str = 'LOCATION,{},{},{},{},{},{},{},{},{}\n'.format( loc.city, loc.state, loc.country, loc.source, loc.station_id, loc.latitu...
python
def _find_utmp(): ''' Figure out which utmp file to use when determining runlevel. Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness. ''' result = {} # These are the likely locations for the file on Ubuntu for utmp in '/var/run/utmp', '/run/utmp': try: r...
java
public static CommercePriceEntry toModel(CommercePriceEntrySoap soapModel) { if (soapModel == null) { return null; } CommercePriceEntry model = new CommercePriceEntryImpl(); model.setUuid(soapModel.getUuid()); model.setExternalReferenceCode(soapModel.getExternalReferenceCode()); model.setCommercePriceE...
python
def plot_raster(self, ax, xlim, x, y, pop_names=False, markersize=20., alpha=1., legend=True, marker='o', rasterized=True): """ Plot network raster plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSu...