language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static boolean containsSyntheticParameterName(MethodSymbol sym) { return sym.getParameters().stream() .anyMatch(p -> SYNTHETIC_PARAMETER_NAME.matcher(p.getSimpleName()).matches()); }
python
def get(self, request, *args, **kwargs): """ List all products in the shopping cart """ cart = ShoppingCartProxy(request) return JsonResponse(cart.get_products(onlypublic=request.GET.get('onlypublic', True)))
python
def include_notify_js_variables(context): """ Inclusion template tag to include all JS variables required by the notify.js file on the HTML page around <script> tags. Example:: {% include_notify_js_variables %} :return: Prepares context for rendering in the inclusion file. """ ctx ...
java
public Vector<Object> getSpecificationRepositoriesOfAssociatedProject(Vector<Object> repositoryParams) { try { Repository repository = loadRepository( repositoryParams ); Collection<Repository> repositories = service.getSpecificationRepositoriesOfAssociatedProject(repository...
python
def websocket_connect(self, message): """Called when WebSocket connection is established.""" self.session_id = self.scope['url_route']['kwargs']['subscriber_id'] super().websocket_connect(message) # Create new subscriber object. Subscriber.objects.get_or_create(session_id=self.s...
java
public UnindexedFace withReasons(String... reasons) { if (this.reasons == null) { setReasons(new java.util.ArrayList<String>(reasons.length)); } for (String ele : reasons) { this.reasons.add(ele); } return this; }
python
def to_frame(self, data, state): """ Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so ...
python
def wraplet(cls, *cls_args, **cls_kwargs): """ Create a factory to produce a Wrapper from a slave factory :param cls_args: positional arguments to provide to the Wrapper class :param cls_kwargs: keyword arguments to provide to the Wrapper class :return: .. code:: python...
java
public synchronized Document readPolicy(URL url) throws ParsingException { try { return readPolicy(url.openStream()); } catch (IOException ioe) { throw new ParsingException("Failed to resolve the URL: " + url.toString(), ioe); } }
java
@Override public ListRunsResult listRuns(ListRunsRequest request) { request = beforeClientExecution(request); return executeListRuns(request); }
java
protected void cleanupFromFinish() { _response = null; _bufferSize = 0; _encoding = null; // LIBERTY _responseBuffer = null; // _outWriterEncoding = null; _gotOutputStream = false; _gotWriter = false; this._pwriter = null; }
java
@Override public String requestDepositAddress(Currency currency, String... arguments) throws IOException { try { CoingiDepositWalletRequest request = new CoingiDepositWalletRequest().setCurrency(currency.getCurrencyCode().toUpperCase()); return depositWallet(request).getAddress(); } catc...
java
private Cell findCell() { final int rowStart = startRow < 0 ? 0 : startRow; final int columnStart = startColumn < 0 ? 0 : startColumn; final int maxRow = POIUtils.getRows(sheet); for(int i=rowStart; i < maxRow; i++) { final Row row = sheet.getRow(i); ...
python
def autoLayout(self): """ Automatically lays out the contents for this widget. """ try: direction = self.currentSlide().scene().direction() except AttributeError: direction = QtGui.QBoxLayout.TopToBottom size = self.size() ...
java
public String restore(String repositoryName, String workspaceName, String backupId, InputStream config, String backupSetPath, boolean removeExists) throws IOException, BackupExecuteException { BackupAgentResponse response = null; String sURL = null; String backupSetP...
java
public ServiceFuture<Void> patchAsync(String jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(patchWithServiceResponseAsync(jobScheduleId, jobSchedulePatchPa...
java
public boolean addRowsForKey(RestoreResultKey key, VoltTable vt) { if (vt == null || key == null) { return false; } RestoreResultValue value = get(key); if (value == null) { return false; } try { if (key.m_partitionId == -1) { ...
java
public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) { query.put(queryParameterName, queryParameterEncodedValue); return this; }
python
def readLine(self): """ read a line Maintains its own buffer, callers of the transport should not mix calls to readBytes and readLine. """ if self.buf is None: self.buf = [] # Buffer may already have a line if we've received unilateral # response(s) f...
java
private static void warn(Object scope, String propertyPath) { if(scope == null) { log.warn("Null object scope while searching for property |%s|.", propertyPath); } else { log.warn("Null value for |%s#%s|.", scope.getClass(), propertyPath); } }
python
def get(**kwargs): """ Safe sensor wrapper """ sensor = None tick = 0 driver = DHTReader(**kwargs) while not sensor and tick < TIME_LIMIT: try: sensor = driver.receive_data() except DHTException: tick += 1 return sensor
python
def open_recruitment(self, n=1): """Open recruitment.""" logger.info("Opening Sim recruitment for {} participants".format(n)) return {"items": self.recruit(n), "message": "Simulated recruitment only"}
java
public static boolean hasWebArgumentMetadata(final JCas jCas) { FSIterator<FeatureStructure> iterator = jCas.getCas().getIndexRepository().getAllIndexedFS( CasUtil.getType(jCas.getCas(), WebArgumentMetadata.class)); return iterator.hasNext(); }
java
public static <N extends AbstractDTNode<?, ?, ?, N>> Iterator<N> innerNodeIterator(N root) { return Iterators.filter(nodeIterator(root), n -> !n.isLeaf()); }
python
def __isValidZIP(self, suffix): """Determine if the suffix is `.zip` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".zip"): return True return False
java
public Scope getEnclosingScope() { AstNode parent = this.getParent(); while (parent != null && !(parent instanceof Scope)) { parent = parent.getParent(); } return (Scope)parent; }
python
def get_call_name(self, node): """ Return call name for the given node. """ if isinstance(node.func, ast.Attribute): return node.func.attr elif isinstance(node.func, ast.Name): return node.func.id
python
def _SchemedMerge(self, scheme, a, b): """Tries to merge two entities according to a merge scheme. A scheme is specified by a map where the keys are entity attributes and the values are merge functions like Merger._MergeIdentical or Merger._MergeOptional. The entity is first migrated to the merged sche...
python
def run(self): """Modified ``run`` that captures return value and exceptions from ``target``""" try: if self._target: return_value = self._target(*self._args, **self._kwargs) if return_value is not None: self._exception = OrphanedReturn(sel...
java
@Pure @Inline(value = "$3.union($1, $2)", imported = MapExtensions.class) public static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) { return union(left, right); }
java
protected static String getCmsPath(String path) { String slashPath = path.replace('\\', '/'); // split path into components, translate each of them separately, then combine them again at the end String[] segments = slashPath.split("/"); List<String> nonEmptySegments = new ArrayLi...
java
public void setIpPermissions(java.util.Collection<IpPermission> ipPermissions) { if (ipPermissions == null) { this.ipPermissions = null; return; } this.ipPermissions = new com.amazonaws.internal.SdkInternalList<IpPermission>(ipPermissions); }
python
def invalidate(self): """ Invalidate access tokens with a client/access token pair Returns: dict: Empty or error dict """ endpoint = '/invalidate' payload = { 'accessToken': self.access_token, 'clientToken': self.client_token, ...
python
def patterns(self): """Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns """ all_patterns = [] for label, patterns in self.token_patterns.items(): ...
python
def _do_timeout_for_leave(self, timeout, datapath, dst, in_port): """the process when the QUERY from the switch timeout expired.""" parser = datapath.ofproto_parser dpid = datapath.id hub.sleep(timeout) outport = self._to_querier[dpid]['port'] if self._to_hosts[dpid][ds...
python
def garbage_cycle(index): """Get reference cycle details.""" graph = _compute_garbage_graphs()[int(index)] graph.reduce_to_cycles() objects = graph.metadata objects.sort(key=lambda x: -x.size) return dict(objects=objects, index=index)
java
@Nonnull public static NonBlockingByteArrayOutputStream getCopyWithLimit (@Nonnull @WillClose final InputStream aIS, @Nonnegative final long nLimit) { final int nAvailable = Math.max (DEFAULT_BUFSIZE, getAvailable (aIS)); final NonBlockingBy...
python
def get_boundaries(self, filter_type, value): """Compute the boundaries to pass to zrangebylex depending of the filter type The third return value, ``exclude`` is ``None`` except for the filters `lt` and `gt` because we cannot explicitly exclude it when querying the sorted-set ...
java
@Override public org.bytedeco.javacpp.Pointer getHostPointer(DataBuffer buffer) { AllocationPoint dstPoint = ((BaseCudaDataBuffer) buffer).getAllocationPoint(); // return pointer with offset if needed. length is specified for constructor compatibility purposes if (dstPoint.getPointers().get...
python
def create_layer(self, lipid_indices=None, flip_orientation=False): """Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, defau...
java
public void compile(ModuleConfiguration configuration) { LOGGER.debug("Compiling module {}", configuration); FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class); Importer importer = injector.getInstance(Importer.class); CompilerRegistry registry = injector...
java
protected static int[] appendUnknownNetworkTypeToTypes(int[] types) { int i = 0; final int[] extendedTypes = new int[types.length + 1]; for (int type : types) { extendedTypes[i] = type; i++; } extendedTypes[i] = Connectivity.UNKNOWN_TYPE; return extendedTypes; }
python
def _get_regional_term(self, C, imt, vs30, rrup): """ In accordance with Abrahamson et al. (2014) we assume as the default region California """ vs30star = self._get_vs30star(vs30, imt) return C['a31'] * np.log(vs30star/C['vlin']) + C['a25'] * rrup
python
def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
python
def get_statement(self, session_id: int, statement_id: int) -> Statement: """Get information about a statement in a session. :param session_id: The ID of the session. :param statement_id: The ID of the statement. """ response = self._client.get( f"/sessions/{session_...
python
def deserializeG1(x, compressed=True): """ Deserializes an array of bytes, @x, into a G1 element. """ return _deserialize(x, G1Element, compressed, librelic.g1_read_bin_abi)
java
public String getTableNames(boolean bAddQuotes) { return (m_tableName == null) ? Record.formatTableNames(ANNIVERSARY_FILE, bAddQuotes) : super.getTableNames(bAddQuotes); }
java
@Override public void run() { if (state.compareAndSet(State.STARTED, State.STOPPING)) { for (final Runnable hook : hooks) { try { hook.run(); } catch (final Throwable t) { LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception...
python
def _shl32(ins): """ Logical Left shift 32bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 0, do nothing """ op1, op2 = tuple(ins.quad[2:]) if is_int(op2): output = _32bit_oper(op1) if int(op2) == 0: outpu...
java
private void addTypeElement(TypeElement typeElement, Map<PackageElement, SortedSet<TypeElement>> map) { PackageElement pkg = utils.containingPackage(typeElement); if (utils.isSpecified(pkg) || configuration.nodeprecated && utils.isDeprecated(pkg)) { // No need to catalog this class if it's ...
python
def update_event_data(self, num, data): """Update event data in dataset.""" if num < 0 or num >= self.params["events_num"]: raise IndexError("Index out of range [0:%s]" % (self.params["events_num"])) if isinstance(data, np.ndarray): raise Typ...
java
public void init(final String name, final boolean[] value, final int dim_x, final int dim_y) { buildAttributeValueObject(name); insert(value, dim_x, dim_y); }
python
def items(self): """ return list of pair of name and value of all declared columns. """ return [ (c.name, getattr(self, c.name, None)) for c in self.__table__._columns ]
python
def setup_versioneer(): """ Generate (temporarily) versioneer.py file in project root directory :return: """ try: # assume versioneer.py was generated using "versioneer install" command import versioneer versioneer.get_version() except ImportError: # it looks vers...
java
private void declare(IndentingWriter o, IParam p) throws BindingException { TypeBinding vb = TypeBinding.bind(g, p.getType(), p.getName()); String javaType = vb.javaType; if (method.isVarArg() && p == params[params.length - 1]) { // use varargs if applicable if (javaType.endsWith("[]")) ...
java
@Override public void run() { while (running) { try { handleIO(); } catch (IOException e) { logRunException(e); } catch (CancelledKeyException e) { logRunException(e); } catch (ClosedSelectorException e) { logRunException(e); } catch (IllegalStateExcep...
python
def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__dict__) d.pop('_weights', None) d.pop('_A', None) d.pop('_B', None) d.pop('_f', None) d.pop('_mK', None) ...
java
public void output(final WireFeed feed, final Writer writer, final boolean prettyPrint) throws IllegalArgumentException, IOException, FeedException { final Document doc = outputJDom(feed); final String encoding = feed.getEncoding(); Format format; if (prettyPrint) { format = ...
java
public D getDestination(final S source){ try { return mapper.nullVSouAllAll(source); } catch (Exception e) { JmapperLog.error(e); } return null; }
java
@Override public INDArray toDense() { // TODO support view conversion INDArray result = Nd4j.zeros(shape()); switch (data().dataType()) { case DOUBLE: for (int i = 0; i < length; i++) { int[] idx = getUnderlyingIndicesOf(i).asInt(); ...
python
def start_sim(self, gui=True, set_values={}, error=None): """ Run the simulation in the background, showing the GUI by default. """ self.error = error if not self.is_running.is_set(): def loop(): self.need_to_stop.clear() self.is_runnin...
python
def install_deb(pkgname, url): """Install package from custom deb hosted on S3. Return true if package was installed by this invocation.""" status = run("dpkg-query -W -f='${{Status}}' {p}; true".format(p=pkgname)) if ('installed' not in status) or ('not-installed' in status): deb = url.rpartiti...
python
def write_data(self, command, data, timeout=None): """Shortcut for writing specifically a DataMessage.""" self.write_message(FilesyncMessageTypes.DataMessage(command, data), timeout)
python
def dependencies(self): """ The number of extra rows needed for each of our inputs to compute this term. """ extra_input_rows = max(0, self.window_length - 1) out = {} for term in self.inputs: out[term] = extra_input_rows out[self.mask] = 0 ...
java
public <T extends Enum<T>> void write(final Enum<T> value) throws IOException { final long ordinal = value.ordinal(); this.write(new Bits(ordinal, 8)); }
java
public static boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { return false; } NetworkInfo info = cm.getActiveNetworkInfo(); return info != null && info.isConnectedOrConnecting()...
java
public static void processTask(Task task) { logger.finest("Processing task " + task); try { switch (task.getType()) { case RUN_JOB: runJob((RunJobTask) task); break; case HANDLE_SLOT_FILLED: handleSlotFilled((HandleSlotFilledTask) task); break; ...
java
public void setRdfa(String rdfa) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(rdfa)) { m_rdfa = rdfa.trim(); } else { m_rdfa = rdfa; } }
python
def list_huisnummers_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie ...
java
public SetRepeatModeOnUsersPlaybackRequest.Builder setRepeatModeOnUsersPlayback(String state) { return new SetRepeatModeOnUsersPlaybackRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .state(state); }
java
public void add(char[] str, int idx) { SAXRecord rr = records.get(String.valueOf(str)); if (null == rr) { rr = new SAXRecord(str, idx); this.records.put(String.valueOf(str), rr); } else { rr.addIndex(idx); } this.realTSindex.put(idx, rr); }
python
def from_node(cls, work): """Initialize an instance from a :class:`Work` instance.""" new = super().from_node(work) # Will put all files found in outdir in GridFs # Warning: assuming binary files. d = {os.path.basename(f): f for f in work.outdir.list_filepaths()} new.reg...
java
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { return new FutureTask<T>(callable); }
java
@RequestMapping(value = "information/{entityType}/{id}", method = RequestMethod.GET) public Resources<EntityInformation> getInformation(@PathVariable ProjectEntityType entityType, @PathVariable ID id) { // Gets the entity ProjectEntity entity = getEntity(entityType, id); // List of informati...
java
SubjectIdentity getSubjectIdentity(final String protocol, final String forHost) { KeytabService selectedService = null; final String hostName = forHost == null ? null : forHost.toLowerCase(Locale.ENGLISH); String name = protocol + "/" + hostName; selectedService = hostServiceMap.get(nam...
python
def powerset(iterable, nonempty=False, reverse=False): """Generate the power set of an iterable. Args: iterable (Iterable): The iterable from which to generate the power set. Keyword Args: nonempty (boolean): If True, don't include the empty set. reverse (boolean): If True, reverse...
python
def _get_running_workers_names(running_workers: list): """May contain sensitive info (like user ids). Use with care.""" return FormattedText().join( [ FormattedText().newline().normal(" - {name}").start_format().bold(name=worker.name).end_format() for worker i...
java
public TypeSpec createCurrencyUtil(String className, Map<String, CurrencyData> currencies) { TypeSpec.Builder type = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC); CurrencyData defaultData = currencies.get("DEFAULT"); currencies.remove("DEFAULT"); MethodSpec.Builder c...
python
def repr2_json(obj_, **kwargs): """ hack for json reprs """ import utool as ut kwargs['trailing_sep'] = False json_str = ut.repr2(obj_, **kwargs) json_str = str(json_str.replace('\'', '"')) json_str = json_str.replace('(', '[') json_str = json_str.replace(')', ']') json_str = json_str.re...
java
public static String getFileName(String fileNameAndPath) { if (fileNameAndPath == null){ return null; } String fileSeparator; if(fileNameAndPath.contains("/")){ fileSeparator = "/"; }else{ fileSeparator = "\\"; } int lastIndexOf=fileNameAndPath.lastIndexOf(fileSeparator)...
java
public com.bazaarvoice.ostrich.AsyncServicePool<S> buildAsync() { ServicePool<S> pool = buildInternal(); boolean shutdownAsyncExecutorOnClose = (_asyncExecutor == null); if (_asyncExecutor == null) { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNa...
java
@Override public ServiceRegistration<?> registerService(String clazz, Object service, Dictionary<String, ?> properties) { MockServiceReference<Object> serviceReference = new MockServiceReference<Object>(getBundle(), properties); if (serviceRegistrations.get(clazz) == null) { serviceRegistrations.put...
python
def module_getmtime(filename): """ Get the mtime associated with a module. If this is a .pyc or .pyo file and a corresponding .py file exists, the time of the .py file is returned. :param filename: filename of the module. :returns: mtime or None if the file doesn"t exist. """ if os.path.sp...
java
@Override void findReferencedClassNames(final Set<String> classNameListOut) { if (classBound != null) { classBound.findReferencedClassNames(classNameListOut); } for (final ReferenceTypeSignature typeSignature : interfaceBounds) { typeSignature.findReferencedClassNames...
java
public static java.util.List<com.liferay.commerce.model.CPDefinitionInventory> getCPDefinitionInventoriesByUuidAndCompanyId( String uuid, long companyId) { return getService() .getCPDefinitionInventoriesByUuidAndCompanyId(uuid, companyId); }
python
def delete(self, params=None): """Delete this resource from the server, passing the specified query parameters. If this resource doesn't support ``DELETE``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. ...
python
def add_button_box(self, stdbtns): """Create dialog button box and add it to the dialog layout""" bbox = QDialogButtonBox(stdbtns) run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole) run_btn.clicked.connect(self.run_btn_clicked) bbox.accepted.connect(self.accept)...
python
def _add_fbc_objective(self, model_tag, obj_id): """Adds the objective(s) to the sbml document.""" objective_list = ET.SubElement(model_tag, _tag( 'listOfObjectives', FBC_V2)) objective_list.set(_tag('activeObjective', FBC_V2), 'O_1') objective_tag = ET.SubElement( ...
python
def from_raw(self, file_names=None, **kwargs): """Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together. """ # T...
java
public static LoggerContext getContext(final ClassLoader loader, final boolean currentContext) { try { return factory.getContext(FQCN, loader, null, currentContext); } catch (final IllegalStateException ex) { LOGGER.warn(ex.getMessage() + " Using SimpleLogger"); retur...
python
def password_hash(password): """Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str """ try: return bcrypt_sha256.encrypt(password) except TypeError: return bcrypt_sha256.encrypt...
java
@GwtIncompatible("To be supported") @Override MapMaker keyEquivalence(Equivalence<Object> equivalence) { checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); keyEquivalence = checkNotNull(equivalence); this.useCustomMap = true; return this; }
python
def get_area_extent(self, size, offsets, factors, platform_height): """Get the area extent of the file.""" nlines, ncols = size h = platform_height # count starts at 1 cols = 1 - 0.5 lines = 1 - 0.5 ll_x, ll_y = self.get_xy_from_linecol(lines, cols, offsets, fact...
python
def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False): """Set the permissions and ownership of a path. Args: path: string, the path for which owner ID and group ID needs to be setup. mode: octal string, the permissions to set on the path. uid: int, the owner ID to be set for the path. ...
python
def save_to_object(self): """Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data. """ tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir) checkpoint...
java
protected String getTargetPath (File fromDir, String path) { return path.substring(0, path.length()-4) + ".jar"; }
python
def update_manual_intervention(self, manual_intervention_update_metadata, project, release_id, manual_intervention_id): """UpdateManualIntervention. [Preview API] Update manual intervention. :param :class:`<ManualInterventionUpdateMetadata> <azure.devops.v5_1.release.models.ManualInterventionUpd...
python
def initialize_indices(self, **kwargs): """ creates all the indicies that are defined in the rdf definitions kwargs: action: which action is to be perfomed initialize: (default) tests to see if the index exisits if not creat...
java
public synchronized void addComponent(ComponentEvent event) { try { if(log.isDebugEnabled())log.debug("Component added "+event); Object o=event.getComponent(); ModelMBean mbean=ModelMBeanImpl.mbeanFor(o); if (mbean==null) l...
java
private static Collection<TileRef> getTiles(Map<ColorRgba, Collection<TileRef>> colors, ColorRgba color) { if (!colors.containsKey(color)) { colors.put(color, new HashSet<TileRef>()); } return colors.get(color); }