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 |
|---|---|---|---|---|
mod.rs | ));
Ok(storage)
}
/// Sets up an instance of `Storage`, with git turned on.
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::C... |
else {
debug!("I expected there to be a {}, but there wasn't any ?", trash_file.display())
}
}
if pdffile.exists(){
debug!("now there is be a {:?} -> {:?}", pdffile, target);
try!(fs::rename(&pdffile, &target));... | {
try!(fs::remove_file(&trash_file));
debug!("just deleted: {}", trash_file.display())
} | conditional_block |
secretcache.go | // http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language govern... | // You may obtain a copy of the License at
// | random_line_split | |
secretcache.go | "istio.io/istio/security/pkg/nodeagent/model"
"istio.io/istio/security/pkg/pki/util"
)
const (
// The size of a private key for a leaf certificate.
keySize = 2048
// max retry number to wait CSR response come back to parse root cert from it.
maxRetryNum = 5
// initial retry wait time duration when waiting root... | (ctx context.Context, token, resourceName string, t time.Time) (*model.SecretItem, error) {
options := util.CertOptions{
Host: resourceName,
RSAKeySize: keySize,
}
// Generate | generateSecret | identifier_name |
secretcache.go | istio.io/istio/security/pkg/nodeagent/model"
"istio.io/istio/security/pkg/pki/util"
)
const (
// The size of a private key for a leaf certificate.
keySize = 2048
// max retry number to wait CSR response come back to parse root cert from it.
maxRetryNum = 5
// initial retry wait time duration when waiting root ... |
if sc.rootCert == nil {
log.Errorf("Failed to get root cert for proxy %q", proxyID)
return nil, errors.New("faied to get root cert")
}
t := time.Now()
ns = &model.SecretItem{
ResourceName: resourceName,
RootCert: sc.rootCert,
Token: token,
CreatedTime: t,
Version: t.String(),
}
... | {
wait := retryWaitDuration
retryNum := 0
for ; retryNum < maxRetryNum; retryNum++ {
time.Sleep(retryWaitDuration)
if sc.rootCert != nil {
break
}
wait *= 2
}
} | conditional_block |
secretcache.go | istio.io/istio/security/pkg/nodeagent/model"
"istio.io/istio/security/pkg/pki/util"
)
const (
// The size of a private key for a leaf certificate.
keySize = 2048
// max retry number to wait CSR response come back to parse root cert from it.
maxRetryNum = 5
// initial retry wait time duration when waiting root ... |
// GenerateSecret generates new secret and cache the secret, this function is called by SDS.StreamSecrets
// and SDS.FetchSecret. Since credential passing from client may change, regenerate secret every time
// instead of reading from cache.
func (sc *SecretCache) GenerateSecret(ctx context.Context, proxyID, resource... | {
ret := &SecretCache{
caClient: cl,
closing: make(chan bool),
evictionDuration: options.EvictionDuration,
notifyCallback: notifyCb,
rootCertMutex: &sync.Mutex{},
rotationInterval: options.RotationInterval,
secretTTL: options.SecretTTL,
}
atomic.StoreUint64(&ret.secretChan... | identifier_body |
main.rs | a < 0 {
b = -1;
}
else {
b = 0;
}
println!("b is {}", b);
}
fn f14() {
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!("number 为 {}", number);
}
fn f15() {
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
... | u32,
}
impl Rectangle {
fn create(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
fn f37() {
let rect = Rectangle::create(30, 50);
println!("{:?}", rect);
}
#[derive(Debug)]
enum Book {
Papery, Electronic
}
fn f38() {
let book = Book::Papery;
println!("{:?... | ;
println!("{}", rect1.wider(&rect2));
}
struct Rectangle4 {
width: u32,
height: | identifier_body |
main.rs | b = -1;
}
else {
b = 0;
}
println!("b is {}", b);
}
fn f14() {
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!("number 为 {}", number);
}
fn f15() {
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
}
printl... | b = 1;
}
else if a < 0 {
| conditional_block | |
main.rs | String,
name: String,
nation: String,
found: u32
}
struct Color(u8, u8, u8);
struct Point2(f64, f64);
fn f33() {
struct Color(u8, u8, u8);
struct Point(f64, f64);
let black = Color(0, 0, 0);
let origin = Point(0.0, 0.0);
println!("black = ({}, {}, {})", black.0, black.1, black.2);
... | }
fn f59() {
let s = String::from("EN中文"); | random_line_split | |
main.rs | a < 0 {
b = -1;
}
else {
b = 0;
}
println!("b is {}", b);
}
fn f14() {
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!("number 为 {}", number);
}
fn f15() {
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
... | let some_string = String::from("hello");
// some_string 被声明有效
return some_string;
// some_string 被当作返回值移动出函数
}
fn takes_and_gives_back(a_string: String) -> String {
// a_string 被声明有效
a_string // a_string 被当作返回值移出函数
}
fn f23() {
let s1 = String::from("hello");
let s2 = &s1;
println... | ring {
| identifier_name |
run_scenario.py | else:
dataset_folder += '/text/questions'
text_dataset = True
if text_dataset:
setup = TextNetworkSetup(text_setup, dataset_folder, args, scenario=True, scenario_setup=scenario_setup)
return setup.scenario_loader, setup.q_network
else:
setup = ImageNetworkSetup(imag... | dataset_folder = 'data'
# Collecting static image setup
image_setup = ImageModelSetup(False, 0, 0)
# Collecting static text setup
text_dataset = False
text_setup = TextModelSetup(False, 0, 0, args.embedding_size, args.sentence_length)
# Creating setup based on data-set
if dataset == 0:
... | identifier_body | |
run_scenario.py | def add_list(list1, list2, dim=1):
if dim == 1:
for l in range(len(list2)):
list1[l] += list2[l]
elif dim == 2:
for l in range(len(list2)):
for i in range(len(list2[l])):
list1[l][i] += list2[l][i]
def divide_list(list1, iterations, dim=1):
if dim ==... |
plt.ylabel("Class Q-value")
plt.legend(loc=9)
plt.title("ReinforcementLearning Scenario")
plt.xlabel("Time step")
plt.ylim((0, 1))
if not os.path.exists(directory + name):
os.makedirs(directory + name)
plt.savefig(directory + name + bar_type + "_" + str(size) + ".png")
... | if len(bottom_list) == 0:
plt.bar(x, np_lists[i], color=colors[i], label=labels[i], edgecolor="black")
bottom_list = np_lists[i]
else:
plt.bar(x, np_lists[i], bottom=bottom_list, color=colors[i], label=labels[i], edgecolor="black")
bottom_list ... | conditional_block |
run_scenario.py | def add_list(list1, list2, dim=1):
if dim == 1:
for l in range(len(list2)):
list1[l] += list2[l]
elif dim == 2:
for l in range(len(list2)):
for i in range(len(list2[l])):
list1[l][i] += list2[l][i]
def divide_list(list1, iterations, dim=1):
if dim ==... | ():
scenarios = ['Meta Scenario', 'Zero Shot Scenario', 'K Shot Scenario', 'One Shot Scenario', 'All scenarios']
for i in range(len(scenarios)):
print(str(i) + ': ' + scenarios[i] + '\n')
return get_integer_input('Select scenario to run [0-N]:\n', 'scenario', len(scenarios))
def get_data_set():
... | get_scenario | identifier_name |
run_scenario.py | def add_list(list1, list2, dim=1):
if dim == 1:
for l in range(len(list2)):
list1[l] += list2[l]
elif dim == 2:
for l in range(len(list2)):
for i in range(len(list2[l])):
list1[l][i] += list2[l][i]
def divide_list(list1, iterations, dim=1):
if dim ==... |
if __name__ == '__main__':
data_sets = ['OMNIGLOT', 'MNIST', 'INH', 'REUTERS', 'QA']
directory = "results/plots/"
nof_scenarios = 1
pretrained_models = get_pretrained_models()
chosen_model_to_train, model_type = get_selected_model()
scenario_type = get_scenario()
if scenario_type == 4:
... | self.LSTM = setup['LSTM']
self.NTM = setup['NTM']
self.LRUA = setup['LRUA'] | random_line_split |
wakers.rs | Future;
use core::task::{Context, Poll};
use core::pin::Pin;
/// Used to signal to one of many waiters that the condition they're waiting on has happened.
pub(crate) struct Notifier {
notify_pending: Mutex<(bool, Option<Arc<Mutex<FutureState>>>)>,
condvar: Condvar,
}
impl Notifier {
pub(crate) fn new() -> Self {
... | }
}
mod std_future {
use core::task::Waker;
pub struct StdWaker(pub Waker);
impl super::FutureCallback for StdWaker {
fn call(&self) { self.0.wake_by_ref() }
}
}
/// (C-not exported) as Rust Futures aren't usable in language bindings.
impl<'a> StdFuture for Future {
type Output = ();
fn poll(self: Pin<&mut ... | } else {
state.callbacks.push(callback);
} | random_line_split |
wakers.rs | ;
use core::task::{Context, Poll};
use core::pin::Pin;
/// Used to signal to one of many waiters that the condition they're waiting on has happened.
pub(crate) struct Notifier {
notify_pending: Mutex<(bool, Option<Arc<Mutex<FutureState>>>)>,
condvar: Condvar,
}
impl Notifier {
pub(crate) fn new() -> Self {
Self... | (&self) { (self)(); }
}
pub(crate) struct FutureState {
callbacks: Vec<Box<dyn FutureCallback>>,
complete: bool,
}
impl FutureState {
fn complete(&mut self) {
for callback in self.callbacks.drain(..) {
callback.call();
}
self.complete = true;
}
}
/// A simple future which can complete once, and calls so... | call | identifier_name |
wakers.rs | ;
use core::task::{Context, Poll};
use core::pin::Pin;
/// Used to signal to one of many waiters that the condition they're waiting on has happened.
pub(crate) struct Notifier {
notify_pending: Mutex<(bool, Option<Arc<Mutex<FutureState>>>)>,
condvar: Condvar,
}
impl Notifier {
pub(crate) fn new() -> Self {
Self... |
#[cfg(any(test, feature = "_test_utils"))]
pub fn notify_pending(&self) -> bool {
self.notify_pending.lock().unwrap().0
}
}
/// A callback which is called when a [`Future`] completes.
///
/// Note that this MUST NOT call back into LDK directly, it must instead schedule actions to be
/// taken later. Rust users ... | {
let mut lock = self.notify_pending.lock().unwrap();
if lock.0 {
Future {
state: Arc::new(Mutex::new(FutureState {
callbacks: Vec::new(),
complete: false,
}))
}
} else if let Some(existing_state) = &lock.1 {
Future { state: Arc::clone(&existing_state) }
} else {
let state = Arc::n... | identifier_body |
svm_digits.py | dataArr, classLabels):
X = mat(dataArr)
labelMat = mat(classLabels).T
m, n =shape(X)
w = zeros((n, 1))
for i in range(m):
w += multiply(alphas[i] * labelMat[i], X[i,:].T)
return w
class optStruct:
def __init__(self, dataMatIn, classLabels, C, toler, kTup):
self.X = dataMatI... | ]
dataMatrix = mat(dataMat)
labelMatrix = mat(labelMat).T
for i in range(m):
index = 0
if (alphas[i] > 0) and (labelMatrix[i] > 0):
index = i
break
b1 = zeros((1,1))
b = labelMatrix[index, :]
for i in range(m):
b1 += alphas[i] * labelMatrix[i] * da... | identifier_body | |
svm_digits.py | 标号为k的数据结构
'''
# fXK = float(multiply(oS.alphas, oS.labelMat).T *\
# (oS.X * oS.X[k, :].T)) + oS.b
fXk = float(multiply(oS.alphas, oS.labelMat).T * oS.K[:,k] + oS.b) # 类似第k组数据所得预测标签(未经过激活函数转换)
EK = fXk - float(oS.labelMat[k]) # 第k组预测结果与实际标签的差值
return EK #返回第k组的误差(标量)
def... | phas[i] - alphaIold) * oS.K[i,j] -\
oS.labelMat[j] * (oS.alphas[j] - alphaJold) * oS.K[j,j]
# 步骤8:根据b_1和b_2更新b
if (0 < oS.alphas[i]) and (oS.C > oS.alphas[i]):
oS.b = b1
elif (0 < oS.alphas[j]) and (oS.C > oS.alphas[j]):
oS.b = b2
else: # alpha[i]、al... |
b2 = oS.b - Ej - oS.labelMat[i] * (oS.al | conditional_block |
svm_digits.py | break
b1 = zeros((1,1))
b = labelMatrix[index, :]
for i in range(m):
b1 += alphas[i] * labelMatrix[i] * dataMatrix[i,:] * dataMatrix[index,:].T
b -= b1
return b
def calcWs(alphas, dataArr, classLabels):
X = mat(dataArr)
labelMat = mat(classLabels).T
m, n =shape(X)
... | index = 0
if (alphas[i] > 0) and (labelMatrix[i] > 0):
index = i | random_line_split | |
svm_digits.py | j > H:
aj = H
elif L > aj:
aj = L
return aj
def calcB(dataMat, labelMat, alphas):
m = shape(dataMat)[0]
dataMatrix = mat(dataMat)
labelMatrix = mat(labelMat).T
for i in range(m):
index = 0
if (alphas[i] > 0) and (labelMatrix[i] > 0):
index = i
... |
if a | identifier_name | |
boilerplate.js | function () {
// Open external link in new windows
$('a[href^="http://"]').filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
// build an animated footer
$('#animated').each(function () {
$(this).hover(function () {
... | var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
$(function () ... | // (indicating the use of another browser).
{ | random_line_split |
boilerplate.js | curTop = document.body.scrollTop;
ad.DirV = true;
}
ad.style.left = curLeft + (ad.DirH ? 1 : -1) + "px";
ad.style.top = curTop + (ad.DirV ? 1 : -1) + "px";
}
}
}
/*------------------------------------------------------------------... | {
var curLeft = parseInt(ad.style.left);
var curTop = parseInt(ad.style.top);
if(ad.offsetWidth + curLeft > document.body.clientWidth + document.body.scrollLeft - 1)
{
curLeft = document.body.scrollLeft + document.body.clientWidth - ad.offsetWidth;
... | conditional_block | |
boilerplate.js | () {
// Open external link in new windows
$('a[href^="http://"]').filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
// build an animated footer
$('#animated').each(function () {
$(this).hover(function () {
$(t... | s the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})");
if (re.exe... | rerVersion()
// Return | identifier_name |
boilerplate.js | quee('slide');
}
);
}
};
$.fn.marquee = function (m) {
var settings = {
'delay': 2000,
'duration': 900,
'stop': true
};
if (typeof m === 'object' || !m) {
if (m) {
... | , options);
this._defaults = defaults;
this._name = pluginName;
if(element) this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic | identifier_body | |
heat_exchanger.py | Calculate
class HeatExchangerWindow(QMainWindow, Ui_MainWindow):
"""
Class obsahující komunikaci mezi uživatelským prostředím a backendem.
Samotné uživatelské prostředí se nachází v souboru heat_exchanger_ui odkud je importováno.
"""
def __init__(self):
super().__init__()
self.setu... | are_table(self):
"""
Pripraveni sloupcu v tabulce
"""
i = 0
for item in ['DN[-]', 'd_out[mm]', 'tl_trub[mm]', 'roztec_trub[mm]', 'delka[mm]', 'roztec_prep[mm]', 'vyska_prep[mm]']:
self.table.insertColumn(i)
self.table.setHorizontalHeaderItem(i, QTableWidge... | splays a separate dialog (alert) informing user of something bad, like
invalid user input or simulation errors.
Args:
error_message ... what should be shown to the user
"""
print(error_message)
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
... | identifier_body |
heat_exchanger.py | Calculate
class HeatExchangerWindow(QMainWindow, Ui_MainWindow):
"""
Class obsahující komunikaci mezi uživatelským prostředím a backendem.
Samotné uživatelské prostředí se nachází v souboru heat_exchanger_ui odkud je importováno.
"""
def __init__(self):
super().__init__()
self.setu... | s['Medium'] = medium
return values
def get_main_inputs(self, input) -> dict:
"""
Ziskani hlavnich vstupu od uzivatele
"""
values = {}
for element in input.parameters:
try:
name = input.name + element['name']
value = getattr... | part_medium)
value | conditional_block |
heat_exchanger.py | import Calculate
class HeatExchangerWindow(QMainWindow, Ui_MainWindow):
"""
Class obsahující komunikaci mezi uživatelským prostředím a backendem.
Samotné uživatelské prostředí se nachází v souboru heat_exchanger_ui odkud je importováno.
"""
def __init__(self):
super().__init__()
se... | item.setData(0, output[1][y])
item.setFlags(Qt.ItemFlags(1))
self.table.setItem(i, j, item)
j += 1
i += 1
def show_graph(self, outputs):
graph_inputs = {
'x' : [],
'y' : [],
's' : [],
... | random_line_split | |
heat_exchanger.py | Calculate
class HeatExchangerWindow(QMainWindow, Ui_MainWindow):
"""
Class obsahující komunikaci mezi uživatelským prostředím a backendem.
Samotné uživatelské prostředí se nachází v souboru heat_exchanger_ui odkud je importováno.
"""
def __init__(self):
super().__init__()
self.setu... | layout, input) -> None:
"""
Pridani vstupu hlavni vstupu do uzivatelskeho prostredi.
"""
title = QLabel(input.title)
title.setAlignment(Qt.AlignCenter)
title.setFont(QFont("Times", 16, QFont.Bold))
parent_layout.addWidget(title)
for element in inp... | s(self, parent_ | identifier_name |
gamestate.rs | /// 1. Placement on an invalid position (either out of bounds or a hole)
/// 2. Placement when the players' avatars are already placed
///
/// This function will choose which penguin to place for the current player, so it is
/// impossible for the player to place a penguin that is not theirs.
pub ... | test_new | identifier_name | |
gamestate.rs | };
board_string.push_str(&tile_string);
board_string.push_str(" ");
}
board_string.push_str("\n");
}
writeln!(f, "{}", board_string)?;
// Write each player, their score, and their penguin positions
for (player_i... | {
let mut board_string = String::new();
for y in 0..self.board.height {
if y % 2 == 1 {
board_string.push_str(" ");
}
for x in 0..self.board.width {
let tile_string = match self.board.get_tile_id(x, y) {
Some(id) ... | identifier_body | |
gamestate.rs | tile: TileId) -> Option<()> {
let occupied_tiles = self.get_occupied_tiles();
if occupied_tiles.contains(&tile) {
None
} else {
let player = self.players.get_mut(&player)?;
player.place_penguin(tile, &self.board)
}
}
/// Places an unplaced ... | {
self.previous_turn_index();
} | conditional_block | |
gamestate.rs | (&self, posn: BoardPosn) -> Option<&Penguin> {
let tile = self.board.get_tile_id(posn.x, posn.y)?;
self.players.iter().find_map(|(_, player)| {
player.find_penguin(tile)
})
}
/// Search for the penguin at the given TileId and return it if possible.
/// Returns None if no... | // Move failed: tile not reachable from tile 0 | random_line_split | |
example.py | Q[s][a] = 0.0
gamma = 0.9 # discount factor
alpha_W = 0.1 # learning rate
t = 1.0 # count time
########################################################################################################################
# To start the algorithm we need any action, so we pick one randomly until we find a valid... | random_line_split | ||
example.py | Green
agent = gridworld.GameEnv()
agent.step(0)
print("I moved up")
agent.step(1)
print("I moved down")
agent.step(2)
print("I moved left")
agent.step(3)
print("I moved right")
########################################################################################################################
# ... |
# loop until done (i.e. solved the maze or gave up)
done = False
while not done:
# perform current step and get the next state, the reward/penalty for the move, and whether the agent is done (solved or gave up)
next_state, reward, done = agent.step(current_action, False)
# get the best currently known a... | current_action = helperFunctions.random_action(None, agent.action_space, eps=1)
found_initial_move = agent.is_possible_action(current_action) | conditional_block |
zbump_nonmorphing.py | 8.4,-9.6,-10.8,-12]:
(x_const,yels,zpos,zneg,lipz) = ellipse_points(r,xelem,cg[1],cg[2],100,shrink)
printer(x_const,yels,zpos,ax)
printer(x_const,yels,zneg,ax)
#print('\nyes is: ',yes)
#print('\nzes is: ',zes)
return (ax,yes,zes,zpos,lipz)
def og_gc_printer(x,y,z,ax):
for i in ... | #print(xb)
#print(zb)
cub_behind = zbum.cubic_solver(xb,zb,-.15,0.15)
#-----------------------z bumping section------------------------#
for k in range(len(ygc)):
if k in behind: # down bump for BEHIND gc's
#### Preliminary calcs for intervals for spanwise smoothing
... | zb = z0b/z0b
#print(x0b)
#print(z0b) | random_line_split |
zbump_nonmorphing.py | (x,y,z,ax):
ax.plot(x,y,z, label = 'Engine',color = 'blue')
def engine(cg,r,length,cg_shift,shrink,ax):
#cg = [-2.28,6.5,-1.86]
#r = 1.5
#length = 2.4
#cg_shift = 2.3
circles_front = 10
circles_back = 5
every__deg = 15
#shri... | printer | identifier_name | |
zbump_nonmorphing.py | .4,-9.6,-10.8,-12]:
(x_const,yels,zpos,zneg,lipz) = ellipse_points(r,xelem,cg[1],cg[2],100,shrink)
printer(x_const,yels,zpos,ax)
printer(x_const,yels,zneg,ax)
#print('\nyes is: ',yes)
#print('\nzes is: ',zes)
return (ax,yes,zes,zpos,lipz)
def og_gc_printer(x,y,z,ax):
for i in r... |
return index
def zgc_bumpNadd(xgc,ygc,zgc,circy,circz,elipz,cg,length,shift,r,shrink,lipz,t,srB,srO,srF,gcnumbeh,gcnumfro,ax):
front = []
over = []
behind = []
alone = []
#print(len(ygc))
#gcnumfro = 20
#gcnumbeh = 30
# for loop through each individual guide_curve
for i in ran... | if ( (abs(gcpts[i+1]-cgy)) < (abs(gcpts[i]-cgy)) ):
index = (i+1) | conditional_block |
zbump_nonmorphing.py |
def og_gc_printer(x,y,z,ax):
for i in range(len(x)):
if i in range(4,67):
ax.plot(x[i],y[i],z[i], label = 'GC',color = 'red')
def new_gc_printer(x,y,z,ax):
for i in range(len(x)):
# if i in range(0,99):
#if i < 67:
#if i < 114:
#if i > 44:
#if i i... | circles_front = 10
circles_back = 5
every__deg = 15
#shrink = 100 # Ellipse z-direction shrink factor
for i in range(0,circles_front+1):
step = cg_shift/circles_front *i
(x_const,yes,zes) = circ_points(r,cg[0]+step,cg[1],cg[2],every__deg)
printer(x_const,yes,z... | identifier_body | |
osm-pbf-analyst.js | (filename, options) {
const _options = Object.assign({}, DEFAULT_OPTIONS, options);
const { highWaterMark, uiEnabled, uiUpdateInterval, uiColors } = _options;
const memory = newMemoryObject(uiEnabled);
const { internal, file, block, primitive } = memory;
const fileReadStream = fs.createReadStream(filename, { ... | OsmPbfAnalyst | identifier_name | |
osm-pbf-analyst.js | /**
* Reads 4 bytes as a 32bit int from `pointer` offset
* @method readInt32
* @return {Int32|Number}
*/
const readInt32 = () => {
const value = internal.buffer.readInt32BE(internal.pointer);
internal.pointer += 4;
return value;
};
/**
* Reads a specified amount of bytes as a Buffer from ... | {
const _options = Object.assign({}, DEFAULT_OPTIONS, options);
const { highWaterMark, uiEnabled, uiUpdateInterval, uiColors } = _options;
const memory = newMemoryObject(uiEnabled);
const { internal, file, block, primitive } = memory;
const fileReadStream = fs.createReadStream(filename, { highWaterMark });
... | identifier_body | |
osm-pbf-analyst.js | => internal.pointer + size <= internal.buffer.length;
/**
* Reads 4 bytes as a 32bit int from `pointer` offset
* @method readInt32
* @return {Int32|Number}
*/
const readInt32 = () => {
const value = internal.buffer.readInt32BE(internal.pointer);
internal.pointer += 4;
return value;
};
/**... | // Each file block has to apply a fix to the lat/lon and timestamps on each node
// http://wiki.openstreetmap.org/wiki/PBF_Format#Definition_of_OSMData_fileblock
const fixLatitude = (lat) => .000000001 * lat.multiply(granularity).add(lat_offset);
const fixLongitude = (lon) => .000000001 * lon.multiply(g... | const firstPrimitive = primitivegroup[0];
const { nodes, dense, ways, relations, changesets } = firstPrimitive; | random_line_split |
main.rs | -history dtolnay/syn dtolnay/quote
star-history serde-rs/serde
",
);
static MISSING_TOKEN: &str = "\
Error: GitHub auth token is not set up.
(Expected config file: {{path}})
Run `gh auth login` to store a GitHub login token. The `gh` CLI
can be installed from <https://cli.github.com>.
If you prefer not to use t... | {
query: String,
}
#[derive(Deserialize, Debug)]
struct Response {
message: Option<String>,
#[serde(default, deserialize_with = "deserialize_data")]
data: VecDeque<Data>,
#[serde(default)]
errors: Vec<Message>,
}
#[derive(Deserialize, Debug)]
struct Message {
message: String,
}
#[derive(... | Request | identifier_name |
main.rs | formatter.write_str("null")?,
}
Ok(())
}
}
struct Work {
series: Series,
cursor: Cursor,
}
#[derive(Serialize)]
struct Request {
query: String,
}
#[derive(Deserialize, Debug)]
struct Response {
message: Option<String>,
#[serde(default, deserialize_with = "deserialize_data")]
... | {
set.insert(Star {
time: now,
node: Default::default(),
});
} | conditional_block | |
main.rs | -history dtolnay/syn dtolnay/quote
star-history serde-rs/serde
",
);
static MISSING_TOKEN: &str = "\
Error: GitHub auth token is not set up.
(Expected config file: {{path}})
Run `gh auth login` to store a GitHub login token. The `gh` CLI
can be installed from <https://cli.github.com>.
If you prefer not to use t... | E: de::Error,
{
Ok(VecDeque::new())
}
}
deserializer.deserialize_any(ResponseVisitor)
}
fn non_nulls<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
struct NonNullsVisitor<T>(PhantomData<fn() -> T>);... | random_line_split | |
main.rs | -history dtolnay/syn dtolnay/quote
star-history serde-rs/serde
",
);
static MISSING_TOKEN: &str = "\
Error: GitHub auth token is not set up.
(Expected config file: {{path}})
Run `gh auth login` to store a GitHub login token. The `gh` CLI
can be installed from <https://cli.github.com>.
If you prefer not to use t... |
}
struct Work {
series: Series,
cursor: Cursor,
}
#[derive(Serialize)]
struct Request {
query: String,
}
#[derive(Deserialize, Debug)]
struct Response {
message: Option<String>,
#[serde(default, deserialize_with = "deserialize_data")]
data: VecDeque<Data>,
#[serde(default)]
errors: V... | {
match &self.0 {
Some(cursor) => {
formatter.write_str("\"")?;
formatter.write_str(cursor)?;
formatter.write_str("\"")?;
}
None => formatter.write_str("null")?,
}
Ok(())
} | identifier_body |
lib.rs | !("OUT_DIR"), "/dump.json"));
serde_json::from_slice::<LootTableSet>(BYTES)
.expect("invalid loot table dump")
.0
.into_iter()
.map(|(k, v)| (k, LootTable(v)))
.collect()
});
/// Returns the loot table with the given ID, if it exists.
/// IDs are the same as those used in M... | {
let table = loot_table("blocks/dirt").expect("missing loot table for dirt block");
let mut rng = StepRng::new(0, 1);
let items = table.sample(&mut rng, &Conditions::default()).unwrap();
assert_eq!(items.as_slice(), &[ItemStack::new(Item::Dirt, 1)]);
} | identifier_body | |
lib.rs | smallvec::SmallVec;
use std::iter;
use thiserror::Error;
/// The global loot table store, initialized at runtime from
/// the embedded loot table dump. (Generated by the build script)
static STORE: Lazy<AHashMap<InlinableString, LootTable>> = Lazy::new(|| {
static BYTES: &[u8] = include_bytes!(concat!(env!("OUT_D... |
})
.expect("entry finding algorithm incorrect");
sample_entry(entry, rng, results, conditions)?;
}
// apply functions to results
results
.iter_mut()
.try_for_each(|item| apply_functions(pool.functions.iter(), item, rng, conditions))?;
Ok(())
}
fn samp... | {
cumulative_weight += entry.weight;
false
} | conditional_block |
lib.rs | use smallvec::SmallVec;
use std::iter;
use thiserror::Error;
/// The global loot table store, initialized at runtime from
/// the embedded loot table dump. (Generated by the build script)
static STORE: Lazy<AHashMap<InlinableString, LootTable>> = Lazy::new(|| {
static BYTES: &[u8] = include_bytes!(concat!(env!("OU... | // the result. This algorithm is O(n) computaitonally, but this is unlikely
// to matter in practice, because loot tables rarely
// have more than one or two entries per pool.
let n = rng.gen_range(0, weight_sum);
let mut cumulative_weight = 0;
let entry = entries
... | for _ in 0..pool.rolls.sample(rng) {
// We choose an integer at random from [0, weight_sum) and
// determine which entry has a cumulative weight matching | random_line_split |
lib.rs | vec::SmallVec;
use std::iter;
use thiserror::Error;
/// The global loot table store, initialized at runtime from
/// the embedded loot table dump. (Generated by the build script)
static STORE: Lazy<AHashMap<InlinableString, LootTable>> = Lazy::new(|| {
static BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), ... | <'a>(
mut conditions: impl Iterator<Item = &'a Condition>,
input: &Conditions,
rng: &mut impl Rng,
) -> bool {
conditions.all(|condition| match condition {
Condition::MatchTool { predicate } => {
if let Some(item) = &predicate.item {
match &input.item {
... | satisfies_conditions | identifier_name |
memory_index.rs | claims: BTreeMap<Property, ID>,
}
impl Permanode {
fn index_claim(&mut self, claim: &Dict, permanode_id: &ID, claim_id: &ID) {
// We require the claim to have the sort key
let sort_value: &Property = match claim.get(self.sort.field()) {
Some(ref prop) => prop,
None => {
... | /// Directory where objects are stored on disk.
path: PathBuf,
/// All objects, indexed by their ID.
objects: HashMap<ID, Object>,
/// Back references: value is all references pointing to the key.
backlinks: HashMap<ID, HashSet<(Backkey, ID)>>,
/// All claim objects, whether they are valid f... | multimap.insert(key.clone(), set);
}
/// The in-memory index, that loads all objects from the disk on startup.
pub struct MemoryIndex { | random_line_split |
memory_index.rs | claims: BTreeMap<Property, ID>,
}
impl Permanode {
fn index_claim(&mut self, claim: &Dict, permanode_id: &ID, claim_id: &ID) {
// We require the claim to have the sort key
let sort_value: &Property = match claim.get(self.sort.field()) {
Some(ref prop) => prop,
None => {
... | <K: Clone + Eq + ::std::hash::Hash,
V: Eq + ::std::hash::Hash>(
multimap: &mut HashMap<K, HashSet<V>>,
key: &K,
value: V)
{
if let Some(set) = multimap.get_mut(key) {
set.insert(value);
return;
}
let mut set = HashSet::new();
set.insert(value);
mul... | insert_into_multimap | identifier_name |
memory_index.rs | claims: BTreeMap<Property, ID>,
}
impl Permanode {
fn index_claim(&mut self, claim: &Dict, permanode_id: &ID, claim_id: &ID) {
// We require the claim to have the sort key
let sort_value: &Property = match claim.get(self.sort.field()) {
Some(ref prop) => prop,
None => {
... |
}
}
}
}
fn insert_into_multimap<K: Clone + Eq + ::std::hash::Hash,
V: Eq + ::std::hash::Hash>(
multimap: &mut HashMap<K, HashSet<V>>,
key: &K,
value: V)
{
if let Some(set) = multimap.get_mut(key) {
set.insert(value);
return;
}
let... | {
let mut map = BTreeMap::new();
swap(&mut self.claims, &mut map);
let mut map = map.into_iter();
let (k, v) = match self.sort {
Sort::Ascending(_) => map.next_back().unwrap(),
Sort::Descendin... | conditional_block |
policy.go | nil {
return err
}
}
for j, _ := range policyDoc.Ingress {
for i, _ := range policyDoc.Ingress[j].Rules {
rule := &policyDoc.Ingress[j].Rules[i]
rule.Protocol = strings.ToUpper(rule.Protocol)
}
for i, _ := range policyDoc.Ingress[j].Peers {
endpoint := &policyDoc.Ingress[j].Peers[i]
err = po... | {
log.Println("Entering policy.Initialize()")
err := policy.store.Connect()
if err != nil {
return err
}
policy.client = client
return nil
} | identifier_body | |
policy.go | },
common.Route{
Method: "GET",
Pattern: findPath + policiesPath + "/{policyName}",
Handler: policy.findPolicyByName,
},
}
return routes
}
// augmentEndpoint augments the endpoint provided with appropriate information
// by looking it up in the appropriate service.
func (policy *PolicySvc) augmentEnd... |
endpoint.TenantNetworkID = &ten.NetworkID
} else if endpoint.TenantExternalID != "" || endpoint.TenantName != "" {
if endpoint.TenantExternalID != "" {
ten.ExternalID = endpoint.TenantExternalID
}
if endpoint.TenantName != "" {
ten.Name = endpoint.TenantName
}
err = policy.client.Find(ten... | {
return err
} | conditional_block |
policy.go | center = dc
for i, _ := range policyDoc.AppliedTo {
endpoint := &policyDoc.AppliedTo[i]
err = policy.augmentEndpoint(endpoint)
if err != nil {
return err
}
}
for j, _ := range policyDoc.Ingress {
for i, _ := range policyDoc.Ingress[j].Rules {
rule := &policyDoc.Ingress[j].Rules[i]
rule.Protocol ... | Initialize | identifier_name | |
policy.go | // 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 to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR ... | random_line_split | ||
views.py | , childcid, order_rule):
foodtyps = Foodtype.objects.all()
if childcid == ALL_TYPE:
goods_list = Goods.objects.filter(categoryid=categoryid)
else:
goods_list = Goods.objects.filter(categoryid=categoryid).filter(childcid=childcid)
foodtype = Foodtype.objects.get(typeid=categoryid)
"... | # 密码错误
return redirect(reverse('axf:user_login'))
else:
request.session['msg'] = '用户不存在'
# 用户不存在
return redirect(reverse('axf:user_login'))
"""
激活
能找到用户的方式
- 根据用户唯一标识
修改用户状态
"""
def send_mail_learn(username, email, userid):
... | return redirect(reverse('axf:mine'))
else:
request.session['msg'] = '密码错误'
| conditional_block |
views.py | 'user/user_register.html', context=data)
elif request.method == "POST":
username = request.POST.get('u_name')
password = request.POST.get('u_password')
email = request.POST.get('u_email')
icon = request.FILES.get('u_icon')
print(password)
user = UserModel()
... | order_list( | identifier_name | |
views.py | , childcid, order_rule):
foodtyps = Foodtype.objects.all()
if childcid == ALL_TYPE:
goods_list = Goods.objects.filter(categoryid=categoryid)
else:
goods_list = Goods.objects.filter(categoryid=categoryid).filter(childcid=childcid)
foodtype = Foodtype.objects.get(typeid=categoryid)
"... | True
user.save()
return HttpResponse('用户激活成功')
def add_to_cart(request):
goodsid = request.GET.get('goodsid')
userid = request.session.get('user_id')
print(goodsid)
data = {
'status': '200',
'msg': 'ok'
}
if not userid:
data['status'] = '302'
data[... | 'active_url': 'http://127.0.0.1:8001/axf/activeuser/?utoken=%s' % token,
}
html = temp.render(data)
send_mail(subject, message, 'rongjiawei1204@163.com', recipient_list, html_message=html)
def active_user(request):
user_token = request.GET.get('utoken')
user_id = cache.get(user_token)
cach... | identifier_body |
views.py | , childcid, order_rule):
foodtyps = Foodtype.objects.all()
if childcid == ALL_TYPE:
goods_list = Goods.objects.filter(categoryid=categoryid)
else:
goods_list = Goods.objects.filter(categoryid=categoryid).filter(childcid=childcid)
foodtype = Foodtype.objects.get(typeid=categoryid)
"... |
def mine(request):
is_login = False
user_id = request.session.get('user_id')
data = {
'title': '我的',
'is_login': is_login,
}
if user_id:
is_login = True
user = UserModel.objects.get(pk=user_id)
data['is_login'] = is_login
data['user_icon'] = '/stat... | random_line_split | |
elgamal.rs | V3bQvhB1tg5cCsTH~VNjts4taDTPWfDZmjtVaxxr\
PRII4NEDKqEzg3JBevM~yft-RDfMc8RVlm-gCGANrRQORFii7uD3o9~y~4P2tLnO7Fy3m5\
rdjRsOsWnCQZzw37mcBoT9rEZPrVpD8pjebJ1~HNc764xIpXDWVt8CbA==",
},
TestVector {
msg: "\0x00",
ct: "AHDZBKiWeaIY... |
// Check test vector
assert_eq!(dec.decrypt(&ct, true).unwrap(), msg);
} | random_line_split | |
elgamal.rs |
};
// γ = α^k mod p
let gamma = ELGAMAL_G.modpow(&k, &ELGAMAL_P);
(k, gamma)
}
/// Generates ElGamal keypairs.
pub struct KeyPairGenerator;
impl KeyPairGenerator {
/// ElGamal key generation, following algorithm 8.17.
pub fn generate() -> (PrivateKey, PublicKey) {
// Select a random... | {
break k;
} | conditional_block | |
elgamal.rs |
self.encrypt_basic(&data).map(|(gamma, delta)| {
if include_zeroes {
// ElGamal ciphertext:
// 0 1 257 258 514
// | 0 | padding zeroes | gamma | 0 | padding zeroes | delta |
let gamma = rect... | // Message must be no more than 222 bytes
if msg.len() > 222 {
return Err(Error::InvalidMessage);
}
let mut rng = OsRng;
let hash = Sha256::digest(msg);
// ElGamal plaintext:
// 0 1 33
// | nonzero byte | SHA256(msg) | msg... | identifier_body | |
elgamal.rs | (gamma, delta): (BigUint, BigUint)) -> Vec<u8> {
// γ^{-a} = γ^{p-1-a}
let gamma_neg_a = gamma.modpow(&(&(*ELGAMAL_PM1)).sub(&self.0), &ELGAMAL_P);
// m = (γ^{-a}) * δ mod p
let m = gamma_neg_a.mul(delta).rem(&(*ELGAMAL_P));
m.to_bytes_be()
}
/// ElGamal decryption us... | _basic(&self, | identifier_name | |
nelder_mead.rs | <Obs<Vec<f64>, V>>,
alpha: f64,
beta: f64,
gamma: f64,
delta: f64,
initial: Vec<Vec<f64>>,
centroid: Vec<f64>,
evaluating: Option<ObsId>,
state: State<V>,
}
impl<V> NelderMeadOptimizer<V>
where
V: Ord,
{
/// Makes a new `NelderMeadOptimizer`.
pub fn new<R: Rng>(params_domain:... | fn reflect_ask(&mut self) -> Vec<f64> {
self.centroid
.iter()
.zip(self.highest().param.iter())
.map(|(&x0, &xh)| x0 + self.alpha * (x0 - xh))
.collect()
}
fn reflect_tell(&mut self, obs: Obs<Vec<f64>, V>) {
if obs.value < self.lowest().value ... | self.simplex.push(obs);
if self.simplex.len() == self.dim() + 1 {
self.simplex.sort_by(|a, b| a.value.cmp(&b.value));
self.update_centroid();
self.state = State::Reflect;
}
}
| identifier_body |
nelder_mead.rs | <Obs<Vec<f64>, V>>,
alpha: f64,
beta: f64,
gamma: f64,
delta: f64,
initial: Vec<Vec<f64>>,
centroid: Vec<f64>,
evaluating: Option<ObsId>,
state: State<V>,
}
impl<V> NelderMeadOptimizer<V>
where
V: Ord,
{
/// Makes a new `NelderMeadOptimizer`.
pub fn new<R: Rng>(params_domain:... | .collect();
initial_simplex.push(x);
}
track!(Self::with_initial_simplex(params_domain, initial_simplex))
}
/// Makes a new `NelderMeadOptimizer` with the given simplex.
pub fn with_initial_simplex(
params_domain: Vec<ContinuousDomain>,
initial_si... | x0 })
| conditional_block |
nelder_mead.rs | > {
params_domain: Vec<ContinuousDomain>,
simplex: Vec<Obs<Vec<f64>, V>>,
alpha: f64,
beta: f64,
gamma: f64,
delta: f64,
initial: Vec<Vec<f64>>,
centroid: Vec<f64>,
evaluating: Option<ObsId>,
state: State<V>,
}
impl<V> NelderMeadOptimizer<V>
where
V: Ord,
{
/// Makes a ne... | lderMeadOptimizer<V | identifier_name | |
nelder_mead.rs | <Obs<Vec<f64>, V>>,
alpha: f64,
beta: f64,
gamma: f64,
delta: f64,
initial: Vec<Vec<f64>>,
centroid: Vec<f64>,
evaluating: Option<ObsId>,
state: State<V>,
}
impl<V> NelderMeadOptimizer<V>
where
V: Ord,
{
/// Makes a new `NelderMeadOptimizer`.
pub fn new<R: Rng>(params_domain:... | self.state = State::ContractInside(obs);
}
}
fn expand_ask(&mut self, prev: Vec<f64>) -> Vec<f64> {
self.centroid
.iter()
.zip(prev.iter())
.map(|(&c, &x)| c + self.beta * (x - c))
.collect()
}
fn expand_tell(&mut self, prev: ... | self.accept(obs);
} else if obs.value < self.highest().value {
self.state = State::ContractOutside(obs);
} else { | random_line_split |
from_module.go | .Diagnostics
// The way this function works is pretty ugly, but we accept it because
// -from-module is a less important case than normal module installation
// and so it's better to keep this ugly complexity out here rather than
// adding even more complexity to the normal module installer.
// The target direct... | if err != nil {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to create local modules directory",
fmt.Sprintf("Failed to create modules directory %s: %s.", modulesDir, err),
))
return diags
}
recordKeys := make([]string, 0, len(instManifest))
for k := range instManifest {
recordK... | // into the final directory structure.
err = os.MkdirAll(modulesDir, os.ModePerm) | random_line_split |
from_module.go | own Install notifications directly below.
wrapHooks := installHooksInitDir{
Wrapped: hooks,
}
getter := reusingGetter{}
_, instDiags := inst.installDescendentModules(fakeRootModule, rootDir, instManifest, true, wrapHooks, getter)
diags = append(diags, instDiags...)
if instDiags.HasErrors() {
return diags
}
... | {
if !strings.HasPrefix(moduleAddr, initFromModuleRootKeyPrefix) {
// We won't announce the root module, since hook implementations
// don't expect to see that and the caller will usually have produced
// its own user-facing notification about what it's doing anyway.
return
}
trimAddr := moduleAddr[len(init... | identifier_body | |
from_module.go | our
// installation process.
fakeRootModule := &tfconfig.Module{
ModuleCalls: map[string]*tfconfig.ModuleCall{
initFromModuleRootCallName: {
Name: initFromModuleRootCallName,
Source: sourceAddr,
Pos: fakePos,
},
},
}
// wrapHooks filters hook notifications to only include Download calls... | Download | identifier_name | |
from_module.go | .Diagnostics
// The way this function works is pretty ugly, but we accept it because
// -from-module is a less important case than normal module installation
// and so it's better to keep this ugly complexity out here rather than
// adding even more complexity to the normal module installer.
// The target direct... |
recordKeys := make([]string, 0, len(instManifest))
for k := range instManifest {
recordKeys = append(recordKeys, k)
}
sort.Strings(recordKeys)
for _, recordKey := range recordKeys {
record := instManifest[recordKey]
if record.Key == initFromModuleRootCallName {
// We've found the module the user reque... | {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to create local modules directory",
fmt.Sprintf("Failed to create modules directory %s: %s.", modulesDir, err),
))
return diags
} | conditional_block |
proxyserver.go | (servers []types.DatabaseServer) []types.DatabaseServer {
sort.Sort(types.DatabaseServers(servers))
return servers
}
var (
// mu protects the shuffleFunc global access.
mu sync.RWMutex
// shuffleFunc provides shuffle behavior for multiple database agents.
shuffleFunc ShuffleFunc = ShuffleRandom
)
// SetShuffleF... | ShuffleSort | identifier_name | |
proxyserver.go | return trace.BadParameter("missing AuthClient")
}
if c.Authorizer == nil {
return trace.BadParameter("missing Authorizer")
}
if c.Tunnel == nil {
return trace.BadParameter("missing Tunnel")
}
if c.TLSConfig == nil {
return trace.BadParameter("missing TLSConfig")
}
if c.Clock == nil {
c.Clock = clockwor... |
return trace.Wrap(err)
}
// Let the appropriate proxy handle the connection and go back
// to listening.
go func() {
defer clientConn.Close()
err := s.PostgresProxy().HandleConnection(s.closeCtx, clientConn)
if err != nil && !utils.IsOKNetworkError(err) {
s.log.WithError(err).Warn("Failed to ha... | {
return nil
} | conditional_block |
proxyserver.go | return trace.BadParameter("missing AuthClient")
}
if c.Authorizer == nil {
return trace.BadParameter("missing Authorizer")
}
if c.Tunnel == nil {
return trace.BadParameter("missing Tunnel")
}
if c.TLSConfig == nil {
return trace.BadParameter("missing TLSConfig")
}
if c.Clock == nil {
c.Clock = clockwor... |
// SQLServerProxy returns a new instance of the SQL Server protocol aware proxy.
func (s *ProxyServer) SQLServerProxy() *sqlserver.Proxy {
return &sqlserver.Proxy{
Middleware: s.middleware,
Service: s,
Log: s.log,
}
}
// Connect connects to the database server running on a remote cluster
// over rev... | Limiter: s.cfg.Limiter,
Log: s.log,
}
} | random_line_split |
proxyserver.go | SQLServerProxy returns a new instance of the SQL Server protocol aware proxy.
func (s *ProxyServer) SQLServerProxy() *sqlserver.Proxy {
return &sqlserver.Proxy{
Middleware: s.middleware,
Service: s,
Log: s.log,
}
}
// Connect connects to the database server running on a remote cluster
// over revers... | {
cluster, err := s.cfg.Tunnel.GetSite(identity.RouteToCluster)
if err != nil {
return nil, nil, trace.Wrap(err)
}
accessPoint, err := cluster.CachingAccessPoint()
if err != nil {
return nil, nil, trace.Wrap(err)
}
servers, err := accessPoint.GetDatabaseServers(ctx, apidefaults.Namespace)
if err != nil {
... | identifier_body | |
mod.rs | use std::char::{self, DecodeUtf16};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::Cloned;
use std::mem;
use std::ops::Deref;
use std::slice;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_ma... | use std::borrow::{Cow, Borrow}; | random_line_split | |
mod.rs | bool {
let weak: *const WeakAtom = self;
let other: *const WeakAtom = other;
weak == other
}
}
unsafe impl Send for Atom {}
unsafe impl Sync for Atom {}
unsafe impl Sync for WeakAtom {}
impl WeakAtom {
/// Construct a `WeakAtom` from a raw `nsAtom`.
#[inline]
pub unsafe fn new... | from | identifier_name | |
mod.rs | Hash, Hasher};
use std::iter::Cloned;
use std::mem;
use std::ops::Deref;
use std::slice;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs"));
}
#[macro_use]
pub mod namespace;
pub use self::namespace::{Namespac... |
/// Get the atom as a slice of utf-16 chars.
#[inline]
pub fn as_slice(&self) -> &[u16] {
unsafe {
slice::from_raw_parts((*self.as_ptr()).mString, self.len() as usize)
}
}
// NOTE: don't expose this, since it's slow, and easy to be misused.
fn chars(&self) -> Decod... | {
self.0.mHash
} | identifier_body |
di_tools.py | self):
d = {}
for cn in self.cols:
ci = self.cols[cn]
d[cn] = self.fields[ci]
return str(d)
def __repr__(self):
return self.__str__()
class _DelimitedFileReader:
def __init__(self, strip):
self.coldict = None
self.handle = None
self.line_reader = None
self.lineno = 0
self.strip = strip
self... | di_unpickle | identifier_name | |
di_tools.py | for l in lines:
l = l.strip()
if l.startswith("Name="):
l = l[6:-1]
cols[l.lower()] = i
i = i + 1
return cols
class ColAccessor:
"""This is a helper class that DictData will return an instance of
when it's being iterated over. Its job is to return the relevant value
when an unknown fieldname (wh... | key = [ r[x] for x in columns ]
value_columns = r.keys()[:]
for x in columns:
value_columns.remove(x)
values = dict([ (x, r[x]) for x in value_columns ])
hash[HashableList(key)] = values
hashes.append(hash)
for r in iterables[0]:
r = dict(r)
key = HashableList([ r[x] for x in columns ])
oops... | for r in iterable: | random_line_split |
di_tools.py | for l in lines:
l = l.strip()
if l.startswith("Name="):
l = l[6:-1]
cols[l.lower()] = i
i = i + 1
return cols
class ColAccessor:
"""This is a helper class that DictData will return an instance of
when it's being iterated over. Its job is to return the relevant value
when an unknown fieldname (wh... |
def __iter__(self):
return iter(self.list)
def di_pickle(o):
"""Given an object, which can be an integer, string, float, list,
tuple, set, frozenset, dictionary, ImmutableDict or any combination
thereof, return a string such that di_unpickle() will reconstruct
the object. The point, ofcourse, being that that d... | return self.list[i] | identifier_body |
di_tools.py | resolve_filename() and it'll
# pick the one with the highest timestamp.
resolve_filename_map = None # after init_resolve_filename, this will
# contain a mapping from lower-cases filename to a tuple with
# actual filename and timestamp
class DictedData_cb(_DelimitedFileReader):
"""This is a generalized DictedData... | j = j + 1 | conditional_block | |
post.go | IF NOT EXISTS admins (
username text PRIMARY KEY,
password text NOT NULL
)`
stmt, err = db.Prepare(create_q)
panicErr(err)
_, err = stmt.Exec()
panicErr(err)
// only these tables so far...
}
func initDbCmd() {
fmt.Print("initialising database...")
db := openSQL()
defer db.Close()
initDatabase(db)
f... | http.Error(w, "file type not allowed", 403) // 403 Forbidden
return false
}
if size > maxSize {
http.Error(w, "file too big", 403) // 403 Forbidden
return false
}
fname := strconv.FormatInt(uniqueTimestamp(), 10) + ext
fullname := pathSrcFile(board, fname)
tmpname := pathSrcFile(board, ".tmp."+f... | {
defer f.Close()
size, err := f.Seek(0, os.SEEK_END)
if err != nil {
http.Error(w, fmt.Sprintf("500 internal server error: %s", err), 500)
return false
}
_, err = f.Seek(0, os.SEEK_SET)
if err != nil {
http.Error(w, fmt.Sprintf("500 internal server error: %s", err), 500)
return false
}
ext... | conditional_block |
post.go | IF NOT EXISTS admins (
username text PRIMARY KEY,
password text NOT NULL
)`
stmt, err = db.Prepare(create_q)
panicErr(err)
_, err = stmt.Exec()
panicErr(err)
// only these tables so far...
}
func initDbCmd() {
fmt.Print("initialising database...")
db := openSQL()
defer db.Close()
initDatabase(db)
f... |
func (r *postResult) IsThread() bool {
return r.Thread == r.Post
}
func acceptPost(w http.ResponseWriter, r *http.Request, p *wPostInfo, board string, isop bool) bool {
var err error
err = r.ParseMultipartForm(1 << 20)
if err != nil {
http.Error(w, fmt.Sprintf("400 bad request: ParseMultipartForm failed: %s",... | {
return r.Thread != 0
} | identifier_body |
post.go | IF NOT EXISTS admins (
username text PRIMARY KEY,
password text NOT NULL
)`
stmt, err = db.Prepare(create_q)
panicErr(err)
_, err = stmt.Exec()
panicErr(err)
// only these tables so far...
}
func initDbCmd() {
fmt.Print("initialising database...")
db := openSQL()
defer db.Close()
initDatabase(db)
f... | (w http.ResponseWriter, r *http.Request) {
var board string
bname, ok := r.Form["name"]
if !ok {
http.Error(w, "400 bad request: no name field", 400)
return
}
board = bname[0]
db := openSQL()
defer db.Close()
ok = deleteBoard(db, board)
if !ok {
http.Error(w, "500 internal server error: board deletion... | postDelBoard | identifier_name |
post.go | IF NOT EXISTS admins (
username text PRIMARY KEY,
password text NOT NULL
)`
stmt, err = db.Prepare(create_q)
panicErr(err)
_, err = stmt.Exec()
panicErr(err)
// only these tables so far...
}
func initDbCmd() {
fmt.Print("initialising database...")
db := openSQL()
defer db.Close()
initDatabase(db)
f... | db := openSQL()
defer db.Close()
var bname string
var maxthreads sql.NullInt64
err |
func postNewThread(w http.ResponseWriter, r *http.Request, board string) {
var p wPostInfo
| random_line_split |
motor_tools.py |
except serial.SerialException:
print "%s is not a connected port, trying next.\n" %port
if x_port_flag is False or y_port_flag is False:
print "Connection failed waiting 5 seconds and trying again.\n"
try:
self.con1.close()
... | self.con2.port = '/dev/ttyUSB%s' %port
self.con2.open()
sleep(2)
sn = self._get_sn(self.con2)
if sn == 'unknown':
sn = self._get_sn(self.con2)
x_port_flag, y_port_flag = self.assign_serial_num... | conditional_block | |
motor_tools.py | a connected port, trying next.\n" %port
if x_port_flag is False or y_port_flag is False:
print "Connection failed waiting 5 seconds and trying again.\n"
try:
self.con1.close()
sleep(1)
self.con2.close()
sleep(1)
... | '''Return the current step or position 'P' of the motor. '''
self.flush()
self.con.write('PR P\r\n')# P is really the step
pat = '\-*[0-9]+\r\n'
output = self._loop_structure(pat)
return int(output.strip('\r\n'))
def _calc_steps(self,linear_dist):
''... |
def _get_current_step(self): | random_line_split |
motor_tools.py | connected port, trying next.\n" %port
if x_port_flag is False or y_port_flag is False:
print "Connection failed waiting 5 seconds and trying again.\n"
try:
self.con1.close()
sleep(1)
self.con2.close()
sleep(1)
... | (self, arg, echk = False):
'''Write a command to the motor where the lines feed and carriage return are automatically included.
This is unlike the primitive class pySerial where you must send the \r\n . '''
self.con.write("%s\r\n" %arg)
sleep(0.1)
list = self.con.readlines()
... | write | identifier_name |
motor_tools.py | _set_var() b/c there's not = sign used for this op
# sleep(0.1)
# self.write('PR EF')
# sleep(0.1)
# self.con.readlines()
def _set_step(self, step):
'''Set the number of steps that the motor uses for a full rotation. '''
if not isinstance(step,int):
prin... | '''Move the motor to an absolute position wrt to the limit switch HOME. '''
steps = self._calc_steps(pos)
self.con.write('MA %i\r\n' %steps)
sleep(0.1)
self._motor_stopped()
self._CurrentStep = self._get_current_step()
self.CurrentPos = float(self._calculate_pos(self._Cur... | identifier_body | |
parser.py | _text',
# 'regex', 'regex_re']
def __init__(self, rule_text):
self.raw_rule_text = rule_text
self.regex_re = None
rule_text = rule_text.strip()
self.is_comment = rule_text.startswith(('!', '[Adblock'))
if self.is_comment:
self.is_html_rule = self... | parts = domains.replace(',', '|').split('|')
return dict(cls._parse_option_negation(p) for p in parts)
@classmethod
def _parse_option_negation(cls, text):
return (text.lstrip('~'), not text.startswith('~'))
@classmethod
def _parse_option(cls, text):
if text.startswith("... | def _parse_domain_option(cls, text):
domains = text[len('domain='):] | random_line_split |
parser.py | _text',
# 'regex', 'regex_re']
def __init__(self, rule_text):
self.raw_rule_text = rule_text
self.regex_re = None
rule_text = rule_text.strip()
self.is_comment = rule_text.startswith(('!', '[Adblock'))
if self.is_comment:
self.is_html_rule = self... | (cls, text):
if text.startswith("domain="):
return ("domain", cls._parse_domain_option(text))
return cls._parse_option_negation(text)
@classmethod
def rule_to_regex(cls, rule):
"""
Convert AdBlock rule to a regular expression.
"""
if not rule:
... | _parse_option | identifier_name |
parser.py | _text',
# 'regex', 'regex_re']
def __init__(self, rule_text):
self.raw_rule_text = rule_text
self.regex_re = None
rule_text = rule_text.strip()
self.is_comment = rule_text.startswith(('!', '[Adblock'))
if self.is_comment:
self.is_html_rule = self... | >>> rule.matching_supported({'domain': 'example.com', 'third-party': False})
True
Rule is a comment:
>>> rule = AdblockRule("!this is not a rule")
>>> rule.matching_supported({})
False
"""
if self.is_comment:
return False
if self.is_... | """
Return whether this rule can return meaningful result,
given the `options` dict. If some options are missing,
then rule shouldn't be matched against, and this function
returns False.
No options:
>>> rule = AdblockRule("swf|")
>>> rule.matching_supported({})
... | identifier_body |
parser.py | :
if optname == 'match-case': # TODO
continue
if optname not in options:
raise ValueError("Rule requires option %s" % optname)
if optname == 'domain':
if not self._domain_matches(options['domain']):
return False
... | return True | conditional_block | |
lookup_ref_delta_objects.rs | use std::convert::TryInto;
use gix_hash::ObjectId;
use crate::data::{entry::Header, input};
/// An iterator to resolve thin packs on the fly.
pub struct LookupRefDeltaObjectsIter<I, LFn> {
/// The inner iterator whose entries we will resolve.
pub inner: I,
lookup: LFn,
/// The cached delta to provide... | Some(Ok(entry))
}
}
}
_ => {
if self.inserted_entries_length_in_bytes != 0 {
if let Header::OfsDelta { base_distance } = entry.header {
// We ha... | Some(base_entry) => {
let base_distance =
self.shifted_pack_offset(entry.pack_offset) - base_entry.shifted_pack_offset;
self.shift_entry_and_point_to_base_by_offset(&mut entry, base_distance); | random_line_split |
lookup_ref_delta_objects.rs | use std::convert::TryInto;
use gix_hash::ObjectId;
use crate::data::{entry::Header, input};
/// An iterator to resolve thin packs on the fly.
pub struct LookupRefDeltaObjectsIter<I, LFn> {
/// The inner iterator whose entries we will resolve.
pub inner: I,
lookup: LFn,
/// The cached delta to provide... | {
/// The original pack offset as mentioned in the entry we saw. This is used to find this as base object if deltas refer to it by
/// old offset.
pack_offset: u64,
/// The new pack offset that is the shifted location of the pack entry in the pack.
shifted_pack_offset: u64,
/// The size change ... | Change | identifier_name |
lookup_ref_delta_objects.rs | use std::convert::TryInto;
use gix_hash::ObjectId;
use crate::data::{entry::Header, input};
/// An iterator to resolve thin packs on the fly.
pub struct LookupRefDeltaObjectsIter<I, LFn> {
/// The inner iterator whose entries we will resolve.
pub inner: I,
lookup: LFn,
/// The cached delta to provide... |
}
#[derive(Debug)]
struct Change {
/// The original pack offset as mentioned in the entry we saw. This is used to find this as base object if deltas refer to it by
/// old offset.
pack_offset: u64,
/// The new pack offset that is the shifted location of the pack entry in the pack.
shifted_pack_off... | {
let (min, max) = self.inner.size_hint();
max.map_or_else(|| (min * 2, None), |max| (min, Some(max * 2)))
} | identifier_body |
ospf_sh_request_list.pb.go |
return ""
}
func (m *OspfShRequestList_KEYS) GetInterfaceName() string {
if m != nil {
return m.InterfaceName
}
return ""
}
func (m *OspfShRequestList_KEYS) GetNeighborAddress() string {
if m != nil {
return m.NeighborAddress
}
return ""
}
type OspfShLsaSum struct {
HeaderLsaType string `pro... | {
return m.VrfName
} | conditional_block | |
ospf_sh_request_list.pb.go | RequestList) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OspfShRequestList.Unmarshal(m, b)
}
func (m *OspfShRequestList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OspfShRequestList.Marshal(b, m, deterministic)
}
func (m *OspfShRequestList) XXX_Merge(src proto.Messag... | 0x9e, 0x13, 0x47, 0xa1, 0xbe, 0x68, 0xcb, 0xb3, 0x9f, 0x7d, 0x18, 0x85, 0xb4, 0xd7, 0x24, 0x38,
0x55, 0x39, 0x7b, 0x09, 0xa3, 0x0c, 0x85, 0x44, 0xe3, 0x2a, 0x76, 0x57, 0x86, 0x98, 0xc3, 0xb6,
0xfc, 0x91, 0xc4, 0xa7, 0x5d, 0x89, 0xec, 0x39, 0x9c, 0xdc, 0xf0, 0xc4, 0xb6, 0x8d, 0x3b, 0x5c, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.