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 |
|---|---|---|---|---|
xmp_dashboard.py | md5_calc', 'ok_nok', 'date') VALUES (?,?,?,?,?,?)", results)
if vital_stats: print("Thread identity: " + str(threading.get_ident()) + " Second sql segment: Rows returned from execute INSERT INTO md5_resutls = "
+ str(cur.rowcount))
except sqlite3.Error as error:
if ... |
new_run | identifier_name | |
xmp_dashboard.py | den ut loopen. Tidigare fortsatte den att stega igenom hela mappen även om den hiottat rätt fil.
# - Ta time() vid start av vartje mapp, och vi slkutet och spara. Skriv sedan ut en liten summering.
# - Vid varje start skriver jag ut mappnamnet. Kan man skriva ut antalet filer också? JAg räknar ju dem innan. Samma vi... | le, '<PelleTags:PelleTag1_md5sum>'),
index_containing_substring(list_file, 'PelleTags:PelleTag1_md5sum=')]
if verbose: print(md5_index)
if any(md5_index): # xmp-filen innehåller en md5-summa.
res = [idx for idx, val in enumerate(md5_... | dex = [index_containing_substring(list_fi | conditional_block |
xmp_dashboard.py |
xmp_file_counter = 0
results = []
time1 = time.time()
try: # Clear db here from all rows with path
sql = "DELETE FROM md5_results WHERE file_path LIKE '" + main_folder + "%'"
cur.execute(sql)
if verbose: print("Thread ... | random_line_split | ||
xmp_dashboard.py | import subprocess
import fileinput
import datetime
import time
import hashlib
import sqlite3
from tkinter import ttk # Denna innehåller comboboxen - drop down.
# generate_md5_Checksum_def är en funktion som ligger i en separat fil,
from generate_md5_Checksum_def import md5Checksum
from connect_sqlite_db impo... | verbose
global xmp | identifier_body | |
sensor_update.py | ())):
rows.append(data[ew])
# spoof the API response
return {
'result': 1,
'message': None,
'epidata': rows,
}
return fetch, fields
@staticmethod
def get_cdc(location, epiweek, valid):
fields = ['num2', 'num4', 'num5', 'num6', 'num7', 'num8']
def fetc... | return ARCH(location).predict(epiweek, valid=valid)
@staticmethod
def get_ar3(location, epiweek, valid): | random_line_split | |
sensor_update.py | _name = fields[idx]
idx += 1
# loop over rows of the response, ordered by epiweek
for row in epidata:
ew = row['epiweek']
if ew not in data:
# make a new entry for this epiweek
data[ew] = {'epiweek': ew}
# save the value of th... | get_epic | identifier_name | |
sensor_update.py | np.sin(angle), np.cos(angle)]
def apply_model(epiweek, beta, values):
bias0 = [1.]
if beta.shape[0] > len(values) + 1:
# constant and periodic bias
bias1 = get_periodic_bias(epiweek)
obs = np.array([values + bias0 + bias1])
else:
# constant bias only
ob... | self.update_single(database, test_week, name, location) | conditional_block | |
sensor_update.py | dot product
for any number of arguments.
"""
N = Ms[0]
for M in Ms[1:]:
N = np.dot(N, M)
return N
def get_weight(ew1, ew2):
""" This function gives the weight between two given
epiweeks based on a function that:
- drops sharply over the most recent ~3... | """
Return a new instance under the default configuration.
If `test_mode` is True, database changes will not be committed.
If `valid` is True, be punctilious about hiding values that were not known
at the time (e.g. run the model with preliminary ILI only). Otherwise, be
more lenient (e.g. fall ba... | identifier_body | |
图像数据处理.py | ducer(['/path/to/output.tfrecords'])
#从队列中读取一个样例
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(#解析单个样例函数
serialized_example,
features={
'images_raw':tf.FixedLenFeature([],tf.string),#解析为一个tensor
'pixels':tf.FixedLenFeature([],tf.int64),
'label':t... | = tf.train.Example(features=tf.train.Feature(feature={
'pixels':_int_64_feature(pixels),
'label':_int_64_feature(np.argmax(labels[index])),
'images_raw':_bytes_features(images_raw)}
))
writer.write(example.SerializerToString())#写入TFRecord文件
writer.close()
读取TFRecord
import tensorflow ... | conditional_block | |
图像数据处理.py |
sess = tf.Session()
#启动多线程处理输入数据
coord = tf.train.Coordinator(}
threads = tf.train.start_queue_runners(sess=sess, coord=coord}
#每次运行可以读取TFRecord 文件中的一个样例。当所有样例读完之后,在此样例中程序
#会再从头读取。
for i in range(10} :
print(sess.run([image, label, pixels]))
图像编码处理
import matplotlib.pyplot as plt
import tensorflow as tf
image_raw... |
image= tf.decode_raw(features[’image_raw’], tf.uint8}#将字符串tensor解析成数组
label = tf.cast(features[’label’], tf.int32}
pixels = tf.cast(features[’pixels’], tf.int32} | random_line_split | |
图像数据处理.py | ))
#读取mnist数据
mnist = input_data.read_data_sets('/path', dtype=tf.uint8, one_hot=True)
images = mnist.train.images
labels = mnist.train.labels
pixels = images.shape[1]
num_examples = mnist.train.num_examples
filename = '/path/to/output.tfrecords'
#创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
... | t(value=[value] | identifier_name | |
图像数据处理.py | True)
images = mnist.train.images
labels = mnist.train.labels
pixels = images.shape[1]
num_examples = mnist.train.num_examples
filename = '/path/to/output.tfrecords'
#创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
images_raw = images[index].tostring()#将每个图像转... | 据
mnist = input_data.read_data_sets('/path', dtype=tf.uint8, one_hot= | identifier_body | |
functions_and_their_processes.rs | n kinds of coins equals
- the number of ways to change amount a using all but the the first kind of coin, plus
- the number of ways to change amount (a - d) using all n kinds of coins where d is the value of the first kind of coin
*/
fn count_change(amount: i128) -> i128 {
cc(amount, 6)
}
fn cc(amount: i128, coin_... | d_divisor(n: i128, test_divisor: i128) -> i128 {
if square(test_divisor) > n {
n
} else {
if devides(test_divisor, n) {
test_divisor
} else {
find_divisor(n, test_divisor + 1)
}
}
}
pub fn smallest_divisor(n: i128) -> i128 {
find_divisor(n, 2)
}
pub fn is_prime(n: i128) -> bool {
... | test_divisor == 0
}
fn fin | identifier_body |
functions_and_their_processes.rs | == 0 || m == n {
1
} else {
pascal(m - 1, n - 1) + pascal(m - 1, n)
}
}
// pascal triangle with interative process
pub fn pascal_iter(m: usize, n: usize) -> i128 {
fn helper(m: usize, n: usize, l: usize, pre_vec: Vec<i128>) -> i128 {
if m == 0 || m == n {
1
} else {
if l == m {
... | for i in 2..n {
if expmod(i, n, n) == i {
println!(" testing {}", i);
}
} | random_line_split | |
functions_and_their_processes.rs | else {
ackermann(a - 1, ackermann(a, b - 1))
}
}
}
}
fn f(n: i128) -> i128 {
ackermann(0, n)
}
fn g(n: i128) -> i128 {
ackermann(1, n)
}
fn h(n: i128) -> i128 {
ackermann(2, n)
}
pub fn fac(n: i128) -> i128 {
if n == 1 {
1
} else {
n * fac(n - 1)
}
}
pub fn fib(n: i128) -> ... | {
2
} | conditional_block | |
functions_and_their_processes.rs | n kinds of coins equals
- the number of ways to change amount a using all but the the first kind of coin, plus
- the number of ways to change amount (a - d) using all n kinds of coins where d is the value of the first kind of coin
*/
fn count_change(amount: i128) -> i128 {
cc(amount, 6)
}
fn | (amount: i128, coin_kind: i8) -> i128 {
if amount == 0 {
1
} else {
if amount < 0 || coin_kind == 0 {
0
} else {
cc(amount, coin_kind - 1) + cc(amount - get_value(coin_kind), coin_kind)
}
}
}
fn get_value(coin_kind: i8) -> i128 {
match coin_kind {
6 => 100,
5 => 50,
4 =>... | cc | identifier_name |
lib.rs | /// method to check for cancellation).
///
/// # Panics
///
/// It is not permitted to create a snapshot from inside of a
/// query. Attepting to do so will panic.
///
/// # Deadlock warning
///
/// The intended pattern for snapshots is that, once created, they
/// are sent t... | set | identifier_name | |
lib.rs |
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overridden by `Database` implementors.
fn salsa_runtime(&self) -> &Runtime {
self.ops_salsa_runtime()
}
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overri... | if pending_revision > current_revision {
runtime.unwind_cancelled();
}
} | random_line_split | |
pwm.rs | IllegalChangeWhileEnabled(&'static str),
#[error("expected boolean value, got {0:?}")]
NotBoolean(String),
#[error("expected a duration in nanoseconds, got {0:?}: {1}")]
NotADuration(String, #[source] std::num::ParseIntError),
}
/// Used in PwmError to format sysfs related errors.
#[derive(Debug)]
pub... | if path.is_file() {
Ok(path)
} else {
Err(PwmError::ControllerNotFound(controller.clone()))
}
}
fn channel_dir(&self, controller: &Controller, channel: &Channel) -> Result<PathBuf> {
let n_pwm = self.npwm(controller)?;
if channel.0 >= n_pwm {
... | let path = self
.sysfs_root
.join(format!("pwmchip{}/{}", controller.0, fname)); | random_line_split |
pwm.rs | duration in nanoseconds, got {0:?}: {1}")]
NotADuration(String, #[source] std::num::ParseIntError),
}
/// Used in PwmError to format sysfs related errors.
#[derive(Debug)]
pub enum Access {
Read(PathBuf),
Write(PathBuf),
}
/// Exposes PWM functionality.
///
/// Since the Linux kernel exposes PWM controll... | {
N | identifier_name | |
pwm.rs | ),
#[error("expected a duration in nanoseconds, got {0:?}: {1}")]
NotADuration(String, #[source] std::num::ParseIntError),
}
/// Used in PwmError to format sysfs related errors.
#[derive(Debug)]
pub enum Access {
Read(PathBuf),
Write(PathBuf),
}
/// Exposes PWM functionality.
///
/// Since the Linux k... | trim_end()
.parse::<u64>()
.map_err(|e| PwmError::NotADuration(s, e))
.map(Duration::from_nanos)
}
#[deri | identifier_body | |
deckbuilder.py | build():
global FILE_EXT
global SHEETS
global EXCEL
# parse args
parser = argparse.ArgumentParser(description='Building decks')
parser.add_argument('-s', "--source", type=str, action='store', dest='source', help='Excel source')
parser.add_argument('-o', "--output", type=str, action='store'... | unicode_font = ImageFont.truetype("Arial.ttf")
y_text = draw_lines(draw, unicode_font, title, parms.DIM_TEXT_TOP_MARGIN())
# space between title and description
y_text += parms.DIM_TEXT_TOP_MARGIN()
# draw description
for p in str.split(description, "\p"):
for n in str.split(p, "\n"):
... | draw = ImageDraw.Draw(img)
# draw title | random_line_split |
deckbuilder.py | build():
global FILE_EXT
global SHEETS
global EXCEL
# parse args
parser = argparse.ArgumentParser(description='Building decks')
parser.add_argument('-s', "--source", type=str, action='store', dest='source', help='Excel source')
parser.add_argument('-o', "--output", type=str, action='store'... |
filename, ext = parms.FILE_SOURCE.split(".")
if ext.lower() not in (parms.EXT_XLS(), parms.EXT_XLSX(), parms.EXT_CSV()):
print("ERROR: Source file type is not supported")
return False
else:
global FILE_EXT
FILE_EXT = ext
if parms.FORMAT not in [parms.FORMAT_PDF()]:
... | print("ERROR: Source file path is invalid")
return False | conditional_block |
deckbuilder.py | tabletop", type=bool, action='store', dest='tabletop',
help='Export for Tabletop Simulator')
parser.add_argument('-p', "--print", type=bool, action='store', dest='print',
help='Print generated files')
args = parser.parse_args()
# redefine global parameters
... | eet_path):
| identifier_name | |
deckbuilder.py | ():
global FILE_EXT
global SHEETS
global EXCEL
# parse args
parser = argparse.ArgumentParser(description='Building decks')
parser.add_argument('-s', "--source", type=str, action='store', dest='source', help='Excel source')
parser.add_argument('-o', "--output", type=str, action='store', dest... | eet(sheet_title, deck):
main_directory = generate_sheet_directories(sheet_title)
pdf = None
if parms.FORMAT == parms.FORMAT_PDF():
pdf = FPDF()
card_paths = []
card_total_count = 0
for c in deck:
card_total_count += c.count
card_counter = 0
for i, card in enumerate(de... | g.size[0] + parms.DIM_CARD_BORDER() * 2, img.size[1] + parms.DIM_CARD_BORDER() * 2)
bordered_img = Image.new("RGB", new_size)
bordered_img.paste(img, (parms.DIM_CARD_BORDER(), parms.DIM_CARD_BORDER()))
return bordered_img
def save_sh | identifier_body |
bot.py | imformation persistently
def setup_db():
""" initialize a new database """
db = TinyDB('db.json')
chats = db.table('chats')
members = db.table('members')
chats.insert({'id': -231128423}) # Kolab chat group
members.insert({'id': 235493361})
def get_member_ids(db):
table = db.table('members'... |
def get_cat_image():
allowed_extension = ['jpg','jpeg','png']
file_extension = ''
while file_extension not in allowed_extension:
url = get_cat_url()
file_extension = re.search("([^.]*)$",url).group(1).lower()
return url
@restricted
def meow(update: 'Update', context: 'CallbackContext... | contents = requests.get('https://aws.random.cat/meow').json()
url = contents['file']
return url | identifier_body |
bot.py | formation persistently
def setup_db():
""" initialize a new database """
db = TinyDB('db.json')
chats = db.table('chats')
members = db.table('members')
chats.insert({'id': -231128423}) # Kolab chat group
members.insert({'id': 235493361})
def get_member_ids(db):
table = db.table('members')
... | (update: 'Update', context: 'CallbackContext'):
""" Add user to the whitelist. """
user_id = update.effective_user.id
chat_id = update.effective_chat.id
chats = get_chat_ids(DB)
if chat_id not in chats:
update.message.reply_text('Did not work. Run this command inside the Ko-Lab group.'... | addme | identifier_name |
bot.py | imformation persistently
def setup_db():
""" initialize a new database """
db = TinyDB('db.json')
chats = db.table('chats')
members = db.table('members')
chats.insert({'id': -231128423}) # Kolab chat group
members.insert({'id': 235493361})
def get_member_ids(db):
table = db.table('members'... |
@restricted
def inlinequery(update: 'Update', context: 'Context'):
"""Handle inline queries."""
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id=uuid4(),
title="Caps",
input_message_content=InputTextMessageContent(
query... | return wrapped | random_line_split |
bot.py | formation persistently
def setup_db():
""" initialize a new database """
db = TinyDB('db.json')
chats = db.table('chats')
members = db.table('members')
chats.insert({'id': -231128423}) # Kolab chat group
members.insert({'id': 235493361})
def get_member_ids(db):
table = db.table('members')
... |
# send a link to the pixel paint app
try:
# TODO: try to open pixel paint url
url = "http://10.90.154.80/"
#response = requests.get(url)
update.message.reply_text("To paint the floor, go to {}".format(url))
except (ConnectionRefusedError, TimeoutError) as err:
msg =... | print("Trying to start LED floor...")
try:
publish.single("vloer/startscript", "paint", hostname="10.94.176.100",
auth={'username': 'vloer', 'password': 'ko-lab'},
port=1883, client_id="kolabbot")
print("LED floor...")
except (ConnectionRefusedEr... | conditional_block |
scrapedin.py | Only matches if the name contains uppercase, lowercase or spaces.
return [name]
else:
return None
def login(self, username, password):
'''
Login to the linked in web page.
The only args required to use this function are the username and password to log int... |
while max_users > len(self.employee_data) and current_page < 100:
self.page.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:
WebDriverWait(self.page, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, 'active')))
# Check if ... | max_users = float('inf') | conditional_block |
scrapedin.py | Only matches if the name contains uppercase, lowercase or spaces.
return [name]
else:
return None
def login(self, username, password):
'''
Login to the linked in web page.
The only args required to use this function are the username and password to log int... |
# Filter by Geographic Region
if georegion:
# region object is created for future-proof purposes in the event new filters become available or formating changes
region = {}
try:
region['full_line'] = list_search('georegion', term=georegion, return_resu... | '''
Utilize the method within the cycle_users function to build different search
parameters such as location, geotag, company, job-title, etc.
This function will return the full URL.
:param str company: target company name
:param str url: default (or custom) linkedin url for fac... | identifier_body |
scrapedin.py | except exceptions.StaleElementReferenceException:
# Handles a race condition where elements are found but are not populated yet.
continue
for pagnation in self.page.find_elements_by_class_name("artdeco-pagination__button"):
if pagnation.text != "Next":
... | random_line_split | ||
scrapedin.py | within the cycle_users function to build different search
parameters such as location, geotag, company, job-title, etc.
This function will return the full URL.
:param str company: target company name
:param str url: default (or custom) linkedin url for faceted linkedin search
:... | dept_wizard | identifier_name | |
snapshot.go | canInternalOpts := &scanInternalOptions{
visitPointKey: visitPointKey,
visitRangeDel: visitRangeDel,
visitRangeKey: visitRangeKey,
visitSharedFile: visitSharedFile,
skipSharedLevels: visitSharedFile != nil,
IterOptions: IterOptions{
KeyTypes: IterKeyTypePointsAndRanges,
LowerBound: lower,
... |
func (l *snapshotList) toSlice() []uint64 {
if l.empty() {
return nil
}
var results []uint64
for i := l.root.next; i != &l.root; i = i.next {
results = append(results, i.seqNum)
}
return results
}
func (l *snapshotList) pushBack(s *Snapshot) {
if s.list != nil || s.prev != nil || s.next != nil {
panic("... | {
v := uint64(math.MaxUint64)
if !l.empty() {
v = l.root.next.seqNum
}
return v
} | identifier_body |
snapshot.go | .remove(s)
// If s was the previous earliest snapshot, we might be able to reclaim
// disk space by dropping obsolete records that were pinned by s.
if e := s.db.mu.snapshots.earliest(); e > s.seqNum {
s.db.maybeScheduleCompactionPicker(pickElisionOnly)
}
s.db = nil
return nil
}
// Close closes the snapshot, ... | // snapshot.
func (es *EventuallyFileOnlySnapshot) hasTransitioned() bool {
es.mu.Lock()
defer es.mu.Unlock() | random_line_split | |
snapshot.go | closeLocked() error {
s.db.mu.snapshots.remove(s)
// If s was the previous earliest snapshot, we might be able to reclaim
// disk space by dropping obsolete records that were pinned by s.
if e := s.db.mu.snapshots.earliest(); e > s.seqNum {
s.db.maybeScheduleCompactionPicker(pickElisionOnly)
}
s.db = nil
ret... | hasTransitioned | identifier_name | |
snapshot.go | their read-only
// point-in-time view is unaltered by the excision. However, if a concurrent
// excise were to happen on one of the protectedRanges, WaitForFileOnlySnapshot()
// would return ErrSnapshotExcised and the EFOS would maintain a reference to the
// underlying readState (and by extension, zombie memtables) f... | {
return nil, nil, firstError(iter.Close(), ErrNotFound)
} | conditional_block | |
conteng_docker.go | "github.com/pkg/errors"
"github.com/syhpoon/xenvman/pkg/lib"
"github.com/syhpoon/xenvman/pkg/logger"
)
var dockerLog = logger.GetLogger("xenvman.pkg.conteng.conteng_docker")
type DockerEngineParams struct {
}
type DockerEngine struct {
cl *client.Client
params DockerEngineParams
subNetOct1 int
subN... | for contPort, hostPort := range params.Ports {
rawPorts = append(rawPorts, fmt.Sprintf("%d:%d", hostPort, contPort))
}
ports, bindings, err := nat.ParsePortSpecs(rawPorts)
if err != nil {
return "", errors.Wrapf(err, "Error parsing ports for %s", name)
}
// Environ
var environ []string
for k, v := range... |
// Ports
var rawPorts []string
| random_line_split |
conteng_docker.go | "github.com/pkg/errors"
"github.com/syhpoon/xenvman/pkg/lib"
"github.com/syhpoon/xenvman/pkg/logger"
)
var dockerLog = logger.GetLogger("xenvman.pkg.conteng.conteng_docker")
type DockerEngineParams struct {
}
type DockerEngine struct {
cl *client.Client
params DockerEngineParams
subNetOct1 int
subN... | (ctx context.Context, id string) error {
return de.cl.NetworkRemove(ctx, id)
}
func (de *DockerEngine) BuildImage(ctx context.Context, imgName string,
buildContext io.Reader) error {
opts := types.ImageBuildOptions{
NetworkMode: "bridge",
Tags: []string{imgName},
Remove: true,
ForceRem... | RemoveNetwork | identifier_name |
conteng_docker.go | "github.com/pkg/errors"
"github.com/syhpoon/xenvman/pkg/lib"
"github.com/syhpoon/xenvman/pkg/logger"
)
var dockerLog = logger.GetLogger("xenvman.pkg.conteng.conteng_docker")
type DockerEngineParams struct {
}
type DockerEngine struct {
cl *client.Client
params DockerEngineParams
subNetOct1 int
subN... |
func (de *DockerEngine) isErrorResponse(r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
split := bytes.Split(data, []byte("\n"))
type errResp struct {
Error string
}
for i := range split {
e := errResp{}
if err := json.Unmarshal(split[i], &e); err == nil && e.Error... | {
de.cl.Close()
} | identifier_body |
conteng_docker.go | "github.com/pkg/errors"
"github.com/syhpoon/xenvman/pkg/lib"
"github.com/syhpoon/xenvman/pkg/logger"
)
var dockerLog = logger.GetLogger("xenvman.pkg.conteng.conteng_docker")
type DockerEngineParams struct {
}
type DockerEngine struct {
cl *client.Client
params DockerEngineParams
subNetOct1 int
subN... |
netParams := types.NetworkCreate{
CheckDuplicate: true,
Driver: "bridge",
IPAM: &network.IPAM{
Config: []network.IPAMConfig{
{
Subnet: sub,
IPRange: sub,
},
},
},
}
r, err := de.cl.NetworkCreate(ctx, name, netParams)
if err != nil {
return "", "", errors.Wrapf(err, "Er... | {
return "", "", err
} | conditional_block |
marktree.js | 119,97,115,100);
var press = new Array(47,45,42,43);
// keydown codes
// var keys2=new Array(87,65,83,68);
var keys= new Array(38,37,40,39);
// keyset 1 = keydown, otherwise press
function checkup(keyset,n) {
if (keyset==1) return (n==keys[0]);
return ((n==press[0]) /*|| (n==press2[0])*/)
}
function chec... | i) {
// added 12.7.2004 to prevent IE error when readonly mode==true
if (li==null) return null;
n=li;
while (1) {
n=n.parentNode;
if (n==null) return null;
if (is_list_node(n)) return n;
}
}
function getVisibleParents(id) {
var n = document.getElementById(id);
while(1) {
expand(n);
n ... | rent_listnode(l | identifier_name |
marktree.js | (119,97,115,100);
var press = new Array(47,45,42,43);
// keydown codes
// var keys2=new Array(87,65,83,68);
var keys= new Array(38,37,40,39);
// keyset 1 = keydown, otherwise press
function checkup(keyset,n) {
if (keyset==1) return (n==keys[0]);
return ((n==press[0]) /*|| (n==press2[0])*/)
}
function che... | return next_actual_sibling_listnode(n);
}
if (is_list_node(n)) return n;
temp=n;
}
}
function next_sibling_listnode(li) {
if (li==null) return null;
var result=null;
var temp=li;
if (is_col(temp)) return next_child_listnode(temp);
while (1) {
var n = temp.nextSibling;
if (n==null) ... | var n = temp.nextSibling;
if (n==null) {
n=parent_listnode(temp); | random_line_split |
marktree.js | ) return (n==keys[3]);
return ((n==press[3]) /*|| (n==press2[3])*/)
}
function is_exp(n) {
if (n==null) return false;
return ((n.className=='exp') || (n.className=='exp_active'));
}
function is_col(n) {
if (n==null) return false;
return ((n.className=='col') || (n.className=='col_active'));
}
function ... | if (node.className=='col') {
node.className='exp';
setSubClass(node,'sub');
// getsub(node).className='sub';
}
var i;
if (node.childNodes!=null)
// for opera if (node.hasChildNodes())
for ( i = 0; i<node.childNodes.length; i++)
collapseAll(node.chi... | identifier_body | |
xcb.rs | fn poll_events(&self) -> Option<Event>
{
let event = match self.conn.poll_for_event()
{
Some(event) => event,
None => return None,
};
match event.response_type() & !0x80
{
xcb::EXPOSE => return Some(Event::ExposedEvent),
xcb::KEY_PRESS => return Some(Event::KeyEvent(KeyEvent::KeyPress)),
xcb... | return Err(Error{error_code: e.error_code()})
};
| conditional_block | |
xcb.rs | impl PropertyValue
{
pub fn get_type_atom_id(&self) -> AtomID
{
return match self
{
PropertyValue::String(_) => xcb::ATOM_STRING,
PropertyValue::I32(_) => xcb::ATOM_INTEGER,
PropertyValue::U32(_) => xcb::ATOM_CARDINAL,
PropertyValue::Atom(_) => xcb::ATOM_ATOM,
PropertyValue::UnknownAtom(atom_id) =>... | None,
Atom(AtomID),
UnknownAtom(AtomID),
}
| random_line_split | |
xcb.rs | KEY_RELEASE => return Some(Event::KeyEvent(KeyEvent::KeyReleased)),
event =>
{
println!("UNKOWN EVENT {:?}", event);
return None;
}
};
}
pub fn send_message(&self, destination: &Window, event: Event)
{
match event
{
Event::ClientMessageEvent {window, event_type, data , ..} =>
{
let ... | erate(wi | identifier_name | |
xcb.rs | , name).get_reply().unwrap().atom();
return if atom_id == xcb::ATOM_NONE { None } else { Some(atom_id) };
}
pub fn find_atom_name(&self, atom_id: AtomID) -> String
{
return xcb::get_atom_name(&self.conn, atom_id).get_reply().unwrap().name().to_owned();
}
pub fn poll_events(&self) -> Option<Event>
|
pub fn send_message(&self, destination: &Window, event: Event)
{
match event
{
Event::ClientMessageEvent {window, event_type, data , ..} =>
{
let message_data = xcb::ffi::xproto::xcb_client_message_data_t::from_data32(data);
let event = xcb::Event::<xcb::ffi::xproto::xcb_client_message_event_t>::... | {
let event = match self.conn.poll_for_event()
{
Some(event) => event,
None => return None,
};
match event.response_type() & !0x80
{
xcb::EXPOSE => return Some(Event::ExposedEvent),
xcb::KEY_PRESS => return Some(Event::KeyEvent(KeyEvent::KeyPress)),
xcb::KEY_RELEASE => return Some(Event::KeyEv... | identifier_body |
models.py | in CustomOrder.get_my_grms(self, profile):
grmcfv = bpoi.custom_field_values.get(field__name=f'{grm.role.name}_approver_id')
if grmcfv and not grmcfv.int_value:
grmcfv.int_value = grm.profile.user.id
grmcfv.save()
history_msg = _("The '{order... |
def is_multilevel_approval(self):
"""
multilevel approvals need to display the roles that have order.approve permissions
based on a BPOI custom_field_value where the field name has an "_approver_id" at the
end, and a valid role exists on the Group for that cfv fie... | '''
in a multilevel approval, we need a get the GroupRoleMembership mappings
and exclude the default approvers role
as well, if there's only one role.name == approvers
'''
if not profile:
profile = self.owner
owned_grms = profile.groupro... | identifier_body |
models.py | cfv and not grmcfv.int_value:
grmcfv.int_value = grm.profile.user.id
grmcfv.save()
history_msg = _("The '{order}' order has been partially approved by {role_label}.").format(order=escape(self), role_label=grm.role.label)
self.add_event('APPROVED', hist... | self.approve_date = get_current_time()
| random_line_split | |
models.py | CustomOrder.get_my_grms(self, profile):
grmcfv = bpoi.custom_field_values.get(field__name=f'{grm.role.name}_approver_id')
if grmcfv and not grmcfv.int_value:
grmcfv.int_value = grm.profile.user.id
grmcfv.save()
history_msg = _("The '{order}' ... | (self, request=None):
"""
This method determines what order process should be taken, and
takes it. By default, the process is to email the approvers, but
this can be overriden by customers to instead call out to a hook,
and that can be overridden by auto-approval (set on th... | start_approval_process | identifier_name |
models.py | in CustomOrder.get_my_grms(self, profile):
grmcfv = bpoi.custom_field_values.get(field__name=f'{grm.role.name}_approver_id')
if grmcfv and not grmcfv.int_value:
grmcfv.int_value = grm.profile.user.id
grmcfv.save()
history_msg = _("The '{order... |
# some orders (like those duplicated by CIT) will not have owners
if self.is_multilevel_approval():
if self.has_all_approver_roles(self.owner, self.group):
return True
return False
else:
if self.owner and self.owner.has_permission('... | return True | conditional_block |
usage.py |
def getInstances(region):
creds = credentials()
try:
conn = ec2.connect_to_region(region, **creds)
instances = []
reservations = conn.get_all_reservations()
for reservation in reservations:
for instance in reservation.instances:
instances.append(ins... | return {"aws_access_key_id": os.environ['AWS_ACCESS_KEY'],
"aws_secret_access_key": os.environ['AWS_SECRET_KEY']} | identifier_body | |
usage.py | credentials()
try:
conn = ec2.connect_to_region(region, **creds)
volumes = conn.get_all_volumes()
except boto.exception.EC2ResponseError:
return []
return volumes
# snapshots got this thing where there are public, private, and owned by me: defaults to all or public?
# we're intere... |
snapshotsDict = {"id": s.id,
"status": s.status,
"region": s.region.name,
"progress": s.progress,
"start_time": s.start_time,
"volume_id": s.volume_id,
"volume_... | for a in amis:
amiIds.append(a.id.encode())
amiKeeps.append(getKeepTag(a)) | conditional_block |
usage.py | credentials()
try:
conn = ec2.connect_to_region(region, **creds)
volumes = conn.get_all_volumes()
except boto.exception.EC2ResponseError:
return []
return volumes
# snapshots got this thing where there are public, private, and owned by me: defaults to all or public?
# we're intere... | "Description": s.description
}
snapshotsDicts.append(snapshotsDict)
return snapshotsDicts
def getVolumesD(region):
""" return a list of dictionaries representing volumes from one region """
volumes = getVolumes(region)
instances = getInstancesD... | "PROD": isProduction(s), | random_line_split |
usage.py | credentials()
try:
conn = ec2.connect_to_region(region, **creds)
volumes = conn.get_all_volumes()
except boto.exception.EC2ResponseError:
return []
return volumes
# snapshots got this thing where there are public, private, and owned by me: defaults to all or public?
# we're intere... | (regions):
""" Write volumes to file """
print "\nWriting volumes info to output file %s" % volumes_data_output_file
with open(volumes_data_output_file, 'w') as f1:
f1.write("VOLUMES\n")
f1.write(
"Name\tvolume_ID\tKEEP-tag_of_volume\tKEEP-tag_of_instance\tproduction?\tvolume_att... | generateInfoVolumes | identifier_name |
enum.go | RatingCode = 2 // 2 = Clean
RatingCodeExplicitOld RatingCode = 4 // 4 = Explicit (old)
)
type PlayGapMode int
const (
PlayGapInsertGap PlayGapMode = 0 // Insert Gap
PlayGapNoGap PlayGapMode = 1 // No Gap
)
type AppleStoreAccountType int
const (
AppleStoreAccountTypeITunes AppleStoreAccountType = 0
AppleSt... | random_line_split | ||
enum.go | case MediaTypePodcast:
return "Podcast"
default:
buf := bytes.Buffer{}
buf.WriteByte('(')
buf.WriteString(strconv.FormatInt(int64(x), 10))
buf.WriteByte(')')
return buf.String()
}
}
type RatingCode int
const (
RatingCodeNone RatingCode = 0 // 0 = None
RatingCodeExplicit RatingCode = 1 // 1... | {
switch x {
case MediaTypeHomeVideo:
return "Home Video"
case MediaTypeMusic:
return "Music"
case MediaTypeAudiobook:
return "Audiobook"
case MediaTypeBookmark:
return "Whacked Bookmark"
case MediaTypeMusicVideo:
return "Music Video"
case MediaTypeMovie:
return "Movie"
case MediaTypeTVShow:
retur... | identifier_body | |
enum.go | () string {
switch x {
case MediaTypeHomeVideo:
return "Home Video"
case MediaTypeMusic:
return "Music"
case MediaTypeAudiobook:
return "Audiobook"
case MediaTypeBookmark:
return "Whacked Bookmark"
case MediaTypeMusicVideo:
return "Music Video"
case MediaTypeMovie:
return "Movie"
case MediaTypeTVSho... | String | identifier_name | |
insert_organisations.py | def select_from_list(matches):
for m, (name, alias) in enumerate(matches):
print(
" %4d %s %s" % (m, name, (alias and ("[%s]" % alias) or ""))
)
print()
print("Choose name or non-numeric to exit: ", end=' ')
choice = input()
try:
choice = int(choice)
exce... | (es, text_orig, context=None, just_search=False):
"""Returns False to skip"""
# pylint: disable=redefined-variable-type
# `org_id` may be `None`, `False` or string.
org_id = None
text_search = text_orig
while True:
if context and context.get("refresh", None):
# Necessarily ... | search_org | identifier_name |
insert_organisations.py | def select_from_list(matches):
for m, (name, alias) in enumerate(matches):
print(
" %4d %s %s" % (m, name, (alias and ("[%s]" % alias) or ""))
)
print()
print("Choose name or non-numeric to exit: ", end=' ')
choice = input()
try:
choice = int(choice)
exce... | for note_data in chunk["note"]:
if note_data["text"] in [note.text for note in org.note_list]:
continue
note = Note(
note_data[" | if "note" in chunk: | random_line_split |
insert_organisations.py | def select_from_list(matches):
for m, (name, alias) in enumerate(matches):
print(
" %4d %s %s" % (m, name, (alias and ("[%s]" % alias) or ""))
)
print()
print("Choose name or non-numeric to exit: ", end=' ')
choice = input()
try:
choice = int(choice)
exce... |
if not matches:
return None
matches = sorted(list(matches))
print()
print("\n%s\n" % name)
existing_name = select_from_list(matches)
return existing_name
def get_org(orm, name):
name = name.lower()
query = orm.query(Org) \
.filter(func.lower(Org.name) == name)
... | matches = set()
lower = orm.query(Org.name) \
.filter(Org.name > name) \
.order_by(Org.name.asc()) \
.limit(3) \
.all()
higher = orm.query(Org.name) \
.filter(Org.name < name) \
.order_by(Org.name.desc()) \
.limit(3) \
.all()
for (name2, ) in... | identifier_body |
insert_organisations.py | def select_from_list(matches):
for m, (name, alias) in enumerate(matches):
print(
" %4d %s %s" % (m, name, (alias and ("[%s]" % alias) or ""))
)
print()
print("Choose name or non-numeric to exit: ", end=' ')
choice = input()
try:
choice = int(choice)
exce... |
es = orm.get_bind().search
if es is None:
LOG.error("Cannot connect to Elasticsearch.")
sys.exit(1)
org_id = search_org(es, name, context=context)
if not org_id:
return org_id
try:
org = orm.query(Org).filter_by(org_id=org_id).one()
except NoResultFound as e:
... | return | conditional_block |
29.js | "1": "<sup>1</sup> Fjala e Zotit që iu drejtua Joelit, birit të Pethuelit.",
"2": "<sup>2</sup> Dëgjoni këtë, o pleq, dëgjoni, ju të gjithë banorë të vendit. A ka ndodhur vallë një gjë e tillë në ditët tuaja apo në ditët e etërve tuaj?",
"3": "<sup>3</sup> Tregojani bijve tuaj, dhe bijtë tuaj bijve të tyre, dh... | var book = {
"name": "Joeli",
"numChapters": 3,
"chapters": {
"1": { | random_line_split | |
simulationlf.py | _phases)[0]
# We won't work on the slack node because it is pointless, so we're only taking nodes starting with the second
brackets = brackets[1:]
for i in range(nb_brackets):
current_bracket = brackets[i]
# p = self.power_definition()
z[i] = (current_bracket... | 'reactive': imag(flow)
}
def printMenu(self, network):
np.set_printoptions(threshold=np.nan, suppress=True, precision=10)
# import re
while True:
# This block is relevant if we use a timestamp.
# It will check the user's input.
# If yo... | flow = voltage * conj(intensity)
return {
'active': real(flow), | random_line_split |
simulationlf.py |
def get_delta_time(self): return self.__delta_time
# SETTERS/MUTATORS
def set_nb_iterations(self, nb): self.__nb_iterations = nb
def set_tolerance(self, t): self.__tolerance = t
def set_delta_time(self, d): self.__delta_time = d
def grid_definition(self, network):
zeros = np.zeros
... | return self.__tolerance | identifier_body | |
simulationlf.py | (self): return self.__nb_iterations
def get_tolerance(self): return self.__tolerance
def get_delta_time(self): return self.__delta_time
# SETTERS/MUTATORS
def set_nb_iterations(self, nb): self.__nb_iterations = nb
def set_tolerance(self, t): self.__tolerance = t
def set_delta_time(self, d):... | get_nb_iterations | identifier_name | |
simulationlf.py | _phases)[0]
# We won't work on the slack node because it is pointless, so we're only taking nodes starting with the second
brackets = brackets[1:]
for i in range(nb_brackets):
current_bracket = brackets[i]
# p = self.power_definition()
z[i] = (current_bracket... | Ebat -= absolute(np.dot(Ibus[bat], Vbus[bat])) * 0.
Ibr = K * Ibus
Vbr = Zbr * Ibr
if (less(divide(absolute(Vbr - Vbr_prev), absolute(Vbr + 0.0000000000000001)), self.__tolerance)).all():
break
Vbr = Vbr_prev + (alpha * (Vbr - Vbr_p... | k += 1
bal = 0
for i in range(len(P)):
if k == 1:
Ibus[i] = -(np.matrix(np.complex(P[i], Q[i])/Vbus[i]).conj())
else:
Ibus[i] = -(np.matrix(np.complex(P[i], Q[i]) / Vbus[i]).conj())
if i % 3 == bat:
... | conditional_block |
mortgage_pandas.py | test['upb_12'] = test['current_actual_upb']
test.drop(columns=['current_actual_upb'], inplace=True)
test['upb_12'] = test['upb_12'].fillna(999999999)
test['delinquency_12'] = test['delinquency_12'].fillna(-1)
joined_df = test.merge(everdf, how='left', on=['loan_id'])
del(everdf)
del(test)
... | dataFilesNumber = 0
time_ETL = time.time()
exec_time_total = 0
print("RUNNING BENCHMARK NUMBER", benchName, "ITERATION NUMBER", iii)
for quarter in range(0, args.df):
year = 2000 + quarter // 4
perf_file = perf_format_path % (str(year), str(quarter % 4 + 1))
files = [f for f in ... | conditional_block | |
mortgage_pandas.py | relocation_mortgage_indicator': CategoricalDtype(['N', 'Y']),
'year_quarter': np.int64
}
a = pd.read_csv(acquisition_path, names=columns, delimiter='|', dtype=dtypes, parse_dates=[6,7], error_bad_lines=True, warn_bad_lines=True, na_filter=True)
return a
def pd_load_names(**kwargs):
""" Loads n... | merged['timestamp_month'] = merged['monthly_reporting_period'].dt.month
merged['timestamp_month'] = merged['timestamp_month'].astype('int8')
merged['timestamp_year'] = merged['monthly_reporting_period'].dt.year
merged['timestamp_year'] = merged['timestamp_year'].astype('int16')
merged = merged.merge(joi... | identifier_body | |
mortgage_pandas.py | import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=2000, perf_file="", **kwargs):
t1 = time.time()
names = pd_load_names()
year_string = str(year) + "Q" + str(quarter) + ".txt"
acq_file = os.path.join(data_directory, "acq", "Acquisition_" + year_string)
print("READING DAT... | from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time | random_line_split | |
mortgage_pandas.py | ,
"holding_taxes": np.float64,
"net_sale_proceeds": np.float64,
"credit_enhancement_proceeds": np.float64,
"repurchase_make_whole_proceeds": np.float64,
"other_foreclosure_proceeds": np.float64,
"non_interest_bearing_upb": np.float64,
"principal_forgiveness_upb": ... | (acquisition_path, **kwargs):
""" Loads acquisition data
Returns
-------
PD DataFrame
"""
columns = [
'loan_id', 'orig_channel', 'seller_name', 'orig_interest_rate', 'orig_upb', 'orig_loan_term',
'orig_date', 'first_pay_date', 'orig_ltv', 'orig_cltv', 'num_borrowers', 'dti', 'b... | pd_load_acquisition_csv | identifier_name |
api.rs | Some(val) => val,
None => "http".to_string()
};
let host = match api_confs.host.clone() {
Some(val) => val,
None => HOST_URL.to_string()
};
let host_url = match api_confs.port.clone() {
Some(port) => format!("{}://{}:{}", scheme, host, port),
... | {
error: String
}
#[derive(Serialize, Deserialize, Debug)]
struct ShaItem {
language: String,
prod_key: String,
version: String,
sha_value: String,
sha_method: String,
prod_type: Option<String>,
group_id: Option<String>,
artifact_id: Option<String>,
classifier: Option<String>,
... | ApiError | identifier_name |
api.rs | Some(val) => val,
None => "http".to_string()
};
let host = match api_confs.host.clone() {
Some(val) => val,
None => HOST_URL.to_string()
};
let host_url = match api_confs.port.clone() {
Some(port) => format!("{}://{}:{}", scheme, host, port),
... | let e = Error::new( ErrorKind::Other, "Unsupported SHA response - expected array");
return Err(e);
}
let shas = res.as_array().unwrap();
if shas.len() == 0 {
let e = Error::new( ErrorKind::Other, "No match for the SHA");
return Err(e);
}
let doc:ShaItem = serde_json... | {
if json_text.is_none() {
return Err(
Error::new(ErrorKind::Other, "No response from API")
)
}
let res: serde_json::Value = serde_json::from_str(json_text.unwrap().as_str())?;
if res.is_object() && res.get("error").is_some() {
let e = Error::new(
ErrorK... | identifier_body |
api.rs | Some(val) => val,
None => "http".to_string()
};
let host = match api_confs.host.clone() {
Some(val) => val,
None => HOST_URL.to_string()
};
let host_url = match api_confs.port.clone() {
Some(port) => format!("{}://{}:{}", scheme, host, port),
... | .clear()
.append_pair("api_key", api_confs.key.clone().unwrap().as_str());
let json_txt = request_json( &resource_url, &confs.proxy );
process_sha_response(json_txt)
}
//replaces base64 special characters with HTML safe percentage encoding
//source: https://en.wikipedia.org/wiki/Base64#URL_ap... |
//attach query params
resource_url
.query_pairs_mut() | random_line_split |
api.rs | Some(val) => val,
None => "http".to_string()
};
let host = match api_confs.host.clone() {
Some(val) => val,
None => HOST_URL.to_string()
};
let host_url = match api_confs.port.clone() {
Some(port) => format!("{}://{}:{}", scheme, host, port),
... | ,
Err(e) => Err(e)
}
}
pub fn fetch_product_by_sha(confs: &Configs, sha: &str)
-> Result<product::ProductMatch, io::Error> {
let api_confs = confs.api.clone();
let resource_path = format!("products/sha/{}", encode_sha(sha) );
let mut resource_url = match configs_to_url(&api_confs, resource_... | {
let sha = m.sha.expect("No product sha from SHA result");
let product = m.product.expect("No product info from SHA result");
match fetch_product( &confs, &product.language, &product.prod_key, &product.version ) {
Ok(mut m) => {
m.sha = Some(sha);... | conditional_block |
txn_ext.rs | isticLocks, TxnExt, TRANSFER_LEADER_COMMAND_REPLY_CTX,
};
use slog::{error, info, Logger};
use crate::{
batch::StoreContext,
raft::Peer,
router::{PeerMsg, PeerTick},
worker::pd,
SimpleWriteEncoder,
};
pub struct TxnContext {
ext: Arc<TxnExt>,
extra_op: Arc<AtomicCell<ExtraOp>>,
reactiv... | && txn_context.reactivate_memory_lock_ticks >= ctx.cfg.reactive_memory_lock_timeout_tick
{
pessimistic_locks.status = LocksStatus::Normal;
txn_context.reactivate_memory_lock_ticks = 0;
} else {
drop(pessimistic_locks);
self.add_pending_tick(Pee... | {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if !self.is_leader() {
return;
}
let transferring_leader = self.raft_group().raft.lead_transferee.is_some();
let txn_... | identifier_body |
txn_ext.rs | isticLocks, TxnExt, TRANSFER_LEADER_COMMAND_REPLY_CTX,
};
use slog::{error, info, Logger};
use crate::{
batch::StoreContext,
raft::Peer,
router::{PeerMsg, PeerTick},
worker::pd,
SimpleWriteEncoder,
};
pub struct TxnContext {
ext: Arc<TxnExt>,
extra_op: Arc<AtomicCell<ExtraOp>>,
reactiv... | <T>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if !self.is_leader() {
return;
}
let transferring_leader = self.raft_group(... | on_reactivate_memory_lock_tick | identifier_name |
txn_ext.rs | _op: Arc::new(AtomicCell::new(ExtraOp::Noop)),
reactivate_memory_lock_ticks: 0,
}
}
}
impl TxnContext {
#[inline]
pub fn on_region_changed(&self, term: u64, region: &Region) {
let mut pessimistic_locks = self.ext.pessimistic_locks.write();
pessimistic_locks.term = term;
... | let pessimistic_locks = RwLockWriteGuard::downgrade(pessimistic_locks);
fail::fail_point!("invalidate_locks_before_transfer_leader");
for (key, (lock, deleted)) in &*pessimistic_locks {
if *deleted { | random_line_split | |
txn_ext.rs | Locks, TxnExt, TRANSFER_LEADER_COMMAND_REPLY_CTX,
};
use slog::{error, info, Logger};
use crate::{
batch::StoreContext,
raft::Peer,
router::{PeerMsg, PeerTick},
worker::pd,
SimpleWriteEncoder,
};
pub struct TxnContext {
ext: Arc<TxnExt>,
extra_op: Arc<AtomicCell<ExtraOp>>,
reactivate_m... |
}
// Returns whether we should propose another TransferLeader command. This is
// for:
// - Considering the amount of pessimistic locks can be big, it can reduce
// unavailable time caused by waiting for the transferee catching up logs.
// - Make transferring leader strictly after write comm... | {
drop(pessimistic_locks);
self.add_pending_tick(PeerTick::ReactivateMemoryLock);
} | conditional_block |
trx_mgr.go |
return nil
}
// CheckSignerKey checks if the transaction is signed by correct public key.
func (e *TrxEntry) CheckSignerKey(fetcher *AuthFetcher) error {
if err := fetcher.CheckPublicKey(e.signer, e.signerKey); err != nil {
return e.SetError(fmt.Errorf("signature failed: %s", err.Error()))
}
return nil
}
// Ch... | {
return e.SetError(fmt.Errorf("tapos failed: %s", err.Error()))
} | conditional_block | |
trx_mgr.go | x) {
return e.SetError(errors.New("found duplicate in-block trx"))
}
return nil
}
func (e *TrxEntry) GetTrxResult() *prototype.TransactionWrapperWithInfo {
return e.result
}
func (e *TrxEntry) GetTrxSize() int {
return e.size
}
func (e *TrxEntry) GetTrxSigner() string {
return e.signer
}
func (e *TrxEntry) GetT... | // if we have met this transaction before, skip initial check and fill up extra information.
// this voids doing the expensive public key recovery again. | random_line_split | |
trx_mgr.go | correct public key.
func (e *TrxEntry) CheckSignerKey(fetcher *AuthFetcher) error {
if err := fetcher.CheckPublicKey(e.signer, e.signerKey); err != nil {
return e.SetError(fmt.Errorf("signature failed: %s", err.Error()))
}
return nil
}
// CheckInBlockTrxs checks if the transaction is a duplicate of any old trans... | () int {
m.waitingLock.RLock()
defer m.waitingLock.RUnlock()
return len(m.waiting)
}
// FetchTrx fetches a batch of transactions from waiting pool.
// Block producer should call FetchTrx to collect transactions of new blocks.
func (m *TrxMgr) FetchTrx(blockTime uint32, maxCount, maxSize int) (entries []*TrxEntry) {... | WaitingCount | identifier_name |
trx_mgr.go |
// Deliver calls entry's callback function.
func (e *TrxEntry) Deliver() {
if e.callback != nil {
e.callback(e.result)
}
}
// InitCheck fills extra information of the entry, and do a basic validation check.
// Note that InitCheck is independent from chain state. We should do it only once for each transaction.
fu... | {
e.result.Receipt.Status = prototype.StatusError
e.result.Receipt.ErrorInfo = err.Error()
return err
} | identifier_body | |
mixhop_trainer.py | ('adj_pows', '1',
'Comma-separated list of Adjacency powers. Setting to "1" '
'recovers valinna GCN. Setting to "0,1,2" uses '
'[A^0, A^1, A^2]. Further, you can feed as '
'"0:20:10,1:10:10", where the syntax is '
'<pow>... |
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
return params
class AccuracyMonitor(object):
"""Monitors and remembers model parameters @ best validation accuracy."""
def __init__(self, sess, early_stop_steps):... | tf.config.experimental.set_memory_growth(gpu, True) | conditional_block |
mixhop_trainer.py | ('adj_pows', '1',
'Comma-separated list of Adjacency powers. Setting to "1" '
'recovers valinna GCN. Setting to "0,1,2" uses '
'[A^0, A^1, A^2]. Further, you can feed as '
'"0:20:10,1:10:10", where the syntax is '
'<pow>... |
def main(unused_argv):
encoded_params = GetEncodedParams()
output_results_file = os.path.join(
FLAGS.results_dir, encoded_params + '.json')
output_model_file = os.path.join(
FLAGS.train_dir, encoded_params + '.pkl')
if os.path.exists(output_results_file) and not FLAGS.retrain:
print('Exiting ... | sizes = [l[min(layer_index, len(l)-1)] for l in self._ratios]
sum_units = numpy.sum(sizes)
size_per_unit = total_dim / float(sum_units)
dims = []
for s in sizes[:-1]:
dim = int(numpy.round(s * size_per_unit))
dims.append(dim)
dims.append(total_dim - sum(dims))
return dims | identifier_body |
mixhop_trainer.py | ('adj_pows', '1',
'Comma-separated list of Adjacency powers. Setting to "1" '
'recovers valinna GCN. Setting to "0,1,2" uses '
'[A^0, A^1, A^2]. Further, you can feed as '
'"0:20:10,1:10:10", where the syntax is '
'<pow>... | (self):
powers = FLAGS.adj_pows.split(',')
has_colon = None
self._powers = []
self._ratios = []
for i, p in enumerate(powers):
if i == 0:
has_colon = (':' in p)
else:
if has_colon != (':' in p):
raise ValueError(
'Error in flag --adj_pows. Either ... | __init__ | identifier_name |
mixhop_trainer.py | adj_pows', '1',
'Comma-separated list of Adjacency powers. Setting to "1" '
'recovers valinna GCN. Setting to "0,1,2" uses '
'[A^0, A^1, A^2]. Further, you can feed as '
'"0:20:10,1:10:10", where the syntax is '
'<pow>:<... | layer_dims = list(map(int, FLAGS.hidden_dims_csv.split(',')))
layer_dims.append(power_parser.output_capacity(dataset.ally.shape[1]))
for j, dim in enumerate(layer_dims):
if j != 0:
model.add_layer('tf.layers', 'dropout', FLAGS.layer_dropout,
pass_training=True)
ca... | model.add_layer('tf.nn', 'l2_normalize', axis=1)
power_parser = AdjacencyPowersParser() | random_line_split |
lib.rs | Day {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", day_string(*self))
}
}
/// Enum with the months of the year.
#[derive(Debug, Clone, Copy)]
pub enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
Octo... | if year % 400 == 0 {
366
} else if year % 100 == 0 {
365
} else if year % 4 == 0 {
366
} else {
365
}
}
/// Takes in a year and month (e.g. 2020, February) and returns the number of days in that month.
pub fn days_in_month(year: u64, month: Month) -> u64 {
match ... | /// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64) -> u64 { | random_line_split |
lib.rs | Day {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", day_string(*self))
}
}
/// Enum with the months of the year.
#[derive(Debug, Clone, Copy)]
pub enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
Octo... |
/// Returns the number of milliseconds passed since the unix epoch.
pub fn milliseconds_since_epoch(&self) -> u128 {
self.delta.as_millis()
}
/// Returns the number of microseconds passed since the unix epoch.
pub fn microseconds_since_epoch(&self) -> u128 {
self.delta.as_micros()... | {
Self::from(&SystemTime::now())
} | identifier_body |
lib.rs | Day {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", day_string(*self))
}
}
/// Enum with the months of the year.
#[derive(Debug, Clone, Copy)]
pub enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
Octo... | (month: Month) -> &'static str {
&month_string(month)[0..3]
}
impl fmt::Display for Month {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", month_string(*self))
}
}
/// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64... | month_abbrev_string | identifier_name |
Main.py | .minH ) )
)
face_num= None #初始化人脸序号
for (x, y, w, h) in faces:
cv2.rectangle( self.image , (x, y), (x + w, y + h), (0, 0 , 255), 2)
id, confidence = self.recognizer.predict(gray[y:y + h, x:x + w])
if confidence < 100 : #50%的识别置信度
... | random_line_split | ||
Main.py | recognize_face_intnet( self ):
font = cv2.FONT_HERSHEY_SIMPLEX
flag,self.image = self.cap.read() #从视频流中读取
self.image = cv2.resize(self.image, (480,320) ) #把读到的帧的大小重新设置为 480*320
gray = cv2.cvtColor( self.image , cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(g... | 'r+')
real_dict = eval( fl.read() )
names = list( real_dict.keys() )
fl.close()
self.collect_name , ok = QInputDialog.getText( self , '请输入你的名字' ,'必须是已经注册的名字!' )
if self.collect_name in names:
self.face_id = names.index( self.collect_name ) + 1
#... | identifier_body | |
Main.py | self.SigninPage_exe )
self.face_recongition_button.clicked.connect( self.Face_start_exe )
self.collect_buttton.clicked.connect( self.Collect_page_exe )
def SigninPage_exe( self ):
self.sginin_page.exec( )#启动注册页面
# 人脸识别页面
def Face_start_exe( self ):
self.face_page.exec( )
... | ge,cv2.COLOR_BGR2RGB ) #视频色彩转换回RGB,这样才是现实的颜色
#pyqt显示逻辑
showImage = QImage( self.image.data, self.image.shape[1] , self.image.shape[0], QImage.Format_RGB888 )
self.cameraLabel.setPixmap(QPixmap.fromImage(showImage))
#打开摄像头
def openCamera(self):
flag = self.cap.open( cap_id )
... | or(self.ima | identifier_name |
Main.py | .resize( 1000 ,500 )
self.cameraLabel = QLabel( 'camera', self )
self.cameraLabel.resize(480 ,320 )
self.cameraLabel.setAlignment( Qt.AlignCenter )
self.timer_camera = QTimer()
self.cap = cv2.VideoCapture() #初始化摄像头
self.recognizer = cv2.face.LBPHFaceRecognizer_... | cv2.putText(self.image, self.name , (x+5,y-5), font, 1, (255,255,255), 2 )
cv2.putText(self.image, str( self.score ), (x+5,y+h-5), font, 1, (255,255,0), 1 )
def closeCamera(self):
self.timer_camera.stop()
self.cap.release()
self.OnceBaiduAPI_flag = False
s... | conditional_block | |
SPT_AGN_emcee_sampler_MPI.py | # Phi*(z) = 10**(log(Phi*(z))
phi_star = 10 ** log_phi_star(redshift) * (cosmo.h / u.Mpc) ** 3
# QLF slopes
alpha1 = -3.35 # alpha in Table 2
alpha2 = -0.37 # beta in Table 2
Phi = 0.4 * np.log(10) * L_L_star * phi_star * (L_L_star ** -alpha1 + L_L_star ** -alpha2) ** -1
return Phi
d... | """
Assef+11 QLF using luminosity and density evolution.
Parameters
----------
abs_mag : astropy table-like
Rest-frame J-band absolute magnitude.
redshift : astropy table-like
Cluster redshift
Returns
-------
Phi : ndarray
Luminosity density
"""
# L/L_... | identifier_body | |
SPT_AGN_emcee_sampler_MPI.py | phi_star = 10 ** log_phi_star(redshift) * (cosmo.h / u.Mpc) ** 3
# QLF slopes
alpha1 = -3.35 # alpha in Table 2
alpha2 = -0.37 # beta in Table 2
Phi = 0.4 * np.log(10) * L_L_star * phi_star * (L_L_star ** -alpha1 + L_L_star ** -alpha2) ** -1
return Phi
def model_rate_opted(params, cluster_id... |
# Define all priors
if (0.0 <= theta <= np.inf and
-6. <= eta <= 6. and
-3. <= zeta <= 3. and
-3. <= beta <= 3. and
0.05 <= rc <= 0.5 and
0.0 <= C < np.inf):
theta_lnprior = 0.0
eta_lnprior = 0.0
beta_lnprior = 0.0
zet... | theta, eta, zeta, beta, rc, C = params | conditional_block |
SPT_AGN_emcee_sampler_MPI.py | _star = 10 ** log_phi_star(redshift) * (cosmo.h / u.Mpc) ** 3
# QLF slopes
alpha1 = -3.35 # alpha in Table 2
alpha2 = -0.37 # beta in Table 2
Phi = 0.4 * np.log(10) * L_L_star * phi_star * (L_L_star ** -alpha1 + L_L_star ** -alpha2) ** -1
return Phi
def | (params, cluster_id, r_r500, j_mag, integral=False):
"""
Our generating model.
Parameters
----------
params : tuple
Tuple of (theta, eta, zeta, beta, rc, C)
cluster_id : str
SPT ID of our cluster in the catalog dictionary
r_r500 : array-like
A vector of radii of obje... | model_rate_opted | identifier_name |
SPT_AGN_emcee_sampler_MPI.py | j_mag : array-like
A vector of J-band absolute magnitudes to be used in the luminosity function
integral : bool, optional
Flag indicating if the luminosity function factor of the model should be integrated. Defaults to `False`.
Returns
-------
model
A surface density profile... | ndim = 5 if args.cluster_only else (1 if args.background_only else 6) | random_line_split | |
client_enum_component_type.go | 00
ComponentsVendorCategoriesKey = 401
ComponentsVendorSalesKey = 402
ComponentsKiosksKey = 500
ComponentsCurrencyLookupsKey = 600
ComponentsPresentationNodesKey = 700
ComponentsCollectiblesKey = 800
ComponentsRecordsKey = 900
ComponentsTransitoryKe... | These are records of what items you've discovered while playing Destiny, and some other basic information.
For detailed information, you will have to call a separate endpoint devoted to the purpose.
` | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.