language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def os_script(os_, vm_=None, opts=None, minion=''): ''' Return the script as a string for the specific os ''' if minion: minion = salt_config_to_yaml(minion) if os.path.isabs(os_): # The user provided an absolute path to the deploy script, let's use it return __render_script...
java
public void put(String data,Charset charset) throws APIException { HttpResponse response = client.put(getUrl(), new StringEntity(data, charset)); HttpClientHelpers.throwIfNotOk(response); }
python
def logpdf_link(self, inv_link_f, y, Y_metadata=None): """ Log Likelihood function given inverse link of f. .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i}) :param inv_link_f: latent variables inverse link of f. :type in...
java
public void insert(final DevState[] argIn, final int dim_x, final int dim_y) { deviceAttributeDAO.insert(argIn, dim_x, dim_y); }
python
def raw_send(self, destination, message, **kwargs): """Send a raw (unmangled) message to a queue. This may cause errors if the receiver expects a mangled message. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param ...
python
def is_wow64(self): """ Determines if the thread is running under WOW64. @rtype: bool @return: C{True} if the thread is running under WOW64. That is, it belongs to a 32-bit application running in a 64-bit Windows. C{False} if the thread belongs to e...
java
public void stop(int restartableId) { requested.remove((Integer) restartableId); Subscription subscription = restartableSubscriptions.get(restartableId); if (subscription != null) subscription.unsubscribe(); }
python
def set_device_offset(self, x_offset, y_offset): """ Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this method is when we want to create a :class:`Surface` that redirects drawing for a portion of an onscreen...
python
def get_variables(self) -> Set[str]: """Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces. """ variables = set() for cmd in self._cmd: ...
java
public void execute() { while (!steps.isEmpty()) { currentStep = steps.remove(0); try { LOG.debugPerformOperationStep(currentStep.getName()); currentStep.performOperationStep(this); successfulSteps.add(currentStep); LOG.debugSuccessfullyPerformedOperationStep(currentS...
python
def mean_fill(adf): """ Looks at each row, and calculates the mean. Honours the Trump override/failsafe logic. """ ordpt = adf.values[0] if not pd.isnull(ordpt): return ordpt fdmn = adf.iloc[1:-1].mean() if not pd.isnull(fdmn): return fdmn ...
java
public String extractPropertyFromURI(String propName, String uri) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "extractPropertyFromURI", new Object[]{propName, uri}); String result = null; // only something to do if uri is non-null & non-empty u if (uri != nu...
python
def init(args=None, lib='standard'): """Intialize the rabit module, call this once before using anything. Parameters ---------- args: list of str, optional The list of arguments used to initialized the rabit usually you need to pass in sys.argv. Defaults to sys.argv when it is N...
python
def get_task_db(self, source_path): '''从数据库中查询source_path的信息. 如果存在的话, 就返回这条记录; 如果没有的话, 就返回None ''' sql = 'SELECT * FROM upload WHERE source_path=?' req = self.cursor.execute(sql, [source_path, ]) if req: return req.fetchone() else: ...
java
protected void addMode(CliModeContainer mode) { CliModeObject old = this.id2ModeMap.put(mode.getId(), mode); if (old != null) { CliStyleHandling handling = this.cliStyle.modeDuplicated(); DuplicateObjectException exception = new DuplicateObjectException(mode, mode.getMode().id()); if (handlin...
java
public void reconstitute(BaseDestinationHandler destinationHandler, SIMPTransactionManager txManager) throws MessageStoreException { if (tc.isEntryEnabled()) SibTr.entry(tc, "reconstitute", new Object[] {destinationHandler, txManager}); initializeNonPersistent(dest...
python
def _check_for_cancel(self, job_id, current_stage=""): """ Check if a job has been requested to be cancelled. When called, the calling function can optionally give the stage it is currently in, so the user has information on where the job was before it was cancelled. :param job_...
python
def output(self, original_filename): """ _filename is not used Args: _filename(string) """ for contract in self.contracts: for function in contract.functions + contract.modifiers: filename = "{}-{}-{}.dot".format(original_filen...
java
@Override public <X extends Archive<X>> X getAsType(Class<X> type, String path) { return this.getArchive().getAsType(type, path); }
python
def op_install_package(self, names): """Install packages into virtual envs as to satisfy app requirements. Exact version numbers could be given as in PIP: somedep==1.5 :param list names: """ venvs = self.get_venvs() for venv in venvs: for name in names: ...
python
def _print_installed_apps(self, controller): """Print out a list of installed sprockets applications :param str controller: The name of the controller to get apps for """ print('\nInstalled Sprockets %s Apps\n' % controller.upper()) print("{0:<25} {1:>25}".format('Name', 'Module...
python
def _expected_reads(run_info_file): """Parse the number of expected reads from the RunInfo.xml file. """ reads = [] if os.path.exists(run_info_file): tree = ElementTree() tree.parse(run_info_file) read_elem = tree.find("Run/Reads") reads = read_elem.findall("Read") re...
java
public Any insert(short data) throws DevFailed { Any out_any = alloc_any(); out_any.insert_short(data); return out_any; }
java
@Override public Stream<LoadBalancerNodeMetadata> findLazy(LoadBalancerNodeFilter filter) { checkNotNull(filter, "Filter must be not a null"); Stream<LoadBalancerPoolMetadata> loadBalancerPools = loadBalancerPoolService.findLazy( filter.getLoadBalancerPoolFilter() ); ...
java
public Object decode(CachedData d) { byte[] data = d.getData(); Object rv = null; if ((d.getFlags() & COMPRESSED) != 0) { data = decompress(d.getData()); } int flags = d.getFlags() & SPECIAL_MASK; if ((d.getFlags() & SERIALIZED) != 0 && data != null) { rv = deserialize(data); } e...
java
@Override public void gbmv(char order, char TransA, int KL, int KU, double alpha, INDArray A, INDArray X, double beta, INDArray Y) { if (Nd4j.getExecutioner().getProfilingMode() == OpExecutioner.ProfilingMode.ALL) OpProfiler.getInstance().processBlasCall(false, A, X, Y); ...
java
@Override public Route getRouteFor(String method, String uri, Request request) { return getRouteFor(HttpMethod.from(method), uri, request); }
java
@Override public void setText(String text) { setUpFace(text, m_imageClass); m_text = text; setTitle(text); }
python
def save_setup_command(argv, build_path): """ Save setup command to a file. """ file_name = os.path.join(build_path, 'setup_command') with open(file_name, 'w') as f: f.write(' '.join(argv[:]) + '\n')
java
public static JsonArrayDocument create(String id, JsonArray content) { return new JsonArrayDocument(id, 0, content, 0, null); }
python
def _determine_keys(dictionary): """Determine the different kinds of keys.""" optional = {} defaults = {} mandatory = {} types = {} for key, value in dictionary.items(): if isinstance(key, Optional): optional[key.value] = parse_schema(value) if isinstance(value, B...
python
def save_wdhistory(self): """Save history to a text file in user home directory""" text = [ to_text_string( self.pathedit.itemText(index) ) \ for index in range(self.pathedit.count()) ] try: encoding.writelines(text, self.LOG_PATH) except EnvironmentErr...
java
public static String upstreamToString(Channel upstream) { if (upstream == null) { linkedRemaining.set(null); return ""; } if (linkedRemaining.get() == null) { linkedRemaining.set(1); } if (linkedRemaining.get() <= 0) { linkedRemaini...
java
@SuppressWarnings("unchecked") public void addPersistentDestinationData(HashMap hm) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addPersistentDestinationData", hm); super.addPersistentData(hm); // Is the destination marked as to be del...
python
def check(self, action, page=None, lang=None, method=None): """Return ``True`` if the current user has permission on the page.""" if self.user.is_superuser: return True if action == 'change': return self.has_change_permission(page, lang, method) if action == 'de...
python
def close_client(self, index=None, client=None, save=False): """Close client tab from index or widget (or close current tab).""" if not self.tabwidget.count(): return if client is not None: index = self.tabwidget.indexOf(client) if index is None and client i...
java
public static <T, R extends Collection<T>> R removeAllFrom(Iterable<? extends T> iterable, R targetCollection) { Iterate.removeAllIterable(iterable, targetCollection); return targetCollection; }
python
def execute_script(script_blocks, script_vars, gallery_conf): """Execute and capture output from python script already in block structure Parameters ---------- script_blocks : list (label, content, line_number) List where each element is a tuple with the label ('text' or 'code'), ...
python
def get_album(self, id): """Return information about this album.""" url = self._base_url + "/3/album/{0}".format(id) json = self._send_request(url) return Album(json, self)
python
def freq_mag(magnitudes, completeness, max_mag, binsize=0.2, **kwargs): """ Plot a frequency-magnitude histogram and cumulative density plot. Currently this will compute a b-value, for a given completeness. B-value is computed by linear fitting to section of curve between completeness and max_mag. ...
python
def averaging(grid, numGrid, numPix): """ resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image...
java
public final QueryParser.tagged_return tagged() throws RecognitionException { QueryParser.tagged_return retval = new QueryParser.tagged_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token TAGGED75=null; Token WS76=null; Token String77=null; Co...
java
public static void extendData(SheetTemplate template, Map<String, String> data) { if (data == null) return; for (Row row : template.sheet) { for (Cell c : row) { if (c.getCellTypeEnum() != CellType.STRING) continue; String str =...
python
def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True): """ Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :par...
java
public static SegmentId dummy(String dataSource, int partitionNum) { return of(dataSource, Intervals.ETERNITY, "dummy_version", partitionNum); }
python
def iter_bitstream(self, iter_duration_generator): """ iterate over self.iter_trigger() and yield the bits """ assert self.half_sinus == False # Allways trigger full sinus cycle # build min/max Hz values bit_nul_min_hz = self.cfg.BIT_NUL_HZ - self.cfg.HZ_VARIATIO...
java
@Nonnull @Nonempty public static String getURL (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final StringBuilder ret = getFullServerName (aHttpRequest.getScheme (), aHttpRequest.getServerName (), ...
python
def __complete_cmds(self, text): """Get the list of commands whose names start with a given text.""" return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
java
void flagTaggedStates() { List<RBBINode> tagNodes = new ArrayList<RBBINode>(); RBBINode tagNode; int i; int n; fRB.fTreeRoots[fRootIx].findNodes(tagNodes, RBBINode.tag); for (i=0; i<tagNodes.size(); i++) { // For each ta...
java
public static void validArgument(boolean expression, String message, Object... messageArgs) { if (!expression) { throw new IllegalArgumentException(format(message, messageArgs)); } }
java
public void write(byte[] buffer, int offset, int length) throws IOException { OutputStream os = getOutputStream(); for (; length > 0x8000; length -= 0x8000) { os.write('D'); os.write(0x80); os.write(0x00); os.write(buffer, offset, 0x8000); ...
python
def nodes(self): """ This is a special derived_class relationship because NodeBalancerNode is the only api object that requires two parent_ids """ if not hasattr(self, '_nodes'): base_url = "{}/{}".format(NodeBalancerConfig.api_endpoint, NodeBalancerNode.derived_url_p...
python
def has_change_permission(self, page, lang, method=None): """Return ``True`` if the current user has permission to change the page.""" # the user has always the right to look at a page content # if he doesn't try to modify it. if method != 'POST': return True ...
python
def getAllIDs(cls, where=None, orderBy=None): """Retrive all the IDs, possibly matching the where clauses. Where should be some list of where clauses that will be joined with AND). Note that the result might be tuples if this table has a multivalue _sqlPrimary. """ (sql,...
python
def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nam...
java
public void afterRead(D record, long startTime) { Instrumented.updateTimer(this.extractorTimer, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); if (record != null) { Instrumented.markMeter(this.readRecordsMeter); } }
python
def browse_in_qt5_ui(self): """Browse and edit the SubjectInfo in a simple Qt5 based UI.""" self._render_type = "browse" self._tree.show(tree_style=self._get_tree_style())
java
@Override public void stopAnimation(final boolean jumpToTarget) { if (!mMapView.getScroller().isFinished()) { if (jumpToTarget) { mMapView.mIsFlinging = false; mMapView.getScroller().abortAnimation(); } else stopPanning(); } ...
python
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for CalendarDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ return (get_start_of_day(self.syea...
python
def inspect(lines): """Inspect SDFile list of string Returns: tuple: (data label list, number of records) """ labels = set() count = 0 exp = re.compile(r">.*?<([\w ]+)>") # Space should be accepted valid = False for line in lines: if line.startswith("M END\n"): ...
java
public static short[] add(short[] array, short element) { short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE); newArray[newArray.length - 1] = element; return newArray; }
python
def start(st_reg_number): """Checks the number valiaty for the São Paulo state""" divisor = 11 verificador_one = int(st_reg_number[len(st_reg_number)-4]) verificador_two = int(st_reg_number[len(st_reg_number)-1]) weights_first = [1, 3, 4, 5, 6, 7, 8, 10] weights_secund = [3, 2, 10, 9, 8, 7, 6,...
java
@Override public IoBuffer fill(int size) { autoExpand(size); int q = size >>> 3; int r = size & 7; for (int i = q; i > 0; i--) { putLong(0L); } q = r >>> 2; r = r & 3; if (q > 0) { putInt(0); } q = r >> 1; r = r & 1; if (q > 0) { putShort((short) ...
python
def remove_nullchars(block): """Strips NULL chars taking care of bytes alignment.""" data = block.lstrip(b'\00') padding = b'\00' * ((len(block) - len(data)) % 8) return padding + data
java
public void addShutdownHookForStoppingContainers(final boolean keepContainer, final boolean removeVolumes, final boolean removeCustomNetworks) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { stopStartedContaine...
java
@SuppressWarnings("unchecked") public EList<IfcGridAxis> getVAxes() { return (EList<IfcGridAxis>) eGet(Ifc2x3tc1Package.Literals.IFC_GRID__VAXES, true); }
java
public boolean hasNext() { if(cachedNext != null) return true; while(itr.hasNext()) { S o = itr.next(); T adapted = adapter.adapt(o); if(adapted != null) { cachedNext = adapted; return true; } } return false; }
java
public BBox calcBBox2D() { check("calcRouteBBox"); BBox bounds = BBox.createInverse(false); for (int i = 0; i < pointList.getSize(); i++) { bounds.update(pointList.getLatitude(i), pointList.getLongitude(i)); } return bounds; }
java
private static String encode(final String txt) { try { return URLEncoder.encode( txt, Charset.defaultCharset().name() ); } catch (final UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } }
java
public final <V> SynchronizedGenericMatrix<V> synchronizedMatrix(GenericMatrix<V> matrix) { return new SynchronizedGenericMatrix<V>(matrix); }
java
public static Prop useFirstFound(String... fileNames) { for (String fn : fileNames) { try { return use(fn, Const.DEFAULT_ENCODING); } catch (Exception e) { continue ; } } throw new IllegalArgumentException("没有配置文件可被使用"); }
java
public void marshall(DocumentParameter documentParameter, ProtocolMarshaller protocolMarshaller) { if (documentParameter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(documentParameter.getName(),...
python
def get_category(self, slug): """ Get the category object """ try: return get_category_for_slug(slug) except ObjectDoesNotExist as e: raise Http404(str(e))
python
def count_vowels(text): """Count number of occurrences of vowels in a given string""" count = 0 for i in text: if i.lower() in config.AVRO_VOWELS: count += 1 return count
java
@Override public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { throw new FFMQException("Unsupported feature","UNSUPPORTED_FEATURE"); }
java
public java.util.List<String> getTagKeys() { if (tagKeys == null) { tagKeys = new com.amazonaws.internal.SdkInternalList<String>(); } return tagKeys; }
java
@Nullable @SuppressWarnings("unchecked") public static <C> C findConfiguration(Class<C> clazz, @Nullable ChannelHandler handler) { Objects.requireNonNull(clazz, "configuration type"); if (handler instanceof BootstrapPipelineHandler) { BootstrapPipelineHandler rph = (BootstrapPipelineHandler) h...
java
public Quaternionf mul(float qx, float qy, float qz, float qw) { set(w * qx + x * qw + y * qz - z * qy, w * qy - x * qz + y * qw + z * qx, w * qz + x * qy - y * qx + z * qw, w * qw - x * qx - y * qy - z * qz); return this; }
java
public static Collection getEmbeddedCollectionInstance(Field embeddedCollectionField) { Collection embeddedCollection = null; Class embeddedCollectionFieldClass = embeddedCollectionField.getType(); if (embeddedCollection == null || embeddedCollection.isEmpty()) { ...
python
def _to_repeatmasker_string(pairwise_alignment, column_width=DEFAULT_COL_WIDTH, m_name_width=DEFAULT_MAX_NAME_WIDTH): """ generate a repeatmasker formated representation of this pairwise alignment. :param column_width: number of characters to output per line of alignment :param m_na...
java
private BigDecimal round(BigDecimal amount) { return new BigDecimal(amount.movePointRight(2).add(new BigDecimal(".5")).toBigInteger()).movePointLeft(2); }
python
def pattern(self, platform, key, compiled=True): """Return the pattern defined by the key string specific to the platform. :param platform: :param key: :param compiled: :return: Pattern string or RE object. """ patterns = self._platform_patterns(platform, compile...
java
public ServiceFuture<ServiceEndpointPolicyDefinitionInner> beginCreateOrUpdateAsync(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions, final ServiceCallback<ServiceEndpointPolicyDefinitionInner> s...
java
@Override public void getScalingEvents(final String scopeName, final String streamName, final Long from, final Long to, final SecurityContext securityContext, final AsyncResponse asyncResponse) { long traceId = LoggerHelpers.traceEnter(log, "getScalingEvents"); try ...
python
def _ParseDistributedTrackingIdentifier( self, parser_mediator, uuid_object, origin): """Extracts data from a Distributed Tracking identifier. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. uuid_object (...
java
public void addProduction(Event event, Grammar grammar) { containers.add(new SchemaLessProduction(this, grammar, event, getNumberOfEvents())); // pre-calculate count for log2 (Note: always 2nd level productions // available) // Note: BuiltInDocContent and BuiltInFragmentContent do not use this // variabl...
python
def _make_dest_env(self): ''' This will create the folder in self.report_dir (defaults to /tmp) to store the sanitized files and populate it using shutil These are the files that will be scrubbed ''' try: shutil.copytree(self.report, self.dir_path, symlinks=True, igno...
python
def _fire_status_changed(self): """ Tells listeners of a changed status. """ for listener in self._status_listeners: try: listener.new_media_status(self.status) except Exception: # pylint: disable=broad-except _LOGGER.exception("Exception thrown w...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static Object getRegisterableMBean(ServiceReference<?> serviceReference, Object mBean) throws NotCompliantMBeanException { // String methodName = "getRegisterableMBean"; // System.out.println(methodName + ": ENTER: MBean [ " ...
java
private SemanticStatus argumentsMatch(final String arg1, final String arg2) { if (arg1.startsWith(ENCODE_PREFIX)) { if (arg2.startsWith(FUNC_PREFIX)) { return INVALID_RETURN_TYPE_ARGUMENT; } if (!arg2.startsWith(ENCODE_PREFIX)) { return INVALI...
python
def set_iscsi_initiator_info(self, initiator_iqn): """Set iSCSI initiator information in iLO. :param initiator_iqn: Initiator iqn for iLO. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. ...
java
public final AntlrDatatypeRuleToken ruleMethodModifier() throws RecognitionException { AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken(); Token kw=null; enterRule(); try { // InternalSARL.g:9800:2: ( (kw= 'def' | kw= 'override' ) ) // InternalSARL...
java
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { final HandlerLocation location = new HandlerLocation(request, handler, HandlerStep.CONTROLLER); threadLocation.set(location); // Start controller stopwatch startStopwatch(location); return true; }
python
def sepBy(p, sep): '''`sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`. Returns a list of values returned by `p`.''' return separated(p, sep, 0, maxt=float('inf'), end=False)
python
def parse_column_filters(*definitions): """Parse multiple compound column filter definitions Examples -------- >>> parse_column_filters('snr > 10', 'frequency < 1000') [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)] >>> parse_column_filters('snr > 10 && freq...
java
@Override public PagedSearchResult discoverSearch(UploadSearchParams discoverSearchParams) { PagedSearchResult result = searchOperations.discoverSearch(discoverSearchParams); if(result!=null && enableAutoSolutionActionTrack) { String reqId = result.getReqId(); this.sendSoluti...
python
def gauge(self, stat, value, rate=1, delta=False): """Set a gauge value.""" if value < 0 and not delta: if rate < 1: if random.random() > rate: return with self.pipeline() as pipe: pipe._send_stat(stat, '0|g', 1) ...
java
public static boolean close(final Object[] streams) { boolean success = true; for (Object stream : streams) { boolean rv = close(stream); if (!rv) success = false; } return success; }
java
public ApiResponse<List<CharacterAssetsLocationsResponse>> postCharactersCharacterIdAssetsLocationsWithHttpInfo( Integer characterId, List<Long> requestBody, String datasource, String token) throws ApiException { com.squareup.okhttp.Call call = postCharactersCharacterIdAssetsLocationsValidateBeforeC...
python
def list_(device, unit=None): ''' Prints partition information of given <device> CLI Examples: .. code-block:: bash salt '*' partition.list /dev/sda salt '*' partition.list /dev/sda unit=s salt '*' partition.list /dev/sda unit=kB ''' _validate_device(device) if un...