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 |
|---|---|---|---|---|
version.py | #!/usr/bin/python3
"""Script to determine the Pywikibot version (tag, revision and date).
.. versionchanged:: 7.0
version script was moved to the framework scripts folder
"""
#
# (C) Pywikibot team, 2007-2021
#
# Distributed under the terms of the MIT license.
#
import codecs
import os
import sys
import pywikibot
... | with codecs.open(requests.certs.where(), 'r', 'utf-8') as cert_file:
text = cert_file.read()
if WMF_CACERT in text:
has_wikimedia_cert = True
pywikibot.output(' certificate test: {}'
.format('ok' if has_wikimedia_cert else 'not ok'))
... | """Print pywikibot version and important settings."""
pywikibot.output('Pywikibot: ' + getversion())
pywikibot.output('Release version: ' + pywikibot.__version__)
pywikibot.output('setuptools version: ' + setuptools.__version__)
pywikibot.output('mwparserfromhell version: '
+ mwpars... | identifier_body |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | """
sql_query = Challenge.query
if serial is not None:
# filter for serial
sql_query = sql_query.filter(Challenge.serial == serial)
if transaction_id is not None:
# filter for transaction id
sql_query = sql_query.filter(Challenge.transaction_id ==
... | :return: list of objects | random_line_split |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | erial=None, transaction_id=None,
sortby=Challenge.timestamp,
sortdir="asc", psize=15, page=1):
"""
This function is used to retrieve a challenge list, that can be displayed in
the Web UI. It supports pagination.
Each retrieved page will also contai... | t_challenges_paginate(s | identifier_name |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | else:
# exact match
sql_query = sql_query.filter(Challenge.serial == serial)
if transaction_id is not None and transaction_id.strip("*"):
# filter for serial
if "*" in transaction_id:
# match with "like"
sql_query = sql_query.filter(Challenge.t... | l_query = sql_query.filter(Challenge.serial.like(serial.replace(
"*", "%")))
| conditional_block |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | sql_query = _create_challenge_query(serial=serial,
transaction_id=transaction_id)
if isinstance(sortby, six.string_types):
# convert the string to a Challenge column
cols = Challenge.__table__.columns
sortby = cols.get(sortby)
if sortdir == "... | "
This function is used to retrieve a challenge list, that can be displayed in
the Web UI. It supports pagination.
Each retrieved page will also contain a "next" and a "prev", indicating
the next or previous page. If either does not exist, it is None.
:param serial: The serial of the token
:par... | identifier_body |
http.py | AND FIXES
DEMANDS data IS ONE OF:
* A JSON-SERIALIZABLE STRUCTURE, OR
* LIST OF JSON-SERIALIZABLE STRUCTURES, OR
* None
Parameters
* zip - ZIP THE REQUEST BODY, IF BIG ENOUGH
* json - JSON-SERIALIZABLE STRUCTURE
* retry - {"times": x, "sleep": y} STRUCTURE
THE BYTE_STRINGS (b""... | self.shared = Data(
length=length,
locker=Lock(),
stream=stream,
done_read=0,
file=file_,
buffer=mmap(file_.fileno(), length)
) | conditional_block | |
http.py | _json
from pyLibrary import convert
from mo_logs.exceptions import Except
from mo_logs import Log
from mo_dots import Data, coalesce, wrap, set_default, unwrap
from pyLibrary.env.big_data import safe_size, ibytes2ilines, icompressed2ibytes
from mo_math import Math
from jx_python import jx
from mo_threads import Thread,... |
def get_json(url, **kwargs):
"""
ASSUME RESPONSE IN IN JSON
"""
response = get(url, **kwargs)
c = response.all_content
return mo_json.json2value(convert.utf82unicode(c))
def options(url, **kwargs):
kwargs.setdefault(b'allow_redirects', True)
kwargs[b"stream"] = True
return HttpRe... | kwargs.setdefault(b'allow_redirects', True)
kwargs[b"stream"] = True
return HttpResponse(request(b'get', url, **kwargs)) | identifier_body |
http.py | mo_json
from pyLibrary import convert
from mo_logs.exceptions import Except
from mo_logs import Log
from mo_dots import Data, coalesce, wrap, set_default, unwrap
from pyLibrary.env.big_data import safe_size, ibytes2ilines, icompressed2ibytes
from mo_math import Math
from jx_python import jx
from mo_threads import Thre... | c = response.content
try:
details = mo_json.json2value(convert.utf82unicode(c))
except Exception as e:
Log.error("Unexpected return value {{content}}", content=c, cause=e)
if response.status_code not in [200, 201]:
Log.error("Bad response", cause=Except.wrap(details))
retur... | Log.error("Expecting `json` parameter")
response = post(url, **kwargs) | random_line_split |
http.py |
* LIST OF JSON-SERIALIZABLE STRUCTURES, OR
* None
Parameters
* zip - ZIP THE REQUEST BODY, IF BIG ENOUGH
* json - JSON-SERIALIZABLE STRUCTURE
* retry - {"times": x, "sleep": y} STRUCTURE
THE BYTE_STRINGS (b"") ARE NECESSARY TO PREVENT httplib.py FROM **FREAKING OUT**
IT APPEARS req... | __iter__ | identifier_name | |
layers.py | 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 OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lic... |
return compat_utils.batch_to_space(
input=tf.tile(images, [scale**2, 1, 1, 1]),
crops=[[0, 0], [0, 0]],
block_shape=scale)
def minibatch_mean_stddev(x):
"""Computes the standard deviation average.
This is used by the discriminator as a form of batch discrimination.
Args:
x: A `Tensor`... | return images | conditional_block |
layers.py | 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 OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lic... | Returns:
A `Tensor` of NHWC format where the last dimension has size `filters`.
"""
if not isinstance(kernel_size, (list, tuple)):
kernel_size = [kernel_size] * 2
kernel_size = list(kernel_size)
def _apply_kernel(kernel_shape, kernel_initializer):
return tf.layers.conv2d(
x,
filte... | """Custom conv2d layer.
In comparison with tf.layers.conv2d this implementation use the He initializer
to initialize convolutional kernel and the weight scaling trick (if
`use_weight_scaling` is True) to equalize learning rates. See
https://arxiv.org/abs/1710.10196 for more details.
Args:
x: A `Tensor` ... | identifier_body |
layers.py | 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 OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lic... | Returns:
A float of he initializer scale.
"""
fan_in = np.prod(shape[:-1])
return np.sqrt(2. / ((1. + slope**2) * fan_in))
def _custom_layer_impl(apply_kernel, kernel_shape, bias_shape, activation,
he_initializer_slope, use_weight_scaling):
"""Helper function to implement custom_x... |
Args:
shape: A list of ints representing the dimensions of a tensor.
slope: A float representing the slope of the ReLu following the layer.
| random_line_split |
layers.py | 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 OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lic... | (kernel_shape, kernel_initializer):
return tf.layers.conv2d(
x,
filters=filters,
kernel_size=kernel_shape[0:2],
strides=strides,
padding=padding,
use_bias=False,
kernel_initializer=kernel_initializer)
with tf.variable_scope(scope, reuse=reuse):
return _... | _apply_kernel | identifier_name |
vs-11.0-scc-files.py | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to us... | \t\t<SccProjectName>Perforce Project</SccProjectName>
\t\t<SccLocalPath>.</SccLocalPath>
\t\t<SccProvider>MSSCCI:Perforce SCM</SccProvider>
"""
test.write('SConstruct', SConscript_contents)
test.run(arguments="Test.vcxproj")
test.must_exist(test.workpath('Test.vcxproj'))
vcproj = test.read('Test.vcxproj', 'r')
expe... | \t\tSccProjectFilePathRelativizedFromConnection1 = .\\\\
\tEndGlobalSection
"""
expected_vcproj_sccinfo = """\ | random_line_split |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def | ():
parser = argparse.ArgumentParser(description='Generates SQLAlchemy model code from an existing database.')
parser.add_argument('url', nargs='?', help='SQLAlchemy url to the database')
parser.add_argument('--version', action='store_true', help="print the version number and exit")
parser.add_argument(... | main | identifier_name |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
parser = argparse.Ar... |
engine = create_engine(args.url)
metadata = MetaData(engine)
tables = args.tables.split(',') if args.tables else None
metadata.reflect(engine, args.schema, not args.noviews, tables)
outfile = codecs.open(args.outfile, 'w', encoding='utf-8') if args.outfile else sys.stdout
generator = CodeGener... | print('You must supply a url\n', file=sys.stderr)
parser.print_help()
return | conditional_block |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
parser = argparse.Ar... | parser.add_argument('--noindexes', action='store_true', help='ignore indexes')
parser.add_argument('--noconstraints', action='store_true', help='ignore constraints')
parser.add_argument('--nojoined', action='store_true', help="don't autodetect joined table inheritance")
parser.add_argument('--noinflect'... | parser.add_argument('--schema', help='load tables from an alternate schema')
parser.add_argument('--tables', help='tables to process (comma-separated, default: all)')
parser.add_argument('--noviews', action='store_true', help="ignore views") | random_line_split |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
| print('You must supply a url\n', file=sys.stderr)
parser.print_help()
return
engine = create_engine(args.url)
metadata = MetaData(engine)
tables = args.tables.split(',') if args.tables else None
metadata.reflect(engine, args.schema, not args.noviews, tables)
outfile = codecs... | parser = argparse.ArgumentParser(description='Generates SQLAlchemy model code from an existing database.')
parser.add_argument('url', nargs='?', help='SQLAlchemy url to the database')
parser.add_argument('--version', action='store_true', help="print the version number and exit")
parser.add_argument('--schem... | identifier_body |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... | (private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions) {}
createConnection(request: Request): XHRConnection {
return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
}
}
| constructor | identifier_name |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... |
ObservableWrapper.callNext(this.response, new Response(responseOptions));
// TODO(gdi2290): defer complete if array buffer until done
ObservableWrapper.callReturn(this.response);
});
this._xhr.addEventListener('error', (err) => {
var responseOptions = new ResponseOptions({body: err, t... | {
responseOptions = baseResponseOptions.merge(responseOptions);
} | conditional_block |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... | }
ObservableWrapper.callNext(this.response, new Response(responseOptions));
// TODO(gdi2290): defer complete if array buffer until done
ObservableWrapper.callReturn(this.response);
});
this._xhr.addEventListener('error', (err) => {
var responseOptions = new ResponseOptions({body:... | responseOptions = baseResponseOptions.merge(responseOptions); | random_line_split |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... | },
None => false,
}
}
} | random_line_split | |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... |
pub fn add_channel(&mut self, name: &str) {
self.channels.push(name.to_string());
self.display_channel(self.channels.len() as i32 - 1, name);
}
pub fn remove_channel(&mut self, name: &str) -> bool {
let index = self.channels.iter().position(|ref s| s.as_str() == name);
ma... | {
mvwaddstr(self.window.inner.id,
index,
1,
&format!("{} - {}", index + 1, name));
wrefresh(self.window.inner.id);
} | identifier_body |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... | (&mut self, name: &str) -> bool {
let index = self.channels.iter().position(|ref s| s.as_str() == name);
match index {
Some(index) => {
self.channels.remove(index);
// TODO: Separate this redraw code into its own function once this method is actually used
... | remove_channel | identifier_name |
FZH04.py | m','--mul', dest='mul', default=1.)
o.add_option('-z','--red', dest='red', default=12.)
opts,args = o.parse_args(sys.argv[1:])
print opts, args
Om,sig8,ns,h,Ob = 0.315, 0.829, 0.96, 0.673, 0.0487
Planck13 = {'baryonic_effects':True,'omega_k_0':0,'omega_M_0':0.315, 'omega_b_0':0.0487, 'n':0.96, 'N_nu':0, 'omega_lambda_... | (S0,deltac,smin,K,d=0.001):
Bp,Bo,Bm = BFZH(S0+d,deltac,smin,K), BFZH(S0,deltac,smin,K), BFZH(S0-d,deltac,smin,K)
return S0/Bo*(Bp-Bm)/2/d
def dlnBFlindlnS0(S0,deltac,smin,K,d=0.001):
Bp,Bo,Bm = BFZHlin(S0+d,deltac,smin,K), BFZHlin(S0,deltac,smin,K), BFZHlin(S0-d,deltac,smin,K)
return S0/Bo*(Bp-Bm)/2/d
##### m_mi... | dlnBFdlnS0 | identifier_name |
FZH04.py | .argv[1:])
print opts, args
Om,sig8,ns,h,Ob = 0.315, 0.829, 0.96, 0.673, 0.0487
Planck13 = {'baryonic_effects':True,'omega_k_0':0,'omega_M_0':0.315, 'omega_b_0':0.0487, 'n':0.96, 'N_nu':0, 'omega_lambda_0':0.685,'omega_n_0':0., 'sigma_8':0.829,'h':0.673}
cosmo = Planck13
def m2R(m):
rhobar = cd.cosmo_densities(**cosm... | S0max = sig0(m2R(M0min)) | conditional_block | |
FZH04.py | ','--mul', dest='mul', default=1.)
o.add_option('-z','--red', dest='red', default=12.)
opts,args = o.parse_args(sys.argv[1:])
print opts, args
Om,sig8,ns,h,Ob = 0.315, 0.829, 0.96, 0.673, 0.0487
Planck13 = {'baryonic_effects':True,'omega_k_0':0,'omega_M_0':0.315, 'omega_b_0':0.0487, 'n':0.96, 'N_nu':0, 'omega_lambda_0... |
def dlinSdlnR(lnR,d=0.001):
res = (n.log(sig0(n.exp(lnR+d)))-n.log(sig0(n.exp(lnR-d))))/d/2
return n.abs(res)
################################## MAIN ######################################
for z in [12., 16.]:
PLOT = True
zeta = 40.
K = scipy.special.erfinv(1-1./zeta)
Tvir = 1.E4
#z = 12.
deltac = Delt... | return RphysoR0(del0,z)*(1+z) | identifier_body |
FZH04.py | m','--mul', dest='mul', default=1.)
o.add_option('-z','--red', dest='red', default=12.)
opts,args = o.parse_args(sys.argv[1:])
print opts, args
Om,sig8,ns,h,Ob = 0.315, 0.829, 0.96, 0.673, 0.0487
Planck13 = {'baryonic_effects':True,'omega_k_0':0,'omega_M_0':0.315, 'omega_b_0':0.0487, 'n':0.96, 'N_nu':0, 'omega_lambda_... | def VdndlnR(lnR0):
S0 = sig0(n.exp(lnR0))
del0 = BFZH(S0,deltac,smin,K)
VoV0 = (RcovEul(del0,z))**3
return VoV0/dlnRdlnR0(lnR0,S0,del0)*S0*fFZH(S0,zeta,bFZH0,bFZH1)*dlinSdlnR(lnR0)
if True:
print 'computing z=',z
#Q = quad(lambda lnR: VdndlnR(lnR),n.log(Rmin),3.5) #integrated over eulerian coordinates
... | return VoV0*S0*fFZH(S0,zeta,bFZH0,bFZH1)*dlinSdlnR(lnR0) | random_line_split |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... | (fname):
params = {}
with open(fname,'r') as f:
lines = f.readlines()
for line in lines:
if line[0] == '#':
continue
data = line.split()
idx = int(data[0])
name = data[1]
ie1 = float(data[2])
ie2 = float(data... | read_data_file | identifier_name |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... |
else:
l = 5
if not l <= n:
raise ValueError('not l<=n')
print('anum,n,l,nval=',atomic_number,n,l,nval)
nseat = sum_array(nstates,n) -sum_array(nstates,n-1)
nseatopen = nseat - nval
for il in range(l+1,n+1):
nseatopen -= freedom[il]
print('nseat,nseatopen=',... | l = 4 | conditional_block |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... |
if __name__ == "__main__":
args = docopt(__doc__)
fname = args['DATA_FILE']
specorder = [ name for name in args['NAME'] ]
params = read_data_file(fname)
write_Coulomb_params(out_Coulomb,params,specorder)
| with open(fname,'w') as f:
#...declare it is 'variable_charge' Coulomb
f.write(' variable_charge \n')
n = 0
e0 = 0.0
for k in specorder:
n += 1
p = params[k]
anum = p[0]
name = p[1]
ie = p[2]
ea = -p[4]
... | identifier_body |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
| params = {}
with open(fname,'r') as f:
lines = f.readlines()
for line in lines:
if line[0] == '#':
continue
data = line.split()
idx = int(data[0])
name = data[1]
ie1 = float(data[2])
ie2 = float(data[3])
... | out_Coulomb= 'in.params.Coulomb'
def read_data_file(fname): | random_line_split |
plural.py | False],
["o$", "oes", None, False]
],
# 13/
# Miltary stuff (Major Generals).
[
["l$", "ls", "general-generals", False]
],
# 14/
# Otherwise, assume that the plural just adds -s
# (cats, programmes).
[
["$", "s", None, False]
],
]
# Suffix categories
plu... | noun_plural | identifier_name | |
plural.py | ],
["numen$", "numena", None, False],
["occiput$", "occipita", None, True],
],
# 6/
# Irregular inflections for common suffixes
# (synopses, mice, men).
[
["man$", "men", None, False],
["person$", "people", None, False],
["([lm])ouse$", "\\1ice", None, False],
["tooth$",... | "a-ata-classical" : ["anathema", "bema", "carcinoma", "charisma", "diploma", "dogma", "drama", "edema", "enema", "enigma", "gumma", "lemma", "lymphoma", "magma", "melisma", "miasma", "oedema", "sarcoma", "schema", "soma", "stigma", "stoma", "trauma"],
"is-ides-classical" : ["clitoris", "iris"],
"us-i-c... | random_line_split | |
plural.py | /
# Some words ending in -o take -os,
# the rest take -oes.
# Words in which the -o is preceded by a vowel always take -os
# (lassos, potatoes, bamboos).
[
["o$", "os", "o-os", False],
["([aeiou])o$", "\\1os", None, False],
["o$", "oes", None, False]
],
# 13/
# Miltary s... | if word in plural_categories[category] and (not classic or (classic and classical)):
if re.search(suffix, word) is not None:
return re.sub(suffix, inflection, word) | conditional_block | |
plural.py | "general-generals", False]
],
# 14/
# Otherwise, assume that the plural just adds -s
# (cats, programmes).
[
["$", "s", None, False]
],
]
# Suffix categories
plural_categories = {
"uninflected" : ["bison", "bream", "breeches", "britches", "carp", "chassis", "clippers", "c... | return plural(word, ADJECTIVE, classical, custom) | identifier_body | |
hat.ts | import type { ColorGroup } from '../static-types';
export const hat: ColorGroup = {
black: 'rgba(38, 46, 51, 1)',
blue01: 'rgba(101, 201, 255, 1)',
blue02: 'rgba(81, 153, 228, 1)',
blue03: 'rgba(37, 85, 124, 1)',
gray01: 'rgba(229, 229, 229, 1)',
gray02: 'rgba(146, 149, 152, 1)',
heather: 'rgba(60, 79, 9... | }; | random_line_split | |
runtests.py | .contrib.flatpages',
'redirects_tests': 'django.contrib.redirects',
}
def get_test_modules():
modules = []
discovery_paths = [
(None, RUNTESTS_DIR),
# GIS tests are in nested apps
('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')),
]
for modpath, dirpath in discovery_p... | teardown(state)
return failures
def bisect_tests(bisection_label, options, test_labels):
state = setup(options.verbosity, test_labels)
test_labels = test_labels or get_installed()
print('***** Bisecting test suite: %s' % ' '.join(test_labels))
# Make sure the bisection point isn't in the t... | state = setup(verbosity, test_labels)
extra_tests = []
# Run the test suite, including the extra validation tests.
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.runner.DiscoverRunner'
TestRunner = get_runner(settings)
test_runner = TestRunner(
verbosi... | identifier_body |
runtests.py | TestCase.available_apps = None
state = {
'INSTALLED_APPS': settings.INSTALLED_APPS,
'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
# Remove the following line in Django 1.10.
'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
'TEMPLATES': settings.TEMPLATES,
'LANGU... | if failures:
print('***** Found problem pair with %s' % label)
return
print('***** No problem pair found') | random_line_split | |
runtests.py | _found_in_labels and module_label not in installed_app_names:
if verbosity >= 2:
print("Importing application %s" % module_name)
settings.INSTALLED_APPS.append(module_label)
# Add contrib.gis to INSTALLED_APPS if needed (rather than requiring
# @override_settings(INSTALL... | sys.exit(bool(failures)) | conditional_block | |
runtests.py | .contrib.flatpages',
'redirects_tests': 'django.contrib.redirects',
}
def get_test_modules():
modules = []
discovery_paths = [
(None, RUNTESTS_DIR),
# GIS tests are in nested apps
('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')),
]
for modpath, dirpath in discovery_p... | paired_tests | identifier_name | |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... | state: ValidityStatus::Valid
}
}
pub fn new(window: &Window, element: &Element) -> Root<ValidityState> {
reflect_dom_object(box ValidityState::new_inherited(element),
window,
ValidityStateBinding::Wrap)
}
}
impl ValidityStat... | impl ValidityState {
fn new_inherited(element: &Element) -> ValidityState {
ValidityState {
reflector_: Reflector::new(),
element: JS::from_ref(element), | random_line_split |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... |
// https://html.spec.whatwg.org/multipage/#dom-validitystate-valid
fn Valid(&self) -> bool {
false
}
}
| {
false
} | identifier_body |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... | (&self) -> bool {
false
}
// https://html.spec.whatwg.org/multipage/#dom-validitystate-typemismatch
fn TypeMismatch(&self) -> bool {
false
}
// https://html.spec.whatwg.org/multipage/#dom-validitystate-patternmismatch
fn PatternMismatch(&self) -> bool {
false
}
... | ValueMissing | identifier_name |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replic... | match field.1.get_type() {
ValueType::VARCHAR => println!("{}", try!(field.1.get_string())),
ValueType::INT => println!("{}", try!(field.1.get_int32())),
ValueType::SET =>
for phone_numbers in try!(fi... | for field in fields_iter {
println!("{}", field.0); | random_line_split |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() | "CREATE TYPE examples.address \
(street text, city text, zip int, phone set<frozen<phone_numbers>>)"
,0
);
session.execute(
"CREATE TABLE examples.udt (id timeuuid, address frozen<address>, PRIMARY KEY(id))",
0
);
insert_into_udt(&session, schema).unwrap();
... | {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replication = \
{ 'class': 'SimpleStrategy', 'replic... | identifier_body |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replic... | (session: &Session) -> Result<(), CassandraError> {
let query = "INSERT INTO examples.udt (id, address) VALUES (?, ?)";
let mut statement = Statement::new(query, 2);
let uuid_gen = UuidGen::new();
let udt_address = schema.get_udt("examples", "address");
let udt_phone = cass_keyspace_meta_user_type_b... | insert_into_udt | identifier_name |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | ,
startAutoplay () {
if (this.autoplay) {
this.autoplayInterval = setInterval(() => {
this.dir === 'ltr' ? this.goPrev() : this.goNext()
}, this.autoplayTimeout)
}
}
},
mounted () {
if (!process.server && this.au... | {
if (this.autoplayInterval) {
this.autoplayInterval = clearInterval(this.autoplayInterval)
}
} | identifier_body |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | }
},
mounted () {
if (!process.server && this.autoplayHoverPause) {
this.$el.addEventListener('mouseenter', this.pauseAutoplay)
this.$el.addEventListener('mouseleave', this.startAutoplay)
this.startAutoplay()
}
}
}
export default autoplay | } | random_line_split |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... |
},
startAutoplay () {
if (this.autoplay) {
this.autoplayInterval = setInterval(() => {
this.dir === 'ltr' ? this.goPrev() : this.goNext()
}, this.autoplayTimeout)
}
}
},
mounted () {
if (!process.server ... | {
this.autoplayInterval = clearInterval(this.autoplayInterval)
} | conditional_block |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | () {
if (!process.server) {
this.pauseAutoplay()
this.$el.removeEventListener('mouseenter', this.pauseAutoplay)
this.$el.removeEventListener('mouseleave', this.startAutoplay)
}
},
methods: {
pauseAutoplay () {
if (this.autoplayInterval) {... | destroyed | identifier_name |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... | return
try:
session.messagesReceived(messages)
except Exception:
log.msg('jsonp_send: messagesReceived() failed')
session.close()
self.write('Message handler failed.')
self.set_status(500)
return
self.write('... | self.write("Broken JSON encoding.")
self.set_status(500) | random_line_split |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... |
class JSONPSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None:
self.set_status(404)
return
... | msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))
self.set_header('Content-Type',
'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(msg))
# FIXME
self.set_header('Etag', 'dummy')
self.write(msg)
self... | identifier_body |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... |
#data = self.request.body.decode('utf-8')
data = self.request.body
ctype = self.request.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
log.msg('jsonp_send: Invalid payload.')
... | self.set_status(404)
return | conditional_block |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... | (self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None:
self.set_status(404)
return
#data = self.request.body.decode('utf-8')
data = self.request.... | post | identifier_name |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class | {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public costsHealth: boolean;
public elite: boolean;
public health: number;
public hideStats: boolean;
public id: string;
public name: string;
public mult... | CardDef | identifier_name |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... | } else if (this.type === CardType.HERO && props.armor) {
// Hero health gem is Armor
this.health = props.armor;
}
this.collectionText = props.collectionText || "";
this.text = props.text || "";
}
}
| {
this.attack = props.attack || 0;
this.armor = props.armor || 0;
this.cardClass = cleanEnum(props.cardClass, CardClass) as CardClass;
this.cardSet = cleanEnum(props.set, CardSet) as CardSet;
this.cost = props.cost || 0;
this.costsHealth = props.costsHealth || false;
this.elite = props.elite || false;
t... | identifier_body |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... | public name: string;
public multiClassGroup: MultiClassGroup;
public rarity: Rarity;
public race: Race;
public silenced: boolean;
public text: string;
public type: CardType;
constructor(props: any) {
this.attack = props.attack || 0;
this.armor = props.armor || 0;
this.cardClass = cleanEnum(props.cardClas... | random_line_split | |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... |
this.collectionText = props.collectionText || "";
this.text = props.text || "";
}
}
| {
// Hero health gem is Armor
this.health = props.armor;
} | conditional_block |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... | (x, weights, biases):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, timesteps, n_input)
# Required shape: 'timesteps' tensors list of shape (batch_size, n_input)
# Unstack to get a list of 'timesteps' tensors of shape (batch_size,
# n_input)
... | RNN | identifier_name |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... |
logits = RNN(X, weights, biases)
prediction = tf.nn.softmax(logits)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate... | x = tf.unstack(x, timesteps, 1)
# Define a lstm cell with tensorflow
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
# Get lstm cell output
outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
# Linear activation, using rnn inner loop last output
return tf.matmul(output... | identifier_body |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... |
print("Optimization Finished!")
print(loss_group)
print(epoch_group)
plt.plot(epoch_group, loss_group)
plt.show()
end_time = time.time()
time_dif = end_time - start_time
print("Time usage: " + str(timedelta(seconds=int(round(time_dif)))))
# Calculate accuracy for 128 mnist test im... | loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
loss_group.append(loss)
epoch_group.append(step)
print("Step " + str(step) + ", Minibatch Loss= " +
"{:.4f}".format(loss) +... | conditional_block |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... | accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
loss_group = []
epoch_group = []
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
start_time = time.time()
... | optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1)) | random_line_split |
test_connection.ts | /**
* super-orm tests
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
import orm = require("../");
import utils = require("./utils");
describe("Connection", function () {
it("getConnection() support promise", async function () {
const conn = orm.createConnection({
connections: [ utils.getConnectio... | const sql = conn.format("SELECT * FROM ::table WHERE id=:id", {
table: "blog_contents",
id: 2,
});
console.log(sql);
const ret = await conn.query(sql);
console.log(ret);
}
{
const sql = conn.format("SELECT * FROM ?? WHERE id=?", [ "blog_contents", 2 ]);
... | }
{ | random_line_split |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... |
file_path = file_path.split(os.sep)
file_path[-1] = 'transliterated_' + file_path[-1]
file_path = os.sep.join(file_path)
with io.open(file_path, 'w', encoding='utf8') as file:
file.write('\n'.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='C... | else:
new_line += ch
new_lines.append(new_line) | random_line_split |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | , v in zip(domain, range) }
with io.open(file_path, 'r', encoding='utf8') as file:
lines = file.readlines()
new_lines = list()
for line in lines:
new_line = ''
for ch in line.strip():
if ch in d.keys():
new_line += d[ch]
else:
new_line += ch
new_lines.append(new_line)... | d = { u:v for u | identifier_name |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | = file_path.split(os.sep)
file_path[-1] = 'transliterated_' + file_path[-1]
file_path = os.sep.join(file_path)
with io.open(file_path, 'w', encoding='utf8') as file:
file.write('\n'.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert from/t... |
file_path | conditional_block |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | print(file_path)
if __name__ == '__main__':
parser = argpa
rse.ArgumentParser(description='Convert from/to Buckwalter transliteration')
parser.add_argument('-fp', '--file-path', help='File path to be transliterated', required=True)
parser.add_argument('-tbw', '--to-buckwalter', help='To Buckwalter transliterat... | with io.open(file_path, 'r', encoding='utf8') as file:
lines = file.readlines()
new_lines = list()
for line in lines:
new_line = ''
for ch in line.strip():
if ch in d.keys():
new_line += d[ch]
else:
new_line += ch
new_lines.append(new_line)
file_path = file_path.spli... | identifier_body |
urls.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
urlpatterns = patterns('openstack_dashboard.dashboards.admin.images.views',
url(r'^images/$', views.IndexView.as_view(), name='index'),
url(r'^create/$', views.CreateView.as_view(), name='create'),
url(r'^(?P<image_id>[^/]+)/update/$',
views.UpdateView.as_view(), name='update'),
url(r'^(?P<ima... |
from django.conf.urls import patterns # noqa
from django.conf.urls import url # noqa
from openstack_dashboard.dashboards.admin.images import views | random_line_split |
codeFixAddVoidToPromise_all.ts | /// <reference path='fourslash.ts' />
// @target: esnext
| ////const p1 = new Promise(resolve => resolve());
////const p2 = new Promise<number>(resolve => resolve());
////const p3 = new Promise<number | string>(resolve => resolve());
////const p4 = new Promise<{ x: number } & { y: string }>(resolve => resolve());
verify.codeFixAll({
fixId: "addVoidToPromise",
f... | // @lib: es2015
// @strict: true
| random_line_split |
consts.ts | export const Signatures = {
FileMagic: 0x9aa2d903,
Sig2Kdbx: 0xb54bfb67,
Sig2Kdb: 0xb54bfb65
} as const;
export const ErrorCodes = {
NotImplemented: 'NotImplemented',
InvalidArg: 'InvalidArg',
BadSignature: 'BadSignature',
InvalidVersion: 'InvalidVersion',
Unsupported: 'Unsupported',
... | Tux: 62,
Feather: 63,
Apple: 64,
Wiki: 65,
Money: 66,
Certificate: 67,
BlackBerry: 68
} as const; | Star: 61, | random_line_split |
index.d.ts | // Type definitions for Numeral.js
// Project: https://github.com/adamwdraper/Numeral-js
// Definitions by: Vincent Bortone <https://github.com/vbortone>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// http://numeraljs.com/#locales
interface NumeralJSLocale {
delimiters: {
thousands: string;
... | },
format: (value: any, format: string, roundingFunction: RoundingFunction) => string,
unformat: (value: string) => number
}
type RegisterType = 'format' | 'locale';
// http://numeraljs.com/#use-it
interface Numeral {
(value?: any): Numeral;
version: string;
isNumeral: boolean;
/**
* This function sets the ... | unformat: RegExp, | random_line_split |
editor.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle 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 later version.
//
// Moodle is dis... | .then(response => {
customjs = response.javascript;
return Templates.render('core_reportbuilder/custom_report', response);
})
.then((html, js) => {
return Templates.replaceNodeContents(reportElement, html, js + c... | const toggledEditMode = toggleEditViewMode.dataset.editMode !== "1";
let customjs = '';
getReport(reportElement.dataset.reportId, toggledEditMode) | random_line_split |
editor.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle 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 later version.
//
// Moodle is dis... |
});
initialized = true;
};
| {
event.preventDefault();
const pendingPromise = new Pending('core_reportbuilder/reports:get');
const toggledEditMode = toggleEditViewMode.dataset.editMode !== "1";
let customjs = '';
getReport(reportElement.dataset.reportId, toggledEditMode)
... | conditional_block |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# 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
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | except Exception as e:
raise e
if current_uptime == before_uptime:
raise Exception("uptime has not changed")
self.do_until_success_or_timeout(check_uptime, reboot_timeout, what_desc="reboot uptime check success")
# reset ... | random_line_split | |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# 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
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | (self, tmp=None, task_vars=None):
self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(changed=True, elapsed=0, rebooted=True)
if task_vars is None:
task_vars = dict()
result = super(ActionModule, s... | run | identifier_name |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# 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
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... |
time.sleep(fail_sleep)
raise TimedOutException("timed out waiting for %s: %s" % (what_desc, exc))
def run(self, tmp=None, task_vars=None):
self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(chang... | display.debug("win_reboot: %s fail (expected), retrying in %d seconds..." % (what_desc, fail_sleep)) | conditional_block |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# 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
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | if self._task.args.get(arg) is not None:
display.warning("Since Ansible %s, %s is no longer used with win_reboot" % (arg, version))
if self._task.args.get('connect_timeout') is not None:
connect_timeout = int(self._task.args.get('connect_timeout', self.DEFAULT_CONNECT_TI... | self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(changed=True, elapsed=0, rebooted=True)
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
if result... | identifier_body |
angular-animate-stylers.js | angular.module('ngAnimateStylers', ['ngAnimateSequence'])
.config(['$$animateStylerProvider', function($$animateStylerProvider)
{
//JQUERY
$$animateStylerProvider.register('jQuery', function() {
return function(element, pre, duration, delay) {
delay = delay || 0;
element.css(pre);
... |
return function(post, done) {
styler.fromTo(
element,
(duration || 0)/1000,
pre || { },
angular.extend( post, {onComplete:done, delay: (delay || 0)/1000} )
);
}
};
});
}]);
| {
throw new Error("GSAP TweenMax or TweenLite is not defined for use within $$animationStylerProvider.");
} | conditional_block |
angular-animate-stylers.js | angular.module('ngAnimateStylers', ['ngAnimateSequence'])
.config(['$$animateStylerProvider', function($$animateStylerProvider)
{
//JQUERY
$$animateStylerProvider.register('jQuery', function() {
return function(element, pre, duration, delay) {
delay = delay || 0;
element.css(pre);
... | return function(element, pre, duration, delay) {
delay = delay || 0;
duration = duration || 1000;
element.css(pre);
return function(post, done) {
var animation = element[0].animate({ 'border-width' : '100px'}, 5000);
//player.onfinish = done;
}
};
... |
//NOT WORKING
$$animateStylerProvider.register('webAnimations', function() { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.