query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
def handle_deletions(self): """ Manages handling deletions of objects that were previously managed by the initial data process but no longer managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on each round of initial data processing. Any receipts that are from previous rounds and not the current round will be deleted. """ deduplicated_objs = {} for model in self.model_objs_registered_for_deletion: key = '{0}:{1}'.format( ContentType.objects.get_for_model(model, for_concrete_model=False), model.id ) deduplicated_objs[key] = model # Create receipts for every object registered for deletion now = timezone.now() registered_for_deletion_receipts = [ RegisteredForDeletionReceipt( model_obj_type=ContentType.objects.get_for_model(model_obj, for_concrete_model=False), model_obj_id=model_obj.id, register_time=now) for model_obj in deduplicated_objs.values() ] # Do a bulk upsert on all of the receipts, updating their registration time. RegisteredForDeletionReceipt.objects.bulk_upsert(
registered_for_deletion_receipts, ['model_obj_type_id', 'model_obj_id'], update_fields=['register_time']) # Delete all receipts and their associated model objects that weren't updated for receipt in RegisteredForDeletionReceipt.objects.exclude(register_time=now): try: receipt.model_obj.delete() except: # noqa # The model object may no longer be there, its ctype may be invalid, or it might be protected. # Regardless, the model object cannot be deleted, so go ahead and delete its receipt. pass receipt.delete()
csn_ccr
func AddMultiple(cookies []*http.Cookie) p.Plugin { return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) { for _, cookie
:= range cookies { ctx.Request.AddCookie(cookie) } h.Next(ctx) }) }
csn_ccr
def get_off_ang(src, rec, nsrc, nrec, verb): r"""Get depths, offsets, angles, hence spatial input parameters. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Parameters ---------- src, rec : list of floats or arrays Source/receiver dipole coordinates x, y, and z (m). nsrc, nrec : int Number of sources/receivers (-). verb : {0, 1, 2, 3, 4} Level of verbosity. Returns ------- off : array of floats Offsets angle : array of floats
Angles """ global _min_off # Pre-allocate off and angle off = np.empty((nrec*nsrc,)) angle = np.empty((nrec*nsrc,)) # Coordinates # Loop over sources, append them one after another. for i in range(nsrc): xco = rec[0] - src[0][i] # X-coordinates [m] yco = rec[1] - src[1][i] # Y-coordinates [m] off[i*nrec:(i+1)*nrec] = np.sqrt(xco*xco + yco*yco) # Offset [m] angle[i*nrec:(i+1)*nrec] = np.arctan2(yco, xco) # Angle [rad] # Note: One could achieve a potential speed-up using np.unique to sort out # src-rec configurations that have the same offset and angle. Very unlikely # for real data. # Minimum offset to avoid singularities at off = 0 m. # => min_off can be set with utils.set_min angle[np.where(off < _min_off)] = np.nan off = _check_min(off, _min_off, 'Offsets', 'm', verb) return off, angle
csn_ccr
func (sys *PolicySys) refresh(objAPI ObjectLayer) error { buckets, err := objAPI.ListBuckets(context.Background()) if err != nil { logger.LogIf(context.Background(), err) return err } sys.removeDeletedBuckets(buckets) for _, bucket := range buckets { config, err := objAPI.GetBucketPolicy(context.Background(), bucket.Name) if err != nil { if _, ok := err.(BucketPolicyNotFound); ok { sys.Remove(bucket.Name) } continue
} // This part is specifically written to handle migration // when the Version string is empty, this was allowed // in all previous minio releases but we need to migrate // those policies by properly setting the Version string // from now on. if config.Version == "" { logger.Info("Found in-consistent bucket policies, Migrating them for Bucket: (%s)", bucket.Name) config.Version = policy.DefaultVersion if err = savePolicyConfig(context.Background(), objAPI, bucket.Name, config); err != nil { logger.LogIf(context.Background(), err) return err } } sys.Set(bucket.Name, *config) } return nil }
csn_ccr
def find_plugins(): """Locate and initialize all available plugins. """ plugin_dir = os.path.dirname(os.path.realpath(__file__)) plugin_dir =
os.path.join(plugin_dir, "plugins") plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")] sys.path.insert(0, plugin_dir) for plugin in plugin_files: __import__(plugin)
csn_ccr
Url encode a value. @param value the value to encode @param encoding the encoding @return the encoded value
@SneakyThrows public static String urlEncode(final String value, final String encoding) { return URLEncoder.encode(value, encoding); }
csn
Determine whether the text nodes contain similar values @param control @param test @return true if text nodes are similar, false otherwise
protected boolean similar(Text control, Text test) { if (control == null) { return test == null; } else if (test == null) { return false; } return control.getNodeValue().equals(test.getNodeValue()); }
csn
protected function shouldBeDelayed(): bool { if ($this->job && \is_null($this->model)) { $this->release(10);
return true; } return false; }
csn_ccr
private function convertToExtendedFieldQuery() { $this->fieldModel = $this->dispatcher->getContainer()->get('mautic.lead.model.field'); $this->selectParts = $this->query->getQueryPart('select'); $this->orderByParts = $this->query->getQueryPart('orderBy'); $this->groupByParts = $this->query->getQueryPart('groupBy'); $this->filters = $this->event->getReport()->getFilters(); $this->where = $this->query->getQueryPart('where'); $this->fieldTables = isset($this->fieldTables) ? $this->fieldTables : []; $this->count = 0; if (!$this->extendedFields) { // Previous method deprecated: // $fields = $this->fieldModel->getEntities( // [ // [ // 'column' => 'f.isPublished', // 'expr' => 'eq', // 'value' => true, // ], // 'force' => [ // 'column' => 'f.object', // 'expr' => 'in', // 'value' => ['extendedField', 'extendedFieldSecure'], // ], // 'hydration_mode' => 'HYDRATE_ARRAY', // ] // ); // // Key by alias. // foreach ($fields as $field) { // $this->extendedFields[$field['alias']] = $field;
// } $this->extendedFields = $this->fieldModel->getExtendedFields(); } $this->alterSelect(); if (method_exists($this->event, 'getQuery')) { // identify ReportQueryEvent instance in backwards compatible way $this->alterOrderBy(); } $this->alterGroupBy(); $this->alterWhere(); $this->query->select($this->selectParts); if (method_exists($this->event, 'getQuery') && !empty($this->orderByParts)) { $orderBy = implode(',', $this->orderByParts); $this->query->add('orderBy', $orderBy); } if (!empty($this->groupByParts)) { $this->query->groupBy($this->groupByParts); } if (!empty($this->where)) { $this->query->where($this->where); } }
csn_ccr
// newUnsucessDest returns a new UnsucessDest constructed from a UnSme struct
func newUnsucessDest(p pdufield.UnSme) UnsucessDest { unDest := UnsucessDest{} unDest.AddrTON, _ = p.Ton.Raw().(uint8) // if there is an error default value will be set unDest.AddrNPI, _ = p.Npi.Raw().(uint8) unDest.Address = string(p.DestAddr.Bytes()) unDest.Error = pdu.Status(binary.BigEndian.Uint32(p.ErrCode.Bytes())) return unDest }
csn
protected function getDefaultConfigurationLibrary($magentoEdition, $entityTypeCode) { // query whether or not, a default configuration file for the passed entity type is available if (isset($this->defaultConfigurations[$edition = strtolower($magentoEdition)])) { if (isset($this->defaultConfigurations[$edition][$entityTypeCode])) { return $this->defaultConfigurations[$edition][$entityTypeCode]; }
// throw an exception, if the passed entity type is not supported throw new \Exception( sprintf( 'Entity Type Code \'%s\' not supported by entity type code \'%s\' (MUST be one of catalog_product, catalog_category or eav_attribute)', $edition, $entityTypeCode ) ); } // throw an exception, if the passed edition is not supported throw new \Exception( sprintf( 'Default configuration for Magento \'%s\' not supported (MUST be one of CE or EE)', $magentoEdition ) ); }
csn_ccr
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. -----Input----- The first line contains two integers, n and k (1 ≤ n ≤ 10^5; 1 ≤ k ≤ 10^9). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 10^5. Each string of the group consists only of lowercase English letters. -----Output----- If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). -----Examples----- Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second
""" Codeforces Contest 260 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ def main(): n,k = read() s = set() for i in range(n): s.add(read(0)) s = list(s) s.sort() s = treeify(s) res = solve(s) if res == 0: # neither: second player win print("Second") if res == 1: # odd: first player win if k is odd print("First" if k % 2 else "Second") if res == 2: # even: second player win print("Second") if res == 3: # both: first player win print("First") def treeify(s): res = [[] for _ in range(26)] for i in s: if i: res[ord(i[0]) - 97].append(i[1:]) fin = [] for i in range(26): if res[i]: fin.append(treeify(res[i])) return fin def solve(s, parity=2): for i in range(len(s)): if isinstance(s[i], list): s[i] = solve(s[i], 3-parity) if not s: return parity # no possible move: current parity if 0 in s: return 3 # any neither: both if 1 in s and 2 in s: return 3 # any odd and any even: both if 1 in s: return 1 # any odd: odd if 2 in s: return 2 # any even: even return 0 # all both: neither ################################### NON-SOLUTION STUFF BELOW def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return map(int, inputs.split()) def write(s="\n"): if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") main()
apps
Gets the passwordCredentials associated with a service principal. @param object_id [String] The object ID of the service principal. @param custom_headers [Hash{String => String}] A hash of custom headers that will be added to the HTTP request. @return [PasswordCredentialListResult] operation results.
def list_password_credentials(object_id, custom_headers:nil) response = list_password_credentials_async(object_id, custom_headers:custom_headers).value! response.body unless response.nil? end
csn
// Retrieve The item price that an account is restricted to.
func (r Account) GetPriceRestrictions() (resp []datatypes.Product_Item_Price_Account_Restriction, err error) { err = r.Session.DoRequest("SoftLayer_Account", "getPriceRestrictions", nil, &r.Options, &resp) return }
csn
// buildInformers creates all the informer factories.
func (sdn *OpenShiftSDN) buildInformers() error { kubeConfig, err := configapi.GetKubeConfigOrInClusterConfig(sdn.NodeConfig.MasterKubeConfig, sdn.NodeConfig.MasterClientConnectionOverrides) if err != nil { return err } kubeClient, err := kubernetes.NewForConfig(kubeConfig) if err != nil { return err } networkClient, err := networkclient.NewForConfig(kubeConfig) if err != nil { return err } kubeInformers := kinformers.NewSharedInformerFactory(kubeClient, sdn.ProxyConfig.IPTables.SyncPeriod.Duration) networkInformers := networkinformers.NewSharedInformerFactory(networkClient, network.DefaultInformerResyncPeriod) sdn.informers = &informers{ KubeClient: kubeClient, NetworkClient: networkClient, KubeInformers: kubeInformers, NetworkInformers: networkInformers, } return nil }
csn
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): attrs = sorted(instname.__dict__.keys()) if len(attrs) == 1: attrs = attrs[0] else: attrs = '{} and {}'.format(', '.join(attrs[:-1]), attrs[-1]) return 'Hi, I\'m one of those {}s! Have a look at my {}.'\ .format(instname.__class__.__name__, attrs)
apps
func (db *BytesConnectionRedis) Close() error { if db.closed { db.Debug("Close() called on a closed connection") return nil } db.Debug("Close()")
db.closed = true safeclose.Close(db.closeCh) if db.client != nil { err := safeclose.Close(db.client) if err != nil { return fmt.Errorf("Close() encountered error: %s", err) } } return nil }
csn_ccr
Remove the current notebook from the list of paired notebooks
def drop_paired_notebook(self, path): """Remove the current notebook from the list of paired notebooks""" if path not in self.paired_notebooks: return fmt, formats = self.paired_notebooks.pop(path) prev_paired_paths = paired_paths(path, fmt, formats) for alt_path, _ in prev_paired_paths: if alt_path in self.paired_notebooks: self.drop_paired_notebook(alt_path)
csn
public TrmClientAttachRequest createNewTrmClientAttachRequest() throws MessageCreateFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewTrmClientAttachRequest"); TrmClientAttachRequest msg = null; try { msg = new TrmClientAttachRequestImpl(); } catch (MessageDecodeFailedException e) { /* No need to FFDC this
as JsMsgObject will already have done so */ // No FFDC code needed throw new MessageCreateFailedException(e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createNewTrmClientAttachRequest"); return msg; }
csn_ccr
Returns the MD5 hash of the input string @param input Input string @return String The md5 hash of the input string @throws HibiscusException
public static String getMD5Hash(final String input) throws HibiscusException { String hashValue = null; try { final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5); byte[] md5Hash = new byte[BYTE_LENGTH_MD5]; messageDigest.update(input.getBytes(ENCODING_CHARSET_NAME), MESSAGE_DIGEST_UPDATE_OFFSET, input.length()); md5Hash = messageDigest.digest(); hashValue = convertToHex(md5Hash); } catch (NoSuchAlgorithmException e) { throw new HibiscusException("Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_MD5, e); } catch (UnsupportedEncodingException e) { throw new HibiscusException("Unsupported Encoding " + ENCODING_CHARSET_NAME , e); } return hashValue; }
csn
Parse arguments of script.
def parse_arguments(args=sys.argv[1:]): """Parse arguments of script.""" cmd_description = "Download tracklistings for BBC radio shows.\n\n" \ "Saves to a text file, tags audio file or does both.\n" \ "To select output file, filename " \ "must both be specified.\n" \ "If directory is not specified, directory is assumed" \ "to be where script is.\n" \ "Filename is the prefix, for someaudio.m4a, use " \ "--filename someaudio\n" \ "Otherwise, an attempt will be made to write " \ "text file to current directory.\n" \ "If choosing 'both', directory and filename should " \ "point to audio file.\n" \ "In this case, text file will have same name " \ "as audio file, but with .txt" # http://stackoverflow.com/questions/7869345/ parser = ArgumentParser(formatter_class=RawTextHelpFormatter, description=cmd_description) action_help = "tag: tag audio file with tracklisting\n" \ "text: write tracklisting to text file (default)\n" \ "both: tag audio file and write to text file" parser.add_argument('action', choices=('tag', 'text', 'both'), default='text', help=action_help) parser.add_argument('pid', help="BBC programme id, e.g. b03fnc82") parser.add_argument('--directory', help="output directory") parser.add_argument('--fileprefix', help="output filename prefix") return parser.parse_args()
csn
Returns an array of Collection instances which use the given storage @param StorageInterface $storage @return array<CollectionInterface>
public function getCollectionsByStorage(StorageInterface $storage) { $this->initialize(); $collections = []; foreach ($this->collections as $collectionName => $collection) { /** @var CollectionInterface $collection */ if ($collection->getStorage() === $storage) { $collections[$collectionName] = $collection; } } return $collections; }
csn
Assignment submission is processed before grading. @param moodleform|null $mform If validation failed when submitting this form - this is the moodleform. It can be null. @return bool Return false if the validation fails. This affects which page is displayed next.
protected function process_submit_for_grading($mform, $notices) { global $CFG; require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php'); require_sesskey(); if (!$this->submissions_open()) { $notices[] = get_string('submissionsclosed', 'assign'); return false; } $data = new stdClass(); $adminconfig = $this->get_admin_config(); $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement; $submissionstatement = ''; if ($requiresubmissionstatement) { $submissionstatement = $this->get_submissionstatement($adminconfig, $this->get_instance(), $this->get_context()); } // If we get back an empty submission statement, we have to set $requiredsubmisisonstatement to false to prevent // that the submission statement checkbox will be displayed. if (empty($submissionstatement)) { $requiresubmissionstatement = false; } if ($mform == null) { $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement, $submissionstatement, $this->get_course_module()->id, $data)); } $data = $mform->get_data(); if (!$mform->is_cancelled()) { if ($mform->get_data() == false) { return false; } return $this->submit_for_grading($data, $notices); } return true; }
csn
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) {
if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
csn_ccr
Function used internally to generate functions to format complex valued data.
def mk_complex_format_func(fmt): """ Function used internally to generate functions to format complex valued data. """ fmt = fmt + u"+i" + fmt def complex_format_func(z): return fmt % (z.real, z.imag) return complex_format_func
csn
public static URI buildURI(String urlTemplate, Map<String, String> keys, Map<String, String> queryParams) { // Compute base url String url = urlTemplate; if (keys != null && keys.size() != 0) { url = StrSubstitutor.replace(urlTemplate, keys); } try { URIBuilder uriBuilder = new URIBuilder(url); // Append query parameters if (queryParams != null && queryParams.size() != 0) {
for (Map.Entry<String, String> entry : queryParams.entrySet()) { uriBuilder.addParameter(entry.getKey(), entry.getValue()); } } return uriBuilder.build(); } catch (URISyntaxException e) { throw new RuntimeException("Fail to build uri", e); } }
csn_ccr
// SetBackgroundColor sets the box's background color.
func (b *Box) SetBackgroundColor(color tcell.Color) *Box { b.backgroundColor = color return b }
csn
The alphabetized kata --------------------- Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed! The input is restricted to contain no numerals and only words containing the english alphabet letters. Example: ```python alphabetized("The Holy Bible") # "BbeehHilloTy" ``` _Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_
def alphabetized(s): return "".join(sorted(filter(str.isalpha, s),key=str.lower))
apps
public function deleteNode($node) { $target_pos = $node->getPosition(); $this->rewind(); $pos = 0; // Omit target node and adjust pos of remainder $done = false; try { while ($n = $this->current()) { if ($pos == $target_pos && !$done) {
$done = true; $this->next(); $this->offsetUnset($pos); } elseif ($pos >= $target_pos) { $n->setPosition($pos); $pos++; $this->next(); } else { $pos++; $this->next(); } } } catch (Exception $e) { // no-op - shift() throws an exception, sigh } }
csn_ccr
Convert input data for storing in the database
private function convert_save_data($save_data, $record = array()) { $out = array(); $words = ''; // copy values into vcard object $vcard = new rcube_vcard($record['vcard'] ?: $save_data['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap); $vcard->reset(); // don't store groups in vCard (#1490277) $vcard->set('groups', null); unset($save_data['groups']); foreach ($save_data as $key => $values) { list($field, $section) = explode(':', $key); $fulltext = in_array($field, $this->fulltext_cols); // avoid casting DateTime objects to array if (is_object($values) && is_a($values, 'DateTime')) { $values = array(0 => $values); } foreach ((array)$values as $value) { if (isset($value)) $vcard->set($field, $value, $section); if ($fulltext && is_array($value)) $words .= ' ' . rcube_utils::normalize_string(join(" ", $value)); else if ($fulltext && strlen($value) >= 3) $words .= ' ' . rcube_utils::normalize_string($value); } } $out['vcard'] = $vcard->export(false); foreach ($this->table_cols as $col) { $key = $col; if (!isset($save_data[$key])) $key .= ':home'; if (isset($save_data[$key])) { if (is_array($save_data[$key])) $out[$col] = join(self::SEPARATOR, $save_data[$key]); else $out[$col] = $save_data[$key]; } } // save all e-mails in database column $out['email'] = join(self::SEPARATOR, $vcard->email); // join words for fulltext search $out['words'] = join(" ", array_unique(explode(" ", $words))); return $out; }
csn
def script(): """Run the command-line script.""" parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.") parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true") parser.add_argument("file", nargs="+", help="file(s) to print tags of") args = parser.parse_args() for filename in args.file: if isinstance(filename, bytes): filename = filename.decode(sys.getfilesystemencoding()) line = "TAGS OF '{0}'".format(os.path.basename(filename)) print("*" * len(line)) print(line) print("*" * len(line)) audioFile = taglib.File(filename) tags = audioFile.tags if len(tags) > 0: maxKeyLen = max(len(key) for key in tags.keys()) for key, values in tags.items(): for value in values: print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
if len(audioFile.unsupported) > 0: print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported)) if sys.version_info[0] == 2: inputFunction = raw_input else: inputFunction = input if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]: audioFile.removeUnsupportedProperties(audioFile.unsupported) audioFile.save()
csn_ccr
how to detect mouse click in the graphic window in python
def on_mouse_motion(self, x, y, dx, dy): """ Pyglet specific mouse motion callback. Forwards and traslates the event to the example """ # Screen coordinates relative to the lower-left corner # so we have to flip the y axis to make this consistent with # other window libraries self.example.mouse_position_event(x, self.buffer_height - y)
cosqa
def is_valid_email(self): """A bool value that indicates whether the address is a valid email address. Note that the check is done be matching to the regular expression
at Email.re_email which is very basic and far from covering end-cases... """ return bool(self.address and Email.re_email.match(self.address))
csn_ccr
public static function saveData(Registry $syncdata) { $db = Factory::getDBO(); $data = new stdClass; $data->syncdata = $syncdata->toString(); $data->syncid = $syncdata->get('syncid'); $data->time_start =
time(); $data->action = $syncdata->get('action'); $db->insertObject('#__jfusion_sync', $data); }
csn_ccr
method to save the tags of an attachment @param Attachments\Model\Entity\Attachment $attachment the attachment entity @param array $tags array of tags @return bool
public function saveTags($attachment, $tags) { $newTags = []; foreach ($tags as $tag) { if (isset($this->config('tags')[$tag])) { $newTags[] = $tag; if ($this->config('tags')[$tag]['exclusive'] === true) { $this->_clearTag($attachment, $tag); } } } $this->Attachments->patchEntity($attachment, ['tags' => $newTags]); return (bool)$this->Attachments->save($attachment); }
csn
detect the date created on a file with python
def get_creation_datetime(filepath): """ Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None """ if platform.system() == 'Windows': return datetime.fromtimestamp(os.path.getctime(filepath)) else: stat = os.stat(filepath) try: return datetime.fromtimestamp(stat.st_birthtime) except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return None
cosqa
private FilesystemIteratorRule getBestRule(final String filename) { String longestPrefix = null; FilesystemIteratorRule rule = null; // First search the path and all of its parents for the first regular rule String path = filename; while(true) { // Check the current path for an exact match //System.out.println("DEBUG: Checking "+path); rule = rules.get(path); if(rule!=null) { longestPrefix = path; break; } // If done, break the loop int pathLen = path.length(); if(pathLen==0) break; int lastSlashPos = path.lastIndexOf(File.separatorChar); if(lastSlashPos==-1) { path = ""; } else if(lastSlashPos==(pathLen-1)) { // If ends with a slash, remove that slash path = path.substring(0, lastSlashPos); } else { // Otherwise, remove and leave the last slash path = path.substring(0, lastSlashPos+1); } } if(prefixRules!=null) { // TODO: If there are many more prefix rules than the
length of this filename, it will at some threshold // be faster to do a map lookup for each possible length of the string. // Would also only need to look down to longestPrefix for(Map.Entry<String,FilesystemIteratorRule> entry : prefixRules.entrySet()) { String prefix = entry.getKey(); if( (longestPrefix==null || prefix.length()>longestPrefix.length()) && filename.startsWith(prefix) ) { //System.err.println("DEBUG: FilesystemIterator: getBestRule: filename="+filename+", prefix="+prefix+", longestPrefix="+longestPrefix); longestPrefix = prefix; rule = entry.getValue(); } } } return rule; }
csn_ccr
Start MongoDB on demand before running your tests. @example describe('my app', function(){ before(require('mongodb-runner/mocha/before'); it('should connect', function(done){ require('mongodb').connect('mongodb://localhost:27017/', done); }); }); @param {Object|Function} [opts] - options or the `done` callback. @return {Function} - Callback for mocha bdd `before` hook.
function mongodb_runner_mocha_before(opts) { if (typeof opts === 'function') { // So you can just do `before(require('mongodb-runner/mocha/before'));` return mongodb_runner_mocha_before({}).apply(this, arguments); } opts = opts || {}; defaults(opts, { port: 27017, timeout: 10000, slow: 10000 }); return function(done) { this.timeout(opts.timeout); this.slow(opts.slow); debug('checking if mongodb is running...'); running(function(err, res) { if (err) { debug('mongodb detection failed so going to try and start one'); runner({ port: opts.port, action: 'start' }, done); return; } if (res && res.length > 0) { if (res[0].port === opts.port) { process.env.MONGODB_RUNNER_MOCHA_SKIP_STOP = '1'; debug('mongodb already running on `localhost:%s` ' + 'so we won\'t start a new one', opts.port); done(); return; } debug('mongodb already running, but its on ' + '`localhost:%d` and we need `localhost:%s` for ' + 'the tests so starting up a new one.', res[0].port, opts.port); runner({ action: 'start', port: opts.port }, done); return; } debug('no mongodb running so starting one up'); runner({ action: 'start', port: opts.port }, done); return; }); }; }
csn
public String[] plan(String aam, String uniqueOfferingsTosca) throws ParsingException, IOException { log.info("Planning for aam: \n" + aam); //Get offerings log.info("Getting Offeing Step: Start"); Map<String, Pair<NodeTemplate, String>> offerings = parseOfferings(uniqueOfferingsTosca); // getOfferingsFromDiscoverer(); log.info("Getting Offeing Step: Complete"); log.info("\nNot deployable offering have been filtered!"); log.info("\nDeployable offerings have location: " + deployableProviders); log.info("Got " + offerings.size() + " offerings from discoverer:"); //Matchmake log.info("Matchmaking Step: Start");
Matchmaker mm = new Matchmaker(); Map<String, HashSet<String>> matchingOfferings = mm.match(ToscaSerializer.fromTOSCA(aam), offerings); log.info("Matchmaking Step: Complete"); //Optimize String mmOutput = ""; try { mmOutput = generateMMOutput2(matchingOfferings, offerings); }catch(JsonProcessingException e){ log.error("Error preparing matchmaker output for optimization", e); } for(String s:matchingOfferings.keySet()){ log.info("Module " + s + "has matching offerings: " + matchingOfferings.get(s)); } log.info("Optimization Step: Start"); log.info("Calling optimizer with suitable offerings: \n" + mmOutput); Optimizer optimizer = new Optimizer(); String[] outputPlans = optimizer.optimize(aam, mmOutput); log.info("Optimzer result: " + Arrays.asList(outputPlans)); log.info("Optimization Step: Complete"); return outputPlans; }
csn_ccr
public boolean truncate(long zxid) throws IOException { FileTxnIterator itr = new FileTxnIterator(this.logDir, zxid); PositionInputStream input = itr.inputStream; long pos = input.getPosition(); // now, truncate at the current position RandomAccessFile raf=new RandomAccessFile(itr.logFile,"rw"); raf.setLength(pos); raf.close();
while(itr.goToNextLog()) { if (!itr.logFile.delete()) { LOG.warn("Unable to truncate " + itr.logFile); } } return true; }
csn_ccr
public Collection<RepositoryResource> getMatchingResources(final FilterPredicate... predicates) throws RepositoryBackendException { Collection<RepositoryResource> resources = cycleThroughRepositories(new RepositoryInvoker<RepositoryResource>() { @Override
public Collection<RepositoryResource> performActionOnRepository(RepositoryConnection connection) throws RepositoryBackendException { return connection.getMatchingResources(predicates); } }); return resources; }
csn_ccr
public function getArgInfoName(ClassDefinition $classDefinition = null) { if (null != $classDefinition) { return sprintf( 'arginfo_%s_%s_%s', strtolower($classDefinition->getCNamespace()), strtolower($classDefinition->getName()),
strtolower($this->getName()) ); } return sprintf('arginfo_%s', strtolower($this->getInternalName())); }
csn_ccr
Extend a query with a list of two-tuples.
def add_params_to_qs(query, params): """Extend a query with a list of two-tuples.""" if isinstance(params, dict): params = params.items() queryparams = urlparse.parse_qsl(query, keep_blank_values=True) queryparams.extend(params) return urlencode(queryparams)
csn
func ToQuicError(err error) *QuicError { switch e := err.(type) { case *QuicError: return e case ErrorCode:
return Error(e, "") } return Error(InternalError, err.Error()) }
csn_ccr
public function setTableName($tableName) { $this->query = str_replace($this->tableName, $tableName, $this->query); $this->dummyQuery
= str_replace($this->tableName, $tableName, $this->dummyQuery); $this->tableName = $tableName; return $this; }
csn_ccr
public function createJsTranslation($content, $langcode = null) { $extracted = $this->parseJs($content); if (empty($extracted)) { return false; } $file = $this->getContextJsFile($langcode);
$translations = $this->loadTranslation($this->getCommonFile($langcode)); foreach ($extracted as $string) { $this->addTranslation($string, $translations, $file); } return true; }
csn_ccr
python instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
cosqa
public function getOffensivenessOfWeaponlike(WeaponlikeCode $weaponlikeCode): int {
return $this->tables->getWeaponlikeTableByWeaponlikeCode($weaponlikeCode)->getOffensivenessOf($weaponlikeCode); }
csn_ccr
function(e) { var DOM = YAHOO.util.Dom; this.logger.log(this.id + " endDrag"); var lel = this.getEl(); var del = this.getDragEl(); // Show the drag frame briefly so we can get its position // del.style.visibility = ""; DOM.setStyle(del, "visibility", "");
// Hide the linked element before the move to get around a Safari // rendering bug. //lel.style.visibility = "hidden"; DOM.setStyle(lel, "visibility", "hidden"); YAHOO.util.DDM.moveToEl(lel, del); //del.style.visibility = "hidden"; DOM.setStyle(del, "visibility", "hidden"); //lel.style.visibility = ""; DOM.setStyle(lel, "visibility", ""); }
csn_ccr
// update brings the VersionList up to date with file. It returns the updated // VersionList, a potentially removed old FileVersion and its index, as well as // the index where the new FileVersion was inserted.
func (vl VersionList) update(folder, device []byte, file protocol.FileInfo, t readOnlyTransaction) (_ VersionList, removedFV FileVersion, removedAt int, insertedAt int) { vl, removedFV, removedAt = vl.pop(device) nv := FileVersion{ Device: device, Version: file.Version, Invalid: file.IsInvalid(), } i := 0 if nv.Invalid { i = sort.Search(len(vl.Versions), func(j int) bool { return vl.Versions[j].Invalid }) } for ; i < len(vl.Versions); i++ { switch vl.Versions[i].Version.Compare(file.Version) { case protocol.Equal: fallthrough case protocol.Lesser: // The version at this point in the list is equal to or lesser // ("older") than us. We insert ourselves in front of it. vl = vl.insertAt(i, nv) return vl, removedFV, removedAt, i case protocol.ConcurrentLesser, protocol.ConcurrentGreater: // The version at this point is in conflict with us. We must pull // the actual file metadata to determine who wins. If we win, we // insert ourselves in front of the loser here. (The "Lesser" and // "Greater" in the condition above is just based on the device // IDs in the version vector, which is not the only thing we use // to determine the winner.) // // A surprise missing file entry here is counted as a win for us. if of, ok := t.getFile(folder, vl.Versions[i].Device, []byte(file.Name)); !ok || file.WinsConflict(of) { vl = vl.insertAt(i, nv) return vl, removedFV, removedAt, i } } } // We didn't find a position for an insert above, so append to the end. vl.Versions = append(vl.Versions, nv) return vl, removedFV, removedAt, len(vl.Versions) - 1 }
csn
public static Hashtable<String, Object> getCustomCredentials(Subject callSubject, String cacheKey) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "getCustomCredentials", cacheKey); } if (callSubject == null || cacheKey == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "getCustomCredentials", " null"); } return null; } GetCustomCredentials action = new GetCustomCredentials(callSubject, cacheKey);
Hashtable<String, Object> cred = (Hashtable<String, Object>) AccessController.doPrivileged(action); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "getCustomCredentials", objectId(cred)); } return cred; }
csn_ccr
public static List<NetFlowV9BaseRecord> parseRecords(ByteBuf bb, Map<Integer, NetFlowV9Template> cache, NetFlowV9OptionTemplate optionTemplate) { List<NetFlowV9BaseRecord> records = new ArrayList<>(); int flowSetId = bb.readUnsignedShort(); int length = bb.readUnsignedShort(); int end = bb.readerIndex() - 4 + length; List<NetFlowV9FieldDef> defs; boolean isOptionTemplate = optionTemplate != null && optionTemplate.templateId() == flowSetId; if (isOptionTemplate) { defs = optionTemplate.optionDefs(); } else { NetFlowV9Template t = cache.get(flowSetId); if (t == null) { return Collections.emptyList(); } defs = t.definitions(); } // calculate record unit size int unitSize = 0; for (NetFlowV9FieldDef def : defs) { unitSize += def.length(); } while (bb.readerIndex() < end && bb.readableBytes() >= unitSize) { final ImmutableMap.Builder<String, Object> fields = ImmutableMap.builder(); for (NetFlowV9FieldDef def : defs) { final String key = def.type().name().toLowerCase(Locale.ROOT); final Optional<Object> optValue = def.parse(bb); optValue.ifPresent(value -> fields.put(key, value)); } if (isOptionTemplate) {
final ImmutableMap.Builder<Integer, Object> scopes = ImmutableMap.builder(); for (NetFlowV9ScopeDef def : optionTemplate.scopeDefs()) { int t = def.type(); int len = def.length(); long l = 0; for (int i = 0; i < len; i++) { l <<= 8; l |= bb.readUnsignedByte(); } scopes.put(t, l); } records.add(NetFlowV9OptionRecord.create(fields.build(), scopes.build())); } else { records.add(NetFlowV9Record.create(fields.build())); } // This flowset cannot contain another record, treat as padding if (end - bb.readerIndex() < unitSize) { break; } } bb.readerIndex(end); return records; }
csn_ccr
how to evaluate if strings are equal python
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
cosqa
func (s *serverConfig) SetCacheConfig(drives, exclude []string, expiry int, maxuse int) { s.Cache.Drives = drives s.Cache.Exclude =
exclude s.Cache.Expiry = expiry s.Cache.MaxUse = maxuse }
csn_ccr
Check that a signature is valid against a public key. @param string $signature @param string $data @param string $publicKey @return bool @throws ApiException @api
public function checkSignature(string $signature, string $data, string $publicKey): bool { return $this->getJson([ 'q' => 'checkSignature', 'signature' => $signature, 'data' => $data, 'public_key' => $publicKey, ]); }
csn
Make a cursor from the specific row. @param Query $query @param mixed $row @return int[]|string[]
protected function makeCursor(Query $query, $row) { $fields = []; foreach ($query->orders() as $order) { $fields[$order->column()] = $this->field($row, $order->column()); } return $fields; }
csn
protected String getWebSocketURL(ChannelHandlerContext ctx, HttpRequest req) { boolean isSecure = ctx.pipeline().get(SslHandler.class) != null;
return (isSecure ? SCHEME_SECURE_WEBSOCKET : SCHEME_WEBSOCKET) + req.getHeaders().get(HttpHeaderNames.HOST) + req.getUri() ; }
csn_ccr
public final int getUint8(final int pos) { if (pos >= limit || pos < 0) throw new IllegalArgumentException("limit excceed:
" + pos); return 0xff & buffer[origin + pos]; }
csn_ccr
public function declinePayment($orderId) { /** * Loads order to validate. */ $this ->paymentBridge ->findOrder($orderId); /** * Order Not found Exception must be thrown just here. */ if (!$this->paymentBridge->getOrder()) { throw new PaymentOrderNotFoundException(); } /** * Payment failed. * * Paid process has ended with failure
*/ $this ->paymentEventDispatcher ->notifyPaymentOrderFail( $this->paymentBridge, $this ->methodFactory ->create() ); return $this; }
csn_ccr
public function getLogger() { if ($this->logger) { return $this->logger; }
$this->setLogger(CoreLib\getLogger()); return $this->logger; }
csn_ccr
func New(rootLogger *logrus.Logger, cfg *config.Gateway, r *Router) *Gateway { logger := rootLogger.WithFields(logrus.Fields{"prefix": "gateway"}) cache, _ := lru.New(5000) gw := &Gateway{ Channels: make(map[string]*config.ChannelInfo), Message: r.Message, Router: r, Bridges: make(map[string]*bridge.Bridge),
Config: r.Config, Messages: cache, logger: logger, } if err := gw.AddConfig(cfg); err != nil { logger.Errorf("Failed to add configuration to gateway: %#v", err) } return gw }
csn_ccr
Finds a document by its identifier @param string|object $id The identifier @param int $lockMode @param int $lockVersion @param array $options @throws Mapping\MappingException @throws LockException @throws UserDeactivatedException @return null | UserInterface
public function find($id, $lockMode = \Doctrine\ODM\MongoDB\LockMode::NONE, $lockVersion = null, array $options = []) { return $this->assertEntity(parent::find($id, $lockMode, $lockVersion), $options); }
csn
public function set($index, $newValue) { if (!$this->offsetSet($index, $newValue)) {
$this->append($newValue); } return $this; }
csn_ccr
func IsSubpath(path, root string) bool { path, err := filepath.Abs(filepath.Clean(path)) if err != nil { return false } root, err = filepath.Abs(filepath.Clean(root)) if err != nil { return false } if root == path {
return true } if root[len(root)-1] != filepath.Separator { root += string(filepath.Separator) } return strings.HasPrefix(path, root) }
csn_ccr
public function appendTokens(Tokenizer $new_tokens) { $this->tokens = array_merge($this->tokens,
$new_tokens->asArray()); $this->rewind(); return $this; }
csn_ccr
// SetUserIdentity sets the UserIdentity field's value.
func (s *Record) SetUserIdentity(v *Identity) *Record { s.UserIdentity = v return s }
csn
Remove a Revoked Certificate Extension @param string $serial @param string $id @access public @return bool
function removeRevokedCertificateExtension($serial, $id) { if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { return $this->_removeExtension($id, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); } } return false; }
csn
Unsubscribe object from all events @param object $obj Subscriber @return boolean Success
public function unsubFromAll($obj) { foreach ($this->events as $event) { $event->unsub($obj); } return true; }
csn
Adjust a feature's location when flipping DNA. :param feature: The feature to flip. :type feature: coral.Feature :param parent_len: The length of the sequence to which the feature belongs. :type parent_len: int
def _flip_feature(self, feature, parent_len): '''Adjust a feature's location when flipping DNA. :param feature: The feature to flip. :type feature: coral.Feature :param parent_len: The length of the sequence to which the feature belongs. :type parent_len: int ''' copy = feature.copy() # Put on the other strand if copy.strand == 0: copy.strand = 1 else: copy.strand = 0 # Adjust locations - guarantee that start is always less than end copy.start = parent_len - copy.start copy.stop = parent_len - copy.stop copy.start, copy.stop = copy.stop, copy.start return copy
csn
public function liftEmbargo() { $query = $this->getEntityManager() ->createQuery('SELECT e.id, e.embargoed FROM '.$this->getEntityName().' e WHERE e.status = \'Embargoed\' AND DATE_DIFF(CURRENT_DATE(), e.embargoed) >= 0'); $embargoed = $query->getResult(); if (empty($embargoed)) { return; } $now = new DateTime(); $updated = array_filter($embargoed, function($entry) use ($now) { $liftEmbargo = $entry['embargoed'] instanceof DateTime ? $entry['embargoed'] : new DateTime($entry['embargoed']); return $now->getTimestamp() >= $liftEmbargo->getTimestamp(); }); $ids = array_map(function($entry) {
return $entry['id']; }, $updated); if (empty($ids)) { return; } $query = $this->getEntityManager() ->createQuery('UPDATE '.$this->getEntityName().' e SET e.status = \'usable\' WHERE e.id IN (' . implode(',', $ids) . ')'); $query->getResult(); }
csn_ccr
func loadModulesHcl(list *ast.ObjectList) ([]*Module, error) { if err := assertAllBlocksHaveNames("module", list); err != nil { return nil, err } list = list.Children() if len(list.Items) == 0 { return nil, nil } // Where all the results will go var result []*Module // Now go over all the types and their children in order to get // all of the actual resources. for _, item := range list.Items { k := item.Keys[0].Token.Value().(string) var listVal *ast.ObjectList if ot, ok := item.Val.(*ast.ObjectType); ok { listVal = ot.List } else { return nil, fmt.Errorf("module '%s': should be an object", k) } var config map[string]interface{} if err := hcl.DecodeObject(&config, item.Val); err != nil { return nil, fmt.Errorf( "Error reading config for %s: %s", k, err) } rawConfig, err := NewRawConfig(config) if err != nil { return nil, fmt.Errorf( "Error reading config for %s: %s", k, err) } // Remove the fields we handle specially delete(config, "source") delete(config, "version") delete(config, "providers") var source string if o := listVal.Filter("source"); len(o.Items) > 0 { err = hcl.DecodeObject(&source, o.Items[0].Val) if err != nil { return nil, fmt.Errorf( "Error parsing source for %s: %s", k, err) } } var version string
if o := listVal.Filter("version"); len(o.Items) > 0 { err = hcl.DecodeObject(&version, o.Items[0].Val) if err != nil { return nil, fmt.Errorf( "Error parsing version for %s: %s", k, err) } } var providers map[string]string if o := listVal.Filter("providers"); len(o.Items) > 0 { err = hcl.DecodeObject(&providers, o.Items[0].Val) if err != nil { return nil, fmt.Errorf( "Error parsing providers for %s: %s", k, err) } } result = append(result, &Module{ Name: k, Source: source, Version: version, Providers: providers, RawConfig: rawConfig, }) } return result, nil }
csn_ccr
function () { if (this.showing && this.hasNode() && this.activator) { this.resetPositioning(); this.activatorOffset = this.getPageOffset(this.activator); var innerWidth = this.getViewWidth(); var innerHeight = this.getViewHeight(); //These are the view "flush boundaries" var topFlushPt = this.vertFlushMargin; var bottomFlushPt = innerHeight - this.vertFlushMargin; var leftFlushPt = this.horizFlushMargin; var rightFlushPt = innerWidth - this.horizFlushMargin; //Rule 1 - Activator Location based positioning //if the activator is in the top or bottom edges of the view, check if the popup needs flush positioning if ((this.activatorOffset.top + this.activatorOffset.height) < topFlushPt || this.activatorOffset.top > bottomFlushPt) { //check/try vertical flush positioning (rule 1.a.i) if (this.applyVerticalFlushPositioning(leftFlushPt, rightFlushPt)) { return; } //if vertical doesn't fit then check/try horizontal flush (rule 1.a.ii) if (this.applyHorizontalFlushPositioning(leftFlushPt, rightFlushPt)) { return; } //if flush positioning didn't work then try just positioning vertically (rule 1.b.i & rule 1.b.ii) if (this.applyVerticalPositioning()){ return; } //otherwise check if the activator is in the left or right edges of the view & if so try horizontal positioning } else if ((this.activatorOffset.left + this.activatorOffset.width) < leftFlushPt || this.activatorOffset.left > rightFlushPt) { //if flush positioning didn't work then try just positioning horizontally (rule 1.b.iii & rule 1.b.iv) if (this.applyHorizontalPositioning()){ return; } } //Rule 2 - no specific logic below for this rule since it is inheritent to the positioning functions, ie we attempt to
never //position a popup where there isn't enough room for it. //Rule 3 - Popup Size based positioning var clientRect = this.getBoundingRect(this.node); //if the popup is wide then use vertical positioning if (clientRect.width > this.widePopup) { if (this.applyVerticalPositioning()){ return; } } //if the popup is long then use horizontal positioning else if (clientRect.height > this.longPopup) { if (this.applyHorizontalPositioning()){ return; } } //Rule 4 - Favor top or bottom positioning if (this.applyVerticalPositioning()) { return; } //but if thats not possible try horizontal else if (this.applyHorizontalPositioning()){ return; } //Rule 5 - no specific logic below for this rule since it is built into the vertical position functions, ie we attempt to // use a bottom position for the popup as much possible. } }
csn_ccr
python prettyxml remove carrige returns
def pp_xml(body): """Pretty print format some XML so it's readable.""" pretty = xml.dom.minidom.parseString(body) return pretty.toprettyxml(indent=" ")
cosqa
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.   Example 1: Input: s = "eleetminicoworoep" Output: 13 Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u. Example 2: Input: s = "leetcodeisgreat" Output: 5 Explanation: The longest substring is "leetc" which contains two e's. Example 3: Input: s = "bcbcbc" Output: 6 Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.   Constraints: 1 <= s.length <= 5 x 10^5 s contains only lowercase English letters.
class Solution: def findTheLongestSubstring(self, s: str) -> int: s = s + 'a' bits, dp = {'a':0,'e':1,'i':2,'o':3,'u':4}, {0:-1} res = 0 key = 0 for i, char in enumerate(s): if char in bits: if key in dp: res = max(res, i-dp[key] - 1) key = key ^ (1 << bits[char]) if key not in dp: dp[key] = i return res
apps
public function removeUnwantedModuleMetaboxes($postType) { $publicPostTypes = array_keys(\Municipio\Helper\PostType::getPublic()); $publicPostTypes[] = 'page'; if
(!in_array($postType, $publicPostTypes)) { // Navigation settings remove_meta_box('acf-group_56d83cff12bb3', $postType, 'side'); // Display settings remove_meta_box('acf-group_56c33cf1470dc', $postType, 'side'); } }
csn_ccr
Constructs a surface polyline. @alias SurfacePolyline @constructor @augments SurfaceShape @classdesc Represents a polyline draped over the terrain surface. <p> SurfacePolyline uses the following attributes from its associated shape attributes bundle: <ul> <li>Draw outline</li> <li>Outline color</li> <li>Outline width</li> <li>Outline stipple factor</li> <li>Outline stipple pattern</li> </ul> @param {Location[]} locations This polyline's locations. @param {ShapeAttributes} attributes The attributes to apply to this shape. May be null, in which case attributes must be set directly before the shape is drawn. @throws {ArgumentError} If the specified locations are null or undefined.
function (locations, attributes) { if (!locations) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfacePolyline", "constructor", "The specified locations array is null or undefined.")); } SurfaceShape.call(this, attributes); /** * This shape's locations, specified as an array locations. * @type {Array} */ this._boundaries = locations; this._stateId = SurfacePolyline.stateId++; // Internal use only. this._isInteriorInhibited = true; }
csn
// Returns identation spaces for end of block character
func (rule *Rule) indentEndBlock() string { result := "" for i := 0; i < (rule.EmbedLevel * indentSpace); i++ { result += " " } return result }
csn
def check_datasource_perms(self, datasource_type=None, datasource_id=None): """ Check if user can access a cached response from explore_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data = get_form_data()[0] datasource_id, datasource_type = get_datasource_info( datasource_id, datasource_type, form_data)
viz_obj = get_viz( datasource_type=datasource_type, datasource_id=datasource_id, form_data=form_data, force=False, ) security_manager.assert_datasource_permission(viz_obj.datasource)
csn_ccr
func (m *HTTPResponseProperties) Validate() error { if m == nil { return nil } { tmp := m.GetResponseCode() if v, ok := interface{}(tmp).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return HTTPResponsePropertiesValidationError{ field: "ResponseCode", reason: "embedded message failed validation", cause: err, } }
} } // no validation rules for ResponseHeadersBytes // no validation rules for ResponseBodyBytes // no validation rules for ResponseHeaders // no validation rules for ResponseTrailers // no validation rules for ResponseCodeDetails return nil }
csn_ccr
this format preprocessor is far from being full markdown, it is built to be usable for tipograph readme in the future, this may grow into full markdown support
function dummyMarkdown() { var codeBlock = /^```/; var quoteBlock = /^>/; var listBlock = /^\* /; var commentInline = '<!--.*-->'; var codeInline = '`.+`'; function split(content) { var pattern = new RegExp([commentInline, codeInline].join('|'), 'g'); var result = null; var last = 0; var output = []; while ((result = pattern.exec(content)) !== null) { output.push({ transform: true, content: content.slice(last, result.index)}); output.push({ transform: false, content: result[0]}); last = pattern.lastIndex; } output.push({ transform: true, content: content.slice(last)}); return output; } return function (input) { var output = []; var lines = input.split('\n'); for (var l = 0; l < lines.length; l++) { var line = lines[l]; var e; var content; if (codeBlock.test(line)) { e = l + 1; while (!codeBlock.test(lines[e])) { e++; } output.push({ transform: false, content: lines.slice(l, e + 1).join('\n') + '\n\n' }); l = e; } else if (quoteBlock.test(line)) { e = l + 1; while (quoteBlock.test(lines[e])) { e++; } content = [line].concat(lines.slice(l + 1, e).map(function (nextLine) { return nextLine.slice(2); })).join(' ') + '\n\n'; output = output.concat(split(content)); l = e - 1; } else if (listBlock.test(line)) { e = l + 1; while (lines[e] !== '') { if (!listBlock.test(lines[e])) { lines[e - 1] += ' ' + lines[e]; lines[e] = ''; } e++; } content = lines.slice(l, e).filter(function (line) { return line !== ''; }).join('\n') + '\n'; output = output.concat(split(content)); l = e - 1; } else if (line !== '') { e = l + 1; while (lines[e] !== '') { e++; } content = lines.slice(l, e).join(' ') + '\n\n'; output = output.concat(split(content)); l = e - 1; } } return output; }; }
csn
private void closeQuietly(Closeable c) { if (c != null) { try {
c.close(); } catch (Throwable t) { logger.warn("Error closing, ignoring", t); } } }
csn_ccr
Copies a file to a target directory
def copy_file_if_missing(file, to_directory) unless File.exists? File.join(to_directory, File.basename(file)) FileUtils.cp(file, to_directory) end end
csn
public static function loadFromPlainList($num, array $positions) { $rPositions = []; foreach ($positions as $pos) {
$rPositions[$pos->generated->column] = $pos; } return new self($num, $rPositions); }
csn_ccr
func NewCiliumEndpointInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredCiliumEndpointInformer(client, namespace, resyncPeriod, indexers, nil) }
csn_ccr
how to set axis range on graphs in python
def ylim(self, low, high, index=1): """Set yaxis limits. Parameters ---------- low : number high : number index : int, optional Returns ------- Chart """ self.layout['yaxis' + str(index)]['range'] = [low, high] return self
cosqa
def _check_unused_kwargs(self, kwargs): """ Call this at the end of call module to check if all the kwargs have been used. Assumes kwargs were extracted using pop. """ if len(kwargs.keys())
!= 0: unused = "" for k in kwargs.keys(): unused += "'%s', "%k if unused[-2:] == ", ": # get rid of trailing comma unused = unused[:-2] raise Exception('Unused keys in kwargs: %s'%unused)
csn_ccr
Iterate internal Routes array Provides a unified method for iterating the Routes array with PHP functions, 'next', 'prev', 'current', and 'end'. Returns the Route on the position that is desired, if no Route is found, false is returned. @param string $function Function name for array iteration @return \SlaxWeb\Router\Route|bool
protected function iterateRoutes(string $function) { if (($route = $function($this->routes)) !== false) { $this->currentRoute = $route; return $this->currentRoute; } return false; }
csn
Creates a local ssh key, if it doesn't exist already, and uploads it to Github.
def _github_create_ssh_key(cls): """Creates a local ssh key, if it doesn't exist already, and uploads it to Github.""" try: login = cls._user.login pkey_path = '{home}/.ssh/{keyname}'.format( home=os.path.expanduser('~'), keyname=settings.GITHUB_SSH_KEYNAME.format(login=login)) # generate ssh key only if it doesn't exist if not os.path.exists(pkey_path): ClHelper.run_command('ssh-keygen -t rsa -f {pkey_path}\ -N \"\" -C \"DevAssistant\"'. format(pkey_path=pkey_path)) try: ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path)) except exceptions.ClException: # ssh agent might not be running env = cls._start_ssh_agent() ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path), env=env) public_key = ClHelper.run_command('cat {pkey_path}.pub'.format(pkey_path=pkey_path)) cls._user.create_key("DevAssistant", public_key) except exceptions.ClException as e: msg = 'Couldn\'t create a new ssh key: {0}'.format(e) raise exceptions.CommandException(msg)
csn
Sets the metric name and tags of this batch. This method only need be called if there is a desire to reuse the data structure after the data has been flushed. This will reset all cached information in this data structure. @throws IllegalArgumentException if the metric name is empty or contains illegal characters or if the tags list is empty or one of the elements contains illegal characters.
@Override public void setSeries(final String metric, final Map<String, String> tags) { IncomingDataPoints.checkMetricAndTags(metric, tags); try { row_key = IncomingDataPoints.rowKeyTemplate(tsdb, metric, tags); RowKey.prefixKeyWithSalt(row_key); reset(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never happen", e); } }
csn
Process the event onGetGroupList and sets a formatted array of groups the user belongs to. @param string $phone The phone number (jid ) of the user @param array $groupArray Array with details of all groups user eitehr belongs to or owns. @return array|bool
public function processGroupArray($phone, $groupArray) { $formattedGroups = []; if (!empty($groupArray)) { foreach ($groupArray as $group) { $formattedGroups[] = ['name' => 'GROUP: '.$group['subject'], 'id' => $group['id']]; } $this->waGroupList = $formattedGroups; return true; } return false; }
csn
Returns the hue with the smallest difference.
function getHueDifference(value) { return hues.reduce(function (min, hue) { var diff = Math.abs(hue - value); if (diff < min) { return diff; } return min; }, Infinity); }
csn
public function totalCount() { if (!isset($this->parameters['conditions'])) { return count($this->value); } if (!$this->totalCount) { if (is_callable($this->totalCountCalculation)) { $this->totalCount = ($this->totalCountCalculation)(); } else {
$mongo = Entity::getInstance()->getDatabase(); $entity = $this->entityClass; $this->totalCount = $mongo->count($entity::getCollection(), $this->parameters['conditions']); } } return $this->totalCount; }
csn_ccr
configure the worker
function (services, callback) { var http = require('http'); var app = require('express')(); var server = http.createServer(app); // get remote services //var fakedb1 = services[0]; //var fakedb2 = services[1]; // all express-related stuff goes here, e.g. app.use(function (req, res) { res.end('Handled by PID = ' + process.pid); }); // all socket.io stuff goes here //var io = require('socket.io')(server); // don't do server.listen(...)! // just pass the server instance to the final async's callback callback(null, server); }
csn
func NewSubjectChecker(spec *authorizationapi.RoleBindingRestrictionSpec) (SubjectChecker, error) { switch { case spec.UserRestriction != nil: return NewUserSubjectChecker(spec.UserRestriction), nil case spec.GroupRestriction != nil: return NewGroupSubjectChecker(spec.GroupRestriction), nil case spec.ServiceAccountRestriction != nil:
return NewServiceAccountSubjectChecker(spec.ServiceAccountRestriction), nil } return nil, fmt.Errorf("invalid RoleBindingRestrictionSpec: %v", spec) }
csn_ccr
Finalize the block in FSDataset. @param dstNamespaceId the namespace id for dstBlock @param dstBlock the block that needs to be finalized @param dstBlockFile the block file for the block that has to be finalized @throws IOException
private void copyBlockLocalFinalize(int dstNamespaceId, Block dstBlock, File dstBlockFile) throws IOException { boolean inlineChecksum = Block.isInlineChecksumBlockFilename(dstBlockFile .getName()); long blkSize = 0; long fileSize = dstBlockFile.length(); lock.writeLock().lock(); try { DatanodeBlockInfo info = volumeMap.get(dstNamespaceId, dstBlock); if (info == null) { throw new IOException("Could not find information for " + dstBlock); } if (inlineChecksum) { blkSize = BlockInlineChecksumReader.getBlockSizeFromFileLength(fileSize, info.getChecksumType(), info.getBytesPerChecksum()); } else { blkSize = fileSize; } FSVolume dstVol = info.getBlockDataFile().getVolume(); // Finalize block on disk. File dest = dstVol.addBlock(dstNamespaceId, dstBlock, dstBlockFile, info.isInlineChecksum(), info.getChecksumType(), info.getBytesPerChecksum()); volumeMap.add(dstNamespaceId, dstBlock, new DatanodeBlockInfo(dstVol, dest, blkSize, true, inlineChecksum, info.getChecksumType(), info.getBytesPerChecksum(), false, 0)); volumeMap.removeOngoingCreates(dstNamespaceId, dstBlock); } finally { lock.writeLock().unlock(); } }
csn
def latch_config_variables(self): """Latch the current value of all config variables as python objects. This function will capture the current value of all config variables at the time that this method is called. It must be called after start() has been called so that any default values in the config variables have been properly set otherwise DataError will be thrown. Conceptually this method performs the operation that happens just before a tile executive hands control to the tile application firmware. It latches in the value of all config variables at that point in time. For convenience, this method does all necessary binary -> python native object conversion so that you just get python objects
back. Returns: dict: A dict of str -> object with the config variable values. The keys in the dict will be the name passed to `declare_config_variable`. The values will be the python objects that result from calling latch() on each config variable. Consult ConfigDescriptor.latch() for documentation on how that method works. """ return {desc.name: desc.latch() for desc in self._config_variables.values()}
csn_ccr
func NewProcessor(gamma float64, highQuality bool) *Processor { prc := new(Processor) gammaInv := 1 / gamma for i := range prc.vals { prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5) } if highQuality { prc.newDrawable = func(p image.Image) draw.Image {
return image.NewNRGBA64(p.Bounds()) } } else { prc.newDrawable = imageserver_image_internal.NewDrawable } return prc }
csn_ccr
def _ip_unnumbered_name(self, **kwargs): """Return the `ip unnumbered` donor name XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_name (str): The donor interface name (1, 2, etc) Returns: XML to be passed to the switch. Raises: None """
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_name' % kwargs['int_type'] ip_unnumbered_name = getattr(self._interface, method_name) config = ip_unnumbered_name(**kwargs) if kwargs['delete']: tag = 'ip-donor-interface-name' config.find('.//*%s' % tag).set('operation', 'delete') return config
csn_ccr
Information about current PHP reporting @return JBDump
public static function errors() { $result = array(); $result['error_reporting'] = error_reporting(); $errTypes = self::_getErrorTypes(); foreach ($errTypes as $errTypeKey => $errTypeName) { if ($result['error_reporting'] & $errTypeKey) { $result['show_types'][] = $errTypeName . ' (' . $errTypeKey . ')'; } } return self::i()->dump($result, '! errors info !'); }
csn
func (c *CheckSuite) GetBeforeSHA() string { if c == nil || c.BeforeSHA == nil {
return "" } return *c.BeforeSHA }
csn_ccr