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 |
|---|---|---|---|---|
athena_cli.py |
import argparse
import atexit
import csv
import json
import os
import readline
import subprocess
import sys
import time
import uuid
import boto3
import botocore
import cmd2 as cmd
from botocore.exceptions import ClientError, ParamValidationError
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = ... | (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 |
import argparse
import atexit
import csv
import json
import os
import readline
import subprocess
import sys
import time
import uuid
import boto3
import botocore
import cmd2 as cmd
from botocore.exceptions import ClientError, ParamValidationError
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = ... |
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_prompt()
def do_set(self, arg):
try:
statement, param_name, val = arg.parsed.raw.... | 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 |
import argparse
import atexit
import csv
import json
import os
import readline
import subprocess
import sys
import time
import uuid
import boto3
import botocore
import cmd2 as cmd
from botocore.exceptions import ClientError, ParamValidationError
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = ... |
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 | package cfgparse
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
)
var (
sectionRegexp = regexp.MustCompile("\\[([^]]+)\\]")
keyValueRegexp = regexp.MustCompile("([^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(.*)$")
interpolateRegexp = regexp.MustCompile("%\... |
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 | package cfgparse
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
)
var (
sectionRegexp = regexp.MustCompile("\\[([^]]+)\\]")
keyValueRegexp = regexp.MustCompile("([^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(.*)$")
interpolateRegexp = regexp.MustCompile("%\... | (line string) bool {
match := keyValueRegexp.MatchString(line)
return match
}
| isKeyValue | identifier_name |
cfgparse.go | package cfgparse
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
)
var (
sectionRegexp = regexp.MustCompile("\\[([^]]+)\\]")
keyValueRegexp = regexp.MustCompile("([^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(.*)$")
interpolateRegexp = regexp.MustCompile("%\... |
func (c *CfgParser) isSectionAlreadyExists(sectionName string) bool {
for section, _ := range c.sections {
if section == sectionName {
return true
}
}
return false
}
func isKeyValue(line string) bool {
match := keyValueRegexp.MatchString(line)
return match
} | return match
} | random_line_split |
cfgparse.go | package cfgparse
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
)
var (
sectionRegexp = regexp.MustCompile("\\[([^]]+)\\]")
keyValueRegexp = regexp.MustCompile("([^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(.*)$")
interpolateRegexp = regexp.MustCompile("%\... |
}
return 0, errors.New("No section exists")
}
func isSection(line string) bool {
match := sectionRegexp.MatchString(line)
return match
}
func (c *CfgParser) isSectionAlreadyExists(sectionName string) bool {
for section, _ := range c.sections {
if section == sectionName {
return true
}
}
return false
}
... | {
return c.sections[sectionName].filePosition, nil
} | conditional_block |
partition_hash_test.go | // Copyright 2022 Matrix Origin
//
// 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... |
func Test_hash_buildEvalPartitionExpression(t *testing.T) {
sql1 := " create table a(col1 int,col2 int) partition by hash(col1+col2)"
one, err := parsers.ParseOne(context.TODO(), dialect.MYSQL, sql1, 1)
require.Nil(t, err)
/*
table test:
col1 int32 pk
col2 int32
*/
tableDef := &plan.TableDef{
Name: "a"... | {
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 | // Copyright 2022 Matrix Origin
//
// 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... | (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 | // Copyright 2022 Matrix Origin
//
// 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... |
`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 | // Copyright 2022 Matrix Origin
//
// 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... |
}
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 | # encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException
import time
import threading
import random
import string
from urllib import parse, request
import re
im... | 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 | # encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException
import time
import threading
import random
import string
from urllib import parse, request
import re
im... | 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 | # encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException
import time
import threading
import random
import string
from urllib import parse, request
import re
im... | 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 | # encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException
import time
import threading
import random
import string
from urllib import parse, request
import re
im... | True
print('号码释放失败:'+RELEASE)
return False
# 前台开启浏览器模式
def openChrome():
# 加启动配置
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars')
# option.add_argument("--proxy-server=http://103.218.240.182:80")
driver = webdriver.Chrome(chrome_options=option)
# 打开chrome浏览器
... | 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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 19:59:22 2020
@author: higor
"""
from datetime import datetime
import cv2
import numpy as np
import time
import base64
import requests
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import timeit
from PIL import Image
import sys, os, os.path... |
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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 19:59:22 2020
@author: higor
"""
from datetime import datetime
import cv2
import numpy as np
import time
import base64
import requests
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import timeit
from PIL import Image
import sys, os, os.path... | 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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 19:59:22 2020
@author: higor
"""
from datetime import datetime
import cv2
import numpy as np
import time
import base64
import requests
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import timeit
from PIL import Image
import sys, os, os.path... |
#--------------------
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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 19:59:22 2020
@author: higor
"""
from datetime import datetime
import cv2
import numpy as np
import time
import base64
import requests
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import timeit
from PIL import Image
import sys, os, os.path... | (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 | from functools import wraps
from logging import getLogger
# Read the docs at https://github.com/eclipse/paho.mqtt.python
# because eclipse.org has outdated information, which does not include MQTTv5
from paho.mqtt.client import Client as MqttClient, MQTTMessage, MQTTv5, MQTT_CLEAN_START_FIRST_ONLY
from paho.mqtt.prop... |
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 | from functools import wraps
from logging import getLogger
# Read the docs at https://github.com/eclipse/paho.mqtt.python
# because eclipse.org has outdated information, which does not include MQTTv5
from paho.mqtt.client import Client as MqttClient, MQTTMessage, MQTTv5, MQTT_CLEAN_START_FIRST_ONLY
from paho.mqtt.prop... | 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 | from functools import wraps
from logging import getLogger
# Read the docs at https://github.com/eclipse/paho.mqtt.python
# because eclipse.org has outdated information, which does not include MQTTv5
from paho.mqtt.client import Client as MqttClient, MQTTMessage, MQTTv5, MQTT_CLEAN_START_FIRST_ONLY
from paho.mqtt.prop... | (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 | from functools import wraps
from logging import getLogger
# Read the docs at https://github.com/eclipse/paho.mqtt.python
# because eclipse.org has outdated information, which does not include MQTTv5
from paho.mqtt.client import Client as MqttClient, MQTTMessage, MQTTv5, MQTT_CLEAN_START_FIRST_ONLY
from paho.mqtt.prop... |
def connect(self):
# currently, this will retry first connects, we don't need bettermqtt
self._mqttc.connect_async(**self.mqtt_server_kwargs)
self._mqttc.loop_start()
def _on_connect(self, client, userdata, flags, rc: ReasonCodes, properties: Properties = None):
if flags['sess... | 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 | # SkyMote Manager
from groundedutils import *
from skymotefirmwareupgrader import SkymoteFirmwareUpgraderThread
import threading
import LabJackPython, skymote
from groundedlogger import log
import csv, os
from datetime import datetime
from time import time as floattime
# We are going to keep names based on unit ids,... | 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 | # SkyMote Manager
from groundedutils import *
from skymotefirmwareupgrader import SkymoteFirmwareUpgraderThread
import threading
import LabJackPython, skymote
from groundedlogger import log
import csv, os
from datetime import datetime
from time import time as floattime
# We are going to keep names based on unit ids,... |
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 | # SkyMote Manager
from groundedutils import *
from skymotefirmwareupgrader import SkymoteFirmwareUpgraderThread
import threading
import LabJackPython, skymote
from groundedlogger import log
import csv, os
from datetime import datetime
from time import time as floattime
# We are going to keep names based on unit ids,... |
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 | # SkyMote Manager
from groundedutils import *
from skymotefirmwareupgrader import SkymoteFirmwareUpgraderThread
import threading
import LabJackPython, skymote
from groundedlogger import log
import csv, os
from datetime import datetime
from time import time as floattime
# We are going to keep names based on unit ids,... | (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 | // =====================================Задача 4 - 1
// Callback функция
// Функция mapArray(array, cb), принимает 1 - м параметром array - массив чисел,
// а вторым параметром cb - функцию обратного вызова(callback).
// Функция mapArray создает новый массив numbers и заполняет его числами
// из массива array прео... | // 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 | package govue
import (
"encoding/xml"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// A Gradebook holds a student's courses, including their grades and assignments in
// those courses, and their school's reporting periods ((mid-)terms, semesters, etc...).
type Gradebook struct {
XMLName xml.Name `xml:"Gradebook... | {
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 | package govue
import (
"encoding/xml"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// A Gradebook holds a student's courses, including their grades and assignments in
// those courses, and their school's reporting periods ((mid-)terms, semesters, etc...).
type Gradebook struct {
XMLName xml.Name `xml:"Gradebook... |
possiblePoints := r.FindStringSubmatch(attr.Value)
if len(possiblePoints) != 2 {
return fmt.Errorf("Expected points attribute in format `x Points Possible`, received %s and parsed %d values", attr.Value, len(possiblePoints))
}
val, err := stringsToFloats(possiblePoints[1:])
if err != nil {
return e... | {
return err
} | conditional_block |
gradebook.go | package govue
import (
"encoding/xml"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// A Gradebook holds a student's courses, including their grades and assignments in
// those courses, and their school's reporting periods ((mid-)terms, semesters, etc...).
type Gradebook struct {
XMLName xml.Name `xml:"Gradebook... | 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 | package govue
import (
"encoding/xml"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// A Gradebook holds a student's courses, including their grades and assignments in
// those courses, and their school's reporting periods ((mid-)terms, semesters, etc...).
type Gradebook struct {
XMLName xml.Name `xml:"Gradebook... | (attr xml.Attr) error {
if strings.Contains(attr.Value, "Points Possible") {
const pointsRegex = "([\\d\\.]+)\\s*Points\\s*Possible"
r, err := regexp.Compile(pointsRegex)
if err != nil {
return err
}
possiblePoints := r.FindStringSubmatch(attr.Value)
if len(possiblePoints) != 2 {
return fmt.Error... | UnmarshalXMLAttr | identifier_name |
mod.rs | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... | (&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 | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... | 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 | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... |
}
if score >= 5 {
return true;
}
}
false
}
}
| {
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 | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... |
/// 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 | use chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File;
use std::io;
use std::io::pr... | (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 | use chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File;
use std::io;
use std::io::pr... |
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 chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url; | 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 |
#pylint: disable=W0201, W0142
import runStatus
runStatus.preloadDicts = False
# import Levenshtein as lv
import sql.conditionals as sqlc
import logging
import settings
import abc
import threading
import urllib.parse
import functools
import operator as opclass
import sql
# import sql.operators as sqlo
import ha... | (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 |
#pylint: disable=W0201, W0142
import runStatus
runStatus.preloadDicts = False
# import Levenshtein as lv
import sql.conditionals as sqlc
import logging
import settings
import abc
import threading
import urllib.parse
import functools
import operator as opclass
import sql
# import sql.operators as sqlo
import ha... |
if 'url' in kwargs and not kwargs['url'].startswith("http"):
self.log.error('')
self.log.error('')
self.log.error("WAT")
self.log.error('')
self.log.error(traceback.format_stack())
self.log.error('')
# print("Upserting!")
with self.transaction(commit=commit) as cur:
# Do everything in o... | 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 | #pylint: disable=W0201, W0142
import runStatus
runStatus.preloadDicts = False
# import Levenshtein as lv
import sql.conditionals as sqlc
import logging
import settings
import abc
import threading
import urllib.parse
import functools
import operator as opclass
import sql
# import sql.operators as sqlo
import hash... | # self.log.info('havePath, haveCtnt, haveMime - %s, %s, %s', havePath, haveCtnt, haveMime)
if not hadFile:
fqPath = self.getFilenameFromIdName(dbid, fileName)
newRowDict = { "dlstate" : 2,
"series" : None,
"contents": len(content),
"istext" : False,
"mimetype": mimetype,
... | dbid, dummy_havePath, dummy_haveCtnt, dummy_haveMime = row | random_line_split |
TextDbBase.py |
#pylint: disable=W0201, W0142
import runStatus
runStatus.preloadDicts = False
# import Levenshtein as lv
import sql.conditionals as sqlc
import logging
import settings
import abc
import threading
import urllib.parse
import functools
import operator as opclass
import sql
# import sql.operators as sqlo
import ha... |
def getHash(self, fCont):
m = hashlib.md5()
m.update(fCont)
return m.hexdigest()
| 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 | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... | {
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 | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... | /// 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 | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... |
#[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 | // Copyright 2022 The LUCI 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... |
// 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 | // Copyright 2022 The LUCI 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... |
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 | // Copyright 2022 The LUCI 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... | (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 | // Copyright 2022 The LUCI 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... |
// chunkIDAsBigInt represents a 128-bit chunk ID
// (normally represented as 32 lowercase hexadecimal characters)
// as a big.Int.
func chunkIDAsBigInt(chunkID string) (*big.Int, error) {
if chunkID == "" {
// "" indicates start of table. This is one before
// ID 00000 .... 00000.
return big.NewInt(-1), nil
}... | {
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 | // Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/ve... |
// 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) (*providersUpgradeInfo,... | {
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 | // Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/ve... | () time.Duration {
var err error
packageInstallTimeoutStr, _ := c.TKGConfigReaderWriter().Get(constants.ConfigVariablePackageInstallTimeout)
packageInstallTimeout := time.Duration(0)
if packageInstallTimeoutStr != "" {
packageInstallTimeout, err = time.ParseDuration(packageInstallTimeoutStr)
if err != nil {
... | getPackageInstallTimeoutFromConfig | identifier_name |
upgrade_region.go | // Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/ve... |
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 | // Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/ve... | 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 | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | 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 | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | (
&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 | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | /// Handle a packet for a specific connection.
///
/// This part does the defragmentation, decryption and decompression.
fn connection_handle_udp_packet(
logger: &Logger,
in_packet_observer: LockedHashMap<
String,
Box<InPacketObserver<CM::AssociatedData>>,
>,
in_command_observer: LockedHashMap<
Str... | {
// 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 | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | 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 | #!/usr/bin/env python3
import argparse
import distutils
import hashlib
import logging
import os
import subprocess
import sys
import tarfile
from typing import List, Tuple
PYTHON_VERSIONS = [
(3,7),
(3,8),
(3,9),
(3,10),
(3,11)
]
if sys.platform == 'win32':
CMAKE_BUILD_ENV_ROOT = os.path.joi... | 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 | #!/usr/bin/env python3
import argparse
import distutils
import hashlib
import logging
import os
import subprocess
import sys
import tarfile
from typing import List, Tuple
PYTHON_VERSIONS = [
(3,7),
(3,8),
(3,9),
(3,10),
(3,11)
]
if sys.platform == 'win32':
CMAKE_BUILD_ENV_ROOT = os.path.joi... |
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 | #!/usr/bin/env python3
import argparse
import distutils
import hashlib
import logging
import os
import subprocess
import sys
import tarfile
from typing import List, Tuple
PYTHON_VERSIONS = [
(3,7),
(3,8),
(3,9),
(3,10),
(3,11)
]
if sys.platform == 'win32':
CMAKE_BUILD_ENV_ROOT = os.path.joi... | (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 | #!/usr/bin/env python3
import argparse
import distutils
import hashlib
import logging
import os
import subprocess
import sys
import tarfile
from typing import List, Tuple
PYTHON_VERSIONS = [
(3,7),
(3,8),
(3,9),
(3,10),
(3,11)
]
if sys.platform == 'win32':
CMAKE_BUILD_ENV_ROOT = os.path.joi... |
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 | package main
import (
"fmt"
"go-bots/ev3"
"go-bots/greyhound/config"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func handleSignals() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
quit("Terminated by signal", sig)
}()
}
var devs *ev3.De... | 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 | package main
import (
"fmt"
"go-bots/ev3"
"go-bots/greyhound/config"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func handleSignals() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
quit("Terminated by signal", sig)
}()
}
var devs *ev3.De... | () 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 | package main
import (
"fmt"
"go-bots/ev3"
"go-bots/greyhound/config"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func handleSignals() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
quit("Terminated by signal", sig)
}()
}
var devs *ev3.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 | package main
import (
"fmt"
"go-bots/ev3"
"go-bots/greyhound/config"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func handleSignals() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
quit("Terminated by signal", sig)
}()
}
var devs *ev3.De... | 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 | from pyspark.sql import SQLContext, SparkSession, HiveContext
from hdfs.client import Client
from pyspark.sql import functions
from pyspark.sql import Row
import pyspark.sql.functions as F
from pyspark.sql.types import *
import pymongo
import pandas as pd
from sqlalchemy import create_engine
import os
import re
from s... | # TODO(laoliang):为了增加古诗推荐的新颖性, 会将每个用户对应的 top-100 放到 Mongodb, 在实时推荐的时候,作为固定的召回集
itemId_set = list(set(self.user_log.itemId))
userId_set = list(set(self.user_log.userId))
# 记录每位用户对应的粗排候选集 Top-100
est_dict = dict()
for uid in userId_set:
est_dict[uid] = list()
... |
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 | from pyspark.sql import SQLContext, SparkSession, HiveContext
from hdfs.client import Client
from pyspark.sql import functions
from pyspark.sql import Row
import pyspark.sql.functions as F
from pyspark.sql.types import *
import pymongo
import pandas as pd
from sqlalchemy import create_engine
import os
import re
from s... | 'lr_all': [0.002, 0.005, 0.01], 'reg_all': [0.02, 0.1, 0.6, 1, 2, 3, 4, 5]}
gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=5)
gs.fit(data)
print(gs.best_score["rmse"])
# 用 网格搜索出来的最佳参数训练模型, 因为在gs里面直接取出estimator会报错
best_param = gs.best_params["... | , 30, 2)),
| conditional_block |
offline.py | from pyspark.sql import SQLContext, SparkSession, HiveContext
from hdfs.client import Client
from pyspark.sql import functions
from pyspark.sql import Row
import pyspark.sql.functions as F
from pyspark.sql.types import *
import pymongo
import pandas as pd
from sqlalchemy import create_engine
import os
import re
from s... | # 搜索的参数范围
param_grid = {'n_factors': list(range(20, 110, 10)), 'n_epochs': list(range(10, 30, 2)),
'lr_all': [0.002, 0.005, 0.01], 'reg_all': [0.02, 0.1, 0.6, 1, 2, 3, 4, 5]}
gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=5)
gs.fit(data)
p... | data = Dataset.load_from_df(self.user_log[["userId", "itemId", \
"rating"]], reader)
| random_line_split |
offline.py | from pyspark.sql import SQLContext, SparkSession, HiveContext
from hdfs.client import Client
from pyspark.sql import functions
from pyspark.sql import Row
import pyspark.sql.functions as F
from pyspark.sql.types import *
import pymongo
import pandas as pd
from sqlalchemy import create_engine
import os
import re
from s... | 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 | # -*- coding: utf-8 -*-
#
# Copyright 2010, 2011 Florian Glanzner (fgl), Tobias Rodäbel
#
# 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
#
# ... | 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 | # -*- coding: utf-8 -*-
#
# Copyright 2010, 2011 Florian Glanzner (fgl), Tobias Rodäbel
#
# 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
#
# ... | elif isinstance(params, dict):
paramset = set(params)
if not args_set == paramset:
raise InvalidParamsError(
"Named parameters do not "
"match method; expected %s" % (str(args_set)))
params = self.decode_dict_keys(params... | "Wrong number of parameters; "
"expected %i got %i" % (len(args_set),len(params)))
return method(*params) | random_line_split |
json_rpc.py | # -*- coding: utf-8 -*-
#
# Copyright 2010, 2011 Florian Glanzner (fgl), Tobias Rodäbel
#
# 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
#
# ... | ""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 | # -*- coding: utf-8 -*-
#
# Copyright 2010, 2011 Florian Glanzner (fgl), Tobias Rodäbel
#
# 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
#
# ... | 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 | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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 r... |
TrainingArguments = gin.configurable(TrainingArguments)
from datasets import DatasetDict, Dataset, Sequence, Value, DatasetInfo
@gin.configurable
class SpanInsideClassifier(SpanClassifier):
def __init__(
self,
span_classification_datasets: DatasetDict,
model_args: SpanInsideClassificat... | """
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 | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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 r... | 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 | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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 r... |
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 | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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 r... | (self, tokens: List[str], start: int, end: int) -> SpanClassifierOutput:
# self.tokenizer()
tokenized = self.tokenizer(
[tokens[start:end]],
is_split_into_words=True,
)
args = {
"span_inside_input_ids": torch.LongTensor(tokenized["input_ids"]).to(
... | predict | identifier_name |
datahandle.py | import requests
from google.cloud import datastore
import google.cloud.logging
###Helper functions
def report_error(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.l... | 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 | import requests
from google.cloud import datastore
import google.cloud.logging
###Helper functions
def report_error(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.l... | """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 | import requests
from google.cloud import datastore
import google.cloud.logging
###Helper functions
def | (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 | import requests
from google.cloud import datastore
import google.cloud.logging
###Helper functions
def report_error(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.l... |
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 | #!/usr/bin/env python
#Pre-process Resting State data and does an ICA
import os,sys
from commando import commando
from commando import writeToLog
import argparse
import numpy as np
import re
from datetime import datetime
from subprocess import call
from subprocess import check_output
import csv
import shutil
import p... | #first construct design.mat
if not os.path.exists(designfile):
mcparams = np.loadtxt(mcparamfile)
wmparams = np.loadtxt(WMfile,ndmin=2)
csfparams = np.loadtxt(CSFfile,ndmin=2)
allconfounds = np.hstack([mcparams,wmparams,csfparams])
numconfounds = 8
heights = np.max(allconfounds,0)-np.... | print sectionColor + "Regressing out confounds ---------------------------" + mainColor
| random_line_split |
restingstate_preprocess_gica_noscrub.py | #!/usr/bin/env python
#Pre-process Resting State data and does an ICA
import os,sys
from commando import commando
from commando import writeToLog
import argparse
import numpy as np
import re
from datetime import datetime
from subprocess import call
from subprocess import check_output
import csv
import shutil
import p... |
if not os.path.exists(icafolder):
#print red + "ICA-AROMA has not been completed for %s\n%s" % (subject,mainColor)
icalocation = "/Volumes/BCI-1/Matt-Emily/ASD_restingstate/ICA-AROMA/ICA_AROMA.py"
if not os.path.exists(icalocation):
icalocation = "/Volumes/BCI/Matt-Emily/ASD_restingstate/ICA-AROM... | 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 | use shim::io;
use shim::path::{PathBuf, Component};
use alloc::string::String;
use stack_vec::StackVec;
use pi::atags::Atags;
use fat32::traits::{Dir, Entry, FileSystem, Metadata, BlockDevice};
use fat32::vfat::BiosParameterBlock;
use fat32::mbr::MasterBootRecord;
use blockdev::mount::*;
use aes128::edevice::Encrypt... | }
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 | use shim::io;
use shim::path::{PathBuf, Component};
use alloc::string::String;
use stack_vec::StackVec;
use pi::atags::Atags;
use fat32::traits::{Dir, Entry, FileSystem, Metadata, BlockDevice};
use fat32::vfat::BiosParameterBlock;
use fat32::mbr::MasterBootRecord;
use blockdev::mount::*;
use aes128::edevice::Encrypt... |
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 | use shim::io;
use shim::path::{PathBuf, Component};
use alloc::string::String;
use stack_vec::StackVec;
use pi::atags::Atags;
use fat32::traits::{Dir, Entry, FileSystem, Metadata, BlockDevice};
use fat32::vfat::BiosParameterBlock;
use fat32::mbr::MasterBootRecord;
use blockdev::mount::*;
use aes128::edevice::Encrypt... | (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 | import json
import requests
import asyncio
import os
import shlex
from time import time
from datetime import datetime
from os.path import basename
from typing import Tuple, Optional
from uuid import uuid4
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import InlineKeyboardButto... | n InlineKeyboardMarkup(buttons)
def get_auth_btns(media, user, data, lsqry: str = None, lspage: int = None):
btn = []
qry = f"_{lsqry}" if lsqry is not None else ""
pg = f"_{lspage}" if lspage is not None else ""
if media=="CHARACTER":
btn.append(InlineKeyboardButton(text="Add to Fav... | = 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 | import json
import requests
import asyncio
import os
import shlex
from time import time
from datetime import datetime
from os.path import basename
from typing import Tuple, Optional
from uuid import uuid4
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import InlineKeyboardButto... | r, data, lsqry: str = None, lspage: int = None):
btn = []
qry = f"_{lsqry}" if lsqry is not None else ""
pg = f"_{lspage}" if lspage is not None else ""
if media=="CHARACTER":
btn.append(InlineKeyboardButton(text="Add to Favs" if data[1] is not True else "Remove from Favs", callback_data=... | ns(media, use | identifier_name |
helper.py | import json
import requests
import asyncio
import os
import shlex
from time import time
from datetime import datetime
from os.path import basename
from typing import Tuple, Optional
from uuid import uuid4
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import InlineKeyboardButto... | 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 | import json
import requests
import asyncio
import os
import shlex
from time import time
from datetime import datetime
from os.path import basename
from typing import Tuple, Optional
from uuid import uuid4
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import InlineKeyboardButto... | 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 | import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn import datasets, linear_model
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, IntSl... | [18.200, 2.000], [ 5.900, 14.200], [14.550, 3.700]])
X = data[:, 0]
y = data[:, 1]
return X, y
def plot_poly_data(X, y, X_test=None, y_test=None):
font = {'family': 'Verdana', 'weight': 'normal'}
rc('font', **font)
plt.figure(figsize=(10, 8))
plt.rcParams.updat... | [ 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 | import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn import datasets, linear_model
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, IntSl... | , color='red')
axis[0].scatter(x, x**2, color='red')
axis[0].plot(ks, np.abs(ks), label="MAE", color='green')
axis[0].scatter(x, np.abs(x), color='green')
axis[0].set_title("Функция ошибки")
axis[0].set_xticks([])
axis[0].set_yticks([])
axis[0].grid()
... | 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 | import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn import datasets, linear_model
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, IntSl... | ():
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 | import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn import datasets, linear_model
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from ipywidgets import interact, IntSl... | обучения")
plt.plot(x[:,1], y_pred_init, color='g', label="Кривая на начальных параметрах")
plt.legend()
plt.show()
| (X_poly_scaled[:, 1]))
plt.grid()
plt.plot(x[:,1], y_pred, color='r', label="Кривая после | identifier_body |
client_conn.rs | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*;
use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
u... | {
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 | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*; |
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.