file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
cfcapp.py
# import time from flask import Flask, json, request from flask.app import setupmethod from threading import Thread class DaemonThread(Thread): def start(self): self.daemon = True super(DaemonThread, self).start() class WSConnection(object):
class CFCContextVars(object): # This class is put into the context of all templates as "CFC" # @property def WEBSOCKET_URL(self): " Provide a URL for the websocket to be used " scheme = request.environ['wsgi.url_scheme'] return '%s://%s/__W__' % ('ws' if scheme == 'http' else 'wss', request.host) class CF...
def __init__(self, app, wsid, fid): self.app = app self.fid = fid self.wsid = wsid def __repr__(self): return '<WSConnection %s fid=..%s>' % (self.wsid, self.fid[-4:]) def created(self): # do something when first connected print "%r: created" % self pass def closed(self): # do something after bein...
identifier_body
cfcapp.py
# import time from flask import Flask, json, request from flask.app import setupmethod from threading import Thread class DaemonThread(Thread): def start(self): self.daemon = True super(DaemonThread, self).start() class WSConnection(object): def __init__(self, app, wsid, fid): self.app = app self.fid = fid ...
(): return dict(CFC = CFCContextVars()) def pinger(self): # Keep all connections alive with some minimal traffic RDB = self.redis #RDB.publish('bcast', 'RESTART') while 1: RDB.publish('bcast', 'PING') time.sleep(self.ping_rate) def rxer(self): # Listen for all traffic from the clients to us. For...
extra_ctx
identifier_name
variablenbindung.rs
fn main()
println!("f = {}", f); }
{ // let - Variablenbindung erstellen, Standard: immutable (Wert ist unveränderbar) let a = 1; println!("a = {}", a); // Muster sind bei einer Variablenbindung möglich, z.B. let (b, c, d) = (2, 3, 4); println!("b = {}, c = {}, d = {}", b, c, d); // Variablenbindung mit Typangabe /...
identifier_body
variablenbindung.rs
fn
() { // let - Variablenbindung erstellen, Standard: immutable (Wert ist unveränderbar) let a = 1; println!("a = {}", a); // Muster sind bei einer Variablenbindung möglich, z.B. let (b, c, d) = (2, 3, 4); println!("b = {}, c = {}, d = {}", b, c, d); // Variablenbindung mit Typangabe ...
main
identifier_name
variablenbindung.rs
fn main() { // let - Variablenbindung erstellen, Standard: immutable (Wert ist unveränderbar) let a = 1; println!("a = {}", a); // Muster sind bei einer Variablenbindung möglich, z.B. let (b, c, d) = (2, 3, 4); println!("b = {}, c = {}, d = {}", b, c, d);
// Variablenbindung mit Typangabe // ohne Typangabe versucht Rust den Typ alleine herauszufinden // i - vorzeichenbehaft u - vorzeichenlos // Ganzzahlen: 8, 16, 32, 64 Bits let e: i32 = 5; println!("e = {}", e); // mut - mutable (Wert ist veränderbar) let mut f = 1; f = 6; print...
random_line_split
Communicator.js
// @flow import React from 'react' import withPropsStream from '@vega/utils/withPropsStream' import {map} from 'rxjs/operators' import styles from './styles/Communicator.css' import ThreadList from './ThreadList' import CreateComment from './CreateComment' function
(props$) { // todo: implement open/close behavior return props$.pipe(map(props => ({...props, isOpen: true}))) } type Props = { isOpen: boolean, subjectIds: string[], focusedCommentId: string } export default withPropsStream( getPropsStream, class Communicator extends React.Component<Props> { state ...
getPropsStream
identifier_name
Communicator.js
// @flow import React from 'react' import withPropsStream from '@vega/utils/withPropsStream' import {map} from 'rxjs/operators' import styles from './styles/Communicator.css' import ThreadList from './ThreadList' import CreateComment from './CreateComment' function getPropsStream(props$)
type Props = { isOpen: boolean, subjectIds: string[], focusedCommentId: string } export default withPropsStream( getPropsStream, class Communicator extends React.Component<Props> { state = { createCommentIsSticky: false } handleCloseCreateComment = event => { this.setState({ ...
{ // todo: implement open/close behavior return props$.pipe(map(props => ({...props, isOpen: true}))) }
identifier_body
Communicator.js
// @flow import React from 'react' import withPropsStream from '@vega/utils/withPropsStream' import {map} from 'rxjs/operators' import styles from './styles/Communicator.css' import ThreadList from './ThreadList' import CreateComment from './CreateComment' function getPropsStream(props$) { // todo: implement open/c...
subjectId={subjectIds} focusedCommentId={focusedCommentId} /> </div> {subjectIds.length === 1 && ( <CreateComment subjectId={subjectIds[0]} showCloseButton={createCommentIsSticky} className={ ...
random_line_split
webapp-hooks.ts
/** * Sets up some hooks for webapp_client * This file is all side effects. * Should be imported ONCE at the top level of the app */ import { alert_message } from "./alerts"; import { redux } from "./app-framework"; import * as misc from "smc-util/misc"; import { webapp_client } from "./webapp-client"; const { ...
//############################################### // Automatically log in //############################################### const remember_me = webapp_client.remember_me_key(); if (reset_password_key()) { // Attempting to do a password reset -- clearly we do NOT want to wait in the hopes // that sign in via a cooki...
// the sign_in function above can be activated, but not the only way. webapp_client.on("signed_in", signed_in);
random_line_split
webapp-hooks.ts
/** * Sets up some hooks for webapp_client * This file is all side effects. * Should be imported ONCE at the top level of the app */ import { alert_message } from "./alerts"; import { redux } from "./app-framework"; import * as misc from "smc-util/misc"; import { webapp_client } from "./webapp-client"; const { ...
); // give it time to possibly resolve itself. SMELL: confused about what is going on here... // Check if user has a has_remember_me cookie (regardless if it is valid or not) // the real "remember_me" is set to be http-only and hence not accessible from javascript (security). redux.getActions("account").setState({ ...
// if we thought user was logged in, but the cookie was invalid, force them to sign in again const f = function() { if (!misc.get_local_storage(remember_me)) { alert_message({ type: "info", message: "You might have to sign in again.", timeout: 1000000 }); ...
conditional_block
industry-jobs.service.ts
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { EVE } from '../../shared/eve.helper'; import { IIndustryJobsData } from '../../shared/interface.helper'; import { Character } from '../models/character/character.model'; import { ScopesComponent ...
extends BaseService { public async getIndustryJobs(character: Character): Promise<IIndustryJobsData[]> { BaseService.confirmRequiredScope(character, ScopesComponent.scopeCodes.JOBS, 'getIndustryJobs'); const url = EVE.getIndustryJobsUrl(character.characterId); const headers = new HttpHead...
IndustryJobsService
identifier_name
industry-jobs.service.ts
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { EVE } from '../../shared/eve.helper'; import { IIndustryJobsData } from '../../shared/interface.helper'; import { Character } from '../models/character/character.model'; import { ScopesComponent ...
return response; } }
{ return []; }
conditional_block
industry-jobs.service.ts
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { EVE } from '../../shared/eve.helper'; import { IIndustryJobsData } from '../../shared/interface.helper'; import { Character } from '../models/character/character.model'; import { ScopesComponent ...
} }
random_line_split
trip-details.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; /* Generated class for the TripDetails page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-trip-details', templateU...
this.userOrganizerName = this.tripObject['user-organizer']['name']; this.userOrganizerPhone = this.tripObject['user-organizer']['phone-number']; this.nbInsiders = this.tripObject['number-insiders']; } ionViewDidLoad() { console.log('Hello TripDetailsPage Page'); } }
random_line_split
trip-details.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; /* Generated class for the TripDetails page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-trip-details', templateU...
{ tripObject: any; name; price; addressFrom; addressTo; description; nbParticipers; userOrganizerName; userOrganizerPhone; nbInsiders; constructor(public navCtrl: NavController, private navParams: NavParams) { this.tripObject = navParams.get('tripObjectSend'); this.name = this.tripObject[...
TripDetailsPage
identifier_name
trip-details.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; /* Generated class for the TripDetails page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-trip-details', templateU...
ionViewDidLoad() { console.log('Hello TripDetailsPage Page'); } }
{ this.tripObject = navParams.get('tripObjectSend'); this.name = this.tripObject['name']; this.price = this.tripObject['price']; this.addressFrom = this.tripObject['address-from']; this.addressTo = this.tripObject['address-to']; this.description = this.tripObject['description']; this.nbPartic...
identifier_body
update_expanded_text_ad.py
#!/usr/bin/env python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
def main(client, ad_id): # Initialize appropriate service. ad_service = client.GetService('AdService', version='v201809') # Create an expanded text ad using the provided ad ID. expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', 'id': ad_id, 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uu...
AD_ID = 'INSERT_AD_ID_HERE'
random_line_split
update_expanded_text_ad.py
#!/usr/bin/env python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, AD_ID)
conditional_block
update_expanded_text_ad.py
#!/usr/bin/env python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
result = ad_service.mutate(operations) updated_ad = result['value'][0] print 'Expanded text ad with ID %s was updated.' % updated_ad['id'] print ('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' 'Final URL: %s\nFinal mobile URL: %s' % (updated_ad['headlinePart1'], upd...
ad_service = client.GetService('AdService', version='v201809') # Create an expanded text ad using the provided ad ID. expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', 'id': ad_id, 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8], 'headlinePart2': 'Tickets on sale now', '...
identifier_body
update_expanded_text_ad.py
#!/usr/bin/env python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
(client, ad_id): # Initialize appropriate service. ad_service = client.GetService('AdService', version='v201809') # Create an expanded text ad using the provided ad ID. expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', 'id': ad_id, 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8]...
main
identifier_name
resnet50_imagenet.py
_train, rec_train_idx, rec_val, rec_val_idx, batch_size, data_nthreads): rec_train = os.path.expanduser(rec_train) rec_train_idx = os.path.expanduser(rec_train_idx) rec_val = os.path.expanduser(rec_val) rec_val_idx = os.path.expanduser(rec_val_idx) jitter_param = 0.4 lighting_pa...
x.reset_ctx(mx.cpu()) arg_params[x.name] = x.data()
conditional_block
resnet50_imagenet.py
mode. Options are step, \ poly and cosine (default: poly)') parser.add_argument('--lr-decay', type=float, default=0.1, help='decay rate of learning rate (default: 0.1)') parser.add_argument('--lr-decay-epoch', type=str, default='40,60', help='epoches at which...
net = get_model(args.model, **kwargs) net.cast(args.dtype) # Create initializer initializer = mx.init.Xavier(rnd_type='gaussian', factor_type="in", magnitude=2) def train_gluon(): def evaluate(epoch): if not args.use_rec: return val_data.reset() a...
kwargs['last_gamma'] = True
random_line_split
resnet50_imagenet.py
. Options are step, \ poly and cosine (default: poly)') parser.add_argument('--lr-decay', type=float, default=0.1, help='decay rate of learning rate (default: 0.1)') parser.add_argument('--lr-decay-epoch', type=str, default='40,60', help='epoches at which lear...
(batch, ctx): data = batch.data[0].as_in_context(ctx) label = batch.label[0].as_in_context(ctx) return data, label train_data = mx.io.ImageRecordIter( path_imgrec=rec_train, path_imgidx=rec_train_idx, preprocess_threads=data_nthreads, shuffle=True, ba...
batch_fn
identifier_name
resnet50_imagenet.py
. Options are step, \ poly and cosine (default: poly)') parser.add_argument('--lr-decay', type=float, default=0.1, help='decay rate of learning rate (default: 0.1)') parser.add_argument('--lr-decay-epoch', type=str, default='40,60', help='epoches at which lear...
@property def provide_label(self): return [mx.io.DataDesc('softmax_label', (self.batch_size,), self.dtype)] def next(self): self.cur_iter += 1 if self.cur_iter <= self.max_iter: return DataBatch(data=(self.data,), ...
return [mx.io.DataDesc('data', self.data.shape, self.dtype)]
identifier_body
index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
* var opts = { * 'returns': '*' * }; * var out = groupIn( obj, opts, indicator ); * // e.g., returns { 'b': [ [ 'a', 'beep' ], [ 'b', 'boop' ], [ 'd', 'bar' ] ], 'f': [ [ 'c', 'foo' ] ] } */ // MODULES // var groupIn = require( './main.js' ); // EXPORTS // module.exports = groupIn;
random_line_split
classes.py
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
self.quality = Quality.UNKNOWN # release name self.name = u'' # size of the release (-1 = n/a) self.size = -1 # release group self.release_group = u'' # version self.version = -1 # hash self.hash = None # content ...
""" Represents a search result from an indexer. """ def __init__(self, episodes): self.provider = None # release show object self.show = None # URL to the NZB/torrent file self.url = u'' # used by some providers to store extra info associated with the resu...
identifier_body
classes.py
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
self.name = name self.url = url self.date = date self.provider = None self.quality = Quality.UNKNOWN self.release_group = None self.version = -1 self.show = show self.indexer = None self.indexerid = -1 self.season = -1 self...
return allSeries[0] class Proper(object): # pylint: disable=too-few-public-methods, too-many-instance-attributes def __init__(self, name, url, date, show):
random_line_split
classes.py
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
(self): return u'{0}.{1}'.format(self.episodes[0].prettyName(), self.resultType) class NZBSearchResult(SearchResult): # pylint: disable=too-few-public-methods """ Regular NZB result with an URL to the NZB """ def __init__(self, episodes): super(NZBSearchResult, self).__init__(episodes...
fileName
identifier_name
classes.py
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
my_string = u'{0} @ {1}\n'.format(self.provider.name, self.url) my_string += u'Extra Info:\n' for extra in self.extraInfo: my_string += u' {0}\n'.format(extra) my_string += u'Episodes:\n' for ep in self.episodes: my_string += u' {0}\n'.format(ep) ...
return u'Invalid provider, unable to print self'
conditional_block
html_tags.ts
', 'Scaron': '\u0160', 'scaron': '\u0161', 'sdot': '\u22C5', 'sect': '\u00A7', 'shy': '\u00AD', 'Sigma': '\u03A3', 'sigma': '\u03C3', 'sigmaf': '\u03C2', 'sim': '\u223C', 'spades': '\u2660', 'sub': '\u2282', 'sube': '\u2286', 'sum': '\u2211', 'sup': '\u2283', 'sup1': '\u00B9', 'sup2': '\...
getHtmlTagDefinition
identifier_name
html_tags.ts
2286', 'sum': '\u2211', 'sup': '\u2283', 'sup1': '\u00B9', 'sup2': '\u00B2', 'sup3': '\u00B3', 'supe': '\u2287', 'szlig': '\u00DF', 'Tau': '\u03A4', 'tau': '\u03C4', 'there4': '\u2234', 'Theta': '\u0398', 'theta': '\u03B8', 'thetasym': '\u03D1', 'thinsp': '\u2009', 'THORN': '\u00DE', 'th...
{ return splitNsName(elementName)[0]; }
identifier_body
html_tags.ts
arr': '\u2190', 'lArr': '\u21D0', 'lceil': '\u2308', 'ldquo': '\u201C', 'le': '\u2264', 'lfloor': '\u230A', 'lowast': '\u2217', 'loz': '\u25CA', 'lrm': '\u200E', 'lsaquo': '\u2039', 'lsquo': '\u2018', 'lt': '<', 'macr': '\u00AF', 'mdash': '\u2014', 'micro': '\u00B5', 'middot': '\u00B7', ...
{ return false; }
conditional_block
html_tags.ts
Egrave': '\u00C8', 'egrave': '\u00E8', 'empty': '\u2205', 'emsp': '\u2003', 'ensp': '\u2002', 'Epsilon': '\u0395', 'epsilon': '\u03B5', 'equiv': '\u2261', 'Eta': '\u0397', 'eta': '\u03B7', 'ETH': '\u00D0', 'eth': '\u00F0', 'Euml': '\u00CB', 'euml': '\u00EB', 'euro': '\u20AC', 'exist': '\u2...
'sube': '\u2286', 'sum': '\u2211', 'sup': '\u2283', 'sup1': '\u00B9', 'sup2': '\u00B2', 'sup3': '\u00B3', 'supe': '\u2287', 'szlig': '\u00DF', 'Tau': '\u03A4', 'tau': '\u03C4', 'there4': '\u2234', 'Theta': '\u0398', 'theta': '\u03B8', 'thetasym': '\u03D1', 'thinsp': '\u2009', 'THORN': '\...
'sub': '\u2282',
random_line_split
SignalWifi1BarLock.js
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsxs(React.Fragment, { children: [/*#__PURE__*/_jsx("path", { d: "M23 16v-1.5c0-1.4-1.1...
}), 'SignalWifi1BarLock');
})]
random_line_split
oauth_provider.py
# -*- coding: utf-8 -*- from odoo import models, fields, api from datetime import datetime, timedelta from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT try: from oauthlib import common as oauthlib_common except: pass import uuid class
(models.Model): CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' _name = 'oauth.application' _rec_name = 'client_id' def generate_client_id(self): return str(uuid.uuid1()) client_id = fields.Char('Client ID', index=True, required=True, d...
OauthApplication
identifier_name
oauth_provider.py
# -*- coding: utf-8 -*- from odoo import models, fields, api from datetime import datetime, timedelta from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT try: from oauthlib import common as oauthlib_common except: pass import uuid class OauthApplication(models.Model): CLIENT_ID_CHARACTER_SET = r'_-.:;...
def generate_client_id(self): return str(uuid.uuid1()) client_id = fields.Char('Client ID', index=True, required=True, default=generate_client_id) token_ids = fields.One2many('oauth.access_token', 'application_id', 'Tokens') _sql_constraints = [ ('client_id_uniq', 'unique (client_id)'...
random_line_split
oauth_provider.py
# -*- coding: utf-8 -*- from odoo import models, fields, api from datetime import datetime, timedelta from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT try: from oauthlib import common as oauthlib_common except: pass import uuid class OauthApplication(models.Model): CLIENT_ID_CHARACTER_SET = r'_-.:;...
access_token = self.env['oauth.access_token'].sudo().search([('application_id', '=', self.id), ('user_id', '=', user_id)], order='id DESC', limit=1) if access_token: access_token = access_token[0] if access_token.is_expired(): access_token = None if not ...
user_id = self.env.user.id
conditional_block
oauth_provider.py
# -*- coding: utf-8 -*- from odoo import models, fields, api from datetime import datetime, timedelta from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT try: from oauthlib import common as oauthlib_common except: pass import uuid class OauthApplication(models.Model): CLIENT_ID_CHARACTER_SET = r'_-.:;...
@api.multi def is_expired(self): self.ensure_one() return datetime.now() > datetime.strptime(self.expires, DEFAULT_SERVER_DATETIME_FORMAT) @api.multi def _allow_scopes(self, scopes): self.ensure_one() if not scopes: return True provided_scopes = se...
""" Checks if the access token is valid. :param scopes: An iterable containing the scopes to check or None """ self.ensure_one() return not self.is_expired() and self._allow_scopes(scopes)
identifier_body
btree.rs
upper_bound: 2 * lb } } ///Implements the Clone trait for the BTree. ///Uses a helper function/constructor to produce a new BTree. pub fn clone(&self) -> BTree<K, V> { return BTree::new_with_node_len(self.root.clone(), self.len, self.lower_bound); } ///Returns the value of a g...
new
identifier_name
btree.rs
get method. pub fn get(self, k: K) -> Option<V> { return self.root.get(k); } ///Checks to see if the key already exists in the tree, and if it is not, ///the key-value pair is added to the tree by calling add on the root node. pub fn add(self, k: K, v: V) -> bool { let is_get = &se...
///the original LeafElt's key is less than the other one's key. fn less_than(&self, other: LeafElt<K, V>) -> bool { let order = self.key.cmp(&other.key); match order {
random_line_split
sensor.py
"""Support for Streamlabs Water Monitor Usage.""" from datetime import timedelta from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN from homeassistant.const import VOLUME_GALLONS from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle DEPENDENCIES = ...
(StreamLabsDailyUsage): """Monitors the yearly water usage.""" @property def name(self): """Return the name for yearly usage.""" return "{} {}".format(self._location_name, NAME_YEARLY_USAGE) @property def state(self): """Return the current yearly usage.""" return se...
StreamLabsYearlyUsage
identifier_name
sensor.py
"""Support for Streamlabs Water Monitor Usage.""" from datetime import timedelta from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN from homeassistant.const import VOLUME_GALLONS from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle DEPENDENCIES = ...
def get_daily_usage(self): """Return the day's usage.""" return self._today def get_monthly_usage(self): """Return the month's usage.""" return self._this_month def get_yearly_usage(self): """Return the year's usage.""" return self._this_year class Strea...
"""Query and store usage data.""" water_usage = self._client.get_water_usage_summary(self._location_id) self._today = round(water_usage["today"], 1) self._this_month = round(water_usage["thisMonth"], 1) self._this_year = round(water_usage["thisYear"], 1)
identifier_body
sensor.py
"""Support for Streamlabs Water Monitor Usage.""" from datetime import timedelta from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN from homeassistant.const import VOLUME_GALLONS from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle DEPENDENCIES = ...
def unit_of_measurement(self): """Return gallons as the unit measurement for water.""" return VOLUME_GALLONS def update(self): """Retrieve the latest daily usage.""" self._streamlabs_usage_data.update() class StreamLabsMonthlyUsage(StreamLabsDailyUsage): """Monitors the mo...
@property
random_line_split
esempio0_json.py
import json import sys import urllib keyword = sys.argv[1] def getTimes(query,num): "Questa funzione fa una ricerca su NY Times" url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num) jtext = urllib.urlopen(url) return jtext def search...
headline = res['hdl'] # snippet = res['snippet'] # author = res['cre'] url = res['url'] print headline.encode('utf-8') print url page_number+=1 search(keyword)
resp = json.load(gt) meta = int(resp['results']['meta']['payload']) for res in resp['results']['results']: print res['snippet']
random_line_split
esempio0_json.py
import json import sys import urllib keyword = sys.argv[1] def getTimes(query,num): "Questa funzione fa una ricerca su NY Times" url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num) jtext = urllib.urlopen(url) return jtext def search...
search(keyword)
page_number = 0 meta = 1 while meta > 0 and page_number<1: gt = getTimes(term,page_number) resp = json.load(gt) meta = int(resp['results']['meta']['payload']) for res in resp['results']['results']: print res['snippet'] headline = res['hdl'] # ...
identifier_body
esempio0_json.py
import json import sys import urllib keyword = sys.argv[1] def getTimes(query,num): "Questa funzione fa una ricerca su NY Times" url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num) jtext = urllib.urlopen(url) return jtext def
(term): page_number = 0 meta = 1 while meta > 0 and page_number<1: gt = getTimes(term,page_number) resp = json.load(gt) meta = int(resp['results']['meta']['payload']) for res in resp['results']['results']: print res['snippet'] headline = res['hdl'] ...
search
identifier_name
esempio0_json.py
import json import sys import urllib keyword = sys.argv[1] def getTimes(query,num): "Questa funzione fa una ricerca su NY Times" url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num) jtext = urllib.urlopen(url) return jtext def search...
page_number+=1 search(keyword)
print res['snippet'] headline = res['hdl'] # snippet = res['snippet'] # author = res['cre'] url = res['url'] print headline.encode('utf-8') print url
conditional_block
make_agent_demos.py
#!/usr/bin/env python3 """ Generate a set of agent demonstrations. The agent can either be a trained model or the heuristic expert (bot). Demonstration generation can take a long time, but it can be parallelized if you have a cluster at your disposal. Provide a script that launches make_agent_demos.py at your cluste...
help="How to handle exceptions during demo generation") parser.add_argument("--job-script", type=str, default=None, help="The script that launches make_agent_demos.py at a cluster.") parser.add_argument("--jobs", type=int, default=0, help="Split generation in...
help="filter out demos with number of steps more than filter-steps") parser.add_argument("--on-exception", type=str, default='warn', choices=('warn', 'crash'),
random_line_split
make_agent_demos.py
#!/usr/bin/env python3 """ Generate a set of agent demonstrations. The agent can either be a trained model or the heuristic expert (bot). Demonstration generation can take a long time, but it can be parallelized if you have a cluster at your disposal. Provide a script that launches make_agent_demos.py at your cluste...
else: generate_demos_cluster() # Validation demos if args.valid_episodes: generate_demos(args.valid_episodes, True, int(1e9))
generate_demos(args.episodes, False, args.seed)
conditional_block
make_agent_demos.py
#!/usr/bin/env python3 """ Generate a set of agent demonstrations. The agent can either be a trained model or the heuristic expert (bot). Demonstration generation can take a long time, but it can be parallelized if you have a cluster at your disposal. Provide a script that launches make_agent_demos.py at your cluste...
def generate_demos(n_episodes, valid, seed, shift=0): utils.seed(seed) # Generate environment env = gym.make(args.env) agent = utils.load_agent(env, args.model, args.demos, 'agent', args.argmax, args.env) demos_path = utils.get_demos_path(args.demos, args.env, 'agent', valid) demos = [] ...
num_frames_per_episode = [len(demo[2]) for demo in demos] logger.info('Demo length: {:.3f}+-{:.3f}'.format( np.mean(num_frames_per_episode), np.std(num_frames_per_episode)))
identifier_body
make_agent_demos.py
#!/usr/bin/env python3 """ Generate a set of agent demonstrations. The agent can either be a trained model or the heuristic expert (bot). Demonstration generation can take a long time, but it can be parallelized if you have a cluster at your disposal. Provide a script that launches make_agent_demos.py at your cluste...
(n_episodes, valid, seed, shift=0): utils.seed(seed) # Generate environment env = gym.make(args.env) agent = utils.load_agent(env, args.model, args.demos, 'agent', args.argmax, args.env) demos_path = utils.get_demos_path(args.demos, args.env, 'agent', valid) demos = [] checkpoint_time = t...
generate_demos
identifier_name
component_len.rs
use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_gen; use malachite_base_test_u...
fn demo_rational_sequence_component_len(gm: GenMode, config: GenConfig, limit: usize) { for xs in unsigned_rational_sequence_gen::<u8>() .get(gm, &config) .take(limit) { println!("component_len({}) = {}", xs, xs.component_len()); } } fn benchmark_rational_sequence_component_len( ...
{ register_demo!(runner, demo_rational_sequence_component_len); register_bench!(runner, benchmark_rational_sequence_component_len); }
identifier_body
component_len.rs
use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_gen; use malachite_base_test_u...
); }
random_line_split
component_len.rs
use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_rational_sequence_gen; use malachite_base_test_u...
(gm: GenMode, config: GenConfig, limit: usize) { for xs in unsigned_rational_sequence_gen::<u8>() .get(gm, &config) .take(limit) { println!("component_len({}) = {}", xs, xs.component_len()); } } fn benchmark_rational_sequence_component_len( gm: GenMode, config: GenConfig, ...
demo_rational_sequence_component_len
identifier_name
account-grimoire-request.js
"use strict"; const _ = require('lodash'); const request = require('request-promise'); const Promise = require('bluebird'); const RequestParameters = require('./request-parameters'); const uriTemplate = _.template('Vanguard/Grimoire/${membershipType}/${membershipId}/'); const parameters = new RequestParameters([{ ...
let error = parameters.validate(this); if (error) { return Promise.reject(error); } let options = parameters.buildOptions(this); let uri = (host || '') + uriTemplate(options.path); return request({ uri: uri, method: 'GET', h...
random_line_split
account-grimoire-request.js
"use strict"; const _ = require('lodash'); const request = require('request-promise'); const Promise = require('bluebird'); const RequestParameters = require('./request-parameters'); const uriTemplate = _.template('Vanguard/Grimoire/${membershipType}/${membershipId}/'); const parameters = new RequestParameters([{ ...
() { return parameters.validate(this); } } module.exports = AccountGrimoireRequest;
validate
identifier_name
account-grimoire-request.js
"use strict"; const _ = require('lodash'); const request = require('request-promise'); const Promise = require('bluebird'); const RequestParameters = require('./request-parameters'); const uriTemplate = _.template('Vanguard/Grimoire/${membershipType}/${membershipId}/'); const parameters = new RequestParameters([{ ...
execute(host) { let error = parameters.validate(this); if (error) { return Promise.reject(error); } let options = parameters.buildOptions(this); let uri = (host || '') + uriTemplate(options.path); return request({ uri: uri, method...
{ this.apiKey = apiKey; _.defaults(this, parameters.defaults()); _.merge(this, values); }
identifier_body
account-grimoire-request.js
"use strict"; const _ = require('lodash'); const request = require('request-promise'); const Promise = require('bluebird'); const RequestParameters = require('./request-parameters'); const uriTemplate = _.template('Vanguard/Grimoire/${membershipType}/${membershipId}/'); const parameters = new RequestParameters([{ ...
let options = parameters.buildOptions(this); let uri = (host || '') + uriTemplate(options.path); return request({ uri: uri, method: 'GET', headers: { 'x-api-key': this.apiKey }, qs: _.isEmpty(options.query) ? undefined ...
{ return Promise.reject(error); }
conditional_block
locale.js
/*================================================== * Chinese localization * *================================================== */ (function() { var javascriptFiles = [ "exhibit-l10n.js", "data/database-l10n.js", "ui/ui-context-l10n.js", "ui/lens-l10n.js", "ui/formatt...
else { SimileAjax.includeJavascriptFiles(document, urlPrefix + "scripts/", javascriptFiles); SimileAjax.includeCssFiles(document, urlPrefix + "styles/", cssFiles); } })();
{ SimileAjax.includeJavascriptFiles(document, urlPrefix, [ "exhibit-zh-bundle.js" ]); if (cssFiles.length > 0) { SimileAjax.includeCssFiles(document, urlPrefix, [ "exhibit-zh-bundle.css" ]); } }
conditional_block
locale.js
/*================================================== * Chinese localization * *================================================== */ (function() { var javascriptFiles = [ "exhibit-l10n.js", "data/database-l10n.js",
"ui/views/ordered-view-frame-l10n.js", "ui/views/tile-view-l10n.js", "ui/views/thumbnail-view-l10n.js", "ui/views/tabular-view-l10n.js", "util/coders-l10n.js", "util/facets-l10n.js", "util/views-l10n.js" ]; var cssFiles = [ ]; var urlPrefix = Exhi...
"ui/ui-context-l10n.js", "ui/lens-l10n.js", "ui/formatter-l10n.js", "ui/widgets/collection-summary-widget-l10n.js", "ui/views/view-panel-l10n.js",
random_line_split
TileRenderer.ts
import { WRAP_MODES } from '@pixi/constants'; import { BaseTexture, Buffer, ObjectRenderer, Renderer } from '@pixi/core'; import { settings } from './settings'; import { TilemapGeometry, TilemapShader } from './TilemapShader'; import { TextileResource } from './TextileResource'; import * as utils from '@pixi/utils'; /...
{ // sorry, nothing } /** * @internal * @ignore */ createVb(): TilemapGeometry { const geom = new TilemapGeometry(); geom.addIndex(this.indexBuffer); geom.lastTimeAccess = Date.now(); return geom; } /** @return The {@link TilemapShader} shader that this rendering pipeline is us...
} start(): void
random_line_split
TileRenderer.ts
import { WRAP_MODES } from '@pixi/constants'; import { BaseTexture, Buffer, ObjectRenderer, Renderer } from '@pixi/core'; import { settings } from './settings'; import { TilemapGeometry, TilemapShader } from './TilemapShader'; import { TextileResource } from './TextileResource'; import * as utils from '@pixi/utils'; /...
extends ObjectRenderer { /** The managing renderer */ public readonly renderer: Renderer; /** The tile animation frame */ public tileAnim = [0, 0]; private ibLen = 0;// index buffer length /** The index buffer for the tilemaps to share. */ private indexBuffer: Buffer = null; /** The shader used to render t...
TileRenderer
identifier_name
TileRenderer.ts
import { WRAP_MODES } from '@pixi/constants'; import { BaseTexture, Buffer, ObjectRenderer, Renderer } from '@pixi/core'; import { settings } from './settings'; import { TilemapGeometry, TilemapShader } from './TilemapShader'; import { TextileResource } from './TextileResource'; import * as utils from '@pixi/utils'; /...
for (let i = 0; i < settings.TEXTILE_UNITS; i++) { if (this.textiles[i]) continue; const resource = new TextileResource(); const baseTex = new BaseTexture(resource); baseTex.scaleMode = settings.TEXTILE_SCALE_MODE; baseTex.wrapMode = WRAP_MODES.CLAMP; this.textiles[i] ...
{ return; }
conditional_block
add_test.py
#!/usr/bin/python import os, sys, re args = sys.argv if not len(args) in (3, 4):
rawdata = [] for line in open(args[1], "rt").readlines(): lookfor = ["basic_cpuid", "ext_cpuid", "intel_fn4", "intel_fn11"] good = False for match in lookfor: if line.find(match) != -1: good = True break if good: rawdata.append(line.strip()) repdata = [] rexp = re.compile('(-?[0-9]+).*') for line in op...
print "Usage: add_test.py <rawdata file> <report file> [tests stash file]" print "If the last is not specified, `tests_stash.txt' is assumed" sys.exit(1)
conditional_block
add_test.py
#!/usr/bin/python import os, sys, re args = sys.argv if not len(args) in (3, 4): print "Usage: add_test.py <rawdata file> <report file> [tests stash file]" print "If the last is not specified, `tests_stash.txt' is assumed" sys.exit(1) rawdata = [] for line in open(args[1], "rt").readlines(): lookfor = ["basic_c...
lines = rawdata + [delimiter] + repdata + [delimiter] fout.writelines(map(lambda s: s + "\n", lines)) fout.close()
stash = "tests_stash.txt" if len(args) == 4: stash = args[3] fout = open(stash, "at") delimiter = "-" * 80
random_line_split
pelicanconf.py
# Theme-specific settings SITENAME = "Marc Sleegers" DOMAIN = "marcsleegers.com" BIO_TEXT = "Infrequent ramblings." FOOTER_TEXT = '&copy; 2022 Marc Sleegers. Licensed <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.' SITE_AUTHOR = "Marc Sleegers" TWITTER_USERNAME = "@marcardioid" GOOGLE_PLUS_URL =...
CATEGORY_SAVE_AS = "" # Disable Atom feed generation FEED_ATOM = "atom.xml" FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None TYPOGRIFY = True MARKDOWN = { "extension_configs": { "markdown.extensions.codehilite": {"linenums": "True"}, "markdown.extensions.admonition": {},...
DIRECT_TEMPLATES = ["index", "archives"] INDEX_SAVE_AS = BLOG_URL + "index.html"
random_line_split
navtree.js
function localStorageSupported() { try { return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem; } catch(e) { return false; } } function storeLink(link) { if (!$("#nav-sync").hasClass('sync') && localStorageSupported()) { window.localStorage.setItem...
{ var i = uri.lastIndexOf('/'); var s = uri.substring(i+1); var m = uri.substring(0,i+1).match(/\/d\w\/d\w\w\/$/); return m ? uri.substring(i-6) : s; }
identifier_body
navtree.js
(uri) { var i = uri.lastIndexOf('/'); var s = uri.substring(i+1); var m = uri.substring(0,i+1).match(/\/d\w\/d\w\w\/$/); return m ? uri.substring(i-6) : s; } function localStorageSupported() { try { return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem; } c...
stripPath2
identifier_name
navtree.js
.split('#')[1]; var srcPage = stripPath($(location).attr('pathname')); var targetPage = stripPath(link.split('#')[0]); a.href = srcPage!=targetPage ? url : "javascript:void(0)"; a.onclick = function(){ storeLink(link); if (!$(a).parent().parent().hasClass('selected')) { ...
n.html('<img src="'+relpath+'sync_on.png" title="'+SYNCONMSG+'"/>'); }
random_line_split
navtree.js
\/d\w\w\/$/); return m ? uri.substring(i-6) : s; } function localStorageSupported() { try { return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem; } catch(e) { return false; } } function storeLink(link) { if (!$("#nav-sync").hasClass('sync') && localSto...
} function getScript(scriptName,func,show) { var head = document.getElementsByTagName("head")[0]; var script = document.createElement('script'); script.id = scriptName; script.type = 'text/javascript'; script.onload = func; script.src = scriptName+'.js'; if ($.browser.msie && $.browser.version<=8) { ...
{ return ''; }
conditional_block
github_backup.py
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/...
def redact(self, s): if hasattr(self.args, 'password'): s = s.replace(self.args.password, 'REDACTED') if hasattr(self.args, 'username'): s = s.replace(self.args.username, 'REDACTED') return s Pagination = namedtuple('Pagination', 'first prev next last') def get_pagi...
def https_url_with_auth(self, base_url): _, suffix = base_url.split('https://') return 'https://%s:%s@%s' % (quote(self.args.username), quote(self.args.password), suffix)
random_line_split
github_backup.py
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/...
except KeyError: print 'no Link header, nothing to paginate through.' pagination = Pagination(None, None, None, None) repos = json.loads(response.read()) for r in repos: if not r.get('archived'): yield r # so, this isn't the DRYest code ;-) while pagination.next...
""" Paginates through all of the repositories using github's Link header. https://developer.github.com/v3/#link-header """ url = API_BASE + 'orgs/%s/repos?' % org qs_params = {'type': repo_type, 'per_page': per_page} if access_token: qs_params.update({'access_token': args.access_toke...
identifier_body
github_backup.py
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/...
(object): def __init__(self, args): self.args = args def exec_cmd(self, command): """ Executes an external command taking into account errors and logging. """ print "Executing command: %s" % self.redact(command) resp = os.system(command) if resp != 0: ...
Helpers
identifier_name
github_backup.py
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/...
# clone the repo fresh, deleting if it already existed print '*** backing up %s... ***' % h.redact(repo_path) try: h.exec_cmd('rm -rf %s && git clone %s %s' % (destdir, repo_path, destdir)) except Exception as e: print 'error: %s' % e
print '*** updating %s... ***' % h.redact(repo_path) with chdir(destdir): try: h.exec_cmd('git pull origin %s' % repo['default_branch']) continue except Exception as e: print 'error: %s (repo=%s); will re-clone!' % (...
conditional_block
RamlResponse.py
from .decorators import raml_optional, raml_simple_parse, raml_tabbed from .RamlBody import RamlBody from .RamlParseable import RamlParseable class RamlResponse(RamlParseable):
@raml_tabbed def __str__(self): return '''\ [RamlResponse({0.code}): description: {0.description} headers: {0.headers} body: {0.body} ]'''.format(self) def __repr__(self): return str(self)
def __init__(self, code, yaml): self.code = code super(RamlResponse, self).__init__(yaml) @raml_optional @raml_simple_parse def parse_description(self): pass @raml_optional @raml_simple_parse def parse_headers(self): pass @raml_optional def parse_body(s...
identifier_body
RamlResponse.py
from .decorators import raml_optional, raml_simple_parse, raml_tabbed from .RamlBody import RamlBody from .RamlParseable import RamlParseable
def __init__(self, code, yaml): self.code = code super(RamlResponse, self).__init__(yaml) @raml_optional @raml_simple_parse def parse_description(self): pass @raml_optional @raml_simple_parse def parse_headers(self): pass @raml_optional def parse_b...
class RamlResponse(RamlParseable):
random_line_split
RamlResponse.py
from .decorators import raml_optional, raml_simple_parse, raml_tabbed from .RamlBody import RamlBody from .RamlParseable import RamlParseable class RamlResponse(RamlParseable): def __init__(self, code, yaml): self.code = code super(RamlResponse, self).__init__(yaml) @raml_optional @raml_...
(self): pass @raml_optional @raml_simple_parse def parse_headers(self): pass @raml_optional def parse_body(self): self.body = { body_encoding[0]: RamlBody(body_encoding[0], body_encoding[1]) for body_encoding in self.yaml['body'].items() } ...
parse_description
identifier_name
test_character_sets.py
# Copyright 2015 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
(self, FakeChar): with pytest.raises(UnsupportedOperation): FakeChar.delete()
test_delete_raises
identifier_name
test_character_sets.py
# Copyright 2015 F5 Networks Inc. #
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES ...
# Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
test_character_sets.py
# Copyright 2015 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
def test_delete_raises(self, FakeChar): with pytest.raises(UnsupportedOperation): FakeChar.delete()
with pytest.raises(UnsupportedOperation): FakeChar.create()
identifier_body
os_server_facts.py
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
module.exit_json(changed=False, ansible_facts=dict( openstack_servers=openstack_servers)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openst...
argument_spec = openstack_full_argument_spec( server=dict(required=False), detailed=dict(required=False, type='bool'), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for...
identifier_body
os_server_facts.py
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
if fnmatch.fnmatch(server['name'], pattern) or fnmatch.fnmatch(server['id'], pattern)] module.exit_json(changed=False, ansible_facts=dict( openstack_servers=openstack_servers))
random_line_split
os_server_facts.py
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
(): argument_spec = openstack_full_argument_spec( server=dict(required=False), detailed=dict(required=False, type='bool'), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is req...
main
identifier_name
os_server_facts.py
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
try: cloud = shade.openstack_cloud(**module.params) openstack_servers = cloud.list_servers( detailed=module.params['detailed']) if module.params['server']: # filter servers by name pattern = module.params['server'] openstack_servers = [serve...
module.fail_json(msg='shade is required for this module')
conditional_block
leader_reputation_test.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::liveness::{ leader_reputation::{ ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic, }, proposer_election::{next, ProposerElection}, }; use consensus_types::{ block::{block...
assert!(proposer_election.is_valid_proposal(&good_proposal)); }
random_line_split
leader_reputation_test.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::liveness::{ leader_reputation::{ ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic, }, proposer_election::{next, ProposerElection}, }; use consensus_types::{ block::{block...
(proposer: Author, voters: Vec<&ValidatorSigner>) -> NewBlockEvent { NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0) } #[test] fn test_simple_heuristic() { let active_weight = 9; let inactive_weight = 1; let mut proposers = vec![]; let mut signers = vec![]; for i...
create_block
identifier_name
leader_reputation_test.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::liveness::{ leader_reputation::{ ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic, }, proposer_election::{next, ProposerElection}, }; use consensus_types::{ block::{block...
#[test] fn test_simple_heuristic() { let active_weight = 9; let inactive_weight = 1; let mut proposers = vec![]; let mut signers = vec![]; for i in 0..8 { let signer = ValidatorSigner::random([i; 32]); proposers.push(signer.author()); signers.push(signer); } let heu...
{ NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0) }
identifier_body
leader_reputation_test.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::liveness::{ leader_reputation::{ ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic, }, proposer_election::{next, ProposerElection}, }; use consensus_types::{ block::{block...
; self.data[start..].to_vec() } } fn create_block(proposer: Author, voters: Vec<&ValidatorSigner>) -> NewBlockEvent { NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0) } #[test] fn test_simple_heuristic() { let active_weight = 9; let inactive_weight = 1; let m...
{ 0 }
conditional_block
icekey.ts
xcc, 0xa7, 0xad, 0x41], [0x4b, 0x2e, 0xd4, 0x33], [0xea, 0xcb, 0x2e, 0x04] ]; private static pBox = [ 0x00000001, 0x00000080, 0x00000400, 0x00002000, 0x00080000, 0x00200000, 0x01000000, 0x40000000, 0x00000008, 0x00000020, 0x00000100, 0x00004000, 0x0001000...
// Create a new ICE key with the specified level. constructor(level: number) { if (!IceKey.spBoxInitialised) { this.spBoxInit(); IceKey.spBoxInitialised = true; } if (level < 1) { this.size = 1; this.rounds = 8; } else { this.size = level; this.rounds = level * ...
random_line_split
icekey.ts
xcc, 0xa7, 0xad, 0x41], [0x4b, 0x2e, 0xd4, 0x33], [0xea, 0xcb, 0x2e, 0x04] ]; private static pBox = [ 0x00000001, 0x00000080, 0x00000400, 0x00002000, 0x00080000, 0x00200000, 0x01000000, 0x40000000, 0x00000008, 0x00000020, 0x00000100, 0x00004000, 0x0001000...
( cipherArray: Uint8Array, plainArray: Uint8Array, from?: number, to?: number ): void { if (from == null) from = 0; if (to == null) to = cipherArray.length; let k = 0; // decrypt full blocks while (from + 8 <= to) { for (let i = 0; i < 8; i++) { this.cipherHolder[i]...
decryptUint8Array
identifier_name
sbt.py
from dependencywatcher.parser.parser import Parser from dependencywatcher.parser.pyparser import PyParser from pyparsing import *
def __init__(self, source): super(SbtParser, self).__init__(source) vars = {} def store_var(st, locn, tokens): vars[tokens[0]] = tokens[1] return tokens def resolve_var(st, locn, tokens): try: tokens[0][2] = vars[tokens[0][2]] ...
class SbtParser(PyParser):
random_line_split
sbt.py
from dependencywatcher.parser.parser import Parser from dependencywatcher.parser.pyparser import PyParser from pyparsing import * class SbtParser(PyParser): def __init__(self, source): super(SbtParser, self).__init__(source) vars = {} def store_var(st, locn, tokens): vars[toke...
VersionSpec = Suppress(Literal("\"")) + Regex("[\[\]\(]?[0-9][-A-Za-z0-9_.\+\,]+[\[\]\)]?") + Suppress(Literal("\"")) ScalaIdentifier = Regex("[a-zA-Z][A-Za-z0-9_.-]+") VarKeyword = Literal("val") | Literal("var") VarDeclaration = Suppress(VarKeyword) + ScalaIdentifier + Suppress(Lite...
try: tokens[0][2] = vars[tokens[0][2]] except KeyError: pass return tokens
identifier_body
sbt.py
from dependencywatcher.parser.parser import Parser from dependencywatcher.parser.pyparser import PyParser from pyparsing import * class SbtParser(PyParser): def
(self, source): super(SbtParser, self).__init__(source) vars = {} def store_var(st, locn, tokens): vars[tokens[0]] = tokens[1] return tokens def resolve_var(st, locn, tokens): try: tokens[0][2] = vars[tokens[0][2]] except ...
__init__
identifier_name
sbt.py
from dependencywatcher.parser.parser import Parser from dependencywatcher.parser.pyparser import PyParser from pyparsing import * class SbtParser(PyParser): def __init__(self, source): super(SbtParser, self).__init__(source) vars = {} def store_var(st, locn, tokens): vars[toke...
Parser.register_parser([".*\.sbt"], SbtParser)
if len(token.data) == 3: dep_name = "%s:%s" % (token.data[0], token.data[1]) version = token.data[2] if version: dependencies.append({"name": dep_name, "version": version, "context": "java", "line": token.line})
conditional_block
persistent.py
# 2017 Red Hat Inc. # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: Ansible Core Team connection: persistent short_description: Us...
raise AnsibleError("Unable to find location of '%s'" % filename) p = subprocess.Popen( [python, find_file_in_path('ansible-connection'), to_text(os.getppid())], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdin = os.fdopen(master, 'wb', 0)...
fullpath = os.path.join(dirname, filename) if os.path.isfile(fullpath): return fullpath
conditional_block
persistent.py
# 2017 Red Hat Inc. # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: Ansible Core Team connection: persistent short_description: Us...
(self, in_path, out_path): pass def fetch_file(self, in_path, out_path): pass def close(self): self._connected = False def run(self): """Returns the path of the persistent connection socket. Attempts to ensure (within playcontext.timeout seconds) that the ...
put_file
identifier_name
persistent.py
# 2017 Red Hat Inc. # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: Ansible Core Team connection: persistent short_description: Us...
def close(self): self._connected = False def run(self): """Returns the path of the persistent connection socket. Attempts to ensure (within playcontext.timeout seconds) that the socket path exists. If the path exists (or the timeout has expired), returns the socket pa...
pass
identifier_body
persistent.py
# 2017 Red Hat Inc. # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: Ansible Core Team connection: persistent short_description: Us...
from ansible.module_utils.six.moves import cPickle from ansible.module_utils.connection import Connection as SocketConnection from ansible.errors import AnsibleError try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class Connection(Connec...
from ansible.plugins.connection import ConnectionBase from ansible.module_utils._text import to_text
random_line_split
Actions.ts
import {ActionButton} from "./ActionButton"; import {Align} from "../Constant/EnumType"; class ActionsBuilder { private _buttons: ActionButton[] = []; private _align: Align = Align.RIGHT; public add(button: ActionButton): ActionsBuilder { this._buttons.push(button); return this; } ...
let $: any = (<any>window).jQuery || (<any>window).$; let $dom = $(`<div class='actions'></div>`); if (this._align != null) { $dom.css('text-align', Align[this._align].toLowerCase()); } if (this._buttons && this._buttons.length > 0) { for (let button of ...
private createDom(): any {
random_line_split
Actions.ts
import {ActionButton} from "./ActionButton"; import {Align} from "../Constant/EnumType"; class ActionsBuilder { private _buttons: ActionButton[] = []; private _align: Align = Align.RIGHT; public add(button: ActionButton): ActionsBuilder { this._buttons.push(button); return this; } ...
(value: Align): ActionsBuilder { this._align = value; return this; } public build(): Actions { let actions = new Actions(); actions.align = this._align; actions.buttons = this._buttons; return actions; } } class Actions { private _buttons: ActionButton[...
align
identifier_name