language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private static void sendMessageBatchOperationMd5Check(SendMessageBatchRequest sendMessageBatchRequest, SendMessageBatchResult sendMessageBatchResult) { Map<String, SendMessageBatchRequestEntry> idToRequestEntryMap = new HashMap<String, SendMessageBatchRe...
java
public List<String> getUsernameAttributes() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_USERNAME_ATTRIBUTE, Collections.singletonList("uid") ); }
python
def get(company='', company_uri=''): """Performs a HTTP GET for a glassdoor page and returns json""" if not company and not company_uri: raise Exception("glassdoor.gd.get(company='', company_uri=''): "\ " company or company_uri required") payload = {} if not company_u...
java
public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } }
java
public static boolean check(String token, String signature, String timestamp, String nonce) { // 防范长密文攻击 if (signature == null || signature.length() > 128 || timestamp == null || timestamp.length() > 128 || nonce == null || nonce.length() > 128...
python
def is_cf_trajectory(nc, variable): ''' Returns true if the variable is a CF trajectory feature type :param netCDF4.Dataset nc: An open netCDF dataset :param str variable: name of the variable to check ''' # x(i, o), y(i, o), z(i, o), t(i, o) # X(i, o) dims = nc.variables[variable].dime...
python
def load_multiformat_time_series(): """Loading time series data from a zip file in the repo""" data = get_example_data('multiformat_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.ds2 = pd.to_datetime(pdf.ds2, unit='s') pdf.to_sql( 'multiform...
java
@GwtIncompatible("Class.getDeclaredFields") public ToStringBuilder addDeclaredFields() { Field[] fields = instance.getClass().getDeclaredFields(); for(Field field : fields) { addField(field); } return this; }
java
private List<Object> create( final Object rowObj, final ExecutionContext ec, final Object previousRow) { if (rowObj instanceof ExcelFixtureRowHandler) { final ExcelFixtureRowHandler rowHandler = (ExcelFixtureRowHandler) rowObj; return rowHandler.handle...
python
def get_order(self, order_id, **params): """https://developers.coinbase.com/api/v2#show-an-order""" response = self._get('v2', 'orders', order_id, params=params) return self._make_api_object(response, Order)
java
public static void changeAlpha(InputStream srcInput, OutputStream destOutput, byte alpha) throws IOException { changeAlpha(srcInput, destOutput, alpha, null); }
python
def get_context_data(self, **kwargs): """ Return a dictionary containing all of the values needed to render the menu instance to a template, including values that might be used by the 'sub_menu' tag to render any additional levels. """ ctx_vals = self._contextual_vals ...
java
protected final <T> void putAdvancedConfig(AdvancedConfig.Key<T> key, T value) { advancedConfig.put(key, value); }
java
@Override protected void addGenericHeaders(final UIContext uic, final WComponent ui) { // Note: This effectively prevents caching of anything served up from a WServlet. // We are ok for WContent and thrown ContentEscapes, as addGenericHeaders will not be called if (getBackingRequest() instanceof SubSessionHttpSe...
java
@Override public CPDefinitionOptionValueRel fetchCPDefinitionOptionValueRelByUuidAndGroupId( String uuid, long groupId) { return cpDefinitionOptionValueRelPersistence.fetchByUUID_G(uuid, groupId); }
python
def is_holiday(now=None, holidays="/etc/acct/holidays"): """is_holiday({now}, {holidays="/etc/acct/holidays"}""" now = _Time(now) # Now, parse holiday file. if not os.path.exists(holidays): raise Exception("There is no holidays file: %s" % holidays) f = open(holidays, "r") # First, read...
python
def get_or_create_with_validation(cls, *args, **kwargs): """ Factory method that gets or creates-and-validates the model object before it is saved. Similar to the get_or_create method on Models, it returns a tuple of (object, created), where created is a boolean specifying whether an obj...
java
@Override public UntagResourcesResult untagResources(UntagResourcesRequest request) { request = beforeClientExecution(request); return executeUntagResources(request); }
python
def _validate_and_parse(self, batch_object): """ Performs validation on the batch object to make sure it is in the proper format. Parameters: * batch_object: The data provided to a POST. The expected format is the following: { "username": "username", ...
python
def query_helper(request,namespace, docid, configuration=None): """Does the actual query, called by query() or pub_query(), not directly""" flatargs = { 'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search re...
python
def get_listing_view(self, request, queryset, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. ``queryset`` can be an actual QuerySet or any iterable. """ view = self.get_view(request, self.view_class, opts) ...
java
private static void parseStyle(SvgElementBase obj, String style) { TextScanner scan = new TextScanner(style.replaceAll("/\\*.*?\\*/", "")); // regex strips block comments while (true) { String propertyName = scan.nextToken(':'); scan.skipWhitespace(); if (!sc...
python
def convert_rtc(cls, timestamp): """Convert a number of seconds since 1/1/2000 to UTC time.""" if timestamp & (1 << 31): timestamp &= ~(1 << 31) delta = datetime.timedelta(seconds=timestamp) return cls._Y2KReference + delta
java
static String rewriteIPv4MappedNotation(String string) { if (!string.contains(".")) { return string; } else { int lastColon = string.lastIndexOf(":"); String firstPart = string.substring(0, lastColon + 1); String mappedIPv4Part ...
java
protected String generateRelationshipText(final RelationshipType relationshipType, boolean shortSyntax, final String spacer) { final StringBuilder retValue; final List<Relationship> relationships; // Create the relationship heading if (relationshipType == RelationshipType.REFER_TO) { ...
java
public void setFirstObservedAt(java.util.Collection<DateFilter> firstObservedAt) { if (firstObservedAt == null) { this.firstObservedAt = null; return; } this.firstObservedAt = new java.util.ArrayList<DateFilter>(firstObservedAt); }
java
public static void handleError(HttpResponse response) throws ParseException, IOException { log.debug("{}", response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { log.debug("{}", EntityUtils.toString(entity)); } }
java
@Override public DirectedGraph<T> copy(Set<Integer> vertices) { Graph<T> g = super.copy(vertices); return new DirectedGraphAdaptor<T>(g); }
python
def duration(self): """ Return a timedelta for this task. Measure the time between this task's start and end time, or "now" if the task has not yet finished. :returns: timedelta object, or None if the task has not even started. """ if not self.started: ...
python
def pformat(self, prefix=()): ''' Makes a pretty ASCII format of the data, suitable for displaying in a console or saving to a text file. Returns a list of lines. ''' nan = float("nan") def sformat(segment, stat): FMT = "n={0}, mean={1}, p50/...
python
def set_rules(self, rules): """ Sets the rules to be run or ignored for the audit. Args: rules: a dictionary of the format `{"ignore": [], "apply": []}`. See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits Passing `{"apply": []...
python
def babel_compile(target): """ Babel, Compiles all translations """ click.echo(click.style("Starting Compile target:{0}".format(target), fg="green")) os.popen("pybabel compile -f -d {0}".format(target))
python
def fit(self, pixel_flux, data_placeholder, var_list, session, feed_dict={}): """ Parameters ---------- pixel_flux : ndarray The TPF-like pixel flux time series. The first dimension must represent time, and the remaining two dimensions must represent t...
java
public static void init(final Map<String, String> _values) { if (AppConfigHandler.HANDLER == null) { AppConfigHandler.HANDLER = new AppConfigHandler(_values); } }
java
public static String convertGlobToRegex(String pattern) { pattern = pattern.replaceAll("[\\\\\\.\\(\\)\\+\\|\\^\\$]", "\\\\$0"); pattern = pattern.replaceAll("\\[\\\\\\^", "[^"); pattern = Ruby.String.of(pattern).gsub("\\{[^\\}]+\\}", m -> { m = m.replaceAll(",", "|"); m = "(" + m.substring(1, ...
java
public static FDBigInteger valueOfPow52(int p5, int p2) { if (p5 != 0) { if (p2 == 0) { return big5pow(p5); } else if (p5 < SMALL_5_POW.length) { int pow5 = SMALL_5_POW[p5]; int wordcount = p2 >> 5; int bitcount = p2 & 0x1f;...
java
public void println(int i) throws IOException { if(this._listener!= null && !checkIfCalledFromWLonError()){ if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "non blocking println int , WriteListener enabled: " + this._listener); ...
python
def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) # assuming the contents has been vetted for utf-8 encoding contents = contents.encode("utf-8") with o...
java
public OvhNetwork project_serviceName_network_private_POST(String serviceName, String name, String[] regions, Long vlanId) throws IOException { String qPath = "/cloud/project/{serviceName}/network/private"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); ad...
java
protected static String ellipsis(String message, int maxLength) { if(message == null) { return "null"; } return message.length() < maxLength ? message : message.substring(0, maxLength - ELLIPSIS.length()) + ELLIPSIS; }
java
public static <U> U valueOrElse(Versioned<U> versioned, U defaultValue) { return versioned == null ? defaultValue : versioned.value(); }
java
public void transfromHeadline() { if (this.hlDepth > 0) { return; } int level = 0; final Line line = this.lines; if (line.isEmpty) { return; } int start = line.leading; while (start < line.value.length() && line....
python
def RandomStandardNormal(shape, dtype, seed): """ Standard (mu=0, sigma=1) gaussian op. """ if seed: np.random.seed(seed) return np.random.normal(size=reduce(mul, shape)).reshape(shape).astype(dtype_map[dtype]),
python
def get_console_size(): """Return console size as tuple = (width, height). Returns (None,None) in non-interactive session. """ display_width = options.display.width # deprecated. display_height = options.display.max_rows # Consider # interactive shell terminal, can detect term size ...
java
public static String fixLength(final String text, final int charsNum, final char paddingChar) { return fixLength(text, charsNum, paddingChar, false); }
java
protected void openVideo(boolean reopen , String ...filePaths) { synchronized (lockStartingProcess) { if( startingProcess ) { System.out.println("Ignoring video request. Detected spamming"); return; } startingProcess = true; } synchronized (inputStreams) { if (inputStreams.size() != filePath...
python
def get_unknown_opttrans_attr(path): """Utility method that gives a `dict` of unknown and unsupported optional transitive path attributes of `path`. Returns dict: <key> - attribute type code, <value> - unknown path-attr. """ path_attrs = path.pathattr_map unknown_opt_tran_attrs = {} for _, ...
python
def set_end_point_uri(self) -> bool: """ Extracts the route from the accessed URL and sets it to __end_point_uri :rtype: bool """ expected_parts = self.__route.split("/") actual_parts = self.__uri.split("/") i = 0 for part in expected_parts: i...
java
@Override public void execute(ExecutorService executor) { File f = new File(_locAdmin.resolveString(_location)); if (f.isAbsolute()) { resolve(_location, _filesToMonitor); } else { resolve(AppManagerConstants.SERVER_APPS_DIR + _location, _filesToMonitor); ...
python
def DeleteUser(self, user_link, options=None): """Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict """ ...
python
def rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """ rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) retur...
java
private int readFlags(byte flags) { // Verify the reserved bits at 7 and 6 are 0 int reserved7 = (flags >> 7) & 1; int reserved6 = (flags >> 6) & 1; if (reserved7 != 0 || reserved6 != 0) { throw new GeoPackageException( "Unexpected GeoPackage Geometry flags. Flag bit 7 and 6 should both be 0, 7=" ...
java
private void clearEdit() { m_fileTable.setEditable(false); if (m_editItemId != null) { updateItem(m_editItemId, false); } m_editItemId = null; m_editProperty = null; m_editHandler = null; updateSorting(); }
java
public static Timer getNamedTimer(String timerName, int todoFlags, long threadId) { Timer key = new Timer(timerName, todoFlags, threadId); registeredTimers.putIfAbsent(key, key); return registeredTimers.get(key); }
java
protected String formatDDLStatement(String sql) { String result = removeComments(sql); String[] parts = getTokens(sql, 0); if (parts.length > 2 && parts[0].equalsIgnoreCase("create") && parts[1].equalsIgnoreCase("table")) { String sqlWithSingleSpaces = String.join(" ", parts); int ...
java
public static Schema superSetOf(Schema schema, Field... newFields) { return superSetOf("superSetSchema" + (COUNTER++), schema, newFields); }
java
public void initializeSubContainers(CmsContainerPageElementPanel containerElement) { int containerCount = m_targetContainers.size(); m_targetContainers.putAll(m_containerpageUtil.consumeContainers(m_containers, containerElement.getElement())); updateContainerLevelInfo(); if (m_targetCon...
java
@Nullable @Size(2) public int[] getValidDateFields() { if (!mIsDateValid) { return null; } final int[] monthYearPair = new int[2]; final String rawNumericInput = getText().toString().replaceAll("/", ""); final String[] dateFields = DateUtils.separateDateStrin...
python
def bck_chunk(self): """ Returns the chunk backward from this chunk in the list of free chunks. """ raise NotImplementedError("%s not implemented for %s" % (self.bck_chunk.__func__.__name__, self.__class__.__name__))
java
private static synchronized PrepPipeline createOrFindPreparer(DatabasePreparer preparer, Iterable<Consumer<Builder>> customizers) throws IOException, SQLException { final ClusterKey key = new ClusterKey(preparer, customizers); PrepPipeline result = CLUSTERS.get(key); if (result != null) { ...
python
def write_backreferences(seen_backrefs, gallery_conf, target_dir, fname, snippet): """Writes down back reference files, which include a thumbnail list of examples using a certain module""" if gallery_conf['backreferences_dir'] is None: return example_file = os.path.join...
python
def _republish_processing_error(self, error): """Republish the original message that was received because a :exc:`~rejected.consumer.ProcessingException` was raised. This for internal use and should not be extended or used directly. Add a header that keeps track of how many times this ...
python
def deploy(self, job_name, command='', blocksize=1): instances = [] """Deploy the template to a resource group.""" self.client.resource_groups.create_or_update( self.resource_group, { 'location': self.location, } ) template_pa...
java
private Where addWhereClauseForRowRange(String keyAlias, Select select, RowRange<?> rowRange) { Where where = null; boolean keyIsPresent = false; boolean tokenIsPresent = false; if (rowRange.getStartKey() != null || rowRange.getEndKey() != null) { keyIsPresent = true; } if (rowRange.getStartToken() !...
java
private boolean isTruncationNeeded(PerJVMInfo lInfo, Map<Task, Map<LogName, LogFileDetail>> taskLogFileDetails, LogName logName) { boolean truncationNeeded = false; LogFileDetail logFileDetail = null; for (Task task : lInfo.allAttempts) { long taskRetainSize = (task.isMapTask() ?...
python
def to_string_short(self): """ see also :meth:`to_string` :return: a shorter abreviated string reprentation of the parameter """ if hasattr(self, 'constrained_by') and len(self.constrained_by) > 0: return "* {:>30}: {}".format(self.uniquetwig_trunc, self.get_quantity...
python
def linear_interpolate(tensor1, tensor2, coeffs): """Linearly interpolate between two tensors at coeff. Args: tensor1: 4-D Tensor, shape=(NHWC) tensor2: 4-D Tensor, shape=(NHWC) coeffs: list of floats. Returns: interp_latents: 5-D Tensor, with interp_latents[i] representing in...
java
protected String getQueryModifier() { String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER); return (null == queryModifier) && (null != m_baseConfig) ? m_baseConfig.getGeneralConfig().getQueryModifier() : queryModifier; }
python
def build_getters_support_matrix(app): """Build the getters support matrix.""" status = subprocess.call("./test.sh", stdout=sys.stdout, stderr=sys.stderr) if status != 0: print("Something bad happened when processing the test reports.") sys.exit(-1) drivers = set() matrix = { ...
python
def nvlist_to_dict(nvlist): '''Convert a CORBA namevalue list into a dictionary.''' result = {} for item in nvlist : result[item.name] = item.value.value() return result
python
def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
python
def add(self, layer, verbosity = 0, position = None): """ Adds a layer. Layer verbosity is optional (default 0). """ layer._verbosity = verbosity layer._maxRandom = self._maxRandom layer.minTarget = 0.0 layer.maxTarget = 1.0 layer.minActivation = 0.0 ...
java
public String asString() throws TransformerException { Properties outputProperties = new Properties(); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); return asString(outputProperties); }
python
def setup_lookup_table( self, hamiltonian='nearest-neighbour' ): """ Create a jump-probability look-up table corresponding to the appropriate Hamiltonian. Args: hamiltonian (Str, optional): String specifying the simulation Hamiltonian. valid values are 'nearest-neigh...
python
def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()])
java
public Hashtable[] getMultipleParams(String name) { List parts = (List)_partMap.getValues(name); if (parts==null) return null; Hashtable[] params = new Hashtable[parts.size()]; for (int i=0; i<params.length; i++) { params[i] = ((Part)parts.get(i))._headers; ...
python
def _create_mel_filter_bank(self): """ Create the Mel filter bank, and store it in ``self.filters``. Note that it is a function of the audio sample rate, so it cannot be created in the class initializer, but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`. ...
java
@SuppressWarnings("deprecation") private static String getPhysicalPath(ArtifactEntry artifactEntry) { String physicalPath = artifactEntry.getPhysicalPath(); if ( physicalPath != null ) { return physicalPath; } String entryPath = artifactEntry.getPath(); String ro...
python
def set_high_water_mark(socket, config): """ Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3. """ if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark...
python
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: ...
java
private boolean removeKeyForAllLanguages(String key) { try { if (hasDescriptor()) { lockDescriptor(); } loadAllRemainingLocalizations(); lockAllLocalizations(key); } catch (CmsException | IOException e) { LOG.warn("Not able loc...
java
public static XIncludeContext newContext(final XIncludeContext contextToCopy) { final XIncludeContext newContext = new XIncludeContext(contextToCopy.configuration); newContext.currentBaseURI = contextToCopy.currentBaseURI; newContext.basesURIDeque.addAll(contextToCopy.basesURIDeque); ...
python
def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = value['name'] # Find the previous value previous_value = __find_and_remove_value(previous, value) if previous_value is not None: ...
python
def list_users(): """ List users. """ users = user_manager.all() if users: print_table( ['ID', 'Email', 'Active', 'Confirmed At'], [(user.id, user.email, 'True' if user.active else 'False', user.confirmed_at.strftime('%Y-%m-%d...
python
def loaddata(settings_module, fixtures, bin_env=None, database=None, pythonpath=None, env=None): ''' Load fixture data Fixtures: comma separated list of fixtures to load CLI Example: .. code-block:: bash salt '*' dj...
java
public static void head(String url, HttpConsumer<HttpExchange> endpoint, MediaTypes... mediaTypes) { addResource(Methods.HEAD, url, endpoint, mediaTypes); }
python
def standard_deviation(x): """ Return a numpy array of column standard deviation Parameters ---------- x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column standard deviation Examples -------- >>> a = np.array([[...
java
public void marshall(GlobalSecondaryIndex globalSecondaryIndex, ProtocolMarshaller protocolMarshaller) { if (globalSecondaryIndex == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(globalSecondaryInde...
java
public V get(K key) throws E { clean(); ValueRef<K, V> valueRef = mValues.get(key); V value; if (valueRef == null || (value = valueRef.get()) == null) { try { value = create(key); } catch (Exception e) { // Workaround co...
java
public String next() { if (fifo.isEmpty()) { throw new RuntimeException("Fifo is empty"); } String cmd = (String) fifo.get(0); fifo.remove(0); return cmd; }
python
def _B(self, R): """Return numpy array from B1 up to and including Bn. (eqn. 6)""" HNn_R = self._HNn / R return HNn_R / self._sin_alpha * (0.4 * HNn_R / self._sin_alpha + 1)
python
def set_result(self, result): """ Sets the result of the Future. :param result: Result of the Future. """ if result is None: self._result = NONE_RESULT else: self._result = result self._event.set() self._invoke_callbacks()
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "_Datum", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "Definition") public JAXBElement<AbstractDatumType> create_Datum(AbstractDatumType value) { return new JAXBElement<AbstractDatumType>(__Datum_QNAME, Abs...
python
def check_lat(self, dataset): ''' float lat(time) ;//....................................... Depending on the precision used for the variable, the data type could be int or double instead of float. lat:long_name = "" ; //...................................... RECOMMENDED - Provide a desc...
java
protected Supplier<Set<Location>> overrideLocationSupplier(Injector injector, Supplier<Set<Location>> originalSupplier) { return originalSupplier; }
java
@Override @Deprecated public void forEachRemaining(java.util.function.Consumer<? super Pair<A, B>> action) { super.forEachRemaining(action); }
java
private static long computeSerialVersionUID(Class<?> cl, Field[] fields) { /* * First we should try to fetch the static slot 'static final long * serialVersionUID'. If it is defined, return it. If not defined, we * really need to compute SUID using SHAOutputStream */ ...
python
def floor(start, resolution): """Floor a datetime by a resolution. >>> now = datetime(2012, 7, 6, 20, 33, 16, 573225) >>> floor(now, STEP_1_HOUR) datetime.datetime(2012, 7, 6, 20, 0) """ if resolution == STEP_10_SEC: return datetime(start.year, start.month, start.day, start.hour, ...
python
def _permission_trees(permissions): """Get the cached permission tree, or build a new one if necessary.""" treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder() for permission in permissions: tree....
python
def _preprocess_params(cls, kwargs): """Returns a preprocessed dictionary of parameters. Use this to filter the kwargs passed to `new`, `create`, `build` methods. Args: **kwargs: a dictionary of parameters """ # kwargs.pop('csrf_token', None) for att...