query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
// matchPropColumn checks if the idxCol match one of columns in required property and return the matched index. // If no column is matched, return -1.
func matchPropColumn(prop *requiredProperty, matchedIdx int, idxCol *model.IndexColumn) int { if matchedIdx < prop.sortKeyLen { // When walking through the first sorKeyLen column, // we should make sure to match them as the columns order exactly. // So we must check the column in position of matchedIdx. propCo...
csn
Filters given comment for embedded code by a given keyword @param string $needle_raw @param string $comment @return string
public function parseComment($needle_raw, $comment = null) { if ($comment === null) { $comment = $this->parameters->get('comment'); } $needle_quoted = preg_quote($needle_raw); $pattern = sprintf('@\{(%1$s):%2$s\}(.+)\{\/(%1$s):%2$s\}@si', $this->getFormatter()->getComment...
csn
// NewBinaryEqualsFunc - returns new BinaryEquals function.
func NewBinaryEqualsFunc(key Key, values ...string) (Function, error) { sset := set.CreateStringSet(values...) if err := validateBinaryEqualsValues(binaryEquals, key, sset); err != nil { return nil, err } return &binaryEqualsFunc{key, sset}, nil }
csn
Search the parameters that were overridden during the parameters-merge phase. @return array Names of the overridden parameters.
private function searchOverridenParameters(array $parametersList): array { $parametersUsageCount = []; foreach ($parametersList as $list) { foreach ($list as $parameter => $_value) { if (!isset($parametersUsageCount[$parameter])) { $parametersUsageCou...
csn
Convert a node into a string in NRML format
def to_string(node): """ Convert a node into a string in NRML format """ with io.BytesIO() as f: write([node], f) return f.getvalue().decode('utf-8')
csn
Builds a list route object. @param Request $req @param Response $res @return ListModelsRoute
protected function getListRoute(Request $req, Response $res) { $route = new ListModelsRoute($req, $res); $route->setApp($this->app) ->setSerializer($this->getSerializer($req)); return $route; }
csn
sets an item from an array with dottet dimensions @param string $key @param mixed $value @param array $arr @return array
public static function set( $key, $value, &$arr ) { if ( strpos( $key, '.' ) === false ) { $arr[$key] = $value; } else { $kp = explode( '.', $key ); switch ( count( $kp ) ) { case 2: $arr[$kp[0]][$kp[1]] = $value; break; case 3: $arr[$kp[0]][$kp[1]][$kp[2]] = $value; bre...
csn
Create the MD5 digest of an input text. @param text the input text @return the hexadecimal representation of the MD5 digest
public static String getMD5Hash(String text) { MessageDigest md; byte[] md5hash = new byte[32]; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace()...
csn
Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviation...
def get_string_camel_patterns(cls, name, min_length=0): """ Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :retur...
csn
Compile route uri pattern regex @return Qlake\Routing\Route
public function compile() { //reset arrays $this->params = []; $this->paramNames = []; $this->conditions = []; $this->compiled = true; $uri = $this->normalizeUri($this->getUri()); // match patterns like /{param?:regex} // tested in https://regex101.com/r/gP6yH7 $regex = preg_replace_callback( ...
csn
removeNamedPolicy removes an authorization rule from the current named policy. @param ptype the policy type, can be "p", "p2", "p3", .. @param params the "p" policy rule. @return succeeds or not.
public boolean removeNamedPolicy(String ptype, String... params) { return removeNamedPolicy(ptype, Arrays.asList(params)); }
csn
Fail if first and second refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is_not(list1, list2) >>> assert_is_not(list1, list1) Traceback (most recent call last): ... AssertionError: both arguments refer to [5, 'foo'] The following msg_fmt arguments...
def assert_is_not(first, second, msg_fmt="{msg}"): """Fail if first and second refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is_not(list1, list2) >>> assert_is_not(list1, list1) Traceback (most recent call last): ... AssertionError: both argument...
csn
Detach the contact from the shapes.
function(){ var prev=this.s1Link.prev; var next=this.s1Link.next; if(prev!==null)prev.next=next; if(next!==null)next.prev=prev; if(this.shape1.contactLink==this.s1Link)this.shape1.contactLink=next; this.s1Link.prev=null; this.s1Link.next=null; this.s1Link....
csn
// GetDotOptions returns the dot components.
func (s Style) GetDotOptions() Style { return Style{ ClassName: s.ClassName, StrokeDashArray: nil, FillColor: s.DotColor, StrokeColor: s.DotColor, StrokeWidth: 1.0, } }
csn
// GetPresetByKeyName Get the Product_Package_Preset which matches the specified // preset key name
func GetPresetByKeyName( sess *session.Session, pkgID int, presetKeyName string, mask ...string, ) (datatypes.Product_Package_Preset, error) { objectMask := "id, name, keyName, description" if len(mask) > 0 { objectMask = mask[0] } service := services.GetProductPackageService(sess) // Get preset id prese...
csn
Run the configured audits with the specified audit_options. :param audit_options: Configuration for the audit :type audit_options: Config :rtype: Dict[str, str]
def run(audit_options): """Run the configured audits with the specified audit_options. :param audit_options: Configuration for the audit :type audit_options: Config :rtype: Dict[str, str] """ errors = {} results = {} for name, audit in sorted(_audits.items()): result_name = nam...
csn
Get special page names, as an associative array case folded alias => real name
function getSpecialPageAliases() { // Cache aliases because it may be slow to load them if ( is_null( $this->mExtendedSpecialPageAliases ) ) { // Initialise array $this->mExtendedSpecialPageAliases = self::$dataCache->getItem( $this->mCode, 'specialPageAliases' ); wfRunHooks( 'LanguageGetSpecialPageAli...
csn
Get Result. @param int $resultMode Result Mode DBInstance::FETCH_* @return mixed
public function getResult($resultMode = 0) { switch ($resultMode) { case self::FETCH_ARRAY: return $this->query->toArray(); break; case self::FETCH_JSON: $result = json_encode($this->query->toArray()); return $result; ...
csn
more likely, strategy should be part of configuration options directly when Config object is created!
def configure_relation case strategy when :ref_many has_many_for subject_class, :role, :through => join_key belongs_to_for join_model, subject_class belongs_to_for join_model, object_model has_many_for role, subject_class, :through => join_key ...
csn
List the overlays in the dataset.
def ls(dataset_uri): """ List the overlays in the dataset. """ dataset = dtoolcore.DataSet.from_uri(dataset_uri) for overlay_name in dataset.list_overlay_names(): click.secho(overlay_name)
csn
Make a snapshot of the current state to enable later reverting.
def snapshot { state: @state.root_hash, gas: gas_used, txs: @transactions, txcount: @transaction_count, refunds: refunds, suicides: suicides, suicides_size: suicides.size, logs: logs, logs_size: logs.size, journal: @journal, # pointer to refe...
csn
Determines whether the string contains an even number of double quote characters. @param string the given string @return true if contains even number of '"'
static boolean isEvenQuotes(String string) { // In principle, we could use the regex given by: // Pattern pEvenQuotes = Pattern.compile("([^\"]*\\\"[^\"]*\\\")*[^\"]*"); // We assume just counting the instances of double quotes is more efficient // but we haven't really tested that a...
csn
// NewVerifyChainCmd returns a new instance which can be used to issue a // verifychain JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
func NewVerifyChainCmd(checkLevel, checkDepth *int32) *VerifyChainCmd { return &VerifyChainCmd{ CheckLevel: checkLevel, CheckDepth: checkDepth, } }
csn
Set or get session key @param mixed $key @param mixed $value @return void
public static function key($key, $value = null) { if ($value == null) return $_SESSION[$key]; $_SESSION[$key] = $value; }
csn
Method to construct the equals expression for byte @param value the byte @return Expression
public Expression<Byte> eq(byte value) { String valueString = "'" + value + "'"; return new Expression<Byte>(this, Operation.eq, valueString); }
csn
set entries per page max 200
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...
csn
Check wether password 1 and password 2 are equivalent While ideally this would be done in clean, there is a chance a superclass could declare clean and forget to call super. We therefore opt to run this password mismatch check in password2 clean, but to show the error above password1 (a...
def clean_password2(self): """ Check wether password 1 and password 2 are equivalent While ideally this would be done in clean, there is a chance a superclass could declare clean and forget to call super. We therefore opt to run this password mismatch check in password2 ...
csn
This method initializes txtLicense @return javax.swing.JTextPane
private JTextPane getTxtLicense() { if (txtLicense == null) { txtLicense = new JTextPane(); txtLicense.setName("txtLicense"); txtLicense.setEditable(false); } return txtLicense; }
csn
Implements date string parsing adhering to RFC 6265.
def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]: """Implements date string parsing adhering to RFC 6265.""" if not date_str: return None found_time = False found_day = False found_month = False found_year = False hour = minute = se...
csn
Compute area as the sum of the mesh cells area values.
def get_area(self): """ Compute area as the sum of the mesh cells area values. """ mesh = self.mesh _, _, _, area = mesh.get_cell_dimensions() return numpy.sum(area)
csn
Creates new instance of \Google\Protobuf\MethodDescriptorProto @throws \InvalidArgumentException @return MethodDescriptorProto
public static function create() { switch (func_num_args()) { case 0: return new MethodDescriptorProto(); case 1: return new MethodDescriptorProto(func_get_arg(0)); case 2: return new MethodDescriptorProto(func_get_arg(0), func_get_arg(1)); case 3: return new MethodDescriptorProto(func_get...
csn
Return metadata for resource-specific actions, such as start, stop, unlink
def get_actions(self, request, view): """ Return metadata for resource-specific actions, such as start, stop, unlink """ metadata = OrderedDict() actions = self.get_resource_actions(view) resource = view.get_object() for action_name, action in actions.ite...
csn
Create roles, permissions and roles_permissions
private function generateRolesAndPermissions() { if( empty($this->aclData) ) { $this->error('empty roles and permissions in "generateRolesAndPermissions" method'); return; } foreach ( $this->aclData as $acl ) { $this->createPermissions($acl['acl']); ...
csn
Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time
def julian2sidereal(Jdate: float) -> float: """ Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time """ jdate = np.atleast_1d(Jdate) assert ...
csn
Return the object that was bound, or a new instance of the specified class if no value has been bound. @param type the type to create if no value was bound @return the value, if bound, otherwise a new instance of {@code type}
public T orElseCreate(Class<? extends T> type) { Assert.notNull(type, "Type must not be null"); return (this.value != null) ? this.value : BeanUtils.instantiateClass(type); }
csn
Select the specific vertex and fragment shader to use. The shader template is used to generate the sources for the vertex and fragment shader based on the vertex, material and light properties. This function may compile the shader if it does not already exist. @param context GVRContext @param rdata renderable entity ...
public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview) { String signature = getClass().getSimpleName(); GVRShaderManager shaderManager = context.getShaderManager(); GVRMaterial mtl = rdata.getMaterial(); synchronized (shaderManager) ...
csn
Reverses the order of all order clauses @param array $attributes Optional list of attributes which should be reversed @return SelectManager
function reverseOrder(array $attributes = null) { if ($attributes !== null) { $attributes = array_map('strval', $attributes); $orders = array_filter($this->getNodes()->orders, function($o) use ($attributes) { $expr = $o->getExpression(); $name = (stri...
csn
Build shellcoding files for the module.
def make_modules(self, groups, code_opts): """Build shellcoding files for the module.""" modules = [] for raw_module, raw_funcs in groups: module = raw_module[0].strip().strip(string.punctuation) funcs = [func.strip() for func in raw_funcs] args = [self.databa...
csn
Apply the filter values for a given model to the given rule. @param array $filter The filter rule to which the values shall get applied. @param ModelInterface $model The model to fetch the values from. @return array
public function parseFilter($filter, $model) { $this->guardProviderNames(null, $model); $applied = [ 'operation' => $filter['operation'], ]; if (isset($filter['local'])) { $applied['property'] = $filter['local']; } if (isset($filter['remote'...
csn
Run the SomaticSniper subgraph on the DNA bams. Optionally split the results into per-chromosome vcfs. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ_options: Dict of universal options used by almost all tool...
def run_somaticsniper(job, tumor_bam, normal_bam, univ_options, somaticsniper_options, split=True): """ Run the SomaticSniper subgraph on the DNA bams. Optionally split the results into per-chromosome vcfs. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict o...
csn
If this collection has already been initialized with an identical criteria, it returns the collection. Otherwise if this Person is new, it will return an empty collection; or if this Person has previously been saved, it will retrieve related PersonTeamLinks from storage. This method is protected by default in order to...
public function getPersonTeamLinksJoinTeam($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildPersonTeamLinkQuery::create(null, $criteria); $query->joinWith('Team', $joinBehavior); return $this->getPersonTeamLinks($query, $con); }
csn
Adjusts the desired number of connections that we will create to peers. Note that if there are already peers open and the new value is lower than the current number of peers, those connections will be terminated. Likewise if there aren't enough current connections to meet the new requested max size, some will be added.
public void setMaxConnections(int maxConnections) { int adjustment; lock.lock(); try { this.maxConnections = maxConnections; if (!isRunning()) return; } finally { lock.unlock(); } // We may now have too many or too few open connections....
csn
Given a list of numeric sequences, returns the corresponding strings
def convert_to_strings(self, sequences, sizes=None): """Given a list of numeric sequences, returns the corresponding strings""" strings = [] for x in xrange(len(sequences)): seq_len = sizes[x] if sizes is not None else len(sequences[x]) string = self._convert_to_string(se...
csn
Apply clipping to the features in a tile. The tile and its features should already be in map space. @param tile tile to put features in @param scale scale @param panOrigin When panning on the client, only this parameter changes. So we need to be aware of it as we calculate the maxScreenEnvelope. @throws GeomajasExcept...
public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException { log.debug("clipTile before {}", tile); List<InternalFeature> orgFeatures = tile.getFeatures(); tile.setFeatures(new ArrayList<InternalFeature>()); Geometry maxScreenBbox = null; // The tile's maximum bounds in...
csn
//Retrieve the player's details using the Steam API. The object needs to be saved after this.
func (player *Player) UpdatePlayerInfo() error { if config.Constants.SteamDevAPIKey == "" { return nil } defer player.Save() player.SetExternalLinks() scraper.SetSteamApiKey(config.Constants.SteamDevAPIKey) p, _ := GetPlayerBySteamID(player.SteamID) if p != nil { *player = *p } playerInfo, infoErr := s...
csn
// Error implements the error interface for NotDirError
func (e NotDirError) Error() string { return fmt.Sprintf("%s is not a directory (folder %s)", e.path, e.path.Tlf) }
csn
Accessor method used to retrieve an Duration object representing the contents of an individual field. If the field does not exist in the record, null is returned. @param field the index number of the field to be retrieved @return the value of the required field @throws MPXJException normally thrown when parsing fails
public Duration getDuration(int field) throws MPXJException { Duration result; if ((field < m_fields.length) && (m_fields[field].length() != 0)) { result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale); } else { res...
csn
Return dict with the all base information about the instance.
def to_dict(self): """ Return dict with the all base information about the instance. """ data = { "name": self.name, "canEdit": self.can_edit, "canCreate": self.can_create, "canDelete": self.can_delete, "perPage": self.per_page,...
csn
Returns the sections for a term @param id @param [Hash] opts the optional parameters @option opts [Integer] :limit @option opts [String] :starting_after @option opts [String] :ending_before @return [SectionsResponse]
def get_sections_for_term(id, opts = {}) data, _status_code, _headers = get_sections_for_term_with_http_info(id, opts) return data end
csn
Create strength of connection matrixfrom a function applied to relaxation vectors.
def distance_measure_common(A, func, alpha, R, k, epsilon): """Create strength of connection matrixfrom a function applied to relaxation vectors.""" # create test vectors x = relaxation_vectors(A, R, k, alpha) # apply distance measure function to vectors d = func(x) # drop distances to self ...
csn
set the args and options.
protected function setParams() { $this->params(); // foreach ($this->params as $key => $value) { $cont = $this->strip($value); // if (Strings::length($cont) > 2) { if ($cont[0] == '-' && $cont[1] == '-') { $this->setOpti...
csn
The client already registered for emails on this pad so notify the UI
function showAlreadyRegistered(type){ if (type == "malformedEmail") { var msg = window._('ep_email_notifications.msgEmailMalformed'); } else if (type == "alreadyRegistered") { var msg = window._('ep_email_notifications.msgAlreadySubscr'); } else { var msg = window._('ep_email_notifications.msgUnknownE...
csn
Atomically deletes documents matching the provided delTerm and adds a block of documents with sequentially assigned document IDs, such that an external reader will see all or none of the documents. @param aDelTerm the term to identify the document(s) to be deleted. May be <code>null</code>. @param aDocs the documents ...
@MustBeLocked (ELockType.WRITE) public void updateDocuments (@Nullable final Term aDelTerm, @Nonnull final Iterable <? extends Iterable <? extends IndexableField>> aDocs) throws IOException { long nSeqNum; if (false) { // Delete and than add nSeqNum = _getWrite...
csn
Run the visitor through the directory tree @overload run @overload run(dirname) @param [String] dirname @yield define TreeNodeVisitor @overload run(tree_node_visitor) @param [TreeNodeVisitor] @yield define TreeNodeVisitor @overload run(dirname, tree_node_visitor) @param [String] dirname @param...
def run(dirname = nil, tree_node_visitor = nil, &block) # # args detection # if dirname and dirname.respond_to?(:enter_node) tree_node_visitor = dirname dirname = nil end # # check dirname # if @dirname.nil? and dirname.nil? raise...
csn
Find a customer. @param string $moip_id @return \Moip\Resource\Customer|stdClass
public function get($moip_id) { return $this->getByPath(sprintf('/%s/%s/%s', MoipResource::VERSION, self::PATH, $moip_id)); }
csn
Return a fully-qualified model string.
def model_path(cls, project, location, model): """Return a fully-qualified model string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/models/{model}", project=project, location=location, model=model, )
csn
// VolumesFromServices creates a new Volumes struct based on volumes configurations and // services configuration. If a volume is defined but not used by any service, it will return // an error along the Volumes.
func VolumesFromServices(cli client.VolumeAPIClient, projectName string, volumeConfigs map[string]*config.VolumeConfig, services *config.ServiceConfigs, volumeEnabled bool) (*Volumes, error) { var err error volumes := make([]*Volume, 0, len(volumeConfigs)) for name, config := range volumeConfigs { volume := NewVol...
csn
// sendDone is used to signal the end
func (qs *queryResponseStream) sendDone() error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordDone, } return qs.client.Send(&header, &rec) }
csn
Converts string from camelCase to kebab-case. @param {string} string string to convert @returns {string} converted string
function camelToKebab( string ) { return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "-" + match.toLocaleLowerCase() ); }
csn
Export the list of models to be rendered. @param renderer_base $output @return string
public function export_for_template(\renderer_base $output) { $components = []; foreach ($this->models as $componentname => $modelslist) { $component = [ 'name' => $this->component_name($componentname), 'component' => $componentname, 'models'...
csn
// OnUserBind method should be called when a user binds a session in remote servers
func (u *UniqueSession) OnUserBind(uid, fid string) { if u.server.ID == fid { return } oldSession := session.GetSessionByUID(uid) if oldSession != nil { // TODO: it would be nice to set this correctly oldSession.Kick(context.Background()) } }
csn
// Defaults sets default configuration options on Put structs
func Defaults(puts []config.Put) error { for i := range puts { defaults(&puts[i]) } return nil }
csn
Check the difference between predictions from MXNet and CoreML.
def check_error(model, path, shapes, output = 'softmax_output', verbose = True): """ Check the difference between predictions from MXNet and CoreML. """ coreml_model = _coremltools.models.MLModel(path) input_data = {} input_data_copy = {} for ip in shapes: input_data[ip] = _np.random...
csn
Make view factory for a match object @param {Match} match @param {Object} props @returns {ReactComponent}
function makeViewFactoryForMatch(match) { var views = {}; for (var i = match.activeTrace.length - 1; i >= 0; i--) { var step = match.activeTrace[i]; var stepProps = getStepProps(step); views = merge(views, collectSubViews(stepProps, views)); if (step.route.view !== undefined) { return makeV...
csn
Compiles an expression node and into a PHP expression. @param Node $node the expression node to compile @return string
protected function compileExpression(Node $node) { $code = $node->escaped ? 'htmlentities(%s, \\ENT_QUOTES, \''.$this->options['escape_charset'].'\')' : '%s'; $value = rtrim(trim($node->value), ';'); if ($this->isVariable($value) && !$node->unchecked) $value = "isset({$value})...
csn
Log an error or print in stdout if no logger.
def log_error(self, msg, *args): """Log an error or print in stdout if no logger.""" if self._logger is not None: self._logger.error(msg, *args) else: print(msg % args)
csn
Get a ServerEndpoint. @param resource_group_name [String] The name of the resource group. The name is case insensitive. @param storage_sync_service_name [String] Name of Storage Sync Service resource. @param sync_group_name [String] Name of Sync Group resource. @param server_endpoint_name [String] Name of Server...
def get_with_http_info(resource_group_name, storage_sync_service_name, sync_group_name, server_endpoint_name, custom_headers:nil) get_async(resource_group_name, storage_sync_service_name, sync_group_name, server_endpoint_name, custom_headers:custom_headers).value! end
csn
Watch napalm function and fire events.
def beacon(config): ''' Watch napalm function and fire events. ''' log.debug('Executing napalm beacon with config:') log.debug(config) ret = [] for mod in config: if not mod: continue event = {} fun = mod.keys()[0] fun_cfg = mod.values()[0] ...
csn
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RepoChartSource.
func (in *RepoChartSource) DeepCopy() *RepoChartSource { if in == nil { return nil } out := new(RepoChartSource) in.DeepCopyInto(out) return out }
csn
Calculate the pairwise distances for each sample. @param \Rubix\Tensor\Matrix $samples @return \Rubix\Tensor\Matrix
protected function pairwiseDistances(Matrix $samples) : Matrix { $distances = []; foreach ($samples as $a) { $temp = []; foreach ($samples as $b) { $temp[] = $this->kernel->compute($a, $b); } $distances[] = $temp; } ...
csn
processes a payload. @param $payload @return mixed the payload
final public function process($payload) { $payload = $this->processor->processStack($payload, $this->stack); if ( $this->next instanceof PipeChainInterface ) { $payload = $this->next->process($payload); } return $payload; }
csn
Lists your available Segments using the provided names @param string $apikey ApiKey that gives you access to our SMTP and HTTP API's. @param array<string> $segmentNames Names of segments you want to load. Will load all contacts if left empty or the 'All Contacts' name has been provided @param bool $includeHistory True:...
public function LoadByName($segmentNames, $includeHistory = false, $from = null, $to = null) { return $this->sendRequest('segment/loadbyname', array( 'segmentNames' => (count($segmentNames) === 0) ? null : join(';', $segmentNames), 'includeHistory' => $includeHistory, ...
csn
Set the list of source directories.
void setSourceBaseList(Iterable<String> sourceBaseList) { for (String repos : sourceBaseList) { if (repos.endsWith(".zip") || repos.endsWith(".jar") || repos.endsWith(".z0p.gz")) { // Zip or jar archive try { if (repos.startsWith("http:") || repos....
csn
Construct the response header. The return value is a list containing the whole response header, with each line as a list element.
def write(self): """Construct the response header. The return value is a list containing the whole response header, with each line as a list element. """ slist = [] slist.append('{}/{}.{} {} {}'.format( self.protocol, self...
csn
// Register a command. It can't have been registered before. Safe to call on a // running server.
func (s *Server) Register(cmd string, f Cmd) error { s.mu.Lock() defer s.mu.Unlock() cmd = strings.ToUpper(cmd) if _, ok := s.cmds[cmd]; ok { return fmt.Errorf("command already registered: %s", cmd) } s.cmds[cmd] = f return nil }
csn
Extracts subnets and security group ids as lists from a VpcConfig dict Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values Returns: Tuple of lists as (subnets, security...
def from_dict(vpc_config, do_sanitize=False): """ Extracts subnets and security group ids as lists from a VpcConfig dict Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values ...
csn
Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend.
def bures_distance(rho0: Density, rho1: Density) -> float: """Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend. """ fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np...
csn
Add the given errors to our internal errors list ====Examples response = remote_call(:action_that_returns_errors, { :stuff => 'foo' }) add_errors(response.errors)
def add_errors(errors) errors.each do |error| if error.respond_to?(:message) self.errors.add(error.field, error.message) elsif error.respond_to?(:messages) error.messages.each do |message| self.errors.add(error.field, message) end end end ...
csn
Process logstore_standard_log entries. This method proceeds to read, complete, remap and, finally, discard or save every log entry. @param array() $data log entry.
public function process_logstore_standard_log($data) { global $DB; $data = $this->process_log($data, get_config('logstore_standard', 'jsonformat')); if ($data) { $DB->insert_record('logstore_standard_log', $data); } }
csn
Given a list of face indexes find the outline of those faces and return it as a Path3D. The outline is defined here as every edge which is only included by a single triangle. Note that this implies a non-watertight mesh as the outline of a watertight mesh is an empty path. ...
def outline(self, face_ids=None, **kwargs): """ Given a list of face indexes find the outline of those faces and return it as a Path3D. The outline is defined here as every edge which is only included by a single triangle. Note that this implies a non-watertight mesh as...
csn
// GetAllAWSElasticsearchDomainResources retrieves all AWSElasticsearchDomain items from an AWS CloudFormation template
func (t *Template) GetAllAWSElasticsearchDomainResources() map[string]*resources.AWSElasticsearchDomain { results := map[string]*resources.AWSElasticsearchDomain{} for name, untyped := range t.Resources { switch resource := untyped.(type) { case *resources.AWSElasticsearchDomain: results[name] = resource } ...
csn
Render the having part of a query. Parameters ---------- having_conditions : list A ``list`` of ``dict``s to filter the rows Returns ------- str A string that represents the "having" part of a query. See Also -------- render_query : Further clarification of `condit...
def _render_having(having_conditions): """Render the having part of a query. Parameters ---------- having_conditions : list A ``list`` of ``dict``s to filter the rows Returns ------- str A string that represents the "having" part of a query. See Also -------- r...
csn
Creates a new user account by registering a password to the user.
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); SecurityListener.fireUserCreated(user.getId()); return user; }
csn
Registers the service in the IoC Container
public function register() { // Bind the returned class to the namespace 'Ooglee\Domain\Contracts\IHashingService' $this->app->singleton('Ooglee\Domain\Contracts\IHashingService', function($app) { //$hasher = $this->app['config']['ioc.app.hasher']; $hasher = \Confi...
csn
getter for preferredTerm - gets The preferred term associated with the corresponding ontology class. @generated @return value of the feature
public String getPreferredTerm() { if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_preferredTerm == null) jcasType.jcas.throwFeatMissing("preferredTerm", "de.julielab.jules.types.OntClassMention"); return jcasType.ll_cas.ll_getStringValue(addr, ((OntClassMention_Type)jcasTyp...
csn
Perform a WVA web services request and return the raw response object :param method: The HTTP method to use when making this request :param uri: The path past /ws to request. That is, the path requested for a relpath of `a/b/c` would be `/ws/a/b/c`. :raises WVAHttpSocketError: if t...
def raw_request(self, method, uri, **kwargs): """Perform a WVA web services request and return the raw response object :param method: The HTTP method to use when making this request :param uri: The path past /ws to request. That is, the path requested for a relpath of `a/b/c` would...
csn
// ensureOplogPermissions adds a special role to the admin user, this role // is required by mongorestore when doing oplogreplay.
func (md *mongoRestorer32) ensureOplogPermissions(dialInfo *mgo.DialInfo) error { s, err := md.newMongoSession(dialInfo) if err != nil { return errors.Trace(err) } defer s.Close() roles := bson.D{ {"createRole", "oploger"}, {"privileges", []bson.D{ { {"resource", bson.M{"anyResource": true}}, {"a...
csn
Write a bytestring to an address in memory on a neigbouring chip. .. warning:: This function is intended for low-level debug use only and is not optimised for performance nor intended for more general use. This method instructs a monitor processor to send 'POKE' neares...
def write_across_link(self, address, data, x, y, link): """Write a bytestring to an address in memory on a neigbouring chip. .. warning:: This function is intended for low-level debug use only and is not optimised for performance nor intended for more general use. This...
csn
rotate one or multiple grayscale or color images 90 degrees
def rot90(img): ''' rotate one or multiple grayscale or color images 90 degrees ''' s = img.shape if len(s) == 3: if s[2] in (3, 4): # color image out = np.empty((s[1], s[0], s[2]), dtype=img.dtype) for i in range(s[2]): out[:, :, i] = np.rot...
csn
Return the count of public keys in the list and embedded.
def _get_public_key_count(self): """Return the count of public keys in the list and embedded.""" index = len(self._public_keys) for authentication in self._authentications: if authentication.is_public_key(): index += 1 return index
csn
Retrieve the calendar used internally for timephased baseline calculation. @return baseline calendar
public ProjectCalendar getBaselineCalendar() { // // Attempt to locate the calendar normally used by baselines // If this isn't present, fall back to using the default // project calendar. // ProjectCalendar result = getCalendarByName("Used for Microsoft Project 98 Baseline Calend...
csn
Called when a window resize signal is detected Resets the scroll window
def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument """ Called when a window resize signal is detected Resets the scroll window """ # Make sure only one resize handler is running try: assert self.resize_lock except Assertion...
csn
// Retrieve The maximum number of IOPs selected for this volume.
func (r Network_Storage) GetIops() (resp string, err error) { err = r.Session.DoRequest("SoftLayer_Network_Storage", "getIops", nil, &r.Options, &resp) return }
csn
THE MAGICAL Z SEGMENT
def add_z(bookings) data3 = '0256' data3 += 'Z' sum = 0 bookings.each do |b| sum += b.value.divmod(100)[0] end data3 += '%015i' % sum data3 += '%015i' % bookings.count data3 += '%0221s' % '' raise "DTAUS: Längenfehler Z (#{data3.size} <> 256)\n" if dat...
csn
Return list of values in db >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.items() [('l0', ['1', '2', '3', '4'])] >>> dc.clear() :return: list of tuple :rtype: list
def values(self): """Return list of values in db >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.items() [('l0', ['1', '2', '3', '4'])] >>> dc.clear() :return: list of tuple :rtype: list """ logger.debug('call values') retu...
csn
Concatenate two or more meshes. Parameters ---------- a: Trimesh object, or list of such b: Trimesh object, or list of such Returns ---------- result: Trimesh object containing concatenated mesh
def concatenate(a, b=None): """ Concatenate two or more meshes. Parameters ---------- a: Trimesh object, or list of such b: Trimesh object, or list of such Returns ---------- result: Trimesh object containing concatenated mesh """ if b is None: b = [] # stack me...
csn
Returns boolean whether the objects is flagged by a user. :param User user: Optional user filter :param int status: Optional status filter :return:
def is_flagged(self, user=None, status=None): """Returns boolean whether the objects is flagged by a user. :param User user: Optional user filter :param int status: Optional status filter :return: """ filter_kwargs = { 'content_type': ContentType.objects.get_...
csn
// SetExpiryTime sets the ExpiryTime field's value.
func (s *AddAttachmentsToSetOutput) SetExpiryTime(v string) *AddAttachmentsToSetOutput { s.ExpiryTime = &v return s }
csn
Returns the last execution time for the job @return [String] with the job's last time
def last_time execution_time = SidekiqScheduler::RedisManager.get_job_last_time(name) relative_time(Time.parse(execution_time)) if execution_time end
csn
Put the document into the 'before' state.
def reverseCommit(self): """ Put the document into the 'before' state. """ # Put the document into the 'before' state. self.baseClass.setText(self.textBefore) self.qteWidget.SCISetStylingEx(0, 0, self.styleBefore)
csn