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 |
|---|---|---|---|---|
stat.go | package stat
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/smartwalle/container/smap"
"math"
kdb "github.com/sv/kdbgo"
)
type Response struct {
Sym string
Qid string
Accountname string
Time time.Time
Entrustno int32
Stockcode string
Askprice float64
Askvol int... | // return float64(-f)
// }
// return float64(f)
//}
func AbsInt(f int32) int32 {
if f < 0 {
return int32(-f)
}
return int32(f)
}
func Float64Fmt(f float64, prec int) float64 {
a := strconv.FormatFloat(f, 'f', prec, 64)
ff, err := strconv.ParseFloat(a, 64)
if err != nil {
fmt.Println(err)
}
return ff
}
fu... | random_line_split | |
stat.go | package stat
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/smartwalle/container/smap"
"math"
kdb "github.com/sv/kdbgo"
)
type Response struct {
Sym string
Qid string
Accountname string
Time time.Time
Entrustno int32
Stockcode string
Askprice float64
Askvol int... | alues() {
for _, stock_map := range (account_map.(smap.Map)).Values() {
stat := stock_map.(*STK)
totalOnlineProfit = totalOnlineProfit + stat.SpaceStk.OnlineProfit
totalProfit = totalProfit + stat.ProfitStk.PastProfit
fmt.Println(stat.SpaceStk.Sym, " ", stat.SpaceStk.Accountname, " ", stat.S... | ice //临时对象记录下之前的均价
//卖的大于原有仓位
var flag bool = false
if AbsInt(newOrder.Bidvol) >= AbsInt(stat.SpaceStk.SpaceVol) {
flag = true
}
stat.SpaceStk.SpaceVol = stat.SpaceStk.SpaceVol + newOrder.Bidvol
fmt.Println("算仓位", stat.SpaceStk.SpaceVol)
if newOrder.Bidvol > 0 {
//算均价
if spaceTemp < 0 {
if ... | identifier_body |
stat.go | package stat
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/smartwalle/container/smap"
"math"
kdb "github.com/sv/kdbgo"
)
type Response struct {
Sym string
Qid string
Accountname string
Time time.Time
Entrustno int32
Stockcode string
Askprice float64
Askvol int... | onnect kdb: %s", err.Error())
return
}
err = con.AsyncCall(".u.sub", &kdb.K{-kdb.KS, kdb.NONE, "Market"}, &kdb.K{-kdb.KS, kdb.NONE, ""})
if err != nil {
fmt.Println("Subscribe: %s", err.Error())
return
}
res, _, err := con.ReadMessage()
if err != nil {
fmt.Println("Error processing message: ... | iled to c | identifier_name |
expdescription.py | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... | "Remove the measurement group '%s'?" % activeMntGrpName,
Qt.QMessageBox.Yes | Qt.QMessageBox.Cancel)
if op != Qt.QMessageBox.Yes:
return
currentIndex = self.ui.activeMntGrpCB.currentIndex()
if self._localConfig is None:
return
if ac... | def deleteMntGrp(self):
'''creates a new Measurement Group'''
activeMntGrpName = str(self.ui.activeMntGrpCB.currentText())
op = Qt.QMessageBox.question(self, "Delete Measurement Group", | random_line_split |
expdescription.py | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... | (Qt.QWidget, TaurusBaseWidget):
'''
A widget for editing the configuration of a experiment (measurement groups,
plot and storage parameters, etc).
It receives a Sardana Door name as its model and gets/sets the configuration
using the `ExperimentConfiguration` environmental variable for that Doo... | ExpDescriptionEditor | identifier_name |
expdescription.py | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... |
def deleteMntGrp(self):
'''creates a new Measurement Group'''
activeMntGrpName = str(self.ui.activeMntGrpCB.currentText())
op = Qt.QMessageBox.question(self, "Delete Measurement Group",
"Remove the measurement group '%s'?" % activeMntGrpName,
Qt.QMessageBox.... | '''creates a new Measurement Group'''
if self._localConfig is None:
return
mntGrpName, ok = Qt.QInputDialog.getText(self, "New Measurement Group",
"Enter a name for the new measurement Group")
if not ok: return
mntGrpName = s... | identifier_body |
expdescription.py | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... |
door = self.getModelObj()
if door is None: return
conf = door.getExperimentConfiguration()
self._originalConfiguration = copy.deepcopy(conf)
self.setLocalConfig(conf)
self._setDirty(False)
self._dirtyMntGrps = set()
#set a list of available channels
... | op = Qt.QMessageBox.question(self, "Reload info from door",
"If you reload, all current experiment configuration changes will be lost. Reload?",
Qt.QMessageBox.Yes | Qt.QMessageBox.Cancel)
if op != Qt.QMessageBox.Yes:
return | conditional_block |
a1.py | """CSCA08 Assignment 1, Fall 2017
I hereby agree that the work contained herein is solely my work and that I
have not received any external help from my peers, nor have I used any
resources not directly supplied by the course in order to complete this
assignment. I have not looked at anyone else's solution, and... |
# check if the indices are found in source gene
if (source_start_anchor != -1 and source_end_anchor != -1):
# check if the indices are found in destination gene
if (destination_start_anchor != -1 and destination_end_anchor != -1):
# for loop to find the anchor sequence from t... | destination_start_anchor = destination_gene.rfind(start_anchor)
destination_end_anchor = destination_gene.rfind(
end_anchor, destination_start_anchor) | conditional_block |
a1.py | """CSCA08 Assignment 1, Fall 2017
I hereby agree that the work contained herein is solely my work and that I
have not received any external help from my peers, nor have I used any
resources not directly supplied by the course in order to complete this
assignment. I have not looked at anyone else's solution, and... | (file_handle, gene, mask):
''' (io.TextIOWrapper, str, str) -> tuple
Takes in a file handle for a file containing one gene per line,
a string representing a gene and a string representing a mask.
Then, it returns a tuple (p, m, z) where p is the first gene that can
pair with the input gene stri... | process_gene_file | identifier_name |
a1.py | """CSCA08 Assignment 1, Fall 2017
I hereby agree that the work contained herein is solely my work and that I
have not received any external help from my peers, nor have I used any
resources not directly supplied by the course in order to complete this
assignment. I have not looked at anyone else's solution, and... |
def match_mask(gene, mask):
''' (str, str) -> int
This function creates a mask to find a specific pattern in the gene.
Masks can pair with parts of genes, but does not necessarily pair
with the entire gene. Masks can be consisted of multis which are
the special nucleotides, represented in... | ''' (list, list, str, str) -> None
This function performs splicing of gene sequences.
Splicing of genes can be done by taking a nucleotide sequence
from one gene and replace it with a nucleotide sequence from another.
First, find the anchor sequences, which are the sequences found
within the st... | identifier_body |
a1.py | """CSCA08 Assignment 1, Fall 2017
I hereby agree that the work contained herein is solely my work and that I
have not received any external help from my peers, nor have I used any
resources not directly supplied by the course in order to complete this
assignment. I have not looked at anyone else's solution, and... | >>> zip_length("AGTCTCGCT")
2
>>> zip_length("AGTCTCGAG")
0
'''
# declare a variable that counts the zip length
zip_length_count = 0
# for loop that is in charge of each nucleotides from the left
for left_index in range(len(gene)):
# declare a variable that is in... | This function returns an integer value that indicates the maximum
number of nucleotides pairs that the gene can zip.
REQ: genes must be consisted of letters {A, G, C, T}
| random_line_split |
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... | }
for dependency in self.graph.get(name).unwrap().dependencies() {
if !self.graph.contains(dependency) {
try!(self.resolve_task(dependency));
}
}
Ok(())
}
fn runtime(&self) -> Runtime {
self.runtime.as_ref().unwrap().clone()
}
... | return Err(format!("no matching task or rule for '{}'", name.as_ref()).into());
}
| conditional_block |
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... | (&mut self) {
self.spec.always_run = true;
}
/// Run all tasks even if they throw errors.
pub fn keep_going(&mut self) {
self.spec.keep_going = true;
}
/// Sets the number of threads to use to run tasks.
pub fn jobs(&mut self, jobs: usize) {
self.jobs = jobs;
}
... | always_run | identifier_name |
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... |
/// Run all tasks even if they throw errors.
pub fn keep_going(&mut self) {
self.spec.keep_going = true;
}
/// Sets the number of threads to use to run tasks.
pub fn jobs(&mut self, jobs: usize) {
self.jobs = jobs;
}
/// Adds a path to Lua's require path for modules.
... | {
self.spec.always_run = true;
} | identifier_body |
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... | // Scheduling was successful, so remove the task frome the queue.
queue.pop_front().unwrap();
} else {
trace!("failed to send channel to thread {}", thread_id);
}
} else {
... | current_tasks.insert(thread_id, task.name().to_string());
free_threads.remove(&thread_id);
| random_line_split |
assembly_finishing_objects.py | # -*- coding: utf-8 -*-
"""
@author : c_georgescu
"""
class Sequence:
def __init__(self, index, mums, step, big_enough):
self.contigs = []
self.discarded_contigs = []
tmp = Sequence.sort_mums(index, mums)
i = 0
while i < len(tmp):
self.contigs.append(Contig(i+1, tmp[i], step, big_enough))
i += 1
s... | while(i < len(mums)):
if (mums[i][5] != orientation):
self.mum_sequences.append(Mum_sequence(orientation, mums[j:i]))
orientation = mums[i][5]
j = i
elif (abs(mums[i-1][1] - mums[i][1]) > 2000000): # arbitrary value that is much bigger than any small jump that could happen, but smaller than the size... | j = 0
if (len(mums) == 1):
self.mum_sequences.append(Mum_sequence(orientation, mums))
return | random_line_split |
assembly_finishing_objects.py | # -*- coding: utf-8 -*-
"""
@author : c_georgescu
"""
class Sequence:
def __init__(self, index, mums, step, big_enough):
self.contigs = []
self.discarded_contigs = []
tmp = Sequence.sort_mums(index, mums)
i = 0
while i < len(tmp):
self.contigs.append(Contig(i+1, tmp[i], step, big_enough))
i += 1
s... | self):
down = float("inf")
up = 0
i = -1
j = -1
k = 0
## need to find highest and lowest seq of mums
while (k < len(self.mum_sequences)):
if self.mum_sequences[k].height > up:
up = self.mum_sequences[k].height
j = k
if self.mum_sequences[k].height < down:
down = self.mum_sequences[k].hei... | ind_rolling_gap( | identifier_name |
assembly_finishing_objects.py | # -*- coding: utf-8 -*-
"""
@author : c_georgescu
"""
class Sequence:
def __init__(self, index, mums, step, big_enough):
self.contigs = []
self.discarded_contigs = []
tmp = Sequence.sort_mums(index, mums)
i = 0
while i < len(tmp):
self.contigs.append(Contig(i+1, tmp[i], step, big_enough))
i += 1
s... |
def search_true_first_sequence(self, start, step):
j = 0
while (j < len(self.mum_sequences) and (self.mum_sequences[j].start < start - step)):
j += 1
return j
def get_position_before_gap(self, step):
i = 1
position = self.mum_sequences[0].end
while (i < len(self.mum_sequences)):
if (self.mum_seque... | = j + 1
start_height = self.mum_sequences[j].height
current_height = start_height
restarted = False
while (i < len(self.mum_sequences)):
if (self.mum_sequences[i].height > current_height):
# current_height = self.mum_sequences[i].height ## ADDED THIS
i += 1
continue
elif (self.mum_sequences[i... | identifier_body |
assembly_finishing_objects.py | # -*- coding: utf-8 -*-
"""
@author : c_georgescu
"""
class Sequence:
def __init__(self, index, mums, step, big_enough):
self.contigs = []
self.discarded_contigs = []
tmp = Sequence.sort_mums(index, mums)
i = 0
while i < len(tmp):
self.contigs.append(Contig(i+1, tmp[i], step, big_enough))
i += 1
s... |
if (res == 1): # rolling case
print "\n\nHERE\n\n"
# search for vertical gap between a and b
# while (compare_heights(a, b)): ## TODO need a function to check when it goes from top to bottom gap, if direct/direct, fisrt higher, if reverse/reverse, first lower
res = c.find_rolling_gap()
# c... | c.futur = 1 | conditional_block |
Ch11. Ex.py | """1. Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look like this:
Please enter a sentence: Th... | """Sorts a dictionary of contacts"""
key_list = list(contacts.keys()) #get keys
key_list.sort() #sort key_list
sorted_list = [] #initialize sorted list
for key in key_list:
contact = (key, contacts[key][0], contacts[key][1]) #create tuple
sorted_list += [contact] #add tuple to... | contacts):
| identifier_name |
Ch11. Ex.py | """1. Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look like this:
Please enter a sentence: Th... |
print("\nAverage grade:", (total_score / len(students)))
#3. Implement the functionality of the above program using a dictionary instead of a list.
import sys
sys.setExecutionLimit(70000)
students = {}
total_score = 0.0
name = input("Enter the name of a student. (When finished, enter nothing)")
while (name != "... | tal_score += grades[index]
print("{0} ({1:.1})".format(student, grades[index]))
| conditional_block |
Ch11. Ex.py | """1. Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look like this:
Please enter a sentence: Th... |
if __name__ == "__main__":
main()
"""2. Write a program that will function as a grade book, allowing a user (a professor or teacher) to enter the class roster for a course, along with each student’s cumulative grade. It then prints the class roster along with the average cumulative grade. Grades are on a 0-1... | text = input("Please enter a sentence: ")
chars = create_dict(text)
print_dict(chars) | identifier_body |
Ch11. Ex.py | """1. Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look like this:
Please enter a sentence: Th... | students = []
grades = []
total_score = 0.0
name = input("Enter the name of a student. (When finished, enter nothing)")
while (name != ""):
students += [name]
name = input("Enter the name of a student. (When finished, enter nothing)")
for i in range(len(students)):
score = float(input("Grade for {0}:".f... | random_line_split | |
train_folds.py | import os, time
mydir = os.path.split(os.path.abspath(__file__))[0]
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
#print('Meu diretorio: {}'.format(mydir))
#print('Minha Home: {}'.format(homepath))
list_lib = [r'{}\anaconda3\envs\arc105'.format(homepath), \
r'{}\anaconda3\envs\arc105\Library\mingw-w64\... | num_workers=4,
drop_last=True)
dataset_val = dataloader.RS_Loader_Semantic(dataset_dir, num_classes, mode='val', indices=indices['val'], isRGB=isRGB)
dataloaders_d... | batch_size=batch_size, | random_line_split |
train_folds.py | import os, time
mydir = os.path.split(os.path.abspath(__file__))[0]
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
#print('Meu diretorio: {}'.format(mydir))
#print('Minha Home: {}'.format(homepath))
list_lib = [r'{}\anaconda3\envs\arc105'.format(homepath), \
r'{}\anaconda3\envs\arc105\Library\mingw-w64\... |
def main():
parser = argparse.ArgumentParser(description='Semantic Segmentation General')
parser.add_argument('--dataset_path', type=str, required=True,
help='Path to dataset')
parser.add_argument('--inRasterReference', type=str, required=True,
help='Path t... | list_folds = np.array(range(5))
# Roll in axis
tmp_set = np.roll(list_folds,id_fold)
indices_train = []
indices_val = []
indices_test = []
# Train
for i in tmp_set[:3]:
indices_train += list(data[data[:,1].astype(int) == i][:,0])
# Val
for i in tmp_set[3:4]:
... | identifier_body |
train_folds.py | import os, time
mydir = os.path.split(os.path.abspath(__file__))[0]
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
#print('Meu diretorio: {}'.format(mydir))
#print('Minha Home: {}'.format(homepath))
list_lib = [r'{}\anaconda3\envs\arc105'.format(homepath), \
r'{}\anaconda3\envs\arc105\Library\mingw-w64\... |
# Test
for i in tmp_set[4:]:
indices_test += list(data[data[:,1].astype(int) == i][:,0])
#print(indices_train)
#print(indices_val)
#print(indices_test)
indices = {}
indices['train'] = indices_train
indices['val'] = indices_val
indices['test'] = indice... | indices_val += list(data[data[:,1].astype(int) == i][:,0]) | conditional_block |
train_folds.py | import os, time
mydir = os.path.split(os.path.abspath(__file__))[0]
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
#print('Meu diretorio: {}'.format(mydir))
#print('Minha Home: {}'.format(homepath))
list_lib = [r'{}\anaconda3\envs\arc105'.format(homepath), \
r'{}\anaconda3\envs\arc105\Library\mingw-w64\... | (id_fold, data):
# Instantiate Folds
list_folds = np.array(range(5))
# Roll in axis
tmp_set = np.roll(list_folds,id_fold)
indices_train = []
indices_val = []
indices_test = []
# Train
for i in tmp_set[:3]:
indices_train += list(data[data[:,1].astype(int) == i][:,0])
... | get_indices | identifier_name |
backtrace.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
Offset: u64,
Segment: u16,
Mode: ADDRESS_MODE,
}
pub struct STACKFRAME64 {
AddrPC: ADDRESS64,
AddrReturn: ADDRESS64,
AddrFrame: ADDRESS64,
AddrStack: ADDRESS64,
AddrBStore: ADDRESS64,
FuncTableEntry: *mut libc::c_void,
Params: [u64; 4],
Far: libc::BOOL,
Virtual: libc:... | ADDRESS64 | identifier_name |
backtrace.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | type SymInitializeFn =
extern "system" fn(libc::HANDLE, *mut libc::c_void,
libc::BOOL) -> libc::BOOL;
type SymCleanupFn =
extern "system" fn(libc::HANDLE) -> libc::BOOL;
type StackWalk64Fn =
extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE,
*mut STACK... | *mut SYMBOL_INFO) -> libc::BOOL; | random_line_split |
backtrace.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
i += 1;
try!(write!(w, " {:2}: {:#2$x}", i, addr, HEX_WIDTH));
let mut info: SYMBOL_INFO = unsafe { intrinsics::init() };
info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong;
// the struct size in C. the value is different to
// `size_of::<SYMBOL_INFO>() - MAX_SYM_NAME + ... | { break } | conditional_block |
platform_types.rs | #![deny(unused)]
use macros::{
d, fmt_debug, fmt_display, ord, u,
};
use std::{
time::{Duration, Instant},
path::PathBuf
};
pub use vec1::{vec1, Vec1};
pub use panic_safe_rope::{BorrowRope, Rope, RopeSlice, RopeSliceTrait, ByteIndex};
pub use text_pos::*;
pub mod floating_point;
pub mod screen_positionin... | },
GoToPosition => match &self.menu {
MenuView::GoToPosition(ref gtp) => Some(>p.go_to_position),
_ => Option::None,
},
}.map(|d| &d.cursors[..])
}
#[must_use]
/// returns the currently visible editor buffer path if it has one.
... | MenuView::FileSwitcher(ref fs) => Some(&fs.search),
_ => Option::None, | random_line_split |
platform_types.rs | #![deny(unused)]
use macros::{
d, fmt_debug, fmt_display, ord, u,
};
use std::{
time::{Duration, Instant},
path::PathBuf
};
pub use vec1::{vec1, Vec1};
pub use panic_safe_rope::{BorrowRope, Rope, RopeSlice, RopeSliceTrait, ByteIndex};
pub use text_pos::*;
pub mod floating_point;
pub mod screen_positionin... | (&self) -> MenuMode {
match self {
Self::None => MenuMode::Hidden,
Self::FileSwitcher(_) => MenuMode::FileSwitcher,
Self::FindReplace(v) => MenuMode::FindReplace(v.mode),
Self::GoToPosition(_) => MenuMode::GoToPosition,
}
}
}
#[must_use]
pub fn kind_e... | get_mode | identifier_name |
platform_types.rs | #![deny(unused)]
use macros::{
d, fmt_debug, fmt_display, ord, u,
};
use std::{
time::{Duration, Instant},
path::PathBuf
};
pub use vec1::{vec1, Vec1};
pub use panic_safe_rope::{BorrowRope, Rope, RopeSlice, RopeSliceTrait, ByteIndex};
pub use text_pos::*;
pub mod floating_point;
pub mod screen_positionin... |
#[must_use]
/// returns the currently visible editor buffer path if it has one.
pub fn current_path(&self) -> Option<PathBuf> {
u!{BufferName}
match self.buffers.get_current_element().name {
Path(ref p) => Some(p.clone()),
Scratch(_) => None,
}
}
}
#[de... | {
use BufferIdKind::*;
match self.current_buffer_kind {
// Seems like we never actually need to access the Text buffer
// cursors here. If we want to later, then some additional restructuring
// will be needed, at least according to the comment this comment
... | identifier_body |
pvc-clone-controller.go | /*
Copyright 2022 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
// detectCloneSize obtains and assigns the original PVC's size when cloning using an empty storage value
func (r *PvcCloneReconciler) detectCloneSize(syncState *dvSyncState) (bool, error) {
sourcePvc, err := r.findSourcePvc(syncState.dvMutated)
if err != nil {
return false, err
}
// because of filesystem overh... | {
// TODO preper const
eventReason := "CloneSourceInUse"
// Check if any pods are using the source PVC
inUse, err := r.sourceInUse(datavolume, eventReason)
if err != nil {
return false, err
}
// Check if the source PVC is fully populated
populated, err := r.isSourcePVCPopulated(datavolume)
if err != nil {
... | identifier_body |
pvc-clone-controller.go | /*
Copyright 2022 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | (dv *cdiv1.DataVolume, pvc *corev1.PersistentVolumeClaim) error {
// first clear out tokens that may have already been added
delete(pvc.Annotations, cc.AnnCloneToken)
delete(pvc.Annotations, cc.AnnExtendedCloneToken)
if isCrossNamespaceClone(dv) {
// only want this initially
// extended token is added later
t... | addCloneToken | identifier_name |
pvc-clone-controller.go | /*
Copyright 2022 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | getKey := func(namespace, name string) string {
return namespace + "/" + name
}
if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &cdiv1.DataVolume{}, dvDataSourceField, func(obj client.Object) []string {
if sourceRef := obj.(*cdiv1.DataVolume).Spec.SourceRef; sourceRef != nil && sourceRef.Kind == cdiv... | random_line_split | |
pvc-clone-controller.go | /*
Copyright 2022 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
pvc = newPvc
}
if syncRes.usePopulator {
if err := r.reconcileVolumeCloneSourceCR(&syncRes); err != nil {
return syncRes, err
}
ct, ok := pvc.Annotations[cc.AnnCloneType]
if ok {
cc.AddAnnotation(datavolume, cc.AnnCloneType, ct)
}
} else {
cc.AddAnnotation(datavolume, cc.AnnCloneType, string(c... | {
if cc.ErrQuotaExceeded(err) {
syncErr = r.syncDataVolumeStatusPhaseWithEvent(&syncRes, cdiv1.Pending, nil,
Event{
eventType: corev1.EventTypeWarning,
reason: cc.ErrExceededQuota,
message: err.Error(),
})
if syncErr != nil {
log.Error(syncErr, "failed to sync DataVolume... | conditional_block |
migration.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {HelperFunction} from './helpers';
import {findImportSpecifier} from './uti... | (node: ts.CallExpression): ts.Node {
const [target, name, args] = node.arguments;
const isNameStatic = ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name);
const isArgsStatic = !args || ts.isArrayLiteralExpression(args);
if (isNameStatic && isArgsStatic) {
// If the name is a static string... | migrateInvokeElementMethod | identifier_name |
migration.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {HelperFunction} from './helpers';
import {findImportSpecifier} from './uti... |
return node;
}
/**
* Migrates a call to `invokeElementMethod(target, method, [arg1, arg2])` either to
* `target.method(arg1, arg2)` or `(target as any)[method].apply(target, [arg1, arg2])`.
*/
function migrateInvokeElementMethod(node: ts.CallExpression): ts.Node {
const [target, name, args] = node.arguments;
... | {
// We need the checks for string literals, because the type of something
// like `"blue"` is the literal `blue`, not `string`.
if (lastArgType === 'string' || lastArgType === 'number' || ts.isStringLiteral(args[2]) ||
ts.isNoSubstitutionTemplateLiteral(args[2]) || ts.isNumericLiteral(args[2])) {
... | conditional_block |
migration.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {HelperFunction} from './helpers';
import {findImportSpecifier} from './uti... |
/**
* Migrates a call to `setElementStyle` call either to a call to
* `setStyle` or `removeStyle`. or to an expression like
* `value == null ? removeStyle(el, key) : setStyle(el, key, value)`.
*/
function migrateSetElementStyle(
node: PropertyAccessCallExpression, typeChecker: ts.TypeChecker): ts.Node {
con... | {
// Clone so we don't mutate by accident. Note that we assume that
// the user's code is providing all three required arguments.
const outputMethodArgs = node.arguments.slice();
const isAddArgument = outputMethodArgs.pop()!;
const createRendererCall = (isAdd: boolean) => {
const innerExpression = node.ex... | identifier_body |
migration.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {HelperFunction} from './helpers';
import {findImportSpecifier} from './uti... | /**
* Migrates a call to `setElementClass` either to a call to `addClass` or `removeClass`, or
* to an expression like `isAdd ? addClass(el, className) : removeClass(el, className)`.
*/
function migrateSetElementClass(node: PropertyAccessCallExpression): ts.Node {
// Clone so we don't mutate by accident. Note that... | return node;
}
| random_line_split |
page.js | /**
Rendering Pages
================
SIMPLE TEXT
--------------
To put simple text or HTML to a screen:
res.render( { body_text: 'Hello <b>world</b>' } );
TEMPLATE
---------
To put a specific template (like a form) with variables:
res.render( 'inbox/form.html', { username: name, phone:... | ( req, res ) {
var cmds = {};
function cmd( group, url, link, help )
{
this.url = url;
this.link = link;
this.help = help;
if(!cmds[group]) { cmds[group] = {}; cmds[group].items = [ ] };
cmds[group].items.push(this);
}
var user = loginstate.getU... | buildMenu | identifier_name |
page.js | /**
Rendering Pages
================
SIMPLE TEXT
--------------
To put simple text or HTML to a screen:
res.render( { body_text: 'Hello <b>world</b>' } );
TEMPLATE
---------
To put a specific template (like a form) with variables:
res.render( 'inbox/form.html', { username: name, phone:... | ;
cmds[group].items.push(this);
}
var user = loginstate.getUser(req);
new cmd('safeharbor', '/about', 'About', 'Learn about Safe Harbor');
new cmd('safeharbor', '/learn', 'Learn', 'Learn about your rights and the DMCA');
new cmd('safeharbor', '/support', 'Support', 'Ask us stuf... | { cmds[group] = {}; cmds[group].items = [ ] } | conditional_block |
page.js | /**
Rendering Pages
================
SIMPLE TEXT
--------------
To put simple text or HTML to a screen:
res.render( { body_text: 'Hello <b>world</b>' } );
TEMPLATE
---------
To put a specific template (like a form) with variables:
res.render( 'inbox/form.html', { username: name, phone:... | return(" "+field+'="'+element[field]+'" ');
}
str += helper("data-alternative-spellings");
str += helper("data-relevancy-booster");
str += ">"+element.name+"</option>\n";
html += str;
})
return(html);
} | random_line_split | |
page.js | /**
Rendering Pages
================
SIMPLE TEXT
--------------
To put simple text or HTML to a screen:
res.render( { body_text: 'Hello <b>world</b>' } );
TEMPLATE
---------
To put a specific template (like a form) with variables:
res.render( 'inbox/form.html', { username: name, phone:... |
var user = loginstate.getUser(req);
new cmd('safeharbor', '/about', 'About', 'Learn about Safe Harbor');
new cmd('safeharbor', '/learn', 'Learn', 'Learn about your rights and the DMCA');
new cmd('safeharbor', '/support', 'Support', 'Ask us stuff');
if( user )
{
new c... | {
this.url = url;
this.link = link;
this.help = help;
if(!cmds[group]) { cmds[group] = {}; cmds[group].items = [ ] };
cmds[group].items.push(this);
} | identifier_body |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | (&mut self, id: String, variants: Vec<Ident>) -> Ret {
let rc = Rc::new(DataType {id: id.clone(), variants: variants.clone()});
for (i, variant) in variants.iter().enumerate() {
self.add_var(variant.clone(), RunVal::Data(rc.clone(), i), Type::Data(rc.clone()))?;
}
self.add_type(id, Type::Data(rc))
}
pub ... | add_datatype | identifier_name |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | }
eval_exp(exp, ctx)
},
_ => eval_exp(exp, ctx),
}
}
pub fn eval_exp_seq(seq: &Vec<Exp>, ctx: &Context) -> Vec<RunVal> {
seq.iter().flat_map(|e| {
if let Exp::Expand(ref e) = e {
let val = eval_exp(e, ctx);
let err = Error(format!("Cannot expand value: {}", val));
iter... | for decl in decls {
eval_decl(decl, ctx).unwrap(); | random_line_split |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | ,
RunVal::Tuple(vals) => Some(vals),
_ => None,
}
}
pub fn create_extract_gate_typed(cases: &Vec<Case>, min_input_size: usize, ctx: &Context) -> (Gate, Type) {
fn reduce_type(output_type: Option<Type>, t: Type) -> Option<Type> {
Some(match output_type {
None => t,
Some(ot) => if ot == t {t} else {Type::A... | {
Some((0..i).map(RunVal::Index).collect())
} | conditional_block |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... |
}
#[derive(Clone,Debug,PartialEq)]
pub struct Context {
path: String,
vars: HashMap<Ident, RunVal>,
types: TypeContext,
}
impl Context {
pub fn new(path: String) -> Context {
Context {
path,
vars: HashMap::new(),
types: TypeContext::new(),
}
}
pub fn path(&self) -> &String {
&self.path
}
p... | {
match self {
&RunVal::Index(ref n) => write!(f, "{}", n),
&RunVal::String(ref s) => write!(f, "{:?}", s),
&RunVal::Data(ref dt, ref index) => write!(f, "{}", dt.variants[*index]),
&RunVal::Tuple(ref vals) => write!(f, "({})", vals.iter().map(|val| format!("{}", val)).collect::<Vec<_>>().join(", ")),
... | identifier_body |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... | return min_v;
}
#[inline]
const fn shuffle(z: i32, y: i32, x: i32, w: i32) -> i32 {
(z << 6) | (y << 4) | (x << 2) | w
} | let max_v = _mm256_max_epi16(reg, min_s); //max(a,0)
let min_v = _mm256_min_epi16(max_v, max_s); //min(max(a,0),255) | random_line_split |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... |
#[inline]
#[target_feature(enable = "avx2")]
#[rustfmt::skip]
unsafe fn ycbcr_to_rgba_unsafe(
y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16],
out: &mut [u8],
offset: &mut usize,
)
{
// check if we have enough space to write.
let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice ... | {
unsafe {
ycbcr_to_rgba_unsafe(y, cb, cr, out, offset);
}
} | identifier_body |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... | (
y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16],
out: &mut [u8],
offset: &mut usize,
)
{
// check if we have enough space to write.
let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice to small cannot write").try_into().unwrap();
let (r, g, b) = ycbcr_to_rgb_baseline_no_cla... | ycbcr_to_rgba_unsafe | identifier_name |
run.js | 'use strict';
const fs = require('fs-extra')
const express = require('express')
const bodyParser = require('body-parser')
const url = require('url')
const dateFormat = require('dateformat')
const spawn = require('child_process').spawn
const request = require('request')
const app = express()
const config = require('./c... | (scam) {
let abusereport = stripIndents`I would like to inform you of suspicious activities at the domain ${url.parse(scam.url).hostname}
${'ip' in scam ? `located at IP address ${scam['ip']}`: ''}.
${'subcategory' in scam && scam.subcategory == "NanoWallet" ?
`The domain is impersonating NanoWallet.io, ... | generateAbuseReport | identifier_name |
run.js | 'use strict';
const fs = require('fs-extra')
const express = require('express')
const bodyParser = require('body-parser')
const url = require('url')
const dateFormat = require('dateformat')
const spawn = require('child_process').spawn
const request = require('request')
const app = express()
const config = require('./c... | var intActiveScams = 0
var intInactiveScams = 0
scams.forEach(function (scam) {
if ('addresses' in scam) {
scam.addresses.forEach(function (address) {
addresses[address] = true
})
}
if ('status' in scam) {
if (scam.status === 'Active') {
++intA... | let addresses = {}
| random_line_split |
run.js | 'use strict';
const fs = require('fs-extra')
const express = require('express')
const bodyParser = require('body-parser')
const url = require('url')
const dateFormat = require('dateformat')
const spawn = require('child_process').spawn
const request = require('request')
const app = express()
const config = require('./c... | else {
return -1
}
})
break
case 'subcategory':
sorting.subcategory = 'sorted'
direction.subcategory = currentDirection
scams.sort(function (a, b) {
if ('subcategory' in a && 'subcategory' in b && a.subcategory && b.subcategory) {
... | {
return a.category.localeCompare(b.category)
} | conditional_block |
run.js | 'use strict';
const fs = require('fs-extra')
const express = require('express')
const bodyParser = require('body-parser')
const url = require('url')
const dateFormat = require('dateformat')
const spawn = require('child_process').spawn
const request = require('request')
const app = express()
const config = require('./c... |
/* Start the web server */
function startWebServer() {
app.use(express.static('_static')); // Serve all static pages first
app.use('/screenshot', express.static('_cache/screenshots/')); // Serve all screenshots
app.use(bodyParser.json({ strict: true })) // to support JSON-encoded bodies
app.get('/(/|index.... | {
let abusereport = stripIndents`I would like to inform you of suspicious activities at the domain ${url.parse(scam.url).hostname}
${'ip' in scam ? `located at IP address ${scam['ip']}`: ''}.
${'subcategory' in scam && scam.subcategory == "NanoWallet" ?
`The domain is impersonating NanoWallet.io, a websi... | identifier_body |
Index.js | import React, { Component, Fragment } from 'react';
import { Route } from "react-router-dom";
import {
Card,
Table,
Modal,
Button,
Drawer,
message,
Breadcrumb,
} from 'antd';
import utils from '@/utils';
import moment from 'moment';
import Enum, { AUTH } from '@/enum';
import classnames from 'classnames';
import... | = {
time_exp: `${moment().startOf('day').add(-1, 'month').unix()},${moment().endOf('day').unix()}`,
...state.filterInfo,
...state.searchData
};
this.setState({ downloadStatus: 2 });
NetOperation.exportRecharge(data).then((res) => {
const items = res.data;
if (items && items.id) {
this.download... | const data | identifier_name |
Index.js | import React, { Component, Fragment } from 'react';
import { Route } from "react-router-dom";
import {
Card,
Table,
Modal,
Button,
Drawer,
message,
Breadcrumb,
} from 'antd';
import utils from '@/utils';
import moment from 'moment';
import Enum, { AUTH } from '@/enum';
import classnames from 'classnames';
import... | encyTree() {
DataAgencys.getTreeData(this.props.match.params.id, (data) => {
this.setState({ agencyTree: data });
}, true);
}
getRechargeDetails() {
const { filterInfo, searchData } = this.state;
const data = {
time_exp: `${moment().startOf('day').add(-1, 'month').unix()},${moment().endOf('day').unix()... | .getRechargeDetails();
this.getAgencyTree();
}
getAg | identifier_body |
Index.js | import React, { Component, Fragment } from 'react';
import { Route } from "react-router-dom";
import {
Card,
Table,
Modal,
Button,
Drawer,
message,
Breadcrumb,
} from 'antd';
import utils from '@/utils';
import moment from 'moment';
import Enum, { AUTH } from '@/enum';
import classnames from 'classnames';
import... | }
}, {
title: '交易金额',
width: 100,
align: 'right',
render: (data) => utils.formatMoney((data.price * data.goods_amount) / 100)
}, {
title: '交易时间',
dataIndex: 'create_time',
width: 130,
render: data => {
if (data) {
return moment.unix(data).format('YYYY-MM-DD HH:mm');
... | render: data => {
if (data.trim()) {
return data;
}
return '-'; | random_line_split |
Index.js | import React, { Component, Fragment } from 'react';
import { Route } from "react-router-dom";
import {
Card,
Table,
Modal,
Button,
Drawer,
message,
Breadcrumb,
} from 'antd';
import utils from '@/utils';
import moment from 'moment';
import Enum, { AUTH } from '@/enum';
import classnames from 'classnames';
import... | mns = [
{
title: '流水号',
dataIndex: 'order_number',
fixed: 'left',
width: 210
}, {
title: '三方单号',
dataIndex: 'serial_number',
fixed: 'left',
width: 320,
render: data => {
if (data.trim()) {
return data;
}
return '-';
}
}, {
title: '交易金额',
widt... | creatColumns(state) {
const colu | conditional_block |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... |
fn create_grid(points: &Vec<Point>, bounds: &Bounds) -> Grid {
let mut grid = HashMap::new();
for x in bounds.x.min..=bounds.x.max {
for y in bounds.y.min..=bounds.y.max {
let point = (x, y);
match closest_point(&point, points) {
Some(area_number) => grid.insert... | {
let points = parse_input(include_str!("../input/day_06.txt"));
let bounds = create_bounds(&points);
let grid = create_grid(&points, &bounds);
let mut areas = HashMap::new();
let mut infinite_areas = HashSet::new();
for (point, area_number) in grid.iter() {
if on_bounds(point,&bounds)... | identifier_body |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... | let bounds = Bounds {x:x_range, y:y_range};
assert!(on_bounds(&(0, 4), &bounds));
assert!(on_bounds(&(3, 2), &bounds));
assert!(on_bounds(&(2, 6), &bounds));
assert!(!on_bounds(&(2, 7), &bounds));
assert!(!on_bounds(&(2, 5), &bounds));
assert!(!on_bounds(&(1, 1)... | fn test_on_bounds() {
let x_range = Range {min:0, max:3};
let y_range = Range {min:2, max:6}; | random_line_split |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... | (reference_point: &Point, points: &Vec<Point>) -> i32 {
points.iter()
.map(|point| distance(reference_point, point))
.sum()
}
fn closest_point(reference_point: &Point, points: &Vec<Point>) -> Option<usize> {
let (index, _) = points.iter()
.map(|point| distance(reference_point, point))
... | total_distance | identifier_name |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | (&self, record: &log::Record) {
let message = format!("{}:{} -- {}", record.level(), record.target(), record.args());
println!("{}", message);
#[cfg(target_os = "android")]
{
unsafe {
let message = ::std::ffi::CString::new(message).unwrap();
le... | log | identifier_name |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | // We take the "low road" here when returning the structs - we expose the
// items (and arrays of items) as strings, which are JSON. The rust side of
// the world gets serialization and deserialization for free and it makes
// memory management that little bit simpler.
extern crate failure;
extern crate serde_json;
ex... | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
| random_line_split |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
#[no_mangle]
pub unsafe extern "C" fn sync15_passwords_sync(
state: *mut PasswordState,
key_id: *const c_char,
access_token: *const c_char,
sync_key: *const c_char,
tokenserver_url: *const c_char,
error: *mut ExternError
) {
with_translated_void_result(error, || {
assert_pointer_not... |
Ok(url::Url::parse(url)?)
}
| identifier_body |
lucy.go | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not... | (docID int32) Doc {
retvalCF := C.lucy_Doc_new(nil, C.int32_t(docID))
return WRAPDoc(unsafe.Pointer(retvalCF))
}
//export GOLUCY_Doc_init
func GOLUCY_Doc_init(d *C.lucy_Doc, fields unsafe.Pointer, docID C.int32_t) *C.lucy_Doc {
ivars := C.lucy_Doc_IVARS(d)
if fields != nil {
ivars.fields = unsafe.Pointer(C.cfish... | NewDoc | identifier_name |
lucy.go | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not... | registry.delete(rxID)
C.cfish_super_destroy(unsafe.Pointer(rt), C.LUCY_REGEXTOKENIZER)
}
//export GOLUCY_RegexTokenizer_Tokenize_Utf8
func GOLUCY_RegexTokenizer_Tokenize_Utf8(rt *C.lucy_RegexTokenizer, str *C.char,
stringLen C.size_t, inversion *C.lucy_Inversion) {
ivars := C.lucy_RegexTokenizer_IVARS(rt)
rxID :... | random_line_split | |
lucy.go | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not... | else {
patternGo = clownfish.CFStringToGo(unsafe.Pointer(pattern))
}
rx, err := regexp.Compile(patternGo)
if err != nil {
panic(err)
}
rxID := registry.store(rx)
ivars.token_re = unsafe.Pointer(rxID)
return rt
}
//export GOLUCY_RegexTokenizer_Destroy
func GOLUCY_RegexTokenizer_Destroy(rt *C.lucy_RegexToke... | {
patternGo = "\\w+(?:['\\x{2019}]\\w+)*"
} | conditional_block |
lucy.go | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not... |
//export GOLUCY_Doc_Set_Fields
func GOLUCY_Doc_Set_Fields(d *C.lucy_Doc, fields unsafe.Pointer) {
ivars := C.lucy_Doc_IVARS(d)
temp := ivars.fields
ivars.fields = unsafe.Pointer(C.cfish_inc_refcount(fields))
C.cfish_decref(temp)
}
//export GOLUCY_Doc_Get_Size
func GOLUCY_Doc_Get_Size(d *C.lucy_Doc) C.uint32_t {
... | {
ivars := C.lucy_Doc_IVARS(d)
if fields != nil {
ivars.fields = unsafe.Pointer(C.cfish_inc_refcount(fields))
} else {
ivars.fields = unsafe.Pointer(C.cfish_Hash_new(0))
}
ivars.doc_id = docID
return d
} | identifier_body |
settings.py | #-*- coding: utf-8 -*-
"""
Django settings for HyperKitty + Postorius
Pay attention to settings ALLOWED_HOSTS and DATABASES!
"""
from os.path import abspath, dirname, join as joinpath
from ConfigParser import SafeConfigParser
def read_cfg(path, section=None, option=None):
config = SafeConfigParser()
config.r... | (section, option):
return config.get(section, option) if config.has_option(section, option) else None
return get(section, option) if section else get
mailman_cfg = read_cfg('/etc/mailman.cfg')
BASE_DIR = '/usr/lib/bundles/mailman-webui'
CONF_DIR = '/etc/mailman-webui'
DATA_DIR = '/var/lib/mailman-webui'
... | get | identifier_name |
settings.py | #-*- coding: utf-8 -*-
"""
Django settings for HyperKitty + Postorius
Pay attention to settings ALLOWED_HOSTS and DATABASES!
"""
from os.path import abspath, dirname, join as joinpath
from ConfigParser import SafeConfigParser
def read_cfg(path, section=None, option=None):
config = SafeConfigParser()
config.r... |
return get(section, option) if section else get
mailman_cfg = read_cfg('/etc/mailman.cfg')
BASE_DIR = '/usr/lib/bundles/mailman-webui'
CONF_DIR = '/etc/mailman-webui'
DATA_DIR = '/var/lib/mailman-webui'
LOG_DIR = '/var/log/mailman-webui'
# Hosts/domain names that are valid for this site.
# NOTE: You MUST add d... | return config.get(section, option) if config.has_option(section, option) else None | identifier_body |
settings.py | #-*- coding: utf-8 -*- | Django settings for HyperKitty + Postorius
Pay attention to settings ALLOWED_HOSTS and DATABASES!
"""
from os.path import abspath, dirname, join as joinpath
from ConfigParser import SafeConfigParser
def read_cfg(path, section=None, option=None):
config = SafeConfigParser()
config.read(path)
def get(secti... | """ | random_line_split |
settings.py | #-*- coding: utf-8 -*-
"""
Django settings for HyperKitty + Postorius
Pay attention to settings ALLOWED_HOSTS and DATABASES!
"""
from os.path import abspath, dirname, join as joinpath
from ConfigParser import SafeConfigParser
def read_cfg(path, section=None, option=None):
config = SafeConfigParser()
config.r... |
#
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
#
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
#
# Absolute path to the directory static... | import ldap
from django_auth_ldap.config import LDAPSearch
ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs')
AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
'ou=People,dc=example,dc=org',
ldap.SCOPE_SUBTREE,
'(&(mail=*)(uid=%(use... | conditional_block |
document-data.ts | /********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*... | private getText(): string {
return this.lines.join(this.eol);
}
private validatePosition(position: theia.Position): theia.Position {
if (!(position instanceof Position)) {
throw new Error('Invalid argument');
}
let { line, character } = position;
let has... | return range;
}
return new Range(start.line, start.character, end.line, end.character);
}
| random_line_split |
document-data.ts | /********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*... | () { return that.lines.length; },
lineAt(lineOrPos: number | theia.Position) { return that.lineAt(lineOrPos); },
offsetAt(pos) { return that.offsetAt(pos); },
positionAt(offset) { return that.positionAt(offset); },
validateRange(ran) { return that.validate... | lineCount | identifier_name |
document-data.ts | /********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*... |
return undefined;
}
}
export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
// Exit early if it's one of these special cases which are meant to match
// against an empty string
if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s... | {
return new Range(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1);
} | conditional_block |
document-data.ts | /********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*... |
private validatePosition(position: theia.Position): theia.Position {
if (!(position instanceof Position)) {
throw new Error('Invalid argument');
}
let { line, character } = position;
let hasChanged = false;
if (line < 0) {
line = 0;
cha... | {
return this.lines.join(this.eol);
} | identifier_body |
run_hook.go | /*
Copyright The Stash Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | (hookErr error) error {
statusOpt := status.UpdateStatusOptions{
Config: opt.config,
KubeClient: opt.kubeClient,
StashClient: opt.stashClient,
Namespace: opt.namespace,
Metrics: opt.metricOpts,
TargetRef: v1beta1.TargetRef{
Kind: opt.targetKind,
Name: opt.targetName,
},
}
if opt.hookT... | handlePreTaskHookFailure | identifier_name |
run_hook.go | /*
Copyright The Stash Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
}
}
}
return "", fmt.Errorf("no pod found for AppBinding %s/%s", opt.namespace, appbindingName)
}
func (opt *hookOptions) handlePreTaskHookFailure(hookErr error) error {
statusOpt := status.UpdateStatusOptions{
Config: opt.config,
KubeClient: opt.kubeClient,
StashClient: opt.stashClient,
Namespa... | {
return notReadyAddrs.TargetRef.Name, nil
} | conditional_block |
run_hook.go | /*
Copyright The Stash Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
func (opt *hookOptions) handlePreTaskHookFailure(hookErr error) error {
statusOpt := status.UpdateStatusOptions{
Config: opt.config,
KubeClient: opt.kubeClient,
StashClient: opt.stashClient,
Namespace: opt.namespace,
Metrics: opt.metricOpts,
TargetRef: v1beta1.TargetRef{
Kind: opt.targetKi... | {
// get the AppBinding
appbinding, err := opt.appClient.AppcatalogV1alpha1().AppBindings(opt.namespace).Get(context.TODO(), appbindingName, metav1.GetOptions{})
if err != nil {
return "", err
}
// AppBinding should have a Service in ClientConfig field. This service selects the app pod. We will execute the hook... | identifier_body |
run_hook.go | /*
Copyright The Stash Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | if err != nil {
// For preBackup or preRestore hook failure, we will fail the container so that the task does to proceed to next step.
// We will also update the BackupSession/RestoreSession status as the update-status Function will not execute.
if opt.hookType == apis.PreBackupHook || opt.hookType == ap... | random_line_split | |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... |
/// List all running applications.
#[cfg(all(not(target_os = "android"), not(target_os = "linux")))]
async fn ps(state: &State) -> Result<String> {
to_table(
vec![vec![
"Name".to_string(),
"Version".to_string(),
"Uptime".to_string(),
]]
.iter()
.... | {
to_table(
vec![vec![
"Name".to_string(),
"Version".to_string(),
"Running".to_string(),
"Type".to_string(),
]]
.iter()
.cloned()
.chain(
state
.applications()
.sorted_by_key(|app| app... | identifier_body |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... | (tx: &EventTx) -> Result<()> {
let rx = serve().await?;
let tx = tx.clone();
// Spawn a task that handles lines received on the debug port.
task::spawn(async move {
while let Ok((line, tx_reply)) = rx.recv().await {
tx.send(Event::Console(line, tx_reply)).await;
}
});
... | init | identifier_name |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... | /// Start applications. If `args` is empty *all* known applications that
/// are not in a running state are started. If a argument is supplied it
/// is used to construct a Regex and all container (names) matching that
/// Regex are attempted to be started.
async fn start(state: &mut State, args: &[&str]) -> Result<Str... | }
| random_line_split |
basic.rs | #[test]
fn basics() {
let immutable = 5;
let mut mutable = 6;
mutable = 2;
let spaces = " "; // auto type deduction
let spaces = spaces.len(); // "shadowing" new variable with same name
const CONSTANT: u32 = 100_000; // constant (type must be specified)
let tuple: (i32, f64, u8) = (50... | }
}
#[test]
fn using_other_iterator_trait_methods() {
let sum: u32 = Counter::new()
.zip(Counter::new().skip(1))
.map(|(a, b)| a * b)
.filter(|x| x % 3 == 0)
.sum();
assert_eq!(18, sum);
}
}
// cargo and creates
// //! Another doc... | None
} | random_line_split |
basic.rs |
#[test]
fn basics() {
let immutable = 5;
let mut mutable = 6;
mutable = 2;
let spaces = " "; // auto type deduction
let spaces = spaces.len(); // "shadowing" new variable with same name
const CONSTANT: u32 = 100_000; // constant (type must be specified)
let tuple: (i32, f64, u8) = (5... | {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
}
// strings
// str is implemented in the core language and String is in the standard library
f... | SpreadsheetCell | identifier_name |
vechain.go | package vechain
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/myafeier/log"
)
// ============common============
//通用请求表单
type Form struct {
AppId string `json:"appid"`
AppKey string `json:"appkey"`
N... | respData := new(ResponseData)
respData.Data = new(Token)
err = json.Unmarshal(body, respData)
if respData.Code != 1 {
err = fmt.Errorf("responseCode:%d error,message:%s\n", respData.Code, respData.Message)
log.Error(err.Error())
goto Retry
}
token = respData.Data.(*Token)
return
}
//======================... | goto Retry
}
log.Debug("toke response :%s \n", body) | random_line_split |
vechain.go | package vechain
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/myafeier/log"
)
// ============common============
//通用请求表单
type Form struct {
AppId string `json:"appid"`
AppKey string `json:"appkey"`
N... | return
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
req.Header.Add("language", "zh_hans")
req.Header.Add("x-api-token", tokenServer.GetToken())
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
log.Error(err.Error())
return
}
defer resp.Body.Close()
respBody... | or(err.Error())
| identifier_name |
vechain.go | package vechain
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/myafeier/log"
)
// ============common============
//通用请求表单
type Form struct {
AppId string `json:"appid"`
AppKey string `json:"appkey"`
N... | != nil {
log.Error(err.Error())
goto Retry
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
req.Header.Add("language", "zh_hans")
req.Header.Add("x-api-token", token)
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
log.Error(err.Error())
goto Retry
}
defer ... | bytes.NewBuffer(data))
if err | conditional_block |
vechain.go | package vechain
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/myafeier/log"
)
// ============common============
//通用请求表单
type Form struct {
AppId string `json:"appid"`
AppKey string `json:"appkey"`
N... | ============
//返回Token结构
type Token struct {
Token string `json:"token"`
Expire int64 `json:"expire"`
}
var lock int32 = 0
var refreshError = fmt.Errorf("token refreshing")
func GetToken(config *VechainConfig) (token *Token, err error) {
if atomic.LoadInt32(&lock) == 1 {
err = refreshError
return
}
atomic.... | ansactionId)
}
//=========================Token========== | identifier_body |
pyvideo_scrape.py | #!/usr/bin/env python3
"""Scrape several conferences into pyvideo repository"""
import copy
import datetime
import json
import os
import pathlib
import re
import sys
import sh
import slugify
import yaml
import youtube_dl
from loguru import logger
JSON_FORMAT_KWARGS = {
'indent': 2,
'separators': (',', ': ')... | if youtube_video_data: # Valid video
self.youtube_videos.append(
Video.from_youtube(
video_data=youtube_video_data, event=self))
else:
logger.warning('Null youtube video')
def load_video_data(self):
"""Load... | youtube_list = sum((scrape_url(url) for url in self.youtube_lists), [])
for youtube_video_data in youtube_list: | random_line_split |
pyvideo_scrape.py | #!/usr/bin/env python3
"""Scrape several conferences into pyvideo repository"""
import copy
import datetime
import json
import os
import pathlib
import re
import sys
import sh
import slugify
import yaml
import youtube_dl
from loguru import logger
JSON_FORMAT_KWARGS = {
'indent': 2,
'separators': (',', ': ')... |
def save_video_data(self):
"""Save all event videos in PyVideo format"""
if self.overwrite:
# Erase old event videos
for path in self.video_dir.glob('*.json'):
path.unlink()
for video in self.videos:
video.save()
def create_commit(se... | self.videos = self.youtube_videos | conditional_block |
pyvideo_scrape.py | #!/usr/bin/env python3
"""Scrape several conferences into pyvideo repository"""
import copy
import datetime
import json
import os
import pathlib
import re
import sys
import sh
import slugify
import yaml
import youtube_dl
from loguru import logger
JSON_FORMAT_KWARGS = {
'indent': 2,
'separators': (',', ': ')... |
def save(self):
""""Save to disk"""
path = self.event.video_dir / '{}.json'.format(self.filename)
if path.exists():
duplicate_num = 1
new_path = path
while new_path.exists():
duplicate_num += 1
new_path = path.parent / (
... | ""Create video copy overwriting fields """
merged_video = Video(self.event)
merged_video.filename = self.filename
for field in self.metadata:
if field in set(fields):
merged_video.metadata[field] = new_video.metadata.get(field)
else:
merged... | identifier_body |
pyvideo_scrape.py | #!/usr/bin/env python3
"""Scrape several conferences into pyvideo repository"""
import copy
import datetime
import json
import os
import pathlib
import re
import sys
import sh
import slugify
import yaml
import youtube_dl
from loguru import logger
JSON_FORMAT_KWARGS = {
'indent': 2,
'separators': (',', ': ')... | (self, upload_date_str):
"""Calculate record date from youtube field and event dates"""
upload_date = datetime.date(
int(upload_date_str[0:4]),
int(upload_date_str[4:6]), int(upload_date_str[6:8]))
if self.event.know_date:
if not (self.event.date_begin <= upl... | __calculate_date_recorded | identifier_name |
verbose.py | #!/usr/bin/env python
import sys
from datetime import datetime, timedelta
from xml.etree import ElementTree as ET
import csv
weekdays = ('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
# locations = {}
# with open('lost-locations.csv') as locfile:
# reader = csv.DictReader(locfile)
# for line in reader:
# ... |
def find_max_temp(pdata, day):
""" find min temp for the night of <prev_day> to <next_day> """
for ival in range(len(pdata['values'])):
start = pdata['time-layout']['start'][ival]
end = pdata['time-layout']['end'][ival]
if start.day == day and end.day == day:
return int(pda... | """ find min temp for the night of <prev_day> to <next_day> """
for ival in range(len(pdata['values'])):
start = pdata['time-layout']['start'][ival]
end = pdata['time-layout']['end'][ival]
if start.day == prev_day and end.day == next_day:
return int(pdata['values'][ival])
# r... | identifier_body |
verbose.py | #!/usr/bin/env python
import sys
from datetime import datetime, timedelta
from xml.etree import ElementTree as ET
import csv
weekdays = ('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
# locations = {}
# with open('lost-locations.csv') as locfile:
# reader = csv.DictReader(locfile)
# for line in reader:
# ... | (pdata, day):
""" find min temp for the night of <prev_day> to <next_day> """
for ival in range(len(pdata['values'])):
start = pdata['time-layout']['start'][ival]
end = pdata['time-layout']['end'][ival]
if start.day == day and end.day == day:
return int(pdata['values'][ival])... | find_max_temp | identifier_name |
verbose.py | #!/usr/bin/env python
import sys
from datetime import datetime, timedelta
from xml.etree import ElementTree as ET
import csv
weekdays = ('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
# locations = {}
# with open('lost-locations.csv') as locfile:
# reader = csv.DictReader(locfile)
# for line in reader:
# ... |
if debug:
print ' final:'
for key in sorted(dailyvals.keys()):
print ' ', key, dailyvals[key]
return dailyvals
def parse_data(root, time_layouts, debug=False):
pars = root.find('data').find('parameters')
data = {}
for vardata in pars:
# first figure out the... | dailyvals[int(starts[ival].day)] = values[ival]
if action == 'mean':
# if debug:
# print 'total', get_time_delta_in_hours(starts[ival], ends[ival])
dailyvals[int(starts[ival].day)] /= weight_sum[ival] #get_time_delta_in_hours(starts[ival], ends[ival]) | conditional_block |
verbose.py | #!/usr/bin/env python
import sys
from datetime import datetime, timedelta
from xml.etree import ElementTree as ET
import csv
weekdays = ('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
# locations = {}
# with open('lost-locations.csv') as locfile:
# reader = csv.DictReader(locfile)
# for line in reader:
# ... | # liquid
row += '<font color=blue><b>'
if day.day in liquid:
if liquid[day.day] > 0.0:
row += (' %.2f' % liquid[day.day]).replace('0.', '.')
else:
row += ' 0'
else:
row += ' - '
row += '</b></font>'
# ... | if day.day in percent_precip:
row += ' %.0f<font size=1>%%</font>' % percent_precip[day.day]
| random_line_split |
ethereum-block.ts | import {toBigIntBE, toBufferBE} from 'bigint-buffer';
import {RlpEncode, RlpList} from 'rlp-stream';
import * as secp256k1 from 'secp256k1';
declare var process: {browser: boolean;};
const keccak = require('keccak');
interface NativeInterface {
recoverFromAddress(verifyBlock: Buffer, signature: Buffer, recovery: bo... | gth > 32) {
throw new Error(`s > 32 bytes!`);
}
const signature = Buffer.alloc(64, 0);
r.copy(signature, 32 - r.length);
s.copy(signature, 64 - s.length);
const chainV = options.chainId * 2 + 35;
const verifySignature =
options.eip155 ? v[0] === chainV || v[0] === chainV + 1 : false;
const rec... | new Error(`r > 32 bytes!`);
}
if (s.len | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.