file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ExportGltf.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... | {
public readonly translation?: number[];
public readonly rotation?: number[];
public readonly scale?: number[];
constructor(xform?: Float64Array) {
if (xform === undefined) return;
if (!almostEqual(0, xform[3], xform[7], xform[11]))
this.translation = [xform[3], xform[11], -xform[7]]; // ... | TranslationRotationScale | identifier_name |
ExportGltf.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... |
function findOrAddMaterialIndexForColor(color: number): number {
let result = GltfGlobals.colorToMaterialMap.get(color);
if (result !== undefined) return result;
const rgb = ColorDef.getColors(color);
const pbrMetallicRoughness: GltfMaterialPbrMetallicRoughness = {
baseColorFactor: [rgb.r / 255, ... | {
let result = GltfGlobals.textureToMaterialMap.get(textureId);
if (result !== undefined) return result;
// glTF-Validator complains if textures/images are defined but empty - wait for texture to define.
if (GltfGlobals.gltf.textures === undefined) {
GltfGlobals.gltf.textures = [];
GltfGlobals.g... | identifier_body |
ExportGltf.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... | findOrAddMaterialIndexForColor(color);
const primitive: GltfMeshPrimitive = {
mode: MeshPrimitiveMode.GlTriangles,
material,
indices: GltfGlobals.gltf.accessors.length,
attributes: {
// eslint-disable-next-line @typescript-eslint/naming-convention
POSITION: GltfGlobals.gltf.ac... | function addMesh(mesh: ExportGraphicsMesh, color: number, textureId?: Id64String) {
const material = textureId !== undefined ? findOrAddMaterialIndexForTexture(textureId) :
| random_line_split |
v2.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'prof_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4 | from PyQt4.QtGui import *
from PyQt4.QtCore import *
import txt2csv as t2csv
import glob, os, re
from measurements import perform_filter
OWNER = 'rn'
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def... | #
# WARNING! All changes made in this file will be lost!
import os, sys
from PyQt4 import QtCore, QtGui | random_line_split |
v2.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'prof_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import os, sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import txt2csv as t2c... | (self, profileDialog):
profileDialog.setWindowTitle(_translate("profileDialog", "Dialog", None))
self.profilebtn1.setText(_translate("profileDialog", "profile", None))
self.label.setText(_translate("profileDialog", "Host Name", None))
self.statusLabel.setText(_translate("profileDialog", ... | retranslateUi | identifier_name |
v2.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'prof_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import os, sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import txt2csv as t2c... |
def retranslateUi(self, profileDialog):
profileDialog.setWindowTitle(_translate("profileDialog", "Dialog", None))
self.profilebtn1.setText(_translate("profileDialog", "profile", None))
self.label.setText(_translate("profileDialog", "Host Name", None))
self.statusLabel.setText(_tran... | profileDialog.setObjectName(_fromUtf8("profileDialog"))
profileDialog.resize(492, 428)
profileDialog.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
profileDialog.setAutoFillBackground(True)
self.buttonBox = QtGui.QDialogButtonBox(profileDialog)
self.buttonBox.setGeometry(QtCo... | identifier_body |
v2.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'prof_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import os, sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import txt2csv as t2c... |
elif txt == 4 or txt == 99:
return "99;99"
def msgbtn(self):
self.pushButton_2.setEnabled(True)
txt_index = self.cmbUsage.currentIndex()
txt = self.assign_details(txt_index)
host = self.hostText.toPlainText()
usage = txt.split(';')[0]
task_cycle ... | return "70;20" | conditional_block |
forminput.js | var definitions = function() {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
success: function(data) {
document.getElementById("definitions").innerHTML = data;
}
});
}
//when loading the website validate rangeout of slider and appearance of checkbox
$(docu... |
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
var mouseover_node = function(z) {
var neighbors = {};
neighbors[z.index] = true;
link.filter(function(d) {
if (d.source == z) {
... | {
d.fx = d3.event.x;
d.fy = d3.event.y;
} | identifier_body |
forminput.js | var definitions = function() {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
success: function(data) {
document.getElementById("definitions").innerHTML = data;
}
});
}
//when loading the website validate rangeout of slider and appearance of checkbox
$(docu... | () {
var g = d3.selectAll(".container");
g.attr("transform", d3.event.transform);
}
function ticked() {
link.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);... | zoomed | identifier_name |
forminput.js | var definitions = function() {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
success: function(data) {
document.getElementById("definitions").innerHTML = data;
}
});
}
//when loading the website validate rangeout of slider and appearance of checkbox
$(docu... | else if (d == "cd") {
return "cardinal digit"
} else return d
});
function zoomed() {
var g = d3.selectAll(".container");
g.attr("transform", d3.event.transform);
}
function ticked() {
link.attr("d", function(d) {
var dx = d.tar... | {
return "preposition/subordinating conjunction"
} | conditional_block |
forminput.js | var definitions = function() {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
success: function(data) {
document.getElementById("definitions").innerHTML = data;
}
});
}
//when loading the website validate rangeout of slider and appearance of checkbox
$(docu... | .attr('x', (d) => x(d.quantity + 0.2))
.attr('text-anchor', 'start')
.text((d) => d.quantity);
//labels
svg.append('text')
.attr('class', 'title')
.attr('x', -margin.left + 20)
.attr('y', -margin.top + 20)
.attr('text-anchor', 'start')
.text('Numbe... | random_line_split | |
supervisor_processor.go | // Copyright 2020 The Monogon Project Authors.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2... |
// Simple case: the context was canceled and the returned error is the context error.
if err := ctx.Err(); err != nil && perr == err {
// Mark the node as canceled successfully.
n.state = nodeStateCanceled
return
}
// Otherwise, the Runnable should not have died or quit. Handle accordingly.
err := r.err
... | {
if inner := errors.Unwrap(perr); inner != nil {
perr = inner
continue
}
break
} | conditional_block |
supervisor_processor.go | // Copyright 2020 The Monogon Project Authors.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2... | () {
s.mu.Lock()
defer s.mu.Unlock()
// Gather all context cancel functions.
var cancels []func()
queue := []*node{s.root}
for {
if len(queue) == 0 {
break
}
cur := queue[0]
queue = queue[1:]
cancels = append(cancels, cur.ctxC)
for _, c := range cur.children {
queue = append(queue, c)
}
}
... | processKill | identifier_name |
supervisor_processor.go | // Copyright 2020 The Monogon Project Authors.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2... | n := s.nodeByDN(r.dn)
ctx := n.ctx
// Simple case: it was marked as Done and quit with no error.
if n.state == nodeStateDone && r.err == nil {
// Do nothing. This was supposed to happen. Keep the process as DONE.
return
}
// Find innermost error to check if it's a context canceled error.
perr := r.err
for... | // Okay, so a Runnable has quit. What now? | random_line_split |
supervisor_processor.go | // Copyright 2020 The Monogon Project Authors.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2... |
// processKill cancels all nodes in the supervision tree. This is only called right before exiting the processor, so
// they do not get automatically restarted.
func (s *supervisor) processKill() {
s.mu.Lock()
defer s.mu.Unlock()
// Gather all context cancel functions.
var cancels []func()
queue := []*node{s.ro... | {
s.ilogger.Info("supervisor processor started")
// Waiters waiting for the GC to be settled.
var waiters []chan struct{}
// The GC will run every millisecond if needed. Any time the processor requests a change in the supervision tree
// (ie a death or a new runnable) it will mark the state as dirty and run the ... | identifier_body |
ipc.rs | //! IPC Transport for *nix
#[cfg(unix)]
extern crate tokio_uds;
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::Path;
use std::sync::{atomic, Arc};
#[cfg(unix)]
use self::tokio_uds::UnixStream;
use crate::api::SubscriptionId;
use crate::helpers;
use crate::rpc;
use crate::transports... | <T>(&self, requests: T) -> Self::Batch
where
T: IntoIterator<Item = (RequestId, rpc::Call)>,
{
let mut it = requests.into_iter();
let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None));
let requests = first.into_iter().chain(it.map(|x| x.1)).collect();... | send_batch | identifier_name |
ipc.rs | //! IPC Transport for *nix
#[cfg(unix)]
extern crate tokio_uds;
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::Path;
use std::sync::{atomic, Arc};
#[cfg(unix)]
use self::tokio_uds::UnixStream;
use crate::api::SubscriptionId;
use crate::helpers;
use crate::rpc;
use crate::transports... | else {
log::warn!("Got unsupported response (id: {:?})", id);
}
}
Message::Notification(notification) => {
if let rpc::Params::Map(params) = notification.params {
let id = params.get("subscription");
let... | {
if let Some(request) = self.pending.lock().remove(&(num as usize)) {
log::trace!("Responding to (id: {:?}) with {:?}", num, outputs);
if let Err(err) = request.send(helpers::to_results_from_outputs(outputs)) {
log::warn!("... | conditional_block |
ipc.rs | //! IPC Transport for *nix
#[cfg(unix)]
extern crate tokio_uds;
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::Path;
use std::sync::{atomic, Arc};
#[cfg(unix)]
use self::tokio_uds::UnixStream;
use crate::api::SubscriptionId;
use crate::helpers;
use crate::rpc;
use crate::transports... |
fn unsubscribe(&self, id: &SubscriptionId) {
self.subscriptions.lock().remove(id);
}
}
enum WriteState {
WaitingForRequest,
Writing { buffer: Vec<u8>, current_pos: usize },
}
/// Writing part of the IPC transport
/// Awaits new requests using `mpsc::UnboundedReceiver` and writes them to the ... | {
let (tx, rx) = mpsc::unbounded();
if self.subscriptions.lock().insert(id.clone(), tx).is_some() {
log::warn!("Replacing already-registered subscription with id {:?}", id)
}
Box::new(rx.map_err(|()| Error::Transport("No data available".into())))
} | identifier_body |
ipc.rs | //! IPC Transport for *nix
#[cfg(unix)]
extern crate tokio_uds;
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::Path;
use std::sync::{atomic, Arc};
#[cfg(unix)]
use self::tokio_uds::UnixStream;
use crate::api::SubscriptionId;
use crate::helpers;
use crate::rpc;
use crate::transports... | let requests = first.into_iter().chain(it.map(|x| x.1)).collect();
self.send_request(id, rpc::Request::Batch(requests), Ok)
}
}
impl DuplexTransport for Ipc {
type NotificationStream = Box<dyn Stream<Item = rpc::Value, Error = Error> + Send + 'static>;
fn subscribe(&self, id: &Subscription... | where
T: IntoIterator<Item = (RequestId, rpc::Call)>,
{
let mut it = requests.into_iter();
let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None)); | random_line_split |
map.js | BMap.register(function (cK) {
if (cK.config && cK.config.isOverviewMap) {
return
}
if (cK.isLoaded()) {
bj(cK)
} else {
cK.addEventListener("load", function () {
bj(this)
})
}
cK.cityName = "\u4e2d\u56fd";
var T = {};
T.enableReque... |
cN = cN || {};
this.dispatchEvent(new bf("onmovestart"));
var cM = this,
cL = cM.temp;
cL.pl = cM.offsetX;
cL.pt = cM.offsetY;
if (cL.tlPan) {
cL.tlPan.cancel()
}
if (cL.dragAni) {
cL.dragAni.stop()
... | {
return
} | conditional_block |
map.js | BMap.register(function (cK) {
if (cK.config && cK.config.isOverviewMap) {
return
}
if (cK.isLoaded()) {
bj(cK)
} else {
cK.addEventListener("load", function () {
bj(this)
})
}
cK.cityName = "\u4e2d\u56fd";
var T = {};
T.enableReque... |
function aY(T) {
var cQ = "11px",
cP = T.cityName || "\u4e2d\u56fd",
cM = T.getMapType(),
cR = ["\u5e38\u5dde\u5e02", "\u6210\u90fd\u5e02", "\u5927\u8fde\u5e02", "\u91cd\u5e86\u5e02", "\u5357\u4eac\u5e02", "\u5357\u660c\u5e02", "\u6b66\u6c49\u5e02"],
cL = [],
cO, cN =... | {
if (cK.temp.copyadded) {
return
}
cK.temp.copyadded = true;
var cM = new aG(81, 2);
if (az()) {
if (cK.highResolutionEnabled()) {
cM.width = 148;
fontSize = "21px"
} else {
cM.width = 72;
cM.height = 0
}
... | identifier_body |
map.js | BMap.register(function (cK) {
if (cK.config && cK.config.isOverviewMap) {
return
}
if (cK.isLoaded()) {
bj(cK)
} else {
cK.addEventListener("load", function () {
bj(this)
})
}
cK.cityName = "\u4e2d\u56fd";
var T = {};
T.enableReque... | (T) {
this.defaultAnchor = BMAP_ANCHOR_BOTTOM_LEFT;
this.defaultOffset = new aG(1, 0);
this.IMG_URL = cb.imgPath + (az() ? "copyright_logo_s.png" : "copyright_logo.png")
}
b0.prototype = new co();
b0.prototype.initialize = function (cK) {
this._map = cK;
var cL = Z("div");
cL.style.heig... | b0 | identifier_name |
map.js | BMap.register(function (cK) {
if (cK.config && cK.config.isOverviewMap) {
return
}
if (cK.isLoaded()) {
bj(cK)
} else {
cK.addEventListener("load", function () {
bj(this)
})
}
cK.cityName = "\u4e2d\u56fd";
var T = {};
T.enableReque... | var cN = Math.round(this.height / 2);
cM = cM || {};
if (Math.abs(T - cL.x) > this.width || Math.abs(cN - cL.y) > this.height || cM.noAnimation) {
this._panTo(T - cL.x, cN - cL.y, cK)
} else {
this._panBy(T - cL.x, cN - cL.y, {
duration: cM.d... | var T = Math.round(this.width / 2);
| random_line_split |
GroupINN.py | from . import tf, arguments, argparse
from functools import reduce
class gcn_classification_net:
class loss_weights:
cross_entropy = 1.0
neg_penalty_reduce = 0.1
neg_penalty_gnn = 0.2
ortho_penalty_p = 0.2
ortho_penalty_n = 0.2
variance_penalty_p = 0.3
varian... |
# Define accuracy metric
eval_metric_ops = {
"metrics/accuracy": tf.metrics.accuracy(
labels=labels, predictions=predictions["classes"]),
"confusion_matrix/TP": tf.metrics.true_positives(
labels=labels, predictions=predictions["classes"]),
... | tf.summary.scalar(loss_scalar.name, loss_scalar, family="loss") | conditional_block |
GroupINN.py | from . import tf, arguments, argparse
from functools import reduce
class gcn_classification_net:
class | :
cross_entropy = 1.0
neg_penalty_reduce = 0.1
neg_penalty_gnn = 0.2
ortho_penalty_p = 0.2
ortho_penalty_n = 0.2
variance_penalty_p = 0.3
variance_penalty_n = 0.5
l2_penalty = 2e-3
@classmethod
def update_parser_argument(cls, parser: argparse.Argu... | loss_weights | identifier_name |
GroupINN.py | from . import tf, arguments, argparse
from functools import reduce
class gcn_classification_net:
class loss_weights:
cross_entropy = 1.0
neg_penalty_reduce = 0.1
neg_penalty_gnn = 0.2
ortho_penalty_p = 0.2
ortho_penalty_n = 0.2
variance_penalty_p = 0.3
varian... |
def model_fn(self, features, labels,
mode:tf.estimator.ModeKeys, params):
"""
features: batch_features from input_fn
labels: batch_labels from input_fn
mode: An instance of tf.estimator.ModeKeys
params: Additional configuration
"""
self.runtime_init(... | self.losses = []
self.is_training = (mode==tf.estimator.ModeKeys.TRAIN) | identifier_body |
GroupINN.py | from . import tf, arguments, argparse
from functools import reduce
class gcn_classification_net:
class loss_weights:
cross_entropy = 1.0
neg_penalty_reduce = 0.1
neg_penalty_gnn = 0.2
ortho_penalty_p = 0.2
ortho_penalty_n = 0.2
variance_penalty_p = 0.3
varian... | "metrics/precision": tf.metrics.precision(
labels=labels, predictions=predictions["classes"]),
"metrics/recall": tf.metrics.recall(
labels=labels, predictions=predictions["classes"])
}
if mode == tf.estimator.ModeKeys.TRAIN:
optimiz... | labels=labels, predictions=predictions["classes"]),
"confusion_matrix/FP": tf.metrics.false_positives(
labels=labels, predictions=predictions["classes"]),
"confusion_matrix/FN": tf.metrics.false_negatives(
labels=labels, predictions=predictions["cl... | random_line_split |
plot_TL_results.py | import numpy as np
import pandas as pd
import json
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, wilcoxon, mannwhitneyu
import scipy.stats as ss
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def lo... | (b_times, r_times, N = None, alpha = 0.1, method = mannwhitneyu):
"""
do wilxocon test to see if b_times - r_times median is less than 0
H0: it is
"""
if N is None:
N = min([len(b_times), len(r_times)])*5
b = np.random.choice(b_times, size = N, replace = True)
r = np.random.choice(r_... | indicator_loss | identifier_name |
plot_TL_results.py | import numpy as np
import pandas as pd
import json
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, wilcoxon, mannwhitneyu
import scipy.stats as ss
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def lo... |
axs[0,0].set_ylabel('BO iterations to GMP convergence', fontsize = SMALL_SIZE)
axs[1,0].set_ylabel('CPU time to GMP convergence', fontsize = SMALL_SIZE)
axs[1,0].set_ylim(-0.05*cputime_max,1.4*cputime_max)
for ax in axs[1,:]:
ax.set_xlabel('secondary initpts', fontsize = SMALL_SIZE)
for... | experiment = experiment_folders[i].copy()
baseline = baseline_folders[i].copy()
explist = baseline
for exp in experiment:
explist.append(exp)
convergence_iterations = []
convergence_times = []
for exp in explist:
if len(exp['initpts'])>1:
... | conditional_block |
plot_TL_results.py | import numpy as np
import pandas as pd
import json
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, wilcoxon, mannwhitneyu
import scipy.stats as ss
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def lo... |
## compare each number of secondary initpts
## to baseline with wilcoxon 2 sample signed rank test to see
## when TL is faster than the baseline, also collect the lowest,
## highest, median and mean expected improvement and their secondary initpts
def indicator_loss(b_times, r_times, N = None, alpha = 0.1, method ... | """
Return true, if A>=B
where >= is loewner order (matrix comparison)
if A>=B, A spans over B
used to detect poor fits of coregionalization
if [coregionalization matrix] > [measured covariance]is broken,
covariance matrix is overestimated / fitted poorly
"""
ret_list = []
for b in... | identifier_body |
plot_TL_results.py | import numpy as np
import pandas as pd
import json
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, wilcoxon, mannwhitneyu
import scipy.stats as ss
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def lo... | polyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression())
polyreg.fit(x_train,y_train)
x = np.unique(convergence_iterations[:,0]).reshape(-1,1)
axs[0,i].set_xticks(x[::2])
y = polyreg.predict(x)
axs[1, i].plot(x,y, color = 'red', label = 'trend', linewidth = 3... | cputime_max = max(clean_rows[:,1])
x_train = clean_rows[:,0].reshape(-1,1)
y_train = clean_rows[:,1].reshape(-1,1)
degree=1 | random_line_split |
mod.rs | pub use self::cdtime::{nanos_to_collectd, CdTime};
pub use self::logger::{collectd_log, log_err, CollectdLoggerBuilder, LogLevel};
pub use self::oconfig::{ConfigItem, ConfigValue};
use crate::bindings::{
data_set_t, meta_data_add_boolean, meta_data_add_double, meta_data_add_signed_int,
meta_data_add_string, met... | let mut name: [c_char; ARR_LENGTH] = [0; ARR_LENGTH];
name[0] = b'h' as c_char;
name[1] = b'i' as c_char;
let val = data_source_t {
name,
type_: DS_TYPE_GAUGE as i32,
min: 10.0,
max: 11.0,
};
let mut v = vec![val];
... | random_line_split | |
mod.rs | pub use self::cdtime::{nanos_to_collectd, CdTime};
pub use self::logger::{collectd_log, log_err, CollectdLoggerBuilder, LogLevel};
pub use self::oconfig::{ConfigItem, ConfigValue};
use crate::bindings::{
data_set_t, meta_data_add_boolean, meta_data_add_double, meta_data_add_signed_int,
meta_data_add_string, met... |
/// The interval in which new values are to be expected. This is typically handled at a global
/// or plugin level. Use at your own discretion.
pub fn interval(mut self, interval: Duration) -> ValueListBuilder<'a> {
self.list.interval = Some(interval);
self
}
/// Add a metadata en... | {
self.list.time = Some(dt);
self
} | identifier_body |
mod.rs | pub use self::cdtime::{nanos_to_collectd, CdTime};
pub use self::logger::{collectd_log, log_err, CollectdLoggerBuilder, LogLevel};
pub use self::oconfig::{ConfigItem, ConfigValue};
use crate::bindings::{
data_set_t, meta_data_add_boolean, meta_data_add_double, meta_data_add_signed_int,
meta_data_add_string, met... | <'a> {
/// Name of the metric. If values has a length of 1, this is often just "value"
pub name: &'a str,
/// The value reported
pub value: Value,
/// Minimum value seen in an interval
pub min: f64,
/// Maximum value seen in an interval
pub max: f64,
}
/// Contains values and metadat... | ValueReport | identifier_name |
input.ts | import { get } from "svelte/store";
import { type DialogState } from "@graphite/state-providers/dialog";
import { type DocumentState } from "@graphite/state-providers/document";
import { type FullscreenState } from "@graphite/state-providers/fullscreen";
import { type PortfolioState } from "@graphite/state-providers/p... |
}
function onContextMenu(e: MouseEvent): void {
if (!targetIsTextField(e.target || undefined) && e.target !== textToolInteractiveInputElement) {
e.preventDefault();
}
}
// Receives a custom event dispatched when the user begins interactively editing with the text tool.
// We keep a copy of the text input... | {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.instance.onWheelScroll(e.clientX, e.clientY, e.buttons, e.deltaX, e.deltaY, e.deltaZ, modifiers);
} | conditional_block |
input.ts | import { get } from "svelte/store";
import { type DialogState } from "@graphite/state-providers/dialog";
import { type DocumentState } from "@graphite/state-providers/document";
import { type FullscreenState } from "@graphite/state-providers/fullscreen";
import { type PortfolioState } from "@graphite/state-providers/p... |
// Pointer events
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events and these are handled in the backend
function onPointerMove(e: PointerEvent): void {
if (!e.buttons) viewportPointerInteractionOngoing = false;
// Don't red... | {
const key = await getLocalizedScanCode(e);
if (await shouldRedirectKeyboardEventToBackend(e)) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.instance.onKeyUp(key, modifiers, e.repeat);
}
} | identifier_body |
input.ts | import { get } from "svelte/store";
import { type DialogState } from "@graphite/state-providers/dialog";
import { type DocumentState } from "@graphite/state-providers/document";
import { type FullscreenState } from "@graphite/state-providers/fullscreen";
import { type PortfolioState } from "@graphite/state-providers/p... | editor.instance.pasteSerializedData(text.substring(16, text.length));
} else if (text.startsWith("graphite/nodes: ")) {
editor.instance.pasteSerializedNodes(text.substring(16, text.length));
}
});
}
const file = item.getAsFile();
if (file?.type.startsWith("image")) {
extractPixel... | item.getAsString((text) => {
if (text.startsWith("graphite/layer: ")) { | random_line_split |
input.ts | import { get } from "svelte/store";
import { type DialogState } from "@graphite/state-providers/dialog";
import { type DocumentState } from "@graphite/state-providers/document";
import { type FullscreenState } from "@graphite/state-providers/fullscreen";
import { type PortfolioState } from "@graphite/state-providers/p... | (e: PointerEvent): void {
if (!e.buttons) viewportPointerInteractionOngoing = false;
// Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas
// TODO: A better approach is to pass along a boolean to the backend's... | onPointerMove | identifier_name |
main.rs | // bin2src - convert a binary file to source code in various languages
//
// Copyright (C) 2020 Alexandre Gomiero de Oliveira
//
// MIT License
//
// Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and assoc... |
}
pub fn generate(&mut self) -> Result<(), &'static str> {
// Test for input file
let (ifname, ifpath, ifsize) = self.input_file_test()?;
// Test for output dir
let ofpath: PathBuf = self.output_dir_test()?;
let go = GeneratorOutput {
... | {
Ok(ofpath)
} | conditional_block |
main.rs | // bin2src - convert a binary file to source code in various languages
//
// Copyright (C) 2020 Alexandre Gomiero de Oliveira
//
// MIT License
//
// Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and assoc... | {
pub input_file: String,
pub output_file: String,
pub output_dir: String,
pub lang: Lang,
pub hex: bool,
}
impl GeneratorInput {
fn input_file_test(&mut self) -> Result<(String, PathBuf, u64), &'static str> {
let ifpath: PathBuf = PathBuf::from(&sel... | GeneratorInput | identifier_name |
main.rs | // bin2src - convert a binary file to source code in various languages
//
// Copyright (C) 2020 Alexandre Gomiero de Oliveira
//
// MIT License
//
// Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and assoc... | _ => "",
};
}
fn get_args_as_strings() -> Result<Vec<String>, &'static str> {
let mut ret: Vec<String> = Vec::new();
let args = env::args_os();
for cmd in args {
ret.push(match cmd.into_string() {
Ok(c) => c,
_ => return Err("Invalid unicode character found"),
... |
match parse_result.generate() {
Err(e) => panic!("Generator error: {}", e), | random_line_split |
production_example.py | # -*- coding: utf-8 -*-
"""
Recommended installs: pip install pytrends fredapi yfinance
Uses a number of live public data sources to construct an example production case.
While stock price forecasting is shown here, time series forecasting alone is not a recommended basis for managing investments!
This is a highly op... | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt # required only for graphs
from autots import AutoTS, load_live_daily, create_regressor
fred_key = None # https://fred.stlouisfed.org/docs/api/api_key.html
gsa_key = None
forecast_name = "example"
graph = True # whether to plot graphs... | patch_sklearn()
except Exception as e:
print(repr(e))
import json
import datetime | random_line_split |
production_example.py | # -*- coding: utf-8 -*-
"""
Recommended installs: pip install pytrends fredapi yfinance
Uses a number of live public data sources to construct an example production case.
While stock price forecasting is shown here, time series forecasting alone is not a recommended basis for managing investments!
This is a highly op... |
print(f"Completed at system time: {datetime.datetime.now()}")
| plt.subplots_adjust(bottom=0.5)
model.plot_horizontal_transformers()
plt.show()
model.plot_horizontal_model_count()
plt.show()
model.plot_horizontal()
plt.show()
# plt.savefig("horizontal.png", dpi=300, bbox_inches="tight")
... | conditional_block |
ip6.go | // Copyright 2012 Google, Inc. All rights reserved.
// Copyright 2009-2011 Andreas Krennmair. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers
import (
"encoding/binary"
"fmt"
"github.com... | }
bytes[0] = (ip6.Version << 4) | (ip6.TrafficClass >> 4)
bytes[1] = (ip6.TrafficClass << 4) | uint8(ip6.FlowLabel>>16)
binary.BigEndian.PutUint16(bytes[2:], uint16(ip6.FlowLabel))
if opts.FixLengths {
ip6.Length = uint16(len(payload))
}
binary.BigEndian.PutUint16(bytes[4:], ip6.Length)
bytes[6] = byte(ip6.Ne... | if err != nil {
return err | random_line_split |
ip6.go | // Copyright 2012 Google, Inc. All rights reserved.
// Copyright 2009-2011 Andreas Krennmair. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers
import (
"encoding/binary"
"fmt"
"github.com... |
}
if ip6.Length == 0 {
return fmt.Errorf("IPv6 length 0, but next header is %v, not HopByHop", ip6.NextHeader)
} else {
pEnd := int(ip6.Length)
if pEnd > len(ip6.Payload) {
df.SetTruncated()
pEnd = len(ip6.Payload)
}
ip6.Payload = ip6.Payload[:pEnd]
}
return nil
}
func (i *IPv6) CanDecode() gopac... | {
for _, o := range ip6.hbh.Options {
if o.OptionType == IPv6HopByHopOptionJumbogram {
if len(o.OptionData) != 4 {
return fmt.Errorf("Invalid jumbo packet option length")
}
payloadLength := binary.BigEndian.Uint32(o.OptionData)
pEnd := int(payloadLength)
if pEnd > len(ip6.Payload) ... | conditional_block |
ip6.go | // Copyright 2012 Google, Inc. All rights reserved.
// Copyright 2009-2011 Andreas Krennmair. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers
import (
"encoding/binary"
"fmt"
"github.com... |
func decodeIPv6HopByHop(data []byte, p gopacket.PacketBuilder) error {
i := &IPv6HopByHop{}
err := i.DecodeFromBytes(data, p)
p.AddLayer(i)
if err != nil {
return err
}
return p.NextDecoder(i.NextHeader)
}
type ipv6HeaderTLVOption struct {
OptionType, OptionLength uint8
ActualLength int
Option... | {
i.ipv6ExtensionBase = decodeIPv6ExtensionBase(data)
i.Options = i.opts[:0]
var opt *IPv6HopByHopOption
for d := i.Contents[2:]; len(d) > 0; d = d[opt.ActualLength:] {
i.Options = append(i.Options, IPv6HopByHopOption(decodeIPv6HeaderTLVOption(d)))
opt = &i.Options[len(i.Options)-1]
}
return nil
} | identifier_body |
ip6.go | // Copyright 2012 Google, Inc. All rights reserved.
// Copyright 2009-2011 Andreas Krennmair. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers
import (
"encoding/binary"
"fmt"
"github.com... | (b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
payload := b.Bytes()
if ip6.HopByHop != nil {
return fmt.Errorf("unable to serialize hopbyhop for now")
}
bytes, err := b.PrependBytes(40)
if err != nil {
return err
}
bytes[0] = (ip6.Version << 4) | (ip6.TrafficClass >> 4)
bytes[1] = (ip6... | SerializeTo | identifier_name |
pod.go | // Copyright 2019 The Kanister Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (ctx context.Context, cli kubernetes.Interface, namespace, name string) error {
attachLog := true
containerForLogs := ""
err := poll.Wait(ctx, func(ctx context.Context) (bool, error) {
p, err := cli.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
attachLog = false
return true, ... | WaitForPodCompletion | identifier_name |
pod.go | // Copyright 2019 The Kanister Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
// DeletePod deletes the specified pod
func DeletePod(ctx context.Context, cli kubernetes.Interface, pod *v1.Pod) error {
if err := cli.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{}); err != nil {
log.WithError(err).Print("DeletePod failed")
}
return nil
}
func StreamPodLogs(ctx cont... | {
pod, err := GetPodObjectFromPodOptions(cli, opts)
if err != nil {
return nil, errors.Wrapf(err, "Failed to get pod from podOptions. Namespace: %s, NameFmt: %s", opts.Namespace, opts.GenerateName)
}
pod, err = cli.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{})
if err != nil {
return ni... | identifier_body |
pod.go | // Copyright 2019 The Kanister Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
return nil
}
// checkPVCAndPVStatus does the following:
// - if PVC is present then check the status of PVC
// - if PVC is pending then check if the PV status is VolumeFailed return error if so. if not then wait for timeout.
// - if PVC not present then wait for timeout
func getVolStatus(ctx context.Context, p... | {
node, err := cli.CoreV1().Nodes().Get(context.TODO(), n[0], metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "%s %s", errAccessingNode, n[0])
}
if !IsNodeReady(node) || !IsNodeSchedulable(node) {
return errors.Errorf("Node %s is currently not ready/schedulable", n[0])
}
} | conditional_block |
pod.go | // Copyright 2019 The Kanister Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | attachLog = false
return false, errors.Errorf("Pod stuck in pending state, reason: %s", p.Status.Reason)
}
}
// check if pvc and pv are up and ready to mount
if err := getVolStatus(timeoutCtx, p, cli, namespace); err != nil {
attachLog = false
return false, err
}
return p.Status.Phase != v1... | if p.Status.Phase == v1.PodPending {
if p.Status.Reason == "OutOfmemory" || p.Status.Reason == "OutOfcpu" { | random_line_split |
js_PassengerEdit.js | //对话框包含处理
function showdialog(t,f) {
jQuery("select").hide();
jQuery("#dialog").html(t);
jQuery("#dialog").dialog({
title: '提示',
bgiframe: true,
height: 180,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
clos... | var carrNo=[];
jQuery("#tab_carry tr").each(function (index,tr) {
var carrCode=jQuery(tr).find("select[id*='ddlCarryCode_']").val();
var AirNo=jQuery.trim(jQuery(tr).find("input[id*='txtAirNo_']").val());
if(carrCode!=""&&AirNo=="") {
msg="航空公司卡号不能为空!";
return fals... | n false;
}
//验证航空公司卡号 暂时不验证
var val_CpyandNo="";
var msg="";
| conditional_block |
js_PassengerEdit.js | //对话框包含处理
function showdialog(t,f) {
jQuery("select").hide();
jQuery("#dialog").html(t);
jQuery("#dialog").dialog({
title: '提示',
bgiframe: true,
height: 180,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
clos... | d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0'));
} else if(fg==1)//yyyy-MM-dd HH
{
d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0')+" "+date.getHours().toStrin... | -MM-dd
| identifier_name |
js_PassengerEdit.js | //对话框包含处理
function showdialog(t,f) {
jQuery("select").hide();
jQuery("#dialog").html(t);
jQuery("#dialog").dialog({
title: '提示',
bgiframe: true,
height: 180,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
clos... | }
for(var key in arr[i]) {
if(arr[i][key]=="0") {
index=key.replace("_","");
istrue=true;
break;
}
}
}
return index;
}
function ddlSetText(ddlObj,flag,num) {
var ddlVal=jQuery.trim(jQuery(ddlObj).val()).split('-... | if(istrue) {
break; | random_line_split |
js_PassengerEdit.js | //对话框包含处理
function showdialog(t,f) {
jQuery("select").hide();
jQuery("#dialog").html(t);
jQuery("#dialog").dialog({
title: '提示',
bgiframe: true,
height: 180,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
clos... | ].split(',');
if(carrArr.length==2) {
carryCode=carrArr[0].toUpperCase();
Card=carrArr[1];
if(i>0) {
//添加
num=addGroup(null,name);
}
//赋值
jQuery("#ta... | tDate").hide();
}
} else if(pasType.indexOf('婴儿')!= -1) {
jQuery("#txtCardNum").hide();
jQuery("#txtDate").show();
}
}
//加载。。。
jQuery(function () {
//初始化航空公司和卡号数
initArr(carryArr,maxCarryNum);
var IsEdit=jQuery("#Hid_IsEdit").val();
//单击旅客类型事件
jQuery("input[type='rad... | identifier_body |
translator.ts | declare const Zotero: any
declare const ZOTERO_TRANSLATOR_INFO: any
import { defaults } from '../../content/prefs-meta'
import { client } from '../../content/client'
import { ZoteroTranslator } from '../../gen/typings/serialized-item'
import type { Preferences } from '../../gen/preferences'
type TranslatorMode = 'exp... | (field: string): string {
field = field.trim()
if (field.startsWith('bibtex.')) return this.BetterBibTeX ? field.replace(/^bibtex\./, '') : ''
if (field.startsWith('biblatex.')) return this.BetterBibLaTeX ? field.replace(/^biblatex\./, '') : ''
return field
}
public init(mode: TranslatorMode) {
... | typefield | identifier_name |
translator.ts | declare const Zotero: any
declare const ZOTERO_TRANSLATOR_INFO: any
import { defaults } from '../../content/prefs-meta'
import { client } from '../../content/client'
import { ZoteroTranslator } from '../../gen/typings/serialized-item'
import type { Preferences } from '../../gen/preferences'
type TranslatorMode = 'exp... |
this.initialized = true
}
public items(): ZoteroTranslator.Item[] {
if (!this.sortedItems) {
this.sortedItems = []
let item: ZoteroTranslator.Item
while (item = (Zotero.nextItem() as ZoteroTranslator.Item)) {
item.cachable = this.cachable
item.journalAbbreviation = item.... | {
let collection: any
while (collection = Zotero.nextCollection()) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const children = collection.children || collection.descendents || []
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
co... | conditional_block |
translator.ts | declare const Zotero: any
declare const ZOTERO_TRANSLATOR_INFO: any
import { defaults } from '../../content/prefs-meta'
import { client } from '../../content/client'
import { ZoteroTranslator } from '../../gen/typings/serialized-item'
import type { Preferences } from '../../gen/preferences'
type TranslatorMode = 'exp... |
for (const key in this.options) {
if (typeof this.options[key] === 'boolean') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.options[key] = !!Zotero.getOption(key)
}
else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
... | caseSensitive: this.platform !== 'mac' && this.platform !== 'win',
sep: this.platform === 'win' ? '\\' : '/',
} | random_line_split |
translator.ts | declare const Zotero: any
declare const ZOTERO_TRANSLATOR_INFO: any
import { defaults } from '../../content/prefs-meta'
import { client } from '../../content/client'
import { ZoteroTranslator } from '../../gen/typings/serialized-item'
import type { Preferences } from '../../gen/preferences'
type TranslatorMode = 'exp... |
}
type TranslatorHeader = {
translatorID: string
translatorType: number
label: string
description: string
creator: string
target: string
minVersion: string
maxVersion: string
priority: number
inRepository: boolean
lastUpdated: string
browserSupport: string
displayOptions: {
exportNotes:... | {
// collections: jabref 4 stores collection info inside the reference, and collection info depends on which part of your library you're exporting
if (['collections'].includes(property)) target.cachable = false
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return target[property]
} | identifier_body |
dposhandler.go | // Copyright 2018 The go-infinet Authors
// This file is part of the go-infinet library.
//
// The go-infinet library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, o... | STATE_CONFIRMED,
response.DelegatedTable,
response.DelegatedTableSign,
nil,
nil,
response.ActiveTime,
};
maxTickets, bestNodeId := uint32(0), "";
for key, value := range NextGigPeriodInstance.confirmedTickets {
if maxTickets < value {
maxTickets = value;
bestNodeId = key;
}
}
... | NextGigPeriodInstance.confirmedBestNode[nodeId] = &GigPeriodTable{
response.Round, | random_line_split |
dposhandler.go | // Copyright 2018 The go-infinet Authors
// This file is part of the go-infinet library.
//
// The go-infinet library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, o... |
// make sure all delegators are synced at this round.
NextGigPeriodInstance = &GigPeriodTable{
round,
STATE_LOOKING,
DelegatorsTable,
SignCandidates(DelegatorsTable),
make(map[string]uint32),
make(map[string]*GigPeriodTable),
activeTime,
};
pm.trySyncAllDelegators()
}
func (pm *DPoSProtocolManager)... | {
if !TestMode {
gap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()
if gap > 2 || gap < -2 {
log.Warn(fmt.Sprintf("Scheduling of the new electing round is improper! current gap: %v seconds", gap))
//restart the scheduler
NextElectionInfo = nil;
go pm.syncDelegatedNodeSafely();
... | conditional_block |
dposhandler.go | // Copyright 2018 The go-infinet Authors
// This file is part of the go-infinet library.
//
// The go-infinet library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, o... |
func (pm *DPoSProtocolManager) Stop() {
if pm.isDelegatedNode() {
pm.packager.Stop();
}
// Quit the sync loop.
log.Info("DPoS Consensus stopped")
}
func (pm *DPoSProtocolManager) newPeer(pv uint, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
return newPeer(pv, p, newMeteredMsgWriter(rw))
}
// ------------------... | {
if DelegatorsTable == nil {
return false;
}
for i :=0; i < len(DelegatorsTable); i++ {
if DelegatorsTable[i] == nodeId {
return true;
}
}
return false;
} | identifier_body |
dposhandler.go | // Copyright 2018 The go-infinet Authors
// This file is part of the go-infinet library.
//
// The go-infinet library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, o... | (nodeId string) bool {
if DelegatorsTable == nil {
return false;
}
for i :=0; i < len(DelegatorsTable); i++ {
if DelegatorsTable[i] == nodeId {
return true;
}
}
return false;
}
func (pm *DPoSProtocolManager) Stop() {
if pm.isDelegatedNode() {
pm.packager.Stop();
}
// Quit the sync loop.
log.Info("D... | isDelegatedNode2 | identifier_name |
staging.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
msg = ('The component [{component}] is required for staging this '
'application.').format(component=self.component)
update_manager.UpdateManager.EnsureInstalledAndRestart([self.component],
msg=msg)
def Run(self, staging_area, descriptor, ... | return | conditional_block |
staging.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (self):
super(NoSdkRootError, self).__init__(
'No SDK root could be found. Please check your installation.')
class StagingCommandFailedError(exceptions.Error):
def __init__(self, args, return_code, output_message):
super(StagingCommandFailedError, self).__init__(
'Staging command [{0}] fail... | __init__ | identifier_name |
staging.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def Stage(self, descriptor, app_dir, runtime, environment):
"""Stage the given deployable or do nothing if N/A.
Args:
descriptor: str, path to the unstaged <service>.yaml or appengine-web.xml
app_dir: str, path to the unstaged app directory
runtime: str, the name of the runtime for the ap... | self.registry = registry
self.staging_area = staging_area | identifier_body |
staging.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | - On success, the STDOUT and STDERR of the staging command are logged at the
INFO level. On failure, a StagingCommandFailedError is raised containing the
STDOUT and STDERR of the staging command (which are surfaced to the user as an
ERROR message).
"""
import cStringIO
import os
import tempfile
from googleclouds... | - A staging command is an executable (binary or script) that takes two
positional parameters: the path of the `<service>.yaml` in the directory
containing the unstaged application code, and the path of an empty directory
in which to stage the application code. | random_line_split |
rozetka_webscrapper.py | import requests
import datetime
import model
import settings
from model.category import Category
from model.group import Group
from model.item import Item
from model.comment import Comment
from bs4 import BeautifulSoup
from driver import Driver
import files.file_reader as fr
import files.file_writer as fw
import ... | (url):
driver = Driver.get()
driver.get(url)
html = driver.page_source
parsed_category = Category()
parsed_category.url = url
soup = BeautifulSoup(html, 'html.parser')
title = soup.find("h1", class_="portal__heading")
if title:
parsed_category.name = decode_str(title.get_text... | parse_category | identifier_name |
rozetka_webscrapper.py | import requests
import datetime
import model
import settings
from model.category import Category
from model.group import Group
from model.item import Item
from model.comment import Comment
from bs4 import BeautifulSoup
from driver import Driver
import files.file_reader as fr
import files.file_writer as fw
import ... | #parse essentials
comment_text = comment.find(class_="comment__text")
if comment_text:
parsed_comment.text = decode_str(comment_text.get_text())
comment_essentials_list = comment.find_all(class_="comment__essentials-item") #has label and optional <dd> with text
parsed_essentials_list = []
... | if fill == "url(#1)":
stars_count += 1
parsed_comment.rating = stars_count
| random_line_split |
rozetka_webscrapper.py | import requests
import datetime
import model
import settings
from model.category import Category
from model.group import Group
from model.item import Item
from model.comment import Comment
from bs4 import BeautifulSoup
from driver import Driver
import files.file_reader as fr
import files.file_writer as fw
import ... |
def parse_comment(comment):
parsed_comment = Comment()
comment_author = comment.find(class_="comment__author")
if comment_author:
comment_date = comment.find(class_="comment__date")
if comment_date:
parsed_comment.date = decode_str(comment_date.get_text())
comment_dat... | return unicodestr | identifier_body |
rozetka_webscrapper.py | import requests
import datetime
import model
import settings
from model.category import Category
from model.group import Group
from model.item import Item
from model.comment import Comment
from bs4 import BeautifulSoup
from driver import Driver
import files.file_reader as fr
import files.file_writer as fw
import ... |
return parsed_comments
def parse_item_page_for_description(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
description = soup.find(class_="product-about__description-content")
return decode_str(description.get_text()) if description else "" #runtime generated
def pa... | comments_list = comments.find_all("li", class_="product-comments__list-item")
comments_count = 0
if comments_list:
for comment in comments_list:
parsed_comments.append(parse_comment(comment))
comments_count += 1
if comments_count >= settings.CO... | conditional_block |
value.rs | //! Types representing for data which will be retrieved from the driver.
//! Currently this data is expected to look like a JSON object but this may be
//! changed in the future. Driver authors must cast the data they retrieve from | use serde::de::{Deserialize, Deserializer, Error as DeError, Visitor, SeqVisitor, MapVisitor};
use serde::de::impls::VecVisitor;
use serde_json;
use error::Error;
/// The type which represents the key for maps used throughout the Ardite
/// codebase.
///
/// Functions similarly to an object key in JavaScript.
pub typ... | //! the driver to these types.
use linear_map::LinearMap;
use serde::ser::{Serialize, Serializer}; | random_line_split |
value.rs | //! Types representing for data which will be retrieved from the driver.
//! Currently this data is expected to look like a JSON object but this may be
//! changed in the future. Driver authors must cast the data they retrieve from
//! the driver to these types.
use linear_map::LinearMap;
use serde::ser::{Serialize, S... |
#[test]
fn test_to_json_pretty() {
assert_eq!(
&value!(["world", 3.333, { "hello" => "world" }, (), (), [1, 2, 3], ()]).to_json_pretty().unwrap(),
"[\n \"world\",\n 3.333,\n {\n \"hello\": \"world\"\n },\n null,\n null,\n [\n 1,\n 2,\n 3\n ],\n null\n]"
);
}
}
| {
assert_eq!(&value!().to_json().unwrap(), "null");
assert_eq!(&value!(true).to_json().unwrap(), "true");
assert_eq!(&value!(false).to_json().unwrap(), "false");
assert_eq!(&value!(7).to_json().unwrap(), "7");
assert_eq!(&value!(6.667).to_json().unwrap(), "6.667");
assert_eq!(&value!("Hello,\n\"... | identifier_body |
value.rs | //! Types representing for data which will be retrieved from the driver.
//! Currently this data is expected to look like a JSON object but this may be
//! changed in the future. Driver authors must cast the data they retrieve from
//! the driver to these types.
use linear_map::LinearMap;
use serde::ser::{Serialize, S... | () {
assert_eq!(value!().get(point![]).cloned(), Some(value!()));
assert_eq!(value!().get(point!["hello"]).cloned(), None);
assert_eq!(value!().get(point!["a", "b", "c", "d", "e"]).cloned(), None);
assert_eq!(value!(true).get(point![]).cloned(), Some(value!(true)));
assert_eq!(value!(true).get(point... | test_get_primitive | identifier_name |
balloon.rs | // Copyright (c) 2020 Ant Financial
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | (&mut self, addr: u64) {
let addr_offset = (addr % self.page_size) >> VIRTIO_BALLOON_PFN_SHIFT;
self.bitmap[(addr_offset / 64) as usize] |= 1 << (addr_offset % 64);
}
fn reset(&mut self) {
let len = ((self.page_size >> VIRTIO_BALLOON_PFN_SHIFT) + 63) / 64;
self.addr = 0;
... | set_bit | identifier_name |
balloon.rs | // Copyright (c) 2020 Ant Financial
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... |
1 => {
let page_size = get_page_size() as usize;
let rbase = align_page_size_down((pfn as u64) << VIRTIO_BALLOON_PFN_SHIFT);
Self::advise_memory_range(
desc_chain.memory(),
... | {
Self::release_memory_range_4k(&mut self.pbp, desc_chain.memory(), pfn)?;
} | conditional_block |
balloon.rs | // Copyright (c) 2020 Ant Financial
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | self.common.resume()
}
}
impl Snapshottable for Balloon {
fn id(&self) -> String {
self.id.clone()
}
fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> {
Snapshot::new_from_versioned_state(&self.state())
}
}
impl Transportable for Balloon {}
impl Migra... | fn resume(&mut self) -> result::Result<(), MigratableError> { | random_line_split |
authenticate-helper.ts | const jwt = require('jsonwebtoken');
import { ApolloError, AuthenticationError } from 'apollo-server-express';
import config from '../../config/config'
import { getDb } from '../../helper/db.helper';
import { getNow } from '../../../share/time.helper';
import { CUSTOMER_TYPE } from '../../../share/constant';
import { Y... |
let customer = await db.collection('customer').aggregate([
{ '$match': condition },
{ '$project': projection },
{
'$lookup': {
from: 'store',
localField: 'store_id',
foreignField: '_id',
as: 'store'
}
},
{
'$lookup': {
from: 'zip_code',
... | {
projection = {
'password': 0
}
} | conditional_block |
authenticate-helper.ts | const jwt = require('jsonwebtoken');
import { ApolloError, AuthenticationError } from 'apollo-server-express';
import config from '../../config/config'
import { getDb } from '../../helper/db.helper';
import { getNow } from '../../../share/time.helper';
import { CUSTOMER_TYPE } from '../../../share/constant';
import { Y... | //login
token = token.replace('Basic ', '');
let query = Buffer.from(token, 'base64').toString('binary').split(':');
let customer = await findAndProcessCustomer({
'$or': [
{
'email': query[0],
},
{
'username': query[0],
},
... | if (token.startsWith('Basic')) {
if (!config.REFRESH_TOKEN_EXPIRE_LIMIT || !config.JWT_EXPIRE_LIMIT) {
throw new AuthenticationError(MSG_SYSTEM_ERROR);
}
| random_line_split |
disk_location.go | package storage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed... |
glog.V(logLevel).Infof("dir %s %s", dir, desc)
}
} |
logLevel := glog.Level(4)
if l.isDiskSpaceLow {
logLevel = glog.Level(0)
} | random_line_split |
disk_location.go | package storage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed... |
func NewDiskLocation(dir string, maxVolumeCount int32, minFreeSpace util.MinFreeSpace, idxDir string, diskType types.DiskType) *DiskLocation {
dir = util.ResolvePath(dir)
if idxDir == "" {
idxDir = dir
} else {
idxDir = util.ResolvePath(idxDir)
}
dirUuid, err := GenerateDirUuid(dir)
if err != nil {
glog.F... | {
glog.V(1).Infof("Getting uuid of volume directory:%s", dir)
dirUuidString = ""
fileName := dir + "/vol_dir.uuid"
if !util.FileExists(fileName) {
dirUuid, _ := uuid.NewRandom()
dirUuidString = dirUuid.String()
writeErr := util.WriteFile(fileName, []byte(dirUuidString), 0644)
if writeErr != nil {
return ... | identifier_body |
disk_location.go | package storage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed... |
}
l.concurrentLoadingVolumes(needleMapKind, workerNum, ldbTimeout)
glog.V(0).Infof("Store started on dir: %s with %d volumes max %d", l.Directory, len(l.volumes), l.MaxVolumeCount)
l.loadAllEcShards()
glog.V(0).Infof("Store started on dir: %s with %d ec shards", l.Directory, len(l.ecVolumes))
}
func (l *DiskLo... | {
workerNum = 10
} | conditional_block |
disk_location.go | package storage
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed... | (volumeSizeLimit uint64) (unUsedSpace uint64) {
l.volumesLock.RLock()
defer l.volumesLock.RUnlock()
for _, vol := range l.volumes {
if vol.IsReadOnly() {
continue
}
datSize, idxSize, _ := vol.FileStat()
unUsedSpace += volumeSizeLimit - (datSize + idxSize)
}
return
}
func (l *DiskLocation) CheckDiskS... | UnUsedSpace | identifier_name |
utility.rs | //! General-purpose utility functions for internal usage within this crate.
use crate::derive_data::{ReflectMeta, StructField};
use crate::field_attributes::ReflectIgnoreBehavior;
use crate::fq_std::{FQAny, FQOption, FQSend, FQSync};
use bevy_macro_utils::BevyManifest;
use bit_set::BitSet;
use proc_macro2::{Ident, Spa... | ;
(ty, bounds)
})
.unzip();
let (ignored_types, ignored_trait_bounds): (Vec<_>, Vec<_>) = ignored_fields
.map(|field| {
let ty = field.data.ty.clone();
let custom_bounds = ignored_bounds(field).map(|bounds| quote!(+ #bounds))... | {
quote!(#bevy_reflect_path::Reflect #custom_bounds)
} | conditional_block |
utility.rs | //! General-purpose utility functions for internal usage within this crate.
use crate::derive_data::{ReflectMeta, StructField};
use crate::field_attributes::ReflectIgnoreBehavior;
use crate::fq_std::{FQAny, FQOption, FQSend, FQSync};
use bevy_macro_utils::BevyManifest;
use bit_set::BitSet;
use proc_macro2::{Ident, Spa... | /// [constant]: StringExpr::Const
pub fn from_str(string: &str) -> Self {
Self::Const(string.into_token_stream())
}
/// Returns tokens for an [owned string](String).
///
/// The returned expression will allocate unless the [`StringExpr`] is [already owned].
///
/// [already owne... | }
/// Creates a [constant] [`StringExpr`] by interpreting a [string slice][str] as a [`struct@LitStr`].
/// | random_line_split |
utility.rs | //! General-purpose utility functions for internal usage within this crate.
use crate::derive_data::{ReflectMeta, StructField};
use crate::field_attributes::ReflectIgnoreBehavior;
use crate::fq_std::{FQAny, FQOption, FQSend, FQSync};
use bevy_macro_utils::BevyManifest;
use bit_set::BitSet;
use proc_macro2::{Ident, Spa... |
/// Appends a [`StringExpr`] to another.
///
/// If both expressions are [`StringExpr::Const`] this will use [`concat`] to merge them.
pub fn appended_by(mut self, other: StringExpr) -> Self {
if let Self::Const(tokens) = self {
if let Self::Const(more) = other {
re... | {
match self {
Self::Const(tokens) | Self::Borrowed(tokens) => tokens,
Self::Owned(owned) => quote! {
&#owned
},
}
} | identifier_body |
utility.rs | //! General-purpose utility functions for internal usage within this crate.
use crate::derive_data::{ReflectMeta, StructField};
use crate::field_attributes::ReflectIgnoreBehavior;
use crate::fq_std::{FQAny, FQOption, FQSend, FQSync};
use bevy_macro_utils::BevyManifest;
use bit_set::BitSet;
use proc_macro2::{Ident, Spa... | (
where_clause: Option<&WhereClause>,
where_clause_options: &WhereClauseOptions,
) -> proc_macro2::TokenStream {
let parameter_types = &where_clause_options.parameter_types;
let active_types = &where_clause_options.active_types;
let ignored_types = &where_clause_options.ignored_types;
let parame... | extend_where_clause | identifier_name |
views_ajax.py | # -*- coding: UTF-8 -*-
import re
import json
import datetime
import multiprocessing
import pdb
from django.db.models import Q
from django.db.utils import IntegrityError
from django.db import transaction
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts impor... |
@csrf_exempt
def getWorkflowStatus(request):
"""获取某个工单的当前状态"""
workflowId = request.POST['workflowid']
if workflowId == '' or workflowId is None :
context = {"status":-1 ,'msg': 'workflowId参数为空.', "data":""}
return HttpResponse(json.dumps(context), content_type='application/json')
work... | elif dictSHA1 != {} and sqlID not in dictSHA1:
pctResult = {"status":4, "msg":"该行SQL不是由pt-OSC执行的", "data":""}
else:
pctResult = {"status":-2, "msg":"整个工单不由pt-OSC执行", "data":""}
return HttpResponse(json.dumps(pctResult), content_type='application/json') | random_line_split |
views_ajax.py | # -*- coding: UTF-8 -*-
import re
import json
import datetime
import multiprocessing
import pdb
from django.db.models import Q
from django.db.utils import IntegrityError
from django.db import transaction
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts impor... | ] != ";":
finalResult['status'] = 'error'
finalResult['msg'] = 'Oracle SQL语句结尾没有以;结尾,请重新修改并提交!'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
sqlContent = sqlContent.rstrip(';')
#使用explain plan进行自动审核
try:
resultList = daoora.sqlAutoreview(sqlCo... | dap authorization failed'}
return HttpResponse(json.dumps(result), content_type='application/json')
if strUsername in login_failure_counter and login_failure_counter[strUsername]["cnt"] >= lockCntThreshold and (
datetime.datetime.now() - login_failure_counter[strUsername][
"... | identifier_body |
views_ajax.py | # -*- coding: UTF-8 -*-
import re
import json
import datetime
import multiprocessing
import pdb
from django.db.models import Q
from django.db.utils import IntegrityError
from django.db import transaction
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts impor... | sqlContent = request.POST['sql_content']
clusterName = request.POST['cluster_name']
finalResult = {'status':'ok', 'msg':'检测通过', 'data':[]}
#服务器端参数验证
if sqlContent is None or clusterName is None:
finalResult['status'] = 'error'
finalResult['msg'] = '页面提交参数可能为空'
... | nse(json.dumps(result), content_type='application/json')
#Oracle SQL简单审核
@csrf_exempt
def orasimplecheck(request):
if request.is_ajax():
sqlContent = request.POST.get('sql_content')
clusterName = request.POST.get('cluster_name')
else:
| conditional_block |
views_ajax.py | # -*- coding: UTF-8 -*-
import re
import json
import datetime
import multiprocessing
import pdb
from django.db.models import Q
from django.db.utils import IntegrityError
from django.db import transaction
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts impor... |
@csrf_exempt
def privMod(request,operation):
loginUser = request.session.get('login_username', False)
hasTableId = [tab.table_id for tab in ora_tab_privs.objects.filter(username = request.GET.get('username'))]
if operation == 'add':
tables = ora_tables.objects.all().exclude(id__in=hasTableId)
... | n/json')
| identifier_name |
consts.go | package renter
import (
"fmt"
"time"
"gitlab.com/NebulousLabs/Sia/build"
"gitlab.com/NebulousLabs/Sia/modules"
)
// Version and system parameters.
const (
// persistVersion defines the Sia version that the persistence was
// last updated
persistVersion = "1.4.2"
)
const (
// AlertMSGSiafileLowRedundancy ind... |
// Default redundancy parameters.
var (
// syncCheckInterval is how often the repair heap checks the consensus code
// to see if the renter is synced. This is created because the contractor
// may not update the synced channel until a block is received under some
// conditions.
syncCheckInterval = build.Select(b... | {
return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy)
} | identifier_body |
consts.go | package renter
import (
"fmt"
"time"
"gitlab.com/NebulousLabs/Sia/build"
"gitlab.com/NebulousLabs/Sia/modules"
)
// Version and system parameters.
const (
// persistVersion defines the Sia version that the persistence was
// last updated
persistVersion = "1.4.2"
)
const (
// AlertMSGSiafileLowRedundancy ind... | (siaPath modules.SiaPath, health, redundancy float64) string {
return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy)
}
// Default redundancy parameters.
var (
// syncCheckInterval is how often the repair heap checks the consensus code
// to see if the rente... | AlertCauseSiafileLowRedundancy | identifier_name |
consts.go | package renter
import (
"fmt"
"time"
"gitlab.com/NebulousLabs/Sia/build"
"gitlab.com/NebulousLabs/Sia/modules"
)
// Version and system parameters.
const (
// persistVersion defines the Sia version that the persistence was
// last updated
persistVersion = "1.4.2"
)
const (
// AlertMSGSiafileLowRedundancy ind... | // syncCheckInterval is how often the repair heap checks the consensus code
// to see if the renter is synced. This is created because the contractor
// may not update the synced channel until a block is received under some
// conditions.
syncCheckInterval = build.Select(build.Var{
Dev: time.Second * 3,
S... | return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy)
}
// Default redundancy parameters.
var ( | random_line_split |
MADDPGAgent.py | import numpy as np
import random
from collections import namedtuple, deque
from MADDPG.Models.MADDPGCritic import Critic
from MADDPG.Models.MADDPGActor import Actor
import torch
import torch.optim as optim
import MADDPG.random_p as rm
from MADDPG.schedule import LinearSchedule
BUFFER_SIZE = int(1e6) # replay buffer... |
epsilon = max((1500 - self.n_step) / 1500, .01)
self.actor_local.eval()
with torch.no_grad():
actions = self.actor_local(state)
self.actor_local.train()
if training:
# return np.clip(actions.cpu().data.numpy()+np.random.uniform(-1,1,(2,2))*epsilon,-1,1)... | state = torch.from_numpy(state).float().detach().to(device)
# print(state.shape,"act")
self.n_step += 1 | random_line_split |
MADDPGAgent.py | import numpy as np
import random
from collections import namedtuple, deque
from MADDPG.Models.MADDPGCritic import Critic
from MADDPG.Models.MADDPGActor import Actor
import torch
import torch.optim as optim
import MADDPG.random_p as rm
from MADDPG.schedule import LinearSchedule
BUFFER_SIZE = int(1e6) # replay buffer... |
else:
return actions.cpu().data.numpy()
def learn(self, experiences, gamma):
"""Update value parameters using given batch of experience tuples.
Params
======
experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples
gamma (float)... | return np.clip(actions.cpu().data.numpy(), -1, 1) # epsilon greedy policy | conditional_block |
MADDPGAgent.py | import numpy as np
import random
from collections import namedtuple, deque
from MADDPG.Models.MADDPGCritic import Critic
from MADDPG.Models.MADDPGActor import Actor
import torch
import torch.optim as optim
import MADDPG.random_p as rm
from MADDPG.schedule import LinearSchedule
BUFFER_SIZE = int(1e6) # replay buffer... | def add(self, states, all_state, action, all_actions, reward, next_state, all_next_state, done):
"""Add a new experience to memory."""
e = self.experience(states, all_state, action, all_actions, reward, next_state, all_next_state, done)
self.memory.append(e)
def sample(self):
"""Ra... | itialize a ReplayBuffer object.
Params
======
action_size (int): dimension of each action
buffer_size (int): maximum size of buffer
batch_size (int): size of each training batch
seed (int): random seed
"""
self.action_size = action_size
... | identifier_body |
MADDPGAgent.py | import numpy as np
import random
from collections import namedtuple, deque
from MADDPG.Models.MADDPGCritic import Critic
from MADDPG.Models.MADDPGActor import Actor
import torch
import torch.optim as optim
import MADDPG.random_p as rm
from MADDPG.schedule import LinearSchedule
BUFFER_SIZE = int(1e6) # replay buffer... | (self, state, training=True):
"""Returns continous actions values for all action for given state as per current policy.
Params
======
state (array_like): current state
"""
state = torch.from_numpy(state).float().detach().to(device)
# print(state.shape,"act")... | act | identifier_name |
server.go | /*
Copyright 2015 Cesanta Software Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | "fmt"
"math/rand"
"net"
"net/http"
"regexp"
"sort"
"strings"
"time"
"github.com/casbin/casbin/v2"
"github.com/cesanta/glog"
"github.com/docker/distribution/registry/auth/token"
"github.com/cesanta/docker_auth/auth_server/api"
"github.com/cesanta/docker_auth/auth_server/authn"
"github.com/cesanta/docker_... | random_line_split | |
server.go | /*
Copyright 2015 Cesanta Software Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
// https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md#example
func (as *AuthServer) CreateToken(ar *authRequest, ares []authzResult) (string, error) {
now := time.Now().Unix()
tc := &as.config.Token
// Sign something dummy to find out which algorithm is used.
_, sigAlg, err := tc.privateK... | {
ares := []authzResult{}
for _, scope := range ar.Scopes {
ai := &api.AuthRequestInfo{
Account: ar.Account,
Type: scope.Type,
Name: scope.Name,
Service: ar.Service,
IP: ar.RemoteIP,
Actions: scope.Actions,
Labels: ar.Labels,
}
actions, err := as.authorizeScope(ai)
if err != n... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.