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 |
|---|---|---|---|---|
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... | (projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects{
try!(writ... | projects_to_csv | identifier_name |
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... |
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 | // Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // 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 | // Copyright 2018 Istio 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 agreed to i... | (ctx context.Context, token, resourceName string, t time.Time) (*model.SecretItem, error) {
options := util.CertOptions{
Host: resourceName,
RSAKeySize: keySize,
}
// Generate the cert/key, send CSR to CA.
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
log.Errorf("Failed to generated key ... | generateSecret | identifier_name |
secretcache.go | // Copyright 2018 Istio 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 agreed to i... |
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 | // Copyright 2018 Istio 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 agreed to i... |
// 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 |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | 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 |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | 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 | use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x = ... | let sub = &s[0..2];
println!("{}", sub);
}
fn f60() {
let s = String::from("ENEEEEEE");
let sub = &s[0..3];
println!("{}", sub);
}
pub struct ClassName {
field: i32,
}
impl ClassName {
pub fn new(value: i32) -> ClassName {
ClassName {
field: value
}
}
... | }
fn f59() {
let s = String::from("EN中文"); | random_line_split |
main.rs |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | 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 | import os
import matplotlib.pyplot as plt
import numpy as np
from reinforcement_utils.reinforcement import ReinforcementLearning as rl
import torch
from scenario import scenario
# Setup
from setup.text import TextModelSetup, TextNetworkSetup
from setup.images import ImageModelSetup, ImageNetworkSetup
def load_scena... |
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... | 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 | import os
import matplotlib.pyplot as plt
import numpy as np
from reinforcement_utils.reinforcement import ReinforcementLearning as rl
import torch
from scenario import scenario
# Setup
from setup.text import TextModelSetup, TextNetworkSetup
from setup.images import ImageModelSetup, ImageNetworkSetup
def load_scena... |
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 | import os
import matplotlib.pyplot as plt
import numpy as np
from reinforcement_utils.reinforcement import ReinforcementLearning as rl
import torch
from scenario import scenario
# Setup
from setup.text import TextModelSetup, TextNetworkSetup
from setup.images import ImageModelSetup, ImageNetworkSetup
def load_scena... | ():
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 | import os
import matplotlib.pyplot as plt
import numpy as np
from reinforcement_utils.reinforcement import ReinforcementLearning as rl
import torch
from scenario import scenario
# Setup
from setup.text import TextModelSetup, TextNetworkSetup
from setup.images import ImageModelSetup, ImageNetworkSetup
def load_scena... |
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 | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | }
}
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 | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | (&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 | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... |
#[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 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time : 2018/12/14 9:21
# @Author : Despicable Me
# @Email :
# @File : svm_digits.py
# @Software: PyCharm
# @Explain :
from numpy import *
import matplotlib.pyplot as plt
def selectJrand(i, m):
j = i
while(j == i):
j = int(random.uniform(0, m))
... | 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 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time : 2018/12/14 9:21
# @Author : Despicable Me
# @Email :
# @File : svm_digits.py
# @Software: PyCharm
# @Explain :
from numpy import *
import matplotlib.pyplot as plt
def selectJrand(i, m):
j = i
while(j == i):
j = int(random.uniform(0, m))
... | 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 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time : 2018/12/14 9:21
# @Author : Despicable Me
# @Email :
# @File : svm_digits.py
# @Software: PyCharm
# @Explain :
from numpy import *
import matplotlib.pyplot as plt
def selectJrand(i, m):
j = i
while(j == i):
j = int(random.uniform(0, m))
... | 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 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time : 2018/12/14 9:21
# @Author : Despicable Me
# @Email :
# @File : svm_digits.py
# @Software: PyCharm
# @Explain :
from numpy import *
import matplotlib.pyplot as plt
def selectJrand(i, m):
j = i
while(j == i):
j = int(random.uniform(0, m))
... | 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 | /*!
* Boilerplate v3.0.2 by @wcweb
* Copyright 2013 wcweb.us.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @wcweb.
*/
if (typeof jQuery === "undefined") { throw new Error("It requires jQuery") }
var Rimifon = {
"Ads" : {},
"NewFl... | 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 | /*!
* Boilerplate v3.0.2 by @wcweb
* Copyright 2013 wcweb.us.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @wcweb.
*/
if (typeof jQuery === "undefined") { throw new Error("It requires jQuery") }
var Rimifon = {
"Ads" : {},
"NewFl... |
}
}
/*---------------------------------------------------------------------
Template Name: lim.it
Version: 1.0
Release Date: July 12, 2010
File: lim.it.js
Updated: 2010-07-12
Copyright (c) 2010 Chanry Ian - http://wcweb.us
---------------------------------------------------------... | {
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 | /*!
* Boilerplate v3.0.2 by @wcweb
* Copyright 2013 wcweb.us.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @wcweb.
*/
if (typeof jQuery === "undefined") { throw new Error("It requires jQuery") }
var Rimifon = {
"Ads" : {},
"NewFl... | 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 | /*!
* Boilerplate v3.0.2 by @wcweb
* Copyright 2013 wcweb.us.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @wcweb.
*/
if (typeof jQuery === "undefined") { throw new Error("It requires jQuery") }
var Rimifon = {
"Ads" : {},
"NewFl... | here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
var now = moment();
this.weekStart = this.options.weekStart || 1;
this.othersParams = this.options.otherParams || '' ;
this.url = this.opt... | , options);
this._defaults = defaults;
this._name = pluginName;
if(element) this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic | identifier_body |
heat_exchanger.py | import sys
from PyQt5.QtGui import QFont, QDoubleValidator # type: ignore
from PyQt5.QtWidgets import (QFileDialog, QHBoxLayout, QVBoxLayout, QCheckBox, # type: ignore
QLabel, QLineEdit, QPushButton, QGroupBox, QRadioButton, QComboBox, QMessageBox,
QFormLayout, QDialogButtonBox, QApplication, QDialog, QMainWi... | 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 | import sys
from PyQt5.QtGui import QFont, QDoubleValidator # type: ignore
from PyQt5.QtWidgets import (QFileDialog, QHBoxLayout, QVBoxLayout, QCheckBox, # type: ignore
QLabel, QLineEdit, QPushButton, QGroupBox, QRadioButton, QComboBox, QMessageBox,
QFormLayout, QDialogButtonBox, QApplication, QDialog, QMainWi... | 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 sys
from PyQt5.QtGui import QFont, QDoubleValidator # type: ignore
from PyQt5.QtWidgets import (QFileDialog, QHBoxLayout, QVBoxLayout, QCheckBox, # type: ignore
QLabel, QLineEdit, QPushButton, QGroupBox, QRadioButton, QComboBox, QMessageBox,
QFormLayout, QDialogButtonBox, QApplication, QDialog, QMainWi... | 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 | import sys
from PyQt5.QtGui import QFont, QDoubleValidator # type: ignore
from PyQt5.QtWidgets import (QFileDialog, QHBoxLayout, QVBoxLayout, QCheckBox, # type: ignore
QLabel, QLineEdit, QPushButton, QGroupBox, QRadioButton, QComboBox, QMessageBox,
QFormLayout, QDialogButtonBox, QApplication, QDialog, QMainWi... | 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 | //! The gamestate module defines the SharedGameState that will be
//! serialized by the server and sent to each client - informing
//! them of any updates to the game. The GameState itself is a
//! shared mutable pointer which in the client is shared between
//! the communication layer (TBD) and the ui layer. It repres... | () {
let board = Board::with_no_holes(3, 3, 3);
let gamestate = GameState::new(board, 4); // create game with 4 players
assert_eq!(gamestate.players.len(), 4);
// should have 6-n penguins per player
assert!(gamestate.players.iter().all(|(_, player)| player.penguins.len() == 2));... | test_new | identifier_name |
gamestate.rs | //! The gamestate module defines the SharedGameState that will be
//! serialized by the server and sent to each client - informing
//! them of any updates to the game. The GameState itself is a
//! shared mutable pointer which in the client is shared between
//! the communication layer (TBD) and the ui layer. It repres... |
}
impl GameState {
/// Create a new GameState with the given board and player_count. Generates new
/// player ids for the number of players given.
/// This will panic if player_count is < MIN_PLAYERS_PER_GAME or > MAX_PLAYERS_PER_GAME.
pub fn new(board: Board, player_count: usize) -> GameState {
... | {
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 | //! The gamestate module defines the SharedGameState that will be
//! serialized by the server and sent to each client - informing
//! them of any updates to the game. The GameState itself is a
//! shared mutable pointer which in the client is shared between
//! the communication layer (TBD) and the ui layer. It repres... |
self.players.remove(&player_id);
self.turn_order.retain(|id| *id != player_id);
// Now actually advance the turn after the player is removed to properly
// handle the case where we skip the turns of possibly multiple players
// whose penguins are all stuck.... | {
self.previous_turn_index();
} | conditional_block |
gamestate.rs | //! The gamestate module defines the SharedGameState that will be
//! serialized by the server and sent to each client - informing
//! them of any updates to the game. The GameState itself is a
//! shared mutable pointer which in the client is shared between
//! the communication layer (TBD) and the ui layer. It repres... | assert_eq!(gamestate.move_avatar_for_player_without_changing_turn(player_id, tile_0, tile_0), None);
assert_eq!(gamestate.move_avatar_for_player_without_changing_turn(player_id, tile_0, unreachable_tile), None);
// success, penguin should now be on tile 5
assert_eq!(gamestate.move_avata... | // Move failed: tile not reachable from tile 0 | random_line_split |
example.py | # Based on a SARSA implementation downloaded from https://github.com/lazyprogrammer/machine_learning_examples/blob/master/rl/sarsa.py
# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python
# https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python
# Modified a... | else:
result = "I haven't learned solving Gridworld in " + str(agent.max_steps) + " steps."
print(result)
# Animate the steps of the trained worker
print("Watch my exploration route... (close the plot window to contine)")
helperFunctions.animate_steps(agent, "Gridworld exploration trained worker", result)
print(... | random_line_split | |
example.py | # Based on a SARSA implementation downloaded from https://github.com/lazyprogrammer/machine_learning_examples/blob/master/rl/sarsa.py
# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python
# https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python
# Modified a... |
# 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 | # Program to be included in Ben's source code for zbumping.
# Re-Plots the guide_curves and a rough outline of the Engines
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import zbumper as zbum
import handpicking ... | #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 | # Program to be included in Ben's source code for zbumping.
# Re-Plots the guide_curves and a rough outline of the Engines
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import zbumper as zbum
import handpicking ... | (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 | # Program to be included in Ben's source code for zbumping.
# Re-Plots the guide_curves and a rough outline of the Engines
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import zbumper as zbum
import handpicking ... |
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 | # Program to be included in Ben's source code for zbumping.
# Re-Plots the guide_curves and a rough outline of the Engines
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import zbumper as zbum
import handpicking ... |
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 | module.exports = OsmPbfAnalyst;
const fs = require('fs');
const zlib = require('zlib');
const EventEmitter = require('events').EventEmitter;
const ProtocolBuffer = require('protobufjs');
const UiRender = require('./ui-render');
const Long = ProtocolBuffer.Long;
const FileFormat = ProtocolBuffer.loadProtoFile('./proto... | (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 | module.exports = OsmPbfAnalyst;
const fs = require('fs');
const zlib = require('zlib');
const EventEmitter = require('events').EventEmitter;
const ProtocolBuffer = require('protobufjs');
const UiRender = require('./ui-render');
const Long = ProtocolBuffer.Long;
const FileFormat = ProtocolBuffer.loadProtoFile('./proto... |
/**
* @private
* @method newMemoryObject
* @param uiEnabled {Boolean}
* @return {Object}
*/
const newMemoryObject = (uiEnabled) => {
const memory = {
internal: { pointer: 0, buffer: new Buffer(0), started: false, paused: false },
file: { name: '', size: 0, bytesRead: 0, chunkCount: 0, chunkSize: 0, opened:... | {
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 | module.exports = OsmPbfAnalyst;
const fs = require('fs');
const zlib = require('zlib');
const EventEmitter = require('events').EventEmitter;
const ProtocolBuffer = require('protobufjs');
const UiRender = require('./ui-render');
const Long = ProtocolBuffer.Long;
const FileFormat = ProtocolBuffer.loadProtoFile('./proto... | // 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 | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... | {
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 | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... |
}
}
let mut data = String::new();
data += "var data = [\n";
for arg in &args {
data += " {\"name\":\"";
data += &arg.to_string();
data += "\", \"values\":[\n";
let stars = &stars[arg];
for (i, star) in stars.iter().enumerate() {
data += ... | {
set.insert(Star {
time: now,
node: Default::default(),
});
} | conditional_block |
main.rs | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... | 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 | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... |
}
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 | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... |
#[test]
fn grass_block_condition() {
let table = loot_table("blocks/grass_block").unwrap_or_else(|| {
panic!(
"missing loot table for grass block\nnote: loaded keys: {:?}",
STORE.keys()
);
});
let mut rng = StepRng::new(0, 1);
... | {
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 | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... |
})
.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 | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... | // 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 | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... | <'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 | //! Implementation of an object indexer that stores everything in memory.
//!
//! This loads all the objects from disk into memory. Objects added to the index
//! are immediately written to disk as well.
//!
//! This is very inefficient and should be backed by proper database code at
//! some point.
use std::collectio... | /// 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 | //! Implementation of an object indexer that stores everything in memory.
//!
//! This loads all the objects from disk into memory. Objects added to the index
//! are immediately written to disk as well.
//!
//! This is very inefficient and should be backed by proper database code at
//! some point.
use std::collectio... | <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 | //! Implementation of an object indexer that stores everything in memory.
//!
//! This loads all the objects from disk into memory. Objects added to the index
//! are immediately written to disk as well.
//!
//! This is very inefficient and should be backed by proper database code at
//! some point.
use std::collectio... |
}
}
}
}
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 | // Copyright (c) 2016 Pani Networks
// 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 appli... |
// makeId generates uniq id from applied to field.
func makeId(allowedTo []common.Endpoint, name string) string {
var data string
data = name
for _, e := range allowedTo {
if data == "" {
data = fmt.Sprintf("%s", e)
} else {
data = fmt.Sprintf("%s\n%s", data, e)
}
}
hasher := sha1.New()
hasher.Wri... | {
log.Println("Entering policy.Initialize()")
err := policy.store.Connect()
if err != nil {
return err
}
policy.client = client
return nil
} | identifier_body |
policy.go | // Copyright (c) 2016 Pani Networks
// 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 appli... |
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 | // Copyright (c) 2016 Pani Networks
// 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 appli... | (client *common.RestClient) error {
log.Println("Entering policy.Initialize()")
err := policy.store.Connect()
if err != nil {
return err
}
policy.client = client
return nil
}
// makeId generates uniq id from applied to field.
func makeId(allowedTo []common.Endpoint, name string) string {
var data string
data... | Initialize | identifier_name |
policy.go | // Copyright (c) 2016 Pani Networks
// 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR ... | random_line_split | |
views.py | import uuid
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader
from django.urls import reverse
from AXF import order_status
from AXF.models import HomeWheel, Home... | # 密码错误
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 | import uuid
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader
from django.urls import reverse
from AXF import order_status
from AXF.models import HomeWheel, Home... | request):
user_id = request.session.get('user_id')
if not user_id:
return redirect(reverse('axf:user_login'))
o_status = request.GET.get('status')
if o_status:
orders = OrderModel.objects.filter(o_user_id=user_id).filter(o_status=o_status)
else:
orders = OrderModel.object... | order_list( | identifier_name |
views.py | import uuid
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader
from django.urls import reverse
from AXF import order_status
from AXF.models import HomeWheel, Home... | 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 | import uuid
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader
from django.urls import reverse
from AXF import order_status
from AXF.models import HomeWheel, Home... |
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 | //! Implementation of I2P's ElGamal public-key encryption scheme over the
//! 2048-bit MODP DH group.
//!
//! This implementation is not constant-time.
//!
//! Original implementation in Java I2P was based on algorithms 8.17 and 8.18
//! specified in section 8.4.1 of the Handbook of Applied Cryptography.
use num_bigin... | }
} |
// Check test vector
assert_eq!(dec.decrypt(&ct, true).unwrap(), msg);
} | random_line_split |
elgamal.rs | //! Implementation of I2P's ElGamal public-key encryption scheme over the
//! 2048-bit MODP DH group.
//!
//! This implementation is not constant-time.
//!
//! Original implementation in Java I2P was based on algorithms 8.17 and 8.18
//! specified in section 8.4.1 of the Handbook of Applied Cryptography.
use num_bigin... |
};
// γ = α^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 | //! Implementation of I2P's ElGamal public-key encryption scheme over the
//! 2048-bit MODP DH group.
//!
//! This implementation is not constant-time.
//!
//! Original implementation in Java I2P was based on algorithms 8.17 and 8.18
//! specified in section 8.4.1 of the Handbook of Applied Cryptography.
use num_bigin... | erive(Clone)]
pub struct Decryptor(BigUint);
impl<'a> From<&'a PrivateKey> for Decryptor {
fn from(priv_key: &PrivateKey) -> Self {
Decryptor(BigUint::from_bytes_be(&priv_key.0[..]))
}
}
impl Decryptor {
/// Basic ElGamal decryption, following algorithm 8.18 2).
fn decrypt_basic(&self, (gamma,... | // 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 | //! Implementation of I2P's ElGamal public-key encryption scheme over the
//! 2048-bit MODP DH group.
//!
//! This implementation is not constant-time.
//!
//! Original implementation in Java I2P was based on algorithms 8.17 and 8.18
//! specified in section 8.4.1 of the Handbook of Applied Cryptography.
use num_bigin... | (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 | //! Adaptive nelder-mead simplex algorithm.
//!
//! # References
//!
//! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS]
//! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm)
//! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–... | 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 | //! Adaptive nelder-mead simplex algorithm.
//!
//! # References
//!
//! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS]
//! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm)
//! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–... | .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 | //! Adaptive nelder-mead simplex algorithm.
//!
//! # References
//!
//! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS]
//! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm)
//! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–... | > {
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 | //! Adaptive nelder-mead simplex algorithm.
//!
//! # References
//!
//! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS]
//! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm)
//! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–... | 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 | package initwd
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
version "github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform-plugin-sdk/internal/modsd... | 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 | package initwd
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
version "github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform-plugin-sdk/internal/modsd... | {
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 | package initwd
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
version "github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform-plugin-sdk/internal/modsd... | (moduleAddr, packageAddr string, version *version.Version) {
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 ... | Download | identifier_name |
from_module.go | package initwd
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
version "github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform-plugin-sdk/internal/modsd... |
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 | /*
Copyright 2020-2021 Gravitational, Inc.
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 to in writing,... | (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 | /*
Copyright 2020-2021 Gravitational, Inc.
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 to in writing,... |
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 | /*
Copyright 2020-2021 Gravitational, Inc.
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 to in writing,... |
// 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 | /*
Copyright 2020-2021 Gravitational, Inc.
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 to in writing,... |
// getConfigForServer returns TLS config used for establishing connection
// to a remote database server over reverse tunnel.
func (s *ProxyServer) getConfigForServer(ctx context.Context, identity tlsca.Identity, server types.DatabaseServer) (*tls.Config, error) {
privateKeyBytes, _, err := native.GenerateKeyPair()
... | {
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 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... | 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 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... | (string: Cow<'a, str>) -> Atom {
Atom::from(&*string)
}
}
impl From<String> for Atom {
#[inline]
fn from(string: String) -> Atom {
Atom::from(&*string)
}
}
impl From<*mut nsAtom> for Atom {
#[inline]
fn from(ptr: *mut nsAtom) -> Atom {
assert!(!ptr.is_null());
u... | from | identifier_name |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... |
/// 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 | """This file contains some convenience functions. They are to be used, not be
freaked out about how they're implemented, although it is pretty clean IMHO.
Currently, it includes the DictedData class, which makes going over data with
a dictionary really easy. Given a dictionary in foo.dic, some data in
foo.txt, and two... | (s):
"""This is the converse of di_pickle(), or anything that encodes like
it. Given a string, reconstruct the encoded object."""
def do_unpickle(s):
if s[:4] == "None":
return None, s[4:]
if s[0] == 'i':
j = 1
if s[j] == '-':
negative = 1
j = j + 1
else:
negative = 0
while s[j].isdigi... | di_unpickle | identifier_name |
di_tools.py | """This file contains some convenience functions. They are to be used, not be
freaked out about how they're implemented, although it is pretty clean IMHO.
Currently, it includes the DictedData class, which makes going over data with
a dictionary really easy. Given a dictionary in foo.dic, some data in
foo.txt, and two... | 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 | """This file contains some convenience functions. They are to be used, not be
freaked out about how they're implemented, although it is pretty clean IMHO.
Currently, it includes the DictedData class, which makes going over data with
a dictionary really easy. Given a dictionary in foo.dic, some data in
foo.txt, and two... |
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 | """This file contains some convenience functions. They are to be used, not be
freaked out about how they're implemented, although it is pretty clean IMHO.
Currently, it includes the DictedData class, which makes going over data with
a dictionary really easy. Given a dictionary in foo.dic, some data in
foo.txt, and two... |
return s[2:j].replace("\\", ""), s[j + 1:]
if s[0] == 'D':
if s[1] != "(":
raise "Malformed input in di_unpickle()"
l = {}
s = s[2:]
while s[0] != ")":
key, s = do_unpickle(s)
value, s = do_unpickle(s)
if type(key) is types.ListType:
key = HashableList(key)
elif type(key) is t... | j = j + 1 | conditional_block |
post.go | package main
import (
"database/sql"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
)
const (
maxImageSize = 8 << 20
maxMusicSize = 50 << 20 // :^)
)
// nice place to also include file sizes
var allowedTypes = map[string]int64{
"image/gif": maxImageSize,
"image/jpe... |
return true
}
func postNewThread(w http.ResponseWriter, r *http.Request, board string) {
var p wPostInfo
db := openSQL()
defer db.Close()
var bname string
var maxthreads sql.NullInt64
err := db.QueryRow("SELECT name, maxthreads FROM boards WHERE name=$1", board).Scan(&bname, &maxthreads)
if err == sql.ErrN... | {
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 | package main
import (
"database/sql"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
)
const (
maxImageSize = 8 << 20
maxMusicSize = 50 << 20 // :^)
)
// nice place to also include file sizes
var allowedTypes = map[string]int64{
"image/gif": maxImageSize,
"image/jpe... |
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 | package main
import (
"database/sql"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
)
const (
maxImageSize = 8 << 20
maxMusicSize = 50 << 20 // :^)
)
// nice place to also include file sizes
var allowedTypes = map[string]int64{
"image/gif": maxImageSize,
"image/jpe... | (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 | package main
import (
"database/sql"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
)
const (
maxImageSize = 8 << 20
maxMusicSize = 50 << 20 // :^)
)
// nice place to also include file sizes
var allowedTypes = map[string]int64{
"image/gif": maxImageSize,
"image/jpe... | db := openSQL()
defer db.Close()
var bname string
var maxthreads sql.NullInt64
err := db.QueryRow("SELECT name, maxthreads FROM boards WHERE name=$1", board).Scan(&bname, &maxthreads)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
panicErr(err)
if !acceptPost(w, r, &p, board, true) {
return
}
... |
func postNewThread(w http.ResponseWriter, r *http.Request, board string) {
var p wPostInfo
| random_line_split |
motor_tools.py | import serial
import re
from time import sleep
import subprocess
from code_tools import CodeTools
import code_tools
class Connection(object):
def __init__(self):
self.con1 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)
self.con2 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)... |
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 | import serial
import re
from time import sleep
import subprocess
from code_tools import CodeTools
import code_tools
class Connection(object):
def __init__(self):
self.con1 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)
self.con2 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)... | '''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 | import serial
import re
from time import sleep
import subprocess
from code_tools import CodeTools
import code_tools
class Connection(object):
def __init__(self):
self.con1 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)
self.con2 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)... | (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 | import serial
import re
from time import sleep
import subprocess
from code_tools import CodeTools
import code_tools
class Connection(object):
def __init__(self):
self.con1 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)
self.con2 = serial.Serial(None, 9600, timeout = 0, writeTimeout = 0)... | '''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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import defaultdict
from functools import partial
from adblockparser.utils import split_data
class AdblockRule(object):
r"""
AdBlock Plus rule.
Check these links for the format details:
* https://adblockplus.org... | 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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import defaultdict
from functools import partial
from adblockparser.utils import split_data
class AdblockRule(object):
r"""
AdBlock Plus rule.
Check these links for the format details:
* https://adblockplus.org... | (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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import defaultdict
from functools import partial
from adblockparser.utils import split_data
class AdblockRule(object):
r"""
AdBlock Plus rule.
Check these links for the format details:
* https://adblockplus.org... |
@classmethod
def _split_options(cls, options_text):
return cls.OPTIONS_SPLIT_RE.split(options_text)
@classmethod
def _parse_domain_option(cls, text):
domains = text[len('domain='):]
parts = domains.replace(',', '|').split('|')
return dict(cls._parse_option_negation(p) ... | """
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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import defaultdict
from functools import partial
from adblockparser.utils import split_data
class AdblockRule(object):
r"""
AdBlock Plus rule.
Check these links for the format details:
* https://adblockplus.org... |
return False
def _is_whitelisted(self, url, options):
return self._matches(
url, options,
self.whitelist_re,
self.whitelist_require_domain,
self.whitelist_with_options
)
def _is_blacklisted(self, url, options):
return self._match... | 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 | /*
Copyright 2019 Cisco Systems
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 to in writing, software
d... |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.