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 |
|---|---|---|---|---|
__init__.py | trans_counts[l1 - 1, l2 - 1] += 1
# Normalize by rows
row_sums = trans_counts.sum(axis=1)
trans_probs = trans_counts / row_sums.reshape((-1, 1))
# Get rid of NaNs
return np.nan_to_num(trans_probs)
def norm_by_rows(matrix):
"""Normalizes a numpy array by rows (axis 1).
... |
return buffer
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = cStringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
def rolling_func(fixations, fun, window_size_ms, step_ms):
start, end = 0, window_size_ms
re... | chars = ([" "] * pad_left) + list(line)
buffer[r, :len(chars)] = chars | conditional_block |
__init__.py | trans_counts[l1 - 1, l2 - 1] += 1
# Normalize by rows
row_sums = trans_counts.sum(axis=1)
trans_probs = trans_counts / row_sums.reshape((-1, 1))
# Get rid of NaNs
return np.nan_to_num(trans_probs)
def norm_by_rows(matrix):
"""Normalizes a numpy array by rows (axis 1).
... | (code_lines, indent_size=4):
from pygments.lexers import PythonLexer
indent_regex = re.compile(r"^\s*")
lexer = PythonLexer()
code_str = "".join(code_lines)
all_tokens = list(lexer.get_tokens(code_str, unfiltered=True))
line_tokens = []
current_line = []
for t in all_tokens:
if... | python_token_metrics | identifier_name |
__init__.py | 2*sigma**2) );
return g / g.sum()
def make_heatmap(points, screen_size, point_size, sigma_denom=5.0):
point_radius = point_size / 2
screen = np.zeros((screen_size[0] + point_size, screen_size[1] + point_size))
kernel = gauss_kern((point_size, point_size), sigma=(point_size / sigma_denom))
for pt in ... | """Splits a sequence into n, rest parts."""
it = iter(seq)
for _ in range(n - 1): | random_line_split | |
__init__.py | def norm_by_rows(matrix):
"""Normalizes a numpy array by rows (axis 1).
Parameters
----------
matrix : array_like
A numpy array with at least two axes.
Returns
-------
a : array_like
A row-normalized numpy array
"""
row_sums = matrix.sum(axis=1)
return matri... | start, end = 0, window_size_ms
return_series = False
if not isinstance(fun, dict):
fun = { "value" : fun }
return_series = True
values = { k : [] for k, v in fun.iteritems() }
times = []
while start < fixations.end_ms.max():
times.append(start + (window_size_ms / 2))
... | identifier_body | |
scheduler.rs |
#[export_name = "__lumen_builtin_yield"]
pub unsafe extern "C" fn process_yield() -> bool {
let s = <Scheduler as rt_core::Scheduler>::current();
// NOTE: We always set root=false here because the root
// process never invokes this function
s.process_yield(/* root= */ false)
}
#[naked]
#[inline(never... | {
unimplemented!()
} | identifier_body | |
scheduler.rs | -> bool {
use liblumen_alloc::erts::term::prelude::*;
if scheduler.current.pid() != scheduler.root.pid() {
scheduler
.current
.exit(atom!("normal"), anyhow!("Out of code").into());
// NOTE: We always set root=false here, even though this can
// be called from the... | (&self, priority: Priority) -> usize {
self.run_queues.read().run_queue_len(priority)
}
/// Returns true if the given process is in the current scheduler's run queue
#[cfg(test)]
pub fn is_run_queued(&self, value: &Arc<Process>) -> bool {
self.run_queues.read().contains(value)
}
... | run_queue_len | identifier_name |
scheduler.rs |
Err(_) => {
panic!("invalid term kind: {}", kind);
}
}
ptr::null_mut()
}
/// Called when the current process has finished executing, and has
/// returned all the way to its entry function. This marks the process
/// as exiting (if it wasn't already), and then yields to the schedul... | {
unimplemented!("unhandled use of malloc for {:?}", tk);
} | conditional_block | |
scheduler.rs | ) -> bool {
use liblumen_alloc::erts::term::prelude::*;
if scheduler.current.pid() != scheduler.root.pid() {
scheduler
.current
.exit(atom!("normal"), anyhow!("Out of code").into());
// NOTE: We always set root=false here, even though this can
// be called from th... | pub enum Run {
/// Run the process now
Now(Arc<Process>),
/// There was a process in the queue, but it needs to be delayed because it is `Priority::Low`
/// and hadn't been delayed enough yet. Ask the `RunQueue` again for another process.
/// -- https://github.com/erlang/otp/blob/fe2b1323a3866ed0a9... | }
}
/// What to run | random_line_split |
client.go | 0",
"http_code": "202",
"phone_numbers": [
"developer@email.com",
"901-111-2222"
],
"success": false
}
// Submit a valid email address or phone number from "phone_numbers" list
res, err := user.Select2FA("developer@email.com")
// MFA sent to developer@email.com
res, err := user.VerifyPIN("123456"... |
return c.do("GET", url, "", nil)
}
/********** OTHER **********/
// GetCryptoMarketData returns market data for cryptocurrencies
func (c *Client) GetCryptoMarketData() (map[string]interface{}, error) {
log.info("========== GET CRYPTO MARKET DATA ==========")
url := buildURL(path["nodes"], "crypto-market-watch")
... | random_line_split | |
client.go | 0",
"http_code": "202",
"phone_numbers": [
"developer@email.com",
"901-111-2222"
],
"success": false
}
// Submit a valid email address or phone number from "phone_numbers" list
res, err := user.Select2FA("developer@email.com")
// MFA sent to developer@email.com
res, err := user.VerifyPIN("123456"... |
qp := []string{"issue_public_key=YES&scope=" + defaultScope}
if len(scope) > 1 {
userId := scope[1]
qp[0] += "&user_id=" + userId
}
return c.do("GET", url, "", qp)
}
/********** NODE **********/
// GetNodes returns all of the nodes
func (c *Client) GetNodes(queryParams ...string) (map[string]interface{}, ... | {
defaultScope = scope[0]
} | conditional_block |
client.go | 0",
"http_code": "202",
"phone_numbers": [
"developer@email.com",
"901-111-2222"
],
"success": false
}
// Submit a valid email address or phone number from "phone_numbers" list
res, err := user.Select2FA("developer@email.com")
// MFA sent to developer@email.com
res, err := user.VerifyPIN("123456"... | (subscriptionID string, data string) (map[string]interface{}, error) {
log.info("========== UPDATE SUBSCRIPTION ==========")
url := buildURL(path["subscriptions"], subscriptionID)
return c.do("PATCH", url, data, nil)
}
// GetWebhookLogs returns all of the webhooks sent to a specific client
func (c *Client) GetWebh... | UpdateSubscription | identifier_name |
client.go | 0",
"http_code": "202",
"phone_numbers": [
"developer@email.com",
"901-111-2222"
],
"success": false
}
// Submit a valid email address or phone number from "phone_numbers" list
res, err := user.Select2FA("developer@email.com")
// MFA sent to developer@email.com
res, err := user.VerifyPIN("123456"... |
/********** SUBSCRIPTION **********/
// GetSubscriptions returns all of the nodes associated with a user
func (c *Client) GetSubscriptions(queryParams ...string) (map[string]interface{}, error) {
log.info("========== GET SUBSCRIPTIONS ==========")
url := buildURL(path["subscriptions"])
return c.do("GET", url, ""... | {
log.info("========== VERIFY ROUTING NUMBER ==========")
url := buildURL("routing-number-verification")
return c.do("POST", url, data, nil)
} | identifier_body |
controller.go |
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
distributed under the License is d... | /*
Copyright © 2020 Dell Inc. or its subsidiaries. All Rights Reserved. | random_line_split | |
controller.go |
func (nc *nodesMapping) getCSIBMNodeName(k8sNodeName string) (string, bool) {
res, ok := nc.k8sToBMNode[k8sNodeName]
return res, ok
}
func (nc *nodesMapping) put(k8sNodeName, bmNodeName string) {
nc.k8sToBMNode[k8sNodeName] = bmNodeName
nc.bmToK8sNode[bmNodeName] = k8sNodeName
}
// NewController returns instance... |
res, ok := nc.bmToK8sNode[bmNodeName]
return res, ok
}
| identifier_body | |
controller.go | .log.WithFields(logrus.Fields{
"method": "reconcileForK8sNode",
"name": k8sNode.Name,
})
if len(k8sNode.Status.Addresses) == 0 {
err := errors.New("addresses are missing for current k8s node instance")
ll.Error(err)
return ctrl.Result{Requeue: false}, err
}
var (
bmNode = &nodecrd.Node{}
... |
k8sNode.ObjectMeta.Labels = make(map[string]string, 1)
}
| conditional_block | |
controller.go | ("Unable to read k8s node %s: %v", k8sNodeName, err)
return ctrl.Result{Requeue: true}, err
}
k8sNodes = []coreV1.Node{*k8sNode}
}
if !k8sNodeFromCache {
k8sNodeCRs := new(coreV1.NodeList)
if err := bmc.k8sClient.ReadList(context.Background(), k8sNodeCRs); err != nil {
ll.Errorf("Unable to read k8s nod... | onstructNodeID( | identifier_name | |
svh_visitor.rs |
// hash leads to unstable SVH, because ident.name is just an index
// into intern table (i.e. essentially a random address), not
// computed from the name content.
//
// With the below enums, the SVH computation is not sensitive to
// artifacts of how rustc was invoked nor of how the source code
// was laid out. (Or ... | SawGenerics,
SawFn,
SawTraitItem,
SawImplItem,
SawStructField,
SawVariant,
SawPath,
SawBlock,
SawPat,
SawLocal,
SawArm,
SawExpr(SawExprComponent<'a>),
SawStmt(SawStmtComponent),
}
/// SawExprComponent carries all of the information that we want
/// to include in the ... | SawTy, | random_line_split |
svh_visitor.rs | Option<token::InternedString>),
SawExprBox,
SawExprVec,
SawExprCall,
SawExprMethodCall,
SawExprTup,
SawExprBinary(hir::BinOp_),
SawExprUnary(hir::UnOp),
SawExprLit(ast::LitKind),
SawExprCast,
SawExprType,
SawExprIf,
SawExprWhile,
SawExprMatch,
SawExprClosure,
... | {
debug!("visit_struct_field: st={:?}", self.st);
SawStructField.hash(self.st); visit::walk_struct_field(self, s)
} | identifier_body | |
svh_visitor.rs |
// hash leads to unstable SVH, because ident.name is just an index
// into intern table (i.e. essentially a random address), not
// computed from the name content.
//
// With the below enums, the SVH computation is not sensitive to
// artifacts of how rustc was invoked nor of how the source code
// was laid out. (Or ... | (&mut self, v: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
debug!("visit_variant: st={:?}", self.st);
SawVariant.hash(self.st);
// walk_variant does not call walk_generics, so do it here.
visit::walk_generics(self, g);
visit::walk_variant(self, v, g, item_id)
}
... | visit_variant | identifier_name |
config.rs | .config.toml";
/// ENV_PREFIX should be used along side the config field name to set a config field using
/// environment variables
/// For example, `IROH_PATH=/path/to/config` would set the value of the `Config.path` field
pub const ENV_PREFIX: &str = "IROH";
/// Paths to files or directory within the [`iroh_data_roo... | () -> Self {
Self {
// TODO(ramfox): this should probably just be a derp map
derp_regions: [default_na_derp_region(), default_eu_derp_region()].into(),
}
}
}
impl Config {
/// Make a config using a default, files, environment variables, and commandline flags.
///
... | default | identifier_name |
config.rs | .config.toml";
/// ENV_PREFIX should be used along side the config field name to set a config field using
/// environment variables
/// For example, `IROH_PATH=/path/to/config` would set the value of the `Config.path` field
pub const ENV_PREFIX: &str = "IROH";
/// Paths to files or directory within the [`iroh_data_roo... |
/// Get the path for this [`IrohPath`] by joining the name to a root directory.
pub fn with_root(self, root: impl AsRef<Path>) -> PathBuf {
let path = root.as_ref().join(self);
path
}
}
/// The configuration for the iroh cli.
#[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)]
... | {
let mut root = iroh_data_root()?;
if !root.is_absolute() {
root = std::env::current_dir()?.join(root);
}
Ok(self.with_root(root))
} | identifier_body |
config.rs | h.config.toml";
/// ENV_PREFIX should be used along side the config field name to set a config field using
/// environment variables
/// For example, `IROH_PATH=/path/to/config` would set the value of the `Config.path` field
pub const ENV_PREFIX: &str = "IROH";
/// Paths to files or directory within the [`iroh_data_ro... | }
}
impl FromStr for IrohPaths {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s {
"keypair" => Self::Keypair,
"blobs.v0" => Self::BaoFlatStoreComplete,
"blobs-partial.v0" => Self::BaoFlatStorePartial,
_ => bail!("unknown fi... | IrohPaths::Keypair => "keypair",
IrohPaths::BaoFlatStoreComplete => "blobs.v0",
IrohPaths::BaoFlatStorePartial => "blobs-partial.v0",
} | random_line_split |
UAGS.py | HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
... | olors:
| identifier_name | |
UAGS.py | else:
NewScrapes = "y"
print("All found game entries will be scraped.")
print()
## all a filter to be used
ScanFilter = input("Limit scanned files to a specific pattern match? " + bcolors.OKBLUE + "(Enter pattern or leave blank) " + bcolors.ENDC)
print()
## check for overwrite of existing images
New... | ## check XML validity
if XML.find("?xml version=")<0 or XML.find("<gameList>")<0 or XML.find("</gameList>")<0:
print (bcolors.FAIL + ">> XML File "+ bcolors.BOLD + XML_File + bcolors.ENDC + bcolors.FAIL + " is malformed." + bcolors.ENDC )
KillXML = input ("Delete file prior to restart? (y/n) "+ bcolors.ENDC )... | text_file = open(XML_File, "r")
XML = text_file.read()
text_file.close()
| random_line_split |
UAGS.py | Ne |
print()
## all a filter to be used
ScanFilter = input("Limit scanned files to a specific pattern match? " + bcolors.OKBLUE + "(Enter pattern or leave blank) " + bcolors.ENDC)
print()
## check for overwrite of existing images
NewImages = input("Overwrite existing images, such as in " + bcolors.BOLD + "boxarts... | wScrapes = "y"
print("All found game entries will be scraped.")
| conditional_block |
UAGS.py | ## main section starting here...
print()
print(bcolors.BOLD + bcolors.OKBLUE + "HoraceAndTheSpider" + bcolors.ENDC + "'s " + "openretro.org " + bcolors.BOLD + "UAE4Arm Amiga Game Scraper" + bcolors.ENDC + " | " + "" + bcolors.FAIL + "www.ultimateamiga.co.uk" + bcolors.ENDC)
print()
## check for overwrite of existing ... | ADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
... | identifier_body | |
databaseDemo.go | (dbfile string) *sql.DB {
database, err := sql.Open("sqlite3", dbfile)
if err != nil {
log.Fatal(err)
}
return database
}
func getMinGPA() float64 {
fmt.Print("What is the minimum GPA for good standing:")
reader := bufio.NewReader(os.Stdin)
value, err := reader.ReadString('\n')
if err != nil {
log.Fatal("H... | OpenDataBase | identifier_name | |
databaseDemo.go | )
value, err := reader.ReadString('\n')
if err != nil {
log.Fatal("How did we fail to read from standard in!?!?")
}
value = strings.TrimSpace(value)
min_gpa, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Fatal("oooops you typed that wrong", err)
}
return min_gpa
}
func findProbationStudents(data... | }
}
func registerForClasses(database *sql.DB) {
insertStatement := "INSERT INTO CLASS_LIST (banner_id, course_prefix, course_number, registration_date)" +
"VALUES(?, 'Comp', 510, DATE('now'))"
preppedStatement, err := database.Prepare(insertStatement)
if err != nil {
log.Fatal("Hey prof you goofed it trying t... | log.Fatal(err)
}
fmt.Printf("%s %s is on probation with a GPA of %f\n", firstName, lastName, gpa) | random_line_split |
databaseDemo.go | value, err := reader.ReadString('\n')
if err != nil {
log.Fatal("How did we fail to read from standard in!?!?")
}
value = strings.TrimSpace(value)
min_gpa, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Fatal("oooops you typed that wrong", err)
}
return min_gpa
}
func findProbationStudents(databa... | if err != nil {
log.Fatal(err)
}
for course, desc := range sampleData {
prefix := course[0:4]
numVal := course[4:7]
courseNum, err := strconv.Atoi(numVal)
if err != nil {
log.Fatal("ooops we must have mistyped", err)
}
preppedStatement.Exec(prefix, courseNum, desc)
}
}
func addSampleStudents(d
at... | {
var sampleData = map[string]string{
"comp502": "Research\n(3 credits)\nPrerequisite: Consent of the department; formal application required\nOriginal research is undertaken by the graduate student in their field. This course culminates in a capstone project. For details, consult the paragraph titled “Directed or I... | identifier_body |
databaseDemo.go | )
value, err := reader.ReadString('\n')
if err != nil {
log.Fatal("How did we fail to read from standard in!?!?")
}
value = strings.TrimSpace(value)
min_gpa, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Fatal("oooops you typed that wrong", err)
}
return min_gpa
}
func findProbationStudents(data... | s(database *sql.DB) {
sampleNames := map[string]string{"John": "Santore", "Enping": "Li", "Michael": "Black",
"Seikyung": "Jung", "Haleh": "Khojasteh", "Abdul": "Sattar", "Paul": "Kim", "Yiheng": "Liang"}
statement := "INSERT INTO STUDENTS (banner_id, first | numVal := course[4:7]
courseNum, err := strconv.Atoi(numVal)
if err != nil {
log.Fatal("ooops we must have mistyped", err)
}
preppedStatement.Exec(prefix, courseNum, desc)
}
}
func addSampleStudent | conditional_block |
utils.rs | the given channel.
// FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable
// and because of that we wouldn't get nice optimizations
fn foreach_sample_zipped<U>(
&self,
channel: usize,
iter: impl Iterator<Item = U>,
func: impl FnMut(&'a S, U),
);
fn... | >(
&self,
channel: usize,
iter: impl Iterator<Item = U>,
mut func: impl FnMut(&'a S, U),
) {
assert!(channel < self.channels);
for (v, u) in Iterator::zip(self.data.chunks_exact(self.channels), iter) {
func(&v[channel], u)
}
}
#[inline]
... | reach_sample_zipped<U | identifier_name |
utils.rs | the given channel.
// FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable
// and because of that we wouldn't get nice optimizations
fn foreach_sample_zipped<U>(
&self,
channel: usize,
iter: impl Iterator<Item = U>,
func: impl FnMut(&'a S, U),
);
fn... | const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
impl Sample for i32 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
/// An extension-trait to... | }
}
impl Sample for i16 { | random_line_split |
utils.rs | the given channel.
// FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable
// and because of that we wouldn't get nice optimizations
fn foreach_sample_zipped<U>(
&self,
channel: usize,
iter: impl Iterator<Item = U>,
func: impl FnMut(&'a S, U),
);
fn... |
impl Sample for i16 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
impl Sample for i32 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
//... | self
}
} | identifier_body |
narwhal.js | $('head').append($script);
})
.then(() => (new Promise((resolve, reject) => {
setTimeout(resolve, waitFor)
})))
)
$(document).ready(() => {
//
// Configurations, selectors, ...
//
const selector = {
ed... | const $createConfiguration = ($configuration) => $configuration
? $('<h5></h5>')
.append($configuration.clone().find('td:nth-child(2)'))
.css({ fontSize: 11 }) | random_line_split | |
narwhal.js | Promise((resolve, reject) => {
const $script = $('<script type="text/javascript">')
.attr('src', url)
.ready(resolve)
$('head').append($script);
})
.then(() => (new Promise((resolve, reject) => {
setTimeout(resolve, waitFor)
... |
})
.then(() => loadScriptAndWait('https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/mode/jinja2/jinja2.min.js', 300))
.then(() => loadScriptAndWait('https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/mode/yaml/yaml.min.js', 300))
.then(() => ... | {
throw Error('CodeMirror was not loaded correctly ...')
} | conditional_block |
mul_fixed.rs | `.
assert_eq!(
config.add_config.x_p, config.add_incomplete_config.x_p,
"add and add_incomplete are used internally in mul_fixed."
);
assert_eq!(
config.add_config.y_p, config.add_incomplete_config.y_p,
"add and add_incomplete are used internally i... | config.running_sum_coords_gate(meta);
config
}
/// Check that each window in the running sum decomposition uses the correct y_p
/// and interpolated x_p.
///
/// This gate is used both in the mul_fixed::base_field_elem and mul_fixed::short
/// helpers, which decompose the scala... | }
| random_line_split |
mul_fixed.rs | _toggle)?;
// Initialize accumulator
let acc = self.initialize_accumulator::<F, NUM_WINDOWS>(region, offset, base, scalar)?;
// Process all windows excluding least and most significant windows
let acc = self.add_incomplete::<F, NUM_WINDOWS>(region, offset, acc, base, scalar)?;
... | Self::FullWidth(scalar_fixed.clone())
}
}
im | identifier_body | |
mul_fixed.rs | : &mut Region<'_, pallas::Base>,
offset: usize,
base: &F,
coords_check_toggle: Selector,
) -> Result<(), Error> {
let mut constants = None;
let build_constants = || {
let lagrange_coeffs = base.lagrange_coeffs();
assert_eq!(lagrange_coeffs.len(), NUM_W... | s_field(&self | identifier_name | |
RhinoResponse.ts | {
private _headersSent: boolean = false;
private STATUS: number = 200;
private COOKIES: HTTPServer.Response = {};
private readonly RESPONSE_HEADERS = new Headers();
constructor(private readonly HTTP_REQUEST: HTTPServer.ServerRequest) {}
/**
* Appends a value to an already existing HTTP ... | RhinoResponse | identifier_name | |
RhinoResponse.ts | ends a value to an already existing HTTP header field, or
* adds the field if it has not been created.
* @param field The HTTP header field name
* @param value The value for the header field.
* @note Should follow the standard from https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
... | *
* Clears a cookie from the response by setting
* its expiration date to a date before now.
* @param name The name of the cookie
*/
public clearCookie(name: string) {
// Sets the cookie to be appended to the response
Cookies.delCookie(this.COOKIES, name);
}
/**
* S... | const _filename = filename ? `filename=${filename};` : "";
this.setHeader(HeaderField.ContentDisposition, `attachment; ${_filename}`);
const ext = Path.extname(filename || "");
this.contentType(ext);
return this;
}
/* | identifier_body |
RhinoResponse.ts | val) => this.RESPONSE_HEADERS.append(field, val));
} else {
// Otherwise, just adds the value to the header
this.RESPONSE_HEADERS.append(field, value);
}
return this;
}
/**
* Sets the HTTP response Content-Disposition header field to “attachment”.
* If... | // Otherwise, just adds the value to the header
this.RESPONSE_HEADERS.set(field, value);
}
| conditional_block | |
RhinoResponse.ts | // Derives the optional values of a cookie
export type CookieOptions = Omit<Omit<Cookies.Cookie, "name">, "value">;
export class RhinoResponse {
private _headersSent: boolean = false;
private STATUS: number = 200;
private COOKIES: HTTPServer.Response = {};
private readonly RESPONSE_HEADERS = new Heade... | random_line_split | ||
node.go | (row, "|") + "]"
}
return fmt.Sprintf("%s [page=%d, all<=%s]", c.node.typ.String(), c.pageNumber, key)
}
type Record struct {
rowid int
columns []Column
}
func (r Record) String() string {
var row []string
for _, c := range r.columns {
row = append(row, c.String())
}
return fmt.Sprintf("rowid=%+v column... | (typ int) int {
switch typ {
case 0, 8, 9:
return 0
case 1:
return 1
case 2:
return 2
case 3:
return 3
case 4:
return 4
case 5:
return 6
case 6, 7:
return 8
case 10, 11:
// https://github.com/sqlite/sqlite/blob/96e3c39bd58ede59150c00e4f8609cbac674ffae/tool/offsets.c#L216
// return 0
panic(f... | columnContentSize | identifier_name |
node.go | (row, "|") + "]"
}
return fmt.Sprintf("%s [page=%d, all<=%s]", c.node.typ.String(), c.pageNumber, key)
}
type Record struct {
rowid int
columns []Column
}
func (r Record) String() string {
var row []string
for _, c := range r.columns {
row = append(row, c.String())
}
return fmt.Sprintf("rowid=%+v column... | u := uint64(b[5]) | uint64(b[4])<<8 | uint64(b[3])<<16 | uint64(b[2])<<24 | uint64(b[1])<<32 | uint64(b[0])<<40
return int64(u)
case 6:
return int64(binary.BigEndian.Uint64(c.content))
case 7:
b := binary.BigEndian.Uint64(c.content)
return math.Float64frombits(b)
case 8:
return int64(0)
case 9:
return... | {
// TODO: validate this works with negative integers (2's complement)
switch c.typ {
case 0:
return nil
case 1:
return int64(c.content[0])
case 2:
return int64(binary.BigEndian.Uint16(c.content))
case 3:
// stdlib binary does not have a 24-bit option
b := c.content
u := uint32(b[2]) | uint32(b[1])<<... | identifier_body |
node.go | (row, "|") + "]"
}
return fmt.Sprintf("%s [page=%d, all<=%s]", c.node.typ.String(), c.pageNumber, key)
}
type Record struct {
rowid int
columns []Column
}
func (r Record) String() string {
var row []string
for _, c := range r.columns {
row = append(row, c.String())
}
return fmt.Sprintf("rowid=%+v column... | func (c Column) AsInt() (int, bool) {
// [1, 6] are the various int64 types
if c.typ >= 1 && c.typ <= 6 {
i64 := c.Value().(int64)
return int(i64), true
}
return 0, false
}
func (c Column) Value() driver.Value {
// TODO: validate this works with negative integers (2's complement)
switch c.typ {
case 0:
... | random_line_split | |
node.go | (row, "|") + "]"
}
return fmt.Sprintf("%s [page=%d, all<=%s]", c.node.typ.String(), c.pageNumber, key)
}
type Record struct {
rowid int
columns []Column
}
func (r Record) String() string {
var row []string
for _, c := range r.columns {
row = append(row, c.String())
}
return fmt.Sprintf("rowid=%+v column... |
if typ != TreeTypeTableLeaf {
// Extract the rowid from the last column:
idx := len(columns) - 1
var ok bool
rowid, ok = | {
return nil, err
} | conditional_block |
terminal.rs | fn name(&self) -> &str;
/// Acquires a lock on terminal read operations and returns a value holding
/// that lock and granting access to such operations.
///
/// The lock must not be released until the returned value is dropped.
fn lock_read<'a>(&'a self) -> Box<dyn TerminalReader<Self> + 'a>;
... | move_to_first_column | identifier_name | |
terminal.rs | .
type PrepareState;
/*
/// Holds an exclusive read lock and provides read operations
type Reader: TerminalReader;
/// Holds an exclusive write lock and provides write operations
type Writer: TerminalWriter;
*/
/// Returns the name of the terminal.
fn name(&self) -> &str;
/// A... | {
self.move_down(n)
} | identifier_body | |
terminal.rs | (usize),
/// The terminal window was resized
Resize(Size),
/// A signal was received while waiting for input
Signal(Signal),
}
/// Defines a low-level interface to the terminal
pub trait Terminal: Sized + Send + Sync {
// TODO: When generic associated types are implemented (and stabilized),
// ... |
/// Flushes any currently buffered output data.
///
/// `TerminalWriter` instances may not buffer data on all systems.
///
/// Data must be flushed when the `TerminalWriter` instance is dropped.
fn flush(&mut self) -> io::Result<()>;
}
impl DefaultTerminal {
/// Opens access to the termina... | ///
/// The terminal interface shall not automatically move the cursor to the next
/// line when `write` causes a character to be written to the final column.
fn write(&mut self, s: &str) -> io::Result<()>; | random_line_split |
passThrough.go | doing the I/O
// operation and performs this one on behalf of it.
//
// Currently, this handler serves non-emulated resources within the /proc/sys
// subtree, but there's nothing specific to this path in this handler's
// implementation (see that the Path attribute is set to "*"), so this one could
// be utilized for ... |
cntr.SetData(path, resource, data)
}
cntr.Unlock()
} else {
data, err = h.fetchFile(n, process)
if err != nil {
return 0, err
}
}
data += "\n"
return copyResultBuffer(req.Data, []byte(data))
}
func (h *PassThrough) Write(
n domain.IOnodeIface,
req *domain.HandlerRequest) (int, error) {
var ... | {
cntr.Unlock()
return 0, err
} | conditional_block |
passThrough.go | doing the I/O
// operation and performs this one on behalf of it.
//
// Currently, this handler serves non-emulated resources within the /proc/sys
// subtree, but there's nothing specific to this path in this handler's
// implementation (see that the Path attribute is set to "*"), so this one could
// be utilized for ... | return 0, io.EOF
}
var (
data string
ok bool
err error
)
path := n.Path()
prs := h.Service.ProcessService()
process := prs.ProcessCreate(req.Pid, req.Uid, req.Gid)
cntr := req.Container
//
// Caching here improves performance by avoiding dispatching the nsenter agent. But
// note that caching i... |
if req.Offset > 0 { | random_line_split |
passThrough.go | doing the I/O
// operation and performs this one on behalf of it.
//
// Currently, this handler serves non-emulated resources within the /proc/sys
// subtree, but there's nothing specific to this path in this handler's
// implementation (see that the Path attribute is set to "*"), so this one could
// be utilized for ... | (
n domain.IOnodeIface,
req *domain.HandlerRequest) error {
logrus.Debugf("Executing Open() for req-id: %#x, handler: %s, resource: %s",
req.ID, h.Name, n.Name())
// Create nsenterEvent to initiate interaction with container namespaces.
nss := h.Service.NSenterService()
event := nss.NewEvent(
req.Pid,
&do... | Open | identifier_name |
passThrough.go | domain.ErrorResponse {
return nil, responseMsg.Payload.(error)
}
info := responseMsg.Payload.(domain.FileInfo)
return info, nil
}
func (h *PassThrough) Open(
n domain.IOnodeIface,
req *domain.HandlerRequest) error {
logrus.Debugf("Executing Open() for req-id: %#x, handler: %s, resource: %s",
req.ID, h.Na... | {
return h.Service
} | identifier_body | |
utils.go | "
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
)
const (
// DefaultQuerySnapshotLimit constant is already present in pkg/csi/service/common/constants.go
// However, using that constant creates an import cycle.
// TODO: Refactor to move all the constants into a top level directory.
DefaultQuerySnapsh... | if err != nil {
return nil, logger.LogNewErrorCodef(log, codes.Internal,
"queryVolume failed for queryFilter: %+v. Err=%+v", queryFilter, err.Error())
}
}
return queryResult, nil
}
// QuerySnapshotsUtil helps invoke CNS QuerySnapshot API. The method takes in a snapshotQueryFilter that represents
// the c... | {
log := logger.GetLogger(ctx)
var queryAsyncNotSupported bool
var queryResult *cnstypes.CnsQueryResult
var err error
if useQueryVolumeAsync {
// AsyncQueryVolume feature switch is enabled.
queryResult, err = m.QueryVolumeAsync(ctx, queryFilter, querySelection)
if err != nil {
if err.Error() == cnsvsphere... | identifier_body |
utils.go | "
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
)
const (
// DefaultQuerySnapshotLimit constant is already present in pkg/csi/service/common/constants.go
// However, using that constant creates an import cycle.
// TODO: Refactor to move all the constants into a top level directory.
DefaultQuerySnapsh... | (ctx context.Context, m cnsvolume.Manager, snapshotQueryFilter cnstypes.CnsSnapshotQueryFilter,
maxEntries int64) ([]cnstypes.CnsSnapshotQueryResultEntry, string, error) {
log := logger.GetLogger(ctx)
var allQuerySnapshotResults []cnstypes.CnsSnapshotQueryResultEntry
var snapshotQuerySpec cnstypes.CnsSnapshotQueryS... | QuerySnapshotsUtil | identifier_name |
utils.go | )
if err != nil {
return nil, logger.LogNewErrorCodef(log, codes.Internal,
"queryVolume failed for queryFilter: %+v. Err=%+v", queryFilter, err.Error())
}
}
return queryResult, nil
}
// QuerySnapshotsUtil helps invoke CNS QuerySnapshot API. The method takes in a snapshotQueryFilter that represents
// the ... | if err != nil {
continue
}
}
log.Infof("Disconnecting vCenter client for host %s", vc.Config.Host) | random_line_split | |
utils.go | "
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
)
const (
// DefaultQuerySnapshotLimit constant is already present in pkg/csi/service/common/constants.go
// However, using that constant creates an import cycle.
// TODO: Refactor to move all the constants into a top level directory.
DefaultQuerySnapsh... | else {
batchSize = snapshotQueryFilter.Cursor.Limit
}
iteration := int64(1)
for {
if iteration > maxIteration {
// Exceeds the max number of results that can be handled by callers.
nextToken := strconv.FormatInt(snapshotQueryFilter.Cursor.Offset, 10)
log.Infof("the number of results: %d approached max-... | {
// Setting the default limit(128) explicitly.
snapshotQueryFilter = cnstypes.CnsSnapshotQueryFilter{
Cursor: &cnstypes.CnsCursor{
Offset: 0,
Limit: DefaultQuerySnapshotLimit,
},
}
batchSize = DefaultQuerySnapshotLimit
} | conditional_block |
block.go | Flag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
return cmd
}
func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
return nil, err
}
// header -> BlockchainInfo
// header, tx -> Block
// results -> BlockRe... | func formatTxResult(cdc *codec.Codec, res *ctypes.ResultTx, resBlock *ctypes.ResultBlock) (sdk.TxResponse, error) {
tx, err := parseTx(cdc, res.Tx)
if err != nil {
return sdk.TxResponse{}, err
}
return sdk.NewResponseResultTx(res, tx, resBlock.Block.Time.Format(time.RFC3339)), nil
}
//
func GetTxFn(cdc *codec.C... |
return tx, nil
}
| random_line_split |
block.go | (client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
return cmd
}
func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
return nil, err
}
// header -> BlockchainInfo
// header, tx -> Block
// results -> BlockResult... |
// CMD
func printBlock(cmd *cobra.Command, args []string) error {
var height *int64
// optional height
if len(args) > 0 {
h, err := strconv.Atoi(args[0])
if err != nil {
return err
}
if h > 0 {
tmp := int64(h)
height = &tmp
}
}
output, err := getBlock(context.NewCLIContext(), height)
if err... | {
node, err := cliCtx.GetNode()
if err != nil {
return -1, err
}
status, err := node.Status()
if err != nil {
return -1, err
}
height := status.SyncInfo.LatestBlockHeight
return height, nil
} | identifier_body |
block.go | Flag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
return cmd
}
func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
return nil, err
}
// header -> BlockchainInfo
// header, tx -> Block
// results -> BlockRe... | (cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
height, err := strconv.ParseInt(vars["height"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest,
"ERROR: Couldn't parse block height. Assumed format is '/block/... | BlockRequestHandlerFn | identifier_name |
block.go | (client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
return cmd
}
func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
return nil, err
}
// header -> BlockchainInfo
// header, tx -> Block
// results -> BlockResult... |
default:
fmt.Printf("unknown type: %+v\n", currTx)
}
}
sdkRest.PostProcessResponse(w, cdc, &blockInfo, cliCtx.Indent)
}
}
func parseTx(cdc *codec.Codec, txBytes []byte) (sdk.Tx, error) {
var tx auth.StdTx
err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx)
if err != nil {
return nil, err
}
... | {
//fmt.Printf("msg|route=%s|type=%s\n", msg.Route(), msg.Type())
switch msg := msg.(type) {
case htdfservice.MsgSend:
displayTx.From = msg.From
displayTx.To = msg.To
displayTx.Hash = hex.EncodeToString(tx.Hash())
displayTx.Amount = unit_convert.DefaultCoinsToBigCoins(msg.Amount)... | conditional_block |
benchmarking.py | _nets('trained_networks/final*')
full_net = load_nets('trained_networks/full*')
with open('trained_networks/decision_tree.pkl', 'rb') as pkl:
dtr_full = pickle.load(pkl)[0]
with open('ligpy_benchmarking_files/ligpy_args.txt', 'rb') as args:
ligpy_args = args.readlines()
ligpy_args = ligpy_args[1:]
# reset ... | (file_completereactionlist, file_completerateconstantlist,
file_compositionlist) = utils.set_paths()
working_directory = 'results_dir'
if not os.path.exists(working_directory):
os.makedirs(working_directory)
# pickle the arguments used for this program to reference during analysis
prog... | """
Create the proper environment to run predict_ligpy() and set up the
kinetic model.
Parameters
----------
standard arguments passed to `ligpy.py`
Returns
-------
standard arguments for `ddasac.run_ddasac()`
"""
call('cp ligpy_benchmarking_files/sa_compositionlist.dat '
... | identifier_body |
benchmarking.py | ets('trained_networks/final*')
full_net = load_nets('trained_networks/full*')
with open('trained_networks/decision_tree.pkl', 'rb') as pkl:
dtr_full = pickle.load(pkl)[0]
with open('ligpy_benchmarking_files/ligpy_args.txt', 'rb') as args:
ligpy_args = args.readlines()
ligpy_args = ligpy_args[1:]
# reset th... |
return y_scaler.inverse_transform(predicted)
def predict_decision_tree(input_data=rand_input, tree=dtr_full):
"""
Predict the output measures using a decision tree trained on all 30
output measures at once.
Parameters
----------
input_data : numpy.ndarray, optional
an... | predicted[:, i] = nets[i].predict(input_data).ravel() | conditional_block |
benchmarking.py | ets('trained_networks/final*')
full_net = load_nets('trained_networks/full*')
with open('trained_networks/decision_tree.pkl', 'rb') as pkl:
dtr_full = pickle.load(pkl)[0]
with open('ligpy_benchmarking_files/ligpy_args.txt', 'rb') as args:
ligpy_args = args.readlines()
ligpy_args = ligpy_args[1:]
# reset th... | ():
"""
Clean up after running predict_ligpy().
Parameters
----------
None
Returns
-------
None
"""
call('rm -rf bsub.c bsub.o ddat.in fort.11 f.out greg10.in jacobian.c '
'jacobian.o model.c model.o net_rates.def parest rates.def '
'results_dir/', shell=True)... | teardown_predict_ligpy | identifier_name |
benchmarking.py | _nets('trained_networks/final*')
full_net = load_nets('trained_networks/full*')
with open('trained_networks/decision_tree.pkl', 'rb') as pkl:
dtr_full = pickle.load(pkl)[0]
with open('ligpy_benchmarking_files/ligpy_args.txt', 'rb') as args:
ligpy_args = args.readlines()
ligpy_args = ligpy_args[1:]
# reset ... | relative_tolerance = float(1e-8)
# These are the files and paths that will be referenced in this program:
(file_completereactionlist, file_completerateconstantlist,
file_compositionlist) = utils.set_paths()
working_directory = 'results_dir'
if not os.path.exists(working_directory):
os.... | '../../../ligpy/ligpy/data/compositionlist.dat;', shell=True
)
absolute_tolerance = float(1e-10) | random_line_split |
main.py | _at.y
# np.arctan(-1) / np.pi
return np.arctan(delta_y / delta_x)
def __repr__(self):
return f'Track: {self.begins_at} -> {self.ends_at}'
def geom(self):
geom = rendering.Line(self.begins_at.arr(), self.ends_at.arr())
geom.set_color(0, 0, 0)
return geom
de... | (self) -> Node:
delta = self.on_track.get_delta()
progress = self.dist_on_track / self.on_track.track_length
x = self.on_track.begins_at.x + progress * delta.x
y = self.on_track.begins_at.y + progress * delta.y
return Node(x=x, y=y)
def curr_station(self):
stations... | pos | identifier_name |
main.py | def reset(self):
track = list(self.origin.tracks())[0]
if track.ends_at == self.origin:
self.train = Train(track=track, dist=track.track_length, direction=1, name='bob')
else:
self.train = Train(track=track, dist=0.0, direction=1, name='bob')
self.state = {... | print(f" game: {game}")
curr_rewards = [] # all raw rewards from the current episode
curr_gradients = [] # all gradients from the current episode
world.reset()
# world.render()
# time.sleep(1 / RENDER_FPS)
for step in range(N_MAX_STEPS):
... | conditional_block | |
main.py | return Node(x=delta_x, y=delta_y)
def get_angle(self):
delta_x = self.ends_at.x - self.begins_at.x
delta_y = self.ends_at.y - self.begins_at.y
# np.arctan(-1) / np.pi
return np.arctan(delta_y / delta_x)
def __repr__(self):
return f'Track: {self.begins_at} -> {s... | delta_y = self.ends_at.y - self.begins_at.y
| random_line_split | |
main.py |
# Called with either one element to determine next action, or a batch
# during optimization. Returns tensor([[left0exp,right0exp]...]).
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
return s... | super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)
self.bn1 = nn.BatchNorm2d(16)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)
self.bn2 = nn.BatchNorm2d(32)
self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
self.bn3 = nn.Bat... | identifier_body | |
test_expand.rs | ],
);
let keys = hex!("6920e299a5202a6d656e636869746f2a");
check(
unsafe { &expand_key(&keys) },
&[
[0x6920e299a5202a6d, 0x656e636869746f2a],
[0xfa8807605fa82d0d, 0x3ac64e6553b2214f],
[0xcf75838d90ddae80, 0xaa1be0e5f9a9c1aa],
[0x180d2f... | random_line_split | ||
test_expand.rs | 6869746f2a],
[0xfa8807605fa82d0d, 0x3ac64e6553b2214f],
[0xcf75838d90ddae80, 0xaa1be0e5f9a9c1aa],
[0x180d2f1488d08194, 0x22cb6171db62a0db],
[0xbaed96ad323d1739, 0x10f67648cb94d693],
[0x881b4ab2ba265d8b, 0xaad02bc36144fd50],
[0xb34f195d096944d6, 0xa3... | ],
);
let keys = [0xff; 24];
check(
unsafe { &expand_key(&keys) },
&[
[0xffffffffffffffff, 0xffffffffffffffff],
[0xffffffffffffffff, 0xe8e9e9e917161616],
[0xe8e9e9e917161616, 0xe8e9e9e917161616],
[0xadaeae19bab8b80f, 0x525151e6454747f0... | {
use super::aes192::expand_key;
let keys = [0x00; 24];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x6263636362636363],
[0x6263636362636363, 0x6263636362636363],
[0x9b9898c9f9fbfbaa,... | identifier_body |
test_expand.rs | x6263636362636363],
[0x6263636362636363, 0x6263636362636363],
[0x9b9898c9f9fbfbaa, 0x9b9898c9f9fbfbaa],
[0x9b9898c9f9fbfbaa, 0x90973450696ccffa],
[0xf2f457330b0fac99, 0x90973450696ccffa],
[0xc81d19a9a171d653, 0x53858160588a2df9],
[0xc81d19a9a171d65... | aes256_expand_key_test | identifier_name | |
day11.rs | FromStr for Item {
type Err = Error;
fn from_str(s: &str) -> Result<Self> |
}
impl std::fmt::Debug for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Item::Chip(id) => write!(f, "{}M", id),
Item::Generator(id) => write!(f, "{}G", id),
Item::ChipAndGenerator => write!(f, "<>"),
}
}
}
#[deriv... | {
let s: Vec<char> = s.chars().collect();
if s.len() != 2 {
return Err(Error::ParseItem {
data: s[0].to_string(),
});
}
match s[1] {
'M' => Ok(Item::Chip(s[0])),
'G' => Ok(Item::Generator(s[0])),
_ => Err(Error:... | identifier_body |
day11.rs | FromStr for Item {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s: Vec<char> = s.chars().collect();
if s.len() != 2 {
return Err(Error::ParseItem {
data: s[0].to_string(),
});
}
match s[1] {
'M' => Ok(Item::Chi... | (&self) -> usize {
self.floors
.iter()
.enumerate()
.map(|(i, f)| f.len() * (i + 1) * 10)
.sum::<usize>()
}
fn is_success(&self) -> bool {
for floor in &self.floors[..self.floors.len() - 1] {
if !floor.is_empty() {
retu... | score | identifier_name |
day11.rs | FromStr for Item {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s: Vec<char> = s.chars().collect();
if s.len() != 2 {
return Err(Error::ParseItem {
data: s[0].to_string(),
});
}
match s[1] {
'M' => Ok(Item::Chi... | for floor in &self.floors[..self.floors.len() - 1] {
if !floor.is_empty() {
return false;
}
}
true
}
fn get_neighbors(&self) -> Vec<State> {
let mut out = Vec::new();
// calculate valid floors that the elevator can move to
... | .map(|(i, f)| f.len() * (i + 1) * 10)
.sum::<usize>()
}
fn is_success(&self) -> bool { | random_line_split |
smpl.tpl.js | Id = blkId || smpl.tpl.utils.MAIN;
var blk = this.__parsedBlocks[blkId];
if (blk) {
delete this.__parsedBlocks[blkId];
return blk.join('');
} else {
return '';
}
};
smpl.tpl.Template.prototype.reset = function() {
if (!this.__data) {
this.init();
}
this.__data = {};
this.__data[smpl.tpl.... | if (!at) return initialPos;
} else if (chr === '/' && input.charAt(pos) === '/') { //Single line comment
if (!at) return initialPos;
while (!newLine.test(input.charAt(++pos)));
++pos; | random_line_split | |
smpl.tpl.js | 'string') |
}
}
if (smpl.tpl.globalObj) {
this.__globalKey = this.__name + '_' + smpl.utils.uniq();
smpl.tpl.globalObj[this.__globalKey] = this;
this.__globalKey = smpl.tpl.globalKey + '["' + this.__globalKey + '"]';
}
};
smpl.tpl.Template.prototype.set = function(block, key, value) {
if (arguments.length ... | {
this.__blocks[blkId] = new Function('smpl', '$', '"use strict";' + this.__blocks[blkId]);
} | conditional_block |
cart.component.ts | ToastrService, private router:Router, private cartService:OrderService,
private sanitizer: DomSanitizer, private countriesService: CountriesService, private cService: CartService) { }
async ngOnInit() {
// this.getCart();
//this.getItems()
this.userinfo = this.auth.getLoginData();
this.buyerId ... |
} else{
this.hideLoader();
}
},
error=> {
console.log( error );
}
)
}
getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = document.createElement("canvas");
var context = canvas.getContext(... | {
this.hideLoader();
} | conditional_block |
cart.component.ts | :ToastrService, private router:Router, private cartService:OrderService,
private sanitizer: DomSanitizer, private countriesService: CountriesService, private cService: CartService) { }
async ngOnInit() {
// this.getCart();
//this.getItems()
this.userinfo = this.auth.getLoginData();
this.buyerId... | (items){
this.productService.updateData(this.shoppingEnpoint, items).subscribe(result => {
console.log( 'result', result );
this.getTotalPricing();
}, error => {
this.toast.error("Error updating cart!", "Error",{positionClass:"toast-top-right"} );
})
}
checkout(){
localSto... | updatecart | identifier_name |
cart.component.ts | ToastrService, private router:Router, private cartService:OrderService,
private sanitizer: DomSanitizer, private countriesService: CountriesService, private cService: CartService) { }
async ngOnInit() {
// this.getCart();
//this.getItems()
this.userinfo = this.auth.getLoginData();
this.buyerId ... |
validateMax(i){
console.log(this.products[i].quantity.value);
if(this.products[i].quantity.value > this.products[i].fish.maximumOrder){
this.products[i].quantity.value = this.products[i].fish.maximumOrder;
this.getAllProductsCount();
}else{
this.getAllProductsCount();
}
}
/... | {
console.log("Product modal ID", itemID, index);
this.itemToDelete = itemID;
this.index = index;
jQuery('#confirmDelete').modal('show');
} | identifier_body |
cart.component.ts | :ToastrService, private router:Router, private cartService:OrderService,
private sanitizer: DomSanitizer, private countriesService: CountriesService, private cService: CartService) { }
async ngOnInit() {
// this.getCart();
//this.getItems()
this.userinfo = this.auth.getLoginData();
this.buyerId... | var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
public isVacio(id, idSuffix) {
let element = document.querySelector('#' + id) as HTMLInputElement;
if (element === null) return true;
//unit measure
const su... | var canvas = document.createElement("canvas"); | random_line_split |
sink.rs | open(&input_file_path)?;
// Replace the @@ marker in the args with the actual file path (if input type is File).
if input_channel == InputChannel::File {
if let Some(elem) = args.iter_mut().find(|e| **e == "@@") {
*elem = input_file_path.to_str().unwrap().to_owned();
... | else {
unsafe {
libc::dup2(dev_null_fd, libc::STDERR_FILENO);
}
}
unsafe {
libc::close(dev_null_fd);
}
unsafe {
// Close the pipe ends used by our pa... | {
//unsafe {
// let fd = self.stderr_file.as_ref().unwrap().0.as_raw_fd();
// libc::dup2(fd, libc::STDERR_FILENO);
// libc::close(fd);
//}
} | conditional_block |
sink.rs | )).unwrap();
envp.push(shm_env_var.as_ptr());
let mut env_from_config = Vec::new();
if let Some(cfg) = self.config.as_ref() {
cfg.sink.env.iter().for_each(|var| {
env_from_config
.push(CString::new(f... | write | identifier_name | |
sink.rs | ::RLIMIT_FSIZE, &rlim as *const libc::rlimit);
assert_eq!(ret, 0);
}
// Disable core dumps
let limit_val: libc::rlimit = std::mem::zeroed();
let ret = libc::setrlimit(libc::RLIMIT_CORE, &limit_val);
... |
log::trace!("Child terminated, getting exit status"); | random_line_split | |
app_store_connect.py | managing Debug Information Files from Apple App Store Connect.
Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's
debug files. These tasks enable this functionality.
"""
import logging
import pathlib
import tempfile
from typing import List, Mapping, Tuple
import requests
i... |
# Sadly this decorator makes this entire function untyped for now as it does not itself have
# typing annotations. So we do all the work outside of the decorated task function to work
# around this.
# Since all these args must be pickled we keep them to built-in types as well.
@instrumented_task(name="sentry.tasks.a... | random_line_split | |
app_store_connect.py | managing Debug Information Files from Apple App Store Connect.
Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's
debug files. These tasks enable this functionality.
"""
import logging
import pathlib
import tempfile
from typing import List, Mapping, Tuple
import requests
i... | "Not authorized to download dSYM using current App Store Connect credentials",
level="info",
)
return
except appstoreconnect_api.ForbiddenError:
sentry_sdk.capture_message(
"Forbidden from downloading... | with sdk.configure_scope() as scope:
scope.set_context("dsym_downloads", {"total": len(builds), "completed": i})
with tempfile.NamedTemporaryFile() as dsyms_zip:
try:
client.download_dsyms(build, pathlib.Path(dsyms_zip.name))
# For no dSYMs, let the build be m... | conditional_block |
app_store_connect.py | managing Debug Information Files from Apple App Store Connect.
Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's
debug files. These tasks enable this functionality.
"""
import logging
import pathlib
import tempfile
from typing import List, Mapping, Tuple
import requests
i... |
def get_or_create_persisted_build(
project: Project, config: appconnect.AppStoreConnectConfig, build: appconnect.BuildInfo
) -> AppConnectBuild:
"""Fetches the sentry-internal :class:`AppConnectBuild`.
The build corresponds to the :class:`appconnect.BuildInfo` as returned by the
AppStore Connect API... | with sentry_sdk.start_span(op="dsym-difs", description="Extract difs dSYM zip"):
with open(dsyms_zip, "rb") as fp:
created = debugfile.create_files_from_dif_zip(fp, project, accept_unknown=True)
for proj_debug_file in created:
logger.debug("Created %r for project %s", pro... | identifier_body |
app_store_connect.py | managing Debug Information Files from Apple App Store Connect.
Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's
debug files. These tasks enable this functionality.
"""
import logging
import pathlib
import tempfile
from typing import List, Mapping, Tuple
import requests
i... | () -> None:
"""Refreshes all AppStoreConnect builds for all projects.
This iterates over all the projects configured in Sentry and for any which has an
AppStoreConnect symbol source configured will poll the AppStoreConnect API to check if
there are new builds.
"""
# We have no way to query for ... | inner_refresh_all_builds | identifier_name |
player.rs | (&self) -> i64 {
self.length
}
}
#[derive(Debug)]
pub enum Event {
PlayerShutDown,
PlaybackStatusChange(PlaybackStatus),
Seeked { position: Duration },
MetadataChange(Option<Metadata>),
}
#[derive(Debug)]
pub struct Progress {
/// If player is stopped, metadata will be None
metadat... | .map(|reply| {
reply
.get1()
.expect("GetNameOwner must have name as first member")
})
}
fn query_all_player_buses(c: &Connection) -> Result<Vec<String>, String> {
let list_names = Message::new_method_call(
"org.freedesktop.DBus",
"/",
... | c.send_with_reply_and_block(get_name_owner, Duration::from_millis(100))
.map_err(|e| e.to_string()) | random_line_split |
player.rs | self) -> i64 {
self.length
}
}
#[derive(Debug)]
pub enum Event {
PlayerShutDown,
PlaybackStatusChange(PlaybackStatus),
Seeked { position: Duration },
MetadataChange(Option<Metadata>),
}
#[derive(Debug)]
pub struct Progress {
/// If player is stopped, metadata will be None
metadata:... |
fn parse_player_metadata<T: arg::RefArg>(
metadata_map: HashMap<String, T>,
) -> Result<Option<Metadata>, String> {
debug!("metadata_map = {:?}", metadata_map);
let file_path_encoded = match metadata_map.get("xesam:url") {
Some(url) => url
.as_str()
.ok_or("url metadata sh... | {
query_player_property::<String>(p, "PlaybackStatus").map(|v| parse_playback_status(&v))
} | identifier_body |
player.rs | (&self) -> i64 {
self.length
}
}
#[derive(Debug)]
pub enum Event {
PlayerShutDown,
PlaybackStatusChange(PlaybackStatus),
Seeked { position: Duration },
MetadataChange(Option<Metadata>),
}
#[derive(Debug)]
pub struct Progress {
/// If player is stopped, metadata will be None
metadat... | (&self) -> Duration {
self.position
}
}
fn query_player_property<T>(p: &ConnectionProxy, name: &str) -> Result<T, String>
where
for<'b> T: dbus::arg::Get<'b>,
{
p.get("org.mpris.MediaPlayer2.Player", name)
.map_err(|e| e.to_string())
}
pub fn query_player_position(p: &ConnectionProxy) -> R... | position | identifier_name |
initialize.py | username':'sarahbro1', }
]:
user = mod.User()
for key in data:
setattr(user, key, data[key])
user.set_password('password')
user.save()
group.user_set.add(user)
#############################################################################
################################ DUMMY DATA ###... | random_line_split | ||
initialize.py | = mod.Area()
area.name = "Vendors"
area.event = event
area.description = "This is where vendors will be located."
area.place_number = 1
area.coordinator = user
area.supervisor = user
area.save()
################################ INVENTORY ##################################
# Bulk product - musket balls
photo ... | setattr(rental, key, data[key]) | conditional_block | |
pharmacie-details.ts | import {Pharmacie} from '../../models/pharmacie';
// Importation de la page de détail d'une pharmacie
import {OpinionPage} from '../opinion/opinion';
// Importation de la page de saisie des horaires de la pharmacie
import {HoursPage} from '../hours/hours';
declare var google;
declare var $;
declare var _;
declare va... | import {SubscriberProvider} from '../../providers/subscriber/subscriber';
// Importation du modèle de données Pharmacie | random_line_split | |
pharmacie-details.ts | : 'build/pages/pharmacie-details/pharmacie-details.html',
// Ajout du provider Pharmacies et Opinions
providers: [PharmaciesProvider, OpinionsProvider, SubscriberProvider]
})
export class PharmacieDetailsPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
id: string;
rs: string;
pharmacie: Pharma... | abonne l'utilisateur aux commentaires de la pharmacie
this.subscriberProvider.subscribe(this.pharmacie._id);
classIcon = 'ion-md-star';
msgToast = 'Pharmacie ajoutée aux favoris';
if (localStorage.getItem('favorites')) {
favorites = JSON.parse(localStorage.getItem('favorites'));
... | bonne l'utilisateur aux commentaires de la pharmacie
this.subscriberProvider.unsubscribe(this.pharmacie._id);
classIcon = 'ion-md-star-outline';
msgToast = 'Pharmacie retirée des favoris';
// Mise a jour de la liste des pharmacies favorites
favorites = JSON.parse(localStorage.getItem('fa... | conditional_block |
pharmacie-details.ts | 'build/pages/pharmacie-details/pharmacie-details.html',
// Ajout du provider Pharmacies et Opinions
providers: [PharmaciesProvider, OpinionsProvider, SubscriberProvider]
})
export class PharmacieDetailsPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
id: string;
rs: string;
pharmacie: Pharmac... | his.pharmacie.hours) {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function formatDay(amo, amc, pmo, pmc) {
if (amo == 0 && pmc == 1440)
return 'Ouvert 24h/24';
// Pas d'horaire le matin
if (amo == 0 && amc == 0... | {
if (t | identifier_name |
did.rs | DID`] query and returns an iterator of (key, value) pairs.
#[inline]
pub fn query_pairs(&self) -> form_urlencoded::Parse {
self.core.query_pairs(self.as_str())
}
/// Change the method of the [`DID`].
#[inline]
pub fn set_method(&mut self, value: impl AsRef<str>) {
self.core.set_method(&mut self.dat... | {
input = &input[2..];
} | conditional_block | |
did.rs | DID {
data: String,
core: Core,
}
impl DID {
/// The URL scheme for Decentralized Identifiers.
pub const SCHEME: &'static str = "did";
/// Parses a [`DID`] from the provided `input`.
///
/// # Errors
///
/// Returns `Err` if any DID segments are invalid.
pub fn parse(input: impl AsRef<str>) -> Re... |
}
impl Display for DID {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(format_args!("{}", self.as_str()))
}
}
impl AsRef<str> for DID {
fn as_ref(&self) -> &str {
self.data.as_ref()
}
}
impl FromStr for DID {
type Err = Error;
fn from_str(string: &str) -> Result<Self, Self::Err> {... | {
f.write_fmt(format_args!("{:?}", self.as_str()))
} | identifier_body |
did.rs | struct DID {
data: String,
core: Core,
}
impl DID {
/// The URL scheme for Decentralized Identifiers.
pub const SCHEME: &'static str = "did";
/// Parses a [`DID`] from the provided `input`.
///
/// # Errors
///
/// Returns `Err` if any DID segments are invalid.
pub fn parse(input: impl AsRef<str>... | self.core.path(self.as_str())
}
/// Returns the [`DID`] method query, if any.
#[inline]
pub fn query(&self) -> Option<&str> {
self.core.query(self.as_str())
}
/// Returns the [`DID`] method fragment, if any.
#[inline]
pub fn fragment(&self) -> Option<&str> {
self.core.fragment(self.as_str(... | #[inline]
pub fn path(&self) -> &str { | random_line_split |
did.rs | .core.authority(self.as_str())
}
/// Returns the [`DID`] method name.
#[inline]
pub fn method(&self) -> &str {
self.core.method(self.as_str())
}
/// Returns the [`DID`] method-specific ID.
#[inline]
pub fn method_id(&self) -> &str {
self.core.method_id(self.as_str())
}
/// Returns the [`D... | remove_dot_segments | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.