query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Create a regular expression based on the given `prefix`. @param {String} `prefix` @return {RegExp}
function toRegex(prefix) { var key = appendPrefix(prefix, '(\\d+)'); if (cache.hasOwnProperty(key)) { return cache[key]; } var regex = new RegExp(createRegexString(key), 'g'); cache[key] = regex; return regex; }
csn
Test the lock. @return true if the lock is held, otherwise false.
public boolean tryLock() { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this , cclass , "tryLock" ); boolean isLocked = true; if (fileLock == null) // Did we get the lock? ...
csn
Respond to the client with a 301 message and redirect them with a Location header. :param str location: The new location to redirect the client to.
def respond_redirect(self, location='/'): """ Respond to the client with a 301 message and redirect them with a Location header. :param str location: The new location to redirect the client to. """ self.send_response(301) self.send_header('Content-Length', 0) self.send_header('Location', location) se...
csn
protected function interpolate($message, $context = array()) { $replace = array(); foreach ($context as $key => $value) {
$replace['{' . $key . '}'] = $value; } return strtr($message, $replace); }
csn_ccr
Runs a test case or test suite, returning the results. @param {YUITest.TestCase|YUITest.TestSuite} testObject The test case or test suite to run. @return {Object} Results of the execution with properties passed, failed, and total. @private @method _run @static
function () { //flag to indicate if the TestRunner should wait before continuing var shouldWait = false; //get the next test node var node = this._next(); if (node !== null) { //set flag to say the testrunner is runn...
csn
func (c *Emulation) SetScriptExecutionDisabled(value bool) (*gcdmessage.ChromeResponse,
error) { var v EmulationSetScriptExecutionDisabledParams v.Value = value return c.SetScriptExecutionDisabledWithParams(&v) }
csn_ccr
public static void deleteFileOrDirectory(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { Path rootPath = Paths.get(file.getAbsolutePath()); Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.re...
.forEach(File::delete); } else { file.delete(); } } else { throw new RuntimeException("File or directory does not exist"); } }
csn_ccr
private void renderMatrix(Graphics2D g2, double fontSize) { int numCategories = confusion.getNumRows(); Font fontNumber = new Font("Serif", Font.BOLD, (int)(0.6*fontSize + 0.5)); g2.setFont(fontNumber); FontMetrics metrics = g2.getFontMetrics(fontNumber); for (int i = 0; i < numCategories; i++) { int y0 =...
// Render numbers inside the squares. Pick a color so that the number is visible no matter what // the color of the square is if( showNumbers && (showZeros || value != 0 )) { int a = (red+green+blue)/3; String text = ""+(int)(value*100.0+0.5); Rectangle2D r = metrics.getStringBounds(text,null...
csn_ccr
def _approx_eq_(self, other: Any, atol: float) -> bool: """Implementation of `SupportsApproximateEquality` protocol.""" if not isinstance(other, type(self)): return NotImplemented #self.value = value % period in __init__() creates a Mod if isinstance(other.value, sympy.Mod):...
high = max(self.value, other.value) # Shift lower value outside of normalization interval in case low and # high values are at the opposite borders of normalization interval. if high - low > self.period / 2: low += self.period return cirq.protocols.approx_eq(low, high, a...
csn_ccr
Set the EventManager used by this service instance to handle its events. It will take care of disabling the old EventManager and will subscribe the internal listeners to the new EventManager @param EventManagerInterface $eventManager
public function setEventManager(EventManagerInterface $eventManager) { if ($this->eventManager === $eventManager || $eventManager === null) { return; } if ($this->eventManager !== null) { $this->detach($this->eventManager); } $this->eventManager = $e...
csn
Event on Mouse up @param {Event} event
function mouseup(event) { // Prevent default dragging of selected content event.preventDefault(); // Remove helper helper.remove(); // Change all selecting items to selected var childs = getSelectable...
csn
Is other a response to self? @rtype: bool
def is_response(self, other): """Is other a response to self? @rtype: bool""" if other.flags & dns.flags.QR == 0 or \ self.id != other.id or \ dns.opcode.from_flags(self.flags) != \ dns.opcode.from_flags(other.flags): return False if dns.rcode...
csn
func (c *Client) Watch(resp func(response keyval.BytesWatchResp), closeChan chan string, keys ...string) error { c.Lock() defer c.Unlock() for _, key := range keys { dc :=
make(chan keyedData) go c.watch(resp, dc, closeChan, key) c.watchers[key] = dc } return nil }
csn_ccr
def should_close(self): """ Check whether the HTTP connection of this request should be closed after the request is finished. We check for the `Connection` HTTP header and for the HTTP Version (only `HTTP/1.1` supports keep-alive.
""" if self.headers.get('connection') == 'close': return True elif 'content-length' in self.headers or \ self.headers.get('METHOD') in ['HEAD', 'GET']: return self.headers.get('connection') != 'keep-alive' elif self.headers.get('VERSION') == 'HTTP/1.0': ...
csn_ccr
def _process_diff(self, yes_work, maybe_work, work_dir, ym_results_path, yn_results_path, stats): """Returns statistics on the difference between the intersection of `yes_work` and `maybe_work` and the intersection of `yes_work` and "no" works. :param yes_work: nam...
:rtype: `dict` """ distinct_results_path = os.path.join( work_dir, 'distinct_{}.csv'.format(maybe_work)) results = [yn_results_path, ym_results_path] labels = [self._no_label, self._maybe_label] self._run_query(distinct_results_path, self._store.diff_supplied, ...
csn_ccr
// PublishDownlink publishes a downlink message
func (c *DefaultClient) PublishDownlink(dataDown types.DownlinkMessage) Token { topic := DeviceTopic{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""} dataDown.AppID = "" dataDown.DevID = "" msg, err := json.Marshal(dataDown) if err != nil { return &simpleToken{fmt.Errorf("Unable to marshal the message payload...
csn
for i in range(5000): if i == sum(int(x) ** int(x) for x in str(i)): print(i)
#include <math.h> #include <iostream> unsigned pwr[10]; unsigned munch( unsigned i ) { unsigned sum = 0; while( i ) { sum += pwr[(i % 10)]; i /= 10; } return sum; } int main( int argc, char* argv[] ) { for( int i = 0; i < 10; i++ ) pwr[i] = (unsigned)pow( (float)i, (float)...
codetrans_contest
Returns stream of aggregated results based on the given window configuration. @param windowConfig window configuration like window length and slide length. @param windowStoreFactory intermediary tuple store for storing tuples for windowing @param inputFields input fields @param aggregator aggregator to run on the wind...
public Stream window(WindowConfig windowConfig, WindowsStoreFactory windowStoreFactory, Fields inputFields, Aggregator aggregator, Fields functionFields) { return window(windowConfig, windowStoreFactory, inputFields, aggregator, functionFields, true); }
csn
def one_of(*generators): """ Generates an arbitrary value of one of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class OneOfGenerators(ArbitraryInterface): """ A closure class around the generators sp...
one of the enclosed generators. """ return arbitrary(random.choice(generators)) OneOfGenerators.__name__ = ''.join([ 'one_of(', ', '.join(generator.__name__ for generator in generators), ')' ]) return OneOfGenerators
csn_ccr
func (l *List) Append(err error) { l.errs =
append(l.errs, err) l.err = nil }
csn_ccr
// Handle 352 who reply
func (conn *Conn) h_352(line *Line) { if !line.argslen(5) { return } nk := conn.st.GetNick(line.Args[5]) if nk == nil { logging.Warn("irc.352(): received WHO reply for unknown nick %s", line.Args[5]) return } if conn.Me().Equals(nk) { return } // XXX: do we care about the actual server the nick is on...
csn
func (w *audioWriter) Close() error { select
{ case w.quit <- true: default: } w.wg.Wait() return nil }
csn_ccr
protected function createDump(Infoset $info) { $content = ''; foreach ($info as $part) {
$content .= Dump::getDump($part); } return $content; }
csn_ccr
public static function getAllMetricsToKeep() { $metricsToKeep = self::getMetricsToKeep(); // convert goal metric names to correct archive names if (Common::isGoalPluginEnabled()) { $goalMetricsToKeep = self::getGoalMetricsToKeep(); $maxGoalId = self::getMaxGoalId();...
// the order report & cart report foreach ($goalMetricsToKeep as $metric) { for ($i = 1; $i <= $maxGoalId; ++$i) // maxGoalId can be 0 { $metricsToKeep[] = Archiver::getRecordName($metric, $i); } $metricsToKeep[] = Arc...
csn_ccr
=====Function Descriptions===== itertools.permutations(iterable[, r]) This tool returns successive rlength permutations of elements in an iterable. If r is not specified or is None, then r defaults to the length of the iterable, and all possible full length permutations are generated. Permutations are printed in a lex...
import itertools s,n = list(map(str,input().split(' '))) s = sorted(s) for p in list(itertools.permutations(s,int(n))): print((''.join(p)))
apps
// Get the last_updated field of the given VM_metrics.
func (_class VMMetricsClass) GetLastUpdated(sessionID SessionRef, self VMMetricsRef) (_retval time.Time, _err error) { _method := "VM_metrics.get_last_updated" _sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID) if _err != nil { return } _selfArg, _err := conver...
csn
protected void initializeDynamicTypeStructures( MethodVisitor mv, ClassDefinition classDef) { if ( classDef.isFullTraiting() ) { mv.visitVarInsn( ALOAD, 0 ); mv.visitTypeInsn( NEW, Type.getInternalName( TraitFieldTMSImpl.class ) ); mv.visitInsn( DUP ); mv.visitMe...
0 ); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType( classDef.getClassName() ), BuildUtils.getterName( fld.getName(), fld.getTypeName() ), "()" + BuildUtils.getTypeDescriptor( fld.getTypeName() ) ); if ( BuildUtils.isPrimitive( fld.getTypeName() ) ) { ...
csn_ccr
def set_per_page(self, entries=100): """ set entries per page max 200 """ if isinstance(entries, int) and entries <= 200: self.per_page = int(entries) return self
else: raise SalesKingException("PERPAGE_ONLYINT", "Please set an integer <200 for the per-page limit");
csn_ccr
public void onBlur (BlurEvent event) { if (_target.getText().trim().equals("")) {
_target.setText(_defaultText); } }
csn_ccr
Is editing currently enabled or not? This widget can toggle this value on the fly. When editing is enabled, it will display an editable attribute form with save, cancel and reset buttons. When editing is not enabled, these buttons will disappear, and a simple attribute form is shown that displays the attribute values, ...
public void setEditingEnabled(boolean editingEnabled) { if (isEditingAllowed()) { this.editingEnabled = editingEnabled; if (editingEnabled) { savePanel.setVisible(true); if (attributeTable != null && attributeTable.isDisabled()) { attributeTable.setDisabled(false); } } else { savePanel.s...
csn
public function getDealerAdminsJoinAdmin($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildDealerAdminQuery::create(null, $criteria);
$query->joinWith('Admin', $joinBehavior); return $this->getDealerAdmins($query, $con); }
csn_ccr
Extract the statements from the json.
def extract_statements(self): """Extract the statements from the json.""" for p_info in self._json: para = RlimspParagraph(p_info, self.doc_id_type) self.statements.extend(para.get_statements()) return
csn
Non-validating version of typed write method
@Override public final void writeTypedElement(AsciiValueEncoder enc) throws IOException { if (mSurrogate != 0) { throwUnpairedSurrogate(); } if (enc.bufferNeedsFlush(mOutputBuffer.length - mOutputPtr)) { flush(); } while (true) { ...
csn
Check all courses published from this site if they have been approved
public static function request_status_update() { global $DB; list($sitecourses, $coursetotal) = api::get_courses('', 1, 1, ['allsitecourses' => 1]); // Update status for all these course. foreach ($sitecourses as $sitecourse) { // Get the publication from the hub course id....
csn
Tries to find out a package key which the Version belongs to. If no package could be found, an empty string is returned. @param Version $version @return string @throws \ReflectionException
protected function getPackageKeyFromMigrationVersion(Version $version) { $sortedAvailablePackages = $this->packageManager->getAvailablePackages(); usort($sortedAvailablePackages, function (PackageInterface $packageOne, PackageInterface $packageTwo) { return strlen($packageTwo->getPackage...
csn
public static function releaseWriteLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{ $lock = $lockDirectory->getFileObject(self::WRITE_LOCK_FILE); $lock->unlock(); }
csn_ccr
func (h *Holder) availableShardsByIndex() map[string]*roaring.Bitmap { m := make(map[string]*roaring.Bitmap) for _, index
:= range h.Indexes() { m[index.Name()] = index.AvailableShards() } return m }
csn_ccr
Analyse the uploaded file, and return the parsed lines. Returns: tuple of tuples of cells content (as text).
def clean_file(self): """Analyse the uploaded file, and return the parsed lines. Returns: tuple of tuples of cells content (as text). """ data = self.cleaned_data['file'] available_parsers = self.get_parsers() for parser in available_parsers: tr...
csn
If the not a bitmap itself, this will read the file's meta data. @param resources {@link android.content.Context#getResources()} @return Point where x = width and y = height
public Point measureImage(Resources resources) { BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options(); justBoundsOptions.inJustDecodeBounds = true; if (bitmap != null) { return new Point(bitmap.getWidth(), bitmap.getHeight()); } else if (resId != null) { ...
csn
Install the hook.
def install_handle_input(self): """Install the hook.""" self.pointer = self.get_fptr() self.hooked = ctypes.windll.user32.SetWindowsHookExA( 13, self.pointer, ctypes.windll.kernel32.GetModuleHandleW(None), 0 ) if not self.hooked: ...
csn
Decrypt, verify and unserialize payload. @codeCoverageIgnore @return mixed
public function decode($data) { $data["data"] = $this->decrypt($data["data"], $this->config["secret"]); if (hash_hmac( "sha256", $data["data"], $this->config["secret"] ) == $data["token"]) { return unserialize($data["data"]); } else { ...
csn
Gets the property for the response. @param UserResponseInterface $response @return string @throws \RuntimeException
protected function getProperty(UserResponseInterface $response) { $resourceOwnerName = $response->getResourceOwner()->getName(); if (!isset($this->properties[$resourceOwnerName])) { throw new \RuntimeException(sprintf("No property defined for entity for resource owner '%s'.", $resourceO...
csn
Returns the value of the initParam. @param filterConfig a FilterConfig instance @param initParam the name of the init parameter @param variable the variable to use if the init param was not defined @return a String
private String getValue(FilterConfig filterConfig, String initParam, String variable) { final String value = filterConfig.getInitParameter(initParam); if (StringUtils.isNotBlank(value)) { return value; } else { return variable; } }
csn
protected function createTransport(array $config) { if (!isset($config['class'])) { $config['class'] = 'Swift_SendmailTransport'; } if (isset($config['plugins'])) { $plugins = $config['plugins']; unset($config['plugins']); } else { $plu...
$transport = $this->createSwiftObject($config); if (!empty($plugins)) { foreach ($plugins as $plugin) { if (is_array($plugin) && isset($plugin['class'])) { $plugin = $this->createSwiftObject($plugin); } $transport->registerPlu...
csn_ccr
// GetSet atomically sets key to value and returns the old value stored at key. // Returns an error when key exists but does not hold a string value.
func (r *Redis) GetSet(key, value string) ([]byte, error) { rp, err := r.ExecuteCommand("GETSET", key, value) if err != nil { return nil, err } return rp.BytesValue() }
csn
def write_library_constants(): """Write libtcod constants into the tcod.constants module.""" from tcod._libtcod import lib, ffi import tcod.color with open("tcod/constants.py", "w") as f: all_names = [] f.write(CONSTANT_MODULE_HEADER) for name in dir(lib): value = ge...
for name in all_names) f.write("\n__all__ = [\n %s,\n]\n" % (all_names,)) with open("tcod/event_constants.py", "w") as f: all_names = [] f.write(EVENT_CONSTANT_MODULE_HEADER) f.write("# --- SDL scancodes ---\n") f.write( "%s\n_REVERSE_SCANCODE_TABLE = %s\n" ...
csn_ccr
def recursive_apply(inval, func): '''Recursively apply a function to all levels of nested iterables :param inval: the object to run the function on :param func: the function that will
be run on the inval ''' if isinstance(inval, dict): return {k: recursive_apply(v, func) for k, v in inval.items()} elif isinstance(inval, list): return [recursive_apply(v, func) for v in inval] else: return func(inval)
csn_ccr
static public function getClient($name) { if (! isset(self::$clients[$name])) { throw new BlobException("There is no client registered for stream
type '" . $name . "://"); } return self::$clients[$name]; }
csn_ccr
native isinstance_ with the test for typing.Union overridden
def isinstance_(x, A_tuple): """ native isinstance_ with the test for typing.Union overridden """ if is_union(A_tuple): return any(isinstance_(x, t) for t in A_tuple.__args__) elif getattr(A_tuple, '__origin__', None) is not None: return isinstance(x, A_tuple.__origin__) else: re...
csn
func NewItem(t ItemType, pos int, line int, v string) Item
{ return Item{t, pos, line, v} }
csn_ccr
public List<SessionTicketKey> parse(File file) throws IOException {
return parseBytes(Files.toByteArray(file)); }
csn_ccr
function( jsonConfig, callback, jQuery ) { if ( jsonConfig instanceof Array ) { jsonConfig = JSONconfig.make( jsonConfig ); } // optional if ( jQuery ) {
$ = jQuery; } this.tree = TreeStore.createTree( jsonConfig ); this.tree.positionTree( callback ); }
csn_ccr
public function filter($matcher) { $filtered = array(); foreach ($this as $key => $element) { if (call_user_func($matcher, $element, $key)) {
$filtered[$key] = $element; } } return new static($filtered); }
csn_ccr
function (events, func) { for (var i = 0; i < events.length; i++) { obj.once(events[i],
func) listeners[events[i]] = func } }
csn_ccr
private static CertificateProvider newCertificateProvider(ComponentManager manager, Store store) throws GeneralSecurityException { try { CertificateProvider provider = manager.getInstance(CertificateProvider.class, "BCStoreX509");
((BcStoreX509CertificateProvider) provider).setStore(store); return provider; } catch (ComponentLookupException e) { throw new GeneralSecurityException("Unable to initialize the certificates store", e); } }
csn_ccr
private Level mapLogLevel(final LogLevel logLevel) { if (LogLevel.DEBUG.equals(logLevel)) { return Level.DEBUG; } else if (LogLevel.TRACE.equals(logLevel)) { return Level.TRACE; } else if (LogLevel.INFO.equals(logLevel)) { return Level.INFO; } else
if (LogLevel.WARN.equals(logLevel)) { return Level.WARN; } else if (LogLevel.ERROR.equals(logLevel)) { return Level.ERROR; } return null; }
csn_ccr
public function replace($newUrl, $opt = self::SCHEME | self::HOST | self::PORT | self::CREDENTIALS | self::PATH | self::QUERY | self::FRAGMENT) { if ($newUrl instanceof Url) { $url = $newUrl; } else if (is_string($newUrl)) { $url = new Url($newUrl); } else { throw new InvalidUrlException(); } $schem...
$path = ($opt & self::PATH) === self::PATH; $query = ($opt & self::QUERY) === self::QUERY; $fragment = ($opt & self::FRAGMENT) === self::FRAGMENT; if ($scheme) { $this->scheme->set($url->scheme->get()); } if ($host) { $this->host->set($url->host->get()); } if ($port) { $this->port->set($url->por...
csn_ccr
func (c *Client) DeleteRecord(domainID, recordID string) error { return
c.do(http.MethodDelete, fmt.Sprintf("/v1/domains/%s/records/%s", domainID, recordID), nil, nil) }
csn_ccr
protected function register(array $options) { foreach ($options as $option => $argument) { if (is_bool($argument)) { add_theme_support($option);
continue; } add_theme_support($option, $argument); } }
csn_ccr
public void cancelOrder(KiteConnect kiteConnect) throws KiteException, IOException { // Order modify request will return order model which will contain only order_id.
// Cancel order will return order model which will only have orderId. Order order2 = kiteConnect.cancelOrder("180116000727266", Constants.VARIETY_REGULAR); System.out.println(order2.orderId); }
csn_ccr
public function getPaymorrowJavaScriptPmInitFull() { $sPmPrintData = $this->_getPaymorrowPrintData(); $sPmControllerPrepareOrder = $this->getPaymorrowControllerPrepareOrderProcessPaymentURL(); $sSelectedMethod = $this->getSelectedPaymorrowMethod(); $sNextButtonId = 'paymentNextStepBo...
$sInvoice = sprintf( 'pmInitFull("INVOICE", "pminvoice", "rb_payment_invoice", "dl_payment_invoice", "payment", %s, "%s", %s, "%s");', $sPmPrintData, $sPmControllerPrepareOrder, ($sSelectedMethod == 'pm_invoice') ? 'true' : 'false', $sNextButtonId ...
csn_ccr
@Override public java.util.concurrent.Future<SubmitContainerStateChangeResult> submitContainerStateChangeAsync( com.amazonaws.handlers.AsyncHandler<SubmitContainerStateChangeRequest, SubmitContainerStateChangeResult> asyncHandler) {
return submitContainerStateChangeAsync(new SubmitContainerStateChangeRequest(), asyncHandler); }
csn_ccr
public function queryVector($query, $options = array()) { return $this->queryArray($query, $options,
function(\PDOStatement $statement) { return $statement->fetchAll(\PDO::FETCH_COLUMN, 0); }); }
csn_ccr
// SetMaximumPartitionCount sets the MaximumPartitionCount field's value.
func (s *Limits) SetMaximumPartitionCount(v int64) *Limits { s.MaximumPartitionCount = &v return s }
csn
// getObjectInfoDir - This getObjectInfo is specific to object directory lookup.
func (xl xlObjects) getObjectInfoDir(ctx context.Context, bucket, object string) (oi ObjectInfo, err error) { var wg = &sync.WaitGroup{} errs := make([]error, len(xl.getDisks())) // Prepare object creation in a all disks for index, disk := range xl.getDisks() { if disk == nil { continue } wg.Add(1) go f...
csn
Add the default properties accesses for each roles
public function addDefaultProperties() { $properties = User::getEditableProperties(); $this->om->startFlushSuite(); foreach ($properties as $property => $editable) { $this->addProperties($property, $editable); } $this->om->endFlushSuite(); }
csn
public function getDictionary(string $name): Definition { if (!$this->hasDictionary($name)) {
throw new \InvalidArgumentException('Dictionary not found: ' . $name); } return $this->dictionaries[$name]; }
csn_ccr
public JSONObject getJson() throws JSONException { JSONObject json = create(); json.put("id", getLogicalId()); json.put("to", "A" + toId); if (completionCode != null) json.put("resultCode", completionCode); if (eventType != null) json.put("event", EventTyp...
if (attributes != null && ! attributes.isEmpty()) json.put("attributes", Attribute.getAttributesJson(attributes)); return json; }
csn_ccr
Return the mmi data as a delimited test string. :returns: A delimited text string that can easily be written to disk for e.g. use by gdal_grid. :rtype: str The returned string will look like this:: 123.0750,01.7900,1 123.1000,01.7900,1.14 123.1250,...
def mmi_to_delimited_text(self): """Return the mmi data as a delimited test string. :returns: A delimited text string that can easily be written to disk for e.g. use by gdal_grid. :rtype: str The returned string will look like this:: 123.0750,01.7900,1 ...
csn
public static function handleCasByKey($memcached, $casToken, $serverKey, $key) { return [ 'attributes' => [ 'casToken' => $casToken,
'serverKey' => $serverKey, 'key' => $key ], 'kind' => Span::KIND_CLIENT ]; }
csn_ccr
function search(req, res, next) { res.__apiMethod = 'search'; buildQuery.call(this, req).exec(function (err, obj) { if (err) { var isCastError = (err.name === 'CastError') || (err.message && err.message[0] === '$') || (err.message === 'and needs an array') ;
if (isCastError) return next( new ModelAPIError(400, err.message) ); return next(err); } res.json(obj); }); }
csn_ccr
public static function real_ip($default = '0.0.0.0', $exclude_reserved = false) { static $server_keys = null; if (empty($server_keys)) { $server_keys = array('HTTP_CLIENT_IP', 'REMOTE_ADDR'); if (\Config::get('security.allow_x_headers', false)) { $server_keys = array_merge(array('HTTP_X_CLUSTER_CLI...
} } foreach ($server_keys as $key) { if ( ! static::server($key)) { continue; } $ips = explode(',', static::server($key)); array_walk($ips, function (&$ip) { $ip = trim($ip); }); $ips = array_filter($ips, function($ip) use($exclude_reserved) { return filter_var($ip, FILTER_VAL...
csn_ccr
public function listTopics(ListTopicsOptions $listTopicsOptions = null) { $response = $this->_listOptions( $listTopicsOptions,
Resources::LIST_TOPICS_PATH ); $listTopicsResult = new ListTopicsResult(); $listTopicsResult->parseXml($response->getBody()); return $listTopicsResult; }
csn_ccr
// getBuildConfigByKey looks up a buildconfig by key in the buildConfigInformer cache
func (c *BuildConfigController) getBuildConfigByKey(key string) (*buildv1.BuildConfig, error) { obj, exists, err := c.buildConfigInformer.GetIndexer().GetByKey(key) if err != nil { klog.V(2).Infof("Unable to retrieve buildconfig %s from store: %v", key, err) return nil, err } if !exists { klog.V(2).Infof("Bui...
csn
Get tracks by flag range @param int $min @param int $max @param int $trackableType @param int $perPage @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
public function getByFlagRange(int $min, int $max = Settings::FLAG_MAX, int $trackableType = Tracker::TRACKER_ANY, int $perPage = 15) : LengthAwarePaginator { $query = $this->getModel()->newQuery(); if ($max === Settings::FLAG_MAX) { $query->where('level', '>=', $min); } else { ...
csn
unescape the string @param string $string @return string
public static function percentUnEscape($string) { // Next, repeatedly percent-unescape the URL until it has no more percent-escapes. // this is not trivial, because the percent character could be in the url, when are we done? // lets unescape till there are no more percentages, or the only percentages are...
csn
Marks this session as invalid.
void invalidate() { if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, "invalidate"); } _sessionInvalidated = true; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, "invali...
csn
average values for key in dictionary python
def _mean_dict(dict_list): """Compute the mean value across a list of dictionaries """ return {k: np.array([d[k] for d in dict_list]).mean() for k in dict_list[0].keys()}
cosqa
Get all data for a row @param int|bool $id ID of the row to return @return array Array of columns of a table row @since 2.1
public function getRow($id = false) { if ($id === false) { $id = $this->activeRow; } if (isset($this->rows[(int) $id])) { return $this->rows[(int) $id]; } else { return false; } }
csn
public static List<CharSequence> getBodies(Message message) { XHTMLExtension xhtmlExtension = XHTMLExtension.from(message); if (xhtmlExtension != null)
return xhtmlExtension.getBodies(); else return null; }
csn_ccr
public function decryptResponseWithSharedKey( ResponseInterface $response, SharedEncryptionKey $key ): ResponseInterface { $encrypted = Base64UrlSafe::decode((string) $response->getBody()); return $response->withBody(
$this->adapter->stringToStream( Simple::decrypt($encrypted, $key) ) ); }
csn_ccr
public Annotation getRef() { if (ArgumentMention_Type.featOkTst && ((ArgumentMention_Type)jcasType).casFeat_ref == null) jcasType.jcas.throwFeatMissing("ref", "de.julielab.jules.types.ArgumentMention");
return (Annotation)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((ArgumentMention_Type)jcasType).casFeatCode_ref)));}
csn_ccr
private static String fileStatusToString(FileStatus stat) { assert stat != null; return String.format( "path: %s, isDir: %s, len: %d, owner: %s",
stat.getPath().toString(), stat.isDir(), stat.getLen(), stat.getOwner()); }
csn_ccr
protected final function definition() { $form = $this->_form; $store = $this->_customdata['store']; $plugin = $this->_customdata['plugin']; $locks = $this->_customdata['locks']; $form->addElement('hidden', 'plugin', $plugin); $form->setType('plugin', PARAM_PLUGIN); ...
$form->addElement('hidden', 'lock', ''); $form->setType('lock', PARAM_ALPHANUMEXT); $form->addElement('static', 'lock-value', get_string('locking', 'cache'), '<em>'.get_string('nativelocking', 'cache').'</em>'); } if (method_exists($this, 'configuration_de...
csn_ccr
python how to do multiple string replaces
def multi_replace(instr, search_list=[], repl_list=None): """ Does a string replace with a list of search and replacements TODO: rename """ repl_list = [''] * len(search_list) if repl_list is None else repl_list for ser, repl in zip(search_list, repl_list): instr = instr.replace(ser, re...
cosqa
Display a critical message bar. :param title: The title of the message bar. :type title: basestring :param message: The message inside the message bar. :type message: basestring :param more_details: The message inside the 'Show details' button. :type more_details: basestring :param butto...
def display_critical_message_bar( title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8, iface_object=iface ): """ Display a critical message bar. :param title: The title of the message bar. :type title: basestring ...
csn
Load a GOParser object from a pickle file. The function automatically detects whether the file is compressed with gzip. Parameters ---------- fn: str Path of the pickle file. Returns ------- `GOParser` The GOParser object stored ...
def read_pickle(fn): """Load a GOParser object from a pickle file. The function automatically detects whether the file is compressed with gzip. Parameters ---------- fn: str Path of the pickle file. Returns ------- `GOParser` ...
csn
private void redistributeBuffers() throws IOException { assert Thread.holdsLock(factoryLock); // All buffers, which are not among the required ones final int numAvailableMemorySegment = totalNumberOfMemorySegments - numTotalRequiredBuffers; if (numAvailableMemorySegment == 0) { // in this case, we need to ...
totalCapacity += Math.min(numAvailableMemorySegment, excessMax); } // no capacity to receive additional buffers? if (totalCapacity == 0) { return; // necessary to avoid div by zero when nothing to re-distribute } // since one of the arguments of 'min(a,b)' is a positive int, this is actually // guara...
csn_ccr
Creates a user and returns it. @param string $username @param string $password @param string $email @param bool $active @param bool $superadmin @return UserInterface
public function create($username, $password, $email, $active, $superadmin) { $user = $this->userManager->createUser(); $user->setUsername($username); $user->setEmail($email); $user->setPlainPassword($password); $user->setEnabled((bool) $active); $user->setSuperAdmin((...
csn
return the Link back to shop @return bool
public function showBackToShop() { $iNewBasketItemMessage = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('iNewBasketItemMessage'); $sBackToShop = \OxidEsales\Eshop\Core\Registry::getSession()->getVariable('_backtoshop'); return ($iNewBasketItemMessage == 3 && $sBackToShop); ...
csn
def _set_token_defaults(token): """ Returns an updated token that includes default values for fields that were introduced since the token was created by checking its version number. """ def _verify_version(jwt_version): supported_version = Version( settings.JWT_AUTH.get('JWT_...
get this far into the decoding process. # TODO: ARCH-166 """ if 'is_restricted' not in token: token['is_restricted'] = False def _set_filters(token): """ We can safely default to an empty list of filters since previously created tokens were either "restr...
csn_ccr
func (i *InstanceID) MarshalMetadata(data interface{}) error { if fmt.Sprintf("%v", data) == "<nil>" { return ErrIIDMetadataNilData }
var err error if i.metadata, err = json.Marshal(data); err != nil { return err } return nil }
csn_ccr
round datetime value to nearest minute python
def __round_time(self, dt): """Round a datetime object to a multiple of a timedelta dt : datetime.datetime object, default now. """ round_to = self._resolution.total_seconds() seconds = (dt - dt.min).seconds rounding = (seconds + round_to / 2) // round_to * round_to return dt + timedelta(0,...
cosqa
def retry(retry_count): """ Retry decorator used during file upload and download. """ def func(f): @functools.wraps(f) def wrapper(*args, **kwargs): for backoff in range(retry_count): try: return f(*args, **kwargs) except E...
backoff) else: raise SbgError('{}: failed to complete: {}'.format( threading.current_thread().getName(), f.__name__) ) return wrapper return func
csn_ccr
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import tensorflow as d2l def f(x): return 3 * x ** 2 - 4 * x
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import torch as d2l def f(x): return 3 * x ** 2 - 4 * x
codetrans_dl
Creates a "status report" for this task. Includes the task ID and overall status, plus reports for all the component task-threads that have ever been started.
synchronized TaskReport generateSingleReport() { ArrayList<String> diagnostics = new ArrayList<String>(); for (List<String> l : taskDiagnosticData.values()) { diagnostics.addAll(l); } TIPStatus currentStatus = null; if (isRunning() && !isComplete()) { currentStatus = TIPStatus.RUNNING; ...
csn
def _get_conversion_factor(old_units, new_units, dtype): """ Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object ...
old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new_units.base_value if old_units.base_offset == 0 and new_units.base_offset == 0: return (ratio, None) else: # the dimensions are the same, so both are temperatures, where ...
csn_ccr
// Retr retrieves file from remote host at path, using retrFn to read from the remote file.
func (ftp *FTP) Retr(path string, retrFn RetrFunc) (s string, err error) { if err = ftp.Type(TypeImage); err != nil { return } var port int if port, err = ftp.Pasv(); err != nil { return } if err = ftp.send("RETR %s", path); err != nil { return } var pconn net.Conn if pconn, err = ftp.newConnection(po...
csn
The result from @see IThreadErrorHandler::OnUncaughtException is given as Parameter in the parent thread You can decide how to handle this If you like you could throw an \Exeption to the caller or you can just return a value indicating that function is failed. You can also trigger error here if you like to @param mixed...
public function OnErrorMessageReachParent($result) { if ($result instanceof SerializableException) { if ($result instanceof SerializableFatalException) { //Fatal exception should be handled separate //This should be tracked on parent throw ne...
csn
// NewPrepareExec creates a new PrepareExec.
func NewPrepareExec(ctx sessionctx.Context, is infoschema.InfoSchema, sqlTxt string) *PrepareExec { base := newBaseExecutor(ctx, nil, prepareStmtLabel) base.initCap = chunk.ZeroCapacity return &PrepareExec{ baseExecutor: base, is: is, sqlText: sqlTxt, } }
csn