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 |
|---|---|---|---|---|
feature_extract.py | numtaps = 255
fil = firwin(numtaps, norm_cutoff)
x_pad = np.pad(x, (numtaps, numtaps), 'edge')
lpf_x = lfilter(fil, 1, x_pad)
lpf_x = lpf_x[numtaps + numtaps // 2: -numtaps // 2]
return lpf_x
def convert_to_continuos_f0(f0):
"""CONVERT F0 TO CONTINUOUS F0.
Args:
f0 (ndarray): or... |
# perform linear interpolation
f = interp1d(nz_frames, f0[nz_frames])
cont_f0 = f(np.arange(0, f0.shape[0]))
return uv, cont_f0
def stft_mcep(x, fftl=512, shiftl=256, dim=25, alpha=0.41, window="hamming", is_padding=False):
"""EXTRACT STFT-BASED MEL-CEPSTRUM.
Args:
x (ndarray): Nump... | # get non-zero frame index
nz_frames = np.where(f0 != 0)[0] | random_line_split |
feature_extract.py | numtaps = 255
fil = firwin(numtaps, norm_cutoff)
x_pad = np.pad(x, (numtaps, numtaps), 'edge')
lpf_x = lfilter(fil, 1, x_pad)
lpf_x = lpf_x[numtaps + numtaps // 2: -numtaps // 2]
return lpf_x
def convert_to_continuos_f0(f0):
"""CONVERT F0 TO CONTINUOUS F0.
Args:
f0 (ndarray): or... | (x, fftl=512, shiftl=256, dim=25, alpha=0.41, window="hamming", is_padding=False):
"""EXTRACT STFT-BASED MEL-CEPSTRUM.
Args:
x (ndarray): Numpy double array with the size (T,).
fftl (int): FFT length in point (default=512).
shiftl (int): Shift length in point (default=256).
dim ... | stft_mcep | identifier_name |
feature_extract.py | numtaps = 255
fil = firwin(numtaps, norm_cutoff)
x_pad = np.pad(x, (numtaps, numtaps), 'edge')
lpf_x = lfilter(fil, 1, x_pad)
lpf_x = lpf_x[numtaps + numtaps // 2: -numtaps // 2]
return lpf_x
def convert_to_continuos_f0(f0):
"""CONVERT F0 TO CONTINUOUS F0.
Args:
f0 (ndarray): or... | shiftl = int(args.shiftms * fs * 0.001)
mspc = librosa.feature.melspectrogram(
x_norm, fs,
n_fft=args.fftl,
hop_length=shiftl,
n_mels=args.mspc_dim,
fmin=args.fmin if args.fmin is not None else 0,
fmax=args.fmax if args.fmax is not ... | """EXTRACT MEL SPECTROGRAM."""
# define feature extractor
for i, wav_name in enumerate(wav_list):
logging.info("now processing %s (%d/%d)" % (wav_name, i + 1, len(wav_list)))
# load wavfile and apply low cut filter
fs, x = wavfile.read(wav_name)
if x.dtype != np.int16:
... | identifier_body |
feature_extract.py | numtaps = 255
fil = firwin(numtaps, norm_cutoff)
x_pad = np.pad(x, (numtaps, numtaps), 'edge')
lpf_x = lfilter(fil, 1, x_pad)
lpf_x = lpf_x[numtaps + numtaps // 2: -numtaps // 2]
return lpf_x
def convert_to_continuos_f0(f0):
"""CONVERT F0 TO CONTINUOUS F0.
Args:
f0 (ndarray): or... |
# get number of frames
n_frame = (len(x) - fftl) // shiftl + 1
# get window function
win = get_window(window, fftl)
# calculate spectrogram
mcep = [pysptk.mcep(x[shiftl * i: shiftl * i + fftl] * win,
dim, alpha, eps=EPS, etype=1)
for i in range(n_frame)]
... | n_pad = fftl - (len(x) - fftl) % shiftl
x = np.pad(x, (0, n_pad), 'reflect') | conditional_block |
main.py | ('Set-Cookie', 'user_id=; Path=/')
def initialize(self, *a, **kw):
webapp2.RequestHandler.initialize(self, *a, **kw)
uid = self.read_secure_cookie('user_id')
if uid != None:
uid = check_secure_val(uid)
if uid != None:
self.username = User.by_id(int(uid)).name
else:
self.username = None
else:... |
EMAIL_RE = re.compile(r'^[\S]+@[\S]+\.[\S]+$')
def valid_email(email):
return not email or EMAIL_RE.match(email)
class SignUp(BaseHandler):
def get(self):
if self.username != None:
self.redirect('/welcome')
# if valid_username(self.username):
# self.render('welcome.html', username = self.username)
el... | return password and PASS_RE.match(password) | identifier_body |
main.py | _header('Set-Cookie', 'user_id=; Path=/')
def initialize(self, *a, **kw):
webapp2.RequestHandler.initialize(self, *a, **kw)
uid = self.read_secure_cookie('user_id')
if uid != None:
uid = check_secure_val(uid)
if uid != None:
self.username = User.by_id(int(uid)).name
else:
self.username = None
... | if not valid_email(email):
params['error_email'] = "That's not a valid email."
have_error = True
if have_error:
self.render('signup-form.html', **params)
else:
# cooked = 'name=' + uname + ';Path=/'
# self.response.headers.add_header('Set-Cookie',str(cooked))
# self.set_cook('name', uname)
u... | elif password != verify:
params['error_verify'] = "Your passwords didn't match."
have_error = True
| random_line_split |
main.py | .IntegerProperty(required=True)
@classmethod
def by_id(cls, uid):
return User.get_by_id(uid)
@classmethod
def by_name(cls, name):
u = User.all().filter('name =', name).get()
return u
@classmethod
def register(cls, name, pw, email = None):
pw_hash = make_pw_hash(name, pw)
return User(name = name,
... | conn.execute("INSERT INTO transactionRequests VALUES (?,?,?,?,?,?)", (self.username,stk_qty,sname,stk_price,t_now,"SELL--FAILED"))
print('naaah boy') | conditional_block | |
main.py | _header('Set-Cookie', 'user_id=; Path=/')
def initialize(self, *a, **kw):
webapp2.RequestHandler.initialize(self, *a, **kw)
uid = self.read_secure_cookie('user_id')
if uid != None:
uid = check_secure_val(uid)
if uid != None:
self.username = User.by_id(int(uid)).name
else:
self.username = None
... | (self):
uname=self.request.get('username')
passwd=self.request.get('password')
u=User.login(uname, passwd)
if u:
self.login(u)
self.redirect('/welcome')
else:
msg = 'Invalid login'
self.render('login-form.html', error = msg)
class LogOut(BaseHandler):
def get(self):
self.logout()
self.redire... | post | identifier_name |
exception.rs | }
paste::item! {
pub fn [< $body:snake _ code >] () -> u16{
$code
}
pub fn [< $body Code >] () -> u16{
$code
}
}
)*
}
}
}
... | error
))
}
} | random_line_split | |
exception.rs | self.cause,
backtrace: self.backtrace,
}
}
pub fn add_message_back(self, msg: impl AsRef<str>) -> Self {
Self {
code: self.code(),
display_text: format!("{}{}", self.display_text, msg.as_ref()),
cause: self.cause,
backtrace: self.back... | (error: std::num::ParseIntError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<std::num::ParseFloatError> for ErrorCode {
fn from(error: std::num::ParseFloatError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<common_arrow::arrow::error::ArrowError> for ErrorCode {
... | from | identifier_name |
exception.rs | .cause,
backtrace: self.backtrace,
}
}
pub fn add_message_back(self, msg: impl AsRef<str>) -> Self {
Self {
code: self.code(),
display_text: format!("{}{}", self.display_text, msg.as_ref()),
cause: self.cause,
backtrace: self.backtrace... |
}
impl From<std::num::ParseFloatError> for ErrorCode {
fn from(error: std::num::ParseFloatError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<common_arrow::arrow::error::ArrowError> for ErrorCode {
fn from(error: common_arrow::arrow::error::ArrowError) -> Self {
ErrorCode::fro... | {
ErrorCode::from_std_error(error)
} | identifier_body |
mailbox.rs | 18,
config: 0x1c,
write: 0x20,
};
// MailboxRegisterOffsets {
// read: 0x20,
// peek: 0x30,
// sender: 0x34,
// status: 0x38,
// config: 0x3c,
// write: 0x40,
// },
// ];
#[inline]
unsafe fn read_reg(base: usize, offset: u8) -> u32 {
((MAPPED_REGISTER... | (base: usize, offset: u8, value: u32) {
((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value)
}
unsafe fn read_mailbox(channel: u8) -> u32 {
// 1. Read the status register until the empty flag is not set.
// 2. Read data from the read register.
// 3. If the lower four bit... | write_reg | identifier_name |
mailbox.rs | 18,
config: 0x1c,
write: 0x20,
};
// MailboxRegisterOffsets {
// read: 0x20,
// peek: 0x30,
// sender: 0x34,
// status: 0x38,
// config: 0x3c,
// write: 0x40,
// },
// ];
#[inline]
unsafe fn read_reg(base: usize, offset: u8) -> u32 {
((MAPPED_REGISTER... |
limit -= 1;
}
write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32));
fence(Ordering::SeqCst);
// println!("Finished writing to mailbox");
}
pub trait PropertyTagList: Sized {
fn prepare(self) -> PropertyMessageWrapper<Self> {
PropertyMessageWrapper::new(self)
}
... | {
panic!(
"Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})",
channel, data
);
} | conditional_block |
mailbox.rs | println!(
// "Got data from mailbox: {:#8x} (from channel {})",
// data, read_channel
// );
if read_channel != channel {
// println!("Wrong channel, trying again...");
if limit == 0 {
panic!(
"Got trampled too many time... | {
let resp: u32;
let msg_ptr = msg as *mut T;
let msg_addr_usize = msg_ptr as usize;
let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?;
unsafe {
write_mailbox(channel as u8, msg_addr_u32);
resp = read_mailbox(channel as u8);
}
// println!(
// "Got response... | identifier_body | |
mailbox.rs | x18,
config: 0x1c,
write: 0x20,
};
// MailboxRegisterOffsets {
// read: 0x20,
// peek: 0x30,
// sender: 0x34,
// status: 0x38,
// config: 0x3c,
// write: 0x40,
// },
// ];
#[inline]
unsafe fn read_reg(base: usize, offset: u8) -> u32 {
((MAPPED_REGISTE... | // Check the channel (lowest 4 bits) of the read value for the correct channel
// If the channel is not the one we wish to read from (i.e: 1), go to step 1
// Return the data (i.e: the read value >> 4)
// println!("Reading mailbox (want channel {})", channel);
let mut limit = 10;
loop {
... | // Execute a memory barrier
// Read from MAIL0_READ | random_line_split |
internal.rs | ![,]>,
}
// Like Path::parse_mod_style but accepts keywords in the path.
fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> {
Ok(syn::Path {
leading_colon: input.parse()?,
segments: {
let mut segments = syn::punctuated::Punctuated::new();
while input.peek(syn::... |
let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| {
value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX);
value
});
let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX);
/... | {
let name = format!("{}", trait_name.unwrap());
metadata_name_attr = quote! { #[ink(metadata_name = #name)] }
} | conditional_block |
internal.rs | Parse,
ParseStream,
},
ItemImpl,
};
use crate::{
metadata::Metadata,
trait_definition::{
EXTERNAL_METHOD_SUFFIX,
EXTERNAL_TRAIT_SUFFIX,
WRAPPER_TRAIT_SUFFIX,
},
};
pub(crate) const BRUSH_PREFIX: &'static str = "__brush";
pub(crate) struct MetaList {
pub... | parse::{ | random_line_split | |
internal.rs | Token![,]>,
}
// Like Path::parse_mod_style but accepts keywords in the path.
fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> {
Ok(syn::Path {
leading_colon: input.parse()?,
segments: {
let mut segments = syn::punctuated::Punctuated::new();
while input.peek(... | (input: ParseStream) -> syn::Result<Self> {
let path = input.call(parse_meta_path)?;
parse_meta_list_after_path(path, input)
}
}
pub(crate) enum NestedMeta {
Path(syn::Path),
List(MetaList),
}
impl Parse for NestedMeta {
fn parse(input: ParseStream) -> syn::Result<Self> {
let p... | parse | identifier_name |
internal.rs | Token![,]>,
}
// Like Path::parse_mod_style but accepts keywords in the path.
fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> | },
})
}
fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> {
let content;
Ok(MetaList {
path,
_paren_token: parenthesized!(content in input),
nested: content.parse_terminated(TokenStream2::parse)?,
})
}
fn parse_meta_after_path(... | {
Ok(syn::Path {
leading_colon: input.parse()?,
segments: {
let mut segments = syn::punctuated::Punctuated::new();
while input.peek(syn::Ident::peek_any) {
let ident = syn::Ident::parse_any(input)?;
segments.push_value(syn::PathSegment::from(id... | identifier_body |
data.py | Args:
filename: string, path to crf file
pserver: jsonrpc.ServerProxy, stanford corenlp server for parsing
Returns:
tuple, (list_stanford_sent_parses, dict_file_corefs, dict_file_synsets)
"""
parses = []
try:
with open(filename) as f:
vprint('OPEN: ... |
""" | random_line_split | |
data.py |
stderr.write("\nERROR: Could not open list file\n")
exit(EIO)
else:
|
def get_id(path):
"""Parses a file path for the filename without extension
Args:
path: string, full (or relative) file path for coreference file.
Must end in .crf
Returns:
string, file id (filename without extension)
>>> path = '/home/user/Desktop/full.crf'
>>> ge... | return parses | conditional_block |
data.py |
coreflist: list of tuples, [('1', {'text': 'dog', 'ref': None})]
Returns:
string, tagged parse tree
>>> ptree = '(S NP( (NN He)) VP( (V ran)))'
>>> coreflist = [('1', {'text': 'He', 'ref': None})]
>>> tag_ptree(ptree, coreflist)
'(S NP( COREF_TAG_1( (NN He))) VP( (V ran)))'
"... | _mk_coref_id | identifier_name | |
data.py |
class FilenameException(Exception):
"""Raised when file does not have the correct extension"""
pass
def mk_parses(listfile, corenlp_host):
"""Creates a list of FileParse objects for the files listed in the listfile
Args:
listfile: string, path to input listfile (see assignment description
... | self.ptree = parse[0]
self.words = parse[1]
self.dependencies = parse[2]
self.text = parse[3] | identifier_body | |
lucidLog-1.0.0.source.js | .pointer;
delete ua.stackLevel;
delete ua.callIdx;
delete ua.callJSON;
ua.timings.startTime = '' + ua.timings.startTime;
var uaJSON = sa.json.encode (ua);
r[uaJSON] = sa.tracer.traced[uaIdx];//sa.l.cleanupTracerData (sa.tracer.traced[uaIdx]);
};
hm (r, 'sa.tracer dump', { htmlID :... |
jQuery(window).mouseup(function(e){
if (dragging) {
jQuery('#ghostbar').remove();
jQuery(window).unbind('mousemove');
| random_line_split | |
lucidLog-1.0.0.source.js | >'
+'<div id="saLucidLog_btnShowJavascript" class="vividButton vividTheme__menu_001" style="position:absolute;left:250px;z-index:41000300"><a href="javascript:sa.l.ui.click.btnShowJavascript();">Javascript</a></div>'
+'<div id="saLucidLog_btnShowLog" class="vividButton vividTheme__menu_001" style="position:abso... | ;
ua.logMessages = lmn;
};
if (ua.calls) {
for (var i=0; i<ua.calls.length; i++) {
/*
if (!sa.l.settings.gottaCleanup) sa.l.settings.gottaCleanup = [];
sa.l.settings.gottaCleanup[sa.l.settings.gottaCleanup.length] = {
ua : ua.calls[i]
};
*/
sa.l.cleanupTracerData (ua.ca... | {
lmn[lm[i][0]] = lm[i][1][1];
} | conditional_block |
index.ts | to hold onto.
vault: Vault;
metadataCache: MetadataCache;
constructor(vault: Vault, metadataCache: MetadataCache, tag: TagIndex, prefix: PrefixIndex) {
this.vault = vault;
this.metadataCache = metadataCache;
this.tag = tag;
this.prefix = prefix;
this.reloadQueue =... |
node.totalCount += 1;
node.files.add(path);
}
public static remove(root: PrefixIndexNode, path: string) {
let parts = path.split("/");
let node = root;
let nodes = [];
for (let index = 0; index < parts.length - 1; index++) {
if (!node.children.has(p... | {
if (!node.children.has(parts[index])) node.children.set(parts[index], new PrefixIndexNode(parts[index]));
node.totalCount += 1;
node = node.children.get(parts[index]) as PrefixIndexNode;
} | conditional_block |
index.ts | things to hold onto.
vault: Vault;
metadataCache: MetadataCache;
constructor(vault: Vault, metadataCache: MetadataCache, tag: TagIndex, prefix: PrefixIndex) {
this.vault = vault;
this.metadataCache = metadataCache;
this.tag = tag;
this.prefix = prefix;
this.reload... | {
// TODO: Instead of only storing file paths at the leaf, consider storing them at every level,
// since this will make for faster deletes and gathers in exchange for slightly slower adds and more memory usage.
// since we are optimizing for gather, and file paths tend to be shallow, this should be ok.
... | PrefixIndexNode | identifier_name |
index.ts | = fileCache.frontmatter;
// Search for the 'tags' field, since it may have wierd
let tagsName: string | undefined = undefined;
for (let key of Object.keys(frontCache ?? {})) {
if (key.toLowerCase() == "tags" || key.toLowerCase() == "tag")
tagsName = key;
}
... | {
this.vault = vault;
this.cache = cache;
} | identifier_body | |
simple-job-board-public.js | * - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploaded File's Extensions
* - Validate Required Inputs ( Attachment, Phone & Email )
* - Checkbox Group Required Attribute Callbacks
* - Custom Styling of File Upload Button
*/
(function ($) {
'use strict';
... | ( event ) {
var error_free = true;
$(".sjb-attachment").each(function () {
var element = $("#" + $(this).attr("id"));
var valid = element.hasClass("valid");
var is_required_class = element.hasClass("sjb-not-required");
... | sjb_is_attachment | identifier_name |
simple-job-board-public.js | * - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploaded File's Extensions
* - Validate Required Inputs ( Attachment, Phone & Email )
* - Checkbox Group Required Attribute Callbacks
* - Custom Styling of File Upload Button
*/
(function ($) {
'use strict';
... | }
});
/**
* Initialize TelInput Plugin
*
* @since 2.2.0
*/
if ($('.sjb-phone-number').length) {
var telInput_id = $('.sjb-phone-number').map(function () {
return this.id;
}).get();
for (var i... | random_line_split | |
simple-job-board-public.js | * - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploaded File's Extensions
* - Validate Required Inputs ( Attachment, Phone & Email )
* - Checkbox Group Required Attribute Callbacks
* - Custom Styling of File Upload Button
*/
(function ($) {
'use strict';
... | else {
error_element.hide();
}
// Stop Form Submission
if (!error_free) {
event.preventDefault();
}
}
}
return error_free;
... | {
var jobpost_form_inputs = $("." + input_class).serializeArray();
var error_free = true;
for (var i in jobpost_form_inputs) {
var element = $("#" + jobpost_form_inputs[i]['name']);
var valid = element.hasClass("valid");
var is_require... | identifier_body |
simple-job-board-public.js | * - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploaded File's Extensions
* - Validate Required Inputs ( Attachment, Phone & Email )
* - Checkbox Group Required Attribute Callbacks
* - Custom Styling of File Upload Button
*/
(function ($) {
'use strict';
... | else {
input.removeClass("valid").addClass("invalid");
}
});
/**
* Initialize TelInput Plugin
*
* @since 2.2.0
*/
if ($('.sjb-phone-number').length) {
var telInput_id = $('.sjb-phone-number').map(function () {
... | {
input.removeClass("invalid").addClass("valid");
error_element.hide();
} | conditional_block |
train_timeline.py | Store some git revision info in a text file in the log directory
src_path,_ = os.path.split(os.path.realpath(__file__))
utils.store_revision_info(src_path, log_dir, ' '.join(sys.argv))
np.random.seed(seed=args.seed)
train_set = utils.get_dataset(args.data_dir)
nrof_classes = len(train_set)
pr... | (filename, epoch):
with open(filename, 'r') as f:
for line in f.readlines():
line = line.split('#', 1)[0]
if line:
par = line.strip().split(':')
e = int(par[0])
lr = float(par[1])
if e <= epoch:
learn... | get_learning_rate_from_file | identifier_name |
train_timeline.py |
def main(args):
#network = importlib.import_module(args.model_def)
subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')
log_dir = os.path.join(os.path.expanduser(args.logs_base_dir), subdir)
if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist
os.makedirs... | return tf_data.Dataset.from_tensor_slices((tensors_x,tensors_y)) | identifier_body | |
train_timeline.py | some git revision info in a text file in the log directory
src_path,_ = os.path.split(os.path.realpath(__file__))
utils.store_revision_info(src_path, log_dir, ' '.join(sys.argv))
np.random.seed(seed=args.seed)
train_set = utils.get_dataset(args.data_dir)
nrof_classes = len(train_set)
print('n... |
learning_rate = tf.train.exponential_decay(learning_rate_placeholder, global_step,
args.learning_rate_decay_epochs*args.epoch_size, args.learning_rate_decay_factor, staircase=True)
tf.summary.scalar('learning_rate', lear... | #labels_placeholder = tf.Variable(np.ones([args.batch_size,]),dtype=tf.int32, name='labels_placeholder')
phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train')
| random_line_split |
train_timeline.py | Store some git revision info in a text file in the log directory
src_path,_ = os.path.split(os.path.realpath(__file__))
utils.store_revision_info(src_path, log_dir, ' '.join(sys.argv))
np.random.seed(seed=args.seed)
train_set = utils.get_dataset(args.data_dir)
nrof_classes = len(train_set)
pr... |
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--logs_base_dir', type=str,
help='Directory where to write event logs.', default='logs/facenet_ms_mp')
parser.add_argument('--models_base_dir', type=str,
help='Directory where to write trained mod... | return learning_rate | conditional_block |
index.js | " id
let dateToday = fDate(now);
let today = document.querySelector("#todaysDate");
today.innerHTML = dateToday.toUpperCase();
}
setDateTime(); //Set the current date time for theTime & todaysDate elements
//update the current city name to match what was searched/submitted
function searchYourCity(event) {
eve... | at = `lat=${lat}`;
let currentLon = `lon=${lon}`;
//api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
let weatherCheckUrl = apiCallWeather + currentLat + "&" + currentLon + "&appid=" + apiKeyWeather + "&units=" + units;
//Get weather information from URL and then display weather
axio... | identifier_body | |
index.js | = fDate(now);
let today = document.querySelector("#todaysDate");
today.innerHTML = dateToday.toUpperCase();
}
setDateTime(); //Set the current date time for theTime & todaysDate elements
//update the current city name to match what was searched/submitted
function searchYourCity(event) {
event.preventDefault();... | navigator. | identifier_name | |
index.js | Months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
let fMonth = fMonths[currentDate.getMonth()];
return (
fDay + ", " +
fMonth +
" " +
currentDate.getDate() +
" "... | //If °F is selected
else
{
units = "imperial";
}
return units;
}
//Temperature conversion
function convertFtoC(tempF){
return Math.floor(((tempF -32)*5/9)*100)/100;
}
function convertCtoF(tempC){
return Math.floor(((tempC*9/5) + 32)*100)/100;
}
//Unit conversions
function convertUnit... |
units = "metric";
}
| conditional_block |
index.js | Months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
let fMonth = fMonths[currentDate.getMonth()];
return (
fDay + ", " +
fMonth +
" " +
currentDate.getDate() +
" "... | return units;
}
//Temperature conversion
function convertFtoC(tempF){
return Math.floor(((tempF -32)*5/9)*100)/100;
}
function convertCtoF(tempC){
return Math.floor(((tempC*9/5) + 32)*100)/100;
}
//Unit conversions
function convertUnits(){
let windSpeed = document.querySelector("#wind_Speed");
let fee... | } | random_line_split |
web.go | patterns for the inputted fields
VALID_NAME string = "^\\p{L}{2,}(?:\\x20\\p{L}{2,}){1,5}$"
VALID_SENTENCE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}]*$"
VALID_MESSAGE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}\\s]+$"
// This email regex has to g... |
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.WriteHeader(statusCode)
w.Write(resp)
}
func (c *Config) Populate() {
content, err := ioutil.ReadFile(path("/config/app.json"))
if err != nil {
... | {
http.Error(w, "Failed to encode content to JSON", http.StatusInternalServerError)
return
} | conditional_block |
web.go | patterns for the inputted fields
VALID_NAME string = "^\\p{L}{2,}(?:\\x20\\p{L}{2,}){1,5}$"
VALID_SENTENCE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}]*$"
VALID_MESSAGE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}\\s]+$"
// This email regex has to g... |
// Append an error message to slice if value fails the checks
func validateField(f *Field, hash map[string]string) {
length := 0
if f.Value != "" {
length = len(f.Value)
}
switch {
case length < f.Length.Min || length > f.Length.Max:
hash[f.Name] = fmt.Sprintf(LENGTH_ERROR, f.DisplayName, f.Length.Min, f.Le... | random_line_split | |
web.go | patterns for the inputted fields
VALID_NAME string = "^\\p{L}{2,}(?:\\x20\\p{L}{2,}){1,5}$"
VALID_SENTENCE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}]*$"
VALID_MESSAGE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}\\s]+$"
// This email regex has to g... |
// Append an error message to slice if value fails the checks
func validateField(f *Field, hash map[string]string) {
length := 0
if f.Value != "" {
length = len(f.Value)
}
switch {
case length < f.Length.Min || length > f.Length.Max:
hash[f.Name] = fmt.Sprintf(LENGTH_ERROR, f.DisplayName, f.Length.Min, f.L... | {
return *h + ":" + strconv.FormatUint(uint64(*p), 10)
} | identifier_body |
web.go | patterns for the inputted fields
VALID_NAME string = "^\\p{L}{2,}(?:\\x20\\p{L}{2,}){1,5}$"
VALID_SENTENCE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}]*$"
VALID_MESSAGE string = "^[\\p{L}\\d\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x{00B4}\\s]+$"
// This email regex has to g... | (w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, PAYLOAD_MAX_SIZE))
if err != nil {
http.Error(w, "Failed to read body from HTTP request", http.StatusInternalServerError)
return
}
mail := new(Mail)
err = json.Unmarshal(body, &mail)
if err != nil {
http.Error(... | handleWriteEmail | identifier_name |
scraper.py | (query)['body']
# find username in submission content using brackets
start, stop = comment.index('['), comment.index(']')
self.username = comment[start + 1:stop]
# -------------------------------------------
# PLANS SCRAPEY-I
# get it? like "api" except... o... | (self):
"""
Retrieve all levels of the autofinger (autoread) list.
Returns a dictionary where the keys are the group names
"Level 1", "Level 2", etc. and the values are a list of
usernames waiting to be read.
"""
# this actually doesn't scrape; there's a functio... | get_autofinger | identifier_name |
scraper.py | dict(query)['body']
# find username in submission content using brackets
start, stop = comment.index('['), comment.index(']')
self.username = comment[start + 1:stop]
# -------------------------------------------
# PLANS SCRAPEY-I
# get it? like "api" except... | verify=url.startswith('https'))
except requests.exceptions.ConnectionError:
err = "Check your internet connection. Plans could also be down."
raise PlansError(err)
return handle
def _parse_message(self, soup):
"""
Scrape... | url = '/'.join((self.base_url, name))
req = requests.Request(method, url, params=get, data=post)
prepped = self.session.prepare_request(req)
try:
handle = self.session.send(prepped, | random_line_split |
scraper.py | (query)['body']
# find username in submission content using brackets
start, stop = comment.index('['), comment.index(']')
self.username = comment[start + 1:stop]
# -------------------------------------------
# PLANS SCRAPEY-I
# get it? like "api" except... o... |
self.session = requests.Session()
self.session.cookies = self.cookiejar
self.parser = PlansPageParser()
self.username = None
def _get_page(self, name, get=None, post=None):
"""
Retrieve an HTML page from plans.
"""
method = 'GET' if post is None els... | self.cookiejar = cookiejar | conditional_block |
scraper.py | function as BS4's decoding formatter
reproduces that behavior.
"""
repls = {
'<': 'lt',
'>': 'gt',
'&': 'amp',
'"': 'quot',
}
def repl(matchobj):
return "&%s;" % repls[matchobj.group(0)]
regex = "([%s])" ... | """
Return plans updated in the last ``hours`` hours.
The result is a list of (username, timestamp) 2-tuples.
"""
post = {'mytime': str(hours)}
response = self._get_page('planwatch.php', post=post)
soup = bs4.BeautifulSoup(response.text, 'html5lib')
results = so... | identifier_body | |
AnimePageFetcher.py | return html
def load_html_from_file(file):
with open(file, 'r') as f:
html = f.read()
return html
#these are the stats found on the stat page of an anime
#Example: https://myanimelist.net/anime/30/Neon_Genesis_Evangelion/stats
def getGeneralStatistics(soup, aggregate_dict={}):
return aggrega... | (html, aggregate_data={}):
getStatSummary(html, aggregate_data)
getStatDistribution(html, aggregate_data)
return aggregate_data
def getStatSummary(html, aggregate_dict={}):
#soup = BeautifulSoup(html, 'html.parser')
start_index = stats_summary_regex.search(html).end()
end_index = stats_score_re... | scrape_stats_page | identifier_name |
AnimePageFetcher.py | with open(out_file, 'w') as f:
soup = BeautifulSoup(html, 'html.parser')
html = soup.prettify()
f.write(html.encode("utf8"))
return html
def load_html_from_file(file):
with open(file, 'r') as f:
html = f.read()
return html
#these are the stats found on the stat... | print "Writing html to", out_file
print "Type is", type(html) | random_line_split | |
AnimePageFetcher.py | return html
def load_html_from_file(file):
with open(file, 'r') as f:
html = f.read()
return html
#these are the stats found on the stat page of an anime
#Example: https://myanimelist.net/anime/30/Neon_Genesis_Evangelion/stats
def getGeneralStatistics(soup, aggregate_dict={}):
return ... |
else:
aggregate_dict["duration"] = None
# Info/Rating
if "Rating" in info_dict:
rating_text = info_dict["Rating"]
rating_shorthand = rating_text.split(" - ")[0].strip()
aggregate_dict["rating"] = rating_shorthand
else:
aggregate_dict["rating"] = None
return... | duration_text = info_dict["Duration"]
mins = 0.0
# Hours
match = hours_regex.search(duration_text)
if match is not None:
mins += float(match.group(1)) * 60.0
# Minutes
match = min_regex.search(duration_text)
if match is not None:
mins += fl... | conditional_block |
AnimePageFetcher.py | return html
def load_html_from_file(file):
with open(file, 'r') as f:
html = f.read()
return html
#these are the stats found on the stat page of an anime
#Example: https://myanimelist.net/anime/30/Neon_Genesis_Evangelion/stats
def getGeneralStatistics(soup, aggregate_dict={}):
return ... |
#Fetches the characters and voice actors associted with a show
#Example: https://myanimelist.net/anime/30/Neon_Genesis_Evangelion/characters
def getCharactersAndJapaneseCast(html):
return
#Fetches the list of other related anime, same series etc.
def getRelatedTitles(html):
return
def cooldown():
COOLDO... | return | identifier_body |
spider.js | 101043000,
101043100,
101043200,
101043300,
101043400,
101043600,
101050101,
101050102,
101050103,
101050104,
101050105,
101050106,
101050107,
101050108,
101050109,
101050110,
101050111,
101050112,
101050113,
101050201,
101050202,
1... | // var before = img[0].getAttribute("alt");
// var after = img[1].getAttribute("alt");
// result["img_title" + (i + 1)] = before;
// result["img_title" + (i + 2)] = after;
// //天气转变,多云转晴 | random_line_split | |
spider.js | 101031000,
101031100,
101031200,
101031400,
101040100,
101040200,
101040300,
101040400,
101040500,
101040600,
101040700,
101040800,
101040900,
101041000,
101041100,
101041300,
101041400,
101041500,
101041600,
101041700,
101041800,
1... | var start = new Date().getTime();
var result = {};
this.waitForSelector("div.fl h1", (function () {
// ------------- Today weather --------------
result["cityId"] = cityId;
var city = this.getHTML('div.cityName.clearfix div.fl h2');
if (city === null) {
result["cit... | _utils__.sendAJAX(host, 'POST', result, false,
{
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});
} catch (e) {
__utils__.log("Server error:" + e, 'error');
}
}
function grab(cityId) {
| identifier_body |
spider.js | 101031000,
101031100,
101031200,
101031400,
101040100,
101040200,
101040300,
101040400,
101040500,
101040600,
101040700,
101040800,
101040900,
101041000,
101041100,
101041300,
101041400,
101041500,
101041600,
101041700,
101041800,
1... | Resource.requested:" + request.url, 'info');
}
});
//casper.on('navigation.requested', function (url, navigationType, navigationLocked, isMainFrame) {
// //this.log("navigation.requested:" + url + " " + navigationType + " " + navigationLocked + " " + isMainFrame, 'info');
//});
//
//casper.on('page.resource.req... | resource.requested:" + request.url,'info');
request.abort();
} else {
//this.log(" | conditional_block |
spider.js | 01050203
];
// var dump = require("utils").dump;
// script argument
// casper.log("Casper CLI passed args:",'info');
// dump(casper.cli.args);
// filter the png & jpg, to speed up
casper.on('resource.requested', function (request) {
//if (/\.(png|jpg)$/i.test(request.url)) {
// 过滤广告链接
if (/(google|tanx|toruk|... | null) {
| identifier_name | |
real_time_plotting_new.py | generate the constrains of the picture manually)
'''
import datetime
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.image as mpimg
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# **** VARIABLES ... | (projection=ccrs.PlateCarree()):
"""
Code from https://ocefpaf.github.io/python4oceanographers/blog/2015/06/22/osm/
"""
fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right... | make_map | identifier_name |
real_time_plotting_new.py | generate the constrains of the picture manually)
'''
import datetime
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.image as mpimg
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# **** VARIABLES ... | gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
return fig, ax
def save_map_image(loc):
"""
Code adapted from https://ocefpaf.github.io/python4oceanographers/blog/2015/06/22/osm/
Grab google maps image covering geographic are... | fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True) | random_line_split |
real_time_plotting_new.py | '''
fig, axes = plt.subplots(2, 2, figsize=(20, 15), num=1,
sharex=False, sharey=False)
ax0 = axes[0, 0]
ax0.set_title('Altitude')
ax0.set_xlabel('Time')
ax0.set_ylabel('Altitude [m]')
ax1 = axes[0, 1]
ax1.set_title('Internal Temperature')
ax1.set_xlabel('... | data = data.split(',')
plot_data(data, header, axes, map_ax, img) | conditional_block | |
real_time_plotting_new.py | generate the constrains of the picture manually)
'''
import datetime
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.image as mpimg
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# **** VARIABLES ... | ax2.set_title('External Temperature')
ax2.set_xlabel('Temperature [$\degree$C]')
ax2.set_ylabel('Altitude [m]')
ax3 = axes[1, 0]
ax3.set_title('Geiger Counters')
ax3.set_xlabel('Count/Time')
ax3.set_ylabel('Altitude [m]')
ax3.legend([Line2D([0], [0], color='red', lw=4),
... | '''
Set the the axes of the desired plots
Written by Curtis Puetz 2018-07-07
Completely changed by Kimberlee Dube 2019-07-17
:return: None
'''
fig, axes = plt.subplots(2, 2, figsize=(20, 15), num=1,
sharex=False, sharey=False)
ax0 = axes[0, 0]
ax0.set_title(... | identifier_body |
main.go | of the share.
DisplaynameOwner string `json:"displayname_owner" xml:"displayname_owner"`
// Additional info to identify the share owner, eg. the email or username
AdditionalInfoOwner string `json:"additional_info_owner" xml:"additional_info_owner"`
// The permission attribute set on the file.
// TODO(jfd) change ... | if share.Id != nil { | random_line_split | |
main.go | UserTypeUser ShareWithUserType = 0
// ShareWithUserTypeGuest represents a guest user
ShareWithUserTypeGuest ShareWithUserType = 1
// The datetime format of ISO8601
_iso8601 = "2006-01-02T15:04:05Z0700"
)
// ResourceType indicates the OCS type of the resource
type ResourceType int
func (rt ResourceType) String()... | sd := &ShareData{
// share.permissions are mapped below
// Displaynames are added later
UIDOwner: LocalUserIDToString(share.GetCreator()),
UIDFileOwner: LocalUserIDToString(share.GetOwner()),
}
if share.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER {
sd.ShareType = ShareTypeUser
sd.ShareWit... | identifier_body | |
main.go | = declined
State int `json:"state" xml:"state"`
// The path to the shared file or folder.
Path string `json:"path" xml:"path"`
// The type of the object being shared. This can be one of 'file' or 'folder'.
ItemType string `json:"item_type" xml:"item_type"`
// The RFC2045-compliant mimetype of the file.
MimeType... | tUserManager(m | identifier_name | |
main.go | share expires.
Expiration string `json:"expiration" xml:"expiration"`
// The public link to the item being shared.
Token string `json:"token" xml:"token"`
// The unique id of the user that owns the file or folder being shared.
UIDFileOwner string `json:"uid_file_owner" xml:"uid_file_owner"`
// The display name o... | sd.ShareWith = "***redacted***"
sd.ShareWithDisplayname = "***redacted***"
}
| conditional_block | |
main.rs | }
total_welfare
}
// assumes that `guest_list` has already been sorted
// just doles out memory in sorted order such that we
// don't give anyone any more memory than they asked for
// it's still possible that we give people too little memory
// which should be checked after getting the result of this
// func... | (proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)>
{
let mut violations: Vec<(usize, Range)> = Vec::new();
let mut index: usize = 0;
for &(guest, amount) in proposed_allocations.iter()
{
// we want to get the guest's forbidden range with the greatest
// min value that is... | invalid_allocations | identifier_name |
main.rs | }
total_welfare
}
// assumes that `guest_list` has already been sorted
// just doles out memory in sorted order such that we
// don't give anyone any more memory than they asked for
// it's still possible that we give people too little memory
// which should be checked after getting the result of this
// func... | .forbidden_ranges
.last()
.filter(|range| {range.max == u64::max_value()})
.map(|range| {range.min})
.unwrap_or(u64::max_value());
let mem_to_alloc = min(remaining_memory, upper_bound... | {
let mut remaining_memory: u64 = available_memory;
guest_list.iter().map
(
|guest|
{
// if there's no memory left to hand out our job is simple
if remaining_memory == 0
{
0
}
// otherwise get the maximum amount mem... | identifier_body |
main.rs | }
total_welfare
}
// assumes that `guest_list` has already been sorted
// just doles out memory in sorted order such that we
// don't give anyone any more memory than they asked for
// it's still possible that we give people too little memory | // which should be checked after getting the result of this
// function
// I think what I really want to return from this is a vector of allocation amounts
// it'll even take up less space than (reference, allocation) pairs and will be much
// less problematic
fn naive_allocation
(
guest_list: &Vec<&Guest>,
av... | random_line_split | |
map.rs | .iter().map(|a| BoundLine(a, self)).collect();
bound.into_iter()
// return self.lines.iter().map(|a| BoundLine(a, self));
}
pub fn iter_sectors(&self) -> std::slice::Iter<Sector> {
self.sectors.iter()
}
pub fn iter_things(&self) -> std::slice::Iter<Thing> {
self.things.ite... | vertex_indices | identifier_name | |
map.rs | -- this should use a method. so should
// new side w/ sector
if bare_line.front_sidedef != -1 {
line.front = Some((bare_line.front_sidedef as usize).into());
}
if bare_line.back_sidedef != -1 {
line.back = Some((bare_line.back_sidedef as ... | random_line_split | ||
map.rs | .iter() {
map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64);
}
for bare_side in bare_map.sides.iter() {
let handle = map.add_side((bare_side.sector as usize).into());
let side = map.side_mut(handle);
side.lower_texture = bare_side.lower_texture.in... |
pub fn iter_things(&self) -> std::slice::Iter<Thing> {
self.things.iter()
}
pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex {
&self.vertices[handle.0]
}
pub fn side(&self, handle: Handle<Side>) -> &Side {
&self.sides[handle.0]
}
pub fn sector(&self, handle... | {
self.sectors.iter()
} | identifier_body |
models.py | .Model):
# Model representing a movie genre (e.g. Science Fiction, Non Fiction).
name = models.CharField(
max_length=200,
help_text="Enter a movie genre (e.g. Science Fiction, French Poetry etc.)"
)
def __str__(self):
# String for representing the Model object (in Admin site... |
# Checks if a director name already exists. If not, create and assign to the movie.
director = None
try:
directors = Director.objects.all()
for d in directors:
if (str(d) == str(imdb_stats[1])):
director = d... | super(Movie, self).save(*args, **kwargs)
# Uses a custom save to end date any subCases
orig = Movie.objects.get(id=self.id)
fields_to_update = []
try:
specs = self.get_video_stats()
orig.duration = specs[0]
orig.fps = specs[1]
ori... | identifier_body |
models.py | .Model):
# Model representing a movie genre (e.g. Science Fiction, Non Fiction).
name = models.CharField(
max_length=200,
help_text="Enter a movie genre (e.g. Science Fiction, French Poetry etc.)"
)
def __str__(self):
# String for representing the Model object (in Admin site... | max_num_find_articles = models.IntegerField('Max number of research articles', default=5, validators=[MinValueValidator(0), MaxValueValidator(100)], help_text="Default number is 5.")
found_articles = models.TextField('Found Research Articles', max_length=5000, null=True, blank=True, help_text="HTML list output ... | fps = models.CharField(max_length=200)
dimensions = models.CharField(max_length=200)
| random_line_split |
models.py | .Model):
# Model representing a movie genre (e.g. Science Fiction, Non Fiction).
name = models.CharField(
max_length=200,
help_text="Enter a movie genre (e.g. Science Fiction, French Poetry etc.)"
)
def __str__(self):
# String for representing the Model object (in Admin site... | (self, *args, **kwargs):
super(Movie, self).save(*args, **kwargs)
# Uses a custom save to end date any subCases
orig = Movie.objects.get(id=self.id)
fields_to_update = []
try:
specs = self.get_video_stats()
orig.duration = specs[0]
or... | save | identifier_name |
models.py | movie (but not a specific copy of a movie).
title = models.CharField(max_length=200, null=True, blank=True, help_text='This field will be overwritten if given a valid IMDB id and left blank.')
imdb_link = models.CharField('IMDB Link', max_length=100, blank=True, null=True, help_text='For example, here is <a t... | orig.found_articles = orig.get_research_articles(self.max_num_find_articles)
fields_to_update.append('found_articles') | conditional_block | |
main.py | (E-V)
ψ = -1/2ψ'' / (E-1/abs(r))
or, reversed:
ψ'' = -2(E - 1/abs(r))ψ
"""
# todo: Center it up? This approach lags.
# ψ_pp = np.diff(np.diff(ψ))
dx = (x[-1] - x[0]) / x.size
ψ_pp = np.diff(np.diff(ψ)) / dx
ψ_pp = np.append(ψ_pp, np.array([0, 0])) # make the lengths match
ψ_... | ))
print("Sample range: ", sample_range)
# Calculate nucleus-e | conditional_block | |
main.py |
from numpy import exp, ndarray, sqrt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from consts import *
import consts
τ = 2 * np.pi
i = complex(0, 1)
# 2020-11-15
"""
One of your goals is to figure out if you can use hydrogen (1d?) WFs as basis functions to create
arbitrary solns to the Sch... | from functools import partial
from typing import List, Iterable, Callable, Tuple | random_line_split | |
main.py | (self.x - other.x, self.y - other.y, self.z - other.z)
def scalar_mul(self, val: float) -> 'Vec':
return Vec(val * self.x, val * self.y, val * self.z)
def length(self) -> float:
return sqrt(self.x**2 + self.y**2 + self.z**2)
matplotlib.use("Qt5Agg")
# import seaborn as sns
# import plotly
# ... | : Callable, x: float, y: Tuple[complex, complex]
) -> Tuple[complex, complex]:
"""
d²ψ/dx² = 2m/ħ² * (V(x) - E)ψ
"""
ψ, φ = y
ψ_p = φ
φ_p = 2 * m_e / ħ ** 2 * (V(x) - E) * ψ
return ψ_p, φ_p
def solve(E: float, V: Callable, ψ0: float, ψ_p0: float, x_span: Tuple[float, float]):
"""
... | E: float, V | identifier_name |
main.py | : float
sx: float
vx: float
def mass(self):
return self.n_prot * m_p + self.n_neut * m_n
def charge(self):
# Charge from protons only.
return self.n_prot * e
def nuc_pot(nuclei: Iterable[Nucleus], sx: float) -> float:
result = 0
for nuclei in nuclei:
# Coulomb... | e to see if we can back-calculate E = -1/2."""
E = -2 / (n + 1) ** 2
x, ψ = h_static(E)
# Calculate potential between the e- field and the nucleus point by integrating.
# todo: Let's do this manually first, then try to apply a scipy.integrate approach.
dx = 1
result = 0
ψ2 = np.conj(ψ) *... | identifier_body | |
syncmgr.rs | synced up to height {} with hash {}",
height, hash
)
}
Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best),
Event::BlockConnected { height, header } => {
write!(
fmt,
... | pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self {
let peers = AddressBook::new(rng.clone());
let last_tip_update = None;
let last_peer_sample = None;
let last_idle = None;
let inflight = HashMap::with_hasher(rng.into());
Self {
... |
impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> {
/// Create a new sync manager. | random_line_split |
syncmgr.rs | {
/// A block was added to the main chain.
BlockConnected {
/// Block height.
height: Height,
/// Block header.
header: BlockHeader,
},
/// A block was removed from the main chain.
BlockDisconnected {
/// Block height.
height: Height,
/// Bloc... | Event | identifier_name | |
syncmgr.rs | up to height {} with hash {}",
height, hash
)
}
Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best),
Event::BlockConnected { height, header } => {
write!(
fmt,
... |
/// Called when a peer disconnected.
pub fn peer_disconnected(&mut self, id: &PeerId) {
self.unregister(id);
}
/// Called when we received a `getheaders` message from a peer.
pub fn received_getheaders<T: BlockReader>(
&mut self,
addr: &PeerId,
(locator_hashes, sto... | {
if link.is_outbound() && !services.has(REQUIRED_SERVICES) {
return;
}
if height > self.best_height().unwrap_or_else(|| tree.height()) {
self.upstream.event(Event::PeerHeightUpdated { height });
}
self.register(socket, height, preferred, link);
... | identifier_body |
syncmgr.rs | Reason::PeerMisbehaving("too many headers"));
return Ok(ImportResult::TipUnchanged);
}
// When unsolicited, we don't want to process too many headers in case of a DoS.
if length > MAX_UNSOLICITED_HEADERS && request.is_none() {
log::debug!("Received {} unsolicited headers... | {
return Some(time);
} | conditional_block | |
dtm.py | /django/BasicBrowser/')
import db as db
from tmv_app.models import *
from scoping.models import Doc, Query
from django.db import connection, transaction
cursor = connection.cursor()
def f_gamma2(docs,gamma,docsizes,docUTset,topic_ids):
vl = []
for d in docs:
if gamma[2][d] > 0.001:
dt = (
... | (topic_n,info,topic_ids,vocab_ids,ys):
print(topic_n)
django.db.connections.close_all()
p = "%03d" % (topic_n,)
p = "dtm-output/lda-seq/topic-"+p+"-var-e-log-prob.dat"
tlambda = np.fromfile(p, sep=" ").reshape((info['NUM_TERMS'],info['SEQ_LENGTH']))
for t in range(len(tlambda)):
for py i... | dtm_topic | identifier_name |
dtm.py | /django/BasicBrowser/')
import db as db
from tmv_app.models import *
from scoping.models import Doc, Query
from django.db import connection, transaction
cursor = connection.cursor()
def f_gamma2(docs,gamma,docsizes,docUTset,topic_ids):
vl = []
for d in docs:
if gamma[2][d] > 0.001:
|
return vl
def tokenize(text):
transtable = {ord(c): None for c in string.punctuation + string.digits}
tokens = nltk.word_tokenize(text.translate(transtable))
tokens = [i for i in tokens if len(i) > 2]
return tokens
def add_features(title):
django.db.connections.close_all()
term, created ... | dt = (
docUTset[gamma[0][d]],
topic_ids[gamma[1][d]],
gamma[2][d],
gamma[2][d] / docsizes[gamma[0][d]],
run_id
)
vl.append(dt) | conditional_block |
dtm.py | /Desktop/django/BasicBrowser/')
import db as db
from tmv_app.models import *
from scoping.models import Doc, Query
from django.db import connection, transaction
cursor = connection.cursor()
def f_gamma2(docs,gamma,docsizes,docUTset,topic_ids):
vl = []
for d in docs:
if gamma[2][d] > 0.001:
... | parallel_add = True
all_dts = []
make_t = 0
add_t = 0
def insert_many(values_list):
query='''
INSERT INTO "tmv_app_doctopic"
("doc_id", "topic_id", "score", "scaled_score", "run_id")
VALUES (%s,%s,%s,%s,%s)
... | ps = 16 | random_line_split |
dtm.py | /django/BasicBrowser/')
import db as db
from tmv_app.models import *
from scoping.models import Doc, Query
from django.db import connection, transaction
cursor = connection.cursor()
def f_gamma2(docs,gamma,docsizes,docUTset,topic_ids):
vl = []
for d in docs:
if gamma[2][d] > 0.001:
dt = (
... |
def add_features(title):
django.db.connections.close_all()
term, created = Term.objects.get_or_create(title=title)
term.run_id.add(run_id)
django.db.connections.close_all()
return term.pk
class snowball_stemmer(object):
def __init__(self):
self.stemmer = SnowballStemmer("english")
... | transtable = {ord(c): None for c in string.punctuation + string.digits}
tokens = nltk.word_tokenize(text.translate(transtable))
tokens = [i for i in tokens if len(i) > 2]
return tokens | identifier_body |
Section3.py | _regions(X,y,classifier,test_idx = None,resolution = 0.02):
markers = ("s","x","o","^","v")
colors = ("red","blue","lightgreen","gray","cyan")
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min,x1_max = X[:,0].min() - 1 ,X[:,0].max() + 1
x2_min,x2_max = X[:,1].min() - 1 ,X[:,1].max() + 1... | np.hstack((y_train,y_test))
plot_decision_regions(X = X_combined_std,y = y_combined,classifier = ppn,test_idx = range(105,150))
plt.xlabel("petal length")
plt.ylabel("petal width")
plt.legend("upper left")
plt.show()
# In[ ]:
import matplotlib.pyplot as plt
import numpy as np
import math
def sigmoid(... | alpha = 1,marker = "o",s = 100, label = "test_set")
# In[ ]:
X_combined_std = np.vstack((X_train_std,X_test_std))
y_combined = | conditional_block |
Section3.py | _regions(X,y,classifier,test_idx = None,resolution = 0.02):
markers = ("s","x","o","^","v")
colors = ("red","blue","lightgreen","gray","cyan")
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min,x1_max = X[:,0].min() - 1 ,X[:,0].max() + 1
x2_min,x2_max = X[:,1].min() - 1 ,X[:,1].max() + 1... | ,c1,label = "J(w) y = 1")
c0 = [cost_0(x) for x in z]
plt.plot(phi_z,c0,label = "J(w) y = -1")
plt.ylim(0.0,5.1)
plt.xlim([0,1])
plt.xlabel("$\phi$(z)")
plt.ylabel("J(w)")
plt.legend(loc = "upper left")
plt.tight_layout()
plt.show()
# In[ ]:
class LogisticRegressionGD(object):
def __init__(self,... | or x in z]
plt.plot(phi_z | identifier_body |
Section3.py | (X,y,classifier,test_idx = None,resolution = 0.02):
markers = ("s","x","o","^","v")
colors = ("red","blue","lightgreen","gray","cyan")
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min,x1_max = X[:,0].min() - 1 ,X[:,0].max() + 1
x2_min,x2_max = X[:,1].min() - 1 ,X[:,1].max() + 1
xx... |
# In[ ]:
svm = SVC(kernel = "rbf",random_state = 1 ,gamma = 0.10,C = 10.0)
svm.fit(X_xor,y_xor)
plot_decision_regions(X_xor,y_xor,classifier = svm)
plt.tight_layout()
plt.show()
# In[ ]:
svm = SVC(kernel = "rbf",random_state = 1,gamma = 0.2 ,C = 1.0)
svm.fit(X_train_std,y_train)
plot_decision_re... | plt.tight_layout()
plt.show()
| random_line_split |
Section3.py | _regions(X,y,classifier,test_idx = None,resolution = 0.02):
markers = ("s","x","o","^","v")
colors = ("red","blue","lightgreen","gray","cyan")
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min,x1_max = X[:,0].min() - 1 ,X[:,0].max() + 1
x2_min,x2_max = X[:,1].min() - 1 ,X[:,1].max() + 1... | random_state = random_state
def fit(self,X,y):
rgen = np.random.RandomState(self.random_state)
self.w = rgen.normal(loc = 0.0,scale = 0.01,size =1+ X.shape[1])
self.gosagun = []
for i in range(self.n_iter):
net_input = self.net_input(X)
output... | _iter
self. | identifier_name |
pipeline_cutouts.py | cutout.wcs.wcs.crpix[1])
hdu.header.set('CDELT1', cutout.wcs.wcs.cdelt[0])
hdu.header.set('CDELT2', cutout.wcs.wcs.cdelt[1])
hdu.header.set('NAXIS1', cutout.wcs.pixel_shape[0])
hdu.header.set('NAXIS2', cutout.wcs.pixel_shape[1])
return hdu
# ------ ------ ------ ------ ------ ------ ------ -... | # get cutout file names, must be in same order so they are matched correctly
images_560 = sorted(glob.glob('560*_cutout.fits'))
images_1400 = sorted(glob.glob('1400*_cutout.fits'))
# loop over image cutouts to make cube for each of them
for file560, file1400, i in zip(images_560, images_1400, range(le... | nt(' Cutting out image {0} of {1}'.format(i+1, split_into**2))
cutout = Cutout2D(hdu.data[0,0,:,:], position=tuple(position_coords_inpixels[i], size=tuple(size_inpixels[i]), mode='trim', wcs=wcs.celestial, copy=True)
cutout.plot_on_original(color=next(colourlist))
# Update the FITS header with the cutout WCS by h... | conditional_block |
pipeline_cutouts.py | j, name ):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def update_header_from_cutout2D(hdu, cut... | e_obj(ob | identifier_name | |
pipeline_cutouts.py | ', cutout.wcs.wcs.crpix[1])
hdu.header.set('CDELT1', cutout.wcs.wcs.cdelt[0])
hdu.header.set('CDELT2', cutout.wcs.wcs.cdelt[1])
hdu.header.set('NAXIS1', cutout.wcs.pixel_shape[0])
hdu.header.set('NAXIS2', cutout.wcs.pixel_shape[1])
return hdu
# ------ ------ ------ ------ ------ ------ ------... |
# create 2D array with coordinates: [ [x1,y1], [x2,y2], [x3,y3]... ]
position_coords_inpixels = np.array([positions_x,positions_y]).T
# create buffer of 5% so images overlap. This can be small... only needs to account for image edge cutting through
size = (im_width/split_into) * 1.05 # e.g. 4000 p... | = fits.open(input_image)[0]
wcs = WCS(hdu.header)
# currently hard coded to only accept square images
im_width = hdu.header['NAXIS1'] # get image width
print(' Input fits image dimensions: {0}'.format(im_width))
print(' Cutting into {0} images of dimensions {1}'.format(split_into**2, im_width/split... | identifier_body |
pipeline_cutouts.py | ', cutout.wcs.wcs.crpix[1])
hdu.header.set('CDELT1', cutout.wcs.wcs.cdelt[0])
hdu.header.set('CDELT2', cutout.wcs.wcs.cdelt[1])
hdu.header.set('NAXIS1', cutout.wcs.pixel_shape[0])
hdu.header.set('NAXIS2', cutout.wcs.pixel_shape[1])
return hdu
# ------ ------ ------ ------ ------ ------ ------... |
def do_image_chopping(input_image, split_into):
hdu = fits.open(input_image)[0]
wcs = WCS(hdu.header)
# currently hard coded to only accept square images
im_width = hdu.header['NAXIS1'] # get image width
print(' Input fits image dimensions: {0}'.format(im_width))
print(' Cutting into {0} imag... |
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ | random_line_split |
web.go | `,`description`,`last_update`,`user_id`,`group`,`unread`,`active` FROM home_view WHERE user_id=%d", userId)
if err != nil {
respondError( w, err.Error() )
return
}
feeds := make([]FeedViewItem, len(rows))
for id, row := range rows {
feeds[id] = FeedViewItem{row.Int(0), row.Str(1), row.Str(2), row.Str(3), ... | if err != nil {
respondError( w, err.Error() )
return
}
if len(rows) == 0 {
fmt.Fprint(w, "{\"error\": \"Could not find entry\"}")
return
}
row := rows[0]
b, err := json.Marshal(FeedEntryModel{row.Str(0)})
if err != nil {
respondError( w, err.Error() )
return
}
//TODO:The update and replace s... | {
id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
userId := 1
if err != nil {
respondError( w, err.Error() )
return
}
conn := GetConnection().Clone()
if err := conn.Connect(); err != nil {
respondError( w, err.Error() )
return
}
defer conn.Close()
rows, _, err := conn.Query("SELECT `conten... | identifier_body |
web.go | `,`description`,`last_update`,`user_id`,`group`,`unread`,`active` FROM home_view WHERE user_id=%d", userId)
if err != nil {
respondError( w, err.Error() )
return
}
feeds := make([]FeedViewItem, len(rows))
for id, row := range rows {
feeds[id] = FeedViewItem{row.Int(0), row.Str(1), row.Str(2), row.Str(3), ... |
/*
_, _, err = GetConnection().QueryFirst("UPDATE user_feed SET unread_items=GREATEST(unread_items-1,0) WHERE user_id=%d AND feed_id=%d", userId, feedId)
if err != nil {
panic(err)
}
*/
//TODO: Extremelly inneficient; Make better method
_, _, err = conn.QueryFirst("CALL update_unread()")
if err != nil {
... | {
respondError( w, err.Error() )
return
} | conditional_block |
web.go | `,`description`,`last_update`,`user_id`,`group`,`unread`,`active` FROM home_view WHERE user_id=%d", userId)
if err != nil {
respondError( w, err.Error() )
return
}
feeds := make([]FeedViewItem, len(rows))
for id, row := range rows {
feeds[id] = FeedViewItem{row.Int(0), row.Str(1), row.Str(2), row.Str(3), ... | (w http.ResponseWriter, r *http.Request) {
var userId uint32 = 1
searchQuery := fmt.Sprintf("userid=%d", userId)
start, err := strconv.ParseInt(r.FormValue("start"), 10, 64)
if err != nil {
start = 0
}
extraSearch, err := getFeedsQueryFromForm(r)
if err != nil {
respondError( w, err.Error() )
return
... | serveFeedItems | identifier_name |
web.go | link`,`description`,`last_update`,`user_id`,`group`,`unread`,`active` FROM home_view WHERE user_id=%d", userId)
if err != nil {
respondError( w, err.Error() )
return
}
feeds := make([]FeedViewItem, len(rows))
for id, row := range rows {
feeds[id] = FeedViewItem{row.Int(0), row.Str(1), row.Str(2), row.Str(... | respondError( w, err.Error() )
return
}
fmt.Fprint(w, string(b))
}
func serveUpdateItemLabels(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(400)
fmt.Fprint(w, "Not a post request.")
return
}
conn := GetConnection().Clone()
if err := conn.Connect(); err != nil {
r... | //TODO: Extremelly inneficient; Make better method
_, _, err = conn.QueryFirst("CALL update_unread()")
if err != nil { | random_line_split |
sandbox.ts | component onto it.
*
* To prevent a component for being initialized (for example when you want to initialize it at a later moment)
* just add a `data-skip` attribute to its root element.
*
* @class
* @param {object} config
* @param {Component[]|[Component, object][]} [config.components] Array of components cons... | {
this.$warn(
`Sandbox.stop is deprecated. Use the "destroy" method instead`,
);
} | conditional_block | |
sandbox.ts | [],
context: createContext(),
id: '',
root: document.body,
};
}
public $id: string;
public $ctx?: IContext;
public $registry: ISandboxRegistryEntry[] = [];
public $instances = new Map<
string | entrySelectorFn,
Component<any, any>[]
>();
/**
* Creates a sandbox instanc... | this.off('error'); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.