language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def close(self, kill_restart=True): ''' Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring ''' self.do_not_restart = kill_restart self.zoo_client.stop() self.zoo_client.close()
python
def lookups(self, request, model_admin): """ Returns a list of tuples like: [ ('AU', 'Australia'), ('GB', 'UK'), ('US', 'USA'), ] One for each country that has at least one Venue. Sorted by the label names. ...
java
public void onMessage(Message msg) { try { LOG.debug("Queuing msg [" + msg.getJMSMessageID() + "]"); } catch (JMSException e) { } this.queue.offer(msg); }
java
@Override public Parser newFixedLengthParser(final File pzmapXML, final File dataSource) { return new FixedLengthParser(pzmapXML, dataSource); }
java
public static String labelList2Text(List<? extends HasWord> ptbWords) { List<String> words = new ArrayList<String>(); for (HasWord hw : ptbWords) { words.add(hw.word()); } return ptb2Text(words); }
java
String getProperty(String property, String def) { return System.getProperty(property, def); }
java
public static boolean getBoolean(java.util.Properties properties, String prop, boolean defaultVal) { String propVal = properties.getProperty(prop); return (propVal != null) ? Boolean.parseBoolean(propVal) ...
python
def variant(self): '''Get the current theme variant''' variant = current_app.config['THEME_VARIANT'] if variant not in self.variants: log.warning('Unkown theme variant: %s', variant) return 'default' else: return variant
python
def inverted_dict_of_lists(d): """Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True """ new_dict = {} for (old_key, old_value_list) in viewitems(dict(d)): for n...
java
public void add(Supplier<JournalContext> journalContext, AlluxioURI alluxioUri, AlluxioURI ufsUri, long mountId, MountPOptions options) throws FileAlreadyExistsException, InvalidPathException { String alluxioPath = alluxioUri.getPath().isEmpty() ? "/" : alluxioUri.getPath(); LOG.info("Mounting {} at {}", ...
java
public String getMessage() { String msg = super.getMessage(); String ec = getErrorCode(); if ((msg == null) && (ec == null)) { return null; } if ((msg != null) && (ec != null)) { return (msg + ", error code: " + ec); } return ((msg != null) ?...
java
public static Link parse(String origin, String link, boolean allowModuleName) { String originMod = origin; int index = link.indexOf('#'); if (index == -1) { if (allowModuleName) { index = link.lastIndexOf('/'); if (index == -1) { re...
java
@Conditioned @Quand("Je mets à jour le texte '(.*)-(.*)' avec une valeur aléatoire qui vérifie '(.*)'[\\.|\\?]") @When("I update text '(.*)-(.*)' with ramdom match '(.*)'[\\.|\\?]") public void updateTextWithRamdomValueMatchRegexp(String page, String elementName, String randRegex, List<GherkinStepConditi...
java
@Override public List<CommerceDiscountUsageEntry> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
python
def save_pip(self, out_dir): """Saves the current working set of pip packages to requirements.txt""" try: import pkg_resources installed_packages = [d for d in iter(pkg_resources.working_set)] installed_packages_list = sorted( ["%s==%s" % (i.key, i.ve...
java
@SuppressWarnings( { "unchecked" }) public Class<Object> getCaller(String name) { // Try walking the stack until we find the class with the name passed in Class<Object> aClass = matchCaller(name); if (aClass == null) { // If we couldn't find the class by the name passed in, ...
java
public static <T extends ImageGray<T>> Planar<T> median(Planar<T> input, @Nullable Planar<T> output, int radius , @Nullable WorkArrays work) { if( output == null ) output = input.createNew(input.width,input.height); for( int band = 0; band < input.getNumBands(); band++ ) { GBlurImageOps.median(input....
python
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_dat...
python
def render(self): """ <a class="btn" href="#"><i class="icon-repeat"></i> Reload</a> or.. <button type="button" class="btn"><i class="icon-repeat"></i> Reload</button> """ html = '' href = self.view if self.view is not None else self.href ...
python
def get_context(self, name, value, attrs): """Add captcha specific variables to context.""" context = super(CaptchaTextInput, self).get_context(name, value, attrs) context['image'] = self.image_url() context['audio'] = self.audio_url() return context
java
public void addAll(final Iterator<? extends T> elements, final LongIterator values) throws IOException { addAll(elements, values, false); }
python
def encode_as_simple(name, value): """Creates an etree element following the simple field convention. Values are assumed to be strs, unicodes, ints, floats, or Decimals: >>> element = encode_as_simple('foo', '5') >>> element.tag == 'foo' True >>> element.text == '5' ...
python
def collect_config(cfg): """ Construct configuration dictionary from configparser. Resolves presets and returns a dictionary containing: .. code-block:: bash { "client_name": { "detector": ("detector_name", detector_opts), "updater": [ ...
java
protected static String normalizePath (String path) { int pathLen; do { pathLen = path.length(); path = path.replaceAll("[^/]+/\\.\\./", ""); } while (path.length() != pathLen); return path; }
python
def to_date(dt, tzinfo=None, format=None): """ Convert a datetime to date with tzinfo """ d = to_datetime(dt, tzinfo, format) if not d: return d return date(d.year, d.month, d.day)
java
public static long getNextIntervalStart(long time, int intervalInMinutes, int offsetInMinutes) { long interval = MINUTE_IN_MS * intervalInMinutes; return getPreviousIntervalStart(time, intervalInMinutes, offsetInMinutes) + interval; }
java
public static boolean methodBelongsTo(Method m, Method[] methods){ boolean result = false; for (int i = 0; i < methods.length && !result; i++) { if(methodEquals (methods [i], m)){ result = true; } } return result; }
python
def get_args(self): """ Use this context manager to add arguments to an argparse object with the add_argument method. Arguments must be defined before the command is defined. Note that no-clean and resume are added upon exit and should not be added in the context manager. For mor...
python
def reset(self): """ Resets index by removing index directory. """ if os.path.exists(self.index_dir): rmtree(self.index_dir) self.index = None
java
private static Document getDocument(URL pathToPersistenceXml) throws InvalidConfigurationException { InputStream is = null; Document xmlRootNode = null; try { if (pathToPersistenceXml != null) { URLConnection conn = pathToPersistenceX...
python
def getFormattedHTML(self, indent=' '): ''' getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace with a pretty-printed version @param indent - space/tab/newline of each level of indent, or integer for how many spaces per level ...
java
public JsonObject toJsonObject() { JsonObjectBuilder factory = Json.createObjectBuilder(); if (nym != null) { JsonObjectBuilder factory2 = Json.createObjectBuilder(); factory2.add("x", Base64.getEncoder().encodeToString(IdemixUtils.bigToBytes(nym.getX()))); factory2.a...
java
@Override public Reader getResource(JoinableResourceBundle bundle, String resourceName, boolean processingBundle) { Reader rd = null; if (!resourceName.contains(":")) { InputStream is = context.getResourceAsStream(resourceName); if (is != null) { rd = new InputStreamReader(is, charset); } } retur...
python
def grouped_insert(t, value): """Insert value into the target tree 't' with correct grouping.""" collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale()) if value.tail is not None: val_prev = value.getprevious() if val_prev is not None: val_prev.tail = (val_prev...
python
def advance_recurring_todo(p_todo, p_offset=None, p_strict=False): """ Given a Todo item, return a new instance of a Todo item with the dates shifted according to the recurrence rule. Strict means that the real due date is taken as a offset, not today or a future date to determine the offset. ...
python
def send_task(self, body): """ 发送任务到任务队列 :param body: 消息 :return: """ self.ch.basic_publish(exchange='', routing_key=self.task_queue, properties=pika.BasicProperties(delivery_mode=2), body=body)
python
def mapitems(function, dict_): """Return a new dictionary where the keys and values come from applying ``function`` to key-value pairs from given dictionary. .. warning:: If ``function`` returns a key-value pair with the same key more than once, it is undefined which value will be chosen ...
java
protected void localRelease() { super.localRelease(); if(bodyContent != null) bodyContent.clearBody(); _rows = DIMENSION_DEFAULT_VALUE; _columns = DIMENSION_DEFAULT_VALUE; _currentRow = -1; _currentColumn = -1; _currentIndex = -1; _verticalRe...
java
protected void sequence_XNumberLiteral(ISerializationContext context, XNumberLiteral semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, XbasePackage.Literals.XNUMBER_LITERAL__VALUE) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValu...
java
public static Map<String, Map<String, String>> merge( final Map<String, Map<String, String>> targetContext, final Map<String, Map<String, String>> newContext ) { final HashMap<String, Map<String, String>> result = deepCopy(targetContext); for (final Map.Entry<String, Map...
java
@Override public PutBotResult putBot(PutBotRequest request) { request = beforeClientExecution(request); return executePutBot(request); }
python
def _create_simulated_annealing_expander(schedule): ''' Creates an expander that has a random chance to choose a node that is worse than the current (first) node, but that chance decreases with time. ''' def _expander(fringe, iteration, viewer): T = schedule(iteration) current = frin...
python
def view_attr(attr_name): """ Creates a getter that will drop the current value and retrieve the view's attribute with specified name. @param attr_name: the name of an attribute belonging to the view. @type attr_name: str """ def view_attr(_value, context, **_params): value = getatt...
java
public static Certificate getCertificate(KeyStore keyStore, String alias) { return KeyUtil.getCertificate(keyStore, alias); }
python
def _gotitem(self, key, ndim, subset=None): """ sub-classes to define return a sliced object Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on...
python
def get_prob(self, src, tgt, mask, pre_compute, return_logits=False): ''' :param s: [src_sequence_length, batch_size, src_dim] :param h: [batch_size, tgt_dim] or [tgt_sequence_length, batch_size, tgt_dim] :param mask: [src_sequence_length, batch_size]\ or [tgt_sequence_lengt...
python
def source(self, fields=None, **kwargs): """ Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes If ``fields`` is None, the entire document will be returned for each hit. If fields is a...
java
public void sendEvent(final Map<String, String> params) { executor.execute(new Runnable() { @Override public void run() { // put user id params.put("cid", userId); Multimap queryParams = HashMultimap.create(); for (Map.Entry...
python
def primary_keys_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]: """ Return all primary keys / identifiers for cls @param cls: class to get keys for @return: List of primary keys """ return [slot_name for slot_name in self.all_slots_for(cls) if self....
python
def unique_id(length=12, increment=0): """ Generate a decent looking alphanumeric unique identifier. First 16 bits are time- incrementing, followed by randomness. This function is used as a nicer looking alternative to: >>> uuid.uuid4().hex Follows the advice in: https://eager.io/blog/how-...
python
def custom_getter(self, activation_dtype=tf.bfloat16): """A custom getter that uses the encoding for bfloat16 and float32 vars. When a bfloat16 or float32 variable is requsted, an encoded float16 varaible is created, which is then decoded and cast to a bfloat16 activation. Args: activation_d...
java
public void upload(String trainingDir, String apiKey, String algorithmId) { JSONObject json = new JSONObject().put("training_dir", trainingDir).put("api_key", apiKey).put("algorithm_id", algorithmId); uploadPost(json); }
java
public void initializeNonPersistent(BaseDestinationHandler destinationHandler) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "initializeNonPersistent", destinationHandler); /** * Remember the destinationHandler that represents the destinatio...
java
public static void clearAllRegisteredControls() { UIContext uic = UIContextHolder.getCurrentPrimaryUIContext(); if (uic != null) { uic.setFwkAttribute(SUBORDINATE_CONTROL_SESSION_KEY, null); } }
java
public boolean isSecure() { // currently called once per request - later we might cache the result per request // and even the method lookup Object request = context.getExternalContext().getRequest(); if (request instanceof HttpServletRequest) { return ((HttpServletRequest) ...
python
def connect(self): """Enumerate and connect to the first USB HID interface.""" try: return comm.getDongle() except comm.CommException as e: raise interface.NotFoundError( '{} not connected: "{}"'.format(self, e))
python
def convert_to_ssml(text, text_format): """ Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plai...
java
private static Set<Class> excludedFromGradientCheckCoverage() { List list = Arrays.asList( //Exclude misc DynamicCustomOp.class, EqualsWithEps.class, ConfusionMatrix.class, Eye.class, OneHot.class, Bi...
java
public void setDocName(String newDocName) { String oldDocName = docName; docName = newDocName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BDT__DOC_NAME, oldDocName, docName)); }
python
def _get_managed_files(self): ''' Build a in-memory data of all managed files. ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: re...
python
def compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.'): """compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file na...
python
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') e...
python
def delete(filething): """ delete(filething) Arguments: filething (filething) Raises: mutagen.MutagenError Remove tags from a file. """ t = OggFLAC(filething) filething.fileobj.seek(0) t.delete(filething)
python
def _initialize_mesh_dimension_name_to_size(self, mesh_shape): """Initializer for self._mesh_dimension_name_to_size. Args: mesh_shape: an mtf.Shape. Returns: A {string: int} mapping mesh dimension names to their sizes. """ mesh_dimension_name_to_size = {} # {string: int} for mesh_...
python
def tofasta(args): """ %prog tofasta [--options] Read GenBank file, or retrieve from web. Output fasta file with one record per file or all records in one file """ p = OptionParser(tofasta.__doc__) p.add_option("--prefix", default="gbfasta", help="prefix of output files [def...
java
Rule FieldTranscription() { return Sequence(String("Z:"), ZeroOrMore(WSP()).suppressNode(), TexText(), HeaderEol()).label(FieldTranscription); }
python
def connect_functions(self): """ Connects all events to the functions which should be called :return: """ # Lambda is sometimes used to prevent passing the event parameter. self.cfg_load_pushbutton.clicked.connect(lambda: self.load_overall_config()) self.cfg_save_...
python
def download_and_verify(path, source_url, sha256): """ Download a file to a given path from a given URL, if it does not exist. After downloading it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesyst...
java
public void update(String cacheName, Cache cache) { cacheManager.enableManagement(cacheName, cache.isManagementEnabled()); updateStatistics(cacheName, cache); }
java
protected String createIssueMessage(Issue issue) { final IssueMessageFormatter formatter = getIssueMessageFormatter(); final org.eclipse.emf.common.util.URI uriToProblem = issue.getUriToProblem(); if (formatter != null) { final String message = formatter.format(issue, uriToProblem); if (message != null) { ...
java
public static LineageEventBuilder fromEvent(GobblinTrackingEvent event) { Map<String, String> metadata = event.getMetadata(); LineageEventBuilder lineageEvent = new LineageEventBuilder(event.getName()); metadata.forEach((key, value) -> { switch (key) { case SOURCE: lineageEvent.setS...
java
public void setContent(java.util.Collection<java.util.Map<String, String>> content) { if (content == null) { this.content = null; return; } this.content = new com.amazonaws.internal.SdkInternalList<java.util.Map<String, String>>(content); }
java
public boolean commitInsert(MessageItem msgItem) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "commitInsert", msgItem); _internalOutputStreamManager.commitInsert(msgItem); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnable...
python
def _format_msg(self, msg, edata): """Substitute parameters in exception message.""" edata = edata if isinstance(edata, list) else [edata] for fdict in edata: if "*[{token}]*".format(token=fdict["field"]) not in msg: raise RuntimeError( "Field {tok...
python
def close(self): """Close any open connections to Redis. :raises: :exc:`tredis.exceptions.ConnectionError` """ if not self._connected.is_set(): raise exceptions.ConnectionError('not connected') self._closing = True if self._clustering: for host i...
python
def write_weight_map(self, model_name): """Save the counts model map to a FITS file. Parameters ---------- model_name : str String that will be append to the name of the output file. Returns ------- """ maps = [c.write_weight_map(model_name)...
java
public static <T extends CharSequence> T validateMoney(T value, String errorMsg) throws ValidateException { if (false == isMoney(value)) { throw new ValidateException(errorMsg); } return value; }
java
private static boolean relate(Point point_a, Point point_b, SpatialReference sr, int relation, ProgressTracker progress_tracker) { if (point_a.isEmpty() || point_b.isEmpty()) { if (relation == Relation.disjoint) return true; // Always true return false; // Always false } Point2D pt_a = point_a.getX...
python
def get(self, identity): """ Constructs a SyncListPermissionContext :param identity: Identity of the user to whom the Sync List Permission applies. :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext :rtype: twilio.rest.sync.v1.service...
java
public static <T, C extends Comparable<? super C>> T minBy(final Iterator<T> iterator, final Function1<? super T, C> compareBy) { if (compareBy == null) throw new NullPointerException("compareBy"); return min(iterator, new KeyComparator<T, C>(compareBy)); }
java
public ItemRef presence(final OnPresence onPresence, final OnError onError) { context.presence(channel, onPresence, onError); return this; }
java
public byte[] getEncoded() throws CertificateEncodingException { try { if (encoded == null) { DerOutputStream tmp = new DerOutputStream(); emit(tmp); encoded = tmp.toByteArray(); } } catch (IOException ex) { throw new Ce...
python
def relocated_record(self): # type: () -> bool ''' Determine whether this Rock Ridge entry has a relocated record (used for relocating deep directory records). Parameters: None. Returns: True if this Rock Ridge entry has a relocated record, False otherw...
java
public static CsvWriter getWriter(File file, Charset charset, boolean isAppend) { return new CsvWriter(file, charset, isAppend); }
python
def _get_matplot_dict(self, option, prop, defdict): """Returns a copy of the settings dictionary for the specified option in curargs with update values where the value is replaced by the key from the relevant default dictionary. :arg option: the key in self.curargs to update. ...
java
public void markTaskCompletion() { if (this.countDownLatch.isPresent()) { this.countDownLatch.get().countDown(); } this.taskState.setProp(ConfigurationKeys.TASK_RETRIES_KEY, this.retryCount.get()); }
java
public void write_attribute(final DeviceProxy deviceProxy, final DeviceAttribute deviceAttribute) throws DevFailed { checkIfTango(deviceProxy, "write_attribute"); try { final DeviceAttribute[] array = { deviceAttribute }; write_attribute(deviceProxy, array); } catch (final NamedDevFailedList e) ...
python
def get_project_ids(self): """ Determines which projects the current user is allowed to visualize. Returns a list of project ids to be used in get_queryset() for filtering. """ user = self.request.user projects = Project.objects.accessible_to(user).values('id') ...
java
protected static ByteBuffer[] toUDPBuffers(GelfMessage message, ThreadLocal<ByteBuffer> writeBuffers, ThreadLocal<ByteBuffer> tempBuffers) { while (true) { try { return message.toUDPBuffers(getBuffer(writeBuffers), getBuffer(tempBuffers)); } catch (BufferOve...
java
public List<FleetMembersResponse> getFleetsFleetIdMembers(Long fleetId, String acceptLanguage, String datasource, String ifNoneMatch, String language, String token) throws ApiException { ApiResponse<List<FleetMembersResponse>> resp = getFleetsFleetIdMembersWithHttpInfo(fleetId, acceptLanguage, ...
java
public void addMessage(final boolean encode, final String msg, final Serializable... args) { MessageModel model = getOrCreateComponentModel(); model.messages.add(new Duplet<>(I18nUtilities.asMessage(msg, args), encode)); // Potential for leaking memory here MemoryUtil.checkSize(model.messages.size(), this.getCl...
python
def reinstall(self, subid, params=None): ''' /v1/server/reinstall POST - account Reinstall the operating system on a virtual machine. All data will be permanently lost, but the IP address will remain the same There is no going back from this call. Link: https://www.vultr...
java
public Upload upload(final String bucketName, final String key, final InputStream input, ObjectMetadata objectMetadata) throws AmazonServiceException, AmazonClientException { return upload(new PutObjectRequest(bucketName, key, input, objectMetadata)); }
python
def get_location(conn, vm_): ''' Return the location object to use ''' locations = conn.list_locations() vm_location = config.get_cloud_config_value('location', vm_, __opts__) if not six.PY3: vm_location = vm_location.encode( 'ascii', 'salt-cloud-force-ascii' ) f...
java
public String[] getProxyHostsWhiteList() { if (_proxyHostsWhiteList == null || _proxyHostsWhiteList.size() == 0) return new String[0]; String[] hosts = new String[_proxyHostsWhiteList.size()]; hosts = (String[]) _proxyHostsWhiteList.toArray(hosts); return hosts; }
python
def _resolve_input(variable, variable_name, config_key, config): """ Resolve input entered as option values with config values If option values are provided (passed in as `variable`), then they are returned unchanged. If `variable` is None, then we first look for a config value to use. If no ...
python
def nodes(self): """ Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode) """ resource = sub_collection( self.get_relation('vss_container_node'), VSSContainerNode) resource._load_from_engine(self, 'nodes...
java
boolean linesIntoCorners( int numLines, GrowQueue_I32 contourCorners ) { skippedCorners.reset(); // this is the index in the contour of the previous corner. When a new corner is found this is used // to see if the newly fit lines point to the same corner. If that happens a corner is "skipped" int contourInd...
java
public static <T> List<List<T>> matrixTransform(List<List<T>> datas) { if (datas.size() == 0 || datas.get(0).size() == 0) { return datas; } int column = datas.size(); int row = datas.get(0).size(); List<List<T>> newData = new ArrayList<>(row); for (int i = 0; ...
java
public void loginWithEmail(String email, String password, final SimpleLoginAuthenticatedHandler completionHandler) { if (!Validation.isValidEmail(email)) { handleInvalidEmail(completionHandler); } else if (!Validation.isValidPassword(password)) { handleInvalidPassword(completionHandler); } ...