code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def url_combo_activated(self, valid):
text = to_text_string(self.url_combo.currentText())
self.go_to(self.text_to_url(text)) | Load URL from combo box first item |
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs):
del params, kwargs
if rng is None:
msg = ('Dropout layer requires apply_fun to be called with a rng keyword '
'argument. That is, instead of `Dropout(params, inputs)`, call '
'it like `Dropout(params, inputs, rng=key)`.')
... | Layer construction function for a dropout layer with given rate. |
def load_config_yaml(self, flags, config_dict):
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_from_file(flags['YAML_FILE'], config_dict)
except KeyError:
print('Yam... | Load config dict and yaml dict and then override both with flags dict. |
def keys(self):
keys = []
for key, value in self.map.items():
if isinstance(value, Shovel):
keys.extend([key + '.' + k for k in value.keys()])
else:
keys.append(key)
return sorted(keys) | Return all valid keys |
def vectors(self, array):
if array.ndim != 2:
raise AssertionError('vector array must be a 2-dimensional array')
elif array.shape[1] != 3:
raise RuntimeError('vector array must be 3D')
elif array.shape[0] != self.n_points:
raise RuntimeError('Number of vectors... | Sets the active vector |
def _get_or_create_s3_bucket(s3, name):
exists = True
try:
s3.meta.client.head_bucket(Bucket=name)
except botocore.exceptions.ClientError as e:
error_code = int(e.response["Error"]["Code"])
if error_code == 404:
exists = False
else:
raise
if not ex... | Get an S3 bucket resource after making sure it exists |
def check_if_modified_since(self, dt, etag=None):
dt = dt.replace(microsecond=0)
if request.if_modified_since and dt <= request.if_modified_since:
raise SameContentException(etag, last_modified=dt) | Validate If-Modified-Since with current request conditions. |
def _to_str(dumped_val, encoding='utf-8', ordered=True):
_dict = OrderedDict if ordered else dict
if isinstance(dumped_val, dict):
return OrderedDict((k, _to_str(v, encoding)) for k,v in dumped_val.items())
elif isinstance(dumped_val, (list, tuple)):
return [_to_str(v, encoding) for v in dum... | Convert bytes in a dump value to str, allowing json encode |
def export_xlsx(self, key):
spreadsheet_file = self.client.files().get(fileId=key).execute()
links = spreadsheet_file.get('exportLinks')
downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
resp, content = self.client._http.request(downloadurl)
... | Download xlsx version of spreadsheet. |
def size(self):
"The canonical serialized size of this branch."
if getattr(self, '_size', None) is None:
self._size = getattr(self.node, 'size', 0)
return self._size | The canonical serialized size of this branch. |
def action_ipset(reader, *args):
ip_set = set()
for record in reader:
if record.log_status in (SKIPDATA, NODATA):
continue
ip_set.add(record.srcaddr)
ip_set.add(record.dstaddr)
for ip in ip_set:
print(ip) | Show the set of IPs seen in Flow Log records. |
def template(self):
s = Template(self._IPTABLES_TEMPLATE)
return s.substitute(filtertable='\n'.join(self.filters),
rawtable='\n'.join(self.raw),
mangletable='\n'.join(self.mangle),
nattable='\n'.join(self.nat),
date=datetime.today()) | Create a rules file in iptables-restore format |
def handleResponse(self, resp):
id=resp["id"]
evt = self.respEvents[id]
del(self.respEvents[id])
evt.handleResponse(resp) | handles a response by fireing the response event for the response coming in |
def new_media_status(self, media_status):
casts = self._casts
group_members = self._mz.members
for member_uuid in group_members:
if member_uuid not in casts:
continue
for listener in list(casts[member_uuid]['listeners']):
listener.multizone... | Handle reception of a new MediaStatus. |
def _deduplicate(lst):
out = []
for i in lst:
if i not in out:
out.append(i)
return out | Auxiliary function to deduplicate lst. |
def handle_cancelpayment(
payment_state: InitiatorPaymentState,
channelidentifiers_to_channels: ChannelMap,
) -> TransitionResult[InitiatorPaymentState]:
events = list()
for initiator_state in payment_state.initiator_transfers.values():
channel_identifier = initiator_state.channel_identi... | Cancel the payment and all related transfers. |
def peek(self, storagemodel:object, modeldefinition = None) -> StorageQueueModel:
try:
messages = modeldefinition['queueservice'].peek_messages(storagemodel._queuename, num_messages=1)
for message in messages:
storagemodel.mergemessage(message)
if storagemodel... | lookup the next message in queue |
def use_gae_thread():
global _THREAD_CLASS
try:
from google.appengine.api.background_thread import background_thread
_THREAD_CLASS = background_thread.BackgroundThread
except ImportError:
_logger.error(
u'Could not install appengine background threads!'
u' Ple... | Makes ``Client``s started after this use the appengine thread class. |
def detect_protocol(cls, message):
main = cls._message_to_payload(message)
def protocol_for_payload(payload):
if not isinstance(payload, dict):
return JSONRPCLoose
version = payload.get('jsonrpc')
if version == '2.0':
return JSONRPCv2
... | Attempt to detect the protocol from the message. |
def toList(self):
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByIndex(i)[0]
for i in range(self.getNumRows())
... | Return a list with the DataFrame data. |
def sign(self, payload):
if self.authenticator:
return self.authenticator.signed(payload)
return payload | Sign payload using the supplied authenticator |
def read_json(file_path):
try:
with open(file_path, 'r') as f:
config = json_tricks.load(f)
except ValueError:
print(' '+'!'*58)
print(' Woops! Looks the JSON syntax is not valid in:')
print(' {}'.format(file_path))
print(' Note: commonly this ... | Read in a json file and return a dictionary representation |
async def _setcolor(self, *, color : discord.Colour):
data = self.bot.config.get("meta", {})
data['default_color'] = str(color)
await self.bot.config.put('meta', data)
await self.bot.responses.basic(message="The default color has been updated.") | Sets the default color of embeds. |
def opendocx(file):
mydoc = zipfile.ZipFile(file)
xmlcontent = mydoc.read('word/document.xml')
document = etree.fromstring(xmlcontent)
return document | Open a docx file, return a document XML tree |
def configure(self):
if self.debug is not None and not self.debug:
self._remove_debug_handlers()
self._remove_debug_only()
logging.config.dictConfig(self.config)
try:
logging.captureWarnings(True)
except AttributeError:
pass | Configure the Python stdlib logger |
def GetSize(cls):
format_str = "".join([x[0] for x in cls._fields])
return struct.calcsize(format_str) | Calculate the size of the struct. |
def OpenDevice(path, enum=False):
desired_access = GENERIC_WRITE | GENERIC_READ
share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE
if enum:
desired_access = 0
h = kernel32.CreateFileA(path,
desired_access,
share_mode,
None, OPEN_E... | Open the device and return a handle to it. |
def j_delete(self, *args):
uid = args[0]
current_infor = MPost.get_by_uid(uid)
tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid'])
is_deleted = MPost.delete(uid)
MCategory.update_count(current_infor.extinfo['def_cat_uid'])
if is_deleted:
output ... | Delete the post, but return the JSON. |
def fix_return_value(v, method_name, method=None, checker=None):
method_name = (method_name or method.__func__.__name__).replace("check_","")
if v is None or not isinstance(v, Result):
v = Result(value=v, name=method_name)
v.name = v.name or method_name
v.checker = checker
v.che... | Transforms scalar return values into Result. |
def dirname(hdfs_path):
scheme, netloc, path = parse(hdfs_path)
return unparse(scheme, netloc, os.path.dirname(path)) | Return the directory component of ``hdfs_path``. |
def _get_struct_filterlist(self):
obj = _make_object("FilterList")
obj.NumberOfFilters = unpack_ui8(self._src)
obj.Filter = filters = []
filter_type = [
("DropShadowFilter", self._get_struct_dropshadowfilter),
("BlurFilter", self._get_struct_blurfilter),
... | Get the values for the FILTERLIST record. |
def delete(self):
try:
return self._server.query('/library/sections/%s' % self.key, method=self._server._session.delete)
except BadRequest:
msg = 'Failed to delete library %s' % self.key
msg += 'You may need to allow this permission in your Plex settings.'
... | Delete a library section. |
def fail(self) -> None:
_debug("fail")
def on_commit(_obj):
raise_testfailure("commit")
def on_rollback(_obj):
raise_testfailure("rollback")
return self._process(on_commit, on_rollback) | for testing purposes only. always fail in commit |
def stop_sync(self):
conn_ids = self.conns.get_connections()
for conn in list(conn_ids):
try:
self.disconnect_sync(conn)
except HardwareError:
pass
self.client.disconnect()
self.conns.stop() | Synchronously stop this adapter |
def decrypt_file(path, password=None):
global PASSWORD_FILE
if not password:
password = PASSWORD_FILE
if path and not os.path.isfile(path):
raise SystemExit(_error_codes.get(106))
query = 'openssl aes-128-cbc -d -salt -in {0} -out {1} -k {2}'
with hide('output'):
local(query.... | Decrypt file with AES method and password. |
def load(self, filename):
with open(filename, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies:
for proxy in proxies[protocol]:
self.proxies[protocol][proxy['addr']] = Proxy(
proxy['addr'], proxy['protocol'], proxy['weight'],
... | Load proxies from file |
def release_locks(self):
if self._remotelib:
self._remotelib.run_keyword('release_locks',
[self._my_id], {})
else:
_PabotLib.release_locks(self, self._my_id) | Release all locks called by instance. |
def project(self, projector = None):
msg = "'%s.project': ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
if projector is None:
try:
self.projector = ugali.utils.projector.Projector(self.config['coords']['reference'][0],
... | Project coordinates on sphere to image plane using Projector class. |
def run_commands(commands,
directory,
env=None
):
if env is None:
env = os.environ.copy()
for step in commands:
if isinstance(step, (list, six.string_types)):
execution_dir = directory
raw_command = step
elif step.... | Run list of commands. |
def load_child_node(self, key):
index = self.get_child_index(key)
if key is None:
return EmptyNode(None)
else:
path = os.path.join(self.get_value(), key)
if index < self.dir_count:
return DirectoryNode(path, self.display, parent=self)
... | Return either a FileNode or DirectoryNode |
def __calculate_current_value(self, asset_class: AssetClass):
if asset_class.stocks:
stocks_sum = Decimal(0)
for stock in asset_class.stocks:
stocks_sum += stock.value_in_base_currency
asset_class.curr_value = stocks_sum
if asset_class.classes:
... | Calculate totals for asset class by adding all the children values |
def from_dict(cls, d):
stats = []
for (filename, lineno, name), stat_values in d.iteritems():
if len(stat_values) == 5:
ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values
else:
ncalls, ncall_nr, total_time, cum_time = stat_values
... | Used to create an instance of this class from a pstats dict item |
def update_trackers(self):
direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on')
self.direct_topics_count = direct_approved_topics.count()
self.direct_posts_count = direct_approved_topics.aggregate(
total_posts_count=Sum('posts_count'))['total_posts_cou... | Updates the denormalized trackers associated with the forum instance. |
def reset_env(exclude=[]):
if os.getenv(env.INITED):
wandb_keys = [key for key in os.environ.keys() if key.startswith(
'WANDB_') and key not in exclude]
for key in wandb_keys:
del os.environ[key]
return True
else:
return False | Remove environment variables, used in Jupyter notebooks |
def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
cur_layers = []
if bottom_layers is not None:
cur_layers.extend(bottom_layers)
cur_layers.extend([layers.Branch(), layers.Parallel(
lay... | A policy and value net function. |
def from_dict(cls, d):
tdos = PhononDos.from_dict(d)
struct = Structure.from_dict(d["structure"])
pdoss = {}
for at, pdos in zip(struct, d["pdos"]):
pdoss[at] = pdos
return cls(struct, tdos, pdoss) | Returns CompleteDos object from dict representation. |
def _sysv_services():
_services = []
output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False)
for line in output.splitlines():
comps = line.split()
try:
if comps[1].startswith('0:'):
_services.append(comps[0])
except IndexError:
... | Return list of sysv services. |
def delete(dataset):
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | Use this function to delete dataset by it's id. |
def prox_soft_plus(X, step, thresh=0):
return prox_plus(prox_soft(X, step, thresh=thresh), step) | Soft thresholding with projection onto non-negative numbers |
def OnPaste(self, event):
data = self.main_window.clipboard.get_clipboard()
focus = self.main_window.FindFocus()
if isinstance(focus, wx.TextCtrl):
focus.WriteText(data)
else:
key = self.main_window.grid.actions.cursor
with undo.group(_("Paste")):
... | Clipboard paste event handler |
def _is_admin(user_id):
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | Is the specified user an admin |
def calculateRange(self):
if not self.autoRangeCti or not self.autoRangeCti.configValue:
return (self.rangeMinCti.data, self.rangeMaxCti.data)
else:
rangeFunction = self._rangeFunctions[self.autoRangeMethod]
return rangeFunction() | Calculates the range depending on the config settings. |
def rank_features(self, inputs: pd.DataFrame, targets: pd.DataFrame, problem_type='classification') -> pd.DataFrame:
try:
X = normalize( \
inputs.apply(pd.to_numeric, errors='coerce') \
.applymap(lambda x: 0.0 if np.isnan(x) else x) \
... | Rank features using Random Forest classifier and the recursive feature elimination |
def ui_label(self):
return ': '.join(filter(None, [
self.ui_device_presentation,
self.ui_id_label or self.ui_id_uuid or self.drive_label
])) | UI string identifying the partition if possible. |
def to_string(self, value):
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
return self.to_json(value) | String gets serialized and deserialized without quote marks. |
def verb_chain_texts(self):
if not self.is_tagged(VERB_CHAINS):
self.tag_verb_chains()
return self.texts(VERB_CHAINS) | The list of texts of ``verb_chains`` layer elements. |
def render_django_template(self, template_path, context=None, i18n_service=None):
context = context or {}
context['_i18n_service'] = i18n_service
libraries = {
'i18n': 'xblockutils.templatetags.i18n',
}
_libraries = None
if django.VERSION[0] == 1 and django.VE... | Evaluate a django template by resource path, applying the provided context. |
def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True):
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(layer.input_channel + n_add,
layer.filters,
kernel_size=layer.kernel_size,
... | wider next conv layer. |
def __start(self):
thread = Thread(target=self.__loop, args=())
thread.daemon = True
thread.start()
self.__enabled = True | Start a new thread to process Cron |
def _set_trace(self, skip=0):
frame = sys._getframe().f_back
for i in range(skip):
frame = frame.f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
... | Start debugging from here. |
def envget(var, default=None):
if 'pyraf' in sys.modules:
from pyraf import iraf
else:
iraf = None
try:
if iraf:
return iraf.envget(var)
else:
raise KeyError
except KeyError:
try:
return _varDict[var]
except KeyError:
... | Get value of IRAF or OS environment variable. |
def upload(self, fileobj, bucket, key, transfer_config=None, subscribers=None):
check_io_access(fileobj, os.R_OK, True)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.SEND) | upload a file using Aspera |
def delay_2(year):
last = delay_1(year - 1)
present = delay_1(year)
next_ = delay_1(year + 1)
if next_ - present == 356:
return 2
elif present - last == 382:
return 1
else:
return 0 | Check for delay in start of new year due to length of adjacent years |
def setup_ufw_rules():
current_rules = server_state('ufw_rules')
if current_rules: current_rules = set(current_rules)
else: current_rules = set([])
role = env.role_lookup[env.host_string]
firewall_rules = set(env.firewall_rules[role])
if not env.overwrite and firewall_rules == current_rules: ret... | Setup ufw app rules from application templates and settings UFW_RULES |
def id_to_name(id):
name = pdgid_names.get(id)
if not name:
name = repr(id)
return name | Convert a PDG ID to a printable string. |
def _on_item_clicked(self, item):
if item:
name = item.data(0, QtCore.Qt.UserRole)
if name:
go = name.block.blockNumber()
helper = TextHelper(self._editor)
if helper.current_line_nbr() != go:
helper.goto_line(go, column=... | Go to the item position in the editor. |
def kill(self):
try:
os.unlink(self.server_address)
except OSError:
if os.path.exists(self.server_address):
raise | Remove the socket as it is no longer needed. |
def version(rest):
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadata.version(pkg) | Get the version of pmxbot or one of its plugins |
def remove_log_action(portal):
logger.info("Removing Log Tab ...")
portal_types = api.get_tool("portal_types")
for name in portal_types.listContentTypes():
ti = portal_types[name]
actions = map(lambda action: action.id, ti._actions)
for index, action in enumerate(actions):
... | Removes the old Log action from types |
def channels_kick(self, room_id, user_id, **kwargs):
return self.__call_api_post('channels.kick', roomId=room_id, userId=user_id, kwargs=kwargs) | Removes a user from the channel. |
def pubkey(self, identity, ecdh=False):
curve_name = identity.get_curve_name(ecdh)
path = _expand_path(identity.get_bip32_address(ecdh))
if curve_name == 'nist256p1':
p2 = '01'
else:
p2 = '02'
apdu = '800200' + p2
apdu = binascii.unhexlify(apdu)
... | Get PublicKey object for specified BIP32 address and elliptic curve. |
def translation_activate_block(function=None, language=None):
def _translation_activate_block(function):
def _decorator(*args, **kwargs):
tmp_language = translation.get_language()
try:
translation.activate(language or settings.LANGUAGE_CODE)
return fun... | Activate language only for one method or function |
def tostr(self, object, indent=-2):
history = []
return self.process(object, history, indent) | get s string representation of object |
def printCols(strlist,cols=5,width=80):
nlines = (len(strlist)+cols-1)//cols
line = nlines*[""]
for i in range(len(strlist)):
c, r = divmod(i,nlines)
nwid = c*width//cols - len(line[r])
if nwid>0:
line[r] = line[r] + nwid*" " + strlist[i]
else:
line[r]... | Print elements of list in cols columns |
def render(self, template, filename, context={}, filters={}):
filename = os.path.normpath(filename)
path, file = os.path.split(filename)
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
path, fil... | Renders a Jinja2 template to text. |
def extern_store_set(self, context_handle, vals_ptr, vals_len):
c = self._ffi.from_handle(context_handle)
return c.to_value(OrderedSet(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len))) | Given storage and an array of Handles, return a new Handle to represent the set. |
def _is_numeric(self, values):
if len(values) > 0:
assert isinstance(values[0], (float, int)), \
"values must be numbers to perform math operations. Got {}".format(
type(values[0]))
return True | Check to be sure values are numbers before doing numerical operations. |
def uninstall(self):
if not self._uninstallable:
_tracer().log('Not uninstalling {}'.format(self), V=9)
return
if self in sys.meta_path:
sys.meta_path.remove(self)
maybe_exposed = frozenset(os.path.join(self._root, importable.path)
for importable in self._... | Uninstall this importer if possible and un-import any modules imported by it. |
def reset(self):
if self._self_thread is not None:
self._self_thread.cancel()
self._self_thread = None
self._self_thread = hub.spawn_after(self._interval, self) | Skip the next iteration and reset timer. |
def _process_converter(self, f, filt=None):
if filt is None:
filt = lambda col, c: True
needs_new_obj = False
new_obj = dict()
for i, (col, c) in enumerate(self.obj.iteritems()):
if filt(col, c):
new_data, result = f(col, c)
if resu... | Take a conversion function and possibly recreate the frame. |
def set(self, value):
value = min(self.max, max(self.min, value))
self._value = value
start_new_thread(self.func, (self.get(),)) | Set the value of the bar. If the value is out of bound, sets it to an extremum |
def _check_cronjob(self):
now = time.time()
self._last_tick = int(self._last_tick)
if now - self._last_tick < 1:
return False
self._last_tick += 1
for project in itervalues(self.projects):
if not project.active:
continue
if proj... | Check projects cronjob tick, return True when a new tick is sended |
def all_resource_urls(query):
urls = []
next = True
while next:
response = requests.get(query)
json_data = json.loads(response.content)
for resource in json_data['results']:
urls.append(resource['url'])
if bool(json_data['next']):
query = json_data['ne... | Get all the URLs for every resource |
def router_connections(self):
clients = []
for server in self._routers:
if Servers().is_alive(server):
client = self.create_connection(Servers().hostname(server))
clients.append(client)
return clients | Return a list of MongoClients, one for each mongos. |
def translate_github_exception(func):
@functools.wraps(func)
def _wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except UnknownObjectException as e:
logger.exception('GitHub API 404 Exception')
raise NotFoundError(str(e))
except GithubExce... | Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions. |
def selectcontains(table, field, value, complement=False):
return selectop(table, field, value, operator.contains,
complement=complement) | Select rows where the given field contains the given value. |
def parse(self, url):
parsed_url = urlparse.urlparse(url)
try:
default_config = self.CONFIG[parsed_url.scheme]
except KeyError:
raise ValueError(
'unrecognised URL scheme for {}: {}'.format(
self.__class__.__name__, url))
handle... | Return a configuration dict from a URL |
def start_module(self):
self.prepare_module()
if not (self.disabled or self.terminated):
self._py3_wrapper.log("starting module %s" % self.module_full_name)
self._py3_wrapper.timeout_queue_add(self) | Start the module running. |
def _get_satellite_tile(self, x_tile, y_tile, z_tile):
cache_file = "mapscache/{}.{}.{}.jpg".format(z_tile, x_tile, y_tile)
if cache_file not in self._tiles:
if not os.path.isfile(cache_file):
url = _IMAGE_URL.format(z_tile, x_tile, y_tile, _KEY)
data = reques... | Load up a single satellite image tile. |
def on_epoch_begin(self, **kwargs):
"Initialize the metrics for this epoch."
self.metrics = {name:0. for name in self.names}
self.nums = 0 | Initialize the metrics for this epoch. |
def doNew(self, WHAT={}, **params):
if hasattr(WHAT, '_modified'):
for key in WHAT:
if key not in ['RECORDID','MODID']:
if WHAT.__new2old__.has_key(key):
self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), WHAT[key])
else:
self._addDBParam(key, WHAT[key])
elif type(WHAT)==dict:
f... | This function will perform the command -new. |
def inactive_response(self, request):
inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '')
if inactive_url:
return HttpResponseRedirect(inactive_url)
else:
return self.error_to_response(request, {'error': _("This user account is marked as inactive.")}) | Return an inactive message. |
def as_python(self, name: str) -> str:
if self._ruleTokens:
pattern = "jsg.JSGPattern(r'{}'.format({}))".\
format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)]))
else:
pattern = "jsg.JSGPattern(r'{}')".format(self._... | Return the python representation |
def update_policy(self,defaultHeaders):
if self.inputs is not None:
for k,v in defaultHeaders.items():
if k not in self.inputs:
self.inputs[k] = v
return self.inputs
else:
return self.inputs | if policy in default but not input still return |
def dhms(secs):
dhms = [0, 0, 0, 0]
dhms[0] = int(secs // 86400)
s = secs % 86400
dhms[1] = int(s // 3600)
s = secs % 3600
dhms[2] = int(s // 60)
s = secs % 60
dhms[3] = int(s+.5)
return dhms | return days,hours,minutes and seconds |
async def kick(self, channel, target, reason=None):
if not self.in_channel(channel):
raise NotInChannel(channel)
if reason:
await self.rawmsg('KICK', channel, target, reason)
else:
await self.rawmsg('KICK', channel, target) | Kick user from channel. |
def ensure_versions_dir_exists(tfenv_path):
versions_dir = os.path.join(tfenv_path, 'versions')
if not os.path.isdir(tfenv_path):
os.mkdir(tfenv_path)
if not os.path.isdir(versions_dir):
os.mkdir(versions_dir)
return versions_dir | Ensure versions directory is available. |
def parse_job_files(self):
repo_jobs = []
for rel_job_file_path, job_info in self.job_files.items():
LOGGER.debug("Checking for job definitions in %s", rel_job_file_path)
jobs = self.parse_job_definitions(rel_job_file_path, job_info)
LOGGER.debug("Found %d job definit... | Check for job definitions in known zuul files. |
def date(objet):
if objet:
return "{}/{}/{}".format(objet.day, objet.month, objet.year)
return "" | abstractRender d'une date datetime.date |
def _create_filter(self):
self._product_filter = {}
for chip in itertools.chain(iter(self._family.targets(self._tile.short_name)),
iter([self._family.platform_independent_target()])):
for key, prods in chip.property('depends', {}).items():
... | Create a filter of all of the dependency products that we have selected. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.