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 |
|---|---|---|---|---|
amap.go | "`
Pname string `json:"pname"`
Poiweight []interface{} `json:"poiweight"`
Postcode []interface{} `json:"postcode"`
Recommend string `json:"recommend"`
Shopid []interface{} `json:"shopid"`
Shopinfo string `json:"shopinfo"`
Tag []interface{} `json:"tag"`
Tel string ... | (mRecs []minRec) (mrp []minRecPage) {
for _, mRec := range mRecs {
mrp = append(mrp, minRecPages(mRec)...)
}
return
}
func recTypePages(rec Rectangle, types string) (mrp []minRecPage) {
cutrec := cutRec(rec, types)
mrp = minRecsPages(cutrec)
return
}
// RecTypePois RecTypePois
func RecTypePois(rec Rectangle, ... | minRecsPages | identifier_name |
models.py | ("将保证金改为0")
# 增加不良记录天数
self.none_punch_days = 1
elif self.none_punch_days >= 1 and self.down_payment > 0:
print("如果不良天数不等于1")
#防止修改数据库debug而出现的错误
self.guaranty = 0
# 如果是日常模式
if self.guaranty == 0:... | identifier_body | ||
models.py | = distance
distances = int(distance)
kilos_day = 2 * distances // actual_day_map[goal_day]
# 查询出没有支付的活动
goal = self.filter(user_id=user_id).filter(start_time=start_time).filter(status="PENDING")
# 如果存在的话就删掉
if goal:
goal.first().delete()
goal ... | te(goal=goal, voucher_ref=file_refpath, voucher_store=file_filepath, distance=distance,record_time = punch_record_time,
document=document)
print(555555555555555555555555555555555555555)
# 如果是自由模式, 则计算剩余距离
if not goal.goal_type:
goal.left_distance -= dista... | record = self.crea | identifier_name |
models.py | filter(start_time=start_time).filter(status="PENDING")
# 如果存在的话就删掉
if goal:
goal.first().delete()
goal = self.create(user_id=user_id,
activity_type=RunningGoal.get_activity(),
start_time=start_time,
goal... | 21: 18,
30: 25,
61: 50
}
goal_distance = distance
left_distance = distance
distances = int(distance)
kilos_day = 2 * distances // actual_day_map[goal_day]
# 查询出没有支付的活动
goal = self.filter(user_id=us... | conditional_block | |
models.py | start_time = timezone.now() # + timedelta(days=1)
# start_time = datetime.strptime("2018-01-01 00:00:01", "%Y-%m-%d %H:%M:%S")
kilos_day, goal_distance, left_distance = None, None, None
if running_type:
kilos_day = distance
else:
actual_day_map = ... | if settings.DEBUG:
start_time = timezone.now()
else:
# 当天创建活动只有后一天才能参加,所以以后一天为开始日期 | random_line_split | |
j1f.rs | (ix: u32, x: f32, y1: bool, sign: bool) -> f32 {
let z: f64;
let mut s: f64;
let c: f64;
let mut ss: f64;
let mut cc: f64;
s = sinf(x) as f64;
if y1 {
s = -s;
}
c = cosf(x) as f64;
cc = s - c;
if ix < 0x7f000000 {
ss = -s - c;
z = cosf(2.0 * x) as f64... | common | identifier_name | |
j1f.rs | 60174561e+02, /* 0xc43de683 */
-1.1849806641e+04, /* 0xc639273a */
-4.8438511719e+04, /* 0xc73d3683 */
];
const QS8: [f32; 6] = [
1.6139537048e+02, /* 0x43216537 */
7.8253862305e+03, /* 0x45f48b17 */
1.3387534375e+05, /* 0x4802bcd6 */
7.1965775000e+05, /* 0x492fb29c */
6.6660125000e+05, ... | {
// 0x401F3E49
assert_eq!(j1f(2.4881766_f32), 0.49999475_f32);
} | identifier_body | |
j1f.rs | ix = x.to_bits();
sign = (ix >> 31) != 0;
ix &= 0x7fffffff;
if ix >= 0x7f800000 {
return 1.0 / (x * x);
}
if ix >= 0x40000000 {
/* |x| >= 2 */
return common(ix, fabsf(x), false, sign);
}
if ix >= 0x39000000 {
/* |x| >= 2**-13 */
z = x * x;
... | let sign: bool;
| random_line_split | |
postgres.go | dev and production
type DB struct {
dbProxy
squirrel.StatementBuilderType
}
type dbProxy interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
Prepare(query string) (*sql.Stmt, erro... |
// GetAllConfigs gets all of the userconfig.
func (d DB) GetAllConfigs(ctx context.Context) (map[string]userconfig.View, error) {
return d.findConfigs(allConfigs)
}
// GetConfigs gets all of the configs that have changed recently.
func (d DB) GetConfigs(ctx context.Context, since userconfig.ID) (map[string]userconf... | {
if !cfg.RulesConfig.FormatVersion.IsValid() {
return fmt.Errorf("invalid rule format version %v", cfg.RulesConfig.FormatVersion)
}
cfgBytes, err := json.Marshal(cfg)
if err != nil {
return err
}
_, err = d.Insert("configs").
Columns("owner_id", "owner_type", "subsystem", "config").
Values(userID, entit... | identifier_body |
postgres.go | migrationsDir = "file:" + migrationsDir
}
m, err := migrate.New(migrationsDir, uri)
if err != nil {
return DB{}, errors.Wrap(err, "database migrations initialization failed")
}
level.Info(util_log.Logger).Log("msg", "running database migrations...")
if err := m.Up(); err != nil {
if err != migrate... | return err
}
return d.SetDeletedAtConfig(ctx, userID, pq.NullTime{Time: time.Now(), Valid: true}, cfg.Config)
} | random_line_split | |
postgres.go | dev and production
type DB struct {
dbProxy
squirrel.StatementBuilderType
}
type dbProxy interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
Prepare(query string) (*sql.Stmt, erro... |
// Legacy configs don't have a rule format version, in which case this will
// be a zero-length (but non-nil) slice.
if len(rfvBytes) > 0 {
err = json.Unmarshal([]byte(`"`+string(rfvBytes)+`"`), &cfg.Config.FormatVersion)
if err != nil {
return nil, err
}
}
cfg.DeletedAt = deletedAt.Time
cfgs[... | {
return nil, err
} | conditional_block |
postgres.go | , "database migrations failed")
}
level.Debug(util_log.Logger).Log("msg", "no change in schema, error (ignored)", "err", err)
}
}
return DB{
dbProxy: db,
StatementBuilderType: statementBuilder(db),
}, err
}
var statementBuilder = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)... | Transaction | identifier_name | |
chroot.go | if err != nil {
return fmt.Errorf("Failed to mount '%s': %w", mount.Source, err)
}
}
return nil
}
func moveMounts(mounts []ChrootMount) error {
for i, mount := range mounts {
// Source path
tmpSource := filepath.Join("/", ".distrobuilder", fmt.Sprintf("%d", i))
// Resolve symlinks
target := mount.T... |
// Mount to the temporary path
err := unix.Mount(mount.Source, tmpTarget, mount.FSType, mount.Flags, mount.Data) | random_line_split | |
chroot.go | temporary path
err := unix.Mount(mount.Source, tmpTarget, mount.FSType, mount.Flags, mount.Data)
if err != nil {
return fmt.Errorf("Failed to mount '%s': %w", mount.Source, err)
}
}
return nil
}
func moveMounts(mounts []ChrootMount) error {
for i, mount := range mounts {
// Source path
tmpSource := f... | if err != nil {
return nil, err
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
// Setup all needed mounts in a temporary location
if len(m) > 0 {
err = setupMounts(rootfs, append(mounts, m...))
} else {
err = setupMounts(rootfs, mounts)
}
if err != nil {
return nil, fmt.Errorf("Failed... | {
// Mount the rootfs
err := unix.Mount(rootfs, rootfs, "", unix.MS_BIND, "")
if err != nil {
return nil, fmt.Errorf("Failed to mount '%s': %w", rootfs, err)
}
// Setup all other needed mounts
mounts := []ChrootMount{
{"none", "/proc", "proc", 0, "", true},
{"none", "/sys", "sysfs", 0, "", true},
{"none"... | identifier_body |
chroot.go | (rootfs string, mounts []ChrootMount) error {
// Create a temporary mount path
err := os.MkdirAll(filepath.Join(rootfs, ".distrobuilder"), 0700)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", filepath.Join(rootfs, ".distrobuilder"), err)
}
for i, mount := range mounts {
// Target path
... | setupMounts | identifier_name | |
chroot.go | distrobuilder"), err)
}
return nil
}
func killChrootProcesses(rootfs string) error {
// List all files under /proc
proc, err := os.Open(filepath.Join(rootfs, "proc"))
if err != nil {
return fmt.Errorf("Failed to open file %q: %w", filepath.Join(rootfs, "proc"), err)
}
dirs, err := proc.Readdirnames(0)
if e... | {
return fmt.Errorf("Failed to chmod %q: %w", d.Path, err)
} | conditional_block | |
main.rs | : QuestionDTO,
pub created_at: DateTime<Local>,
pub created_at_recognizable: String,
}
impl AnswerDTO {
fn from(a: model::Answer) -> Self {
Self {
id: a.id, body: a.body, created_at: a.created_at,
created_at_recognizable: utils::recognizable_datetime(a.created_at),
... |
/* POST /questions */
#[derive(FromForm)]
struct PostQuestionForm {
body: String
}
#[derive(Serialize, Debug)]
struct PostQuestionFailedDTO {
reason: String
}
#[post("/questions", data = "<params>")]
fn post_question(repo: web::guard::Repository, client_ip: web::guard::ClientIP, params: request::Form<PostQ... | {
let answer_dtos = repo.search_answers(query.clone())
.into_iter()
.map(|a| AnswerDTO::from(a))
.collect::<Vec<_>>();
let context = SearchDTO {
profile: ProfileDTO {
username: profile.clone().nam... | identifier_body |
main.rs | /* Force ssl */
#[get("/<path..>")]
fn redirect_ssl(path: PathBuf, _ssl: web::guard::ForceSSL) -> response::Redirect {
let redirect_to = format!("https://{}/{}", env::var("APPLICATION_DOMAIN").unwrap(), path.as_path().display());
println!("Redirect to:{}", redirect_to);
response::Redirect::to(redirect_to)
}... | mpl<'r> resp | identifier_name | |
main.rs | : QuestionDTO,
pub created_at: DateTime<Local>,
pub created_at_recognizable: String,
}
impl AnswerDTO {
fn from(a: model::Answer) -> Self {
Self {
id: a.id, body: a.body, created_at: a.created_at,
created_at_recognizable: utils::recognizable_datetime(a.created_at),
... | ,
Err(err) => {
match err {
model::StoreQuestionError::BlankBody => {
let context = PostQuestionFailedDTO { reason: String::from("質問の内容が空です") };
Err(Template::render("question/post_failed", &context))
}
}
}
... | {
let question_id = question.id;
notify::send_email(question);
Ok(response::Redirect::to(format!("/question/{}/after_post", question_id)))
} | conditional_block |
main.rs | : QuestionDTO,
pub created_at: DateTime<Local>,
pub created_at_recognizable: String,
}
impl AnswerDTO {
fn from(a: model::Answer) -> Self {
Self {
id: a.id, body: a.body, created_at: a.created_at,
created_at_recognizable: utils::recognizable_datetime(a.created_at),
... | #[derive(Serialize, Debug)]
struct ShowAnswerDTO {
pub answer: AnswerDTO,
pub next_answer: Option<AnswerDTO>,
pub prev_answer: Option<AnswerDTO>,
}
#[get("/question/<question_id>")]
fn show_question(question_id: i32, repo: web::guard::Repository) -> Result<response::Redirect, status::NotFound<&'static str>... | random_line_split | |
lib.rs | //! ```
//!
//! To get started using Crabsformer, read the quickstart tutorial below.
//!
//! # Quickstart Tutorial
//!
//! ## Prerequisites
//! Before reading this quick tutorial you should know a bit of Rust. If you
//! would like to refresh your memory, take a look at the [Rust book].
//!
//! [Rust book]: https://do... | //!
//! and this to your crate root:
//!
//! ```
//! use crabsformer::prelude::*; | random_line_split | |
2.1.dl_tf_intermediate_classifications.py | , may not be use ful for current analysis
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
data.info() # Now see if any missing values in any columns
#Note: how to impute missing value is purview of ML. Here, do simple thing so that we focus on DL
age_avg = data['Age'].mean()
data['Age... |
if caller_source == 'train':
dataset = dataset.shuffle(len(features)) #if ".repeat()" is added here then add "epochs steps_per_epoch" in fit
dataset = dataset.batch(custom_batch_size)
return dataset
#train in iterable dataset
ds_train = input_fn(training_set[FEATURES], tr... | dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) | conditional_block |
2.1.dl_tf_intermediate_classifications.py | , may not be use ful for current analysis
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
data.info() # Now see if any missing values in any columns
#Note: how to impute missing value is purview of ML. Here, do simple thing so that we focus on DL
age_avg = data['Age'].mean()
data['Age... | (features, labels = None, custom_batch_size = batch_size, caller_source = 'train'):
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices(dict(features))
if caller_source != 'test':
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
... | input_fn | identifier_name |
2.1.dl_tf_intermediate_classifications.py | , may not be use ful for current analysis
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
data.info() # Now see if any missing values in any columns
#Note: how to impute missing value is purview of ML. Here, do simple thing so that we focus on DL
age_avg = data['Age'].mean()
data['Age... | training_set.shape
training_set.head(2)
len_fea = len(ar_independent_features)
# Build the model
model = tf.keras.models.Sequential() # same as tf.keras.Sequential()
model.add(tf.keras.layers.Dense(2*len_fea, input_shape=(len_fea,), activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(len_fea, activation=t... | random_line_split | |
2.1.dl_tf_intermediate_classifications.py | , may not be use ful for current analysis
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
data.info() # Now see if any missing values in any columns
#Note: how to impute missing value is purview of ML. Here, do simple thing so that we focus on DL
age_avg = data['Age'].mean()
data['Age... |
#train in iterable dataset
ds_train = input_fn(training_set[FEATURES], training_set[LABEL],custom_batch_size = batch_size)
#Create feature columns
feature_cols = []
# numeric cols
for num_col in NUM_FEATURES:
feature_cols.append(tf.feature_column.numeric_column(num_col, dtype=tf.float32))
#bucketized... | dataset = tf.data.Dataset.from_tensor_slices(dict(features))
if caller_source != 'test':
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
if caller_source == 'train':
dataset = dataset.shuffle(len(features)) #if ".repeat()" is added here then add "epochs st... | identifier_body |
ivf_torch.py | elif dtype == int:
return int
elif dtype == list:
return "float32"
else:
raise ValueError(
"[KeOps] {} data type incompatible with KeOps.".format(dtype)
)
@staticmethod
def rand(m, n, dtype=default_dtype, device="cpu"):
... | return "float64"
elif dtype == torch.float16:
return "float16" | random_line_split | |
ivf_torch.py | list:
return "float32"
else:
raise ValueError(
"[KeOps] {} data type incompatible with KeOps.".format(dtype)
)
@staticmethod
def rand(m, n, dtype=default_dtype, device="cpu"):
return torch.rand(m, n, dtype=dtype, device=device)
@staticme... |
if k == 1:
return self.tools.view(self.tools.long(d.argmin(dim=1)), -1)
else:
return self.tools.long(d.argKmin(K=k, dim=1))
def __sort_clusters(self, x, lab, store_x=True):
lab, perm = self.tools.sort(self.tools.view(lab, -1))
if store_x:
self._... | d.backend = self.__backend | conditional_block |
ivf_torch.py | list:
return "float32"
else:
raise ValueError(
"[KeOps] {} data type incompatible with KeOps.".format(dtype)
)
@staticmethod
def rand(m, n, dtype=default_dtype, device="cpu"):
return torch.rand(m, n, dtype=dtype, device=device)
@staticme... |
N, D = x.shape
c = x[:K, :].clone()
x_i = LazyTensor(x.view(N, 1, D).to(device))
for i in range(Niter):
c_j = LazyTensor(c.view(1, K, D).to(device))
D_ij = distance(x_i, c_j)
cl = D_ij.argmin(dim=1).long().view(-1)
# updating c: either ... | "Helper function to optimise centroid location"
c = torch.clone(c.detach()).to(device)
c.requires_grad = True
x1 = LazyTensor(x.unsqueeze(0))
op = torch.optim.Adam([c], lr=1 / n)
scaling = 1 / torch.gather(torch.bincount(cl), 0, cl).view(-1, 1)
sca... | identifier_body |
ivf_torch.py | list:
return "float32"
else:
raise ValueError(
"[KeOps] {} data type incompatible with KeOps.".format(dtype)
)
@staticmethod
def rand(m, n, dtype=default_dtype, device="cpu"):
return torch.rand(m, n, dtype=dtype, device=device)
@staticme... | (self):
pass
def __k_argmin(self, x, y, k=1):
x_LT = self.__LazyTensor(
self.tools.to(self.tools.unsqueeze(x, 1), self.__device)
)
y_LT = self.__LazyTensor(
self.tools.to(self.tools.unsqueeze(y, 0), self.__device)
)
d = self.__distance(x_LT, ... | __get_tools | identifier_name |
views.py | ,
title=title,
description=description,
start_time=start_time,
end_time=end_time,
location= location
)
return HttpResponseRedirect(reverse('manCal:calendar'))
return render(request, 'event.html', {'form': form})
#generic update view for ev... | note_delete | identifier_name | |
views.py |
else:
Http404('Wrong credentials')
# If logged in, session variables are cleaned up and user logged out. Otherwise redirected to login page
@login_required
def logoutView(request):
logout(request)
#registration
def signUpView(request):
#checking if methos is POST
if request.method == "POST":... | request.session['username'] = username
request.session['password'] = password
context = {
'username': username,
'password': password,
'loggedin': True
}
response = render(request, 'index.html', context)
# Remember last login in cookie
... | conditional_block | |
views.py | .com/maps/api/geocode/json?'
#API response conteining geo-cordinates
response = requests.get(base_url, params=params).json()
#checking if the request was succesful
if response['status'] == 'OK':
geometry = response['results'][0]['geometry']
#obtaing latiture and longitude
... | note.complited = False
elif note.complited == False:
note.complited = True
#saveing new status | random_line_split | |
views.py | variable
title = form.cleaned_data['title']
description = form.cleaned_data['description']
start_time = form.cleaned_data['start_time']
end_time = form.cleaned_data['end_time']
location = form.cleaned_data['location']
#creating new event object
Event.objects.get_... | file = EventFiles.objects.get(id = file_id)
file.delete()
return JsonResponse({'result' : 'ok'}, status=200) | identifier_body | |
utils.py | and SENTENCE_END tokens
print("Reading CSV file...")
with open(filename, 'rt') as f:
reader = csv.reader(f, skipinitialspace=True)
reader.next()
# Split full comments into sentences
sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode("utf-8").lower()) for x in reader])
... |
tokens = word_tokenize(text)
word_freq = nltk.FreqDist(tokens)
if verbose:
print("Found %d unique words tokens." % len(word_freq.items()))
vocab = word_freq.most_common(vocsize-3)
indices_word = [x[0] for x in vocab]
indices_word.append(UNKNOWN_TOKEN)
indices_word.append(S... | print('corpus length:', len(text)) | conditional_block |
utils.py | _to_index = dict([(w, i) for i, w in enumerate(index_to_word)])
# Replace all words not in our vocabulary with the unknown token
for i, sent in enumerate(tokenized_sentences):
tokenized_sentences[i] = [w if w in word_to_index else UNKNOWN_TOKEN for w in sent]
# Create the training data
X_train... | """
Saves stuff to disk as pickle object
:type stuff: any type
:param stuff: data to be stored
Return: create pickle file at path
"""
if path == None:
# TODO take name from something
output = open('results/i-will-be-overwritten.pkl', 'wb')
else:
output = open(pat... | identifier_body | |
utils.py | and SENTENCE_END tokens
print("Reading CSV file...")
with open(filename, 'rt') as f:
reader = csv.reader(f, skipinitialspace=True)
reader.next()
# Split full comments into sentences
sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode("utf-8").lower()) for x in reader])
... | (s, index_to_word):
sentence_str = [index_to_word[x] for x in s[1:-1]]
print(" ".join(sentence_str))
sys.stdout.flush()
def generate_sentence(model, index_to_word, word_to_index, min_length=5):
# We start the sentence with the start token
new_sentence = [word_to_index[SENTENCE_START_TOKEN]]
# R... | print_sentence | identifier_name |
utils.py | and SENTENCE_END tokens
print("Reading CSV file...")
with open(filename, 'rt') as f:
reader = csv.reader(f, skipinitialspace=True)
reader.next()
# Split full comments into sentences
sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode("utf-8").lower()) for x in reader])
... |
return xx, yy, vocab, word_indices, indices_word
def train_with_sgd(model, X_train, y_train, learning_rate=0.001, nepoch=40, startfrom = 0, decay=0.9,
callback_every=10000, callback=None):
for epoch in range(startfrom, nepoch):
num_examples_seen = 0
# For each training examp... |
# Create the training data
xx = np.asarray(tokens[:-1], dtype=np.int32)
yy = np.asarray(tokens[1:], dtype=np.int32) | random_line_split |
Surreal.py | #
# Hugues THOMAS - 11/06/2018
# Nicolas DONATI - 01/01/2020
# ----------------------------------------------------------------------------------------------------------------------
#
# Imports and global variables
# \**********************************/
#
# Basic libs
import tensorflow as t... | (stacked_points, stacked_evecs, stacked_evecs_trans,
stacked_evals, stacked_evecs_full, obj_inds, stack_lengths):
"""
From the input point cloud, this function compute all the point clouds at each conv layer, the neighbors
indices, the pooling indices and other use... | tf_map | identifier_name |
Surreal.py | #
# Hugues THOMAS - 11/06/2018
# Nicolas DONATI - 01/01/2020
# ----------------------------------------------------------------------------------------------------------------------
#
# Imports and global variables
# \**********************************/
#
# Basic libs
import tensorflow as t... | pass
elif config.in_features_dim == 3:
stacked_features = tf.concat((stacked_features, stacked_points), axis=1)
else:
raise ValueError('Only accepted input dimensions are 1, 3 (with or without XYZ)')
# Get the whole input list
... | """
From the input point cloud, this function compute all the point clouds at each conv layer, the neighbors
indices, the pooling indices and other useful variables.
:param stacked_points: Tensor with size [None, 3] where None is the total number of points
:param stack_le... | identifier_body |
Surreal.py | #
# Hugues THOMAS - 11/06/2018
# Nicolas DONATI - 01/01/2020
# ----------------------------------------------------------------------------------------------------------------------
#
# Imports and global variables
# \**********************************/
#
# Basic libs
import tensorflow as t... |
else:
return cpp_subsampling.compute(points, features=features, classes=labels, sampleDl=sampleDl, verbose=verbose)
# ----------------------------------------------------------------------------------------------------------------------
#
# Class Definition
# \***************/
#
class S... | return cpp_subsampling.compute(points, classes=labels, sampleDl=sampleDl, verbose=verbose) | conditional_block |
Surreal.py | ------
#
# Hugues THOMAS - 11/06/2018
# Nicolas DONATI - 01/01/2020
# ----------------------------------------------------------------------------------------------------------------------
#
# Imports and global variables
# \**********************************/
#
# Basic libs
import tensorfl... | :param labels: optional (N,) matrix of integer labels
:param sampleDl: parameter defining the size of grid voxels
:param verbose: 1 to display
:return: subsampled points, with features and/or labels depending of the input
"""
if (features is None) and (labels is None):
return cpp_subsam... | :param points: (N, 3) matrix of input points
:param features: optional (N, d) matrix of features (floating number) | random_line_split |
widget.rs | ,
) -> Option<(NodeId, CallWidgetsConfig)> {
let query_data = self.widget_queries.get_mut(&target)?;
let (definitions, errors) = configuration::deserialize_widget_definitions(
&data,
&self.graph.suggestion_db(),
&self.graph.parser(),
);
for error... | }
buffer.push(']'); | random_line_split | |
widget.rs | , manager_notifications) = Manager::new(executed_graph.clone_ref());
let frp = Frp::new();
let model = Rc::new(RefCell::new(Model {
manager,
graph: executed_graph.clone_ref(),
widgets_of_node: default(),
widget_queries: default(),
}));
le... | update | identifier_name | |
argument_parser.py | (locustfile):
"""
Attempt to locate a locustfile, either explicitly or by searching parent dirs.
"""
# Obtain env value
names = [locustfile]
# Create .py version if necessary
if not names[0].endswith('.py'):
names.append(names[0] + '.py')
# Does the name contain path elements?
... | find_locustfile | identifier_name | |
argument_parser.py | parse_options(args=args)
sys.stderr.write("Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.\n")
sys.exit(1)
if locustfile == "locust.py":
sys.stderr.write("The locustfile must not be named `locust.py`. Please rename the file and ... | '-s', '--stop-timeout',
action='store',
type=int, | random_line_split | |
argument_parser.py | parent_path = os.path.dirname(path)
if parent_path == path:
# we've reached the root path which has been checked this iteration
break
path = parent_path
# Implicit 'return None' if nothing was found
def get_empty_argument_parser(add_help=True, de... |
if locustfile == "locust.py":
sys.stderr.write("The locustfile must not be named `locust.py`. Please rename the file and try again.\n")
sys.exit(1)
return locustfile
def setup_parser_arguments(parser):
"""
Setup command-line options
Takes a configargparse.Argume... | if options.help or options.version:
# if --help or --version is specified we'll call parse_options which will print the help/version message
parse_options(args=args)
sys.stderr.write("Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.\n")
... | conditional_block |
argument_parser.py | parent_path = os.path.dirname(path)
if parent_path == path:
# we've reached the root path which has been checked this iteration
break
path = parent_path
# Implicit 'return None' if nothing was found
def get_empty_argument_parser(add_help=True, de... | parser.add_argument(
'-r', '--hatch-rate',
type=float,
default=1,
help="The rate per second in which clients are spawned. Only used together with --headless"
)
# Time limit of the test run
parser.add_argument(
'-t', '--run-time',
help="Stop after the speci... | """
Setup command-line options
Takes a configargparse.ArgumentParser as argument and calls it's add_argument
for each of the supported arguments
"""
parser._optionals.title = "Common options"
parser.add_argument(
'-H', '--host',
help="Host to load test in the following form... | identifier_body |
client.rs | client may receive.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Notification {
/// A new data has been sent for a visualization.
VisualizationUpdate {
/// Identifies the specific visualization.
context: VisualizationContext,
/// Data to be passed to the visualization.
data: ... |
}
/// Function that does early processing of the peer's message and decides how it shall be
/// handled. Returns a function so that it may be passed to the `Handler`.
fn processor(
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> + 'static
{
mo... | {
Err(RpcError::MismatchedResponseType.into())
} | conditional_block |
client.rs | client may receive.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Notification {
/// A new data has been sent for a visualization.
VisualizationUpdate {
/// Identifies the specific visualization.
context: VisualizationContext,
/// Data to be passed to the visualization.
data: ... | (
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> + 'static
{
move |event: TransportEvent| {
let binary_data = match event {
TransportEvent::BinaryMessage(data) => data,
_ => return Disposition::error(UnexpectedTextMe... | processor | identifier_name |
client.rs | client may receive.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Notification {
/// A new data has been sent for a visualization.
VisualizationUpdate {
/// Identifies the specific visualization.
context: VisualizationContext,
/// Data to be passed to the visualization.
data: ... |
fn write_file(&self, path: &Path, contents: &[u8]) -> StaticBoxFuture<FallibleResult> {
info!("Writing file {} with {} bytes.", path, contents.len());
let payload = ToServerPayload::WriteFile { path, contents };
self.make_request(payload, Self::expect_success)
}
fn read_file(&self... | {
info!("Initializing binary connection as client with id {client_id}.");
let payload = ToServerPayload::InitSession { client_id };
self.make_request(payload, Self::expect_success)
} | identifier_body |
client.rs | client may receive.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Notification {
/// A new data has been sent for a visualization.
VisualizationUpdate {
/// Identifies the specific visualization.
context: VisualizationContext,
/// Data to be passed to the visualization.
data: ... | // ===============
struct ClientFixture {
transport: MockTransport,
client: Client,
executor: futures::executor::LocalPool,
}
impl ClientFixture {
fn new() -> ClientFixture {
let transport = MockTransport::new();
let client = Client::new(tran... |
// ===============
// === Fixture === | random_line_split |
anlyzPRR.py | 2d' % (recdDateTime.year, recdDateTime.month)
except Exception as e:
print('huh')
if prr['status'] == 'Closed':
# 180228
# closeDate = prr['statusUpDate']
closeDate = prr['closeDate']
if closeDate==None:
nmissClose += 1
missCloseDetails[dept][recdMonKey].append(prrID)
continu... | random_line_split | ||
anlyzPRR.py | rrID] = prr
print('bldIndexTblCSV: NPRR=%d NDept=%d NMultDept=%d NCloseDate=%d' % \
(len(prrTbl),len(deptTbl),nmultDept,ncloseDate))
if startDate != None:
print('bldIndexTblCSV: NOld dropped=%d' % (nolder))
# freqList = freqHist3(deptTbl)
# print('Dept,Freq')
# for dept,freq in freqList:
# print('"%s",%d... | outs = open(outf,'w')
outs.write('Dept,Freq\n')
for dept in sorted(deptTbl.keys()):
nrecent = 0
for prrIdx in deptTbl[dept]:
prr = prrTbl[prrIdx]
if prr['createDate'] >= startDate:
nrecent += 1
outs.write('%s,%d\n' % (dept,nrecent))
outs.close() | identifier_body | |
anlyzPRR.py | (a,b):
"decreasing order of frequencies"
return b[1] - a[1]
flist = list(tbl.items()) #python3
flist.sort(key=cmp_to_key(cmpd1))
return flist
AllCSVHeader = ['Id', 'Created At', 'Request Text', 'Due Date', 'Point of Contact', 'Request Date',
'Status', 'URL', 'Visibility', 'Closed Date', 'Closure Reasons',... | cmpd1 | identifier_name | |
anlyzPRR.py | hist: value -> freq
'''
sum = n = 0
for v in hist.keys():
n += hist[v]
sum += v * hist[v]
return n,float(sum) / n
def compMedian(hist):
'''compute MEDIAN value
ASSUME hist: value -> freq
'''
# only singletons thwart the search for half-way point
if len(hist) == 1:
return hist[0]
sum = n = 0
v... | dkey = 1000 + openYears | conditional_block | |
control.rs | This configuration file is meant to specify its
//! running state. It can be reloaded at runtime, to change the whole state of the server.
//!
//! The first time the configuration file is read, ellidri uses it to create the tokio runtime.
//! This is because the number of workers is yet unknown, and cannot be change... |
} else {
tokio::spawn(new_b.future);
bindings.push((new_b.address, new_b.handle));
}
}
shared.rehash(cfg.state).await;
log::info!("Configuration reloaded");
}
/// Re-read the configuration file and re-generate the bindings.
///
/// See documentation of `reload_bin... | {
// Failure to send the command means either the binding task have dropped the
// command channel, or the binding task doesn't exist anymore. Both possibilities
// shouldn't happen (see doc for `Control.bindings`); but in the opposite case
// let's remov... | conditional_block |
control.rs | . This configuration file is meant to specify its
//! running state. It can be reloaded at runtime, to change the whole state of the server.
//!
//! The first time the configuration file is read, ellidri uses it to create the tokio runtime.
//! This is because the number of workers is yet unknown, and cannot be chang... | (
config_path: String,
shared: State,
stop: mpsc::Sender<SocketAddr>,
) -> Option<(Config, Vec<LoadedBinding<impl Future<Output = ()>>>)> {
let mut cfg = match Config::from_file(&config_path) {
Ok(cfg) => cfg,
Err(err) => {
log::error!("Failed to read {:?}: {}", config_path, ... | reload_config | identifier_name |
control.rs | . This configuration file is meant to specify its
//! running state. It can be reloaded at runtime, to change the whole state of the server.
//!
//! The first time the configuration file is read, ellidri uses it to create the tokio runtime.
//! This is because the number of workers is yet unknown, and cannot be chang... | //!
//! Bindings are identified by their socket address (IP address + TCP port). TLS identities are
//! not kept track of, thus ellidri might reload the same TLS identity for a binding (it is fine to
//! let it do we are not reading thousands for TLS identities here).
use crate::{Config, net, State, tls};
use crate::... | //! - If a binding is present in both configurations, `Control` will keep the binding and send a
//! command to it, either to make it listen for raw TCP connections, or to listen for TLS
//! connections with a given `TlsAcceptor` (see `tokio-tls` doc for that). | random_line_split |
config.rs | env = "PATHFINDER_ETHEREUM_API_PASSWORD",
)]
ethereum_password: Option<String>,
#[arg(
long = "ethereum.url",
long_help = r"This should point to the HTTP RPC endpoint of your Ethereum entry-point, typically a local Ethereum client or a hosted gateway service such as Infura or Cloud... |
#[arg(
long = "ethereum.password",
long_help = "The optional password to use for the Ethereum API",
value_name = None, | random_line_split | |
config.rs | {
#[arg(
long,
value_name = "DIR",
value_hint = clap::ValueHint::DirPath,
long_help = "Directory where the node should store its data",
env = "PATHFINDER_DATA_DIRECTORY",
default_value_os_t = (&std::path::Component::CurDir).into()
)]
data_directory: PathBuf... | Cli | identifier_name | |
vacuum.py | .clean import CleanAction, CleanArea, CleanMode
from deebot_client.commands.custom import CustomCommand
from deebot_client.events import (
BatteryEvent,
CustomCommandEvent,
ErrorEvent,
FanSpeedEvent,
ReportStatsEvent,
RoomsEvent,
StatusEvent,
)
from deebot_client.events.event_bus import Even... |
async def on_status(event: StatusEvent) -> None:
self._state = event.state
self.async_write_ha_state()
listeners: list[EventListener] = [
self._vacuum_bot.events.subscribe(BatteryEvent, on_battery),
self._vacuum_bot.events.subscribe(CustomCommandEvent, ... | self._rooms = event.rooms
self.async_write_ha_state() | identifier_body |
vacuum.py | .clean import CleanAction, CleanArea, CleanMode
from deebot_client.commands.custom import CustomCommand
from deebot_client.events import (
BatteryEvent,
CustomCommandEvent,
ErrorEvent,
FanSpeedEvent,
ReportStatsEvent,
RoomsEvent,
StatusEvent,
)
from deebot_client.events.event_bus import Even... | | SUPPORT_RETURN_HOME
| SUPPORT_FAN_SPEED
| SUPPORT_BATTERY
| SUPPORT_SEND_COMMAND
| SUPPORT_LOCATE
| SUPPORT_MAP
| SUPPORT_STATE
| SUPPORT_START
)
# Must be kept in sync with services.yaml
SERVICE_REFRESH = "refresh"
SERVICE_REFRESH_PART = "part"
SERVICE_REFRESH_SCHEMA = {
vol.Requ... | SUPPORT_DEEBOT: int = (
SUPPORT_PAUSE
| SUPPORT_STOP | random_line_split |
vacuum.py | .clean import CleanAction, CleanArea, CleanMode
from deebot_client.commands.custom import CustomCommand
from deebot_client.events import (
BatteryEvent,
CustomCommandEvent,
ErrorEvent,
FanSpeedEvent,
ReportStatsEvent,
RoomsEvent,
StatusEvent,
)
from deebot_client.events.event_bus import Even... |
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_REFRESH,
SERVICE_REFRESH_SCHEMA,
"_service_refresh",
)
class DeebotVacuum(DeebotEntity, StateVacuumEntity): # type: ignore
"""Deebot Vacuum."""
def __init__(self, va... | async_add_entities(new_devices) | conditional_block |
vacuum.py | .clean import CleanAction, CleanArea, CleanMode
from deebot_client.commands.custom import CustomCommand
from deebot_client.events import (
BatteryEvent,
CustomCommandEvent,
ErrorEvent,
FanSpeedEvent,
ReportStatsEvent,
RoomsEvent,
StatusEvent,
)
from deebot_client.events.event_bus import Even... | (event: FanSpeedEvent) -> None:
self._fan_speed = event.speed
self.async_write_ha_state()
async def on_report_stats(event: ReportStatsEvent) -> None:
self.hass.bus.fire(EVENT_CLEANING_JOB, dataclass_to_dict(event))
async def on_rooms(event: RoomsEvent) -> None:
... | on_fan_speed | identifier_name |
lib.rs | (error::Jose::WrongKeyType {
expected: format!("{:?}", $expected),
actual: format!("{:?}", $actual),
}
.into())
};
}
impl Client {
/// Constructs a client from an issuer url and client parameters via discovery
pub fn discover(id: String, secret: String, redirect: Url... | if expected != actual { | random_line_split | |
lib.rs | wrong_key {
($expected:expr, $actual:expr) => {
Err(error::Jose::WrongKeyType {
expected: format!("{:?}", $expected),
actual: format!("{:?}", $actual),
}
.into())
};
}
impl Client {
/// Constructs a client from an issuer url and client parameters via discove... | (&self, token: &mut IdToken) -> Result<(), Error> {
// This is an early return if the token is already decoded
if let Compact::Decoded { .. } = *token {
return Ok(());
}
let header = token.unverified_header()?;
// If there is more than one key, the token MUST have a ... | decode_token | identifier_name |
lib.rs | _token(client, auth_code)
.map_err(Error::from)
}
/// A reference to the config document of the provider obtained via discovery
pub fn config(&self) -> &Config {
&self.oauth.provider.0
}
/// Constructs the auth_url to redirect a client to the provider. Options are... optional. ... | {
return Err(Validation::Expired(Expiry::Expires(
chrono::naive::NaiveDateTime::from_timestamp(claims.exp, 0),
))
.into());
} | conditional_block | |
machine.rs | {
// Store the error in self, then return a ref to it
self.error = Some(WithSource::new(
iter::once(SourceErrorWrapper::new(
error,
span,
&self.source,
)),
... | FailureReason | identifier_name | |
machine.rs | &mut self,
stack_ref: &SpanNode<StackRef>,
value: LangValue,
) -> Result<(), (RuntimeError, Span)> {
// Have to access this first cause borrow checker
let max_stack_length = self.hardware_spec.max_stack_length;
let stack = &mut self.stacks[stack_ref.value().0];
// I... | pub fn stacks(&self) -> HashMap<StackRef, &[LangValue]> {
self.hardware_spec
.all_stack_refs() | random_line_split | |
machine.rs | is
/// invalid (shouldn't be possible because of validation).
fn get_val_from_src(&self, src: &SpanNode<ValueSource<Span>>) -> LangValue {
match src.value() {
ValueSource::Const(Node(val, _)) => *val,
ValueSource::Register(reg_ref) => self.get_reg(*reg_ref.value()),
}
... |
/// Pops an element off the given stack. If the pop is successful, the
/// popped value is returned. If the stack is empty, an error is returned.
/// If the stack reference is invalid, will panic (should be validated at
/// build time).
fn pop_stack(
&mut self,
stack_ref: &SpanNode... | {
// Have to access this first cause borrow checker
let max_stack_length = self.hardware_spec.max_stack_length;
let stack = &mut self.stacks[stack_ref.value().0];
// If the stack is capacity, make sure we're not over it
if stack.len() >= max_stack_length {
return Err... | identifier_body |
machine.rs | is
/// invalid (shouldn't be possible because of validation).
fn get_val_from_src(&self, src: &SpanNode<ValueSource<Span>>) -> LangValue {
match src.value() {
ValueSource::Const(Node(val, _)) => *val,
ValueSource::Register(reg_ref) => self.get_reg(*reg_ref.value()),
}
... |
}
/// Internal function to execute the next instruction. The return value
/// is the same as [Self::execute_next], except the error needs to be
/// wrapped before being handed to the user.
fn execute_next_inner(&mut self) -> Result<bool, (RuntimeError, Span)> {
// We've previously hit an e... | {
Err((RuntimeError::EmptyStack, *stack_ref.metadata()))
} | conditional_block |
rgou.py | (event):
print("clicked at", event.x, event.y)
coords(event.x,event.y)
# coordss(event.x,event.y)
#frame = Frame(game, width=100, height=100)
#game.mainloop()
game = tk.Tk()
game.title("Royal Game of Ur")
## BG image
#fname = "RGOU.gif"
#fname = "RGOU2.gif"
fname = "RGOU4.gif"
bg_image = tk.PhotoImage... | callback | identifier_name | |
rgou.py | 89,80,257,152,[0,1]],
[189,170,257,231,[1,1]],
[189,239,257,315,[2,1]],
[189,325,257,394,[3,1]],
[189,403,257,478,[4,1]],
[189,489,257,560,[5,1]],
[189,578,257,635,[6,1]],
[189,650,257,719,[7,1]],
[270,80,338,152,[0,2]],
[270,170,338,231,[1,2]],
... |
# score()
def endmove(playagain = False): # True == one more move
global turn,rolled,moved
if turn == 0:
opponent = 2
else:
opponent = 0
if not playagain:
turn = opponent
rolled = False
moved = True
if playagain:
s = roll()
if s == 0:
... | a = tk.messagebox.askokcancel("popup","reset?")
if a:
def_cv_pieces(True)
setup() | identifier_body |
rgou.py | 189,80,257,152,[0,1]],
[189,170,257,231,[1,1]],
[189,239,257,315,[2,1]],
[189,325,257,394,[3,1]],
[189,403,257,478,[4,1]],
[189,489,257,560,[5,1]],
[189,578,257,635,[6,1]],
[189,650,257,719,[7,1]],
[270,80,338,152,[0,2]],
[270,170,338,231,[1,2]],
... | global cv
global whiterollicon,blackrollicon
whiterollicon = rollicon(0)
blackrollicon = rollicon(2)
if len(rollicons) == 3:
cv.delete(rollicons[0])
cv.delete(rollicons[2])
# w = rollicons[0]
# b = rollicons[2]
# cv[w]["image"] = whiterollicon
# cv[b]["ima... | global w ,b | random_line_split |
rgou.py | def def_cv_pieces(delete=False):
global whitepic , blackpic
global cv
global white_cv
global black_cv
global pieces_cv
if delete:
for i in white_cv:
cv.delete(i)
#
for i in black_cv:
cv.delete(i)
return
white_cv= []
black_cv = []
piece... | cv.itemconfig(scoretext[0],font="Times 30 italic bold",text=t) | conditional_block | |
lib.rs | typically starts each line with `///`.
//!
//! In both cases all image paths are relative to the **crate root**.
//!
//! ## Embedding images in outer attribute documentation
//!
//! Outer attribute documentation is typically used for documenting functions, structs, traits,
//! macros and so on. Let's consider document... | {
label: String,
path: PathBuf,
}
impl Parse for ImageDescription {
fn parse(input: ParseStream) -> parse::Result<Self> {
let label = input.parse::<syn::LitStr>()?;
input.parse::<syn::Token![,]>()?;
let path = input.parse::<syn::LitStr>()?;
Ok(ImageDescription {
... | ImageDescription | identifier_name |
lib.rs | //! around the current limitations of `rustdoc` and enables a practically workable approach to
//! embedding images in a portable manner.
//!
//! # How to embed images in documentation
//!
//! First, you'll need to depend on this crate. In `cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! // Replace x.x with the lat... | //!
//! This crate represents a carefully crafted solution based on procedural macros that works | random_line_split | |
orders-alter.js | _id":parseSegment[1]};
order.doPost(parseSegment[0],data,function(result){
order.reloadCallBack(result,obj);
});
}else if(obj.hasClass("alRefundDel") && confirm("确认删除订单吗?")){ // 实际上是隐藏订单组
order.doPost(parseSegment[0],data,function(result){
order.reloadCallBack(result,obj);
});
}else if(obj.hasClass("del... | }
order.createGroupLiHtml = function(nowGroup,buttonHtml){
var orderHtmls = "";
var imagesHtmls = "";
var disableHtmls = "";
for(q in nowGroup.orderGoodsImage.pics){
disableHtmls = "";
if(nowGroup.orderGoodsImage.pics[q].disable){
disableHtmls = '<i class="icon-failstate"></i>';
}
imagesHtmls += '<span ... | 'type':'post',
'dataType':'json',
success:func
}); | random_line_split |
rs_handler_user.go | .Userid = userid
rs.rolePid.Request(msg1, ctx.Self())
} else {
//TODO 添加房间数据返回
rsp := handler.GetUserDataMsg(arg, rs.User)
if rs.gamePid != nil {
rsp.Game = true
}
if rs.BankPhone != "" {
rsp.Bank = true
}
rs.Send(rsp)
}
case *pb.GotUserData:
arg := msg.(*pb.GotUserData)
glog.De... | OG_TYPE15))
//充值消息提醒
record1, msg1 := handler.GiveNotice(amount, rs.User.GetUserid(), userid)
if record1 != nil {
rs.loggerPid.Tell(record1)
}
rs.Send(msg1)
} else {
msg.Error = pb.GiveUseridError
}
}
case pb.BankSelect: //查询
msg.Phone = rs.User.BankPhone
case pb.BankOpen: //开通
... | Currency(0, -1*amount, 0, 0, int32(pb.L | conditional_block |
rs_handler_user.go | .Userid = userid
rs.rolePid.Request(msg1, ctx.Self())
} else {
//TODO 添加房间数据返回
rsp := handler.GetUserDataMsg(arg, rs.User)
if rs.gamePid != nil {
rsp.Game = true
}
if rs.BankPhone != "" {
rsp.Bank = true
}
rs.Send(rsp)
}
case *pb.GotUserData:
arg := msg.(*pb.GotUserData)
glog.De... | User.BankPhone == "" {
msg.Error = pb.BankNotOpen
} else if (coin - amount) < data.BANKRUPT {
msg.Error = pb.NotEnoughCoin
} else if amount <= 0 {
msg.Error = pb.DepositNumberError
} else {
rs.addCurrency(0, -1*amount, 0, 0, int32(pb.LOG_TYPE12))
rs.addBank(amount, int32(pb.LOG_TYPE12), "")
}
ca... | rs. | identifier_name |
rs_handler_user.go | rsp := handler.GetCurrency(arg, rs.User)
rs.Send(rsp)
case *pb.CBuy:
arg := msg.(*pb.CBuy)
glog.Debugf("CBuy %#v", arg)
//优化
rsp, diamond, coin := handler.Buy(arg, rs.User)
//同步兑换
rs.addCurrency(diamond, coin, 0, 0, int32(pb.LOG_TYPE18))
//响应
rs.Send(rsp)
record, msg2 := handler.BuyNotice(coin, r... | rs.joinActivity(arg, ctx)
case *pb.CGetCurrency:
arg := msg.(*pb.CGetCurrency)
glog.Debugf("CGetCurrency %#v", arg)
//响应 | random_line_split | |
rs_handler_user.go | id = userid
rs.rolePid.Request(msg1, ctx.Self())
} else {
//TODO 添加房间数据返回
rsp := handler.GetUserDataMsg(arg, rs.User)
if rs.gamePid != nil {
rsp.Game = true
}
if rs.BankPhone != "" {
rsp.Bank = true
}
rs.Send(rsp)
}
case *pb.GotUserData:
arg := msg.(*pb.GotUserData)
glog.Debugf(... | rs.addCurrency(0, amount, 0, 0, int32(pb.LOG_TYPE13))
rs.addBank(-1*amount, int32(pb.LOG_TYPE13), "")
}
case pb.BankGift: //赠送
if rs.User.BankPhone == "" {
msg.Error = pb.BankNotOpen
} else if arg.GetPassword() != rs.User.BankPassword {
msg.Error = pb.PwdError
//} else if amount > rs.User.GetBank(... | = "" {
msg.Error = pb.BankNotOpen
} else if (coin - amount) < data.BANKRUPT {
msg.Error = pb.NotEnoughCoin
} else if amount <= 0 {
msg.Error = pb.DepositNumberError
} else {
rs.addCurrency(0, -1*amount, 0, 0, int32(pb.LOG_TYPE12))
rs.addBank(amount, int32(pb.LOG_TYPE12), "")
}
case pb.BankDraw: ... | identifier_body |
ppo_trainer.py | po_cfg: config node with relevant params
Returns:
None
"""
logger.add_filehandler(self.config.LOG_FILE)
if observation_space is None:
observation_space = self.envs.observation_spaces[0]
self.actor_critic = AudioNavBaselinePolicy(
observation... |
METRICS_BLACKLIST = {"top_down_map", "collisions.is_collision"}
@classmethod
def _extract_scalars_from_info(
cls, info: Dict[str, Any]
) -> Dict[str, float]:
result = {}
for k, v in info.items():
if k in cls.METRICS_BLACKLIST:
continue
... | checkpoints = glob.glob(f"{self.config.CHECKPOINT_FOLDER}/*.pth")
if len(checkpoints) == 0:
count_steps = 0
count_checkpoints = 0
start_update = 0
else:
last_ckpt = sorted(checkpoints, key=lambda x: int(x.split(".")[1]))[-1]
checkpoint_path = l... | identifier_body |
ppo_trainer.py | _rgb=self.config.EXTRA_RGB
)
self.agent = PPO(
actor_critic=self.actor_critic,
clip_param=ppo_cfg.clip_param,
ppo_epoch=ppo_cfg.ppo_epoch,
num_mini_batch=ppo_cfg.num_mini_batch,
value_loss_coef=ppo_cfg.value_loss_coef,
entropy_coef... | random_line_split | ||
ppo_trainer.py | po_cfg: config node with relevant params
Returns:
None
"""
logger.add_filehandler(self.config.LOG_FILE)
if observation_space is None:
observation_space = self.envs.observation_spaces[0]
self.actor_critic = AudioNavBaselinePolicy(
observation... | (
cls, infos: List[Dict[str, Any]]
) -> Dict[str, List[float]]:
results = defaultdict(list)
for i in range(len(infos)):
for k, v in cls._extract_scalars_from_info(infos[i]).items():
results[k].append(v)
return results
def _collect_rollout_step(
... | _extract_scalars_from_infos | identifier_name |
ppo_trainer.py | have an np.size of 1, so explicitly ban those
elif np.size(v) == 1 and not isinstance(v, str):
result[k] = float(v)
return result
@classmethod
def _extract_scalars_from_infos(
cls, infos: List[Dict[str, Any]]
) -> Dict[str, List[float]]:
results = defa... | for metric, value in metrics.items():
writer.add_scalar(f"Metrics/{metric}", value, count_steps) | conditional_block | |
imaging-multibeam.py | go to scratch space on the node.
scratch = os.getenv("TMPDIR")
if __name__ == "__main__":
# Our single command line argument is a parset containing all
# configuration information we'll need.
input_parset = lofar.parameterset.parameterset(sys.argv[1])
# We require `sbs_per_beam` input MeasurementSets... |
# We source a special build for using the "new" awimager
awim_init = input_parset.getString("awimager.initscript")
# Calculate the threshold for cleaning based on the noise in a dirty map
# We don't use our threadpool here, since awimager is parallelized
noise_parset_name = get_parset_subset(input... | limit_baselines(target_info["output_ms"], target_info["bl_limit_ms"], maxbl)
with time_code("Limiting maximum baseline length"):
pool.map(limit_bl, ms_target.values()) | random_line_split |
imaging-multibeam.py | go to scratch space on the node.
scratch = os.getenv("TMPDIR")
if __name__ == "__main__":
# Our single command line argument is a parset containing all
# configuration information we'll need.
input_parset = lofar.parameterset.parameterset(sys.argv[1])
# We require `sbs_per_beam` input MeasurementSets... |
with time_code("Limiting maximum baseline length"):
pool.map(limit_bl, ms_target.values())
# We source a special build for using the "new" awimager
awim_init = input_parset.getString("awimager.initscript")
# Calculate the threshold for cleaning based on the noise in a dirty map
# We don't... | target_info["bl_limit_ms"] = mkdtemp(dir=scratch)
limit_baselines(target_info["output_ms"], target_info["bl_limit_ms"], maxbl) | identifier_body |
imaging-multibeam.py | go to scratch space on the node.
scratch = os.getenv("TMPDIR")
if __name__ == "__main__":
# Our single command line argument is a parset containing all
# configuration information we'll need.
input_parset = lofar.parameterset.parameterset(sys.argv[1])
# We require `sbs_per_beam` input MeasurementSets... | (target_info):
output = os.path.join(mkdtemp(dir=scratch), "combined.MS")
run_ndppp(
get_parset_subset(input_parset, "combine.parset", scratch),
{
"msin": str(target_info["datafiles"]),
"msout": output
}
)
target_info["c... | combine_ms | identifier_name |
imaging-multibeam.py | to scratch space on the node.
scratch = os.getenv("TMPDIR")
if __name__ == "__main__":
# Our single command line argument is a parset containing all
# configuration information we'll need.
input_parset = lofar.parameterset.parameterset(sys.argv[1])
# We require `sbs_per_beam` input MeasurementSets fo... |
except Exception, e:
print "Error in phaseonly with %s" % (target_info["combined_ms"])
print str(e)
raise
# Most Lisa nodes have 24 GB RAM -- we don't want to run out
calpool = ThreadPool(6)
with time_code("Phase-only calibration"):
calpool.map(phaseonly... | shutil.copy(logfile, target_info["output_dir"]) | conditional_block |
bressan_computerscience.py |
"""
loans_lenders = loans_lenders_import.explode('lenders').drop_duplicates()
loans_lenders.head(5)
"""####2. **For each loan, add a column duration corresponding to the number of days between the disburse time and the planned expiration time. If any of those two dates is missing, also the duration must be missing... | divide_value_by_period | identifier_name | |
bressan_computerscience.py | (loans_import['disburse_time'], format="%Y-%m-%d %H:%M:%S", errors="coerce")
loans_import['duration'] = loans_import['planned_expiration_time'] - loans_import['disburse_time']
loans_import.head(5)
"""####3. **Find the lenders that have funded at least twice.**"""
lender_foundings = loans_lenders.groupby('lenders')... | start_date = row['disburse_time'].tz_localize(None)
end_date = row['planned_expiration_time'].tz_localize(None)
value = row['loan_amount']
# calculating the difference in years considewring leap years
jumps = end_date.year - start_date.year
if jumps != 0:
dayss = []
starting_year = start_date.year
... | identifier_body | |
bressan_computerscience.py | .csv'
loans_import = pd.read_csv(loans_url)
loans_import.dtypes
loans_import.head(2)
lenders_url = '/content/drive/My Drive/additional-kiva-snapshot/lenders.csv'
lenders_import = pd.read_csv(lenders_url)
lenders_import.dtypes
lenders_import.head(5)
country_stats_url = '/content/drive/My Drive/additional-kiva-snapsh... |
"""Then, I join obtained dataset with the _loans_ dataset by loan ID"""
lender_loan_country_full = pd.merge(
lender_loan_country.drop_duplicates(),
loans_import[['loan_id','loan_amount','country_code']],
left_on= ['loan_id'],
... |
lender_loan_country = lender_loan_country[['loan_id', 'lender_country']]
lender_loan_country.head(5) | random_line_split |
bressan_computerscience.py | """
lender_foundings = loans_lenders.groupby('lenders').size().reset_index(name='foundings')
lender_foundings[lender_foundings['foundings'] > 2]
"""####4. **For each country, compute how many loans have involved that country as borrowers.**"""
country_loans = loans_import.groupby('country_code').size().reset_index... | dayss = []
starting_year = start_date.year
for i in range(jumps):
next_year = starting_year + 1
next_year_comp = datetime(next_year, 1, 1)
# get the difference in days
diff = (next_year_comp - start_date).days
dayss.append(diff)
# re-assigning start and end dates
... | conditional_block | |
titanic-alpha-attempt.py | Ages < 1 indicate age in months.
#
#
# [1]: http://www.mymarketresearchmethods.com/types-of-data-nominal-ordinal-interval-ratio/
# In[ ]:
# count the number of passengers for first 25 ages
train_df.groupby('Age').size().head(25)
# another way to do the above
#train_df['Age'].value_counts().sort_index().head(25... | (dataset, age_groups):
for sex in ['male','female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages
tmp['AgeGroup'] = age_groups[sex] # index age group values
dataset = dataset.combine_first(tmp) # uses tmp to fill holes
return dat... | insert_age_group_values | identifier_name |
titanic-alpha-attempt.py | Ages < 1 indicate age in months.
#
#
# [1]: http://www.mymarketresearchmethods.com/types-of-data-nominal-ordinal-interval-ratio/
# In[ ]:
# count the number of passengers for first 25 ages
train_df.groupby('Age').size().head(25)
# another way to do the above
#train_df['Age'].value_counts().sort_index().head(25... |
# number of males and females by age group
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
# randomly generate a list of age groups based on age group frequency (for each sex separately)
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male','female']:
... | na_males = dataset[dataset.Sex == 'male'].loc[:,'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:,'AgeGroup'].isnull().sum()
return {'male': na_males, 'female': na_females} | identifier_body |
titanic-alpha-attempt.py | Cabin might be conceivably be related to survival, but unfortunately most values are missing. Nevertheless, by way of an exercise, we will extract the feature, Deck, from cabin by taking the first character of the label and analyze survival rates by deck.
# In[ ]:
# deck is the first letter of cabin
train_df['Deck'... | # The methods marked * either discover linear classification boundaries (logistic regression, perceptron, and SVMs if using linear kernels) or assume no relationship between features (naive bayes) and thus are not expected to perform as well (see the section above on the relationship between survival, age group and sex... | random_line_split | |
titanic-alpha-attempt.py | Ages < 1 indicate age in months.
#
#
# [1]: http://www.mymarketresearchmethods.com/types-of-data-nominal-ordinal-interval-ratio/
# In[ ]:
# count the number of passengers for first 25 ages
train_df.groupby('Age').size().head(25)
# another way to do the above
#train_df['Age'].value_counts().sort_index().head(25... |
return age_groups
# insert the new age group values
def insert_age_group_values(dataset, age_groups):
for sex in ['male','female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages
tmp['AgeGroup'] = age_groups[sex] # index age group va... | relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex], replace=True, p=relfreq) | conditional_block |
contacts-details.component.ts | .log('run contacts')
this.searchKin(this.user);
}
}
doctorChangeEvent(data: any){
var doc = this.doctors.filter(x => x.name == data).shift();
if(!doc){
this.inputForm.patchValue({
address1: '',
address2: '',
phone1: '',
phone2:'',
email: '',
... | this.globalS.sToast('Success', 'Contact Deleted');
this.searchKin(this.user);
});
} | random_line_split | |
contacts-details.component.ts | => {
};
@Component({
selector: 'app-contacts-details',
templateUrl: './contacts-details.component.html',
styleUrls: ['./contacts-details.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => ContactsDetailsComponent),
}
],
changeDe... |
buildForm(): void {
this.kindetailsGroup = this.formBuilder.group({
listOrder: [''],
type: [''],
name: [''],
email: [''],
address1: [''],
address2: [''],
suburbcode: [''],
suburb: [''],
postcode: [''],
phone1: [''],
phone2: [''],
mobile: ['... | {
this.listS.getdoctorinformation().subscribe(data => {
console.log(data);
this.doctors = data;
})
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.