query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
// Tracef prints to the standard logger with the Trace level.
func (me *Logger) Tracef(format string, v ...interface{}) { me.printf(Ptrace, format, v...) }
csn
public Map<Artifact, Dependency> resolve(BomConfig config) throws Exception { Map<Artifact, Dependency> dependencies = new LinkedHashMap<Artifact, Dependency>(); if (config != null && config.getImports() != null) { for (BomImport bom : config.getImports()) { Map<Artifact, Dep...
// order is important for imported boms dependencies.put(e.getKey(), e.getValue()); } } } } return dependencies; }
csn_ccr
def edit_link(self, inst): """ Edit link for the change view """ if not inst.is_active: return u'--' update_url = reverse('admin:{}_{}_add'.format(self.model._meta.app_label, self.model._meta.model_name))
update_url += "?source={}".format(inst.pk) return u'<a href="{}">{}</a>'.format(update_url, _('Update'))
csn_ccr
// RunWait runs the waiting logic
func (o *WaitOptions) RunWait() error { visitCount := 0 err := o.ResourceFinder.Do().Visit(func(info *resource.Info, err error) error { if err != nil { return err } visitCount++ finalObject, success, err := o.ConditionFn(info, o) if success { o.Printer.PrintObj(finalObject, o.Out) return nil } ...
csn
python dictonary to string to dict
def str_dict(some_dict): """Convert dict of ascii str/unicode to dict of str, if necessary""" return {str(k): str(v) for k, v in some_dict.items()}
cosqa
// Run runs the http command.
func (m *Main) Run() error { src, err := NewJSONSource(WithAddr(m.Bind)) if err != nil { return errors.Wrap(err, "getting json source") } if m.TranslatorDir == "" { m.TranslatorDir, err = ioutil.TempDir("", "pdk") if err != nil { return errors.Wrap(err, "creating temp directory") } } log.Println("lis...
csn
Unclip all clipped elements and remove itself
function() { // unclip all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unclip() this.targets = [] // remove clipPath from parent this.parent().removeElement(this) return this }
csn
Monkey-patch pyopengl to fix a bug in glBufferSubData.
def _patch(): """ Monkey-patch pyopengl to fix a bug in glBufferSubData. """ import sys from OpenGL import GL if sys.version_info > (3,): buffersubdatafunc = GL.glBufferSubData if hasattr(buffersubdatafunc, 'wrapperFunction'): buffersubdatafunc = buffersubdatafunc.wrapperFunc...
csn
def translate(self, value): """Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum. """ if self._check_if_already_proper(value): return value try:
return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value ))
csn_ccr
Wait until the "until" condition returns true or time runs out. @param message the failure message @param timeoutInMilliseconds the amount of time to wait before giving up @param intervalInMilliseconds the interval to pause between checking "until" @throws WaitTimedOutException if "until" doesn't return true until the...
public void wait(String message, long timeoutInMilliseconds, long intervalInMilliseconds) { long start = System.currentTimeMillis(); long end = start + timeoutInMilliseconds; while (System.currentTimeMillis() < end) { if (until()) return; try { Thread.sleep(intervalInMilliseconds); ...
csn
Updates size of given CSS rule @param {TextEditor} editor @param {Node} srcProp @param {Number} width @param {Number} height
function updateCSSNode(editor, srcProp, width, height) { const rule = srcProp.parent; const widthProp = getProperty(rule, 'width'); const heightProp = getProperty(rule, 'height'); // Detect formatting const separator = srcProp.separator || ': '; const before = getBefore(editor, srcProp); const insertOpt = { aut...
csn
public boolean isEnabled(String featurePath) { checkArgument(!Strings.isNullOrEmpty(featurePath));
return config.getConfig(featurePath).getBoolean("enabled"); }
csn_ccr
private function determineGitRoot($path) { // @codingStandardsIgnoreStart while (\strlen($path) > 1) { // @codingStandardsIgnoreEnd if (\is_dir($path . DIRECTORY_SEPARATOR . '.git')) { return $path;
} $path = \dirname($path); } throw new \RuntimeException('Could not determine git root, starting from ' . \func_get_arg(0)); }
csn_ccr
Create a Cache Entry, from the Zid string and the CSV representation of HEX RAW data and phone number @param key ZID string @param value CSV of HEX raw data and phone number, for example "E84FE07E054660FFF5CF90B4,+3943332233323" @return a new ZRTP cache entry
public static ZrtpCacheEntry fromString(String key, String value) { String data = null; String number = null; int sep = value.indexOf(','); if (sep > 0) { data = value.substring(0, sep); number = value.substring(sep + 1); } else { data = value; number = ""; } byte[] buffer = new byt...
csn
// serveListener serves a listener for local and non local connections.
func (m *Manager) serveListener(ctx context.Context, lCh <-chan net.Listener) { var l net.Listener select { case l = <-lCh: case <-ctx.Done(): return } ctx = log.WithLogger(ctx, log.G(ctx).WithFields( logrus.Fields{ "proto": l.Addr().Network(), "addr": l.Addr().String(), })) if _, ok := l.(*net.TCPL...
csn
public EntityGraph getDefaultGraph(final Session session) { if (this.defaultExpandGraph == null) { final EntityGraph<?> graph = session.createEntityGraph(clazz); populateGraph(graph, getEagerFetch());
this.defaultExpandGraph = graph; return graph; } else { return this.defaultExpandGraph; } }
csn_ccr
Mobile Display Keystrokes Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it? Well, here you have to calculate how much keystrokes you have to do for a specific word. This is the layout: Return the amount of keystrokes of input str (! only letters, digits ...
def mobile_keyboard(s): lookup = { c: i for s in "1,2abc,3def,4ghi,5jkl,6mno,7pqrs,8tuv,9wxyz,*,0,#".split(",") for i, c in enumerate(s, start=1) } return sum(lookup[c] for c in s)
apps
Create a new project model and use the project store to save it. @param string $title @param string $type @param string $reference @param array $options @return \PHPCI\Model\Project
public function createProject($title, $type, $reference, $options = array()) { // Create base project and use updateProject() to set its properties: $project = new Project(); return $this->updateProject($project, $title, $type, $reference, $options); }
csn
Allows conversion of arrays into a mutable List @param array an array @return the array as a List
public static List primitiveArrayToList(Object array) { int size = Array.getLength(array); List list = new ArrayList(size); for (int i = 0; i < size; i++) { Object item = Array.get(array, i); if (item != null && item.getClass().isArray() && item.getClass().getComponentTyp...
csn
Handles the next debug event. @see: L{cont}, L{dispatch}, L{wait}, L{stop} @raise WindowsError: Raises an exception on error. If the wait operation causes an error, debugging is stopped (meaning all debugees are either killed or detached from). If the event dispat...
def next(self): """ Handles the next debug event. @see: L{cont}, L{dispatch}, L{wait}, L{stop} @raise WindowsError: Raises an exception on error. If the wait operation causes an error, debugging is stopped (meaning all debugees are either killed or detached fro...
csn
Create a new editable document that is a copy of the supplied document. @param original the original document @return the editable document; never null
public static EditableDocument newDocument( Document original ) { BasicDocument newDoc = new BasicDocument(); newDoc.putAll(original); return new DocumentEditor(newDoc, DEFAULT_FACTORY); }
csn
WORDFILE = 'unixdict.txt' MINLEN = 6 class Trie(object): class Node(object): def __init__(self, char='\0', parent=None): self.children = {} self.char = char self.final = False self.parent = parent def descend(self, char, ext...
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; ...
codetrans_contest
// String returns an easy way to visualize what you have in your constructors.
func (c *Constructors) String() string { var s string for k := range *c { s += k.String() + "=>" + "(func() interface {})" + "\t" } return s }
csn
@SuppressWarnings("unchecked") // If a.equals(b) then a and b have the same type. public synchronized <T> T intern(T value) { Preconditions.checkNotNull(value); // Use a pseudo-random number generator to mix up the high and low bits of the hash code. Random generator = new java.util.Random(value.hashCode...
rehashIfNeeded(); return value; } if (candidate.equals(value)) { Preconditions.checkArgument( value.getClass() == candidate.getClass(), "Interned objects are equals() but different classes: %s and %s", value, candidate); return (T...
csn_ccr
Sets or updates an Attribute instance's properties. @method setAttributeConfig @param {String} key The attribute's name. @param {Object} map A key-value map of attribute properties @param {Boolean} init Whether or not this should become the intial config.
function(key, map, init) { this._configs = this._configs || {}; map = map || {}; if (!this._configs[key]) { map.name = key; this._configs[key] = this.createAttribute(map); } else { this._configs[key].configure(map, init); ...
csn
public function canBeAnswered() { $countInThread = Comment::find() ->where(['thread' => $this->thread, 'user_id' => Yii::$app->user->id]) ->count(); return !Yii::$app->user->isGuest && $this->last && // this is a last comment in a thread
Yii::$app->user->identity->group == User::GROUP_COMMENTATOR && // you are a commentator $this->user_id != Yii::$app->user->id && // last comment not yours $countInThread > 0; // you begin this thread }
csn_ccr
// ToV3Resource converts a sharedaction Resource to V3 Resource format
func (r Resource) ToV3Resource() V3Resource { return V3Resource{ FilePath: r.Filename, Mode: r.Mode, Checksum: ccv3.Checksum{Value: r.SHA1}, SizeInBytes: r.Size, } }
csn
python most beautiful string in the world
def beautify(string, *args, **kwargs): """ Convenient interface to the ecstasy package. Arguments: string (str): The string to beautify with ecstasy. args (list): The positional arguments. kwargs (dict): The keyword ('always') arguments. """ parser = Parser(args, kwargs) return parser.beautify(string...
cosqa
function _normaliseExt(ext) { // we don't use '.' in our extension info... but some might leak in here and there ext =
(ext||'').trim(); if (ext.length && ext[0]=='.') return ext.substr(1); return ext; }
csn_ccr
Turn mongoose model to graffiti model @method getModel @param {Object} model Mongoose model @return {Object} graffiti model
function getModel(model) { const schemaPaths = model.schema.paths; const name = model.modelName; const fields = extractPaths(schemaPaths, { name }); return { name, fields, model }; }
csn
function(){ var args = Array.prototype.slice.call(arguments); Backbone.View.prototype.undelegateEvents.apply(this, args);
Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents")); Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents")); }
csn_ccr
def build_spotify_api(): """Build the Spotify API for future use""" data = datatools.get_data() if "spotify_client_id" not in data["discord"]["keys"]: logger.warning("No API key found with name 'spotify_client_id'") logger.info("Please add your Spotify client id with name 'spotify_client_id'...
try: global spclient client_credentials_manager = SpotifyClientCredentials( data["discord"]["keys"]["spotify_client_id"], data["discord"]["keys"]["spotify_client_secret"]) spclient = spotipy.Spotify(client_credentials_manager=client_credentials_manager) ...
csn_ccr
Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0.
def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc): """Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0. """ self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc) self.set_distributed_assembled_values(a_loc)
csn
public function getData() { $systemInformation = []; $systemInformation['newup_version'] = Application::VERSION;
return $this->dataArray + $systemInformation + $this->collectData(); }
csn_ccr
private void decreaseComponentLevelMarkedForDeletion() { //The common case is this co if (!_componentsMarkedForDeletion.get(_deletionLevel).isEmpty()) {
_componentsMarkedForDeletion.get(_deletionLevel).clear(); } _deletionLevel--; }
csn_ccr
function(parent, app) { this.use(middleware.sanitizeHost(app)); this.use(middleware.bodyParser());
this.use(middleware.cookieParser()); this.use(middleware.fragmentRedirect()); }
csn_ccr
public function setPluginLoader($type, $loader) { $type = $this->_validateLoaderType($type); if (is_string($loader)) { if (!class_exists($loader)) { Zend_Loader::loadClass($loader); } $loader = new $loader(); } elseif (!is_object($l...
Zend_Loader_PluginLoader) { throw new Zend_Http_UserAgent_Exception(sprintf( 'Expected an object extending Zend_Loader_PluginLoader; received %s', get_class($loader) )); } $basePrefix = 'Zend_Http_UserAgent_'; $basePath = 'Zend/Http/Us...
csn_ccr
Get template list :call-seq: templates -> Hash Return a Hash of all templates Example: templates Example return: { 'ubuntu-10.04-standard_10.04-4_i386' => { 'format' => 'tgz', 'content' => 'vztmpl', 'volid' => 'local:vztmpl/ubuntu-10.04-standard_10.04-4_i386.tar.gz', ...
def templates data = http_action_get "nodes/#{@node}/storage/local/content" template_list = {} data.each do |ve| name = ve['volid'].gsub(%r{local:vztmpl\/(.*).tar.gz}, '\1') template_list[name] = ve end template_list end
csn
Load the contents of meta_file and the corresponding data. If fields containing Personally Identifiable Information are detected in the metadata they are anonymized before asign them into `table_dict`. Args: base_dir(str): Root folder of the dataset files. Returns: ...
def _get_tables(self, base_dir): """Load the contents of meta_file and the corresponding data. If fields containing Personally Identifiable Information are detected in the metadata they are anonymized before asign them into `table_dict`. Args: base_dir(str): Root folder of ...
csn
Calculate the column widths @param array $rows The rows on which the columns width will be calculated on. @return array
protected function _calculateWidths($rows) { $widths = []; foreach ($rows as $line) { foreach (array_values($line) as $k => $v) { $columnLength = $this->_cellWidth($v); if ($columnLength >= (isset($widths[$k]) ? $widths[$k] : 0)) { $wid...
csn
// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordUntilSeparator(sep)] }
csn
function getSuiteData (suite) { var suiteData = { description : suite.description, durationSec : 0, specs: [], suites: [], passed: true }, specs = suite.specs(), suites = suite.suites(), ...
passed : specs[i].results().passedCount === specs[i].results().totalCount, results : specs[i].results() }; suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed; suiteData.durationSec += suiteData.specs[i].durationSec; } //...
csn_ccr
Create an ARRAY UNode with the given node name. @param name Name for new ARRAY node. @return New ARRAY UNode.
public static UNode createArrayNode(String name) { return new UNode(name, NodeType.ARRAY, null, false, ""); }
csn
Adding value dimensions not currently supported by iris interface. Adding key dimensions not possible on dense interfaces.
def add_dimension(cls, columns, dimension, dim_pos, values, vdim): """ Adding value dimensions not currently supported by iris interface. Adding key dimensions not possible on dense interfaces. """ if not vdim: raise Exception("Cannot add key dimension to a dense repr...
csn
def union(geom = nil) if geom check_geometry(geom) cast_geometry_ptr(FFIGeos.GEOSUnion_r(Geos.current_handle_pointer, ptr, geom.ptr), srid_copy: pick_srid_from_geoms(srid, geom.srid)) else
if respond_to?(:unary_union) unary_union else union_cascaded end end end
csn_ccr
Locks the specified version.
def lock_version(self, service_id, version_number): """Locks the specified version.""" content = self._fetch("/service/%s/version/%d/lock" % (service_id, version_number)) return self._status(content)
csn
Fire this when the sound is ready to play to begin Web Audio playback.
function() { self._playLock = false; setParams(); self._refreshBuffer(sound); // Setup the playback params. var vol = (sound._muted || self._muted) ? 0 : sound._volume; node.gain.setValueAtTime(vol, Howler.ctx.currentTime); sound._playStart = Howler...
csn
Convert a config array to a Config object with the correct fallback. @param array $config @return Config
protected function prepareConfig(array $config) { $config = new Config($config); $config->setFallback($this->getConfig()); return $config; }
csn
Send the register payload.
def _send_register_payload(self, websocket): """Send the register payload.""" file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME) data = codecs.open(file, 'r', 'utf-8') raw_handshake = data.read() handshake = json.loads(raw_handshake) handshake['payload'...
csn
// SetTableStatus sets the TableStatus field's value.
func (s *TableDescription) SetTableStatus(v string) *TableDescription { s.TableStatus = &v return s }
csn
Returns the bare access token for the authorized client.
def get_token(self): """ Returns the bare access token for the authorized client. """ if not self.authenticated: raise ValueError("Must authenticate() as a client first.") # If token has expired we'll need to refresh and get a new # client credential ...
csn
func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { repos := make([]*Repository, 0, 10)
return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos) }
csn_ccr
def valid_str(x: str) -> bool: """ Return ``True`` if ``x`` is a non-blank string; otherwise return ``False``. """ if isinstance(x,
str) and x.strip(): return True else: return False
csn_ccr
func (rb *ResponseBuffer) Write(p []byte) (int, error) {
return rb.buf.Write(p) }
csn_ccr
Return args based on layout.json and conditional rendering. Args: required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args.
def profile_settings_args_layout_json(self, required): """Return args based on layout.json and conditional rendering. Args: required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or optional App args. """ pro...
csn
Using abstracted code, find a transform which minimizes the difference between corresponding features in both images. This code is completely model independent and is the core algorithms.
public static<T extends ImageGray<T>, FD extends TupleDesc> Homography2D_F64 computeTransform( T imageA , T imageB , DetectDescribePoint<T,FD> detDesc , AssociateDescription<FD> associate , ModelMatcher<Homography2D_F64,AssociatedPair> modelMatcher ) { // get the length of the description Lis...
csn
func (c *ServerContext) SetAgent(a agent.Agent, channel ssh.Channel) { c.Lock() defer c.Unlock() if c.agentChannel != nil { c.Infof("closing
previous agent channel") c.agentChannel.Close() } c.agentChannel = channel c.agent = a }
csn_ccr
Returns the fortran code string that would define this value element. :arg suffix: an optional suffix to append to the name of the variable. Useful for re-using definitions with new names. :arg local: when True, the parameter definition is re-cast as a local variable definition that...
def definition(self, suffix = "", local=False, ctype=None, optionals=True, customdim=None, modifiers=None): """Returns the fortran code string that would define this value element. :arg suffix: an optional suffix to append to the name of the variable. Useful for re-using de...
csn
// markMachineFailedInAZ moves the machine in zone from MachineIds to FailedMachineIds // in availabilityZoneMachines, report if there are any availability zones not failed for // the specified machine.
func (task *provisionerTask) markMachineFailedInAZ(machine apiprovisioner.MachineProvisioner, zone string) (bool, error) { if zone == "" { return false, errors.New("no zone provided") } task.machinesMutex.Lock() defer task.machinesMutex.Unlock() azRemaining := false for _, zoneMachines := range task.availabilit...
csn
func (s *FilterLogEventsOutput) SetSearchedLogStreams(v []*SearchedLogStream)
*FilterLogEventsOutput { s.SearchedLogStreams = v return s }
csn_ccr
def migrate(schema_file, config_file): '''Migrates a configuration file using a confirm schema.''' schema = load_schema_file(open(schema_file, 'r'))
config = load_config_file(config_file, open(config_file, 'r').read()) config = append_existing_values(schema, config) migrated_config = generate_config_parser(config) migrated_config.write(sys.stdout)
csn_ccr
def json(self, args=None): """Return a dictionary representation of the class. Notes ----- This is meant to be used by a third-party library wanting to wrap this class into another interface. """ names = ['identifier', 'abstract', 'keywords'] out = {key: getattr...
= self.notes out['parameters'] = str({key: {'default': p.default if p.default != p.empty else None, 'desc': ''} for (key, p) in self._sig.parameters.items()}) if six.PY2: out = walk_map(out, lambda x: x.decode('utf8') if isinstance(x, six.string_types) els...
csn_ccr
Calculate the offset from the component to this component. @param compAnchor The component that would be the upper left hand of this screen. @param offset The offset to set for return.
public void calcOffset(Container compAnchor, Point offset) { offset.x = 0; offset.y = 0; Container parent = this; while (parent != null) { offset.x -= parent.getLocation().x; offset.y -= parent.getLocation().y; parent = parent.getParent(); ...
csn
Use this API to update servicegroup.
public static base_response update(nitro_service client, servicegroup resource) throws Exception { servicegroup updateresource = new servicegroup(); updateresource.servicegroupname = resource.servicegroupname; updateresource.servername = resource.servername; updateresource.port = resource.port; updateresource...
csn
public Token add( Variable variable ) { Token t = new Token(variable);
push( t ); return t; }
csn_ccr
Run the Simple Packet Printer Example
def run(iface_name=None, bpf=None, summary=None, max_packets=50): """Run the Simple Packet Printer Example""" # Create the classes streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets) meta = packet_meta.PacketMeta() rdns = reverse_dns.ReverseDNS() t...
csn
def base_url(klass, space_id, webhook_id, resource_id=None): """ Returns the URI for the webhook call. """ return "spaces/{0}/webhooks/{1}/calls/{2}".format(
space_id, webhook_id, resource_id if resource_id is not None else '' )
csn_ccr
public void updateFaxJob(FaxJob faxJob,HTTPResponse httpResponse,FaxActionType faxActionType) { //get path String path=this.getPathToResponseData(faxActionType); //get fax job ID
String id=this.findValue(httpResponse,path); if(id!=null) { faxJob.setID(id); } }
csn_ccr
Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies.
def configure_firewall(self, server, firewall_rule_bodies): """ Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies. """ server_uuid, server_instance = uuid_and_instance(server) return [ self.create_firewall_rule(server_uuid, rule) ...
csn
def _parse(cls, data, key=None): """ Parse a set of data to extract entity-only data. Use classmethod `parse` if available, otherwise use the `endpoint` class variable to extract data from a data blob. """ parse = cls.parse if cls.parse is not None else cls.get_endpoint(...
data = parse(data) elif isinstance(parse, str): data = data[key] else: raise Exception('"parse" should be a callable or string got, {0}' .format(parse)) return data
csn_ccr
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev",...
class Solution: def longestPrefix(self, strn: str) -> str: max_prefs = [0]*len(strn) curr = 0 for idx in range(1, len(strn)): while True: if curr == 0: if strn[idx] == strn[0]: curr = 1 max_prefs[idx...
apps
def generate_content @pdf = Prawn::Document.new( info: self.metadata, top_margin: @format[:header_size] + @format[:top_margin], bottom_margin: @format[:footer_size] + @format[:bottom_margin]
) add_page_body add_page_header add_page_footer add_page_numbering end
csn_ccr
Store file from given path. @param string $path @param string|null $filetype @return \Routegroup\Media\File
public function fromPath($path, $filetype = null) { $filesystem = new Filesystem; $file = new UploadedFile( $path, last(explode('/', $path)), $filetype ?: $filesystem->mimeType($path), $filesystem->size($path), null, true ...
csn
Return a true value if two namespace uri values match.
def nsUriMatch(self, value, wanted, strict=0, tt=type(())): """Return a true value if two namespace uri values match.""" if value == wanted or (type(wanted) is tt) and value in wanted: return 1 if not strict and value is not None: wanted = type(wanted) is tt and wanted or...
csn
static void requestOverlay(Source source) { Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_OVERLAY); source.startActivity(intent); }
csn_ccr
def remove_escalation_policy(self, escalation_policy, **kwargs): """Remove an escalation policy from this team.""" if isinstance(escalation_policy, Entity): escalation_policy = escalation_policy['id'] assert isinstance(escalation_policy, six.string_types) endpoint = '{0}/{1...
self.endpoint, self['id'], escalation_policy, ) return self.request('DELETE', endpoint=endpoint, query_params=kwargs)
csn_ccr
Return list of setters @param clazz
public static List<Method> getBeanSetters(Class<?> clazz) { List<Method> methods = CollectUtils.newArrayList(); for (Method m : clazz.getMethods()) { if (m.getName().startsWith("set") && m.getName().length() > 3) { if (Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) ...
csn
Draws the bars along the x axis @param {D3Selection} layersSelection Selection of layers @return {void}
function drawHorizontalBars(layersSelection) { let layerJoin = layersSelection .data(layers); layerElements = layerJoin .enter() .append('g') .attr('transform', ({key}) => `translate(0,${yScale(key)})`) .c...
csn
def _setup_images(directory, brightness, saturation, hue, preserve_transparency): """ Apply modifiers to the images of a theme Modifies the images using the PIL.ImageEnhance module. Using this function, theme images are modified to given them a unique look and feel. Works best w...
image = imgops.shift_hue(image, hue) if preserve_transparency is True: image = imgops.make_transparent(image) # Save the new image image.save(os.path.join(directory, file_name.replace("gif", "png"))) image.close() for file_name in (item for ...
csn_ccr
Set the position of the datapoints
def set_data_values(self, label, x, y, z): """ Set the position of the datapoints """ # TODO: avoid re-allocating an array every time self.layers[label]['data'] = np.array([x, y, z]).transpose() self._update()
csn
The default method that takes an object and converts it into a params hash. By default, if there is a single dynamic segment named `blog_post_id` and the object is a `BlogPost` with an `id` of `12`, the serialize method will produce: { blog_post_id: 12 }
function(manager, context) { var modelClass, routeMatcher, namespace, param, id; if (Ember.empty(context)) { return ''; } if (modelClass = this.modelClassFor(get(manager, 'namespace'))) { param = paramForClass(modelClass); id = get(context, 'id'); context = {}; context[param] = id;...
csn
python dynamically populating dropdown based upon another dropdown selection
def onchange(self, value): """Called when a new DropDownItem gets selected. """ log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
cosqa
Resolve aliases in the direct dependencies of the target. :param target: The direct dependencies of this target are included. :param scope: When specified, only deps with this scope are included. This is more than a filter, because it prunes the subgraphs represented by aliases with un-matched scop...
def resolve_aliases(self, target, scope=None): """Resolve aliases in the direct dependencies of the target. :param target: The direct dependencies of this target are included. :param scope: When specified, only deps with this scope are included. This is more than a filter, because it prunes the subgr...
csn
public String getAnnotationDescription(String key) { try { return annotationDescriptionBundle.getString(key); } catch (MissingResourceException mre) { if (DEBUG) {
return "TRANSLATE(" + key + ") (param={0}}"; } else { try { return englishAnnotationDescriptionBundle.getString(key); } catch (MissingResourceException mre2) { return key + " {0}"; } } } }
csn_ccr
// MapClaims returns a list of logins based on the provided claims, // returns a list of logins and list of kubernetes groups
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string) { var logins, kubeGroups []string for _, mapping := range c.GetTeamsToLogins() { teams, ok := claims.OrganizationToTeams[mapping.Organization] if !ok { // the user does not belong to this organization continue } for _, team ...
csn
Automatically discovers and registers installed formats. If a format is already registered with an exact same name, the discovered format will not be registered. :param exclude: (optional) Exclude formats from registering
def discover(self, exclude=None): """Automatically discovers and registers installed formats. If a format is already registered with an exact same name, the discovered format will not be registered. :param exclude: (optional) Exclude formats from registering """ if excl...
csn
gather user account information @return bool|mixed
public function getAccountInfo() { $url = 'https://api.dropbox.com/1/account/info'; $result = $this->doOAuthCall($url,'POST'); $result_body = json_decode($result['body'], true); if (!array_key_exists('error', $result_body)) { return $result_body; } else { trigger_error(sprintf(self::E_APIERROR,$result_b...
csn
func (kcs *kbfsCurrentStatus) Init() { kcs.failingServices
= map[string]error{} kcs.invalidateChan = make(chan StatusUpdate) }
csn_ccr
Cast value object. @param m the m @param castType the cast type @param value the value @return the object
@SuppressWarnings("PMD.LooseCoupling") public static Object castValue(Method m, Class<?> castType, String value) { try { if (castType.isEnum()) { Method valueOf; try { valueOf = castType.getMethod("valueOf", String.class); ...
csn
creates a mirror and returns a mirror object. target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_cg name
def create_mirror(self, resource_name, target_name, mirror_type, slave_resource_name, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no'): '''creates a mirror and returns a mirror object. target n...
csn
def find_furious_yaml(config_file=__file__): """ Traverse directory trees to find a furious.yaml file Begins with the location of this file then checks the working directory if not found Args: config_file: location of this file, override for testing Returns: the path of...
or None if not found """ checked = set() result = _find_furious_yaml(os.path.dirname(config_file), checked) if not result: result = _find_furious_yaml(os.getcwd(), checked) return result
csn_ccr
function directOutput(context) { var o = tryExpr(this.parts[1].func, context); return (typeof
o === 'undefined' && !this._strict) ? '' : o; }
csn_ccr
// convertProtoMount converts between a list of proto and structs Mount
func convertProtoMounts(in []*proto.Mount) []*Mount { if in == nil { return nil } out := make([]*Mount, len(in)) for i, d := range in { out[i] = convertProtoMount(d) } return out }
csn
Use the TranslateArray method to retrieve translations for multiple source texts. @param array $texts Required. An array containing the texts for translation. All strings must be of the same language. The total of all texts to be translated must not exceed 10000 characters. The maximum number of array elem...
public function translateArray(array $texts, $to, $from = null, $contentType = 'text/plain', $category = 'general') { $requestXml = "<TranslateArrayRequest>"."<AppId/>"."<From>$from</From>"."<Options>"."<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$category</Catego...
csn
sets it as already done
def firsttime(self): """ sets it as already done""" self.config.set('DEFAULT', 'firsttime', 'no') if self.cli_config.getboolean('core', 'collect_telemetry', fallback=False): print(PRIVACY_STATEMENT) else: self.cli_config.set_value('core', 'collect_telemetry', ask_...
csn
Locations that could not be reached. Generated from protobuf field <code>repeated string unreachable = 3;</code> @param string[]|\Google\Protobuf\Internal\RepeatedField $var @return $this
public function setUnreachable($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING); $this->unreachable = $arr; return $this; }
csn
Set the named related object. @param string $name The name of the relation @param mixed $related_object The related object
public function setRelation($name, $related_object) { //if no related object is supplied, set it to false (an array //value of null will not pass an isset() check on the //relation_objects array). if (!$related_object) { $related_object = false; } $this->...
csn
def MAKE_WPARAM(wParam): """ Convert arguments to the WPARAM type. Used automatically by SendMessage, PostMessage, etc. You shouldn't need to call this function. """
wParam = ctypes.cast(wParam, LPVOID).value if wParam is None: wParam = 0 return wParam
csn_ccr
Close all connections and empty the pool. This method is thread safe.
def close(self): """ Close all connections and empty the pool. This method is thread safe. """ if self._closed: return try: with self.lock: if not self._closed: self._closed = True for address in list...
csn
download files with wget
def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10): """ download files with wget """ # file name if f is False: f = ftp.rsplit('/', 1)[-1] # downloaded file if it does not already exist # check md5s on server (optional) t = 0 while md5check(f, ft...
csn