language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def make_list(cls, item_converter=None, listsep=','): """ Create a type converter for a list of items (many := 1..*). The parser accepts anything and the converter needs to fail on errors. :param item_converter: Type converter for an item. :param listsep: List separator to use...
java
public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception { ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>(); PreparedStatement query = null; ResultSet results = null; try (Connection sqlConnection = ...
python
def to_dict(self): """Transform the date-range to a dict.""" d = {} d['start'] = date_to_str(self.start) d['end'] = date_to_str(self.end) return d
java
protected List<ProviderInfo<? extends Object>> prepareProviders(boolean custom, boolean busGlobal, Object[] providers, ...
python
def setconf(self, conf, rscpath, logger=None): """Set input conf in input path. :param Configuration conf: conf to write to path. :param str rscpath: specific resource path to use. :param Logger logger: used to log info/errors. :param bool error: raise catched errors. :r...
python
def pdf_Gates_Gaudin_Schuhman(d, d_characteristic, m): r'''Calculates the probability density of a particle distribution following the Gates, Gaudin and Schuhman (GGS) model given a particle diameter `d`, characteristic (maximum) particle diameter `d_characteristic`, and exponent `m`. .. math:...
java
public final static Function<Integer, Integer> pow(int power, RoundingMode roundingMode) { return new Pow(power, roundingMode); }
python
def update(self, payload): """Updates the queried record with `payload` and returns the updated record after validating the response :param payload: Payload to update the record with :raise: :NoResults: if query returned no results :MultipleResults: if query returned mor...
python
def _map_arg_names(source, mapping): """Map one set of keys to another.""" return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping if cf_name in source}
python
async def start_all_linking(self, linkcode, group, address=None): """Start the All-Linking process with the IM and device.""" _LOGGING.info('Starting the All-Linking process') if address: linkdevice = self.plm.devices[Address(address).id] if not linkdevice: ...
java
public Integer awaitStatusCode(long timeout, TimeUnit timeUnit) { try { if (!awaitCompletion(timeout, timeUnit)) { throw new DockerClientException("Awaiting status code timeout."); } } catch (InterruptedException e) { throw new DockerClientException("A...
java
public boolean hasTemplate(String key) { Program program = (Program) this.programCache.get(key); return program != null; }
python
def get_content_type(*names): """Return the MIME content type for the file with the given name.""" for name in names: if name is not None: mimetype, encoding = mimetypes.guess_type(name) if mimetype is not None: if isinstance(mimetype, bytes): ...
java
public final Parser<RECORD> addDissectors(final List<Dissector> dissectors) { assembled = false; if (dissectors != null) { allDissectors.addAll(dissectors); } return this; }
python
def get_form(self, request, obj=None, **kwargs): """Change the form depending on whether we're adding or editing the slot.""" if obj is None: # Adding a new Slot kwargs['form'] = SlotAdminAddForm return super(SlotAdmin, self).get_form(request, obj, **kwargs)
python
def get_in_property(value, is_bytes=False): """Get shortcut for `Block` property.""" if value.startswith('^'): prefix = value[1:3] temp = value[3:] negate = '^' else: prefix = value[:2] temp = value[2:] negate = '' if prefix != 'in': raise ValueE...
java
protected ApiUser createUserAgent(User sfsUser) { ApiUser answer = UserAgentFactory.newUserAgent( sfsUser.getName(), context.getUserAgentClass(), context.getGameUserAgentClasses()); sfsUser.setProperty(APIKey.USER, answer); answer.setId(sfsUser.ge...
python
def subCell2DFnArray(arr, fn, shape, dtype=None, **kwargs): ''' Return array where every cell is the output of a given cell function Args: fn (function): ...to be executed on all sub-arrays Returns: array: value of every cell equals result of fn(sub-array) Example: ...
python
def configure_logging(self, verbosity_lvl=None, format='%(message)s'): """Switches on logging at a given level. :param verbosity_lvl: :param format: """ if not verbosity_lvl: verbosity_lvl = logging.INFO logging.basicConfig(format=format) self.logger...
java
@Override public void doReAuthAnswerEvent(ServerAuthSession appSession, ReAuthRequest rar, ReAuthAnswer raa) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Gq AuthorizationSessionFactory :: doReAuthAnswerEvent :: appSession[{}], RAR[{}],...
python
def add_notes(self, notes): """Feed notes to self.add_note. The notes can either be an other NoteContainer, a list of Note objects or strings or a list of lists formatted like this: >>> notes = [['C', 5], ['E', 5], ['G', 6]] or even: >>> notes = [['C', 5, {'volume': 20}...
java
public final void setDatas(@NonNull Iterable<? extends Data<?>> datas) { checkNotNull(datas, "datas"); mDataWatcher.setDatas(datas); mDatas.clear(); for (Data<?> data : datas) { mDatas.add(data); } // Clear error message, because the caller expects the view st...
java
public static int cudaMemset3DAsync(cudaPitchedPtr pitchedDevPtr, int value, cudaExtent extent, cudaStream_t stream) { return checkResult(cudaMemset3DAsyncNative(pitchedDevPtr, value, extent, stream)); }
java
public final static Function<Integer, Integer> pow(int power, MathContext mathContext) { return new Pow(power, mathContext); }
python
def __get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to i...
java
public static <X> String createFieldId(Field field, Collection<Annotation> annotations) { StringBuilder builder = new StringBuilder(); builder.append(field.getDeclaringClass().getName()); builder.append('.'); builder.append(field.getName()); builder.append(createAnnotationCollect...
java
@Override public Calendar counter(Calendar request) { Calendar counter = transform(Method.COUNTER, request); counter.validate(); return counter; }
python
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
java
private Class<?> loadClass(final String classname) throws PluginException { if (null == classname) { throw new IllegalArgumentException("A null java class name was specified."); } if (null != classCache.get(classname)) { return classCache.get(classname); } ...
java
private String getErrorCode(SQLException ex) { String result = null; SQLException nestedEx = null; if (ex.getErrorCode() != 0) { result = Integer.toString(ex.getErrorCode()); } if (result == null) { nestedEx = ex.getNextException(); if (neste...
java
public static <A> Tuple2<A, A> fill(A a) { return tuple(a, a); }
java
public GregorianCalendar toGregorianCalendar() { DateTimeZone zone = getZone(); GregorianCalendar cal = new GregorianCalendar(zone.toTimeZone()); cal.setTime(toDate()); return cal; }
java
@Override public HashCode secureHash() { final Hasher code = StandardSettings.HASHFUNC.newHasher().putLong(mBucketKey).putLong(mLastBucketKey); for (int i = 0; i < mDatas.length; i++) { if (mDatas[i] != null) { code.putObject(mDatas[i], mDatas[i].getFunnel()); ...
python
def __init(self): """ initializes the properties """ params = { "f" : "json", } json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
python
def camelcase_to_underline(param_dict): """ 将驼峰命名的参数字典键转换为下划线参数 :param: * param_dict: (dict) 请求参数字典 :return: * temp_dict: (dict) 转换后的参数字典 举例如下:: print('--- transform_hump_to_underline demo---') hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right...
python
def cbpdn_class_label_lookup(label): """Get a CBPDN class from a label string.""" clsmod = {'admm': admm_cbpdn.ConvBPDN, 'fista': fista_cbpdn.ConvBPDN} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvBPDN solver method %s' % label)
java
public static void initialize(final Class<?> _class) throws CacheReloadException { if (InfinispanCache.get().exists(Attribute.NAMECACHE)) { InfinispanCache.get().<String, Attribute>getCache(Attribute.NAMECACHE).clear(); } else { InfinispanCache.get().<String, Attribut...
java
@Override protected void encode() { char[] controlChars = toControlChars(content); int l = controlChars.length; if (!content.matches("[\u0000-\u007F]+")) { throw new OkapiException("Invalid characters in input data"); } int[] values = new int[controlC...
python
def mcmc(self, n_burn, n_run, walkerRatio, sigma_scale=1, threadCount=1, init_samples=None, re_use_samples=True): """ MCMC routine :param n_burn: number of burn in iterations (will not be saved) :param n_run: number of MCMC iterations that are saved :param walkerRatio: ratio of ...
python
def validate(self): """Validate that the OutputContextField is correctly representable.""" if not isinstance(self.location, Location): raise TypeError(u'Expected Location location, got: {} {}'.format( type(self.location).__name__, self.location)) if not self.location...
python
def stop(self): """Stop the daemonized process. If the process is already stopped this call should exit successfully. If the process cannot be stopped this call should exit with code STOP_FAILED. """ if self.pid is None: return None try: ...
python
def has_required_params(self): ''' Check if required parameters for a tool launch are set. ''' return self.consumer_key and\ self.consumer_secret and\ self.resource_link_id and\ self.launch_url
java
public UpdateRequest updateUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException { return this.updateResource("sheets/" + sheetId + "/updaterequests/" + updateRequest.getId(), UpdateRequest.class, updateRequest); }
java
public HttpResponse invoke(String uri, String payload, HttpMethod method, Map<String, String> headers) { HttpResponse result = null; String url = directoryAddresses + uri; try { if (method == HttpMethod.PUT) { result = HttpUtils.put(url, payload, headers); ...
java
protected void setBigJoin(String[] masterLabels, String[] masterColumn, String[] dataColumn, String masterSeparator, List<String> masterData) throws DataFormatException { if (masterColumn.length != dataColumn.length) { throw new Dat...
python
def overwrite_file_check(args, filename): """If filename exists, overwrite or modify it to be unique.""" if not args['overwrite'] and os.path.exists(filename): # Confirm overwriting of the file, or modify filename if args['no_overwrite']: overwrite = False else: t...
java
@Override public final IoBuffer shrink() { if (!recapacityAllowed) { throw new IllegalStateException( "Derived buffers and their parent can't be expanded."); } int position = position(); int capacity = capacity(); int limit = limit(); ...
java
protected BAMTaskSummaryImpl updateTask(TaskEvent event, BAMTaskWorker worker) { return updateTask(event, null, worker); }
java
public void toWriter(boolean wholeDocument, Writer writer, Properties outputProperties) throws TransformerException { StreamResult streamResult = new StreamResult(writer); DOMSource domSource = null; if (wholeDocument) { domSource = new DOMSource(getDocument(...
java
private StringBuffer loadScriptTemplate(String path) { StringWriter sw = new StringWriter(); InputStream is = null; try { is = ClassLoaderResourceUtils.getResourceAsStream(path, this); int i; while ((i = is.read()) != -1) { sw.write(i); } } catch (IOException e) { Marker fatal = MarkerFacto...
java
public static String getVersion(Class<?> aClass, String groupId, String artifactId) { String version = null; // lets try find the maven property - as the Java API rarely works :) InputStream is = null; String fileName = "/META-INF/maven/" + groupId + "/" + artifactId + ...
java
public ServiceFuture<SummarizeResultsInner> summarizeForManagementGroupAsync(String managementGroupName, final ServiceCallback<SummarizeResultsInner> serviceCallback) { return ServiceFuture.fromResponse(summarizeForManagementGroupWithServiceResponseAsync(managementGroupName), serviceCallback); }
python
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None: """Add directory to serve static files. First argument ``prefix`` is a URL prefix for the ``path``. ``path`` must be a directory. If ``no_watch`` is True, any change of the files in the path do not trigger restart if ``--autor...
java
public synchronized boolean awaitTermination(long milliseconds) throws InterruptedException { long end = System.currentTimeMillis() + milliseconds; for (Map.Entry<String, ThreadPoolExecutor> e: executors.entrySet()) { ThreadPoolExecutor executor = e.getValue(); if (!executor.awaitTer...
java
public static <Data extends AbstractKVStorable> DRUMS<Data> openTable(AccessMode accessMode, DRUMSParameterSet<Data> gp) throws IOException { AbstractHashFunction hashFunction; try { hashFunction = readHashFunction(gp); } catch (ClassNotFoundException e) { thr...
python
def parse_original_feature_from_example(example, feature_name): """Returns an `OriginalFeatureList` for the specified feature_name. Args: example: An example. feature_name: A string feature name. Returns: A filled in `OriginalFeatureList` object representing the feature. """ feature = get_exampl...
python
def all(self, value, pos=None): """Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way...
python
def _venv_match(self, installed, requirements): """Return True if what is installed satisfies the requirements. This method has multiple exit-points, but only for False (because if *anything* is not satisified, the venv is no good). Only after all was checked, and it didn't exit, the ve...
java
public static String translate(String str) { if (str == null) return ""; // TODO do-while machen int index, last = 0, endIndex; StringBuilder sb = null; String tagName; while ((index = str.indexOf('<', last)) != -1) { // read tagname int len = str.length(); char c; for (endIndex = index + 1; e...
java
private ConceptDefinitionComponent getCodeDefinition(ConceptDefinitionComponent c, String code) { if (code.equals(c.getCode())) return c; for (ConceptDefinitionComponent g : c.getConcept()) { ConceptDefinitionComponent r = getCodeDefinition(g, code); if (r != null) return r; } return null; }
python
def _set_external_lsa_onstartup(self, v, load=False): """ Setter method for external_lsa_onstartup, mapped from YANG variable /rbridge_id/router/ospf/max_metric/router_lsa/on_startup/external_lsa_onstartup (container) If this variable is read-only (config: false) in the source YANG file, then _set_exter...
java
public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } }
java
public Collection<String> generateTableJoinOrder() { List<JoinNode> leafNodes = generateLeafNodesJoinOrder(); Collection<String> tables = new ArrayList<>(); for (JoinNode node : leafNodes) { tables.add(node.getTableAlias()); } return tables; }
python
def setup_logger(log_level, log_file=None, logger_name=None): """setup logger @param log_level: debug/info/warning/error/critical @param log_file: log file path @param logger_name: the name of logger, default is 'root' if not specify """ applogger = AppL...
java
public ObjectFunctionSetSpecificationDCAFnSet createObjectFunctionSetSpecificationDCAFnSetFromString(EDataType eDataType, String initialValue) { ObjectFunctionSetSpecificationDCAFnSet result = ObjectFunctionSetSpecificationDCAFnSet.get(initialValue); if (result == null) throw new IllegalArgumentException("The value...
python
def status(self, status_code=None): """ Set status or Get Status """ if status_code is not None: self.response_model.status = status_code # return string for response support return str(self.response_model.status)
java
@Override public void characters (char ch[], int start, int len) { while (len > 0 && Character.isWhitespace(ch[start])) { ++start; --len; } while (len > 0 && Character.isWhitespace(ch[start+len-1])) { --len; } if (_text.length() > ...
python
def update(self, id, name, incident_preference): """ This API endpoint allows you to update an alert policy :type id: integer :param id: The id of the policy :type name: str :param name: The name of the policy :type incident_preference: str :param incid...
java
public Query execute(Vector statements, PageContext pc, SQL sql, int maxrows) throws PageException { // parse sql if (statements.size() != 1) throw new DatabaseException("only one SQL Statement allowed at time", null, null, null); ZQuery query = (ZQuery) statements.get(0); // single table if (query.getFrom().size...
java
public int count(String messageKey, Severity severity) { int count = 0; if (severity == null || messageKey == null) { return count; } for (ValidationResult result : results) { for (ValidationMessage<Origin> message : result.getMessages()) { if (me...
java
public void addWords(String... words){ HashSet<String> wordsSet = CollectionUtil.newHashSet(words); for (String word : wordsSet) { addWord(word); } }
python
def destroy(self, request, pk=None, parent_lookup_organization=None): '''Remove a user from an organization.''' user = get_object_or_404(User, pk=pk) org = get_object_or_404( SeedOrganization, pk=parent_lookup_organization) self.check_object_permissions(request, org) ...
java
public static HardwareDescription extractFromSystem(long managedMemory) { final int numberOfCPUCores = Hardware.getNumberCPUCores(); final long sizeOfJvmHeap = Runtime.getRuntime().maxMemory(); final long sizeOfPhysicalMemory = Hardware.getSizeOfPhysicalMemory(); return new HardwareDescription(numberOfCPUCores...
python
def vm_profiles_config(path, providers, env_var='SALT_CLOUDVM_CONFIG', defaults=None): ''' Read in the salt cloud VM config file ''' if defaults is None: defaults = VM_CONFIG_DEFAULTS overrides = salt.config.load_config( ...
java
private void streamToOutput(InputStream inputStream) throws IOException { try { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } finally { inp...
java
@SuppressWarnings("checkstyle:all") protected void generateAbstractAppender() { final TypeReference abstractAppender = getCodeElementExtractor().getAbstractAppenderImpl(); StringConcatenationClient content = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation it) { ...
java
public static double mean( InterleavedS8 img ) { return sum(img)/(double)(img.width*img.height*img.numBands); }
python
def logger(self, logger): """Set the logger if is not None, and it is of type Logger.""" if logger is None or not isinstance(logger, Logger): raise ValueError("Logger can not be set to None, and must be of type logging.Logger") self._logger = logger
java
protected final Class<T> getEntityClass() { @SuppressWarnings("unchecked") final Class<T> result = (Class<T>) TypeHelper.getTypeArguments(JpaSearchRepository.class, this.getClass()).get(0); return result; }
python
def find_ask(): """ Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found. """ if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, '...
java
public void setReplicaSettings(java.util.Collection<ReplicaSettingsDescription> replicaSettings) { if (replicaSettings == null) { this.replicaSettings = null; return; } this.replicaSettings = new java.util.ArrayList<ReplicaSettingsDescription>(replicaSettings); }
java
@Override public void refresh() { // do nothing org.grails.io.support.Resource descriptor = getDescriptor(); if (grailsApplication == null || descriptor == null) { return; } ClassLoader parent = grailsApplication.getClassLoader(); GroovyClassLoader gcl = ...
python
def _parse_string(self, line): """ Consume the complete string until next " or \n """ log.debug("*** parse STRING: >>>%r<<<", line) parts = self.regex_split_string.split(line, maxsplit=1) if len(parts) == 1: # end return parts[0], None pre, match, po...
java
public MultinomialModelPrediction predictMultinomial(RowData data, double offset) throws PredictException { double[] preds = preamble(ModelCategory.Multinomial, data, offset); MultinomialModelPrediction p = new MultinomialModelPrediction(); if (enableLeafAssignment) { // only get leaf node assignment if en...
java
public void marshall(NetworkBinding networkBinding, ProtocolMarshaller protocolMarshaller) { if (networkBinding == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(networkBinding.getBindIP(), BINDIP_BI...
java
public Difference<BaseType> compareArraysWithId(List<String> field1, ArrayType node1, List<String> field2, ArrayType node2, ...
python
def hwvtep_attach_vlan_vid(self, **kwargs): """ Identifies exported VLANs in VXLAN gateway configurations. Args: name (str): overlay_gateway name vlan(str): vlan_id range callback (function): A function executed upon completion of the method...
python
def generate_disk_vdev(self, start_vdev=None, offset=0): """Generate virtual device number for disks :param offset: offset of user_root_vdev. :return: virtual device number, string of 4 bit hex. """ if not start_vdev: start_vdev = CONF.zvm.user_root_vdev vdev ...
java
private NameResolver of(final String targetAuthority, final Helper helper) { requireNonNull(targetAuthority, "targetAuthority"); // Determine target ips final String[] hosts = PATTERN_COMMA.split(targetAuthority); final List<EquivalentAddressGroup> targets = new ArrayList<>(hosts.length)...
java
public static String secondsToHoursMinutesSeconds(final long secs) { final double minutesRemaining = (secs / 60) % 60; final double hoursRemaining = Math.floor(secs / 60 / 60); final double secondsRemaining = secs % 60; final StringBuilder sb = new StringBuilder();...
java
private static boolean containsComplement(final LinkedHashSet<Formula> formulas, final Formula f) { return formulas.contains(f.negate()); }
java
@Override public DescriptorValue calculate(IAtom atom, IAtomContainer container) { IAtomType atomType; try { atomType = CDKAtomTypeMatcher.getInstance(atom.getBuilder()).findMatchingAtomType(container, atom); } catch (CDKException e) { return new DescriptorValue(getSp...
java
private void comboXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboXActionPerformed if (visualizer == null) return; JComboBox cb = (JComboBox)evt.getSource(); int dim = cb.getSelectedIndex(); streamPanel0.setActiveXDim(dim); streamPanel1.setActiveXDim(dim)...
java
@Override public User logIn(String username, String password) throws AuthenticationException { // Find our user String uPwd = file_store.getProperty(username); if (uPwd == null) { throw new AuthenticationException("User '" + username + "' not found...
python
def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name...
python
def search_hashes( self, hash_prefix=None, threat_types=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the full hashes that match the requested hash prefix. This ...
python
def value(self, view, template=None): """Get a list of items validated against the template. """ out = [] for item in view: out.append(self.subtemplate.value(item, self)) return out
python
def _data(self, pipe=None): """ Returns a Python dictionary with the same values as this object (without checking the local cache). """ pipe = self.redis if pipe is None else pipe items = pipe.hgetall(self.key).items() return {self._unpickle_key(k): self._unpickl...
java
public static void main(String[] args) throws IOException, ClassNotFoundException { CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter(); f.init(new SeqClassifierFlags()); int numDocs = 0; int numTokens = 0; int numEntities = 0; String lastAnsBase = ""; for (Iterator<Li...
python
def ecdh(self, identity, pubkey): """Get shared session key using Elliptic Curve Diffie-Hellman.""" assert pubkey[:1] == b'\x04' peer = ecdsa.VerifyingKey.from_string( pubkey[1:], curve=ecdsa.curves.NIST256p, hashfunc=hashlib.sha256) shared = ecdsa.Ver...