query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
def tags_newer(self, versions_file, majors): """ Checks this git repo tags for newer versions. @param versions_file: a common.VersionsFile instance to check against. @param majors: a list of major branches to check. E.g. ['6', '7'] @raise RuntimeError: no newer tags were
found. @raise MissingMajorException: A new version from a newer major branch is exists, but hasn't been downloaded due to it not being in majors. """ highest = versions_file.highest_version_major(majors) all = self.tags_get() newer = _newer_tags_get(highest, all) if len(newer) == 0: raise RuntimeError("No new tags found.") return newer
csn_ccr
public void calcOffset(Container compAnchor, Point offset) { offset.x = 0; offset.y = 0; Container parent = this; while (parent != null) { offset.x -= parent.getLocation().x; offset.y -= parent.getLocation().y; parent = parent.getParent();
if (parent == compAnchor) return; // Success } // Failure - comp not found. offset.x = 0; offset.y = 0; }
csn_ccr
def add_geometry(self, geometry, node_name=None, geom_name=None, parent_node_name=None, transform=None): """ Add a geometry to the scene. If the mesh has multiple transforms defined in its metadata, they will all be copied into the TransformForest of the current scene automatically. Parameters ---------- geometry : Trimesh, Path2D, Path3D PointCloud or list Geometry to initially add to the scene base_frame : str or hashable Name of base frame metadata : dict Any metadata about the scene graph : TransformForest or None A passed transform graph to use Returns ---------- node_name : str Name of node in self.graph """ if geometry is None: return # PointCloud objects will look like a sequence elif util.is_sequence(geometry): # if passed a sequence add all elements for value in geometry: self.add_geometry( geometry=value, node_name=node_name, geom_name=geom_name, parent_node_name=parent_node_name, transform=transform, ) return elif isinstance(geometry, dict): # if someone passed us a dict of geometry for key, value in geometry.items(): self.add_geometry(value, geom_name=key) return # get or create a name to reference the geometry by if geom_name is not None: # if name is passed use it name = geom_name elif 'name' in geometry.metadata: # if name is in metadata use it
name = geometry.metadata['name'] elif 'file_name' in geometry.metadata: name = geometry.metadata['file_name'] else: # try to create a simple name name = 'geometry_' + str(len(self.geometry)) # if its already taken add a unique random string to it if name in self.geometry: name += ':' + util.unique_id().upper() # save the geometry reference self.geometry[name] = geometry # create a unique node name if not passed if node_name is None: # a random unique identifier unique = util.unique_id(increment=len(self.geometry)) # geometry name + UUID node_name = name + '_' + unique.upper() if transform is None: # create an identity transform from parent_node transform = np.eye(4) self.graph.update(frame_to=node_name, frame_from=parent_node_name, matrix=transform, geometry=name, geometry_flags={'visible': True}) return node_name
csn_ccr
Construct the context class loader by adding all jars.
private void createClassLoader() { if (!Utils.isNullOrEmpty(settings.getJarFiles())) { try { String[] files = settings.getJarFiles().split(";"); List<URL> urls = newArrayList(); for (String path : files) { File file = new File(path); if (file.isFile()) { urls.add(file.toURI().toURL()); } } classLoader = new Java4CppClassLoader(urls.toArray(new URL[files.length]), classLoader); } catch (Exception e) { throw new RuntimeException("Failed to load jar " + e.getMessage()); } } }
csn
Add standard attributes and price data to the collection. @param ProductCollection $collection Product collection. @return ProductCollection
public function prepareCollection(ProductCollection $collection) { $collection->addAttributeToSelect($this->attributes); $collection->addPriceData(); return $collection; }
csn
public function setIpAllocationPolicy($var) { GPBUtil::checkMessage($var, \Google\Cloud\Container\V1\IPAllocationPolicy::class);
$this->ip_allocation_policy = $var; return $this; }
csn_ccr
// PrepareForCreate clears the status of a replication controller before creation.
func (rcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { controller := obj.(*api.ReplicationController) controller.Status = api.ReplicationControllerStatus{} controller.Generation = 1 pod.DropDisabledTemplateFields(controller.Spec.Template, nil) }
csn
protected function initOptions() { $this->containerOptions = array_merge([ 'id' => $this->getId()
],$this->containerOptions); Html::addCssClass($this->containerOptions, 'owl-carousel'); }
csn_ccr
Sets the values to be inserted. If no params are passed, then it returns the currently stored values @deprecated 3.4.0 Use setValues()/getValues() instead. @param array|null $values Array with values to be inserted. @return array|$this
public function values($values = null) { deprecationWarning( 'ValuesExpression::values() is deprecated. ' . 'Use ValuesExpression::setValues()/getValues() instead.' ); if ($values !== null) { return $this->setValues($values); } return $this->getValues(); }
csn
public EJBObject[] loadEntireCollection() { EJBObject[] result = null; try { result = (EJBObject[]) allRemainingElements(); } catch (NoMoreElementsException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", // "270", this); return elements; } catch (EnumeratorException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", //
"276", this); throw new RuntimeException(e.toString()); } catch (RemoteException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", // "282", this); throw new RuntimeException(e.toString()); } elements = result; return result; }
csn_ccr
// MySavedComments fetches comments saved by current user using OAuth.
func (o *OAuthSession) MySavedComments(params ListingOptions) ([]*Comment, error) { me, err := o.Me() if err != nil { return nil, err } return o.SavedComments(me.Name, params) }
csn
func NewExecutionRulesAccepter(rules []imagepolicy.ImageExecutionPolicyRule, integratedRegistryMatcher RegistryMatcher) (Accepter, error) { mapped := make(mappedAccepter) for _, rule := range rules { over, selectors, err := imageConditionInfo(&rule.ImageCondition) if err != nil { return nil, err } rule.ImageCondition.MatchImageLabelSelectors = selectors for gr := range over { a, ok := mapped[gr] if !ok { a = &executionAccepter{ covers: gr, integratedRegistryMatcher: integratedRegistryMatcher, } mapped[gr] = a } byResource := a.(*executionAccepter) byResource.rules = append(byResource.rules,
rule) } } for _, a := range mapped { byResource := a.(*executionAccepter) if len(byResource.rules) > 0 { // if all rules are reject, the default behavior is allow allReject := true for _, rule := range byResource.rules { if !rule.Reject { allReject = false break } } byResource.defaultReject = !allReject } } return mapped, nil }
csn_ccr
// WriteThroughput returns the write throughput
func (v *Stats) WriteThroughput() uint64 { intv := toSec(v.IntervalMs) if intv == 0 { return 0 } return (v.WriteBytes) / intv }
csn
func linkDir(src, dst string) error { if err := os.MkdirAll(dst, 0777); err != nil { return err
} return syscall.Mount(src, dst, "", syscall.MS_BIND, "") }
csn_ccr
public Node replaceNode(Node n) { if (parent() == null) { throw new UnsupportedOperationException("Replacing the root node is not supported"); } List tail = getTail(); parent().appendNode(n.name(), n.attributes(), n.value());
parent().children().addAll(tail); getParentList(parent()).remove(this); this.setParent(null); return this; }
csn_ccr
Generates conditions for where clause. @return mixed[]
private function getWhereClause(): array { $result = array_merge($this->getOwnerFields(), $this->getBelongTo(), $this->getPermissions()); $result = array_merge($result, $this->getParentPermissions(), $this->getParentJoinsWhereClause()); $result = array_merge_recursive($result, $this->getSupervisorWhereClause()); return $result; }
csn
Returns the calculated average of the current data @return the calculated average of the current data
public double getAverage() { if (!DATA_LIST.isEmpty()) { double sum = 0; for (DataPoint dataPoint : DATA_LIST) { sum += dataPoint.getValue(); } return sum / DATA_LIST.size(); } return 0; }
csn
Apply the transposition to the target iterable. Parameters ---------- target - iterable The iterable to transpose. This would be suitable for things such as a shape as well as a list of ``__getitem__`` keys. inverse - bool Whether to map old dimension to new dimension (forward), or new dimension to old dimension (inverse). Default is False (forward). Returns ------- A tuple derived from target which has been ordered based on the new axes.
def _apply_axes_mapping(self, target, inverse=False): """ Apply the transposition to the target iterable. Parameters ---------- target - iterable The iterable to transpose. This would be suitable for things such as a shape as well as a list of ``__getitem__`` keys. inverse - bool Whether to map old dimension to new dimension (forward), or new dimension to old dimension (inverse). Default is False (forward). Returns ------- A tuple derived from target which has been ordered based on the new axes. """ if len(target) != self.ndim: raise ValueError('The target iterable is of length {}, but ' 'should be of length {}.'.format(len(target), self.ndim)) if inverse: axis_map = self._inverse_axes_map else: axis_map = self._forward_axes_map result = [None] * self.ndim for axis, item in enumerate(target): result[axis_map[axis]] = item return tuple(result)
csn
def recursive_delete(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.get_children(path: path) raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK
threads = result.fetch(:children).map do |name| Thread.new do Thread.abort_on_exception = true recursive_delete(path: File.join(path, name)) end end threads.each(&:join) result = zk.delete(path: path) raise Kazoo::Error, "Failed to delete node #{path}. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK end
csn_ccr
The code provided is supposed replace all the dots `.` in the specified String `str` with dashes `-` But it's not working properly. # Task Fix the bug so we can all go home early. # Notes String `str` will never be null.
def replace_dots(string): return string.replace('.', '-')
apps
Deletes message. @param int $id @return PodiumResponse @throws NoMembershipException @throws ModelNotFoundException
public function removeMessage(int $id): PodiumResponse { return $this->getPodium()->message->remove($id, $this->ensureMembership()); }
csn
public function getMagentoCreditCartType($ccType) { $ccTypesMapper = Mage::helper('adyen')->getCcTypesAltData(); if (isset($ccTypesMapper[$ccType])) {
$ccType = $ccTypesMapper[$ccType]['code']; } return $ccType; }
csn_ccr
Returns a formatter object that can be reused for similar formatting task under the same locale and options. This is often a speedier alternative to using other methods in this class as only one formatter object needs to be constructed. ### Options - `locale` - The locale name to use for formatting the number, e.g. fr_FR - `type` - The formatter type to construct, set it to `currency` if you need to format numbers representing money or a NumberFormatter constant. - `places` - Number of decimal places to use. e.g. 2 - `precision` - Maximum Number of decimal places to use, e.g. 2 - `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00 - `useIntlCode` - Whether or not to replace the currency symbol with the international currency code. @param array $options An array with options. @return \NumberFormatter The configured formatter instance
public static function formatter($options = []) { $locale = isset($options['locale']) ? $options['locale'] : ini_get('intl.default_locale'); if (!$locale) { $locale = static::DEFAULT_LOCALE; } $type = NumberFormatter::DECIMAL; if (!empty($options['type'])) { $type = $options['type']; if ($options['type'] === static::FORMAT_CURRENCY) { $type = NumberFormatter::CURRENCY; } } if (!isset(static::$_formatters[$locale][$type])) { static::$_formatters[$locale][$type] = new NumberFormatter($locale, $type); } $formatter = static::$_formatters[$locale][$type]; $options = array_intersect_key($options, [ 'places' => null, 'precision' => null, 'pattern' => null, 'useIntlCode' => null ]); if (empty($options)) { return $formatter; } $formatter = clone $formatter; return static::_setAttributes($formatter, $options); }
csn
how to add tensorflow to pythonpath after downloading directory
def tfds_dir(): """Path to tensorflow_datasets directory.""" return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
cosqa
def execute(self, limitRequest=350000, limitResMax=-1): """Executes the query.""" query = self.getQueries() query = self.__buildLimit(query, limitResMax) nbr_results = limitResMax if (limitResMax == -1): query.setBaseUrl(self.__url+'/count') countUrl = query.getUrl() result_count = Util.retrieveJsonResponseFromServer(countUrl) nbr_results=result_count['total'] else: nbr_results = limitResMax resultSearch = [] if nbr_results < limitRequest :
query.setBaseUrl(self.__url+'/records') url = query.getUrl() startVal = query._getParameters()['start'] while (nbr_results-startVal)>0 :#Do the job per 300 items till nbr_result is reached resultTemp = Util.retrieveJsonResponseFromServer(url) resultSearch.extend(self.__parseResponse(resultTemp)) parameters = query._getParameters() startVal = parameters['start'] + parameters['limit'] query = UpdateParameter(query, 'start', startVal) query.setBaseUrl(self.__url+'/records') url=query.getUrl() else: out_mess="Not allowed\nNbr results (%d) exceeds limit_request param: %d\n" % (nbr_results, limitRequest) self.__logger.info(out_mess) return resultSearch
csn_ccr
Use this API to fetch auditsyslogpolicy_csvserver_binding resources of given name .
public static auditsyslogpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{ auditsyslogpolicy_csvserver_binding obj = new auditsyslogpolicy_csvserver_binding(); obj.set_name(name); auditsyslogpolicy_csvserver_binding response[] = (auditsyslogpolicy_csvserver_binding[]) obj.get_resources(service); return response; }
csn
Gets image file format. @param imageFile input image file @return image file format
public static String getImageFileFormat(File imageFile) { String imageFileName = imageFile.getName(); String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1); if (imageFormat.matches("(pbm|pgm|ppm)")) { imageFormat = "pnm"; } else if (imageFormat.matches("(jp2|j2k|jpf|jpx|jpm)")) { imageFormat = "jpeg2000"; } return imageFormat; }
csn
Output the aggregate block count results.
def finalize(self): """Output the aggregate block count results.""" for name, count in sorted(self.blocks.items(), key=lambda x: x[1]): print('{:3} {}'.format(count, name)) print('{:3} total'.format(sum(self.blocks.values())))
csn
Try to guess the encoding of a request without going through the slow chardet process
def guess_encoding(request): """ Try to guess the encoding of a request without going through the slow chardet process""" ctype = request.headers.get('content-type') if not ctype: # we don't have a content-type, somehow, so... LOGGER.warning("%s: no content-type; headers are %s", request.url, request.headers) return 'utf-8' # explicit declaration match = re.search(r'charset=([^ ;]*)(;| |$)', ctype) if match: return match[1] # html default if ctype.startswith('text/html'): return 'iso-8859-1' # everything else's default return 'utf-8'
csn
Get standard belongsToMany reference key name for 'from' and 'to' models Reversed gives the 'to' key @param string $relation @param bool $reversed (default: false) @return string
public function getCmsReferenceKeyForRelation($relation, $reversed = false) { $isParent = ( array_key_exists($relation, $this->relationsConfig) && array_key_exists('parent', $this->relationsConfig[$relation]) && (bool) $this->relationsConfig[$relation]['parent'] ); if ($reversed) { $isParent = ! $isParent; } return $isParent ? config('pxlcms.relations.references.keys.to', 'to_entry_id') : config('pxlcms.relations.references.keys.from', 'from_entry_id'); }
csn
Update year in jalali date @param int $year
private function setYear($year) { //preventing duplication process if ($year == $this->year) { return; } $this->year = (int) $year; $maximumDayAvailable = static::getMonthLength($this->year, $this->month); if ($this->day > $maximumDayAvailable) { $this->day = $maximumDayAvailable; } }
csn
// CLEmail implements Client interface.
func (p *implementation) CLEmail(c context.Context, host string, changeNumber int64) (email string, err error) { defer func() { err = common.TagGRPC(c, err) }() changeInfo, err := p.clEmailAndProjectNoACLs(c, host, changeNumber) if err != nil { return } allowed, err := p.acls.IsAllowed(c, host, changeInfo.Project) switch { case err != nil: return case allowed: email = changeInfo.GetOwner().GetEmail() default: err = errGRPCNotFound } return }
csn
// Get returns wrapped username and LDAP groups and possibly updates the cache
func (lud *LdapUserData) Get() *querypb.VTGateCallerID { if int64(time.Since(lud.lastUpdated).Seconds()) > lud.asl.RefreshSeconds { go lud.update() } return &querypb.VTGateCallerID{Username: lud.username, Groups: lud.groups} }
csn
public function getDefaultDomain() { if ($this->defaultDomain) { return $this->defaultDomain; } elseif ($first = $this->getDomains()->first()) {
return $first->getDomain(); } else { return null; } }
csn_ccr
Calls a callback with optional args and keyword args lists. This method exists so we can inspect the `_max_calls` attribute that's set by `_on`. If this value is None, the callback is considered to have no limit. Otherwise, an integer value is expected and decremented until there are no remaining calls
def _call(callback, args=[], kwargs={}): """ Calls a callback with optional args and keyword args lists. This method exists so we can inspect the `_max_calls` attribute that's set by `_on`. If this value is None, the callback is considered to have no limit. Otherwise, an integer value is expected and decremented until there are no remaining calls """ if not hasattr(callback, '_max_calls'): callback._max_calls = None # None implies no callback limit if callback._max_calls is None: return _call_partial(callback, *args, **kwargs) # Should the signal be disconnected? if callback._max_calls <= 0: return disconnect(callback) callback._max_calls -= 1 return _call_partial(callback, *args, **kwargs)
csn
// RemoteAddr returns the remote network address.
func (c *Conn) RemoteAddr() net.Addr { if !c.ok() { return nil } return c.raddr }
csn
private function getRelationships(Item $item) { if ($include_params = $this->resource->getIncludeParams()) {
$item->setIncludeParams($include_params); return $item->getIncluded(); } return []; }
csn_ccr
public InetAddress [] lookupAllHostAddr(String host) throws UnknownHostException { Name name = null; try { name = new Name(host); } catch (TextParseException e) { throw new UnknownHostException(host); } Record [] records = null; if (preferV6) records = new Lookup(name, Type.AAAA).run(); if (records == null) records = new Lookup(name, Type.A).run(); if (records == null && !preferV6) records = new Lookup(name, Type.AAAA).run(); if (records == null) throw new UnknownHostException(host); InetAddress[] array = new InetAddress[records.length]; for (int i
= 0; i < records.length; i++) { Record record = records[i]; if (records[i] instanceof ARecord) { ARecord a = (ARecord) records[i]; array[i] = a.getAddress(); } else { AAAARecord aaaa = (AAAARecord) records[i]; array[i] = aaaa.getAddress(); } } return array; }
csn_ccr
Returns a unicode string for string. :param string: The input string. :type string: `basestring` :returns: A unicode string. :rtype: `unicode`
def _ensure_unicode_string(string): """Returns a unicode string for string. :param string: The input string. :type string: `basestring` :returns: A unicode string. :rtype: `unicode` """ if not isinstance(string, six.text_type): string = string.decode('utf-8') return string
csn
func (r Hardware_SecurityModule750) GetScaleAssets() (resp []datatypes.Scale_Asset, err error) { err
= r.Session.DoRequest("SoftLayer_Hardware_SecurityModule750", "getScaleAssets", nil, &r.Options, &resp) return }
csn_ccr
python 3 send text message
async def _send_plain_text(self, request: Request, stack: Stack): """ Sends plain text using `_send_text()`. """ await self._send_text(request, stack, None)
cosqa
public function removeDir($path) { if ($path == 'packages' or $path == '/') { return false; } $files = array_diff(scandir($path), ['.', '..']); foreach ($files as $file) { if (is_dir("$path/$file")) {
$this->removeDir("$path/$file"); } else { @chmod("$path/$file", 0777); @unlink("$path/$file"); } } return rmdir($path); }
csn_ccr
func (i *info) Client() hrpc.RegionClient { i.m.RLock()
c := i.client i.m.RUnlock() return c }
csn_ccr
public OkVolley init(Context context) { this.mContext = context; InstanceRequestQueue = newRequestQueue(context); mUserAgent = generateUserAgent(context); mRequestHeaders = new HashMap<>();
mRequestHeaders.put(OkRequest.HEADER_USER_AGENT, mUserAgent); mRequestHeaders.put(OkRequest.HEADER_ACCEPT_CHARSET, OkRequest.CHARSET_UTF8); return this; }
csn_ccr
Copies vat info from the parent to all children. In Magento, VAT info on the children may contain a 0 vat rate. To correct this, we copy the vat information (rate, source, correction info). @param array $parent The parent invoice line. @param array[] $children The child invoice lines. @return array[] The child invoice lines with vat info copied form the parent.
protected function copyVatInfoToChildren(array $parent, array $children) { static $vatMetaInfoTags = array( Meta::VatRateMin, Meta::VatRateMax, Meta::VatRateLookup, Meta::VatRateLookupLabel, Meta::VatRateLookupSource, Meta::VatRateLookupMatches, Meta::VatClassId, Meta::VatClassName, ); foreach ($children as &$child) { if (isset($parent[Tag::VatRate])) { $child[Tag::VatRate] = $parent[Tag::VatRate]; } $child[Meta::VatAmount] = 0; foreach ($vatMetaInfoTags as $tag) { unset($child[$tag]); } if (Completor::isCorrectVatRate($parent[Meta::VatRateSource])) { $child[Meta::VatRateSource] = Completor::VatRateSource_Copied_From_Parent; } else { // The parent does not yet have correct vat rate info, so also // copy the meta data to the child, so later phases can also // correct the children. $child[Meta::VatRateSource] = $parent[Meta::VatRateSource]; foreach ($vatMetaInfoTags as $tag) { if (isset($parent[$tag])) { $child[$tag] = $parent[$tag]; } } } $child[Meta::LineVatAmount] = 0; unset($child[Meta::LineDiscountVatAmount]); } return $children; }
csn
protected function blockTable($line, array $block = null) { if (! isset($block) or isset($block[ 'type' ]) or isset($block[ 'interrupted' ])) { return; } if (strpos($block[ 'element' ][ 'text' ], '|') !== false and chop($line[ 'text' ], ' -:|') === '') { $alignments = array(); $divider = $line[ 'text' ]; $divider = trim($divider); $divider = trim($divider, '|'); $dividerCells = explode('|', $divider); foreach ($dividerCells as $dividerCell) { $dividerCell = trim($dividerCell); if ($dividerCell === '') { continue; } $alignment = null; if ($dividerCell[ 0 ] === ':') { $alignment = 'left'; } if (substr($dividerCell, -1) === ':') { $alignment = $alignment === 'left' ? 'center' : 'right'; } $alignments[] = $alignment; } $headerElements = array(); $header = $block[ 'element' ][ 'text' ]; $header = trim($header); $header = trim($header, '|'); $headerCells = explode('|', $header); foreach ($headerCells as $index => $headerCell) { $headerCell = trim($headerCell); $headerElement = [ 'name' => 'th', 'text' => $headerCell, 'handler' => 'line', ]; if (isset($alignments[ $index ])) { $alignment = $alignments[ $index ]; $headerElement[ 'attributes' ] = [
'style' => 'text-align: ' . $alignment . ';', ]; } $headerElements[] = $headerElement; } $block = [ 'alignments' => $alignments, 'identified' => true, 'element' => [ 'name' => 'table', 'handler' => 'elements', 'attributes' => [ 'class' => 'table table-striped table-bordered' ], ], ]; $block[ 'element' ][ 'text' ][] = [ 'name' => 'thead', 'handler' => 'elements', ]; $block[ 'element' ][ 'text' ][] = [ 'name' => 'tbody', 'handler' => 'elements', 'text' => array(), ]; $block[ 'element' ][ 'text' ][ 0 ][ 'text' ][] = [ 'name' => 'tr', 'handler' => 'elements', 'text' => $headerElements, ]; return $block; } }
csn_ccr
send http request with authorization python
def auth_request(self, url, headers, body): """Perform auth request for token.""" return self.req.post(url, headers, body=body)
cosqa
Deletes an item from the static acceleration array. @param string|int $key As given to get|set|delete @return bool True on success, false otherwise.
protected function static_acceleration_delete($key) { unset($this->staticaccelerationarray[$key]); if ($this->staticaccelerationsize !== false && isset($this->staticaccelerationkeys[$key])) { unset($this->staticaccelerationkeys[$key]); $this->staticaccelerationcount--; } return true; }
csn
Generates the tags for the HTML head. @param array $files List of file URLs that should be HTML tags generated for @param string $filetype Typ of the given files, e.g. 'js' or 'css' @return string Generated string for inclusion into the HTML head @throws MW_Jsb2_Exception If the file type is unknown
protected function _createHtml( array $files, $filetype ) { $html = ''; foreach( $files as $file ) { switch( $filetype ) { case 'js': $html .= '<script type="text/javascript" src="' . $file . '"></script>' . PHP_EOL; break; case 'css': $html .= '<link rel="stylesheet" type="text/css" href="' . $file . '"/>' . PHP_EOL; break; default: throw new MW_Jsb2_Exception( sprintf( 'Unknown file extension: "%1$s"', $filetype ) ); } } return $html; }
csn
Get an array with the specified length from the pool. @param {number} length The preferred length of the array. @return {Array} An array.
function getWithLength(length) { var arrays = pool[length]; var array; var i; // Create the first array for the specified length if (!arrays) { array = create(length); } // Find an unused array among the created arrays for the specified length if (!array) { for (i = arrays.length; i--;) { if (!arrays[i].inUse) { array = arrays[i]; break; } } // If no array was found, create a new one if (!array) { array = create(length); } } array.inUse = true; return array; }
csn
@SuppressWarnings("OptionalGetWithoutIsPresent") public Token<DelegationTokenIdentifier> getBoundOrNewDT(String renewer) throws IOException { logger.atFine().log("Delegation token requested"); if (isBoundToDT()) { // the FS was created on startup with a token, so return it. logger.atFine().log("Returning current token"); return getBoundDT(); }
// not bound to a token, so create a new one. // issued DTs are not cached so that long-lived filesystems can // reliably issue session/role tokens. return tokenBinding.createDelegationToken(renewer); }
csn_ccr
public List<Node> copyDirectory(Node destdir, Filter filter) throws DirectoryNotFoundException, CopyException {
return new Copy(this, filter).directory(destdir); }
csn_ccr
// lambdaWalker returns a walkfunc that applies lambda to every file with extension ext. Ignores all other file types. // Lambda should take the file path as its parameter.
func lambdaWalker(lambda func(string) error, ext string) filepath.WalkFunc { walk := func(path string, f os.FileInfo, err error) error { // if error occurs during traversal to path, exit and crash if err != nil { return err } // skip anything that is a directory if f.IsDir() { return nil } if filepath.Ext(path) == ext { return lambda(path) } // ignore anything else return nil } return walk }
csn
// reloadConfig and reinitialise phosphor client if necessary // // Get Config // Test hash of config to determine if changed // If so, update config & reinit
func (p *Phosphor) reloadConfig() error { c := p.configProvider.Config() // Skip reloading if the config is the same h := fmt.Sprintf("%x", deephash.Hash(c)) if p.compareConfigHash(h) { return nil } // keep reference to the old channel so we can drain this in parallel with // new traces the transport receives oldChan := p.traceChan // init new channel for traces, ensure this *isn't* zero bufLen := c.BufferSize if bufLen == 0 { bufLen = defaultTraceBufferSize } newChan := make(chan []byte, bufLen) // Get a new transport and keep a reference to the old one p.trMtx.Lock() defer p.trMtx.Unlock() oldTr := p.tr endpoint := fmt.Sprintf("%s:%v", c.Host, c.Port) newTr := newUDPTransport(endpoint) // start new transport by passing both channels to this // therefore it starts consuming from the new one (with nothing) // and also the old one (still current) in parallel to the previous transport // If this somehow fails, abort until next attempt if err := newTr.Consume(oldChan, newChan); err != nil { newTr.Stop() return err } // swap the client reference of the trace channel from old to new, so // new clients start using the new resized channel // TODO atomically swap this p.traceChan = newChan // gracefully shut down old transport, so just the new one is running if oldTr != nil { if err := oldTr.Stop(); err != nil { return err } } // set the config hash & swap the transport as we're finished p.updateConfigHash(h) p.tr = newTr return nil }
csn
Copy a file from source to destination, may be done recursively and may ignore system files @access public @author Lionel Lecaque, <lionel@taotesting.com> @param string source @param string destination @param boolean recursive @param boolean ignoreSystemFiles @return boolean
static public function copy($source, $destination, $recursive = true, $ignoreSystemFiles = true) { if(!is_readable($source)){ return false; } $returnValue = (bool) false; // Check for System File $basename = basename($source); if ($basename[0] === '.' && $ignoreSystemFiles === true) { return false; } // Check for symlinks if (is_link($source)) { return symlink(readlink($source), $destination); } // Simple copy for a file if (is_file($source)) { // get path info of destination. $destInfo = pathinfo($destination); if (isset($destInfo['dirname']) && ! is_dir($destInfo['dirname'])) { if (! mkdir($destInfo['dirname'], 0777, true)) { return false; } } return copy($source, $destination); } // Make destination directory if ($recursive == true) { if (! is_dir($destination)) { // 0777 is default. See mkdir PHP Official documentation. mkdir($destination, 0777, true); } // Loop through the folder $dir = dir($source); while (false !== $entry = $dir->read()) { // Skip pointers if ($entry === '.' || $entry === '..') { continue; } // Deep copy directories self::copy("${source}/${entry}", "${destination}/${entry}", $recursive, $ignoreSystemFiles); } // Clean up $dir->close(); return true; } else { return false; } return (bool) $returnValue; }
csn
logging python close log file
def close_log(log, verbose=True): """Close log This method closes and active logging.Logger instance. Parameters ---------- log : logging.Logger Logging instance """ if verbose: print('Closing log file:', log.name) # Send closing message. log.info('The log file has been closed.') # Remove all handlers from log. [log.removeHandler(handler) for handler in log.handlers]
cosqa
Generate a controller with the given name for the given package @param string $packageKey The package key of the controller's package @param string $subpackage An optional subpackage name @param string $controllerName The name of the new controller @param boolean $overwrite Overwrite any existing files? @return array An array of generated filenames
public function generateActionController($packageKey, $subpackage, $controllerName, $overwrite = false) { list($baseNamespace, $namespaceEntryPath) = $this->getPrimaryNamespaceAndEntryPath($this->packageManager->getPackage($packageKey)); $controllerName = ucfirst($controllerName); $controllerClassName = $controllerName . 'Controller'; $templatePathAndFilename = 'resource://Neos.Kickstarter/Private/Generator/Controller/ActionControllerTemplate.php.tmpl'; $contextVariables = []; $contextVariables['packageKey'] = $packageKey; $contextVariables['packageNamespace'] = trim($baseNamespace, '\\'); $contextVariables['subpackage'] = $subpackage; $contextVariables['isInSubpackage'] = ($subpackage != ''); $contextVariables['controllerClassName'] = $controllerClassName; $contextVariables['controllerName'] = $controllerName; $fileContent = $this->renderTemplate($templatePathAndFilename, $contextVariables); $subpackagePath = $subpackage != '' ? $subpackage . '/' : ''; $controllerFilename = $controllerClassName . '.php'; $controllerPath = Files::concatenatePaths([$namespaceEntryPath, $subpackagePath, 'Controller']) . '/'; $targetPathAndFilename = $controllerPath . $controllerFilename; $this->generateFile($targetPathAndFilename, $fileContent, $overwrite); return $this->generatedFiles; }
csn
Publish metrics for a subcontainer and handle filtering on tags
def _update_container_metrics(self, instance, subcontainer, kube_labels): """Publish metrics for a subcontainer and handle filtering on tags""" tags = list(instance.get('tags', [])) # add support for custom tags if len(subcontainer.get('aliases', [])) >= 1: # The first alias seems to always match the docker container name container_name = subcontainer['aliases'][0] else: self.log.debug("Subcontainer doesn't have a name, skipping.") return tags.append('container_name:%s' % container_name) container_image = self.kubeutil.image_name_resolver(subcontainer['spec'].get('image')) if container_image: tags.append('container_image:%s' % container_image) split = container_image.split(":") if len(split) > 2: # if the repo is in the image name and has the form 'docker.clearbit:5000' # the split will be like [repo_url, repo_port/image_name, image_tag]. Let's avoid that split = [':'.join(split[:-1]), split[-1]] tags.append('image_name:%s' % split[0]) if len(split) == 2: tags.append('image_tag:%s' % split[1]) try: cont_labels = subcontainer['spec']['labels'] except KeyError: self.log.debug("Subcontainer, doesn't have any labels") cont_labels = {} # Collect pod names, namespaces, rc... if KubeUtil.NAMESPACE_LABEL in cont_labels and KubeUtil.POD_NAME_LABEL in cont_labels: # Kubernetes >= 1.2 tags += self._get_post_1_2_tags(cont_labels, subcontainer, kube_labels) elif KubeUtil.POD_NAME_LABEL in cont_labels: # Kubernetes <= 1.1 tags += self._get_pre_1_2_tags(cont_labels, subcontainer, kube_labels) else: # Those are containers that are not part of a pod. # They are top aggregate views and don't have the previous metadata. tags.append("pod_name:no_pod") # if the container should be filtered we return its tags without publishing its metrics is_filtered = self.kubeutil.are_tags_filtered(tags) if is_filtered: self._filtered_containers.add(subcontainer['id']) return tags stats = subcontainer['stats'][-1] # take the latest self._publish_raw_metrics(NAMESPACE, stats, tags) if subcontainer.get("spec", {}).get("has_filesystem") and stats.get('filesystem', []) != []: fs = stats['filesystem'][-1] if fs['capacity'] > 0: fs_utilization = float(fs['usage'])/float(fs['capacity']) self.publish_gauge(self, NAMESPACE + '.filesystem.usage_pct', fs_utilization, tags) else: self.log.debug("Filesystem capacity is 0: cannot report usage metrics.") if subcontainer.get("spec", {}).get("has_network"): net = stats['network'] self.publish_rate(self, NAMESPACE + '.network_errors', sum(float(net[x]) for x in NET_ERRORS), tags) return tags
csn
func (o *Buffer) enc_ref_bool(p *Properties, base structPointer) error { v := structPointer_RefBool(base, p.field) if v == nil { return ErrNil } x := 0
if *v { x = 1 } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil }
csn_ccr
python3 parse a substring to datetime in a string
def parse_date(s): """Fast %Y-%m-%d parsing.""" try: return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10])) except ValueError: # other accepted format used in one-day data set return datetime.datetime.strptime(s, '%d %B %Y').date()
cosqa
Creates a new image of the same type and number of bands @param imgWidth image width @param imgHeight image height @return new image
@Override public Planar<T> createNew(int imgWidth, int imgHeight) { return new Planar<>(type, imgWidth, imgHeight, bands.length); }
csn
def should_build(self, fpath, meta): """ Checks if the file should be built or not Only skips layouts which are tagged as INCREMENTAL Rebuilds only those files with mtime changed since previous build """ if meta.get('layout', self.default_template) in self.inc_layout:
if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath): return False else: return True return True
csn_ccr
def ip_to_url(ip_addr): """ Resolve a hostname based off an IP address. This is very limited and will probably not return any results if it is a shared IP address or an address with improperly setup DNS records. .. code:: python reusables.ip_to_url('93.184.216.34') # example.com # None reusables.ip_to_url('8.8.8.8') # 'google-public-dns-a.google.com'
:param ip_addr: IP address to resolve to hostname :return: string of hostname or None """ try: return socket.gethostbyaddr(ip_addr)[0] except (socket.gaierror, socket.herror): logger.exception("Could not resolve hostname")
csn_ccr
private FeatureIndex[] createFeatureIndex(int subspaceCount) // throws // Exception {
logger.info("create feature index"); FeatureIndex[] index = new FeatureIndex[subspaceCount]; for (int i = 0; i < subspaceCount; i++) index[i] = new FeatureIndex(false, 1); return index; }
csn_ccr
Checks if the hub has now activity turned on. This is implemented by checking the hubs current activity. If the activities id is equal to -1, no activity is on currently. @returns {Q.Promise}
function isOff () { debug('check if turned off') return this.getCurrentActivity() .then(function (activityId) { var off = (activityId === '-1') debug(off ? 'system is currently off' : 'system is currently on with activity ' + activityId) return off }) }
csn
def hdf5(self): """Path of output hdf5 folder if relevant, None otherwise.""" if self._rundir['hdf5'] is UNDETERMINED: h5_folder = self.path / self.par['ioin']['hdf5_output_folder']
if (h5_folder / 'Data.xmf').is_file(): self._rundir['hdf5'] = h5_folder else: self._rundir['hdf5'] = None return self._rundir['hdf5']
csn_ccr
Copies the input stream to the output stream using a 4K buffer @param inputStream the stream to copy @param outputStream the stream to write to @throws IOException if there is an exception reading or writing
private void copy(final InputStream inputStream, final FileOutputStream outputStream) throws IOException { final byte[] buffer = new byte[1024*4]; int n; try { while (-1 != (n = inputStream.read(buffer))) { outputStream.write(buffer, 0, n); } } finally { inputStream.close(); outputStream.close(); } }
csn
public static String[] getColumnFamilyList(String path) throws RocksDBException { List<byte[]> cfList = RocksDB.listColumnFamilies(new Options(), path); if (cfList == null || cfList.size() == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List<String> result
= new ArrayList<>(cfList.size()); for (byte[] cf : cfList) { result.add(new String(cf, StandardCharsets.UTF_8)); } return result.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
csn_ccr
r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters.
def purge(root=os.path.join(base.data_dir(), 'models')): r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. """ root = os.path.expanduser(root) files = os.listdir(root) for f in files: if f.endswith(".params"): os.remove(os.path.join(root, f))
csn
Returns the String identifying the given cudaLimit @param n The cudaLimit @return The String identifying the given cudaLimit
public static String stringFor(int n) { switch (n) { case cudaLimitStackSize: return "cudaLimitStackSize"; case cudaLimitPrintfFifoSize: return "cudaLimitPrintfFifoSize"; case cudaLimitMallocHeapSize: return "cudaLimitMallocHeapSize"; case cudaLimitDevRuntimeSyncDepth: return "cudaLimitDevRuntimeSyncDepth"; case cudaLimitDevRuntimePendingLaunchCount: return "cudaLimitDevRuntimePendingLaunchCount"; case cudaLimitMaxL2FetchGranularity: return "cudaLimitMaxL2FetchGranularity"; } return "INVALID cudaLimit: "+n; }
csn
function (column) { if (isString(column.type) && column.type.match(/string/i) && column.text) {
delete column["default"]; } return this._super(arguments, [column]); }
csn_ccr
def returnIndexList(self, limit=False): '''Return a list of integers that are list-index references to the original list of dictionaries." Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnIndexList() [0, 1, 2, 3] >>> print PLOD(test).sort("name").returnIndexList() [3, 0, 2, 1]
:param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :return: A list of integers representing the original indices. ''' if limit==False: return self.index_track result = [] for i in range(limit): if len(self.table)>i: result.append(self.index_track[i]) return result
csn_ccr
Attempt to create a durable subscription on a remote ME. @param MP The MessageProcessor. @param subState State describing the subscription to create. @param remoteME The ME where the subscription should be created.
public static void createRemoteDurableSubscription( MessageProcessor MP, ConsumerDispatcherState subState, SIBUuid8 remoteMEUuid, SIBUuid12 destinationID) throws SIDurableSubscriptionAlreadyExistsException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createRemoteDurableSubscription", new Object[] { MP, subState, remoteMEUuid, destinationID }); // Issue the request via the DurableInputHandler int status = issueCreateDurableRequest(MP, subState, remoteMEUuid, destinationID); switch (status) { case DurableConstants.STATUS_SUB_ALREADY_EXISTS: { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createRemoteDurableSubscription", "SIDurableSubscriptionAlreadyExistsException"); throw new SIDurableSubscriptionAlreadyExistsException( nls.getFormattedMessage( "SUBSCRIPTION_ALREADY_EXISTS_ERROR_CWSIP0143", new Object[] {subState.getSubscriberID(), subState.getDurableHome()}, null)); } case DurableConstants.STATUS_SUB_GENERAL_ERROR: { // Problem on other side which should be logged, best we // can do is throw an exception here. if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createRemoteDurableSubscription", "SIErrorException"); SibTr.error(tc,"INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.DurableInputHandler", "1:955:1.52.1.1" }); throw new SIErrorException( nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.DurableInputHandler", "1:962:1.52.1.1" }, null)); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createRemoteDurableSubscription"); }
csn
Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell.
def preprocess_worksheet(self, table, worksheet): ''' Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell. ''' table_conversion = [] flags = {} units = {} for rind, row in enumerate(table): conversion_row = [] table_conversion.append(conversion_row) if self.skippable_rows and worksheet in self.skippable_rows and rind in self.skippable_rows[worksheet]: self.flag_change(flags, 'interpreted', (rind, None), worksheet, self.FLAGS['skipped-row']) continue for cind, cell in enumerate(row): position = (rind, cind) if self.skippable_columns and worksheet in self.skippable_columns and cind in self.skippable_columns[worksheet]: conversion = None self.flag_change(flags, 'interpreted', position, worksheet, self.FLAGS['skipped-column']) else: # Do the heavy lifting in pre_process_cell conversion = auto_convert_cell(self, cell, position, worksheet, flags, units, parens_as_neg=self.parens_as_neg) conversion_row.append(conversion) # Give back our conversions, type labeling, and conversion flags return table_conversion, flags, units
csn
func (b *Backoffer) Backoff(typ backoffType, err error) error { if strings.Contains(err.Error(), mismatchClusterID) { logutil.Logger(context.Background()).Fatal("critical error", zap.Error(err)) } select { case <-b.ctx.Done(): return errors.Trace(err) default: } typ.Counter().Inc() // Lazy initialize. if b.fn == nil { b.fn = make(map[backoffType]func(context.Context) int) } f, ok := b.fn[typ] if !ok { f = typ.createFn(b.vars) b.fn[typ] = f } b.totalSleep += f(b.ctx) b.types = append(b.types, typ) var startTs interface{} if ts := b.ctx.Value(txnStartKey); ts != nil { startTs = ts } logutil.Logger(context.Background()).Debug("retry later", zap.Error(err), zap.Int("totalSleep", b.totalSleep), zap.Int("maxSleep", b.maxSleep), zap.Stringer("type", typ), zap.Reflect("txnStartTS", startTs)) b.errors
= append(b.errors, errors.Errorf("%s at %s", err.Error(), time.Now().Format(time.RFC3339Nano))) if b.maxSleep > 0 && b.totalSleep >= b.maxSleep { errMsg := fmt.Sprintf("%s backoffer.maxSleep %dms is exceeded, errors:", typ.String(), b.maxSleep) for i, err := range b.errors { // Print only last 3 errors for non-DEBUG log levels. if log.GetLevel() == zapcore.DebugLevel || i >= len(b.errors)-3 { errMsg += "\n" + err.Error() } } logutil.Logger(context.Background()).Warn(errMsg) // Use the first backoff type to generate a MySQL error. return b.types[0].TError() } return nil }
csn_ccr
Override this method to change the default Route implementation @param controllerMethod The ControllerMethod @param parameterNames parameters of the method @return Route representation
protected Route getRouteStrategy(ControllerMethod controllerMethod, Parameter[] parameterNames) { return new FixedMethodStrategy(originalUri, controllerMethod, this.supportedMethods, builder.build(), priority, parameterNames); }
csn
Calculates the extended gcd @param {number} a @param {number} b @returns {Array}
function(a, b) { // gcd = a * s + b * t var s = 0, t = 1, u = 1, v = 0; while (a !== 0) { var q = b / a | 0, r = b % a; var m = s - u * q, n = t - v * q; b = a; a = r; s = u; t = v; u = m; v = n; } return [b /* gcd*/, s, t]; }
csn
Register or render a View. If View is registered this method returns the index number from View @param string $view @param array $data @return int|null
public static function render($view, array $data = array()) { if (self::$force || App::state() > 2) { \UtilsSandboxLoader('application/View/' . strtr($view, '.', '/') . '.php', self::$shared + $data); return $data = null; } return array_push(self::$views, array(strtr($view, '.', '/'), $data)) - 1; }
csn
Normalizes a nested array. @param array $files The nested array @return array Normalized array
protected static function normalizeNested(array $files) { $normalized = []; foreach (array_keys($files['tmp_name']) as $key) { $spec = [ 'name' => $files['name'][$key], 'tmp_name' => $files['tmp_name'][$key], 'type' => $files['type'][$key], 'size' => $files['size'][$key], 'error' => $files['error'][$key], ]; $normalized[$key] = static::build($spec); } return $normalized; }
csn
calculating the average of a list in python
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist))
cosqa
public static ServerSetup[] verbose(ServerSetup[] serverSetups) { ServerSetup[] copies = new ServerSetup[serverSetups.length]; for (int i = 0; i < serverSetups.length; i++) {
copies[i] = serverSetups[i].createCopy().setVerbose(true); } return copies; }
csn_ccr
Minimizes the capacity to the actual length of the string. @return this, to enable chaining
public StrBuilder minimizeCapacity() { if (buffer.length > length()) { final char[] old = buffer; buffer = new char[length()]; System.arraycopy(old, 0, buffer, 0, size); } return this; }
csn
python asyncio syncio hybrid
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
cosqa
Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a result set of columns that uniquely identify a row
def rowIdColumns(self, table, catalog=None, schema=None, # nopep8 nullable=True): """Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a result set of columns that uniquely identify a row """ fut = self._run_operation(self._impl.rowIdColumns, table, catalog=catalog, schema=schema, nullable=nullable) return fut
csn
def list_straten(self, gemeente, sort=1): ''' List all `straten` in a `Gemeente`. :param gemeente: The :class:`Gemeente` for which the \ `straten` are wanted. :rtype: A :class:`list` of :class:`Straat` ''' try: id = gemeente.id except AttributeError: id = gemeente def creator(): res = crab_gateway_request( self.client, 'ListStraatnamenWithStatusByGemeenteId', id, sort ) try: return[ Straat( r.StraatnaamId, r.StraatnaamLabel,
id, r.StatusStraatnaam )for r in res.StraatnaamWithStatusItem ] except AttributeError: return [] if self.caches['long'].is_configured: key = 'ListStraatnamenWithStatusByGemeenteId#%s%s' % (id, sort) straten = self.caches['long'].get_or_create(key, creator) else: straten = creator() for s in straten: s.set_gateway(self) return straten
csn_ccr
Add a prepare bridge method to the classfile for the given type. @param cf file to which to add the prepare bridge @param leaf leaf class @param returnClass type returned from generated bridge method @since 1.2
private static void definePrepareBridge(ClassFile cf, Class leaf, Class returnClass) { TypeDesc returnType = TypeDesc.forClass(returnClass); if (isPublicMethodFinal(leaf, PREPARE_METHOD_NAME, returnType, null)) { // Cannot override. return; } MethodInfo mi = cf.addMethod(Modifiers.PUBLIC.toBridge(true), PREPARE_METHOD_NAME, returnType, null); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.invokeVirtual(PREPARE_METHOD_NAME, cf.getType(), null); b.returnValue(returnType); }
csn
Checks if any changed child sockets are in the bucket. @param int $bucket The bucket to get results in. @param int $timeout The timeout for changed socket checking (default 0). @return int|void Returns the number of changed sockets for children workers in $bucket, or empty array if none.
protected function get_changed_sockets($bucket = self::DEFAULT_BUCKET, $timeout = 0) { $write_dummy = null; $exception_dummy = null; // grab all the children sockets $sockets = array(); foreach ($this->forked_children as $pid => $child) { if ($child['bucket'] == $bucket) { $sockets[$pid] = $child['socket']; } } if (!empty($sockets)) { // find changed sockets and return the array of them $result = @socket_select($sockets, $write_dummy, $exception_dummy, $timeout); if ($result !== false && $result > 0) { return $sockets; } } return null; }
csn
Triggers entity's fieldAttached callback. @return void
public function fieldAttached() { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->fieldAttached($this); } return true; }
csn
Returns permissions from the Role. @return PermissionInterface[]
public function getPermissions() { $mode = \RecursiveIteratorIterator::CHILD_FIRST; $iterator = $this->createRecursiveIterator($mode); $permissions = []; /** @var $child RoleInterface */ foreach ($iterator as $child) { $permissions = array_replace_recursive($permissions, $child->getPermissions()); } return array_replace_recursive($permissions, $this->permissions); }
csn
Decode hex string to a byte array @param encoded encoded string @return return array of byte to encode
static public byte[] decode(String encoded) { if (encoded == null) return null; int lengthData = encoded.length(); if (lengthData % 2 != 0) return null; char[] binaryData = encoded.toCharArray(); int lengthDecode = lengthData / 2; byte[] decodedData = new byte[lengthDecode]; byte temp1, temp2; char tempChar; for (int i = 0; i < lengthDecode; i++) { tempChar = binaryData[i * 2]; temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp1 == -1) return null; tempChar = binaryData[i * 2 + 1]; temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp2 == -1) return null; decodedData[i] = (byte) ((temp1 << 4) | temp2); } return decodedData; }
csn
Run configured command @return string
public function run() { $result = $this->getCommand()->run(); if ($result->getExitCode() != 0) { throw new \RuntimeException(sprintf( 'Command failed. Exit code %d, output %s', $result->getExitCode(), $result->getStdErr())); } return $this->parse($result->getStdOut()); }
csn
Get a single image CLI Example: .. code-block:: bash salt '*' glanceng.image_get name=image1 salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d
def image_get(auth=None, **kwargs): ''' Get a single image CLI Example: .. code-block:: bash salt '*' glanceng.image_get name=image1 salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.get_image(**kwargs)
csn
private function raiseIndentationLevel(int $indentationLevel, array $tokensInLine): int { $raisingIndentation = [ TokenInterface::TYPE_BRACE_OPEN, ]; if ($this->indentConditions && $this->insideCondition === false) { $raisingIndentation[] = TokenInterface::TYPE_CONDITION; } foreach ($tokensInLine as $token) {
if (in_array($token->getType(), $raisingIndentation)) { if ($token->getType() === TokenInterface::TYPE_CONDITION) { $this->insideCondition = true; } return $indentationLevel + 1; } } return $indentationLevel; }
csn_ccr
func (r *DatabaseFactory) MustGet(dbName ...string) *DB
{ db, err := r.Get(dbName...) if err != nil { panic(err) } return db }
csn_ccr
Add proper formated variable names, initializers and type names to use in templates
def generate_messages_info(msgs): """Add proper formated variable names, initializers and type names to use in templates""" for msg in msgs: msg.swift_name = camel_case_from_underscores(msg.name) msg.formatted_description = "" if msg.description: msg.description = " ".join(msg.description.split()) msg.formatted_description = "\n/**\n %s\n*/\n" % " ".join(msg.description.split()) msg.message_description = msg.description.replace('"','\\"') for field in msg.ordered_fields: field.swift_name = lower_camel_case_from_underscores(field.name) field.return_type = swift_types[field.type][0] # configure fields initializers if field.enum: # handle enums field.return_type = camel_case_from_underscores(field.enum) field.initial_value = "try data.mavEnumeration(offset: %u)" % field.wire_offset elif field.array_length > 0: if field.return_type == "String": # handle strings field.initial_value = "data." + swift_types[field.type][2] % (field.wire_offset, field.array_length) else: # other array types field.return_type = "[%s]" % field.return_type field.initial_value = "try data.mavArray(offset: %u, count: %u)" % (field.wire_offset, field.array_length) else: # simple type field field.initial_value = "try data." + swift_types[field.type][2] % field.wire_offset field.formatted_description = "" if field.description: field.description = " ".join(field.description.split()) field.formatted_description = "\n\t/// " + field.description + "\n" fields_info = map(lambda field: '("%s", %u, "%s", "%s")' % (field.swift_name, field.wire_offset, field.return_type, field.description.replace('"','\\"')), msg.fields) msg.fields_info = ", ".join(fields_info) msgs.sort(key = lambda msg : msg.id)
csn
public static function build_query_string() { $params = array(); foreach (func_get_args() as $arg) { $arg = is_array($arg) ? $arg : array($arg => '1');
$params = array_merge($params, $arg); } return http_build_query($params); }
csn_ccr
def set_by_Id(self, Id, is_added): """Update selected_ids with given Id""" row = self.collection.index_from_id(Id) if row is None:
return self._set_id(Id, is_added, self.index(row, 0))
csn_ccr
Create an instance of the oss driver. @param array $config @return \yuncms\filesystem\Filesystem @throws \OSS\Core\OssException @throws \Exception
public function createOssAdapter(array $config) { $root = $config['root'] ?? null; $oss = new OssClient($config['access_id'], $config['access_secret'], $config['endpoint'], $config['isCName'] ?? false, $config['securityToken'] ?? null, $config['proxy'] ?? null ); $oss->setTimeout($config['timeout'] ?? 3600); $oss->setConnectTimeout($config['connectTimeout'] ?? 10); $oss->setUseSSL($config['useSSL'] ?? false); return $this->adapt($this->createFlysystem( new OssAdapter($oss, $config['bucket'], $root), $config )); }
csn
get a fitting Unmarshaller @return - the Unmarshaller for the classOfT set @throws JAXBException
public Unmarshaller getUnmarshaller() throws JAXBException { JAXBContext context = JAXBContext.newInstance(classOfT); Unmarshaller u = context.createUnmarshaller(); u.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { return true; } }); return u; }
csn
def gettext_lazy(message, domain=DEFAULT_DOMAIN): """Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are some messages that need to be translated, but the translation can't be done at the point the message itself is written. For example, the names of the fields in a Model can't be translated at the point they are written, otherwise the translation would be done when the file is imported, long before a user even connects. To avoid this, `gettext_lazy` should be used. For example: .. code-block:: python
from zengine.lib.translation import gettext_lazy, InstalledLocale from pyoko import model, fields class User(model.Model): name = fields.String(gettext_lazy('User Name')) print(User.name.title) 'User Name' InstalledLocale.install_language('tr') print(User.name.title) 'Kullanıcı Adı' Args: message (basestring, unicode): The input message. domain (basestring): The domain of the message. Defaults to 'messages', which is the domain where all application messages should be located. Returns: unicode: The translated message, with the translation itself being delayed until the text is actually used. """ return LazyProxy(gettext, message, domain=domain, enable_cache=False)
csn_ccr