language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Anima open(String url, String user, String pass, Quirks quirks) { return open(new Sql2o(url, user, pass, quirks)); }
java
public LauncherTypeEnum getLauncherType() { return Enums.getIfPresent(LauncherTypeEnum.class, this.getProp(ConfigurationKeys.JOB_LAUNCHER_TYPE_KEY, JobLauncherFactory.JobLauncherType.LOCAL.name())) .or(LauncherTypeEnum.LOCAL); }
python
def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument """ Called when a window resize signal is detected Resets the scroll window """ # Make sure only one resize handler is running try: assert self.resize_lock except Assertion...
java
public static String makeClassPath(TopologyAPI.Topology topology, String originalPackageFile) { String originalPackage = new File(originalPackageFile).getName(); StringBuilder classPathBuilder = new StringBuilder(); // TODO(nbhagat): Take type of package as argument. if (originalPackage.endsWith(".jar")...
python
def _normalize_merge_diff(diff): """Make compare_config() for merge look similar to replace config diff.""" new_diff = [] for line in diff.splitlines(): # Filter blank lines and prepend +sign if line.strip(): new_diff.append("+" + line) if new_diff...
java
public T process(String[] arguments, T bean) { return process(Arrays.asList(arguments), bean); }
java
public static Class<?> erasure(Type type) { if (type instanceof ParameterizedType) { return erasure(((ParameterizedType)type).getRawType()); } if (type instanceof TypeVariable<?>) { return erasure(((TypeVariable<?>)type).getBounds()[0]); } if (type instance...
python
def setup_signals(self, ): """Connect the signals with the slots to make the ui functional :returns: None :rtype: None :raises: None """ self.duplicate_tb.clicked.connect(self.duplicate) self.delete_tb.clicked.connect(self.delete) self.load_tb.clicked.con...
java
public void setResourceEntryList(int i, ResourceEntry v) { if (ConceptMention_Type.featOkTst && ((ConceptMention_Type)jcasType).casFeat_resourceEntryList == null) jcasType.jcas.throwFeatMissing("resourceEntryList", "de.julielab.jules.types.ConceptMention"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas....
python
def prior_to_xarray(self): """Convert prior samples to xarray.""" prior = self.prior # filter posterior_predictive and log_likelihood prior_predictive = self.prior_predictive if prior_predictive is None: prior_predictive = [] elif isinstance(prior_predi...
java
protected Enumeration<URL> findResources(String name) throws IOException { return java.util.Collections.emptyEnumeration(); }
java
public List<AbstractPatternRule> loadFalseFriendRules(String filename) throws ParserConfigurationException, SAXException, IOException { if (motherTongue == null) { return Collections.emptyList(); } FalseFriendRuleLoader ruleLoader = new FalseFriendRuleLoader(motherTongue); try (InputStream i...
java
public final void mAUTO_ISO() throws RecognitionException { try { int _type = AUTO_ISO; int _channel = DEFAULT_TOKEN_CHANNEL; // druidG.g:603:10: ( ( 'AUTO_ISO' ) ) // druidG.g:603:11: ( 'AUTO_ISO' ) { // druidG.g:603:11: ( 'AUTO_ISO' ) // druidG.g:603:12: 'AUTO_ISO' { match("AUTO_ISO"); ...
java
private static void extractIccData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException { byte[] buffer = decodeHexCommentBlock(reader); if (buffer != null) new IccReader().extract(new ByteArrayReader(buffer), metadata); }
java
public void execute(Task task) { try { apply(this.task.getDestinationDir(), this.task.getClasspath()); } catch (IOException exception) { throw new GradleException("Error accessing file system", exception); } }
java
private String getPropertyLabel(PropertyIdValue propertyIdValue) { PropertyRecord propertyRecord = this.propertyRecords .get(propertyIdValue); if (propertyRecord == null || propertyRecord.propertyDocument == null) { return propertyIdValue.getId(); } else { return getLabel(propertyIdValue, propertyRecord...
java
@GET @Produces(MediaType.TEXT_PLAIN) @Description("Does not do anything. Is only supported for backwards compatibility.") @Path("/logout") public Response logout(@Context HttpServletRequest req) { return Response.ok("You have logged out.").build(); }
java
private void search(Node node, E q, int k, List<Neighbor<E, E>> neighbors) { int d = (int) distance.d(node.object, q); if (d <= k) { if (node.object != q || !identicalExcluded) { neighbors.add(new Neighbor<>(node.object, node.object, node.index, d)); } } ...
python
def _get_regex_pattern(label): """Return a regular expression of the label. This takes care of plural and different kinds of separators. """ parts = _split_by_punctuation.split(label) for index, part in enumerate(parts): if index % 2 == 0: # Word if not parts[index]...
python
def rank_items(self, userid, user_items, selected_items, recalculate_user=False): """ Rank given items for a user and returns sorted item list """ # check if selected_items contains itemids that are not in the model(user_items) if max(selected_items) >= user_items.shape[1] or min(selected_items)...
java
private <T> Observable<T> asObservable(Executor<T> transaction) { return Observable.create(emitter -> storeFactory.execute(new StoreTransaction<ChatStore>() { @Override protected void execute(ChatStore store) { try { transaction.execute(store, emitter)...
python
def _check_positions(self): '''Checks each bee to see if it abandons its current food source (has not found a better one in self._limit iterations); if abandoning, it becomes a scout and generates a new, random food source ''' self.__verify_ready() max_trials = 0 ...
python
def to_otu(self, biom_id=None): """Converts a list of objects associated with a classification result into a `dict` resembling an OTU table. Parameters ---------- biom_id : `string`, optional Optionally specify an `id` field for the generated v1 BIOM file. R...
java
public static String ENDPOINT_WRONG_PARAMS(Object arg0, Object arg1) { return localizer.localize(localizableENDPOINT_WRONG_PARAMS(arg0, arg1)); }
python
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value ...
python
def generate_device_id(steamid): """Generate Android device id :param steamid: Steam ID :type steamid: :class:`.SteamID`, :class:`int` :return: android device id :rtype: str """ h = hexlify(sha1_hash(str(steamid).encode('ascii'))).decode('ascii') return "android:%s-%s-%s-%s-%s" % (h[:8]...
python
def _get_min_max_value(min, max, value=None, step=None): """Return min, max, value given input values with possible None.""" # Either min and max need to be given, or value needs to be given if value is None: if min is None or max is None: raise ValueError('unable to infer range, value f...
python
def name_history(self): """A list of user names (as user can change those occasionally). :rtype: list """ history = [] idx = 0 get_history = self._iface.get_name_history uid = self.user_id while True: name = get_history(uid, idx) ...
python
def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs): # type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset] """ Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics. """ if not no_warn: warnings.warn("open_datasets is an...
python
def histogram(self, key, **dims): """Adds histogram with dimensions to the registry""" return super(MetricsRegistry, self).histogram( self.metadata.register(key, **dims))
java
protected void _syncProperties( final T object, final T p_object ) { BeansUtil.copyPropertiesExcept( p_object, object, new String[] { "persistentID" } ); }
java
public Matrix4d scaleAround(double factor, double ox, double oy, double oz) { return scaleAround(factor, factor, factor, ox, oy, oz, this); }
java
public String getProperty(final String key) { if (hasProperty(key)) { return properties.getProperty(key); } else { throw new PropertyLookupException("property not found: " + key); } }
java
public void detach(Object self) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { for (String fieldName : doc.fieldNames()) { Object value = getValue(self, fieldName, false, null); if (value instanceof OLazyObjectMultivalueElement) ((OLazyObjectMultivalueElement) value).detac...
java
public Optional<V> findOne(final K key) { return findOne(key, mongoProperties.getDefaultReadTimeout(), TimeUnit.MILLISECONDS); }
java
public GitlabAward getAward(GitlabIssue issue, Integer awardId) throws IOException { String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId() + GitlabAward.URL + "/" + awardId; return retrieve().to(tailUrl, GitlabAward.class); }
python
def remove_on_change(self, attr, *callbacks): ''' Remove a callback from this object ''' if len(callbacks) == 0: raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) fo...
java
public static String formatLatitude(Locale locale, double latitude, UnitType unit) { return format(locale, latitude, unit, NS); }
java
public static List<CPInstance> findByC_ST(long CPDefinitionId, int status, int start, int end) { return getPersistence().findByC_ST(CPDefinitionId, status, start, end); }
python
def sendcontrol(self, char): '''Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). ...
java
private byte[] berEncodedValue() { final ByteBuffer buff = ByteBuffer.allocate(5); buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); buff.put((byte) 0x03); // size buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x01); // int size buff.put(Numbe...
python
def pool(builder, size, timeout=None): """Create a pool that imposes a limit on the number of stored instances. Args: builder: a function to build an instance. size: the size of the pool. timeout(Optional[float]): the seconds to wait before raising a ``queue.Empty`` exce...
python
def request(self, request): """Sets the request of this V1beta1CertificateSigningRequestSpec. Base64-encoded PKCS#10 CSR data # noqa: E501 :param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501 :type: str """ if request is None: ...
python
def when_file_changed(*filenames, **kwargs): """ Register the decorated function to run when one or more files have changed. :param list filenames: The names of one or more files to check for changes (a callable returning the name is also accepted). :param str hash_type: The type of hash to use...
java
@Override public List<BaseStyler> getStylers(String... styleClasses) throws VectorPrintException { if (styleClasses == null || styleClasses.length == 0 || styleClasses[0] == null || styleClasses[0].isEmpty()) { return Collections.EMPTY_LIST; } List<BaseStyler> stylers = new ArrayList<>(sty...
java
public static String get(final String templateName, final Map<String, Object> data) { StringWriter writer = new StringWriter(); write(templateName, data, writer); return writer.toString(); }
python
def _remove_some_work_units(self, work_spec_name, work_unit_names, suffix='', priority_min='-inf', priority_max='+inf'): '''Remove some units from somewhere.''' now = time.time() if work_unit_names is None: count = 0 ...
python
def element_wise(self, other, op): """ Apply an elementwise operation to data. Both self and other data must have the same mode. If self is in local mode, other can also be a numpy array. Self and other must have the same shape, or other must be a scalar. Parameters ...
python
def refresh_client(self): """ Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date. """ req = self.session.post( self._fmip_refresh_url, params=self.params, data=json.dumps( { ...
java
public static Builder from(Reader swaggerReader) { Validate.notNull(swaggerReader, "swaggerReader must not be null"); Swagger swagger; try { swagger = new SwaggerParser().parse(IOUtils.toString(swaggerReader)); } catch (IOException e) { throw new RuntimeException(...
java
public ListOrdersRequest withPaymentMethod(String... values) { List<String> list = getPaymentMethod(); for (String value : values) { list.add(value); } return this; }
java
public static void newBuilder(String projectId, String topicId) throws Exception { ProjectTopicName topic = ProjectTopicName.of(projectId, topicId); Publisher publisher = Publisher.newBuilder(topic).build(); try { // ... } finally { // When finished with the publisher, make sure to shutdown ...
java
@Override public void actionPerformed(ActionEvent event) { Object mysource = event.getSource(); if ( ! (mysource instanceof JComboBox )) { super.actionPerformed(event); return; } @SuppressWarnings("unchecked") JComboBox<String> source = (JComboBox<String>) event.getSource(); String value = source....
python
def set_xylims(self, lims, axes=None, panel=None): """overwrite data for trace t """ if panel is None: panel = self.current_panel self.panels[panel].set_xylims(lims, axes=axes, **kw)
java
@Override public List<Job> parse(String text) throws ParseException { final List<Job> jobs; if (StringUtils.isNotBlank(text)) { text = StringUtils.replace(text, "\n\t", ""); jobs = new LinkedList<Job>(); String separator = "\n"; if (text.indexOf("\r\n"...
python
def __initialize_ui(self): """ Initializes the View ui. """ self.viewport().installEventFilter(ReadOnlyFilter(self)) if issubclass(type(self), QListView): super(type(self), self).setUniformItemSizes(True) elif issubclass(type(self), QTreeView): s...
java
public ResourceName parentName() { PathTemplate parentTemplate = template.parentTemplate(); return new ResourceName(parentTemplate, values, endpoint); }
java
public static <T, K> boolean moveUp(List<T> list, K key, Function<T, K> keyMapper, int n) { if (list == null) return false; ArrayList<T> newList = new ArrayList<T>(); boolean changed = false; for (int i = 0; i < list.size(); i++) { T item = list.get(i); if (i > 0 && key.equals(keyMapper.ap...
java
private static void parseFilters(final FilterType filterType, final WebApp webApp) { final WebAppFilter filter = new WebAppFilter(); if (filterType.getFilterName() != null) { filter.setFilterName(filterType.getFilterName().getValue()); } if (filterType.getFilterClass() != null) { filter.setFilterCla...
python
def dry_run_report(self): """ Returns text displaying the items that need to be uploaded or a message saying there are no files/folders to upload. :return: str: report text """ project_uploader = ProjectUploadDryRun() project_uploader.run(self.local_project) ...
python
def update_parameter(self, parameter_id, content=None, name=None, param_type=None): """ Updates the parameter attached to an Indicator or IndicatorItem node. All inputs must be strings or unicode objects. :param parameter_id: The unique id of the parameter to modify :param cont...
python
def GetAPFSVolumeByPathSpec(self, path_spec): """Retrieves an APFS volume for a path specification. Args: path_spec (PathSpec): path specification. Returns: pyfsapfs.volume: an APFS volume or None if not available. """ volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path...
java
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { int context = getArg0AsNode(xctxt); XObject val; if (DTM.NULL != context) { DTM dtm = xctxt.getDTM(context); String qname = dtm.getNodeNameX(context); val = (null == qname) ? XString.EMPTYS...
java
@Override public Endpoint next(Endpoint[] array) { return array[(int) (System.nanoTime() % array.length)]; }
java
public void readExternal(PofReader reader) throws IOException { name = reader.readString(0); last = reader.readLong(1); }
python
def get_templates(self, team_context, workitemtypename=None): """GetTemplates. [Preview API] Gets template :param :class:`<TeamContext> <azure.devops.v5_0.work_item_tracking.models.TeamContext>` team_context: The team context for the operation :param str workitemtypename: Optional, When ...
python
def list_presets(self, package_keyname, **kwargs): """Gets active presets for the given package. :param str package_keyname: The package for which to get presets :returns: A list of package presets that can be used for ordering """ get_kwargs = {} get_kwargs['mask'] = k...
python
def for_class(digobj, repo): '''Generate a ContentModel object for the specified :class:`DigitalObject` class. Content model object is saved in the specified repository if it doesn't already exist.''' full_name = '%s.%s' % (digobj.__module__, digobj.__name__) cmodels = getattr(d...
java
public Observable<ServiceResponse<ContentKeyPolicyPropertiesInner>> getPolicyPropertiesWithSecretsWithServiceResponseAsync(String resourceGroupName, String accountName, String contentKeyPolicyName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.clien...
java
public List<CmsRelation> getRelationsForResource( CmsRequestContext context, CmsResource resource, CmsRelationFilter filter) throws CmsException { List<CmsRelation> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check...
python
def add_documents(self, documents): ''' Adds more than one document using the same API call Returns two lists: the first one contains the successfully uploaded documents, and the second one tuples with documents that failed to be uploaded and the exceptions raised. ''' ...
java
@Benchmark public int constructAndIter(ConstructAndIterState state) { int dataSize = state.dataSize; int[] data = state.data; MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap(); for (int i = 0; i < dataSize; i++) { mutableBitmap.add(data[i]); } ImmutableBitmap bitmap = fact...
java
public FailoverGroupInner beginForceFailoverAllowDataLoss(String resourceGroupName, String serverName, String failoverGroupName) { return beginForceFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName).toBlocking().single().body(); }
python
def send(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`.""" if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell....
java
@Override public SetDefaultPolicyVersionResult setDefaultPolicyVersion(SetDefaultPolicyVersionRequest request) { request = beforeClientExecution(request); return executeSetDefaultPolicyVersion(request); }
python
def build_final_response(request, meta, result, menu, hproject, proxyMode, context): """Build the final response to send back to the browser""" if 'no_template' in meta and meta['no_template']: # Just send the json back return HttpResponse(result) # TODO this breaks pages not using new template ...
java
public String getViewPath(String className, String methodName, String viewName) { if (Strings.isNotEmpty(viewName)) { if (viewName.charAt(0) == Constants.separator) { return viewName; } } Profile profile = profileServie.getProfile(className); if (null == profile) { throw new RuntimeException("no c...
java
public void marshall(DescribeEnvironmentMembershipsRequest describeEnvironmentMembershipsRequest, ProtocolMarshaller protocolMarshaller) { if (describeEnvironmentMembershipsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { ...
java
public static <T> ConjunctionMatcher<T> compose(Iterable<Matcher<? super T>> matchers) { return compose(null, matchers); }
python
def handleContractDetails(self, msg, end=False): """ handles contractDetails and contractDetailsEnd """ if end: # mark as downloaded self._contract_details[msg.reqId]['downloaded'] = True # move details from temp to permanent collector self.contract_deta...
python
def find_packages_by_root_package(where): """Better than excluding everything that is not needed, collect only what is needed. """ root_package = os.path.basename(where) packages = [ "%s.%s" % (root_package, sub_package) for sub_package in find_packages(where)] packages.insert(0...
python
def rpc_name(rpc_id): """Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of...
java
public static Headers of(Map<String, String> headers) { if (headers == null) throw new NullPointerException("headers == null"); // Make a defensive copy and clean it up. String[] namesAndValues = new String[headers.size() * 2]; int i = 0; for (Map.Entry<String, String> header : ...
python
def register_callback_created(self, func, serialised=True): """ Register a callback for resource creation. This will be called when any *new* resource is created within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. ...
java
private InternalCacheEntry<WrappedBytes, WrappedBytes> performRemove(long bucketHeadAddress, long actualAddress, WrappedBytes key, WrappedBytes value, boolean requireReturn) { long prevAddress = 0; // We only use the head pointer for the first iteration long address = bucketHeadAddress; ...
java
public static String buildHostsOnlyList(List<HostAndPort> hostAndPorts) { StringBuilder sb = new StringBuilder(); for (HostAndPort hostAndPort : hostAndPorts) { sb.append(hostAndPort.getHostText()).append(","); } if (sb.length() > 0) { sb.delete(sb.length() - 1, sb.length()); } retur...
python
def bitset(bs, member_label=None, filename=None, directory=None, format=None, render=False, view=False): """Graphviz source for the Hasse diagram of the domains' Boolean algebra.""" if member_label is None: member_label = MEMBER_LABEL if filename is None: kind = 'members' if memb...
java
public void product(IntIntVector other) { // TODO: Add special case for IntIntDenseVector. for (int i=0; i<idxAfterLast; i++) { elements[i] *= other.get(i); } }
python
def export(cwd, remote, target=None, user=None, username=None, password=None, revision='HEAD', *opts): ''' Create an unversioned copy of a tree. cwd The path to the Subversion repository remote : None URL and ...
java
@Override public EEnum getIfcFlowInstrumentTypeEnum() { if (ifcFlowInstrumentTypeEnumEEnum == null) { ifcFlowInstrumentTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(993); } return ifcFlowInstrumentTypeEnumEEnum; }
python
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The ...
java
public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException { FieldType fieldType = verifyColumnName(columnName); if (fieldType.isForeignCollection()) { throw new SQLException("Can't update foreign colletion field: " + columnName); } addUpdateColumnToList(columnName, ne...
python
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTe...
java
public void sendComponent(Component componentRequest) throws TCAPSendException { if (this.previewMode) return; if (this.provider.getStack().getStatisticsEnabled()) { switch (componentRequest.getType()) { case Invoke: this.provider.getStack()....
java
@Deprecated public BillingInfo createOrUpdateBillingInfo(final BillingInfo billingInfo) { final String accountCode = billingInfo.getAccount().getAccountCode(); // Unset it to avoid confusing Recurly billingInfo.setAccount(null); return doPUT(Account.ACCOUNT_RESOURCE + "/" + accountCo...
java
@Override public DescribeComplianceByResourceResult describeComplianceByResource(DescribeComplianceByResourceRequest request) { request = beforeClientExecution(request); return executeDescribeComplianceByResource(request); }
java
@Override @Pure protected Class<?> findClass(final String name) throws ClassNotFoundException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws ClassNotFoundException { final String path = name.replace('.', '/').concat(".c...
python
def get_account(self): """Get details of the current account. :returns: an account object. :rtype: Account """ api = self._get_api(iam.DeveloperApi) return Account(api.get_my_account_info(include="limits, policies"))
python
def uniform(self, low: float, high: float) -> float: """Return a random floating number in the range: low <= n <= high. Args: low (float): The lower bound of the random range. high (float): The upper bound of the random range. Returns: float: A random float....
python
def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False): r"""Raises ValidationException if value is not a valid filename. Filenames can't contain \\ / : * ? " < > | Returns the value argument. * value (str): The value being valida...