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 |
|---|---|---|---|---|
athena_cli.py | csv.QUOTE_ALL)
if self.format == 'CSV_HEADER':
csv_writer.writerow(headers)
csv_writer.writerows([[text.encode("utf-8") for text in row] for row in self.athena.yield_rows(results, headers)])
elif self.format == 'TSV':
print(tabulate([row fo... | (self, arg):
help_output = """
Supported commands:
QUIT
SELECT
ALTER DATABASE <schema>
ALTER TABLE <table>
CREATE DATABASE <schema>
CREATE TABLE <table>
DESCRIBE <table>
DROP DATABASE <schema>
DROP TABLE <table>
MSCK REPAIR TABLE <table>
SHOW COLUMNS FROM <table>
SHOW CREATE TABLE <table>
SHOW DATABASES [LIKE <... | do_help | identifier_name |
athena_cli.py | csv.QUOTE_ALL)
if self.format == 'CSV_HEADER':
csv_writer.writerow(headers)
csv_writer.writerows([[text.encode("utf-8") for text in row] for row in self.athena.yield_rows(results, headers)])
elif self.format == 'TSV':
print(tabulate([row fo... |
See http://docs.aws.amazon.com/athena/latest/ug/language-reference.html
"""
print(help_output)
def do_quit(self, arg):
print()
return -1
def do_EOF(self, arg):
return self.do_quit(arg)
def do_use(self, schema):
self.dbname = schema.rstrip(';')
self.set_pr... | help_output = """
Supported commands:
QUIT
SELECT
ALTER DATABASE <schema>
ALTER TABLE <table>
CREATE DATABASE <schema>
CREATE TABLE <table>
DESCRIBE <table>
DROP DATABASE <schema>
DROP TABLE <table>
MSCK REPAIR TABLE <table>
SHOW COLUMNS FROM <table>
SHOW CREATE TABLE <table>
SHOW DATABASES [LIKE <pattern>]
SHOW PARTIT... | identifier_body |
athena_cli.py | csv.QUOTE_ALL)
if self.format == 'CSV_HEADER':
csv_writer.writerow(headers)
csv_writer.writerows([[text.encode("utf-8") for text in row] for row in self.athena.yield_rows(results, headers)])
elif self.format == 'TSV':
print(tabulate([row fo... |
else: # ALIGNED
print(tabulate([x for x in self.athena.yield_rows(results, headers)], headers=headers, tablefmt='presto'))
if status == 'FAILED':
print(stats['QueryExecution']['Status']['StateChangeReason'])
try:
del cmd.Cmd.do_show # "show" is an Athena command
... | for num, row in enumerate(self.athena.yield_rows(results, headers)):
print('--[RECORD {}]--'.format(num+1))
print(tabulate(zip(*[headers, row]), tablefmt='presto')) | conditional_block |
cfgparse.go | Type(fileType string) bool {
for _, value := range allowedTypes {
if value == fileType {
return true
}
}
return false
}
func getFileType(filename string) (string, error) {
fileType := filepath.Ext(filename)
if !isValidType(fileType) {
errMessage := "File type not supported. Supported types (" + strings.J... |
func getKeyValuefromSectionValue(sectionValue string, sep string, lineNo uint) (string, string) {
defer func() {
err := recover()
if err != nil {
errMessage := fmt.Sprintf("Config file format error at line no %d. Please format it correctly", lineNo)
panic(errMessage)
}
}()
keyValues := strings.Split(se... | {
if len(fileName) == 0 {
err := errors.New("file name cannot be empty")
return err
}
fileType, err := getFileType(fileName)
c.fileName = fileName
if err != nil {
return err
}
c.fileType = fileType
c.setDelimitor()
cfgFile, err := os.Open(fileName)
defer cfgFile.Close()
if err != nil {
return err
}
... | identifier_body |
cfgparse.go | }
numOfBytes = len(buff)
filePos = filePos + int64(numOfBytes) + 1
line := strings.TrimFunc(string(buff), unicode.IsSpace)
lineNo++
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if isSection(line) {
sectionHeader := sectionRegexp.FindStringSubmatch(line)[1]
curSection = section{}
... | isKeyValue | identifier_name | |
cfgparse.go | int64
var numOfBytes int
for {
buff, _, err := reader.ReadLine()
if err != nil {
break
}
if len(buff) == 0 {
filePos++
continue
}
numOfBytes = len(buff)
filePos = filePos + int64(numOfBytes) + 1
line := strings.TrimFunc(string(buff), unicode.IsSpace)
lineNo++
if strings.HasPrefix(line, "... | return match
} | random_line_split | |
cfgparse.go | (c *CfgParser) Parse(cfgFile *os.File) {
reader := bufio.NewReader(cfgFile)
var lineNo uint
var curSection section
var filePos int64
var numOfBytes int
for {
buff, _, err := reader.ReadLine()
if err != nil {
break
}
if len(buff) == 0 {
filePos++
continue
}
numOfBytes = len(buff)
filePos = ... | {
return c.sections[sectionName].filePosition, nil
} | conditional_block | |
partition_hash_test.go | BY HASH(col2) PARTITIONS 4;",
"CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATETIME) PARTITION BY HASH (YEAR(col3));",
"CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATETIME) PARTITION BY HASH (YEAR(col3) + col1 % (7*24));",
"CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATE) PARTITION BY LINEAR HASH( YEAR(c... | {
type kase struct {
sql string
def *plan.PartitionByDef
wantErr bool
}
kases := []kase{
{
sql: "create table a(col1 int) partition by hash(col1) (partition x1, partition x2);",
def: &plan.PartitionByDef{
PartitionNum: 2,
},
wantErr: false,
},
{
sql: "create table a(col1 int) ... | identifier_body | |
partition_hash_test.go | .Fatalf("%+v", err)
}
outPutPlan(logicPlan, true, t)
}
// -----------------------Hash Partition-------------------------------------
func TestHashPartition(t *testing.T) {
// HASH(expr) Partition
sqls := []string{
"CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1);",
"CREATE TABLE t1 (col1 INT, ... | (t *testing.T) {
// HASH(expr) Partition
sqls := []string{
"CREATE TABLE t2 (col1 INT, col2 CHAR(5)) " +
"PARTITION BY HASH(col1) PARTITIONS 1 " +
"( PARTITION p0 " +
"ENGINE = 'engine_name' " +
"COMMENT = 'p0_comment' " +
"DATA DIRECTORY = 'data_dir' " +
"INDEX DIRECTORY = 'data_dir' " +
"MAX_... | TestHashPartition2 | identifier_name |
partition_hash_test.go | .Fatalf("%+v", err)
}
outPutPlan(logicPlan, true, t)
}
// -----------------------Hash Partition-------------------------------------
func TestHashPartition(t *testing.T) {
// HASH(expr) Partition
sqls := []string{
"CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1);",
"CREATE TABLE t1 (col1 INT, ... |
`create table p_hash_table_03(
col1 bigint ,
col2 date default '1970-01-01',
col3 varchar(30)
)
partition by hash(col4)
partitions 8;`,
}
mock := NewMockOptimizer(false)
for _, sql := range sqls {
_, err := buildSingleStmt(mock, t, sql)
t.Log(sql)
require.NotNil(t, err)
t.Log(err)
... | separated DATE NOT NULL DEFAULT '9999-12-31',
job_code INT,
store_id INT
) PARTITION BY HASH(store_id) PARTITIONS 102400000000;`, | random_line_split |
partition_hash_test.go | .Fatalf("%+v", err)
}
outPutPlan(logicPlan, true, t)
}
// -----------------------Hash Partition-------------------------------------
func TestHashPartition(t *testing.T) {
// HASH(expr) Partition
sqls := []string{
"CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1);",
"CREATE TABLE t1 (col1 INT, ... |
}
func TestHashPartition2(t *testing.T) {
// HASH(expr) Partition
sqls := []string{
"CREATE TABLE t2 (col1 INT, col2 CHAR(5)) " +
"PARTITION BY HASH(col1) PARTITIONS 1 " +
"( PARTITION p0 " +
"ENGINE = 'engine_name' " +
"COMMENT = 'p0_comment' " +
"DATA DIRECTORY = 'data_dir' " +
"INDEX DIRECTOR... | {
t.Log(sql)
_, err := buildSingleStmt(mock, t, sql)
require.Nil(t, err)
if err != nil {
t.Fatalf("%+v", err)
}
} | conditional_block |
register.py | f_fn = open("first_name", "r")
all_fn = []
for line in f_fn.readlines():
if len(line) > 2 and "-" not in line:
all_fn.append(line.strip())
f_fn.close()
f_ln = open("last_name", "r")
all_ln = []
for line in f_ln.readlines():
if len(line) > 2 and "-" not in line:
... | ccount():
| identifier_name | |
register.py | _ln,1)[0]
return last_name
def mail_account(self,first_name,last_name):
mail_name = first_name.lower() + last_name.lower() + ''.join(random.sample(string.digits, 4))
return mail_name
ra = random_account()
header_dict = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11... | day = driver.find_element_by_id('day')
day.send_keys('1')
gender = driver.find_element_by_id('gender')
gender.send_keys('不愿透露')
personalDetailsNext = driver.find_element_by_id('personalDetailsNext')
personalDetailsNext.click()
elif headingText.text == "充分利用您的电话号码":
... | month.send_keys('1') | random_line_split |
register.py | ,1)[0]
return last_name
def mail_account(self,first_name,last_name):
mail_name = first_name.lower() + last_name.lower() + ''.join(random.sample(string.digits, 4))
return mail_name
ra = random_account()
header_dict = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0)... | ile&token=' + \
token+'&itemid='+ITEMID+'&excludeno='+EXCLUDENO
MOBILE1 = request.urlopen(request.Request(
url=url, headers=header_dict)).read().decode(encoding='utf-8')
if MOBILE1.split('|')[0] == 'success':
MOBILE = MOBILE1.split('|')[1]
print('获取号码是:\n'... | KN1+'。代码释义:1001:参数token不能为空;1002:参数action不能为空;1003:参数action错误;1004:token失效;1005:用户名或密码错误;1006:用户名不能为空;1007:密码不能为空;1008:账户余额不足;1009:账户被禁用;1010:参数错误;1011:账户待审核;1012:登录数达到上限')
return False
def getPhNumber():
if token.strip():
global phoneNumber, isRelese
EXCLUDENO = '' # 排除号段170_171
... | conditional_block |
register.py | ,1)[0]
return last_name
def mail_account(self,first_name,last_name):
mail_name = first_name.lower() + last_name.lower() + ''.join(random.sample(string.digits, 4))
return mail_name
ra = random_account()
header_dict = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0)... | isRelese = True
return True
else:
print('获取短信超时,错误代码是'+text1+',循环数是'+ROUND)
return False
else:
print('获取手机消息失败,token为空重新获取')
smsLogin()
return False
def releaseNumber():
url = 'http://api.fxhyd.cn/UserInterface.aspx?action=release... | TOKEN+'&itemid='+ITEMID+'&mobile='+MOBILE+'&release=1'
text1 = request.urlopen(request.Request(
url=url, headers=header_dict)).read().decode(encoding='utf-8')
TIME1 = time.time()
TIME2 = time.time()
ROUND = 1
while (TIME2-TIME1) < WAIT and not text1.split('|')[... | identifier_body |
webcam-local_folder-emotions-gdrive.py | , basename
from deepface import DeepFace
#Google authorisation
#----------------------
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("googlecreds.txt")
if gauth.credentials is None:
# Authenticate via google if they're not there, and get refresh token to automate token re... |
start_time_azure = time.time()
annotate_image(image)
end_time_azure = time.time()
print("time for azure model: ")
print(end_time_azure-start_time_azure)
#----Uncomment to also run deepface model
# ====================================================... | b = b[:-4] | conditional_block |
webcam-local_folder-emotions-gdrive.py | , basename
from deepface import DeepFace
#Google authorisation
#----------------------
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("googlecreds.txt")
if gauth.credentials is None:
# Authenticate via google if they're not there, and get refresh token to automate token re... | b = b[:-4]
start_time_azure = time.time()
annotate_image(image)
end_time_azure = time.time()
print("time for azure model: ")
print(end_time_azure-start_time_azure)
#----Uncomment to also run deepface model
# ==============================... | #label images without .jpg and call functions
for image in images:
b = os.path.basename(image)
if b.endswith('.jpg'): | random_line_split |
webcam-local_folder-emotions-gdrive.py | , basename
from deepface import DeepFace
#Google authorisation
#----------------------
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("googlecreds.txt")
if gauth.credentials is None:
# Authenticate via google if they're not there, and get refresh token to automate token re... |
#--------------------
def webcam_images_to_local_folders():
#function that takes webcam image and saves to local folder
#Define number of frames to be captured and interval
watch_time = 1 #in minutes
interval = 0.991442321 #Target of 1 fps, adjusted for average time taken in for loop
#nframes... | sys.stdout = sys.__stdout__ | identifier_body |
webcam-local_folder-emotions-gdrive.py | , basename
from deepface import DeepFace
#Google authorisation
#----------------------
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("googlecreds.txt")
if gauth.credentials is None:
# Authenticate via google if they're not there, and get refresh token to automate token re... | (image_url):
img = cv2.imread(image_url)
predictions = DeepFace.analyze(img) #uses FER2013 dataset and others; more accurate than I could get myself
print(predictions)
#Azure Face API for emotion detection
#(time for report: average time = 0.355s)
def annotate_image(image_url):
... | annotate_image_deepface | identifier_name |
mqtt_framework.py | qtt.reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions
log = getLogger(__name__)
class GenericMqttEndpoint:
def __init__(self, client_kwargs: dict, password_auth: dict, server_kwargs: dict, tls: bool):
"""
:param client_kwargs: See https://github.com/eclipse... |
return _subscribe_decorator
def publish(self, topic_pattern, *topic_data, **kwargs):
"""
:param topic_pattern: A topic pattern, e.g. a/+/c/#
:param topic_data: some elements matching the pattern, e.g. "b", ("d", "e")
:param kwargs: Passed to Client.publish(self, topic, pay... | setattr(func, _SUBSCRIBE_DECORATOR_NAME, (topic, kwargs))
# no @wraps
return func | identifier_body |
mqtt_framework.py | qtt.reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions
log = getLogger(__name__)
class GenericMqttEndpoint:
def __init__(self, client_kwargs: dict, password_auth: dict, server_kwargs: dict, tls: bool):
"""
:param client_kwargs: See https://github.com/eclipse... | raise Exception("The pattern has a component after a #: {!r}".format(cur_pattern))
except StopIteration:
# topic has been exhausted by list() enumeration, and pattern is empty, too.
return
else:
try:
cur_topic = next(topic_p... | if cur_pattern == "#":
yield list(topic_parts)
try:
cur_pattern = next(pattern_parts) | random_line_split |
mqtt_framework.py | .reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions
log = getLogger(__name__)
class GenericMqttEndpoint:
def __init__(self, client_kwargs: dict, password_auth: dict, server_kwargs: dict, tls: bool):
"""
:param client_kwargs: See https://github.com/eclipse/pa... | (pattern, topic):
"""
returns one string for each "+", followed by a list of strings when a trailing "#" is present
"""
pattern_parts = iter(pattern.split("/"))
topic_parts = iter(topic.split("/"))
while True:
try:
cur_pattern = next(pattern_parts)
except StopIteratio... | unpack_topic | identifier_name |
mqtt_framework.py | .reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions
log = getLogger(__name__)
class GenericMqttEndpoint:
def __init__(self, client_kwargs: dict, password_auth: dict, server_kwargs: dict, tls: bool):
"""
:param client_kwargs: See https://github.com/eclipse/pa... |
# this is done only once, not on every reconnect / resubscribe.
self._mqttc.message_callback_add(topic_pattern, create_caller(decorated_function))
def connect(self):
# currently, this will retry first connects, we don't need bettermqtt
self._mqttc.connect_async(**s... | decorated_function = attribute
topic_pattern, kwargs = getattr(decorated_function, _SUBSCRIBE_DECORATOR_NAME)
if topic_pattern in self._managed_subsciptions:
raise Exception(
"A client cannot subscribe to an identical topic filter multiple tim... | conditional_block |
skymotemanager.py | ridge(LJSocket = ljsocketAddress, serial = dev['serial'])
try:
d.ethernetFirmwareVersion()
except:
d.ethernetFWVersion = "(No Ethernet)"
d.nameCache = d.getName()
d.readSerialNumber()
d.usbFirmwareVersion()
d.mainFir... | def __init__(self, bridge):
threading.Thread.__init__(self)
self.daemon = True
self.bridge = bridge
self.name = sanitize(self.bridge.nameCache)
self.filename = "%%Y-%%m-%%d %%H__%%M__%%S %s %s.csv" % (self.name, "spontaneous")
self.filename = datetime.now().strftime(self.... | identifier_body | |
skymotemanager.py | str(int(value))
chType += " lqi"
return {'connection' : connection, 'state' : state, 'value' : dictValue, 'chType' : chType}
class SkyMoteManager(object):
def __init__(self, address = LJSOCKET_ADDRESS, port = LJSOCKET_PORT):
# The address and port to try to connect to LJSocket
self.ad... |
return results
def getBridge(self, serial):
if isinstance(serial, skymote.Bridge):
return serial
elif serial in self.bridges:
return self.bridges[serial]
else:
return self.bridges[str(serial)]
def getMote(self, b, un... | for mote in b.listMotes():
results[str(mote.moteId)] = mote.sensorSweep() | conditional_block |
skymotemanager.py |
if channelName == "Temperature":
dictValue = kelvinToFahrenheit(float(value) + 273.15)
state = (FLOAT_FORMAT % dictValue) + " °F"
elif channelName == "Vbatt":
state = (FLOAT_FORMAT % value) + " V"
chType += " vbatt"
elif channelName == "Bump":
chType = DIGITAL_IN... | def createFeedbackDict(channelName, value):
connection = channelName
state = FLOAT_FORMAT % value
dictValue = FLOAT_FORMAT % value
chType = ANALOG_TYPE | random_line_split | |
skymotemanager.py | (int(value))
chType += " lqi"
return {'connection' : connection, 'state' : state, 'value' : dictValue, 'chType' : chType}
class SkyMoteManager(object):
def __init__(self, address = LJSOCKET_ADDRESS, port = LJSOCKET_PORT):
# The address and port to try to connect to LJSocket
self.addres... | (self):
results = dict()
for b in self.bridges.values():
for mote in b.listMotes():
results[str(mote.moteId)] = mote.sensorSweep()
return results
def getBridge(self, serial):
if isinstance(serial, skymote.Bridge):
... | scan | identifier_name |
dz04.js | subIndex));
// [1, 1, 1, 1, 1]
// ================================================Задача 4 - 2
// Callback функция и метод push
// Функция isUniq принимает три параметра - element, index и arr.
// Функция возвращает true или false в зависимости от того встречается
// ли элемент первый раз в массиве(true)
// или э... | // inventory.add
// inventory.remove
//выступал объект inventory
// const inventory = {
// items: ['Knife', 'Gas mask'],
// add(itemName) {
// this.items.push(itemName);
// return `Adding ${itemName} to inventory`;
// },
// remove(itemName) {
// this.items = this.items.filter(it... |
// bind для замены this в методах объекта
// Оформи вызов метода invokeInventoryAction таким образом,
// чтобы в качестве this для методов | random_line_split |
gradebook.go | book
// by the instructor.
Date GradebookDate `xml:",attr"`
// DueDate is the date on which the assignment was due for the student.
DueDate GradebookDate `xml:",attr"`
// Score holds the student's earned and possible raw score of the assignment.
Score AssignmentScore `xml:",attr"`
// ScoreType is the kind of ... | {
fs := make([]float64, 0, len(strs))
for _, s := range strs {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
fs = append(fs, f)
}
return fs, nil
} | identifier_body | |
gradebook.go | category's weighted percentage and
// letter grade.
GradeSummaries []*AssignmentGradeCalc `xml:"GradeCalculationSummary>AssignmentGradeCalc"`
// Assignments holds all of the course's assignments for the grading period.
Assignments []*Assignment `xml:"Assignments>Assignment"`
}
// AssignmentGradeCalc represents o... | {
return err
} | conditional_block | |
gradebook.go | attr"`
}
// A Course represents one of a student's classes.
type Course struct {
// Period is the period of the day in which the student has this class.
Period int `xml:",attr"`
// ID holds identification information for this class, which includes
// its Name and ID within the school's/StudentVUE's systems.
ID C... | Notes string `xml:",attr"`
}
// A CourseID holds the identification information for a class.
type CourseID struct {
// ID is the school's/StudentVUE's internal ID for the class.
ID string
// Name is the official name of the class.
Name string
}
func (cid *CourseID) UnmarshalXMLAttr(attr xml.Attr) error {
const... | Points AssignmentPoints `xml:",attr"`
// Notes is any comment added by the instructor on the assignment entry. | random_line_split |
gradebook.go | awGradeScore float64 `xml:"CalculatedScoreRaw,attr"`
// GradeSummaries holds the grade summaries for each of the course's weighted categories.
// For example, if a course weighs Tests and Homework as separate categories, those will
// be contained here with information including the category's weighted percentage a... | UnmarshalXMLAttr | identifier_name | |
mod.rs | Define array index type
pub type ArrayIndex = usize;
/// The Piece type includes black and white
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum PieceType {
WHITE, BLACK
}
impl PieceType {
pub fn get_name(&self) -> &str {
match self {
PieceType::WHITE => "White",
PieceType::BLA... | (&self) -> board::BoardPieceType {
match self {
PieceType::BLACK => board::BoardPieceType::BLACK,
PieceType::WHITE => board::BoardPieceType::WHITE,
}
}
}
impl fmt::Display for PieceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self... | to_board_piece_type | identifier_name |
mod.rs | Define array index type
pub type ArrayIndex = usize;
/// The Piece type includes black and white
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum PieceType {
WHITE, BLACK
}
impl PieceType {
pub fn get_name(&self) -> &str {
match self {
PieceType::WHITE => "White",
PieceType::BLA... | self
}
/// Set the second player (Uses black piece)
pub fn set_second_player(&mut self, player_type: GameBuilderPlayerType) -> &mut Self {
self.second_player = player_type;
self
}
pub fn build(&self) -> Game {
Game::new(
GameBuilder::create_player(self.f... | pub fn set_first_player(&mut self, player_type: GameBuilderPlayerType) -> &mut Self {
self.first_player = player_type; | random_line_split |
mod.rs | same as Game struct
///
pub(in game) struct GameContext {
/// A board 2D array copy
board: Board,
/// None if it's first player point
last_point: Option<CoordinationFlat>,
/// Total pieces in the game
total_pieces: usize
}
impl GameContext {
pub fn new(board: Board, last_point: Option<Coo... | {
let mut a = self.board.get(next_coord.unwrap());
while next_coord.is_ok() && a.is_ok() && a.unwrap() == last_player_color {
score += 1;
next_coord = move_dir_reverse(&next_coord.unwrap(), dir);
a = self.boa... | conditional_block | |
mod.rs | array index type
pub type ArrayIndex = usize;
/// The Piece type includes black and white
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum PieceType {
WHITE, BLACK
}
impl PieceType {
pub fn get_name(&self) -> &str {
match self {
PieceType::WHITE => "White",
PieceType::BLACK => "... |
/// Get the current player
fn get_current_player(&self) -> &Box<Player> {
&self.players[self.current_player]
}
/// Get the current player mutable reference
fn get_current_player_mut(&mut self) -> &mut Box<Player> {
&mut self.players[self.current_player]
}
/// Check the ga... | {
if self.current_player == 0 {
&mut self.players[1]
} else {
&mut self.players[0]
}
} | identifier_body |
lib.rs | (Serialize, Deserialize)]
pub struct Site {
pub base_uri: String,
pub name: String,
pub proto: String,
pub description: String,
}
#[derive(Serialize, Deserialize)]
pub struct Data {
pub gpx_input: String,
pub img_input: String,
pub site_output: String,
}
#[derive(Serialize, Deserialize)]
p... | (dir: &Path) -> Vec<Photo> {
let mut photos: Vec<Photo> = Vec::new();
unsafe {
gexiv2_sys::gexiv2_log_set_level(gexiv2_sys::GExiv2LogLevel::MUTE);
}
for entry in fs::read_dir(dir).unwrap() {
let img_path = entry.unwrap().path();
let file_metadata = rexiv2::Metadata::new_from_pa... | parse_photos | identifier_name |
lib.rs | (Serialize, Deserialize)]
pub struct Site {
pub base_uri: String,
pub name: String,
pub proto: String,
pub description: String,
}
#[derive(Serialize, Deserialize)]
pub struct Data {
pub gpx_input: String,
pub img_input: String,
pub site_output: String,
}
#[derive(Serialize, Deserialize)]
p... |
None
}
pub fn parse_photos(dir: &Path) -> Vec<Photo> {
let mut photos: Vec<Photo> = Vec::new();
unsafe {
gexiv2_sys::gexiv2_log_set_level(gexiv2_sys::GExiv2LogLevel::MUTE);
}
for entry in fs::read_dir(dir).unwrap() {
let img_path = entry.unwrap().path();
let file_metadat... | {
res.sort_unstable_by_key(|r| r.datetime.timestamp());
return Some(res);
} | conditional_block |
lib.rs | use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use tera::{compile_templates, Context, Tera};
#[derive(Serialize, Deserialize)]
pub struct Coordinate {
lon: f64,
lat: f64,
}
pub struct Photo {
path: PathBuf,
datetime: Naive... | use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File; | random_line_split | |
TextDbBase.py | ON %s (url );''' ),
("%s_title_index" % self.tableName, self.tableName, '''CREATE INDEX %s ON %s (title );''' ),
("%s_fhash_index" % self.tableName, self.tableName, '''CREATE INDEX %s ON %s (fhash );''' ),
("%s_title_coll_index" % self.tableName, self.tableName, '''CREATE INDEX %s ON %... | (self, returning=None, **kwargs):
cols = [self.table.src]
vals = [self.tableKey]
if 'url' in kwargs:
cols.append(self.table.netloc)
vals.append(urllib.parse.urlparse(kwargs['url']).netloc.lower())
for key, val in kwargs.items():
key = key.lower()
if key not in self.colMap:
raise ValueError(... | sqlBuildInsertArgs | identifier_name |
TextDbBase.py | for line in traceback.format_exc().split("\n"):
self.log.error(line)
else:
with self.transaction(commit=commit) as cur:
if distance != None:
self.updateDistance(cur, distance, **kwargs)
cur.execute(query, queryArguments)
try:
self.insertDelta(cursor=cur, **kwargs)
except ValueError... | self.log.error('')
self.log.error('')
self.log.error("WAT")
self.log.error('')
self.log.error(traceback.format_stack())
self.log.error('') | conditional_block | |
TextDbBase.py | # Only pass commit=False if the calling code can gaurantee it'll call commit() itself within a reasonable timeframe.
def insertIntoDb(self, commit=True, cursor=None, **kwargs):
query, queryArguments = self.sqlBuildInsertArgs(returning=[self.table.dbid], **kwargs)
if self.QUERY_DEBUG:
print("Query = ", query)
... | dbid, dummy_havePath, dummy_haveCtnt, dummy_haveMime = row | random_line_split | |
TextDbBase.py | and self.tableKey:
kwargs["src"] = self.tableKey
where = self.sqlBuildConditional(**kwargs)
wantCols = (
self.table.dbid,
self.table.src,
self.table.dlstate,
self.table.url,
self.table.title,
self.table.series,
self.table.contents,
self.table.istext,
self.table.fhash,
... | if 'istext' in kwargs and not kwargs['istext']:
return
if not 'contents' in kwargs:
return
if 'url' in kwargs:
old = self.getRowByValue(url=kwargs['url'], cursor=cursor)
elif 'dbid' in kwargs:
old = self.getRowByValue(dbid=kwargs['dbid'], cursor=cursor)
else:
raise ValueError("No identifying in... | identifier_body | |
stateless.rs | accumulator::*;
/// At the moment, this particular struct resembles more closely an NFT.
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Default, Clone, Encode, Decode, PartialEq, Eq, Copy)]
pub struct UTXO {
pub_key: H256,
id: u64,
}
/// Primitive transaction model with one input and one output.
#[cfg_... | {
input: UTXO,
output: UTXO,
witness: Vec<u8>,
// Would in practice include a signature here.
}
pub trait Trait: system::Trait {
type Event: From<Event> + Into<<Self as system::Trait>::Event>;
}
decl_storage! {
trait Store for Module<T: Trait> as Stateless {
State get(get_state): U204... | Transaction | identifier_name |
stateless.rs | use accumulator::*;
/// At the moment, this particular struct resembles more closely an NFT.
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Default, Clone, Encode, Decode, PartialEq, Eq, Copy)]
pub struct UTXO {
pub_key: H256,
id: u64,
}
/// Primitive transaction model with one input and one output.
#[c... | /// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// Initialize generic event
fn deposit_event() = default;
/// Receive request to execute a transaction.
/// Verify the contents of a transaction and temporarily add it to a queue of v... | decl_module! { | random_line_split |
stateless.rs | accumulator::*;
/// At the moment, this particular struct resembles more closely an NFT.
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Default, Clone, Encode, Decode, PartialEq, Eq, Copy)]
pub struct UTXO {
pub_key: H256,
id: u64,
}
/// Primitive transaction model with one input and one output.
#[cfg_... |
#[test]
fn test_del() {
with_externalities(&mut new_test_ext(), || {
let elems = vec![U2048::from(3), U2048::from(5), U2048::from(7)];
// Collect witnesses for the added elements
let witnesses = witnesses::create_all_mem_wit(Stateless::get_state(), &elems);
... | {
with_externalities(&mut new_test_ext(), || {
let elems = vec![U2048::from(3), U2048::from(5), U2048::from(7)];
let (state, _, _) = accumulator::batch_add(Stateless::get_state(), &elems);
assert_eq!(state, U2048::from(5));
});
} | identifier_body |
worker.go | protobuf/types/known/timestamppb"
)
const (
// batchSize is the number of chunks to read from Spanner at a time.
batchSize = 10
// TargetTaskDuration is the desired duration of a re-clustering task.
// If a task completes before the reclustering run has completed, a
// continuation task will be scheduled.
//
/... |
// softEndTime is the (soft) deadline for the run.
softEndTime := clock.Now(ctx).Add(duration)
if runEndTime.Before(softEndTime) {
// Stop by the run end time.
softEndTime = runEndTime
}
var done bool
for clock.Now(ctx).Before(softEndTime) && !done {
err := retry.Retry(ctx, transient.Only(retry.Default), ... | task: task,
nextReportDue: task.State.NextReportDue.AsTime(),
currentChunkID: task.State.CurrentChunkId,
} | random_line_split |
worker.go | protobuf/types/known/timestamppb"
)
const (
// batchSize is the number of chunks to read from Spanner at a time.
batchSize = 10
// TargetTaskDuration is the desired duration of a re-clustering task.
// If a task completes before the reclustering run has completed, a
// continuation task will be scheduled.
//
/... |
pendingUpdates = NewPendingUpdates(ctx)
// Advance our position only on successful commit.
t.currentChunkID = entry.ChunkID
if err := t.calculateAndReportProgress(ctx); err != nil {
return false, err
}
}
}
// More to do.
return false, nil
}
// calculateAndReportProgress reports progress on ... | {
if err == UpdateRaceErr {
// Our update raced with another update.
// This is retriable if we re-read the chunk again.
err = transient.Tag.Apply(err)
}
return false, err
} | conditional_block |
worker.go | protobuf/types/known/timestamppb"
)
const (
// batchSize is the number of chunks to read from Spanner at a time.
batchSize = 10
// TargetTaskDuration is the desired duration of a re-clustering task.
// If a task completes before the reclustering run has completed, a
// continuation task will be scheduled.
//
/... | (ctx context.Context) (done bool, err error) {
ctx, s := trace.StartSpan(ctx, "go.chromium.org/luci/analysis/internal/clustering/reclustering.recluster")
s.Attribute("project", t.task.Project)
s.Attribute("currentChunkID", t.currentChunkID)
defer func() { s.End(err) }()
readOpts := state.ReadNextOptions{
StartC... | recluster | identifier_name |
worker.go | GAE autoscaling,
// autoscaling work best when tasks are relatively small (so that work
// can be moved between instances in real time).
func (w *Worker) Do(ctx context.Context, task *taskspb.ReclusterChunks, duration time.Duration) (*taskspb.ReclusterChunks, error) {
if task.State == nil {
return nil, errors.New("... | {
nextID, err := chunkIDAsBigInt(nextChunkID)
if err != nil {
return 0, err
}
startID, err := chunkIDAsBigInt(task.StartChunkId)
if err != nil {
return 0, err
}
endID, err := chunkIDAsBigInt(task.EndChunkId)
if err != nil {
return 0, err
}
if startID.Cmp(endID) >= 0 {
return 0, fmt.Errorf("end chunk I... | identifier_body | |
upgrade_region.go | Upgrade configuration by reading BOM file to get the providers versions
// b) Get the providers information from the management cluster
// c) Prepare the providers upgrade information
// d) Call the clusterctl ApplyUpgrade() to upgrade providers
// e) Wait for providers to be up and running
// 2. call the UpgradeC... | }
// getProvidersUpgradeInfo prepares the upgrade information by comparing the provider current version with and the upgradable version
// obtained from the BOM file.
func (c *TkgClient) getProvidersUpgradeInfo(regionalClusterClient clusterclient.Client, bomConfig *tkgconfigbom.BOMConfiguration) (*providersUpgradeInf... | {
puo := &ApplyProvidersUpgradeOptions{}
puo.ManagementGroup = pUpgradeInfo.managementGroup
for i := range pUpgradeInfo.providers {
instanceVersion := pUpgradeInfo.providers[i].Namespace + "/" + pUpgradeInfo.providers[i].ProviderName + ":" + pUpgradeInfo.providers[i].Version
switch clusterctlv1.ProviderType(pUp... | identifier_body |
upgrade_region.go | != nil {
return errors.Wrap(err, "failed to get providers upgrade information")
}
if len(pUpgradeInfo.providers) == 0 {
log.Infof("All providers are up to date...")
return nil
}
pUpgradeApplyOptions, err := c.GenerateProvidersUpgradeOptions(pUpgradeInfo)
if err != nil {
return errors.Wrap(err, "failed to... | getPackageInstallTimeoutFromConfig | identifier_name | |
upgrade_region.go | Upgrade configuration by reading BOM file to get the providers versions
// b) Get the providers information from the management cluster
// c) Prepare the providers upgrade information
// d) Call the clusterctl ApplyUpgrade() to upgrade providers
// e) Wait for providers to be up and running
// 2. call the UpgradeC... |
if isPacific {
return errors.New("upgrading 'Tanzu Kubernetes Cluster service for vSphere' management cluster is not yet supported")
}
// Validate the compatibility before upgrading management cluster
err = c.validateCompatibilityBeforeManagementClusterUpgrade(options, regionalClusterClient)
if err != nil {
... | {
return errors.Wrap(err, "error determining 'Tanzu Kubernetes Cluster service for vSphere' management cluster")
} | conditional_block |
upgrade_region.go | the Upgrade configuration by reading BOM file to get the providers versions
// b) Get the providers information from the management cluster
// c) Prepare the providers upgrade information
// d) Call the clusterctl ApplyUpgrade() to upgrade providers
// e) Wait for providers to be up and running
// 2. call the Upgr... | instanceVersion := pUpgradeInfo.providers[i].Namespace + "/" + pUpgradeInfo.providers[i].ProviderName + ":" + pUpgradeInfo.providers[i].Version
switch clusterctlv1.ProviderType(pUpgradeInfo.providers[i].Type) {
case clusterctlv1.CoreProviderType:
puo.CoreProvider = instanceVersion
case clusterctlv1.Bootstrap... | func (c *TkgClient) GenerateProvidersUpgradeOptions(pUpgradeInfo *providersUpgradeInfo) (*ApplyProvidersUpgradeOptions, error) {
puo := &ApplyProvidersUpgradeOptions{}
puo.ManagementGroup = pUpgradeInfo.managementGroup
for i := range pUpgradeInfo.providers { | random_line_split |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... | }
fn support_target_description_xml_override(
&mut self,
) -> Option<TargetDescriptionXmlOverrideOps<'_, Self>> {
Some(self)
}
fn support_breakpoints(&mut self) -> Option<BreakpointsOps<'_, Self>> {
Some(self)
}
fn support_memory_map(&mut self) -> Option<MemoryMapO... | type Arch = RuntimeArch;
type Error = Error;
fn base_ops(&mut self) -> BaseOps<'_, Self::Arch, Self::Error> {
BaseOps::MultiThread(self) | random_line_split |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... | <'a> {
/// The probe-rs session object
session: &'a Mutex<Session>,
/// A list of core IDs for this stub
cores: Vec<usize>,
/// TCP listener accepting incoming connections
listener: TcpListener,
/// The current GDB stub state machine
gdb: Option<GdbStubStateMachine<'a, RuntimeTarget<'a>... | RuntimeTarget | identifier_name |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... |
HaltReason::Step => MultiThreadStopReason::DoneStep,
_ => MultiThreadStopReason::SignalWithThread {
tid,
signal: Signal::SIGINT,
... | {
// Some architectures do not allow us to distinguish between hardware and software breakpoints, so we just treat `Unknown` as hardware breakpoints.
MultiThreadStopReason::HwBreak(tid)
} | conditional_block |
packet_codec.rs | Data>>,
>,
is_client: bool,
connection: &ConnectionValue<CM::AssociatedData>,
_: SocketAddr,
mut packet: InPacket,
) -> Result<()>
{
let con2 = connection.downgrade();
let packet_sink = con2.as_packet_sink();
let mut con = connection.mutex.lock();
let con = &mut *con;
let packet_res;
let mut ack... | con.1.resender.ack_packet(p_type, ack_id);
} else if p_type.is_voice() {
// Seems to work better without assembling the first 3 voice packets
// Use handle_voice_packet to assemble fragmented voice packets
/*let mut res = Self::handle_voice_packet(&logger, params, &header, p_data);
le... | PacketType::CommandLow
};
| conditional_block |
packet_codec.rs | (
&mut self,
(addr, packet): (SocketAddr, InPacket),
) -> impl Future<Item = (), Error = Error>
{
// Find the right connection
let cons = self.connections.read();
if let Some(con) =
cons.get(&CM::get_connection_key(addr, &packet)).cloned()
{
// If we are a client and have only a single connection, w... | handle_udp_packet | identifier_name | |
packet_codec.rs | packet,
)
.into_future()
} else {
drop(cons);
let is_client = self.is_client;
tokio::spawn(future::lazy(move || {
if let Err(e) = Self::connection_handle_udp_packet(
&logger,
in_packet_observer,
in_command_observer,
is_client,
&con,
addr,
packet... | {
// Find the right connection
let cons = self.connections.read();
if let Some(con) =
cons.get(&CM::get_connection_key(addr, &packet)).cloned()
{
// If we are a client and have only a single connection, we will do the
// work inside this future and not spawn a new one.
let logger = self.logger.new(o... | identifier_body | |
packet_codec.rs | logger: &Logger,
in_packet_observer: LockedHashMap<
String,
Box<InPacketObserver<CM::AssociatedData>>,
>,
in_command_observer: LockedHashMap<
String,
Box<InCommandObserver<CM::AssociatedData>>,
>,
is_client: bool,
connection: &ConnectionValue<CM::AssociatedData>,
_: SocketAddr,
mut packet:... | random_line_split | ||
build_all.py | JAVA_HOME = '/Program Files/Eclipse Adoptium/jdk-8.0.362.9-hotspot/'
else:
CMAKE_BUILD_ENV_ROOT = os.path.join(os.environ['HOME'], 'cmake_build_env_root')
if sys.platform == 'linux':
CUDA_ROOT = '/usr/local/cuda-11'
JAVA_HOME = '/opt/jdk/8'
elif sys.platform == 'darwin':
JAVA_HOM... | random_line_split | ||
build_all.py | win32':
return (os.path.join(base_path, 'include'), os.path.join(base_path, 'libs', f'python{py_ver[0]}{py_ver[1]}.lib'))
# for some reason python versions for python <=3.7 contain 'm' suffix
python_sub_name = f'python{py_ver[0]}.{py_ver[1]}' + ('m' if py_ver <= (3,7) else '')
if sys.platform == '... |
if not dry_run:
subprocess.check_call(cmd)
def get_exe_files(system:str, name:str) -> List[str]:
return [name + '.exe' if system == 'windows' else name]
def get_static_lib_files(system:str, name:str) -> List[str]:
prefix = '' if system == 'windows' else 'lib'
suffix = '.lib' if syste... | logging.info(' '.join(cmd)) | conditional_block |
build_all.py | win32':
return (os.path.join(base_path, 'include'), os.path.join(base_path, 'libs', f'python{py_ver[0]}{py_ver[1]}.lib'))
# for some reason python versions for python <=3.7 contain 'm' suffix
python_sub_name = f'python{py_ver[0]}.{py_ver[1]}' + ('m' if py_ver <= (3,7) else '')
if sys.platform == '... | (system:str, name:str) -> List[str]:
return [name + '.exe' if system == 'windows' else name]
def get_static_lib_files(system:str, name:str) -> List[str]:
prefix = '' if system == 'windows' else 'lib'
suffix = '.lib' if system == 'windows' else '.a'
return [prefix + name + sub_suffix + suffix for sub_su... | get_exe_files | identifier_name |
build_all.py | win32':
return (os.path.join(base_path, 'include'), os.path.join(base_path, 'libs', f'python{py_ver[0]}{py_ver[1]}.lib'))
# for some reason python versions for python <=3.7 contain 'm' suffix
python_sub_name = f'python{py_ver[0]}.{py_ver[1]}' + ('m' if py_ver <= (3,7) else '')
if sys.platform == '... |
def get_python_plat_name(platform_name: str):
system, arch = platform_name.split('-')
if system == 'windows':
return 'win_amd64'
elif system == 'darwin':
return 'macosx_11_0_universal2'
else: # linux
return 'manylinux2014_' + arch
def build_r_package(src_root_dir: str, build... | distutils.file_util.copy_file(
src=os.path.join(src_root_dir, 'ci', 'cmake', 'cuda.cmake'),
dst=os.path.join(src_root_dir, 'cmake', 'cuda.cmake'),
verbose=verbose,
dry_run=dry_run
) | identifier_body |
greyhound.go | ev3.CheckDriver(devs.OutA, ev3.DriverRcxMotor, ev3.OutA)
ev3.CheckDriver(devs.OutB, ev3.DriverRcxMotor, ev3.OutB)
ev3.CheckDriver(devs.OutC, ev3.DriverRcxMotor, ev3.OutC)
ev3.CheckDriver(devs.OutD, ev3.DriverRcxMotor, ev3.OutD)
// Check sensors
ev3.CheckDriver(devs.In1, ev3.DriverColor, ev3.In1)
ev3.CheckDriver... | switch sensorRead {
case sensorReadZero:
case sensorReadB:
case sensorReadF:
// Out
out = true
pos, hint, cross = 0, 0, false
case sensorReadR:
pos = conf.SensorRadius*2 + distanceFromSensor(r)
hint = 0
cross, out = false, false
case sensorReadRB:
pos = conf.SensorRadius + positionBetweenSensors(b, ... | sensorRead |= bitF
}
| random_line_split |
greyhound.go | ev3.CheckDriver(devs.OutA, ev3.DriverRcxMotor, ev3.OutA)
ev3.CheckDriver(devs.OutB, ev3.DriverRcxMotor, ev3.OutB)
ev3.CheckDriver(devs.OutC, ev3.DriverRcxMotor, ev3.OutC)
ev3.CheckDriver(devs.OutD, ev3.DriverRcxMotor, ev3.OutD)
// Check sensors
ev3.CheckDriver(devs.In1, ev3.DriverColor, ev3.In1)
ev3.CheckDriver... | () int {
return timespanAsTicks(initializationTime, time.Now())
}
func ticksToMillis(ticks int) int {
return ticks / 1000
}
func print(data ...interface{}) {
fmt.Fprintln(os.Stderr, data...)
}
func quit(data ...interface{}) {
close()
log.Fatalln(data...)
}
func waitEnter() {
// Let the button be released if ne... | currentTicks | identifier_name |
greyhound.go | 3.CheckDriver(devs.OutA, ev3.DriverRcxMotor, ev3.OutA)
ev3.CheckDriver(devs.OutB, ev3.DriverRcxMotor, ev3.OutB)
ev3.CheckDriver(devs.OutC, ev3.DriverRcxMotor, ev3.OutC)
ev3.CheckDriver(devs.OutD, ev3.DriverRcxMotor, ev3.OutD)
// Check sensors
ev3.CheckDriver(devs.In1, ev3.DriverColor, ev3.In1)
ev3.CheckDriver(de... |
func distanceFromSensor(value int) int {
return value * conf.SensorRadius / conf.SensorSpan
}
func positionBetweenSensors(value1 int, value2 int) int {
return (value1 - value2) * conf.SensorRadius / conf.SensorSpan
}
func sign(value int) int {
if value > 0 {
return 1
} else if value < 0 {
return -1
} else {
... | {
return value < conf.SensorSpan
} | identifier_body |
greyhound.go | ev3.CheckDriver(devs.OutA, ev3.DriverRcxMotor, ev3.OutA)
ev3.CheckDriver(devs.OutB, ev3.DriverRcxMotor, ev3.OutB)
ev3.CheckDriver(devs.OutC, ev3.DriverRcxMotor, ev3.OutC)
ev3.CheckDriver(devs.OutD, ev3.DriverRcxMotor, ev3.OutD)
// Check sensors
ev3.CheckDriver(devs.In1, ev3.DriverColor, ev3.In1)
ev3.CheckDriver... | else if right < nextSpeedRight {
nextSpeedRight -= delta
if nextSpeedRight < right {
nextSpeedRight = right
}
}
lastSpeedLeft = nextSpeedLeft
lastSpeedRight = nextSpeedRight
motorL1.Value = nextSpeedLeft / accelSpeedFactor
motorL2.Value = nextSpeedLeft / accelSpeedFactor
motorR1.Value = -nextSpeedRight... | {
nextSpeedRight += delta
if nextSpeedRight > right {
nextSpeedRight = right
}
} | conditional_block |
offline.py | 1 列
# 时间戳用长整型
showPoetryDetails = showPoetryDetails. \
withColumn("userId", showPoetryDetails.userId.cast(LongType())). \
withColumn("itemId", showPoetryDetails.itemId.cast(IntegerType()))
# 点击行为评分为 1分
showPoetryDetails = showPoetryDetails. \
withColu... |
dataset = train_sort_model_df.toPandas()
# 从 MySql 读取 用户喜欢的诗人数据,构造特征
engine = create_engine('mysql+pymysql://root:12345678@39.96.165.58:3306/huamanxi')
userandauthor = pd.read_sql_table('userandauthor', engine)
# 为了区分诗人id和古诗id,诗人id加20w
userandauthor.userId = userandauth... | identifier_body | |
offline.py | collectPoem.rating.cast(IntegerType()))
return collectPoem
def process_evaluatePoem(self):
def reg_extract3(string):
ans = re.findall("like=(.+)&poemId=(.+)", string)
rating = None
if ans[0][0] == '0':
rating = '-2'
else:
... | , 30, 2)),
| conditional_block | |
offline.py | 类型一致
collectPoem = collectPoem. \
withColumn("userId", collectPoem.userId.cast(LongType())). \
withColumn("itemId", collectPoem.itemId.cast(IntegerType())). \
withColumn("rating", collectPoem.rating.cast(IntegerType()))
return collectPoem
def process_evaluatePoe... | data = Dataset.load_from_df(self.user_log[["userId", "itemId", \
"rating"]], reader)
| random_line_split | |
offline.py | self.spark = SparkSession.builder.appName("ddd").getOrCreate()
sc = self.spark.sparkContext
sqlContext = SQLContext(sc)
hive_context = HiveContext(sc)
# hive_context.setConf("hive.metastore.uris", "thrift://localhost:9083")
# 读取用户信息表
self.user_info = sqlContext.read.for... | identifier_name | ||
json_rpc.py | -values are not allowed for Service Methods
- handles only HTTP POST
- JSON-RPC Version < 2.0 (same as 1.2) not supported
TODOs:
- more Comments
- Examples (doctest?)
- Factor out handler methods to reuse in other frameworks
"""
from google.appengine.ext import webapp
from inspect import getargspec
import c... | elif msg.error:
return (msg.error.status,
self._build_error(msg.error, msg.message_id))
elif msg.result:
return (200, self._build_result(msg))
else: # pragma: no cover
# Should never be reached
logging.warn('Message neither c... | eturn None
| conditional_block |
json_rpc.py | json-rpc-over-http proposal.
"""
code = 0
message = None
status = 500
def __init__(self, message=None):
if message is not None:
self.message = message
def __str__(self):
return(self.message)
def __repr__(self):
return '%s("%s")' % (str(self.__class__._... | "Wrong number of parameters; "
"expected %i got %i" % (len(args_set),len(params)))
return method(*params) | random_line_split | |
json_rpc.py | 602
message = 'Invalid params'
class InternalError(JsonRpcError):
"""Internal JSON-RPC error."""
code = -32603
message = 'Internal error'
class ServerError(JsonRpcError):
"""Base Class for implementation-defined Server Errors.
The Error Code must be between -32099..-32000
"""
code... | ""Convert all keys in dict d to str.
Python does not allow unicode keys in dictionaries.
:param dict d: A JSON-RPC message.
"""
try:
r = {}
for (k, v) in d.iteritems():
r[str(k)] = v
return r
except UnicodeEncodeError: # prag... | identifier_body | |
json_rpc.py | -values are not allowed for Service Methods
- handles only HTTP POST
- JSON-RPC Version < 2.0 (same as 1.2) not supported
TODOs:
- more Comments
- Examples (doctest?)
- Factor out handler methods to reuse in other frameworks
"""
from google.appengine.ext import webapp
from inspect import getargspec
import c... | JsonRpcError):
"""Invalid method parameter(s)."""
code = -32602
message = 'Invalid params'
class InternalError(JsonRpcError):
"""Internal JSON-RPC error."""
code = -32603
message = 'Internal error'
class ServerError(JsonRpcError):
"""Base Class for implementation-defined Server Errors.... | nvalidParamsError( | identifier_name |
inside.py | classification loss is computed (Cross-Entropy).
"""
return_dict = self.config.use_return_dict
outputs = self.bert(
span_inside_input_ids,
attention_mask=span_inside_attention_mask,
# token_type_ids=token_type_ids,
)
pooled_output = outputs[... | )
cache_dir: Optional[str] = field(
default=None,
metadata={
"help": "Where do you want to store the pretrained models downloaded from huggingface.co"
},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={
"help": "Whether to use o... | """
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={
"help": "Path to pretrained model or model identifier from huggingface.co/models"
}
)
config_name: Optional[str] = field(
defa... | identifier_body |
inside.py | classification loss is computed (Cross-Entropy).
"""
return_dict = self.config.use_return_dict
outputs = self.bert(
span_inside_input_ids,
attention_mask=span_inside_attention_mask,
# token_type_ids=token_type_ids,
)
pooled_output = outputs[... | Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
"""
max_seq_length: int = field(
default=128,
metadata={
"help": "The maximum total input sequence length after tokenization. Sequences longer "
... | """
Arguments pertaining to what data we are going to input our model for training and eval. | random_line_split |
inside.py | classification loss is computed (Cross-Entropy).
"""
return_dict = self.config.use_return_dict
outputs = self.bert(
span_inside_input_ids,
attention_mask=span_inside_attention_mask,
# token_type_ids=token_type_ids,
)
pooled_output = outputs[... |
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
task_to_keys = {
"cola": ("sentence", None),
"mnli": ("premise", "hypothesis"),
"mrpc": ("sentence1", "sentence... | output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output | conditional_block |
inside.py | which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={
"help": "Path to pretrained model or model identifier from huggingface.co/models"
}
)
config_name: Optional[str] = field(
default=None,
metadata={
... | predict | identifier_name | |
datahandle.py | 'allergens': {'sesame-seed': 'sesame seeds',
'tree-nuts': 'tree nuts',
'wheat_barley_rye': 'wheat or barley or rye'}}
#If traits specified, extract into a string
for i, trait in enumerate(requisites['trait']):
if traits_text:
traits... | def check_meal_available(data, meal):
"""Searches response data to check if meal is available at specified location/date.
:param data: MDining API HTTP response data
:type data: dict
:param meal: Name of meal
:type meal: string
"""
for key in data['menu']['meal']:
if data['menu']['m... | random_line_split | |
datahandle.py | if allergens_text:
allergens_text = ' without ' + allergens_text
if traits_text:
traits_text = ' that is ' + traits_text
#Return combined string
if (allergens_text or traits_text) and 'Sorry, that is not available' in text:
traits_text = traits_text.replace(' that is ', '')
... | """Handles searching for appropriate data response for valid specified
location and food item entities (and meal entity if included) from ``findItem`` intent.
:param date_in: Input date
:type date_in: string
:param loc_in: Input location
:type loc_in: string
:param item_in: Input food item
... | identifier_body | |
datahandle.py | (error_text):
"""Logs error to Stackdriver.
:param error_text: The text to log to Stackdriver
:type error_text: string
"""
client = google.cloud.logging.Client()
logger = client.logger("automated_error_catch")
logger.log_text(error_text)
def get_secrets():
"""Fetches secrets from Datast... | report_error | identifier_name | |
datahandle.py | 'allergens': {'sesame-seed': 'sesame seeds',
'tree-nuts': 'tree nuts',
'wheat_barley_rye': 'wheat or barley or rye'}}
#If traits specified, extract into a string
for i, trait in enumerate(requisites['trait']):
if traits_text:
traits... |
for item in item_data:
if check_item_specifications(item, traits, allergens) == False:
continue
if item_in.upper() in item['name'].upper():
if item['name'][-1] == ' ':
item['name'] = item['name'][:-1]
possible_matches.append(item['name'] + ' dur... | item_data.append(course_data) | conditional_block |
restingstate_preprocess_gica_noscrub.py | ,mainColor)
#Make sure scrub file exists and if not, then set the number of scrubbing TRs to zero
if os.path.exists(metric_values_text):
fds = np.loadtxt(metric_values_text)
tr = len(fds)
mfd = np.mean(fds)
else:
print red + "No outliers found for %s. Moving on\n%s" % (subject,mainColor)
num_col... | print sectionColor + "Regressing out confounds ---------------------------" + mainColor
| random_line_split | |
restingstate_preprocess_gica_noscrub.py | = preprocess_featfolder + "/reg"
preprocess_output = preprocess_featfolder + "/filtered_func_data.nii.gz"
# if os.path.exists(regdir):
# print red + "Subject %s has an old, bad feat folder. Be careful%s" %(subject,mainColor)
# #shutil.rmtree(preprocess_featfolder)
icafolder = preprocess_featfolder + "/ICA_ARO... | print red + "Preprocess feat not completed correctly. %s does not exist. Moving on to next subject\n%s" %(preprocess_output,mainColor)
continue | conditional_block | |
shell.rs | blk" => FILESYSTEM.lsblk(),
"mount" => mount(cwd, &self.args[1..]),
"umount" => umount(cwd, &self.args[1]),
"mkcrypt" => encrypt_part(&self.args[1..]),
path => kprintln!("unknown command: {}", path)
}
}
}
fn pwd(cwd: &mut PathBuf) {
let path = cwd.as_path... | }
fn ls(cwd: &PathBuf, args: &[&str]) {
let mut rel_dir = cwd.clone();
let mut changed_dir = false;
let mut show_hidden = false;
for arg in args {
if *arg == "-a" {
show_hidden = true;
continue
}
if changed_dir {
continue
}
i... | }
}
}
return true | random_line_split |
shell.rs | " => FILESYSTEM.lsblk(),
"mount" => mount(cwd, &self.args[1..]),
"umount" => umount(cwd, &self.args[1]),
"mkcrypt" => encrypt_part(&self.args[1..]),
path => kprintln!("unknown command: {}", path)
}
}
}
fn pwd(cwd: &mut PathBuf) {
let path = cwd.as_path();... |
fn mkdir(cwd: &PathBuf, args: &[&str]) {
let abs_path = match get_abs_path(cwd, args[0]) {
Some(p) => p,
None => return
};
let dir_metadata = fat32::vfat::Metadata {
name: String::from(abs_path.file_name().unwrap().to_str().unwrap()),
created: fat32::vfat::Timestamp::defau... | {
let mut raw_path: PathBuf = PathBuf::from(dir_arg);
if !raw_path.is_absolute() {
raw_path = cwd.clone().join(raw_path);
}
let abs_path = match canonicalize(raw_path) {
Ok(p) => p,
Err(_) => {
kprintln!("\ninvalid arg: {}", dir_arg);
return None;
... | identifier_body |
shell.rs | blk" => FILESYSTEM.lsblk(),
"mount" => mount(cwd, &self.args[1..]),
"umount" => umount(cwd, &self.args[1]),
"mkcrypt" => encrypt_part(&self.args[1..]),
path => kprintln!("unknown command: {}", path)
}
}
}
fn pwd(cwd: &mut PathBuf) {
let path = cwd.as_path... | (cwd: &mut PathBuf, path: &str) -> bool {
if path.len() == 0 { return true }
if &path[0..1] == "/" {
// cwd.clear() not implemented in shim :(
while cwd.pop() {}
}
for part in path.split('/') {
// Remove any / that makes its way in
let part = part.replace("/", "");
... | cd | identifier_name |
helper.py | (png_file):
await x.edit_text("This sticker is Gey, Task Failed Successfully ≧ω≦")
await asyncio.sleep(5)
await x.delete()
raise Exception(stdout + stderr)
dls_loc = png_file
elif replied.sticker and replied.sticker.file_name.endswith(".webp"):
... | = 1:
buttons.append([InlineKeyboardButton(text="Next", callback_data=f"page_{media}{qry}_{int(lspage)+1}_{str(auth)}_{user}")])
elif lspage == result[1][1]:
buttons.append([InlineKeyboardButton(text="Prev", callback_data=f"page_{media}{qry}_{int(lspage)-1}_{str(auth)}_{user}")])
... | conditional_block | |
helper.py | Gey, Task Failed Successfully ≧ω≦")
await asyncio.sleep(5)
await x.delete()
raise Exception(stdout + stderr)
dls_loc = png_file
elif replied.sticker and replied.sticker.file_name.endswith(".webp"):
stkr_file = os.path.join(DOWN_PATH, f"{rand_key()}.png")
... | ns(media, use | identifier_name | |
helper.py | clog('ANIBOT', f'UserID: {user}', 'BAN')
return
await asyncio.sleep(USER_WC[user])
else:
USER_WC[user] = 0
except KeyError:
pass
USER_JSON[user] = nut
try:
await func(_, ... | os.rename(dls_loc, stkr_file)
if not os.path.lexists(stkr_file):
await x.edit_text("```Sticker not found...```")
await asyncio.sleep(5)
await x.delete()
return
dls_loc = stkr_file
elif replied.animation or replied.video:
await x... | stkr_file = os.path.join(DOWN_PATH, f"{rand_key()}.png")
| random_line_split |
helper.py | await clog('ANIBOT', f'UserID: {user}', 'BAN')
return
await asyncio.sleep(USER_WC[user])
else:
USER_WC[user] = 0
except KeyError:
pass
USER_JSON[user] = nut
try:
await fu... | def clog(name: str, text: str, tag: str):
log = f"#{name.upper()} #{tag.upper()}\n\n{text}"
await anibot.send_message(chat_id=LOG_CHANNEL_ID, text=log)
def get_btns(media, user: int, result: list, lsqry: str = None, lspage: int = None, auth: bool = False, sfw: str = "False"):
buttons = []
qry... | ng Time Stamp to Readable Format"""
seconds, milliseconds = divmod(int(time_stamp), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days) + " Days, ") if days else "")
+ ((str(hours) + " Hours, ") ... | identifier_body |
regression2_helper.py | 1, projection='3d')
ax.scatter(X1, X2, y/1e6, color="black")
ax.set_xlabel('Cреднее количество комнат')
ax.set_ylabel('LSTAT %')
ax.set_zlabel('Цена квартиры, $1000')
xx, yy = np.meshgrid(np.linspace(2, 9, 100), np.linspace(0, 40, 100))
z = np.zeros_like(xx)
f... | [ 9.400, 16.050], [35.150, 16.800], [28.100, 11.400], [10.550, 7.150], [11.800, 8.800],
[37.050, 17.750], [17.100, 3.000], [30.900, 9.450], [29.200, 15.150], [20.550, 2.800], | random_line_split | |
regression2_helper.py | 200, 9.600], [33.050, 17.800], [12.950, 6.850],
[23.550, 5.700], [35.800, 18.850], [39.650, 18.550], [19.900, 2.200], [ 6.650, 12.200],
[16.700, 1.550], [ 3.550, 15.550], [34.450, 18.250], [ 2.600, 14.900], [27.800, 15.900]])
X = data[:, 0]
y = data[:, 1]
... | plt.ylim(0, 20)
plt.grid()
plt.plot(scaler.inverse_transform(x_axis_ticks)[:, 1], y_pred, color='r')
plt.show()
def plot_mae_mse():
x_slrd = FloatSlider(min=-1.5, max=1.5, step=0.1, value=0, description='$x$')
@interact(x=x_slrd)
def f(x):
fig, axis = plt.subplot... | conditional_block | |
regression2_helper.py | ():
data, y = load_all_data()
return data[:, 5], data[:, -1], y
def print_3d_table_with_data(X1, X2, y):
l = len(X1)
d = {"Cреднее количество комнат" : pd.Series(X1, index=range(0, l)),
"LSTAT %" : pd.Series(X2, index=range(0, l)),
'Цена квартиры, $1000$' : pd.Series(y, index=rang... | load_small_data | identifier_name | |
regression2_helper.py | value=1, description='c')
@interact(a=a_koef, b=b_koef, c=c_koef)
def interact_plot_parabol(a, b, c):
x = np.linspace(-10, 10, num=200)
y = a*x**2 + b*x + c
plt.figure(figsize=(16,10))
plt.plot(x, y, color='black')
plt.xlim((-10,10))
plt.ylim((-10,100))
... | (X_poly_scaled[:, 1]))
plt.grid()
plt.plot(x[:,1], y_pred, color='r', label="Кривая после | identifier_body | |
client_conn.rs | Stream<I>;
type HttpStreamSpecific = ClientStreamData;
type ConnSpecific = ClientConnData;
type ToWriteMessage = ClientToWriteMessage;
const OUT_REQUEST_OR_RESPONSE: RequestOrResponse = RequestOrResponse::Request;
const CLIENT_OR_SERVER: ClientOrServer = ClientOrServer::Client;
}
pub struct Clien... | {
write_tx: UnboundedSender<ClientToWriteMessage>,
}
unsafe impl Sync for ClientConn {}
pub struct StartRequestMessage {
pub headers: Headers,
pub body: HttpStreamAfterHeaders,
pub resp_tx: oneshot::Sender<Response>,
}
enum ClientToWriteMessage {
Start(StartRequestMessage),
WaitForHandshake(... | ClientConn | identifier_name |
client_conn.rs |
use futures::future::Future;
use futures::stream::Stream;
use futures::sync::mpsc::unbounded;
use futures::sync::mpsc::UnboundedSender;
use futures::sync::oneshot;
use tls_api::TlsConnector;
use tokio_core::reactor;
use tokio_io::AsyncRead;
use tokio_io::AsyncWrite;
use tokio_timer::Timer;
use tokio_tls_api;
use so... | use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
use service::Service; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.