language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _compact(*args): """Returns a new list after removing any non-true values""" ret = {} if len(args) == 1: args = args[0] if isinstance(args, ListValue): args = args.value if isinstance(args, dict): for i, item in args.items(): if bool(item):...
python
def get_obj_url(request, obj): """ Returns object URL if current logged user has permissions to see the object """ if (is_callable(getattr(obj, 'get_absolute_url', None)) and (not hasattr(obj, 'can_see_edit_link') or (is_callable(getattr(obj, 'can_see_edit_link', None)) and obj....
python
def draw_mini_map(self, surf): """Draw the minimap.""" if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): # Draw the rendered version. surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.obs...
python
def _get_column(cls, name): """ Based on cqlengine.models.BaseModel._get_column. But to work with 'pk' """ if name == 'pk': return cls._meta.get_field(cls._meta.pk.name) return cls._columns[name]
python
def flight_time(logfile): '''work out flight time for a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename) in_air = False start_time = 0.0 total_time = 0.0 total_dist = 0.0 t = None last_msg = None last_time_usec = None while True:...
java
public final AbstractItem next(boolean allowUnavailable) throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "next", Boolean.valueOf(allowUnavailable)); AbstractItem found = null; // check from current position ...
python
def port_channels(self): """list[dict]: A list of dictionary items of port channels. Examples: >>> import pynos.device >>> switches = ['10.24.39.202'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ...
python
def skill_update(self, skill_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#update-skill-by-id" api_path = "/api/v2/skills/{skill_id}" api_path = api_path.format(skill_id=skill_id) return self.call(api_path, method="PUT", data=data, **kwargs)
python
def createSuperimposedSensorySDRs(sequenceSensations, objectSensations): """ Given two lists of sensations, create a new list where the sensory SDRs are union of the individual sensory SDRs. Keep the location SDRs from the object. A list of sensations has the following format: [ { 0: (set([1, 5, 10...
python
def distance(self): """The current distance from the tablet's sensor, normalized to the range [0, 1] and whether it has changed in this event. If this axis does not exist on the current tool, this property is (0, :obj:`False`). Returns: (float, bool): The current value of the the axis. """ distance ...
java
public static EntityKey fromData( EntityKeyMetadata entityKeyMetadata, GridType identifierGridType, final Serializable id, SharedSessionContractImplementor session) { Object[] values = LogicalPhysicalConverterHelper.getColumnsValuesFromObjectValue( id, identifierGridType, entityKeyMetadata.get...
python
def adapt_item(item, package, filename=None): """Adapts ``.epub.Item`` to a ``DocumentItem``. """ if item.media_type == 'application/xhtml+xml': try: html = etree.parse(item.data) except Exception as exc: logger.error("failed parsing {}".format(item.name)) ...
python
def stalecheck(web3, **kwargs): ''' Use to require that a function will run only of the blockchain is recently updated. If the chain is old, raise a StaleBlockchain exception Define how stale the chain can be with keyword arguments from datetime.timedelta, like stalecheck(web3, days=2) Turn o...
java
public DescribeIpResponse describeIp(DescribeIpRequest request) { InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, UTILS); checkNotNull(request.getIp()); internalRequest.addParameter("action", request.getAction()); internalRequest.addParameter("ip", reque...
python
def _request_reports(self, domains): """Sends multiples requests for the resources to a particular endpoint. Args: resource_param_name: a string name of the resource parameter. resources: list of of the resources. endpoint_name: AlexaRankingApi endpoint URL suffix. ...
python
def notch_fir(self, f1, f2, order, beta=5.0, remove_corrupted=True): """ notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and ...
java
public static String getClassFieldNameWithValue(Class clazz, Object value) { Field[] fields = clazz.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; try { Object constant = field.get(null); if (value.equals(constant)) { return clazz.getName() + "." + field.getName()...
java
public static boolean is_vargiya3(String str) { if (str.equals("g") || str.equals("j") || str.equals("q") || str.equals("d") || str.equals("b")) return true; return false; }
python
def clear(cls, fn): # type: (FunctionType) -> None """ Clear result cache on the given function. If the function has no cached result, this call will do nothing. Args: fn (FunctionType): The function whose cache should be cleared. """ if hasa...
python
def conversations_replies(self, *, channel: str, ts: str, **kwargs) -> SlackResponse: """Retrieve a thread of messages posted to a conversation Args: channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890' ts (str): Unique identifier of a thread's parent message....
java
public static String padTo(final int i, final int pad) { String n = Integer.toString(i); return padTo(n, pad); }
java
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception { try { byte[] buffer = base64.decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); return (RSAPublicKey) keyFactory.generatePublic(keySp...
java
@Override protected IIOMetadataNode getStandardDataNode() { IIOMetadataNode node = new IIOMetadataNode("Data"); IIOMetadataNode sampleFormat = new IIOMetadataNode("SampleFormat"); sampleFormat.setAttribute("value", header.getTransferType() == DataBuffer.TYPE_FLOAT ...
python
def generateVariantAnnotation(self, variant): """ Generate a random variant annotation based on a given variant. This generator should be seeded with a value that is unique to the variant so that the same annotation will always be produced regardless of the order it is generated ...
python
def control_number(endpoint): """Populate the ``control_number`` key. Also populates the ``self`` key through side effects. """ def _control_number(self, key, value): self['self'] = get_record_ref(int(value), endpoint) return int(value) return _control_number
python
def process_result_value(self, value, dialect): """ SQLAlchemy uses this to convert a string into a SourceLocation object. We separate the fields by a | """ if value is None: return None p = value.split("|") if len(p) == 0: return None ...
java
void buildCSSTypesDictionary() { String description; String value; TextSearchDictionaryEntry de; //search eval() expression description = "text/css"; value = "text/css"; de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009); v.add(de); }
python
def put(self, endpoint, json=None, params=None, **kwargs): """ PUT to DHIS2 :param endpoint: DHIS2 API endpoint :param json: HTTP payload :param params: HTTP parameters :return: requests.Response object """ json = kwargs['data'] if 'data' in kwargs else js...
python
def SetStorageWriter(self, storage_writer): """Sets the storage writer. Args: storage_writer (StorageWriter): storage writer. """ self._storage_writer = storage_writer # Reset the last event data information. Each storage file should # contain event data for their events. self._last_...
java
public DJBar3DChartBuilder addSerie(AbstractColumn column, String label) { getDataset().addSerie(column, label); return this; }
python
def clip_rect(self, x:float, y:float, w:float, h:float) -> None: """Clip further output to this rect.""" pass
java
private int getCountForRange(TableCountProbingContext probingContext, StrSubstitutor sub, Map<String, String> subValues, long startTime, long endTime) { String startTimeStr = Utils.dateToString(new Date(startTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT); String endTimeStr = Utils.dateToString(ne...
python
def get_dcap(self, cycle=None, dataset_number=None): """Returns discharge_capacity (in mAh/g), and voltage.""" # TODO: should return a DataFrame as default # but remark that we then have to update e.g. batch_helpers.py dataset_number = self._validate_dataset_number(dataset_number) ...
java
public static Path getTaskOutputPath(JobConf conf, String name) throws IOException { // ${mapred.out.dir} Path outputPath = getOutputPath(conf); if (outputPath == null) { throw new IOException("Undefined job output-path"); } OutputCommitter committer = conf.getOutputCommitter(); Path w...
python
def generate_tile_coordinates_from_pixels(roi, scale, size): """Yields N x M rectangular tiles for a region of interest. Parameters ---------- roi : GeoVector Region of interest scale : float Scale factor (think of it as pixel resolution) size : tuple Pixel size in (widt...
java
private static String getContentTypeEncoding(final String httpContentType) { String encoding = null; if (httpContentType != null) { final int i = httpContentType.indexOf(";"); if (i > -1) { final String postMime = httpContentType.substring(i + 1); ...
java
public boolean isDeflectorHealthy() { return deflectorHealth() .map(health -> !"red".equals(health.path("status").asText()) && indexSetRegistry.isUp()) .orElse(false); }
python
def lstm_init_states(batch_size): """ Returns a tuple of names and zero arrays for LSTM init states""" hp = Hyperparams() init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden) init_names = [s[0] for s in init_shapes] init_arrays = [mx.nd.ze...
java
private RequestConfig requestConfigWithSkipAppendUriPath(Request request) { RequestConfig config = new AmazonWebServiceRequestAdapter(request.getOriginalRequest()); config.getRequestClientOptions().setSkipAppendUriPath(true); return config; }
python
def close(self): """Closes the record and index files.""" if not self.is_open: return super(IndexCreator, self).close() self.fidx.close()
java
@XmlElement(name="method") public void setMethodInfos(final List<MethodInfo> methodInfos) { if(methodInfos == this.methodInfos) { // Java7の場合、getterで取得したインスタンスをそのまま設定するため、スキップする。 return; } this.methodInfos.clear(); for(MethodInfo item : method...
python
def get_objective_form_for_update(self, objective_id): """Gets the objective form for updating an existing objective. A new objective form should be requested for each update transaction. arg: objective_id (osid.id.Id): the ``Id`` of the ``Objective`` return:...
python
def live_pidfile(pidfile): # pragma: no cover """(pidfile:str) -> int | None Returns an int found in the named file, if there is one, and if there is a running process with that process id. Return None if no such process exists. """ pid = read_pidfile(pidfile) if pid: try: ...
python
def to_searchable_text_metadata(value): """Parse the given metadata value to searchable text :param value: The raw value of the metadata column :returns: Searchable and translated unicode value or None """ if not value: return u"" if value is Missing.Value: return u"" if is_...
java
public boolean create(String index) { CreateIndexRequestBuilder createIndexRequestBuilder = admin().indices().prepareCreate(index); return JMElasticsearchUtil.logRequestQueryAndReturn("create", createIndexRequestBuilder, createIndexRequestBuilder.execute()...
python
def exit_sync(self): ''' Waiting for all threads to appear, then continue. ''' if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]: raise RuntimeError('Thread name "%s" is not valid.') if self._scan_threads and self.current_module_...
python
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
java
@Override protected void enqueueNotification(final Notification not) { not.lastRun = System.currentTimeMillis(); final SubscriptionSummary summary = postNotification(not.subscriber, not.mimeType, not.payload); not.callback.onSummaryInfo(summary); }
java
public Sheet getSheet(long id, EnumSet<SheetInclusion> includes, EnumSet<ObjectExclusion> excludes, Set<Long> rowIds, Set<Integer> rowNumbers, Set<Long> columnIds, ...
java
@Requires({ "oldLocals != null", "extraIndex >= -1" }) @Ensures("result >= 0") protected int getPostDescOffset(List<Integer> oldLocals, int extraIndex) { int off = 0; if (extraIndex != -1) { ++off; } off += oldLocals.size(); return off; }
java
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return lastIndexOfIgnoreCase(str, searchStr, str.length()); }
java
public IfcProtectiveDeviceTrippingUnitTypeEnum createIfcProtectiveDeviceTrippingUnitTypeEnumFromString( EDataType eDataType, String initialValue) { IfcProtectiveDeviceTrippingUnitTypeEnum result = IfcProtectiveDeviceTrippingUnitTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentExcep...
java
public Message withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
@Override public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { if ((access & ACC_SYNTHETIC) != 0) throw new IllegalStateException("Cannot create type for anonym...
java
public Structure getStructureForPdbId(String pdbId) throws IOException, StructureException { if(pdbId == null) return null; if(pdbId.length() != 4) { throw new StructureException("Unrecognized PDB ID: "+pdbId); } while (checkLoading(pdbId)) { // waiting for loading to be finished... try { Threa...
java
public void setImage (Mirage image) { if (_mirage != null) { _totalTileMemory -= _mirage.getEstimatedMemoryUsage(); } _mirage = image; if (_mirage != null) { _totalTileMemory += _mirage.getEstimatedMemoryUsage(); } }
python
def WithLimitedCallFrequency(min_time_between_calls): """Function call rate-limiting decorator. This decorator ensures that the wrapped function will be called at most once in min_time_between_calls time for the same set of arguments. For all excessive calls a previous cached return value will be returned. ...
java
public Class<?> getClassType() { if (m_type == null) { return String.class; } try { return Class.forName(m_type); } catch (ClassNotFoundException e) { return String.class; } }
java
public ServiceException setException(Throwable innerException) { ByteArrayOutputStream messageOutputStream = new ByteArrayOutputStream(); innerException.printStackTrace(new PrintStream(messageOutputStream)); String exceptionMessage = messageOutputStream.toString(); this.fault.set...
java
private void computeDivUVD(GrayF32 u , GrayF32 v , GrayF32 psi , GrayF32 divU , GrayF32 divV , GrayF32 divD ) { final int stride = psi.stride; // compute the inside pixel for (int y = 1; y < psi.height-1; y++) { // index of the current pixel int index = y*stride + 1; for (int x = 1; x < psi...
python
def upload_file(self, path=None, stream=None, name=None, **kwargs): """ Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param stri...
python
def expect(self): ''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
python
def get_as_boolean_with_default(self, key, default_value): """ Converts map element into a boolean or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: boolean value ot the element or d...
python
def WriteHeader(self): """Writes the header to the output.""" output_text = self._field_delimiter.join(self._fields) output_text = '{0:s}\n'.format(output_text) self._output_writer.Write(output_text)
java
public void sendResponse(Response arg0) throws SipException, InvalidArgumentException { validateWrappedTransaction(); final Dialog d = wrappedTransaction.getDialog(); if (d != null) { final DialogWrapper dw = ra.getDialogWrapper(d); if (dw != null) { fin...
java
public static void join(Object strand, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { Strand.join(strand, timeout, unit); }
python
def on_init(app): # pylint: disable=unused-argument """ Run sphinx-apidoc and swg2rst after Sphinx initialization. Read the Docs won't run tox or custom shell commands, so we need this to avoid checking in the generated reStructuredText files. """ docs_path = os.path.abspath(os.path.dirname(__...
java
protected List<Map<String, ?>> generateComments() { final List<Map<String, ?>> list = new ArrayList<>(); // Block comment list.add(pattern(it -> { it.delimiters("(/\\*+)", "(\\*/)"); //$NON-NLS-1$ //$NON-NLS-2$ it.style(BLOCK_COMMENT_STYLE); it.beginStyle(BLOCK_COMMENT_DELIMITER_STYLE); it.endStyle(BL...
python
def _param_grad_helper(self, dL_dK, X, X2, target): """derivative of the covariance matrix with respect to the parameters.""" if X2 is None: X2 = X dist = np.abs(X - X2.T) ly=1/self.lengthscaleY lu=np.sqrt(3)/self.lengthscaleU #ly=self.lengthscaleY #lu=self.lengt...
python
def refine_MIDDLEWARE_CLASSES(original): """ Django docs say that the LocaleMiddleware should come after the SessionMiddleware. Here, we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position. Be careful with the order when refining the Middleware...
java
public static <T> List<T> query(Class<T> targetClass, final Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal) { final Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); ...
java
public static Trades adaptTrades(CexIOTrade[] cexioTrades, CurrencyPair currencyPair) { List<Trade> tradesList = new ArrayList<>(); long lastTradeId = 0; for (CexIOTrade trade : cexioTrades) { long tradeId = trade.getTid(); if (tradeId > lastTradeId) { lastTradeId = tradeId; } ...
python
def get_data_disk_size(vm_, swap, linode_id): ''' Return the size of of the data disk in MB .. versionadded:: 2016.3.0 ''' disk_size = get_linode(kwargs={'linode_id': linode_id})['TOTALHD'] root_disk_size = config.get_cloud_config_value( 'disk_size', vm_, __opts__, default=disk_size - s...
python
def do_create(self, params): """ \x1b[1mNAME\x1b[0m create - Creates a znode \x1b[1mSYNOPSIS\x1b[0m create <path> <value> [ephemeral] [sequence] [recursive] [async] \x1b[1mOPTIONS\x1b[0m * ephemeral: make the znode ephemeral (default: false) * sequence: make the znode sequentia...
python
def assoc(m, key, val): """Copy-on-write associates a value in a dict""" cpy = deepcopy(m) cpy[key] = val return cpy
java
public PermitsPool removeListener(AvailabilityListener listener) { synchronized (listeners) { for (Iterator<WeakReference<AvailabilityListener>> iter = listeners.iterator(); iter.hasNext();) { WeakReference<AvailabilityListener> item = iter.next(); if ...
python
def authenticate(url, username, password): ''' Queries an asset behind CMU's WebISO wall. It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/trac/wiki/ShibbolethProtocol) Note that you can use this to authenticate stuff beyond just grades! (any CMU service) Sample usage: s = authen...
python
def addButton( fnc, states=("On", "Off"), c=("w", "w"), bc=("dg", "dr"), pos=(20, 40), size=24, font="arial", bold=False, italic=False, alpha=1, angle=0, ): """Add a button to the renderer window. :param list states: a list of possible states ['On', 'Off'] :p...
python
def get_parts_of_url_path(url): """Given a url, take out the path part and split it by '/'. Args: url (str): the url slice returns list: parts after the domain name of the URL """ parsed = urlparse(url) path = unquote(parsed.path).lstrip('/') parts = path.split('/') re...
python
def add_headers(self, header_dict): # type: (Dict[str, str]) -> None """Deserialize a specific header. :param dict header_dict: A dictionary containing the name of the header and the type to deserialize to. """ if not self.response: return for name, ...
python
def value(self): """returns the wkid id for use in json calls""" if self._wkid == None and self._wkt is not None: return {"wkt": self._wkt} else: return {"wkid": self._wkid}
java
public void sendTo(String topicURI, Object event, String eligibleWebSocketSessionId) { sendTo(topicURI, event, Collections.singleton(eligibleWebSocketSessionId)); }
java
public static dnspolicy_dnsglobal_binding[] get(nitro_service service, String name) throws Exception{ dnspolicy_dnsglobal_binding obj = new dnspolicy_dnsglobal_binding(); obj.set_name(name); dnspolicy_dnsglobal_binding response[] = (dnspolicy_dnsglobal_binding[]) obj.get_resources(service); return response; }
java
private void deleteCollections(Object obj, List listCds) throws PersistenceBrokerException { // get all members of obj that are collections and delete all their elements Iterator i = listCds.iterator(); while (i.hasNext()) { CollectionDescriptor cds = (CollectionDescript...
python
def set_buffer(library, session, mask, size): """Sets the size for the formatted I/O and/or low-level I/O communication buffer(s). Corresponds to viSetBuf function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :para...
java
@Override public Optional<OWLOntology> loadInputOntology() throws OWLOntologyCreationException { if (options.ontology.isPresent()) { return options.ontology; } if (owlOntology.isPresent()){ return owlOntology; } return loadOntologyFromFile(); }
python
def revoke_session(): """Revoke a session.""" form = RevokeForm(request.form) if not form.validate_on_submit(): abort(403) sid_s = form.data['sid_s'] if SessionActivity.query.filter_by( user_id=current_user.get_id(), sid_s=sid_s).count() == 1: delete_session(sid_s=sid_s)...
java
@Override public ConstructorWriterImpl getConstructorWriter(ClassWriter classWriter) { return new ConstructorWriterImpl((SubWriterHolderWriter) classWriter, classWriter.getTypeElement()); }
java
@Override public List getList(final String key, final List defaultValue) { if (containsKey(key)) { return Arrays.asList(getStringArray(key)); } else { return defaultValue; } }
java
public AppValidator succeedsWith(String expectedMessage) { stringsToFind.add(expectedMessage); stringsToFind.add(APP_START_CODE); server.addIgnoredErrors(Collections.singletonList(expectedMessage)); return this; }
python
def calc_mean_hr(rr, fs=None, min_rr=None, max_rr=None, rr_units='samples'): """ Compute mean heart rate in beats per minute, from a set of rr intervals. Returns 0 if rr is empty. Parameters ---------- rr : numpy array Array of rr intervals. fs : int, or float The correspond...
java
private void validateUsername() { final String usernameValue = getUserName(); if (StringUtils.isBlank(usernameValue)) { final String msg = "Username cannot be blank; check configuration " + "of user attributes and their data sources."; ...
python
def remodelTreeRemovingRoot(root, node): """ Node is mid order number """ import bioio assert root.traversalID.mid != node hash = {} def fn(bT): if bT.traversalID.mid == node: assert bT.internal == False return [ bT ] elif bT.internal: i = ...
java
@Service public BulkResponse restart(List<String> workflowIds, boolean useLatestDefinitions) { BulkResponse bulkResponse = new BulkResponse(); for (String workflowId : workflowIds) { try { workflowExecutor.rewind(workflowId, useLatestDefinitions); bulkResponse...
java
public final SgArgument getLastArgument() { final int size = arguments.size(); if (size == 0) { return null; } return arguments.get(size - 1); }
python
def url_to_host_port(url, port=None): """ Given a URL, turn it into (host, port) for a blockstack server. Return (None, None) on invalid URL """ if not url.startswith('http://') and not url.startswith('https://'): url = 'http://' + url if not port: port = RPC_SERVER_PORT ur...
java
public static String getLocation(String providerName) { for (String key : map.keySet()) { if (providerName.startsWith(key)) { return map.get(key); } } return null; }
java
public Collection<Deployment> findByMessageListener(String messageListener) { Collection<Deployment> result = new ArrayList<Deployment>(); for (Deployment d : deployments) { if (d.getResourceAdapter() != null && d.getResourceAdapter().isMessageListenerSupported(messageListener)) ...
java
public static String getKeywordValue(String localeID, String keywordName) { return new LocaleIDParser(localeID).getKeywordValue(keywordName); }
java
public void show() { final CmsPopup popup = new CmsPopup(CmsAliasMessages.messageTitleAliasEditor()); popup.setGlassEnabled(true); popup.setModal(true); final RepeatingCommand updateCommand = new RepeatingCommand() { public boolean execute() { if...