query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', N...
csn
func (p *PhysicalProperty) Clone() *PhysicalProperty { prop := &PhysicalProperty{ Items: p.Items, TaskTp:
p.TaskTp, ExpectedCnt: p.ExpectedCnt, } return prop }
csn_ccr
update figures and statistics windows with a new selection of specimen
def update_selection(self): """ update figures and statistics windows with a new selection of specimen """ # clear all boxes self.clear_boxes() self.draw_figure(self.s) # update temperature list if self.Data[self.s]['T_or_MW'] == "T": self.te...
csn
Displays whether 'restart on freeze' is on or off if supported :return: A string value representing the "restart on freeze" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_freeze
def get_restart_freeze(): ''' Displays whether 'restart on freeze' is on or off if supported :return: A string value representing the "restart on freeze" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_freeze ''' ret = salt.utils.mac_utils...
csn
Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @return: the extension @rtype: string
def guess_extension(amimetype, normalize=False): """ Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @return: the extension @rtype: string """ ext = _mimes.guess_extension(amimetype) if ext and normalize: # Normalize some...
csn
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.  At the end, the "skyline" when...
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: # Pad with inf to make implementation easier INF = -10_000 n = len(grid) total = 0 max_rows = [max(row, default=INF) for row in grid] # Transpose the grid to make max less cumbersome ...
apps
private String decodeAndEscapeSelectors(FacesContext context, UIComponent component, String selector) { selector = ExpressionResolver.getComponentIDs(context, component, selector);
selector = BsfUtils.escapeJQuerySpecialCharsInSelector(selector); return selector; }
csn_ccr
public function twitter($entity) { $twitterName = Configure::read('Settings.Cms.SEO.Social.twitter_username'); if ($twitterName !== null) { $twitterName = '@' . $twitterName; } $attributes = [ 'twitter:card' => 'summary', 'twitter:title' => $this-...
'twitter:site' => $twitterName, 'twitter:creator' => $twitterName, ]; $out = ''; foreach ($attributes as $property => $content) { $out .= $this->_render(self::ATTR_NAME, $property, $content); } return $out; }
csn_ccr
remove leading zeros python
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
cosqa
Truncate a collection's data @return Collection
public function truncate() { $this->_map = []; $this->_data = []; $this->_models = []; $this->_pointer = 0; return $this; }
csn
Basic parser to deal with date format of the Kp file.
def _parse(yr, mo, day): """ Basic parser to deal with date format of the Kp file. """ yr = '20'+yr yr = int(yr) mo = int(mo) day = int(day) return pds.datetime(yr, mo, day)
csn
Checks if results in cache will satisfy the source before parsing. @param Event $event Current event emitted by the manager (Reflect class) @return void
public function onReflectProgress(GenericEvent $event) { if ($response = $this->storage->fetch($event)) { ++$this->stats[self::STATS_HITS]; $this->hashUserData = sha1(serialize($response)); $event['notModified'] = $response; } else { $this->hashUserDat...
csn
def json_dumps(cls, obj, **kwargs): """ A rewrap of json.dumps done for one reason - to inject a custom `cls` kwarg :param obj: :param kwargs: :return: :rtype: str
""" if 'cls' not in kwargs: kwargs['cls'] = cls.json_encoder return json.dumps(obj, **kwargs)
csn_ccr
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'. For example: input = "(first)and(second)" should return {0:6, 10:17} If brackets cannot be pair...
def bracket_pairs(string): brackets = {} open_brackets = [] for i, c in enumerate(string): if c == '(': open_brackets.append(i) elif c == ')': if not open_brackets: return False brackets[open_brackets.pop()] = i return False if open_b...
apps
Get youtube ID @param {string} url @returns {string} video id
function getYoutubeID(url) { let videoID = ''; url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/); if (url[2] !== undefined) { videoID = url[2].split(/[^0-9a-z_\-]/i); videoID = videoID[0]; } else { videoID = url; } return videoID; }
csn
// Base64 reads string from config file then decode using base64
func (r *Reader) Base64(name string) []byte { return r.Base64Default(name, []byte{}) }
csn
protected int interpretInfo(LineParser lp, MessageMgr mm){ String fileName = this.getFileName(lp); String content = this.getContent(fileName, mm); if(content==null){ return 1; } String[] lines = StringUtils.split(content, "\n"); String info = null; for(String s : lines){ if(s.startsWith("//**")){ ...
mm.report(MessageMgr.createInfoMessage("script {} - info: {}", new Object[]{fileName, info})); // Skb_Console.conInfo("{}: script {} - info: {}", new Object[]{shell.getPromptName(), fileName, info}); } return 0; }
csn_ccr
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two di...
def gcd(a, b): while b > 0: a, b = b, a % b return a n = int(input()) A = list(map(int, input().split())) GCD = A[0] for x in A[1:]: GCD = gcd(GCD, x) num = max(A) // GCD - n if num % 2 == 0: print("Bob") else: print("Alice")
apps
def _pruning_base(self, axis=None, hs_dims=None): """Gets margin if across CAT dimension. Gets counts if across items. Categorical variables are pruned based on their marginal values. If the marginal is a 0 or a NaN, the corresponding row/column is pruned. In case of a subvars (items) d...
return self.as_array(weighted=False, include_transforms_for_dims=hs_dims) # In case of allowed axis, just return the normal API margin. This call # would throw an exception when directly invoked with bad axis. This is # intended, because we want to be as explicit as possible. Margins ...
csn_ccr
def _search_for_files(parts): """ Given a list of parts, return all of the nested file parts. """ file_parts = [] for part in parts: if isinstance(part, list):
file_parts.extend(_search_for_files(part)) elif isinstance(part, FileToken): file_parts.append(part) return file_parts
csn_ccr
Renders a hidden form field containing the technical identity of the given object. @param object $object Object to create the identity field for @param string $name Name @return string A hidden field containing the Identity (UUID in Flow) of the given object or NULL if the object is unknown to the persistence framewor...
protected function renderHiddenIdentityField($object, $name) { if (!is_object($object) || $this->persistenceManager->isNewObject($object)) { return ''; } $identifier = $this->persistenceManager->getIdentifierByObject($object); if ($identifier === null) { retur...
csn
how to turn bytes string into bytes in python3
def to_bytes(s, encoding="utf-8"): """Convert a string to bytes.""" if isinstance(s, six.binary_type): return s if six.PY3: return bytes(s, encoding) return s.encode(encoding)
cosqa
func (t *Template) GetAWSElasticLoadBalancingV2ListenerCertificateWithName(name string) (*resources.AWSElasticLoadBalancingV2ListenerCertificate, error) { if untyped, ok := t.Resources[name]; ok
{ switch resource := untyped.(type) { case *resources.AWSElasticLoadBalancingV2ListenerCertificate: return resource, nil } } return nil, fmt.Errorf("resource %q of type AWSElasticLoadBalancingV2ListenerCertificate not found", name) }
csn_ccr
Outputs the mail to a text file according to RFC 4155. @param \Swift_Mime_SimpleMessage $message The message to send @param array &$failedRecipients Failed recipients (no failures in this transport) @return int
public function send(\Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $message->generateId(); // Create a mbox-like header $mboxFrom = $this->getReversePath($message); $mboxDate = strftime('%c', $message->getDate()->getTimestamp()); $messageString = sprintf('...
csn
def _consolidate_classpath(self, targets, classpath_products): """Convert loose directories in classpath_products into jars. """ # TODO: find a way to not process classpath entries for valid VTs. # NB: It is very expensive to call to get entries for each target one at a time. # For performance reasons ...
# Regenerate artifact for invalid vts. if not vt.valid: with self.open_jar(jarpath, overwrite=True, compressed=False) as jar: jar.write(entry.path) # Replace directory classpath entry with its jarpath. classpath_products.remove_for_target(vt...
csn_ccr
Returns model table name @return string
public function getTableName() { if (is_null($this->_tableName)) { $this->_tableName = $this->getDescriptor()->getEntity() ->getTableName(); } return $this->_tableName; }
csn
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { GetField fields = in.readFields(); beginDefaultContext = fields.get(BEGIN_DEFAULT, true); // Note that further processing is required
in JEEMetadataContextProviderImpl.deserializeThreadContext // in order to re-establish the thread context based on the metadata identity if not defaulted. }
csn_ccr
Generate a linear lookup table. :param nbits: int Number of bits to represent a quantized weight value :param wp: numpy.array Weight blob to be quantized Returns ------- lookup_table: numpy.array Lookup table of shape (2^nbits, ) qw: numpy.array Decomposed bit ...
def _get_linear_lookup_table_and_weight(nbits, wp): """ Generate a linear lookup table. :param nbits: int Number of bits to represent a quantized weight value :param wp: numpy.array Weight blob to be quantized Returns ------- lookup_table: numpy.array Lookup table ...
csn
// ResponseHeaders responds with a map of header values
func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) { args := r.URL.Query() for k, vs := range args { for _, v := range vs { w.Header().Add(http.CanonicalHeaderKey(k), v) } } body, _ := json.Marshal(args) if contentType := w.Header().Get("Content-Type"); contentType == "" { w.Header(...
csn
public static List<TracyEvent> getEvents() { TracyThreadContext ctx = threadContext.get(); List<TracyEvent> events = EMPTY_TRACY_EVENT_LIST;
if (isValidContext(ctx)) { events = ctx.getPoppedList(); } return events; }
csn_ccr
Determine if the app has custom exception handler @return bool
public function hasCustomHandler() { if (!class_exists(\App\Exception\Handler::class)) { return false; } if (!in_array(\Pharest\Exception\ExceptionHandler::class, class_implements(\App\Exception\Handler::class))) { return false; } return true; }
csn
Stages the models for use by subsequent functions @param {???} app - loopback application @param {Array} models - instances of ModelType to populate with data @param {callback} cb - callback that handles the error or successful completion
function stageModels(app, models, cb) { logger.debug('stageModels entry'); async.forEach(models, function(model, callback) { app.dataSources.db.automigrate( model.name, function(err) { callback(err); } ); }, function(err) { logger.debug('stageModels ex...
csn
function normalizeIdentifier(identifier) { if (identifier === ".") { // '.' might be referencing either the root or a locally scoped variable // called '.'. So try for the locally scoped variable first and then // default to the root return "(data['.'] || data)"; }
return "data" + identifier.split(".").map(function(property) { return property ? "['" + property + "']" : ""; }).join(""); }
csn_ccr
public function slice($start_index, $end_index = NULL) { if ($start_index < 0) { $start_index = $this->count() + $start_index; } if ($end_index < 0) { $end_index = $this->count() + $end_index; } $last_index = $this->count() - 1; if ($start_index > $last_index) { $start_index = ...
= $end_index; } $length = $end_index - $start_index; } else { $length = $this->count() - $start_index; } return new NodeCollection(array_slice($this->nodes, $start_index, $length)); }
csn_ccr
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on...
class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 if len(nums) < 3: return max(nums) dp = [0] * len(nums) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) for i in range(2, len(nums)): dp[i] = max(dp...
apps
compute manhattan distance python
def _manhattan_distance(vec_a, vec_b): """Return manhattan distance between two lists of numbers.""" if len(vec_a) != len(vec_b): raise ValueError('len(vec_a) must equal len(vec_b)') return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))
cosqa
Send SOAP message. Depending on how the ``nosend`` & ``retxml`` options are set, may do one of the following: * Return a constructed web service operation request without sending it to the web service. * Invoke the web service operation and return its SOAP reply XML. ...
def send(self, soapenv): """ Send SOAP message. Depending on how the ``nosend`` & ``retxml`` options are set, may do one of the following: * Return a constructed web service operation request without sending it to the web service. * Invoke the web service...
csn
def accuracy(current, predicted): """ Computes the accuracy of the TM at time-step t based on the prediction at time-step t-1 and the current active columns at time-step t. @param current (array) binary vector containing current active columns @param predicted (array) binary vector containing predicted act...
@return acc (float) prediction accuracy of the TM at time-step t """ acc = 0 if np.count_nonzero(predicted) > 0: acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted)) return acc
csn_ccr
Returns the given child index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.index_of(node_b) 0 >>> node_a.inde...
def index_of(self, child): """ Returns the given child index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.index_of(no...
csn
func PasswordFieldFromInstance(val reflect.Value, t reflect.Type, fieldNo int, name
string) *Field { ret := PasswordField(name) ret.SetValue(fmt.Sprintf("%s", val.Field(fieldNo).String())) return ret }
csn_ccr
Use this API to fetch csvserver_cmppolicy_binding resources of given name .
public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{ csvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding(); obj.set_name(name); csvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service); return response; }
csn
def _deserialize(self, data): """ Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Meta.deserialize_skip`` :param data dict: JSON-style object with instance data. :return: this instance ...
except AttributeError: # _meta not available skip = [] for key, value in data.items(): if key not in skip: value = self._deserialize_value(key, value) setattr(self, key, value) return self
csn_ccr
public function mergedWith(Metadata $additionalMetadata): self { $values = array_merge($this->values, $additionalMetadata->values);
if ($values === $this->values) { return $this; } return new static($values); }
csn_ccr
Returns a DOM representation of the payment. @return: Element
def to_xml(self): ''' Returns a DOM representation of the payment. @return: Element ''' for n, v in { "amount": self.amount, "date": self.date, "method":self.method}.items(): if is_empty_or_none(v): raise PaymentError("'%s' attribu...
csn
// NewReader creates a new Reader reading from r. // NewReader automatically reads in the ar file header, and checks it is valid.
func NewReader(r io.Reader) (*Reader, error) { ar := &Reader{r: r} arHeader := make([]byte, arHeaderSize) _, err := io.ReadFull(ar.r, arHeader) if err != nil { return nil, err } if string(arHeader) != ArFileHeader { return nil, errors.New("ar: Invalid ar file") } return ar, nil }
csn
Writes reversed integer to buffer. @param out Buffer @param value Integer to write
public static void writeReverseInt(IoBuffer out, int value) { out.put((byte) (0xFF & value)); out.put((byte) (0xFF & (value >> 8))); out.put((byte) (0xFF & (value >> 16))); out.put((byte) (0xFF & (value >> 24))); }
csn
Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: byte...
def read(self, size=None): """Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remain...
csn
Gets the html of this node, including it's own tag. @return string
public function outerHtml() { // special handling for root if ($this->tag->name() == 'root') { return $this->innerHtml(); } if ( ! is_null($this->outerHtml)) { // we already know the results. return $this->outerHtml; } $return = $...
csn
public function generateUuid() { if (is_readable(self::UUID_SOURCE)) { $uuid = trim(file_get_contents(self::UUID_SOURCE)); } elseif (function_exists('mt_rand')) { /** * Taken from stackoverflow answer, possibly not the fastest or * strictly standards com...
// 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } else { ...
csn_ccr
Puts all the child widgets in the correct position.
def _grid_widgets(self): """Puts all the child widgets in the correct position.""" self._font_family_header.grid(row=0, column=1, sticky="nswe", padx=5, pady=5) self._font_label.grid(row=1, column=1, sticky="nswe", padx=5, pady=(0, 5)) self._font_family_list.grid(row=2, rowspan=3, column...
csn
Returns a list of Encodings that belong to a Profile. @param id_or_name Id or name of a Profile. @param factory_id Id of a Factory. @param [Hash] opts the optional parameters @return [PaginatedEncodingsCollection]
def profile_encodings(id_or_name, factory_id, opts = {}) data, _status_code, _headers = profile_encodings_with_http_info(id_or_name, factory_id, opts) return data end
csn
Convert hours, minutes, seconds, and microseconds to fractional days. Parameters ---------- hour : int, optional Hour number. Defaults to 0. min : int, optional Minute number. Defaults to 0. sec : int, optional Second number. Defaults to 0. micro : int, optional ...
def hmsm_to_days(hour=0,min=0,sec=0,micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. Parameters ---------- hour : int, optional Hour number. Defaults to 0. min : int, optional Minute number. Defaults to 0. sec : int, optional Seco...
csn
protected String properties(TQProperty<?>... props) { StringBuilder selectProps = new StringBuilder(50); for (int i = 0; i < props.length; i++) { if (i > 0) { selectProps.append(","); }
selectProps.append(props[i].propertyName()); } return selectProps.toString(); }
csn_ccr
Attach a URL to a sheet. The URL can be a normal URL (attachmentType "URL"), a Google Drive URL (attachmentType "GOOGLE_DRIVE") or a Box.com URL (attachmentType "BOX_COM"). It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/attachments @param sheetId the sheet id @param attachment the att...
public Attachment attachUrl(long sheetId, Attachment attachment) throws SmartsheetException { return this.createResource("sheets/" + sheetId + "/attachments", Attachment.class, attachment); }
csn
Adds a case clause to this switch statement.
public SwitchBuilder addCase(Expression caseLabel, Statement body) { clauses.add(new Switch.CaseClause(ImmutableList.of(caseLabel), body)); return this; }
csn
func newLoadBalancerController(cfg *loadBalancerConfig, kubeClient *unversioned.Client, namespace string, tcpServices map[string]int) *loadBalancerController { lbc := loadBalancerController{ cfg: cfg, client: kubeClient, queue: workqueue.New(), reloadRateLimiter: util.NewTokenBucketRateLimiter( reloadQP...
}, } lbc.svcLister.Store, lbc.svcController = framework.NewInformer( cache.NewListWatchFromClient( lbc.client, "services", namespace, fields.Everything()), &api.Service{}, resyncPeriod, eventHandlers) lbc.epLister.Store, lbc.epController = framework.NewInformer( cache.NewListWatchFromClient( lbc.clie...
csn_ccr
def update(self, settings): """Recursively merge the given settings into the current settings.""" self.settings.cache_clear() self._settings = settings
log.info("Updated settings to %s", self._settings) self._update_disabled_plugins()
csn_ccr
// extractSwaggerOptionFromFileDescriptor extracts the message of type // swagger_options.Swagger from a given proto method's descriptor.
func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) { if file.Options == nil { return nil, nil } if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) { return nil, nil } ext, err := proto.GetExtension(file.Options, swagger_op...
csn
func TypeToMySQL(typ querypb.Type) (mysqlType, flags int64) {
val := typeToMySQL[typ] return val.typ, val.flags }
csn_ccr
Return output with specified encoding.
def wrap_output(output, encoding): """Return output with specified encoding.""" return codecs.getwriter(encoding)(output.buffer if hasattr(output, 'buffer') else output)
csn
def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until all items in the queue are processed. Returns an awaitable, which raises
`tornado.util.TimeoutError` after a timeout. """ return self._finished.wait(timeout)
csn_ccr
protected function createExtensionSelector() { $this->getAndSaveSelectedTestableKey(); /** @var \Tx_Phpunit_ViewHelpers_ExtensionSelectorViewHelper $extensionSelectorViewHelper */ $extensionSelectorViewHelper = GeneralUtility::makeInstance(\Tx_Phpunit_ViewHelpers_ExtensionSelect...
$extensionSelectorViewHelper->injectTestFinder($this->testFinder); $extensionSelectorViewHelper->setAction(BackendUtility::getModuleUrl('tools_txphpunitbeM1')); $extensionSelectorViewHelper->render(); }
csn_ccr
Trim values at input thresholds using pandas function
def clip(self, lower=None, upper=None): ''' Trim values at input thresholds using pandas function ''' df = self.export_df() df = df.clip(lower=lower, upper=upper) self.load_df(df)
csn
Returns the IDs of related objects.
public Map<String, String> getLinks() { if (links == null) { return ImmutableMap.of(); } return ImmutableMap.copyOf(links); }
csn
Returns the array of attachments set in the instance variable. @param bool $reset (optional, default is false) @since 5.5.0 @return array|null
function getBookMedia( $reset = false ) { // Cheap cache static $book_media = null; if ( $reset || $book_media === null ) { $book_media = []; $args = [ 'post_type' => 'attachment', 'posts_per_page' => -1, // @codingStandardsIgnoreLine 'post_status' => 'inherit', 'no_found_rows' => true, ...
csn
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''): ''' convertPossibleValues - Convert input value to one of several possible values, with a default for invalid entries @param val <None/str> - The input value ...
if val is None: if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Convert to a string val = tostr(val).lower() # If empty string, same as null if val == '': if emptyValue is EMPTY_IS_INVALID: return _handleIn...
csn_ccr
Add the IFRAME tag for the frame that lists all classes. @param contentTree the content tree to which the information will be added
private void addAllClassesFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.IFRAME(DocPaths.ALLCLASSES_FRAME.getPath(), "packageFrame", configuration.getText("doclet.All_classes_and_interfaces")); HtmlTree leftBottom = HtmlTree.DIV(HtmlStyle.leftBottom, frame); contentTre...
csn
def receive(self, request, wait=True, timeout=None): """ Polls the message buffer of the TCP connection and waits until a valid message is received based on the message_id passed in. :param request: The Request object to wait get the response for :param wait: Wait for the final ...
and (current_time > timeout): error_msg = "Connection timeout of %d seconds exceeded while" \ " waiting for a response from the server" \ % timeout raise smbprotocol.exceptions.SMBException(error_msg) response = request.re...
csn_ccr
Acquires the canonical File for the supplied file. @param file A non-null File for which the canonical File should be retrieved. @return The canonical File of the supplied file.
public static File getCanonicalFile(final File file) { // Check sanity Validate.notNull(file, "file"); // All done try { return file.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("Could not acquire the canonical file fo...
csn
Total power used.
def total_power(self): """Total power used. """ power = self.average_current * self.voltage return round(power, self.sr)
csn
public boolean checkAndMaybeUpdate() throws IOException { try { File nativeLibDir = soSource.soDirectory; Context updatedContext = applicationContext.createPackageContext(applicationContext.getPackageName(), 0); File updatedNativeLibDir = new File(updatedContext.getApplicationInfo().nati...
flags |= DirectorySoSource.RESOLVE_DEPENDENCIES; soSource = new DirectorySoSource(updatedNativeLibDir, flags); soSource.prepare(flags); applicationContext = updatedContext; return true; } return false; } catch (PackageManager.NameNotFoundException e) { throw new ...
csn_ccr
def members_from_rank_range(self, starting_rank, ending_rank, **options): ''' Retrieve members from the leaderboard within a given rank range. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to...
from the leaderboard that fall within the given rank range. ''' return self.members_from_rank_range_in( self.leaderboard_name, starting_rank, ending_rank, **options)
csn_ccr
def _check_and_flip(arr): """Transpose array or list of arrays if they are 2D.""" if hasattr(arr, 'ndim'): if arr.ndim >= 2: return arr.T else:
return arr elif not is_string_like(arr) and iterable(arr): return tuple(_check_and_flip(a) for a in arr) else: return arr
csn_ccr
private void addField(int fieldIndex, XmlSchemaObjectBase xsdSchemaObject, Map < String, Object > fields, RootCompositeType compositeTypes) { if (xsdSchemaObject instanceof XmlSchemaElement) { XmlSchemaElement xsdElement = (XmlSchemaElement) xsdSchemaObject;
fields.put(getFieldName(xsdElement), getProps(fieldIndex, xsdElement, compositeTypes)); } else if (xsdSchemaObject instanceof XmlSchemaChoice) { XmlSchemaChoice xsdChoice = (XmlSchemaChoice) xsdSchemaObject; fields.put(getFieldName(xsdChoice), ...
csn_ccr
public function findByHost($hostname, $onlyActive = false) { $domains = $onlyActive === true ? $this->findByActive(true)->toArray() : $this->findAll()->toArray();
return $this->domainMatchingStrategy->getSortedMatches($hostname, $domains); }
csn_ccr
func determineBlockHeights(blocksMap map[chainhash.Hash]*blockChainContext) error { queue := list.New() // The genesis block is included in blocksMap as a child of the zero hash // because that is the value of the PrevBlock field in the genesis header. preGenesisContext, exists := blocksMap[zeroHash] if !exists |...
queue.Front() { queue.Remove(e) hash := e.Value.(*chainhash.Hash) height := blocksMap[*hash].height // For each block with this one as a parent, assign it a height and // push to queue for future processing. for _, childHash := range blocksMap[*hash].children { blocksMap[*childHash].height = height + 1...
csn_ccr
Get the full url to the original video. @param MediaInterface $media @return string
public function getUrl(MediaInterface $media) { $metadata = $media->getMetaData(); return sprintf('%s?v=%s', self::WATCH_URL, $metadata['id']); }
csn
Creates a new JavaLoggerProxy and redirects the platform logger to it
private void redirectToJavaLoggerProxy() { DefaultLoggerProxy lp = DefaultLoggerProxy.class.cast(this.loggerProxy); JavaLoggerProxy jlp = new JavaLoggerProxy(lp.name, lp.level); // the order of assignments is important this.javaLoggerProxy = jlp; // isLoggable checks javaLoggerProxy if...
csn
Set the attributes of the hint of the form element object @param array $attribs @return AbstractElement
public function setHintAttributes(array $attribs) { foreach ($attribs as $a => $v) { $this->setHintAttribute($a, $v); } return $this; }
csn
// UpdateOrganization updates an organization in the organizations store
func (s *Service) UpdateOrganization(w http.ResponseWriter, r *http.Request) { var req organizationRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { invalidJSON(w, s.Logger) return } if err := req.ValidUpdate(); err != nil { invalidData(w, err, s.Logger) return } ctx := r.Context() i...
csn
def compress(data, mode=DEFAULT_MODE, quality=lib.BROTLI_DEFAULT_QUALITY, lgwin=lib.BROTLI_DEFAULT_WINDOW, lgblock=0, dictionary=b''): """ Compress a string using Brotli. .. versionchanged:: 0.5.0 Added ``mode``, ``quality``, `lgwin``,...
# This method uses private variables on the Compressor object, and # generally does a whole lot of stuff that's not supported by the public # API. The goal here is to minimise the number of allocations and copies # we have to do. Users should prefer this method over the Compressor if # they know they h...
csn_ccr
public function getValues() { $attrs = array(); foreach ($this->_attributes as $attr => $value) { $attrs[$attr]
= $this->getValue($attr); } return $attrs; }
csn_ccr
state insertion on mouse click :param widget: :param Gdk.Event event: mouse click event
def on_mouse_click(self, widget, event): """state insertion on mouse click :param widget: :param Gdk.Event event: mouse click event """ import rafcon.gui.helpers.state_machine as gui_helper_state_machine if self.view.get_path_at_pos(int(event.x), int(event.y)) is not Non...
csn
Finds an HTML element by class and the text value and clicks it. @param string $text Text value of the element @param string $selector CSS selector of the element @param string $textSelector Extra CSS selector for text of the element @param string $baseElement Element in which the sear...
public function clickElementByText($text, $selector, $textSelector = null, $baseElement = null) { $element = $this->getElementByText($text, $selector, $textSelector, $baseElement); if ($element && $element->isVisible()) { $element->click(); } elseif ($element) { throw...
csn
Builds a Datetime object given a jd and utc offset.
def fromJD(jd, utcoffset): """ Builds a Datetime object given a jd and utc offset. """ if not isinstance(utcoffset, Time): utcoffset = Time(utcoffset) localJD = jd + utcoffset.value / 24.0 date = Date(round(localJD)) time = Time((localJD + 0.5 - date.jdn) * 24) ...
csn
A package-private method that supports all kinds of profile modification, including renaming or deleting one or more profiles. @param modifications Use null key value to indicate a profile that is to be deleted.
static void modifyProfiles(File destination, Map<String, Profile> modifications) { final boolean inPlaceModify = destination.exists(); File stashLocation = null; // Stash the original file, before we apply the changes if (inPlaceModify) { boolean stashed = false; ...
csn
Backs up the specified storage account. Requests that a backup of the specified storage account be downloaded to the client. This operation requires the storage/backup permission. @param vault_base_url [String] The vault name, for example https://myvault.vault.azure.net. @param storage_account_name [String] The ...
def backup_storage_account(vault_base_url, storage_account_name, custom_headers:nil) response = backup_storage_account_async(vault_base_url, storage_account_name, custom_headers:custom_headers).value! response.body unless response.nil? end
csn
final public function animate($sel, Array $keyframes, Array $opts) { if (! array_key_exists('animate', $this->response)) { $this->response['animate'] = [];
} $this->response['animate'][$sel] = ['keyframes' => $keyframes, 'opts' => $opts]; return $this; }
csn_ccr
updatating plot object inline python juypter
def _push_render(self): """Render the plot with bokeh.io and push to notebook. """ bokeh.io.push_notebook(handle=self.handle) self.last_update = time.time()
cosqa
public function traverse() { if (self::$ignoreAjax or ! $this->validate()) { return; } $request = app('antares.request'); $module = $request->getModule(); $controller = $request->getController(); $action = $request->getAction();
$insert = [ 'type_id' => $this->getLogTypeByName($module), 'owner_type' => $request->getControllerClass(), 'priority_id' => $this->logPrioriotyId('low'), 'name' => strtoupper(implode('_', [$module, $controller, $action])), 'type' =>...
csn_ccr
Computes the union of this +Directory+ with another +Directory+. If the two directories have a file path in common, the file in the +other+ +Directory+ takes precedence. If the two directories have a sub-directory path in common, the union's sub-directory path will be the union of those two sub-directories. @rais...
def |(other) if !other.is_a?(Directory) raise ArgumentError, "#{other} is not a Directory" end dup.tap do |directory| other.files.each do |file| directory.add_file(file.dup) end other.directories.each do |new_directory| existing_directory = @direct...
csn
Custom renders the table page summary. @return string the rendering result. @throws \yii\base\InvalidConfigException
public function renderPageSummary() { $content = parent::renderPageSummary(); if ($this->showCustomPageSummary) { if (!$content) { $content = "<tfoot></tfoot>"; } if ($this->beforeSummary) { foreach ($this->beforeSummary...
csn
Sets the localized value of this cp definition specification option value in the language. @param value the localized value of this cp definition specification option value @param locale the locale of the language
@Override public void setValue(String value, java.util.Locale locale) { _cpDefinitionSpecificationOptionValue.setValue(value, locale); }
csn
Send a message through the udp socket. :type message: Message :param message: the message to send
def send_datagram(self, message): """ Send a message through the udp socket. :type message: Message :param message: the message to send """ if not self.stopped.isSet(): host, port = message.destination logger.debug("send_datagram - " + str(message...
csn
func (r *Router) Add(meth, path string, hand HandlerFunc) { route := &Route{ Path: path, Method: meth, Handler: hand, } // Rank the route route.Rank = route.rank() // Add the route to the tree
r.routes[meth] = append(r.routes[meth], route) // Sort the routes according to rank sort.Sort(ranker(r.routes[meth])) }
csn_ccr
func NewBridge(info Info) *Bridge { acc := Bridge{} acc.Accessory =
New(info, TypeBridge) return &acc }
csn_ccr
Once we have entered a turn we can keep executing propagations without waiting for another tick. Start a trampoline to process the current queue.
function enterTurn() { var snapshot; while ((snapshot = queue).length) { queue = []; trampoline(snapshot); } queue = null; }
csn
A storage which keeps configuration settings for attachments
def storage(self): """A storage which keeps configuration settings for attachments """ annotation = self.get_annotation() if annotation.get(ATTACHMENTS_STORAGE) is None: annotation[ATTACHMENTS_STORAGE] = OOBTree() return annotation[ATTACHMENTS_STORAGE]
csn
Returns all the widgets.
public static function get() { $widgets = []; foreach (Packages::all() as $package) { $dir = __DIR__.'/../../'.$package.'/src'; $files = is_dir($dir) ? scandir($dir) : []; foreach ($files as $file) { if ($file == 'Widgets.json') { ...
csn
Return whether or not the provided subject ends with suffix. @param string $subject @param string $suffix @param null|string $encoding @return bool @throws InvalidArgumentException
public static function endsWith($subject, $suffix, $encoding = null) { return Rope::of($subject, $encoding)->endsWith($suffix); }
csn