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 |
|---|---|---|---|---|
modules.go | api.FullNode
Messager api.IMessager
MarketClient api2.MarketFullNode
MetadataService *service.MetadataService
LogService *service.LogService
SectorInfoService *service.SectorInfoService
Sealer sectorstorage.SectorManager
SectorIDCounter types2.SectorIDCounter
Verifier... | {
accessor(cfg)
return nil
} | identifier_body | |
modules.go | .AuthNew(ctx, []auth.Permission{"admin"})
if err != nil {
return nil, xerrors.Errorf("creating storage auth header: %w", err)
}
headers := http.Header{}
headers.Add("Authorization", "Bearer "+string(token))
return sectorstorage.StorageAuth(headers), nil
}
func MinerID(ma types2.MinerAddress) (types2.MinerID, e... |
si, err := api.StateSectorGetInfo(ctx, maddr, sector, types.EmptyTSK)
if err != nil {
return xerrors.Errorf("getting sector info: %w", err)
} | random_line_split | |
asset.rs | use uuid::Uuid;
use std::sync::Arc;
use error::{Error, Result};
pub struct Asset {
pub name: String,
pub bundle_offset: u64,
pub objects: HashMap<i64, ObjectInfo>,
pub is_loaded: bool,
pub endianness: Endianness,
pub tree: Option<TypeMetadata>,
pub types: HashMap<i64, Arc<TypeNode>>,
pu... | AssetRef | identifier_name | |
asset.rs | Read, Seek, SeekFrom};
use std::io;
use lzma;
use uuid::Uuid;
use std::sync::Arc;
use error::{Error, Result};
pub struct Asset {
pub name: String,
pub bundle_offset: u64,
pub objects: HashMap<i64, ObjectInfo>,
pub is_loaded: bool,
pub endianness: Endianness,
pub tree: Option<TypeMetadata>,
... |
}
self.objects.insert(obj.path_id, obj);
Ok(())
}
pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> {
if self.format >= 14 {
return buffer.read_i64(&self.endianness);
}
let result = buffer.read_i32(&self.endianness)? ... | {} | conditional_block |
asset.rs | ,
name: String::new(),
objects: HashMap::new(),
is_loaded: false,
endianness: Endianness::Big,
tree: None,
types: HashMap::new(),
// when requesting first element it should be the asset itself
asset_refs: vec![AssetOrRef::As... | pub enum AssetOrRef {
Asset,
AssetRef(AssetRef), | random_line_split | |
TripAdvisor.py | .get(URL)
labelEng =''
try:
labelEng = driver.find_element_by_css_selector("[for='taplc_prodp13n_hr_sur_review_filter_controls_0_filterLang_en']")
print('no exception occured')
except:
continue
strNum = labelEng.find_element_by_css_selector('span')
... | if e == '1.0 of 5 bubbles':
result.append('1')
elif e == '2.0 of 5 bubbles':
result.append('2')
elif e == '3.0 of 5 bubbles':
result.append('3')
elif e == '4.0 of 5 bubbles':
result.append('4')
elif e == '5.0 of 5 bubbles':
resu... | conditional_block | |
TripAdvisor.py | URL is called----------')
for postfix in information:
URL = preUrl+postfix[0]+postfix[1]
driver.get(URL)
labelEng =''
try:
labelEng = driver.find_element_by_css_selector("[for='taplc_prodp13n_hr_sur_review_filter_controls_0_filterLang_en']")
print('no exce... | (driver):
result = []
basics = driver.find_elements_by_class_name('inlineReviewUpdate')
for inner in basics:
if inner.text == '': continue
#col = inner.find_element_by_class_name('col1of2')
#memberInfo = inner.find_element_by_class_name('member_info')
try:
locati... | getMemberLocationInfo | identifier_name |
TripAdvisor.py | URL is called----------')
for postfix in information:
URL = preUrl+postfix[0]+postfix[1]
driver.get(URL)
labelEng =''
try:
labelEng = driver.find_element_by_css_selector("[for='taplc_prodp13n_hr_sur_review_filter_controls_0_filterLang_en']")
print('no exce... |
# Collect the reviews from 'TripAdvisor.com'
# Argument: URL for collecting reviews and ratings, STRING
# Return type: none
def collectReviews(driver, URL):
print('----------collectReviews is called----------')
rating = []
dates = []
locations = []
try:
parentOfMore = driver.find_elemen... | print('----------calculateNumOfPages is called----------')
if int(numOfReviews/10) > 0:
if numOfReviews%10 == 0:
numOfPages = int(numOfReviews/10)
else:
numOfPages = int(numOfReviews/10) + 1
elif int(numOfReviews/10) == 0:
if numOfReviews%10 == 0:
numO... | identifier_body |
TripAdvisor.py | )
for i in range(1, numOfPages):
infixPage = 10*i
infix = '-or' + str(infixPage)
URL = preUrl+postfix[0]+infix+postfix[1]
driver.get(URL)
collectReviews(driver, URL)
print('----------completeURL finished----------')
driver.quit()
# Print th... | print('----------readPostifxFormFile finished----------') | random_line_split | |
hooks.py | _BQ_API_VERSION)
return getattr(messages, message_name)
def GetApiClient():
return apis.GetClientInstance(_BQ_API, _BQ_API_VERSION)
# Argument Processors
def JobListProjectionProcessor(show_config):
projection_enum = (
GetApiMessage('BigqueryJobsListRequest').ProjectionValueValuesEnum)
if show_config... |
def ProcessDatasetOverwrite(ref, args, request):
"""Process the if-exists flag on datasets create."""
del ref
dataset_id = request.dataset.datasetReference.datasetId
project_id = request.projectId
if args.overwrite:
if _DatasetExists(dataset_id, project_id):
_TryDeleteDataset(dataset_id, projec... | """Ensure that view parameters are set properly tables create request."""
del ref # unused
if not args.view:
request.table.view = None
return request | identifier_body |
hooks.py | _BQ_API_VERSION)
return getattr(messages, message_name)
def GetApiClient():
return apis.GetClientInstance(_BQ_API, _BQ_API_VERSION)
# Argument Processors
def JobListProjectionProcessor(show_config):
projection_enum = (
GetApiMessage('BigqueryJobsListRequest').ProjectionValueValuesEnum)
if show_config... | (ref, args, request):
"""Process the overwrite flag on tables copy."""
del ref # Unused
if args.overwrite:
request.job.configuration.copy.writeDisposition = 'WRITE_TRUNCATE'
return request
def ProcessTableCopyConfiguration(ref, args, request):
"""Build JobConfigurationTableCopy from request resource a... | ProcessTableCopyOverwrite | identifier_name |
hooks.py | Error parsing data file [{}]'.format(ype))
# Request modifiers
def SetProjectId(ref, args, request):
"""Set projectId value for a BigQueryXXXRequests."""
del ref
project = args.project or properties.VALUES.core.project.Get(required=True)
project_ref = resources.REGISTRY.Parse(project,
... | random_line_split | ||
hooks.py | BQ_API_VERSION)
return getattr(messages, message_name)
def GetApiClient():
return apis.GetClientInstance(_BQ_API, _BQ_API_VERSION)
# Argument Processors
def JobListProjectionProcessor(show_config):
projection_enum = (
GetApiMessage('BigqueryJobsListRequest').ProjectionValueValuesEnum)
if show_config:
... |
return request
def ProcessTableCopyConfiguration(ref, args, request):
"""Build JobConfigurationTableCopy from request resource args."""
del ref # Unused
source_ref = args.CONCEPTS.source.Parse()
destination_ref = args.CONCEPTS.destination.Parse()
arg_utils.SetFieldInMessage(
request, 'job.configu... | request.job.configuration.copy.writeDisposition = 'WRITE_TRUNCATE' | conditional_block |
mod.rs | = Duration::from_secs(60 * 30);
// 'DEBUG'
const DEFAULT_NODE_STATS_LOGGING_DELAY: Duration = Duration::from_millis(60_000);
const DEFAULT_NODE_STATS_UPDATING_DELAY: Duration = Duration::from_millis(30_000);
const DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF: Duration = Duration::from_millis(10_000);
const DEFAULT_PACKE... | }
} | random_line_split | |
mod.rs | ::helpers::inaddr_any;
use nym_config::{
must_get_home, read_config_from_toml_file, save_formatted_config_to_file, NymConfigTemplate,
DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME, DEFAULT_DATA_DIR, NYM_DIR,
};
use serde::{Deserialize, Serialize};
use std::io;
use std::net::IpAddr;
use std::path::{Path, PathBuf};... | (mut self, port: u16) -> Self {
self.mixnode.mix_port = port;
self
}
pub fn with_verloc_port(mut self, port: u16) -> Self {
self.mixnode.verloc_port = port;
self
}
pub fn with_http_api_port(mut self, port: u16) -> Self {
self.mixnode.http_api_port = port;
... | with_mix_port | identifier_name |
maximin.py | lower
own_tokens[token].append(pos)
score = num_defeated * 1.5
# assign values to own tokens as [# beatable]/[# identical * closest enemy dist]
for hand, positions in own_tokens.items():
if len(positions) > 0: # check that there are instances of the hand first
beat... |
# subtract number of opponent tokens on the board
for hand, positions in opp_tokens.items():
for position in positions:
score -= 1
return score
class Player:
def __init__(self, player):
"""
Called once at the beginning of a game to initialise this player.
... | min_target_dist = inf
for target in targets:
target_dist = dist(position, target)
if target_dist < min_target_dist:
min_target_dist = target_dist
if min_target_dist == 0: # this shouldn't happen as the opponent shoul... | conditional_block |
maximin.py | lower
own_tokens[token].append(pos)
score = num_defeated * 1.5
# assign values to own tokens as [# beatable]/[# identical * closest enemy dist]
for hand, positions in own_tokens.items():
if len(positions) > 0: # check that there are instances of the hand first
beat... | for s in "rps":
yield "THROW", s, x
occupied = {x for x, s in self.board.items() if any(map(isplayer, s))}
for x in occupied:
adjacent_x = self._ADJACENT(x)
for y in adjacent_x:
yield "SLIDE", x, y
if y in occupi... | (r, q) for r, q in self._SET_HEXES if sign * r >= 4 - throws
)
for x in throw_zone: | random_line_split |
maximin.py | {}, target position: {}".format(position, target))
score += init_value/min_target_dist
# subtract number of opponent tokens on the board
for hand, positions in opp_tokens.items():
for position in positions:
score -= 1
return score
class Playe... | """
Submit an action to the game for validation and application.
If the action is not allowed, raise an InvalidActionException with
a message describing allowed actions.
Otherwise, apply the action to the game state.
"""
# validate the actions:
for action, c in [(... | identifier_body | |
maximin.py |
own_tokens[token].append(pos)
score = num_defeated * 1.5
# assign values to own tokens as [# beatable]/[# identical * closest enemy dist]
for hand, positions in own_tokens.items():
if len(positions) > 0: # check that there are instances of the hand first
beats = be... | :
def __init__(self, player):
"""
Called once at the beginning of a game to initialise this player.
Set up an internal representation of the game state.
The parameter player is the string "upper" (if the instance will
play as Upper), or the string "lower" (if the instance wi... | Player | identifier_name |
HAN_Evaluator.py | .val_max_sent_length
}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.alphas_sent], feed_dict=feed_dict)
#pred, a1, A = sess.run([predictions, model.alphas1, model.alphas2, model.alphas3, model.alphas4],
#feed_dict=feed_dict)
a_wor... | return 0 | conditional_block | |
HAN_Evaluator.py | =0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print("averages-------")
print(results)
print("------------")
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = ... | color = (0.0, 0.0, 0.0)
else:
color = (1.0, 1.0, 1.0)
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != "PAD":
word = sentence[i, j]
else:
word = ""
fontsize = _font_size(len(word))
... | x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5): | random_line_split |
HAN_Evaluator.py | 0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print("averages-------")
print(results)
print("------------")
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = "... | (data):
#data = np.array(data)
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
#max_weight = attention_weights.max()
#attention_weights = attention_weights/max_weight # increase weights to make... | visualize_attention | identifier_name |
HAN_Evaluator.py | =0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print("averages-------")
print(results)
print("------------")
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = ... |
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse=True)
print(sorted_correct[0:2])
#selection = sorted_correct[1]
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5]))
#selection_zipped_tuple = list(zip(selection[0], selection[4]))
selection_zipped... | return (x[3])[(x[2])] | identifier_body |
inb4404.py | = os.path.join(script_path, "downloads")
# Whether to use the original filenames or UNIX timestamps
# True -> original filenames
# False -> UNIX timestamps
self.USE_NAMES = False
# Path to an archive file (holds MD5 hashes of downloaded files)
self.ARCHIVE = None
... |
def parse_cli():
"""Parse the command line arguments with argparse."""
defaults = DefaultOptions()
parser = CustomArgumentParser(usage="%(prog)s [OPTIONS] THREAD [THREAD]...")
parser.add_argument("thread", nargs="*", help="thread URL")
parser.add_argument(
"-l", "--list", action="append"... | """Convert string provided by argparse to an archive path."""
path = os.path.abspath(string)
try:
with open(path, "r") as f:
_ = f.read(1)
except FileNotFoundError:
pass
except (OSError, UnicodeError):
raise argparse.ArgumentTypeError(f"{path} is not a valid archive!"... | identifier_body |
inb4404.py | = os.path.join(script_path, "downloads")
# Whether to use the original filenames or UNIX timestamps
# True -> original filenames
# False -> UNIX timestamps
self.USE_NAMES = False
# Path to an archive file (holds MD5 hashes of downloaded files)
self.ARCHIVE = None
... | (self, position, link):
"""Initialize thread object."""
self.count = 0
self.files = []
self.pos = position
self.link = link.split("#")[0]
info = link.partition(".org/")[2]
# info has the form <board>/thread/<thread> or <board>/thread/<thread>/<dir name>
i... | __init__ | identifier_name |
inb4404.py | = os.path.join(script_path, "downloads")
# Whether to use the original filenames or UNIX timestamps
# True -> original filenames
# False -> UNIX timestamps
self.USE_NAMES = False
# Path to an archive file (holds MD5 hashes of downloaded files)
self.ARCHIVE = None
... | # Retries imply attempts after the first try failed
# So the max. number of attempts is opts.retries+1
attempt = 0
while attempt <= opts.retries or opts.retries < 0:
if attempt > 0:
err(f"Retrying... ({attempt} out of "
f"{opts.retries if o... | err(f"Thread 404'd!")
return
msg(f"{self.fetch_progress()} {self.link}")
| random_line_split |
inb4404.py | = os.path.join(script_path, "downloads")
# Whether to use the original filenames or UNIX timestamps
# True -> original filenames
# False -> UNIX timestamps
self.USE_NAMES = False
# Path to an archive file (holds MD5 hashes of downloaded files)
self.ARCHIVE = None
... |
else:
progress = t_progress
return progress
async def get_file(self, link, name, md5, session):
"""Download a single file."""
if os.path.exists(name) or md5 in opts.archived_md5:
self.count += 1
return
async with session.get(link) as me... | progress = f"{t_progress} {f_progress}" | conditional_block |
barista-examples.ts | -runner';
const ARGS_TO_OMIT = 3;
const DEPLOY_URL_ARG = 'deploy-url';
const projectRoot = join(__dirname, '../../..');
const environmentsDir = join(
projectRoot,
'src',
'barista-examples',
'environments',
);
const args = process.argv.splice(ARGS_TO_OMIT);
const getDeployUrl = () => {
const deployUrlArg = ... | }
/** Parse the AST of the given source file and collects Angular component metadata. */
export function retrieveExampleTemplateContent(fileName: string, content: string): string | undefined {
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, false);
const componentTemplates: strin... | {
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, false);
const componentClassNames: string[] = [];
// tslint:disable-next-line:no-any
const visitNode = (node: any): void => {
if (node.kind === ts.SyntaxKind.ClassDeclaration) {
if (node.decorators && node.decorators.l... | identifier_body |
barista-examples.ts | -runner';
const ARGS_TO_OMIT = 3;
const DEPLOY_URL_ARG = 'deploy-url';
const projectRoot = join(__dirname, '../../..');
const environmentsDir = join(
projectRoot,
'src',
'barista-examples',
'environments',
);
const args = process.argv.splice(ARGS_TO_OMIT);
const getDeployUrl = () => {
const deployUrlArg = ... | .join('\n');
const exampleList = parsedData.map(m => m.component);
return fs
.readFileSync(join(examplesDir, './app.module.template'), 'utf8')
.replace('${imports}', exampleImports)
.replace('${examples}', `[\n ${exampleList.join(',\n ')},\n]`);
}
/** Generates the imports for each example file ... |
/** Inlines the app module template with the specified parsed data. */
function populateAppModuleTemplate(parsedData: ExampleMetadata[]): string {
const exampleImports = parsedData
.map(m => buildImportsTemplate(m)) | random_line_split |
barista-examples.ts | -runner';
const ARGS_TO_OMIT = 3;
const DEPLOY_URL_ARG = 'deploy-url';
const projectRoot = join(__dirname, '../../..');
const environmentsDir = join(
projectRoot,
'src',
'barista-examples',
'environments',
);
const args = process.argv.splice(ARGS_TO_OMIT);
const getDeployUrl = () => {
const deployUrlArg = ... |
done();
});
/** Creates the examples module */
task('barista-example:generate', done => {
const metadata = getExampleMetadata(glob(join(examplesDir, '*/*.ts')));
generateAppModule(metadata, 'app.module.ts', examplesDir);
generateAppComponent(metadata);
const routeData = flatten(generateRouteMetadata(metada... | {
const errors = invalidExampleRefs.map(
ref => `Invalid example name "${ref.name}" found in ${ref.sourcePath}.`,
);
const errorMsg = errors.join('\n');
done(errorMsg);
return;
} | conditional_block |
barista-examples.ts | -runner';
const ARGS_TO_OMIT = 3;
const DEPLOY_URL_ARG = 'deploy-url';
const projectRoot = join(__dirname, '../../..');
const environmentsDir = join(
projectRoot,
'src',
'barista-examples',
'environments',
);
const args = process.argv.splice(ARGS_TO_OMIT);
const getDeployUrl = () => {
const deployUrlArg = ... | (
parsedData: ExampleMetadata[],
outputFile: string,
baseDir: string,
): void {
const generatedModuleFile = populateAppModuleTemplate([...parsedData]);
const generatedFilePath = join(baseDir, outputFile);
if (!fs.existsSync(dirname(generatedFilePath))) {
fs.mkdirSync(dirname(generatedFilePath));
}
f... | generateAppModule | identifier_name |
interpreter.rs | : &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be d... | Ok(write_env)
}
/// Evaluate guard implementation
#[allow(clippy::borrowed_box)]
// XXX: Allow for this warning. It would make sense to use a reference when we
// have the `box` match pattern available in Rust.
fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 {
(match &**guard {
ir::Guar... | write_env.map.get(&done_cell)
);*/ | random_line_split |
interpreter.rs | : &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be d... | (assigns: &[ir::Assignment]) -> &ir::Assignment {
assigns
.iter()
.find(|assign| {
let dst = assign.dst.borrow();
dst.is_hole() && dst.name == "done"
})
.expect("Group does not have a done signal")
}
/// Determines if writing a particular cell and cell port i... | get_done_signal | identifier_name |
interpreter.rs | : &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be d... | // queue any required updates.
//determine if dst_cell is a combinational cell or not
if is_combinational(&dst_cell, &assign.dst.borrow().name, env) {
// write to assign.dst to e2 immediately, if combinational
write_env.put(
... | {
// check if the cells are constants?
// cell of assign.src
let src_cell = get_cell_from_port(&assign.src);
// cell of assign.dst
let dst_cell = get_cell_from_port(&assign.dst);
/*println!(
"src cell {:... | conditional_block |
interpreter.rs | : &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be d... | }
ir::Guard::Geq(g1, g2) => {
env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow())
}
ir::Guard::Leq(g1, g2) => {
env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow())
}
ir::Guard::Port(p) => env.get_from_port(&p.borrow())... | {
(match &**guard {
ir::Guard::Or(g1, g2) => {
(eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1)
}
ir::Guard::And(g1, g2) => {
(eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1)
}
ir::Guard::Not(g) => eval_guard(g, &env) != 0,
ir::... | identifier_body |
dg.py | (csvfile)
spamwriter.writerow(first_row)
for index in xrange(len(Nlist)):
# print poi.get(str(Nlist[index]))
spamwriter.writerow(poi.get(str(Nlist[index]), None))
def plot_whole_network(DG):
# pos = random_layout(DG)
# pos = shell_layout(DG) | pos = spring_layout(DG)
# pos = spectral_layout(DG)
# plt.title('Plot of Network')
draw(DG, pos)
plt.show()
def pdf(data, xmin=None, xmax=None, linear_bins=False, **kwargs):
if not xmax:
xmax = max(data)
if not xmin:
xmin = min(data)
if linear_bins:
bins = rang... | random_line_split | |
dg.py | (csvfile)
spamwriter.writerow(first_row)
for index in xrange(len(Nlist)):
# print poi.get(str(Nlist[index]))
spamwriter.writerow(poi.get(str(Nlist[index]), None))
def plot_whole_network(DG):
# pos = random_layout(DG)
# pos = shell_layout(DG)
pos = spring_layout(DG)
# pos = spec... |
def rmse(predict, truth):
# calculate RMSE of a prediction
RMSE = mean_squared_error(truth, predict)**0.5
return RMSE
def mean_bin(list_x, list_y, linear_bins=False):
# the returned values are raw values, not logarithmic values
size = len(list_x)
xmin = min(list_x)
xmax = max(list_x)
... | return [i for i in list_a if i>0] | identifier_body |
dg.py | (csvfile)
spamwriter.writerow(first_row)
for index in xrange(len(Nlist)):
# print poi.get(str(Nlist[index]))
spamwriter.writerow(poi.get(str(Nlist[index]), None))
def plot_whole_network(DG):
# pos = random_layout(DG)
# pos = shell_layout(DG)
pos = spring_layout(DG)
# pos = spec... |
new_bin_means_y.append(sum_y/hist_x[index])
return new_bin_meanx_x, new_bin_means_y
def cut_lists(list_x, list_y, fit_start=-1, fit_end=-1):
if fit_start != -1:
new_x, new_y = [], []
for index in xrange(len(list_x)):
if list_x[index] >= fit_start:
new_x... | key = list_x[i]
if (key >= range_min) and (key < range_max):
sum_y += list_y[i] | conditional_block |
dg.py | (csvfile)
spamwriter.writerow(first_row)
for index in xrange(len(Nlist)):
# print poi.get(str(Nlist[index]))
spamwriter.writerow(poi.get(str(Nlist[index]), None))
def plot_whole_network(DG):
# pos = random_layout(DG)
# pos = shell_layout(DG)
pos = spring_layout(DG)
# pos = spec... | (list_x, list_y, linear_bins=False):
# the returned values are raw values, not logarithmic values
size = len(list_x)
xmin = min(list_x)
xmax = max(list_x)
if linear_bins:
bins = range(int(xmin), int(xmax+1))
else:
log_min_size = np.log10(xmin)
log_max_size = np.log10(xmax... | mean_bin | identifier_name |
lib.rs | H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d != 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log di... |
if *current_bucket == *max_bucket {
return None;
}
*current_bucket += 1;
*current_bucket_remaining = None;
}
}
}
pub enum DiscoveryRequest {
Ping,
}
pub enum DiscoveryResponse {
Pong,
}
pub enum DiscoveryPacket {
WhoAreYou,
... | {
// Safety: we have exclusive access to underlying node table
return Some(unsafe { &mut *ptr.as_ptr() });
} | conditional_block |
lib.rs | H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d != 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log di... |
}
pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator ... | {
Closest(NodeEntries {
node_table: self,
current_bucket: 0,
max_bucket: 255,
current_bucket_remaining: None,
})
} | identifier_body |
lib.rs | self.bucket(node_id)?;
bucket.nodes.get_mut(&node_id.0)
}
pub fn add_node(&mut self, record: Enr<K>, peer_state: PeerState) {
let node_id = H256(record.node_id().raw());
// If we don't have such node already...
if !self.all_nodes.contains(&node_id.0) {
// Check tha... | test_iterator | identifier_name | |
lib.rs | ptr::NonNull,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
net::UdpSocket,
prelude::*,
stream::{StreamExt, *},
};
use tokio_util::{codec::*, udp::*};
pub mod proto;
pub mod topic;
pub type RawNodeId = [u8; 32];
#[must_use]
pub fn distance(a: H256, b: H256) -> U256 {
U256... | ops::BitXor, | random_line_split | |
codewander-plotlyScatterPlot.js | label:'lines+markers'}],
defaultValue:'markers'
},
markerSize: {
type: "integer",
label: "Marker Size",
ref: "markerSize",
defaultValue: 12
},
highlightFirstPoint:{
type: "boolean",
ref: "highlightFirstPoint",
label:... |
//var ff=window.getComputedStyle(getElementsByTagName("body")[0],null).getPropertyValue("font-family") ;
var pdisplayModeBar=false
if (self.$scope.layout.generalSettings.displayModeBar=='1') {pdisplayModeBar=true}
else if (self.$scope.layout.generalSettings.displayModeBar=='-1') {pdisplayMo... | {
rightMargin=rightMargin + 100
} | conditional_block |
codewander-plotlyScatterPlot.js | ',label:'lines+markers'}],
defaultValue:'markers'
},
markerSize: {
type: "integer",
label: "Marker Size",
ref: "markerSize",
defaultValue: 12
},
highlightFirstPoint:{
type: "boolean",
ref: "highlightFirstPoint",
labe... | (Matrix)
{
var data=[];
var total_series_count = measures_count/2;
var series | convert | identifier_name |
codewander-plotlyScatterPlot.js | Value:"",
expression: "always"
},
showGrid: {
type: "boolean",
ref: "xAxisSettings.showGrid",
label: "Show Grid",
defaultValue: true
},
showLine: {
type: "boolean",
ref: "xAxisSettings.showLine",
l... | {
var data=[];
var total_series_count = measures_count/2;
var series_array =[]
var settingArrayLength = self.$scope.layout.seriesSettings.length;
var settingArray=self.$scope.layout.seriesSettings;
for (var i =0 ;i<total_series_count;i++)
{
var series={}
series.x=[];
... | identifier_body | |
codewander-plotlyScatterPlot.js | Zero Line",
ref: "xAxisSettings.showZeroLine",
defaultValue:true
},
showTicklabels: {
type: "boolean",
label: "Show Tick Labels",
ref: "xAxisSettings.showTicklabels",
defaultValue: true
}
}
},
YAxisSettings: {
type:... | series.marker={size:12}
}
series_array.push(series);
} | random_line_split | |
sdr_rec_type.go | Sensor) SetMBExp(M int16, B int16, Bexp int8, Rexp int8) {
r.MTol = 0
r.Bacc = 0
r.RBexp = 0
_M := uint16(math.Abs(float64(M)))
_M = _M & 0x01ff //mask leave low 9bit
if M < 0 {
_M = (((^_M) + 1) & 0x01ff) | 0x0200
}
r.MTol = r.MTol | (_M & 0x00ff)
r.MTol = r.MTol | ((_M << 6) & 0xc000)
_B := uint16(math... | UnmarshalBinary | identifier_name | |
sdr_rec_type.go | 1ff) | 0x0200
}
r.Bacc = r.Bacc | (_B & 0x00ff)
r.Bacc = r.Bacc | ((_B << 6) & 0xc000)
_Bexp := uint8(math.Abs(float64(Bexp)))
_Bexp = _Bexp & 0x07 //mask leeve low 3bit
if Bexp < 0 {
_Bexp = (((^_Bexp) + 1) & 0x07) | 0x08
}
r.RBexp = r.RBexp | (_Bexp & 0x0f)
_Rexp := uint8(math.Abs(float64(Rexp)))
_Rexp ... | Reserved [3]byte
EntityID uint8 | random_line_split | |
sdr_rec_type.go | ())
//merge all
recLen := uint8(fb.Len() + db.Len())
hb.WriteByte(byte(recLen))
hb.Write(fb.Bytes())
hb.Write(db.Bytes())
return hb.Bytes(), nil
}
// section 43.1
type sdrFullSensorFields struct { //size 42
SensorOwnerId uint8
SensorOwnerLUN uint8
SensorNumber uint8
EntityId ... | {
buffer := bytes.NewReader(data)
err := binary.Read(buffer, binary.LittleEndian, &r.SDRRecordHeader)
if err != nil {
return err
}
//skip the record length
_, err = buffer.ReadByte()
if err != nil {
return err
}
binary.Read(buffer, binary.LittleEndian, &r.sdrFullSensorFields)
idLen, err := buffer.ReadB... | identifier_body | |
sdr_rec_type.go | 0x01ff) | 0x0200
}
r.MTol = r.MTol | (_M & 0x00ff)
r.MTol = r.MTol | ((_M << 6) & 0xc000)
_B := uint16(math.Abs(float64(B)))
_B = _B & 0x01ff //mask leave low 9bit
if B < 0 {
_B = (((^_B) + 1) & 0x01ff) | 0x0200
}
r.Bacc = r.Bacc | (_B & 0x00ff)
r.Bacc = r.Bacc | ((_B << 6) & 0xc000)
_Bexp := uint8(math.A... | {
return err
} | conditional_block | |
bytesearch.rs | ::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_le... |
}
None
}
}
// CharSet helper. Avoid branching in the loop to get good unrolling.
#[allow(unused_parens)]
#[inline(always)]
pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool {
let mut result = false;
for &v in set.iter() {
result |= (v == c);
}
result... | {
return Some(idx);
} | conditional_block |
bytesearch.rs | (&self, rhs: &[u8]) -> bool {
debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length");
if cfg!(feature = "prohibit-unsafe") {
// Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare.
self == rhs
... | equals_known_len | identifier_name | |
bytesearch.rs | {
fn contains(self, b: u8) -> bool;
fn find_in(self, rhs: &[u8]) -> Option<usize>;
}
// Beware: Rust is cranky about loop unrolling.
// Do not try to be too clever here.
impl SmallArraySet for [u8; 2] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1]
}
... | impl fmt::Debug for ByteBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | random_line_split | |
bytesearch.rs | ::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_le... |
/// Set a bit in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
let byte = val >> 4;
let bit = val & 0xF;
self.0[byte as usize] |= 1 << bit;
}
/// Update ourselves from another bitmap, in place.
pub fn bitor(&mut self, rhs: &ByteBitmap) {
for i... | {
let byte = val >> 4;
let bit = val & 0xF;
(self.0[byte as usize] & (1 << bit)) != 0
} | identifier_body |
trainer.py | eg_index)
num_pos = len(pos_index)
dice = {"dice_all": dice}
if self.get_class_metric:
num_classes = probability.shape[1]
for c in range(num_classes):
iflat = probability[:, c,...].view(batch_size, -1)
tflat = ... | self.net.load_state_dict(new_state_dict)
else:
try:
self.net.load_state_dict(chkpt['state_dict'])
except:
new_state_dict = fix_multigpu_chkpt_names(chkpt['state_dict'], drop=True)
self.net.load_state_dict(new_state_dict)
... | self.best_metric = chkpt['best_metric']
# fix the DataParallel caused problem with keys names
if self.multi_gpu_flag:
new_state_dict = fix_multigpu_chkpt_names(chkpt['state_dict'], drop=False) | random_line_split |
trainer.py | eg_index)
num_pos = len(pos_index)
dice = {"dice_all": dice}
if self.get_class_metric:
num_classes = probability.shape[1]
for c in range(num_classes):
iflat = probability[:, c,...].view(batch_size, -1)
tflat = ... | (state_dict, drop=False):
""" fix the DataParallel caused problem with keys names """
new_state_dict = {}
for k in state_dict:
if drop:
new_k = re.sub("module.", "", k)
else:
new_k = "module." + k
new_state_dict[new_k] = copy.deepcopy(state_dict[k])
return... | fix_multigpu_chkpt_names | identifier_name |
trainer.py | dice_neg = np.mean(self.dice_neg_scores[phase])
dice_pos = np.mean(self.dice_pos_scores[phase])
dices = [dice, dice_neg, dice_pos]
iou = np.nanmean(self.iou_scores[phase])
return dices, iou
def epoch_log(self, phase, epoch_loss, itr):
'''logging the metrics at the end of an... | for param in param_group['params']:
param.data = param.data.add(-1.*self.weights_decay * param_group['lr'], param.data) | conditional_block | |
trainer.py |
def fix_multigpu_chkpt_names(state_dict, drop=False):
""" fix the DataParallel caused problem with keys names """
new_state_dict = {}
for k in state_dict:
if drop:
new_k = re.sub("module.", "", k)
else:
new_k = "module." + k
new_state_dict[new_k] = copy.deep... | """dumpы all metrics and training meta-data"""
for dict_name in ["losses", "dice_scores", "iou_scores"]:
pickle.dump(self.__dict__[dict_name], open(f"{self.model_path}/{dict_name}.pickle.dat", "wb"))
# dump class variables for further traning
training_meta = {}
for k in self... | identifier_body | |
Zichen Pan - S&P500.py | 20))
_ = plt.title('Stock AA Daily Volume By Rolling of a Week', fontdict = {'fontsize':30})
# In[35]:
# Correlation
sp500_plot.corr()
# In[36]:
df_close = sp500_plot.loc[sp500_plot['Ticker'] == 'A', ['Daily Closing Price']]
pd.plotting.autocorrelation_plot(df_close);
# In[37]:
df_volume = sp500_plot.loc[s... | random_line_split | ||
Zichen Pan - S&P500.py |
with open("sp500tickers.pickle", "wb") as f:
pickle.dump(tickers, f)
return tickers
# In[3]:
tickers = sorted(save_sp500_tickers())
tickers[0]
# In[4]:
# get first stock ('A') from yahoo
start_date = datetime.date(2018,1,1)
end_date = datetime.date.today()
current_ticker = pdr.get_data_yahoo(s... | ticker = row.findAll('td')[0].text
tickers.append(ticker) | conditional_block | |
Zichen Pan - S&P500.py | # cursor
crsr = connection.cursor()
# In[16]:
# drop table if necessary (to rerun the create command, or error: table already exists)
crsr.execute("""DROP TABLE sp500_df""")
# In[17]:
crsr.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = crsr.fetchall()
print(tables)
# In[18]:
# SQL ... | (timeseries):
#Determing rolling statistics
rolmean = timeseries.rolling(7).mean()
rolstd = timeseries.rolling(7).std()
#Plot rolling statistics:
orig = plt.plot(timeseries, color='blue',label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd... | test_stationarity | identifier_name |
Zichen Pan - S&P500.py | exists)
crsr.execute("""DROP TABLE sp500_df""")
# In[17]:
crsr.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = crsr.fetchall()
print(tables)
# In[18]:
# SQL command to create a table in the database
sql_command_create = """CREATE TABLE sp500_df (
NUM INTEGER PRIMARY KEY,
Ticker VARCHAR(... | rolmean = timeseries.rolling(7).mean()
rolstd = timeseries.rolling(7).std()
#Plot rolling statistics:
orig = plt.plot(timeseries, color='blue',label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd, color='black', label = 'Rolling Std')
plt.legend(lo... | identifier_body | |
context.go | handlers/middlewares who used this context.
Errors errorMsgs
}
/************************************/
/************* 创建上下文 *************/
/********** CONTEXT CREATION ********/
/************************************/
func (c *Context) reset() {
c.Response.Headers = make(map[string]string) // 空 map 需要初始化后才可以使用
c.Ke... | tcut for c.ShouldBindWith(obj, binding.JSON).
func (c *Context) ShouldBindJSON(obj interface{}) error {
return c.ShouldBindWith(obj, binding.JSON)
}
// ShouldBindWith 使用指定的绑定引擎绑定数据到传递到结构体指针
// ShouldBindWith binds the passed struct pointer using the specified binding engine.
// See the binding package.
func (c *Conte... | ShouldBindJSON 是 c.ShouldBindWith(obj, binding.JSON) 的快捷方式
// ShouldBindJSON is a shor | identifier_body |
context.go | the handlers/middlewares who used this context.
Errors errorMsgs
}
/************************************/
/************* 创建上下文 *************/
/********** CONTEXT CREATION ********/
/************************************/
func (c *Context) reset() {
c.Response.Headers = make(map[string]string) // 空 map 需要初始化后才可以使用
... | // ShouldBindJSON 是 c.ShouldBindWith(obj, binding.JSON) 的快捷方式
// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
func (c *Context) ShouldBindJSON(obj interface{}) error {
return c.ShouldBindWith(obj, binding.JSON)
}
// ShouldBindWith 使用指定的绑定引擎绑定数据到传递到结构体指针
// ShouldBindWith binds the passed stru... | random_line_split | |
context.go | 入 HTTP 响应头, 然后把错误推送进 `c.Errors`
// 可以查看 Context.Error() 获取更多细节
// AbortWithError calls `AbortWithStatus()` and `Error()` internally.
// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
// See Context.Error() for more details.
func (c *Context) AbortWithError(code int, er... | set. Suc | identifier_name | |
context.go | 增加 handler
c.Errors = c.Errors[0:0]
}
/************************************/
/************* 调用链控制 *************/
/*********** FLOW CONTROL ***********/
/************************************/
// Next 应该确保只在中间件中使用
// 调用 Next 时会开始执行被挂在调用链中的后续 Handlers
// Next should be used only inside middleware.
// It executes the p... | &c.Response); err != nil {
panic(err)
}
}
// JSON 将给定的结构序列化为 JSON 类型后添加到响应体中
// 并且设置响应头中的 Content-Type 为 "application/json"
func | conditional_block | |
texel.rs | pub(crate) mod constants {
use super::{AsTexel, MaxAligned, Texel};
macro_rules! constant_texel {
($(($name:ident, $type:ty)),*) => {
$(pub const $name: Texel<$type> = Texel(core::marker::PhantomData) ;
impl AsTexel for $type {
fn texel() -> Texel<Self> {
... | () -> Texel<[T; 6]> {
T::texel().array::<6>()
}
}
impl<T: AsTexel> AsTexel for [T; 7] {
fn texel() -> Texel<[T; 7]> {
T::texel().array::<7>()
}
}
impl<T: AsTexel> AsTexel for [T; 8] {
fn texel() -> Texel<[T; 8]> {
T::texel().array::<8... | texel | identifier_name |
texel.rs | to be aligned to `ALIGNMENT`.
pub fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX... | self.cast_mut_bytes(texel)
}
| identifier_body | |
texel.rs | have an alignment of *at most* `MAX_ALIGN`.
/// - The type must *not* be a ZST.
/// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
pub const fn for_type() -> Option<Self> {
if Texel::<P>::check_invariants() {
Some(Texel(PhantomData))
} els... | None
}
| conditional_block | |
texel.rs | #![allow(unsafe_code)]
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use core::marker::PhantomData;
use core::{fmt, hash, mem, num, ptr, slice};
use crate::buf::buf;
/// Marker struct to denote a texel type.
///
/// Can be constructed only for types that have expected alignment and no byte invariants. I... | random_line_split | ||
lib.rs | ))
}
fn into_path(py: Python, pointer: JSONPointer) -> PyResult<Py<PyList>> {
let path = PyList::empty(py);
for chunk in pointer {
match chunk {
jsonschema::paths::PathChunk::Property(property) => {
path.append(property.into_string())?
}
jsonschem... | from_str | identifier_name | |
lib.rs | PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyErr> {
slf.iter.next()
}
}
fn into_py_err(py: Python, error: jsonschema::ValidationError) -> PyResult<PyErr> {
let pyerror_type = PyType::new::<ValidationError>(py);
let message = error.to_string()... | message.push(']');
}
message.push(':');
message.push_str("\n ");
message.push_str(&error.instance.to_string());
message
}
/// is_valid(schema, instance, draft=None, with_meta_schemas=False)
///
/// A shortcut for validating the input instance against the schema.
///
/// >>> is_valid(... | jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()),
// Keywords are not used for instances
jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"),
}; | random_line_split |
lib.rs | };
};
if let Some(last) = error.schema_path.last() {
message.push(' ');
push_chunk(&mut message, last)
}
message.push_str(" in schema");
let mut chunks = error.schema_path.iter().peekable();
while let Some(chunk) = chunks.next() {
// Skip the last element as it is alrea... | {
iter_on_error(py, &self.schema, instance)
} | identifier_body | |
view-profile.component.ts | { UserControllerService } from '../../services/api/user-controller.service';
import { Car } from '../../models/car.model';
import { Link } from '../../models/link.model';
import { GeocodeService } from '../../services/geocode.service';
import { CustomtimePipe} from '../../pipes/customtime.pipe';
/**
* Represents the... |
//loads the first car. done this way because original batch made car-user relationship a 1 to many
//should've been a one to one
console.log("PRINTING OUT CAR = " + this.principal.cars[0].match(/\d+/)[0]);
this.userService.getCarById(Number(this.principal.cars[0].match(/\d+/)[... | {
this.authService.principal.subscribe(user => {
this.principal = user;
if (this.principal.id > 0) {
this.existingBio = this.principal.bio;
this.firstName = this.principal.firstName;
this.lastName = this.principal.lastName;
this.username = this.principal.email;
th... | identifier_body |
view-profile.component.ts | { UserControllerService } from '../../services/api/user-controller.service';
import { Car } from '../../models/car.model';
import { Link } from '../../models/link.model';
import { GeocodeService } from '../../services/geocode.service';
import { CustomtimePipe} from '../../pipes/customtime.pipe';
/**
* Represents the... | populateLocation() {
this.locationSerivce.getlocation(this.principal.location).subscribe(data => {
console.log(data);
this.principal.location = data;
});
}
/**
* Enables limited ability to modify the User's role in the system
*/
switchRole() {
if (this.principal.role === Role.Driv... | this.populateLocation();
}
//Populate user location by finding the latitude and logitude via Maps service. | random_line_split |
view-profile.component.ts | { UserControllerService } from '../../services/api/user-controller.service';
import { Car } from '../../models/car.model';
import { Link } from '../../models/link.model';
import { GeocodeService } from '../../services/geocode.service';
import { CustomtimePipe} from '../../pipes/customtime.pipe';
/**
* Represents the... | (id: number) {
this.result = window.confirm('Are you sure you want to make this trainer a rider?');
if (this.result) {
this.userService.updateRole(id, Role.Rider).then();
location.reload(true);
} else {
alert('No changes will be made');
}
}
makeTrainer(id: number) {
this.resul... | makeRider | identifier_name |
view-profile.component.ts | ocodeService } from '../../services/geocode.service';
import { CustomtimePipe} from '../../pipes/customtime.pipe';
/**
* Represents the page that allows users to view (and edit) their profile
*/
@Component({
selector: 'app-view-profile',
templateUrl: './view-profile.component.html',
styleUrls: ['./view-profile... | {
this.userService.updateRole(id, Role.Admin).then();
location.reload(true);
} | conditional_block | |
main_2.py |
exp_date BETWEEN '{year}-{month}-01' AND '{year}-{month}-{days_in_month}'
AND exp_type = 'DR'
AND username = '{user}';""")
try:
expense = cursor.fetchone()[0]
if expense == None:
expense = 0
except TypeError:
print("No records found. Setting expense... |
else:
# plt.clf()
return plot_graphs()
# graph_active = True
cursor.close()
# <------------------------------- Beginning of Matplotlib helper code -----------------------> #
# <----- Taken from https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib.py ----->... | return plot_graphs() | conditional_block |
main_2.py | Union[str, int],
n: int = 10000,
start_date: str = f"{year}-{month}-1",
end_date: str = f"{year}-{month}-{day}",
asc_or_desc: str = "ASC",
orderer: str = "particulars") -> List[Tuple]:
headings = [
"Par... | random_line_split | ||
main_2.py |
exp_date BETWEEN '{year}-{month}-01' AND '{year}-{month}-{days_in_month}'
AND exp_type = 'DR'
AND username = '{user}';""")
try:
expense = cursor.fetchone()[0]
if expense == None:
expense = 0
except TypeError:
print("No records found. Setting expense... | (user: Union[str, int],
n: int = 10000,
start_date: str = f"{year}-{month}-1",
end_date: str = f"{year}-{month}-{day}",
asc_or_desc: str = "ASC",
orderer: str = "particulars") -> List[Tuple]:
headings = [
... | get_transactions | identifier_name |
main_2.py | \ \
# \ \_______\ \_______\ \__\
# \|_______|\|_______|\|__|
'''
Why am I using a class to store all my GUI functions?
-> So that I could use locally created values like vals and user_details within other functions
and to prevent me from getting a headache while managing scopes.
No, seriously though, ... | income, expenses = get_income_and_expense(self.user.uname)
if (income, expenses) == (None, None):
dash_layout = [
[T(f"Welcome {self.user.first_name}")],
[T("Looks like you have no transactions!\nGo add one in the Transactions tab.",
justification=... | identifier_body | |
calSettings.py | size: self.size
pos: self.pos
<HolidayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:
Color:
rgba: (128, 0, 128, 0.5)
Rectangle:
pos: self.pos
size: self.size
<HalfdayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:... |
self.right_arrow = Button(text=">", on_press=self.go_next,
pos_hint={"top": 1, "right": 1}, size_hint=(.1, .1))
self.add_widget(self.left_arrow)
self.add_widget(self.right_arrow)
# Title
self.title_label = Label(text=self.title, pos_hint=... | self.left_arrow = Button(text="<", on_press=self.go_prev,
pos_hint={"top": 1, "left": 0}, size_hint=(.1, .1)) | random_line_split |
calSettings.py | size: self.size
pos: self.pos
<HolidayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:
Color:
rgba: (128, 0, 128, 0.5)
Rectangle:
pos: self.pos
size: self.size
<HalfdayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:... | self.add_widget(self.right_arrow)
# Title
self.title_label = Label(text=self.title, pos_hint={"top": 1, "center_x": .5}, size_hint=(None, 0.15), halign=("center"))
self.add_widget(self.title_label)
# ScreenManager
self.sm = ScreenManager(pos_hint={"top": .9}, size_hint=... | """ Basic calendar widget """
def __init__(self, as_popup=False, touch_switch=False, *args, **kwargs):
super(CalendarWidgetS, self).__init__(*args, **kwargs)
self.as_popup = as_popup
self.touch_switch = touch_switch
#self.selectedDates = []
self.prepare_data()
self.... | identifier_body |
calSettings.py | size: self.size
pos: self.pos
<HolidayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:
Color:
rgba: (128, 0, 128, 0.5)
Rectangle:
pos: self.pos
size: self.size
<HalfdayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:... | (ToggleButton):
pass
class HolidayBtn(ToggleButton):
pass
class HalfdayBtn(ToggleButton):
pass
class CalendarWidgetS(RelativeLayout):
""" Basic calendar widget """
def __init__(self, as_popup=False, touch_switch=False, *args, **kwargs):
super(CalendarWidgetS, self).__init__(*args, **kwar... | ToggleBtn | identifier_name |
calSettings.py | size: self.size
pos: self.pos
<HolidayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:
Color:
rgba: (128, 0, 128, 0.5)
Rectangle:
pos: self.pos
size: self.size
<HalfdayBtn>:
font_name: 'fonts/moon-bold.otf'
canvas.before:... |
if self.as_popup:
self.parent_popup.dismiss()
#getInfo.openPopup()
def go_prev(self, inst):
""" Go to screen with previous month """
# Change active date
self.active_date = [self.active_date[0], self.quarter_nums[0][1],
self.quarte... | selectedDates.append(selected) | conditional_block |
checktime.go | of the RootCA and ServerName
// for servers that are not signed by a well known certificate
// authority. It will skip the authentication for the server. It
// is not recommended outside of a test environment.
NoValidate bool `yaml:"no_validate"`
// This option turns off encryption entirely
// it is only for tes... | {
client.locker.Unlock()
return
} | conditional_block | |
checktime.go | // TimedOut means there was no response from server
TimedOut = 2
// BadResponse means the response from server was not formatted correctly
BadResponse = 3
// InsaneResponse means the server provided a time value which is crazy
InsaneResponse = 4
// SycallFailed means the syscall failed to work to set the time
S... | recentTime = int64(1514786400000)
// SetTimeOk means the time was set Correctly
SetTimeOk = 1 | random_line_split | |
checktime.go | means there was no response from server
TimedOut = 2
// BadResponse means the response from server was not formatted correctly
BadResponse = 3
// InsaneResponse means the server provided a time value which is crazy
InsaneResponse = 4
// SycallFailed means the syscall failed to work to set the time
SycallFailed ... | (config *ClientConfig) (err error) {
client.pretend = config.Pretend
client.host = config.Host
client.port = config.Port
client.checkTimeInterval = time.Duration(config.CheckTimeInterval) * time.Second
if client.checkTimeInterval < 5 {
client.checkTimeInterval = defaultCheckTimeInterval
}
if !config.NoTLS {
... | Reconfigure | identifier_name |
checktime.go | means there was no response from server
TimedOut = 2
// BadResponse means the response from server was not formatted correctly
BadResponse = 3
// InsaneResponse means the server provided a time value which is crazy
InsaneResponse = 4
// SycallFailed means the syscall failed to work to set the time
SycallFailed ... |
func newClientError(resp *http.Response) (ret *ClientError) {
ret = new(ClientError)
ret.StatusCode = resp.StatusCode
ret.Status = resp.Status
return
}
// StatusChannel returns the status channel which can be used to know if time is set
// if nothing reads the channel, the time will be set anyway, and a simple l... | {
return fmt.Sprintf("TIME Client Error: %d - %s", err.StatusCode, err.Status)
} | identifier_body |
x0CompilerUI.py |
if mod == 1:
while window.debug == 0:
time.sleep(0.05)
window.setCodeStatus(run.c, False)
if window.debug == 1: # next step
pass
if window.debug == 2: # step into
pass
if window.debug == 3: # over step
mod = 0
window.setDebugEnabled(False)
if window.debug == 4: # step out
r... | break | conditional_block | |
x0CompilerUI.py |
'''
class x0Highlighter(QSyntaxHighlighter):
Rules = []
Formats = {}
def __init__(self, parent=None):
super(x0Highlighter, self).__init__(parent)
self.initializeFormats()
BUILDINS = ["and", "not", "int", "char", "bool", "true", "false"]
OPERATORS = ["\+", "-", "\*", "/", "%", "&", "\|", "~", "\^", "\!",... | ileInit(self):
self.filetag = False
self.filepath = os.getcwd()
self.filename = ""
self.workPathLabel.setText("")
cleanfiles()
def initUI(self):
self.fileInit()
self.errTbInit()
#self.scroll = QScrollArea()
#self.scroll.setWidgrt(self.)
self.actionNew.triggered.connect(self.newFile)
self.action... | his function is used to initialize the errMsgTable
'''
self.errorMsgTable.clear()
self.errorMsgTable.setColumnCount(3)
self.errorMsgTable.setRowCount(1)
self.errorMsgTable.setHorizontalHeaderLabels(['errno', 'line', 'message'])
self.errorMsgTable.verticalHeader().setVisible(False)
self.errorMsgTable.setEd... | identifier_body |
x0CompilerUI.py | if isfile(".\\~.tmp"):
os.remove(".\\~.tmp")
if isfile(os.getcwd()+"\\ferr.json"):
os.remove(os.getcwd()+"\\ferr.json")
if isfile(os.getcwd()+"\\fcode.json"):
os.remove(os.getcwd()+"\\fcode.json")
'''
This function is the real processing for backstage-interpretation
and it should work in a new thread so tha... | def cleanfiles():
from os.path import isfile | random_line_split | |
x0CompilerUI.py | texts
'''
class x0Highlighter(QSyntaxHighlighter):
Rules = []
Formats = {}
def __init__(self, parent=None):
super(x0Highlighter, self).__init__(parent)
self.initializeFormats()
BUILDINS = ["and", "not", "int", "char", "bool", "true", "false"]
OPERATORS = ["\+", "-", "\*", "/", "%", "&", "\|", "~", "\^",... | build&run or debug a processing
'''
# clear output label and table contents
self.label.setText("")
self.outputLabel.setText("")
self.tableWidget.clear()
self.tableWidget.setRowCount(0);
#添加表头:
list = ['idx','name','value','level','addr','size']
for i in range(6):
item = QTableWidgetItem(li... | ration for | identifier_name |
form_input.rs | styles::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg; | /// type Properties = ();
/// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
/// FormInputExample {
/// link,
/// value: "".to_string(),
/// }
/// }
/// fn update(&mut self, msg: Self::Message) -> ShouldRender {
/// match msg {
/// ... | random_line_split | |
form_input.rs | ::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg;
/// type Properties = ();
/// fn create(_: Self::Properti... | (&mut self, props: Self::Properties) -> ShouldRender {
if self.props != props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
html! {
<>
<input
id=self.props.id.clone()
... | change | identifier_name |
form_input.rs | ::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg;
/// type Properties = ();
/// fn create(_: Self::Properti... | InputType::Time => "time".to_string(),
InputType::Url => "url".to_string(),
InputType::Week => "week".to_string(),
}
}
#[wasm_bindgen_test]
fn should_create_form_input() {
let props = Props {
key: "".to_string(),
code_ref: NodeRef::default(),
id: "form-input-id-... | {
match input_type {
InputType::Button => "button".to_string(),
InputType::Checkbox => "checkbox".to_string(),
InputType::Color => "color".to_string(),
InputType::Date => "date".to_string(),
InputType::Datetime => "datetime".to_string(),
InputType::DatetimeLocal => "d... | identifier_body |
main.rs | total_bytes_transferred: usize,
/// The number of times the Bytes Per Second has been measured.
total_measures: usize,
/// Accumulation of all of the Bytes Per Second measures.
total_bps: f64,
/// The Bytes Per Second during the last measure.
last_bps: f64,
/// The number of bytes trans... | {
write!(output, "\x1b[{}A", lines)?;
Ok(())
} | identifier_body | |
main.rs | io::Write;
if let Err(e) = writeln!($err_write, $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
macro_rules! print_err {
($fmt:expr) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt) {
panic!("Error wh... | } else {
measure_stdin(buffer_size, iterations, passthrough);
}
}
fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) {
let parsed_addr: IpAddr = match address.parse() {
Ok(parsed) => parsed,
Err(_) => {
print_err!("B... | } | random_line_split |
main.rs | usize,
/// The number of times the Bytes Per Second has been measured.
total_measures: usize,
/// Accumulation of all of the Bytes Per Second measures.
total_bps: f64,
/// The Bytes Per Second during the last measure.
last_bps: f64,
/// The number of bytes transferred during the last me... | byte_to_mem_units | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.