file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ChildNodeInterface.js | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
suite('ChildNodeInterface', function() {
function getTree() {
var tree = {};
var div = tree.div = document.createElement('div');
div... | div.innerHTML = '<a></a>';
var a = div.firstChild;
a.remove();
assert.equal(div.firstChild, null);
assert.equal(a.parentNode, null);
// no op.
div.remove();
});
}); | });
test('remove', function() {
var div = document.createElement('div'); | random_line_split |
111815001.py | import random
import math
import sympy
from sympy import latex, fraction, Symbol, Rational
localid =11181500100000
letter=["a","b","c","d"]
n=[0,0,0,0,0,0]
m=[0,0,0,0,0]
f = open("111815001.tex","w") #opens file with name of "test.txt"
for x in range(0, 1000):
localid = localid +1
writewrong=["\correctchoice{... | writewrong[z]=writewrong[z]+str(letter[z])
random.shuffle(writewrong)
f.write("\n\n\n")
f.write("\\element{slope}{")
f.write("\n")
f.write("\\begin{question}{")
f.write(str(localid))
f.write("}")
f.write("\n")
f.write("Find the slope using points: (")
f.write(str(n[1]))
... | random_line_split | |
111815001.py | import random
import math
import sympy
from sympy import latex, fraction, Symbol, Rational
localid =11181500100000
letter=["a","b","c","d"]
n=[0,0,0,0,0,0]
m=[0,0,0,0,0]
f = open("111815001.tex","w") #opens file with name of "test.txt"
for x in range(0, 1000):
localid = localid +1
writewrong=["\correctchoice{... |
random.shuffle(writewrong)
f.write("\n\n\n")
f.write("\\element{slope}{")
f.write("\n")
f.write("\\begin{question}{")
f.write(str(localid))
f.write("}")
f.write("\n")
f.write("Find the slope using points: (")
f.write(str(n[1]))
f.write(",")
f.write(str(n[2]))
f.wri... | writewrong[z]=writewrong[z]+str(letter[z]) | conditional_block |
Entity.ts | /**
* @fileOverview Abstract interface for entities
* @author <a href="mailto:tim.hollies@warwick.ac.uk">Tim Hollies</a>
* @version 0.0.1
*/
import { Serializable } from './Serializable';
export class Entity implements Serializable {
public uid: number | null;
public entityType: number; // TODO: ideally t... |
public serialize() : any {
return this;
}
} | {
this.uid = data.uid;
this.entityType = data.entityType;
this.label = data.label;
this.parent = data.parent;
this.creator = data.creator;
this.creationTimestamp = data.creationTimestamp;
this.lastmodifiedTimestamp = data.lastmodifiedTimestamp;
return this;
... | identifier_body |
Entity.ts | /**
* @fileOverview Abstract interface for entities
* @author <a href="mailto:tim.hollies@warwick.ac.uk">Tim Hollies</a>
* @version 0.0.1
*/
import { Serializable } from './Serializable';
export class Entity implements Serializable {
public uid: number | null;
public entityType: number; // TODO: ideally t... | (data: any) : Entity {
this.uid = data.uid;
this.entityType = data.entityType;
this.label = data.label;
this.parent = data.parent;
this.creator = data.creator;
this.creationTimestamp = data.creationTimestamp;
this.lastmodifiedTimestamp = data.lastmodifiedTimestamp;
... | deserialize | identifier_name |
Entity.ts | /**
* @fileOverview Abstract interface for entities
* @author <a href="mailto:tim.hollies@warwick.ac.uk">Tim Hollies</a>
* @version 0.0.1
*/
import { Serializable } from './Serializable';
export class Entity implements Serializable {
public uid: number | null;
public entityType: number; // TODO: ideally t... |
this.creationTimestamp = data.creationTimestamp;
this.lastmodifiedTimestamp = data.lastmodifiedTimestamp;
return this;
}
public serialize() : any {
return this;
}
} | this.creator = data.creator; | random_line_split |
pyrenamer_menu_cb.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option... | def on_menu_patterns_activate(self, widget):
self.main.notebook.set_current_page(0)
def on_menu_substitutions_activate(self, widget):
self.main.notebook.set_current_page(1)
def on_menu_insert_activate(self, widget):
self.main.notebook.set_current_page(2)
def on_menu_manual_act... | lf.main.file_browser.create_new()
self.main.file_browser.set_active_dir(self.main.active_dir)
| identifier_body |
pyrenamer_menu_cb.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option... |
def __init__(self, main):
self.main = main
def on_menu_undo_activate(self, widget):
self.main.undo_manager.undo()
self.main.dir_reload_current()
self.main.menu_undo.set_sensitive(False)
self.main.menu_redo.set_sensitive(True)
def on_menu_redo_activate(self, widget)... | renamerMenuCB:
| identifier_name |
pyrenamer_menu_cb.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option... | GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
If you find any bugs or have any suggestions email: code@infinicode.... | random_line_split | |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... | self.current_vertical_line = (value & 0x3ff) as u16;
// TODO clear interrupt line
}
} | self.current_vertical_line & 0x3ff
}
fn write_current_vertical_line(&mut self, value: u32) { | random_line_split |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... | (&mut self, addr: u32, value: u32) {
match addr {
VI_INTR_REG => self.write_halfline(value),
VI_H_START_REG => self.write_h_video(value),
VI_V_CURRENT_REG => self.write_current_vertical_line(value),
_ => {
panic!("Cannot write to register in Video ... | write | identifier_name |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... |
fn write_halfline(&mut self, value: u32) {
self.intr_half_line = value & 0x3ff;
}
fn read_h_video(&self) -> u32 {
(self.horizontal_video_start as u32) << 16 | (self.horizontal_video_end as u32)
}
fn write_h_video(&mut self, value: u32) {
self.horizontal_video_start = (val... | {
self.intr_half_line
} | identifier_body |
base.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# Save the credentials.
self._credentials = credentials
# Lifted into its own function so it can be stubbed out during tests.
self._prep_wrapped_messages(client_info)
def _prep_wrapped_messages(self, client_info):
# Precomputed wrapped methods
self._wrapped_method... | credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) | conditional_block |
base.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | (self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def get_geo_target_constan... | close | identifier_name |
base.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
def _prep_wrapped_messages(self, client_info):
# Precomputed wrapped methods
self._wrapped_methods = {
self.get_geo_target_constant: gapic_v1.method.wrap_method(
self.get_geo_target_constant,
default_timeout=None,
client_info=client_info,... | """Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the applica... | identifier_body |
base.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
from google.ads.googleads.v9.resources.types import geo_target_constant
from google.ads.googleads.v9.services.types import geo_target_constant_service
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-ads",).version,
)
except pkg_resources... |
import google.auth # type: ignore
from google.api_core import gapic_v1
from google.auth import credentials as ga_credentials # type: ignore | random_line_split |
uid_filter.rs | use filter;
use filter::Filter;
use walkdir::DirEntry;
use std::os::unix::fs::MetadataExt;
use std::process;
pub struct UidFilter {
uid: u32,
comp_op: filter::CompOp,
}
impl UidFilter {
pub fn new(comp_op: filter::CompOp, uid: u32) -> UidFilter {
UidFilter{comp_op: comp_op, uid: uid}
}
}
impl... | _ => {
eprintln!("Operator {:?} not covered for attribute uid!", self.comp_op);
process::exit(1);
},
}
}
} | filter::CompOp::Unequal => self.uid != dir_entry.metadata().unwrap().uid(), | random_line_split |
uid_filter.rs | use filter;
use filter::Filter;
use walkdir::DirEntry;
use std::os::unix::fs::MetadataExt;
use std::process;
pub struct UidFilter {
uid: u32,
comp_op: filter::CompOp,
}
impl UidFilter {
pub fn new(comp_op: filter::CompOp, uid: u32) -> UidFilter {
UidFilter{comp_op: comp_op, uid: uid}
}
}
impl... | (&self, dir_entry: &DirEntry) -> bool {
match self.comp_op {
filter::CompOp::Equal => self.uid == dir_entry.metadata().unwrap().uid(),
filter::CompOp::Unequal => self.uid != dir_entry.metadata().unwrap().uid(),
_ => {
eprintln!("Operator ... | test | identifier_name |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
#[inline]
fn print_byte<T: Writer>(stdout: &mut T, ch: &u8) {
if let Err(err) = stdout.write_u8(*ch) {
crash!(1, "{}", err);
}
}
#[inline]
fn print_string<T: Writer>(_: &mut T, s: &String) {
print!("{}", s);
}
fn version () {
println!("{} v{}", NAME, VERSION);
}
| {
if lines {
tail_impl!(String, lines, print_string, reader, line_count, beginning);
} else {
tail_impl!(u8, bytes, print_byte, reader, byte_count, beginning);
}
// if we follow the file, sleep a bit and print the rest if the file has grown.
while follow {
sleep(Duration::mi... | identifier_body |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
None => match given_options.opt_str("c") {
Some(n) => {
let mut slice = n.as_slice();
if slice.len() > 0 && slice.char_at(0) == '+' {
beginning = true;
slice = &slice[1..];
}
byte_count = match p... | {
let mut slice = n.as_slice();
if slice.len() > 0 && slice.char_at(0) == '+' {
beginning = true;
slice = &slice[1..];
}
line_count = match parse_size(slice) {
Some(m) => m,
None => {
show... | conditional_block |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
// if we follow the file, sleep a bit and print the rest if the file has grown.
while follow {
sleep(Duration::milliseconds(sleep_msec as i64));
for io_line in reader.lines() {
match io_line {
Ok(line) => print!("{}", line),
Err(err) => panic!(err)
... | } else {
tail_impl!(u8, bytes, print_byte, reader, byte_count, beginning);
} | random_line_split |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... | <T: Reader>(reader: &mut BufferedReader<T>, mut line_count: usize, mut byte_count: usize, beginning: bool, lines: bool, follow: bool, sleep_msec: u64) {
if lines {
tail_impl!(String, lines, print_string, reader, line_count, beginning);
} else {
tail_impl!(u8, bytes, print_byte, reader, byte_coun... | tail | identifier_name |
title.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable} from '@angular/core';
import {getDOM} from '../dom/dom_adapter';
import {DOCUMENT} from... |
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instea... | random_line_split | |
title.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable} from '@angular/core';
import {getDOM} from '../dom/dom_adapter';
import {DOCUMENT} from... | (newTitle: string) { getDOM().setTitle(this._doc, newTitle); }
}
| setTitle | identifier_name |
title.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable} from '@angular/core';
import {getDOM} from '../dom/dom_adapter';
import {DOCUMENT} from... |
/**
* Set the title of the current HTML document.
* @param newTitle
*/
setTitle(newTitle: string) { getDOM().setTitle(this._doc, newTitle); }
}
| { return getDOM().getTitle(this._doc); } | identifier_body |
hydrogen.py | # -*- coding: utf-8 -*-
"""
hydrogen
~~~~~~~~
Hydrogen is an extremely lightweight workflow enhancement tool for Python
web applications, providing bower/npm-like functionality for both pip and
bower packages.
:author: David Gidwani <david.gidwani@gmail.com>
:license: BSD, see LICENSE for ... | (self, zip_file, dest, expected_version=None):
bower_json = None
root = None
deps_installed = []
for info in zip_file.infolist():
if PurePath(info.filename).name == "bower.json":
with zip_file.open(info) as f:
bower_json = json.load(f)
... | extract_bower_zipfile | identifier_name |
hydrogen.py | # -*- coding: utf-8 -*-
"""
hydrogen
~~~~~~~~
Hydrogen is an extremely lightweight workflow enhancement tool for Python
web applications, providing bower/npm-like functionality for both pip and
bower packages.
:author: David Gidwani <david.gidwani@gmail.com>
:license: BSD, see LICENSE for ... |
if not packages:
for group in groups:
if group not in h.requirements:
warning("{} not in requirements".format(group))
continue
install = (h.install_bower if group.startswith("bower")
else h.install_pip)
for requireme... | random_line_split | |
hydrogen.py | # -*- coding: utf-8 -*-
"""
hydrogen
~~~~~~~~
Hydrogen is an extremely lightweight workflow enhancement tool for Python
web applications, providing bower/npm-like functionality for both pip and
bower packages.
:author: David Gidwani <david.gidwani@gmail.com>
:license: BSD, see LICENSE for ... |
@property
def yaml(self):
return yaml.dump(self.serialized, default_flow_style=False,
encoding=None)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
else:
ret = self[key] = self.default_factory(name=... | to_ret = {}
for group, requirements in self.items():
to_ret[group] = [str(requirement) for requirement in requirements]
return to_ret | identifier_body |
hydrogen.py | # -*- coding: utf-8 -*-
"""
hydrogen
~~~~~~~~
Hydrogen is an extremely lightweight workflow enhancement tool for Python
web applications, providing bower/npm-like functionality for both pip and
bower packages.
:author: David Gidwani <david.gidwani@gmail.com>
:license: BSD, see LICENSE for ... |
self.filename = filename
def save(self, filename=None):
filename = Path(filename) if filename is not None else self.filename
with filename.open("w") as f:
f.write(self.yaml)
@property
def serialized(self):
to_ret = {}
for group, requirements in self.ite... | for requirement in requirements:
self[group].add(Requirement.coerce(requirement)) | conditional_block |
add.tsx | import * as React from 'react'
import * as Kb from '../../../../common-adapters'
import * as Styles from '../../../../styles'
import * as Types from '../../../../constants/types/teams'
import * as Teams from '../../../../constants/teams'
import * as Container from '../../../../util/container'
import * as ChatTypes from... | ...Styles.padding(6, Styles.globalMargins.small),
backgroundColor: Styles.globalColors.blueGrey,
justifyContent: 'space-between',
},
filterInput: {
marginRight: Styles.globalMargins.tiny,
maxWidth: 148,
},
headerButton: Styles.platformStyles({
isMobile: {
flexGrow: 1,
},
}),
... | const styles = Styles.styleSheetCreate(() => ({
containerNew: { | random_line_split |
Nodes.tsx | import React from 'react';
import cx from 'classnames';
import { Group } from '@visx/group';
import DefaultNode from './DefaultNode';
import { NodeProvidedProps } from './types';
export type NodeProps<Node> = {
/** Array of links to render. */
nodes?: Node[];
/** Component for rendering a single link. */
node... |
export default function Nodes<Node>({
nodes = [],
nodeComponent = DefaultNode,
className,
x = (d: any) => (d && d.x) || 0,
y = (d: any) => (d && d.y) || 0,
}: NodeProps<Node>) {
return (
<>
{nodes.map((node, i) => (
<Group
key={`network-node-${i}`}
className={cx('visx-... | x?: (d: Node) => number;
/** Returns the center y coordinate of a node. */
y?: (d: Node) => number;
}; | random_line_split |
Owasp.CsrfGuard.js | /**
* The OWASP CSRFGuard Project, BSD License
* Eric Sheridan (eric.sheridan@owasp.org), Copyright (c) 2011
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribut... |
this._send.apply(this, arguments);
}
}
/** ie does not properly support prototype - wrap completely * */
function hijackExplorer() {
var _XMLHttpRequest = window.XMLHttpRequest;
function alloc_XMLHttpRequest() {
this.base = _XMLHttpRequest ? new _XMLHttpRequest : new window.ActiveXObj... | {
this.onsend.apply(this, arguments);
} | conditional_block |
Owasp.CsrfGuard.js | /**
* The OWASP CSRFGuard Project, BSD License
* Eric Sheridan (eric.sheridan@owasp.org), Copyright (c) 2011
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribut... | }
function init_XMLHttpRequest() {
return new alloc_XMLHttpRequest;
}
init_XMLHttpRequest.prototype = alloc_XMLHttpRequest.prototype;
/** constants * */
init_XMLHttpRequest.UNSENT = 0;
init_XMLHttpRequest.OPENED = 1;
init_XMLHttpRequest.HEADERS_RECEIVED = 2;
init_XMLHttpRequest... | random_line_split | |
Owasp.CsrfGuard.js | /**
* The OWASP CSRFGuard Project, BSD License
* Eric Sheridan (eric.sheridan@owasp.org), Copyright (c) 2011
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribut... | (form, tokenName, tokenValue, pageTokens) {
var action = form.getAttribute("action");
if(action != null && isValidUrl(action)) {
var uri = parseUri(action);
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", tokenName);
hid... | injectTokenForm | identifier_name |
Owasp.CsrfGuard.js | /**
* The OWASP CSRFGuard Project, BSD License
* Eric Sheridan (eric.sheridan@owasp.org), Copyright (c) 2011
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistribut... |
/** inject tokens as hidden fields into forms * */
function injectTokenForm(form, tokenName, tokenValue, pageTokens) {
var action = form.getAttribute("action");
if(action != null && isValidUrl(action)) {
var uri = parseUri(action);
var hidden = document.createElement("input");
hidden.s... | {
var uri = "";
var token = "://";
var index = url.indexOf(token);
var part = "";
/**
* ensure to skip protocol and prepend context path for non-qualified
* resources (ex: "protect.html" vs
* "/Owasp.CsrfGuard.Test/protect.html").
*/
if(index > 0) {
part = url.substring(index +... | identifier_body |
ContactClearDataConfirmModal.tsx | import { useState } from 'react';
import { c } from 'ttag';
import { noop } from '@proton/shared/lib/helpers/function';
import { Key } from '@proton/shared/lib/interfaces';
import { Alert, ErrorButton, FormModal, Input, Row } from '../../../components';
import { useModals } from '../../../hooks';
import ContactClearDat... | onSubmit={handleSubmit}
onClose={onClose}
submit={
<ErrorButton disabled={dangerInput !== dangerWord} type="submit">{c('Action')
.t`Clear data`}</ErrorButton>
}
{...rest}
>
<Alert className="mb1" type="in... | <FormModal
title={c('Title').t`Warning`} | random_line_split |
ceres.py | # Copyright 2011 Chris Davis
#
# 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, so... | :returns: ``[(startTime, endTime, timeStep), ...]``
"""
return [(slice.startTime, slice.endTime, slice.timeStep) for slice in self.slices]
def readMetadata(self):
"""Update node metadata from disk
:raises: :class:`CorruptNode`
"""
with open(self.metadataFile, 'r') as fh:
try:
... | random_line_split | |
ceres.py | # Copyright 2011 Chris Davis
#
# 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, so... | (object):
__slots__ = ('node', 'startTime', 'timeStep', 'fsPath')
def __init__(self, node, startTime, timeStep):
self.node = node
self.startTime = startTime
self.timeStep = timeStep
self.fsPath = join(node.fsPath, '%d@%d.slice' % (startTime, timeStep))
def __repr__(self):
return "<CeresSlice... | CeresSlice | identifier_name |
ceres.py | # Copyright 2011 Chris Davis
#
# 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, so... |
class NodeDeleted(Exception):
pass
class InvalidRequest(Exception):
pass
class InvalidAggregationMethod(Exception):
pass
class SliceGapTooLarge(Exception):
"For internal use only"
class SliceDeleted(Exception):
pass
def aggregate(aggregationMethod, values):
# Filter out None values
knownValue... | pass | identifier_body |
ceres.py | # Copyright 2011 Chris Davis
#
# 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, so... |
def find(self, nodePattern, fromTime=None, untilTime=None):
"""Find nodes which match a wildcard pattern, optionally filtering on
a time range
:param nodePattern: A glob-style metric wildcard
:param fromTime: Optional interval start time in unix-epoch.
:param untilTime: Optional interval ... | raise ValueError("invalid caching behavior configured '%s'" % self.nodeCachingBehavior) | conditional_block |
NotificationDetail.js | import React from "react";
import { Link } from "react-router";
import Loader from "../../core/Loader";
import DataComponent from "../base/DataComponent";
import DataError from "../base/DataError";
import ResourceAction from "./../base/ResourceAction";
import history from "../../history";
/**
* @author Niklas Keller
... |
}
export default NotificationDetail; | {
let content = null;
if (this.state.loaded) {
if (this.state.failed) {
content = (
<DataError />
);
} else {
let emails = this.state.data.emails.map((item) => (
<li><code>{item}</code></li>
... | identifier_body |
NotificationDetail.js | import React from "react";
import { Link } from "react-router";
import Loader from "../../core/Loader";
import DataComponent from "../base/DataComponent";
import DataError from "../base/DataError";
import ResourceAction from "./../base/ResourceAction"; | /**
* @author Niklas Keller
*/
class NotificationDetail extends DataComponent {
getDataUri() {
return "notifications/" + this.props.params.id;
}
componentWillReceiveProps(next) {
let oldId = this.props.params.id;
let newId = next.params.id;
if (oldId !== newId) {
... | import history from "../../history";
| random_line_split |
NotificationDetail.js | import React from "react";
import { Link } from "react-router";
import Loader from "../../core/Loader";
import DataComponent from "../base/DataComponent";
import DataError from "../base/DataError";
import ResourceAction from "./../base/ResourceAction";
import history from "../../history";
/**
* @author Niklas Keller
... | () {
let content = null;
if (this.state.loaded) {
if (this.state.failed) {
content = (
<DataError />
);
} else {
let emails = this.state.data.emails.map((item) => (
<li><code>{item}</code></l... | render | identifier_name |
NotificationDetail.js | import React from "react";
import { Link } from "react-router";
import Loader from "../../core/Loader";
import DataComponent from "../base/DataComponent";
import DataError from "../base/DataError";
import ResourceAction from "./../base/ResourceAction";
import history from "../../history";
/**
* @author Niklas Keller
... |
}
render() {
let content = null;
if (this.state.loaded) {
if (this.state.failed) {
content = (
<DataError />
);
} else {
let emails = this.state.data.emails.map((item) => (
<li><cod... | {
this.fetchData();
} | conditional_block |
ProjectModel.ts | const sander = require("sander");
import { basename, dirname, join } from "path";
const glob = require("glob-promise");
import { PageSettings, BitSettings, BlockSettings, ProjectSettings, Material, BitRef, PageTree, PageContext, BlockContext, CacheableMat, SettingsType } from "./interfaces";
import { flatten } from ".... |
return { namespace, name };
}
}
| {
namespace = splitId[0];
name = splitId[1];
} | conditional_block |
ProjectModel.ts | const sander = require("sander");
import { basename, dirname, join } from "path";
const glob = require("glob-promise");
import { PageSettings, BitSettings, BlockSettings, ProjectSettings, Material, BitRef, PageTree, PageContext, BlockContext, CacheableMat, SettingsType } from "./interfaces";
import { flatten } from ".... | case "page":
{
const namespace = await factory.getProjectName();
const name = basename(path).match(ProjectFactory.getNameRegex(SettingsType.Page))[1];
collection = this.pages;
item = collection.find(x => x.name === name && x.namespace === namespace);
affectedPages = [... | .map(p => p.name);
break;
} | random_line_split |
ProjectModel.ts | const sander = require("sander");
import { basename, dirname, join } from "path";
const glob = require("glob-promise");
import { PageSettings, BitSettings, BlockSettings, ProjectSettings, Material, BitRef, PageTree, PageContext, BlockContext, CacheableMat, SettingsType } from "./interfaces";
import { flatten } from ".... | ({tries, settings}): Promise<BitRef[]> {
return new Promise((resolve, reject) => {
if (tries < 5) {
settings.source.fetch().then(resolve)
.catch(err => {
if (err.code !== 403) { // Code 403: Rate limit exceeded
return reject(err);
... | fetchGDOC | identifier_name |
ProjectModel.ts | const sander = require("sander");
import { basename, dirname, join } from "path";
const glob = require("glob-promise");
import { PageSettings, BitSettings, BlockSettings, ProjectSettings, Material, BitRef, PageTree, PageContext, BlockContext, CacheableMat, SettingsType } from "./interfaces";
import { flatten } from ".... |
private getMatCache({styles, scripts}): { scriptCache: Material[], styleCache: Material[] } {
// Using JSON here to clone by value, not reference
const styleMats = JSON.parse(JSON.stringify(this.materials.filter(x => x.type === "style")));
const scriptMats = JSON.parse(JSON.stringify(this.materials.filt... | {
const globalScripts = this.assembleGlobalMats(scripts, "script");
const globalAssets = this.assembleGlobalMats(assets, "asset");
const globalStyles = this.assembleGlobalMats(styles, "style");
const { bitStyles, bitScripts } = this.assembleBitMats(blocks);
const { styleCache, scriptCache } = this.... | identifier_body |
test_run.py | """
This Test will run through benchbuild's execution pipeline.
"""
import os
import unittest
from contextlib import contextmanager
from benchbuild.utils import cmd
def shadow_commands(command):
def shadow_command_fun(func):
def shadow_command_wrapped_fun(self, *args, **kwargs):
cmd.__override... |
class TestRun(unittest.TestCase):
@shadow_commands("true")
def test_run(self):
from benchbuild import experiment
from benchbuild.utils.actions import Experiment
class MockExp(experiment.Experiment):
NAME = "mock-exp"
def actions_for_project(self, project):
... | inside = None
true = cmd.true
mkdir = cmd.mkdir
class test_class(object):
@shadow_commands("true")
def shadow_hook(self):
return cmd.mkdir
outside = cmd.mkdir
inside = test_class().shadow_hook()
self.assertEqual(inside.formulate()... | identifier_body |
test_run.py | """
This Test will run through benchbuild's execution pipeline.
"""
import os
import unittest
from contextlib import contextmanager
from benchbuild.utils import cmd
def shadow_commands(command):
def shadow_command_fun(func):
def shadow_command_wrapped_fun(self, *args, **kwargs):
cmd.__override... | return cmd.mkdir
outside = cmd.mkdir
inside = test_class().shadow_hook()
self.assertEqual(inside.formulate(), true.formulate(),
msg="true (before) is not the same as true (inside)")
self.assertNotEqual(mkdir.formulate(), inside.formulate(),
... | @shadow_commands("true")
def shadow_hook(self): | random_line_split |
test_run.py | """
This Test will run through benchbuild's execution pipeline.
"""
import os
import unittest
from contextlib import contextmanager
from benchbuild.utils import cmd
def shadow_commands(command):
def | (func):
def shadow_command_wrapped_fun(self, *args, **kwargs):
cmd.__override_all__ = command
res = func(self, *args, **kwargs)
cmd.__override_all__ = None
return res
return shadow_command_wrapped_fun
return shadow_command_fun
class TestShadow(unitte... | shadow_command_fun | identifier_name |
test_run.py | """
This Test will run through benchbuild's execution pipeline.
"""
import os
import unittest
from contextlib import contextmanager
from benchbuild.utils import cmd
def shadow_commands(command):
def shadow_command_fun(func):
def shadow_command_wrapped_fun(self, *args, **kwargs):
cmd.__override... | from benchbuild.utils import log
log.configure()
TestRun().test_run() | conditional_block | |
workflows-selection-service.ts | import { flatten, isNull } from "underscore";
import { Step, Workflow } from "../models";
import { WorkflowSelectionStore } from "./workflow-selection-store";
export type WfChainWrapper = {
workflow: Workflow;
isBeforeRunWorkflow?: boolean;
isAfterRunWorkflow?: boolean;
selectedWorkflowBeforeRunWorkflowIndex?: num... |
const editedWorkflow = viewModel.editedWorkflow;
if (
this.store.lastSelectedStepIndex !== null &&
this.verifySelectedIndex(
this.store.lastSelectedStepIndex,
editedWorkflow?.steps,
this.store.checkLastSelectedstep
)
) {
const step = editedWorkflow?.steps[this.store.lastSelectedStepInde... | {
viewModel.editWorkflowAtIndex(this.store.lastEditedWorkflowIndex);
} | conditional_block |
workflows-selection-service.ts | import { flatten, isNull } from "underscore";
import { Step, Workflow } from "../models";
import { WorkflowSelectionStore } from "./workflow-selection-store";
export type WfChainWrapper = {
workflow: Workflow;
isBeforeRunWorkflow?: boolean;
isAfterRunWorkflow?: boolean;
selectedWorkflowBeforeRunWorkflowIndex?: num... | {
private store: WorkflowSelectionStore;
private location: AngularLocationService;
private static primaryWorkflowName = "primary";
constructor(store: WorkflowSelectionStore, locationService: AngularLocationService) {
this.store = store;
this.location = locationService;
}
private verifySelectedIndex = <T>(
... | WorkflowsSelectionService | identifier_name |
workflows-selection-service.ts | import { flatten, isNull } from "underscore";
import { Step, Workflow } from "../models";
import { WorkflowSelectionStore } from "./workflow-selection-store";
export type WfChainWrapper = {
workflow: Workflow;
isBeforeRunWorkflow?: boolean;
isAfterRunWorkflow?: boolean;
selectedWorkflowBeforeRunWorkflowIndex?: num... | selectedWorkflowAfterRunWorkflowIndex: -1
},
wrapper
);
export class WorkflowsSelectionService {
private store: WorkflowSelectionStore;
private location: AngularLocationService;
private static primaryWorkflowName = "primary";
constructor(store: WorkflowSelectionStore, locationService: AngularLocationServi... | workflow: null,
isBeforeRunWorkflow: true,
isAfterRunWorkflow: false,
selectedWorkflowBeforeRunWorkflowIndex: -1, | random_line_split |
wrap.js | var fs = require('fs');
var dot = require('dot');
var defaults = require('defaults');
var Block = require('glint-block');
var Style = require('glint-plugin-block-style-editable');
var TextBlock = require('glint-block-text');
var MDBlock = require('glint-block-markdown');
var MetaBlock = require('glint-block-meta');
var... |
function editor() {
return Block(CKEditorBlock()).use(Style());
}
exports = module.exports = function wrap(o) {
o = o || {};
var wrap = Wrap();
var blocks = {
'home-title': text().selector('[data-id=home-title]'),
'home-teaser': editor().selector('[data-id=home-teaser]'),
'home-subtitle': mark... | {
return Block(MDBlock()).use(Style());
} | identifier_body |
wrap.js | var fs = require('fs');
var dot = require('dot');
var defaults = require('defaults');
var Block = require('glint-block');
var Style = require('glint-plugin-block-style-editable');
var TextBlock = require('glint-block-text');
var MDBlock = require('glint-block-markdown');
var MetaBlock = require('glint-block-meta');
var... | () {
return Block(CKEditorBlock()).use(Style());
}
exports = module.exports = function wrap(o) {
o = o || {};
var wrap = Wrap();
var blocks = {
'home-title': text().selector('[data-id=home-title]'),
'home-teaser': editor().selector('[data-id=home-teaser]'),
'home-subtitle': markdown().selector('... | editor | identifier_name |
wrap.js | var fs = require('fs');
var dot = require('dot');
var defaults = require('defaults');
var Block = require('glint-block');
var Style = require('glint-plugin-block-style-editable');
var TextBlock = require('glint-block-text');
var MDBlock = require('glint-block-markdown');
var MetaBlock = require('glint-block-meta');
var... |
'bb-title': text().selector('[data-id=bb-title]'),
'bb-content': markdown().selector('[data-id=bb-content]'),
'doc-title': text().selector('[data-id=doc-title]'),
'doc-content': markdown().selector('[data-id=doc-content]'),
'img-title': text().selector('[data-id=img-title]'),
'img-content': e... | 'home-box-5': markdown().selector('[data-id=home-box-5]'),
'home-box-6': markdown().selector('[data-id=home-box-6]'),
'www-title': text().selector('[data-id=www-title]'),
'www-content': editor().selector('[data-id=www-content]'), | random_line_split |
textedit.rs | //! Editing text in this library is handled by either `nk_edit_string` or
//! `nk_edit_buffer`. But like almost everything in this library there are multiple
//! ways of doing it and a balance between control and ease of use with memory
//! as well as functionality controlled by flags.
//!
//! This library genera... | //! The final way is using a dynamically growing nk_text_edit struct, which
//! has both a default version if you don't care where memory comes from and an
//! allocator version if you do. While the text editor is quite powerful for its
//! complexity I would not recommend editing gigabytes of data with it.
//! It ... | random_line_split | |
IconButtonProps.ts | import React from 'react';
import {
OverridableComponent,
OverridableStringUnion,
OverridableTypeMap,
OverrideProps,
} from '@mui/types';
import { SxProps } from '../styles/defaultTheme';
import { ColorPaletteProp, VariantProp } from '../styles/types';
export type IconButtonSlot = 'root';
export interface Ico... | /**
* @default 0
*/
tabIndex?: NonNullable<React.HTMLAttributes<any>['tabIndex']>;
/**
* The variant to use.
* @default 'light'
*/
variant?: OverridableStringUnion<VariantProp, IconButtonPropsVariantOverrides>;
};
defaultComponent: D;
}
export interface ExtendIconButtonType... | * The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps; | random_line_split |
context.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` execution contexts.
//!
//! This is inteded t... | use super::InterruptFrame;
assert_eq!(size_of::<InterruptFrame>(), 32);
}
}
impl fmt::Debug for InterruptFrame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f
, "Interrupt Frame: \
\n instruction pointer: {:p} \
\n co... | #[cfg(test)]
mod test {
#[test]
fn test_interrupt_frame_correct_size() {
use core::mem::size_of; | random_line_split |
context.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` execution contexts.
//!
//! This is inteded t... | () {
use core::mem::size_of;
use super::InterruptFrame;
assert_eq!(size_of::<InterruptFrame>(), 32);
}
}
impl fmt::Debug for InterruptFrame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f
, "Interrupt Frame: \
\n instruction po... | test_interrupt_frame_correct_size | identifier_name |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (time: &Duration) -> String {
format!("{}.{:.9}s", time.as_secs(), time.subsec_nanos())
}
/// Formats the time as microseconds.
pub fn as_micros(time: &Duration) -> u64 {
time.as_secs() * 1_000_000 + time.subsec_nanos() as u64 / 1_000
}
/// Converts U256 into string.
/// TODO Overcomes: https://github.com/paritytec... | format_time | identifier_name |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | else {
format!("\"{:x}\"", v)
}
}
| {
"\"0x0\"".into()
} | conditional_block |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity. | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of t... |
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | random_line_split |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
/// Formats the time as microseconds.
pub fn as_micros(time: &Duration) -> u64 {
time.as_secs() * 1_000_000 + time.subsec_nanos() as u64 / 1_000
}
/// Converts U256 into string.
/// TODO Overcomes: https://github.com/paritytech/bigint/issues/13
pub fn u256_as_str(v: &U256) -> String {
if v.is_zero() {
"\"0x0\"".... | {
format!("{}.{:.9}s", time.as_secs(), time.subsec_nanos())
} | identifier_body |
PersonalityReactions.ts | module TK.SpaceTac {
// Reaction triggered
export type PersonalityReaction = PersonalityReactionConversation
// Condition to check if a reaction may happen, returning involved ships (order is important)
export type ReactionCondition = (player: Player, battle: Battle | null, ship: Ship | null, event: Ba... |
}
| {
if (battle && ship && event) {
if (event instanceof ShipDamageDiff && player.is(ship.fleet.player) && !ship.is(event.ship_id)) {
let hurt = battle.getShip(event.ship_id);
return (hurt && player.is(hurt.fleet.player)) ? [hurt, ship] : [];
} else {
... | identifier_body |
PersonalityReactions.ts | module TK.SpaceTac {
// Reaction triggered
export type PersonalityReaction = PersonalityReactionConversation
// Condition to check if a reaction may happen, returning involved ships (order is important)
export type ReactionCondition = (player: Player, battle: Battle | null, ship: Ship | null, event: Ba... | let codes = difference(keys(pool), this.done);
let candidates = nna(codes.map((code: string): [string, Ship[], ReactionProfile[]] | null => {
let [condition, chance, profiles] = pool[code];
if (this.random.random() <= chance) {
let involved = ... | check(player: Player, battle: Battle | null = null, ship: Ship | null = null, event: BaseBattleDiff | null = null, pool: ReactionPool = BUILTIN_REACTION_POOL): PersonalityReaction | null { | random_line_split |
PersonalityReactions.ts | module TK.SpaceTac {
// Reaction triggered
export type PersonalityReaction = PersonalityReactionConversation
// Condition to check if a reaction may happen, returning involved ships (order is important)
export type ReactionCondition = (player: Player, battle: Battle | null, ship: Ship | null, event: Ba... | (messages: { interlocutor: Ship, message: string }[]) {
this.messages = messages;
}
}
/**
* Standard reaction pool
*/
export const BUILTIN_REACTION_POOL: ReactionPool = {
friendly_fire: [cond_friendly_fire, 1, [
[traits => 1, ships => new PersonalityReactio... | constructor | identifier_name |
PersonalityReactions.ts | module TK.SpaceTac {
// Reaction triggered
export type PersonalityReaction = PersonalityReactionConversation
// Condition to check if a reaction may happen, returning involved ships (order is important)
export type ReactionCondition = (player: Player, battle: Battle | null, ship: Ship | null, event: Ba... | else {
return [];
}
}
}
| {
if (event instanceof ShipDamageDiff && player.is(ship.fleet.player) && !ship.is(event.ship_id)) {
let hurt = battle.getShip(event.ship_id);
return (hurt && player.is(hurt.fleet.player)) ? [hurt, ship] : [];
} else {
return [];
}
... | conditional_block |
register-device.js | /**
* Copyright 2019, Google LLC
*
* 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 ... |
/**
* Cloud Function: Verify IoT device and add to user
*/
module.exports = functions.firestore.document('pending/{device}').onWrite(async (change, context) => {
const deviceId = context.params.device;
// Verify this is either a create or update
if (!change.after.exists) {
console.log(`Pending device rem... | {
// Convert the pending key into PEM format
const chunks = pendingDevice.public_key.match(/(.{1,64})/g);
chunks.unshift('-----BEGIN PUBLIC KEY-----');
chunks.push('-----END PUBLIC KEY-----');
const pendingKey = chunks.join('\n');
if (deviceKey !== pendingKey) throw new Error(`Public Key Mismatch:\nExpecte... | identifier_body |
register-device.js | /**
* Copyright 2019, Google LLC
*
* 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 ... | const projectId = process.env.GCLOUD_PROJECT;
const parentName = `projects/${projectId}/locations/${functions.config().cloudiot.region}`;
const registryName = `${parentName}/registries/${functions.config().cloudiot.registry}`;
const request = {
name: `${registryName}/devices/${deviceId}`
};
... | */
function getDevice(client, deviceId) {
return new Promise((resolve, reject) => { | random_line_split |
register-device.js | /**
* Copyright 2019, Google LLC
*
* 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 ... | (pendingDevice, deviceKey) {
// Convert the pending key into PEM format
const chunks = pendingDevice.public_key.match(/(.{1,64})/g);
chunks.unshift('-----BEGIN PUBLIC KEY-----');
chunks.push('-----END PUBLIC KEY-----');
const pendingKey = chunks.join('\n');
if (deviceKey !== pendingKey) throw new Error(`Pu... | verifyDeviceKey | identifier_name |
__init__.py | import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... | ():
AppConfig.DBENGINE = create_db_engine()
def init_login():
login_manager = LoginManager()
login_manager.init_app(app)
AppConfig.LOGINMANAGER = login_manager
# Create user loader function
@login_manager.user_loader
def load_user(user_id):
return UserService().getAll().filter_by(... | build_db_engine | identifier_name |
__init__.py | import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... |
register_mods()
api = register_rest_api()
register_rest_resources()
build_db_engine()
init_login()
init_logger()
set_app_configuration()
app.run(AppConfig.APPHOST, AppConfig.APPPORT) | app.config['REMEMBER_COOKIE_DURATION'] = AppConfig.REMEMBER_COOKIE_DURATION | identifier_body |
__init__.py | import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... |
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
# set the secret key. keep this really secret:
app.secret_key = AppConfig.APPSECRETKEY
def register_mods():
app.register_blueprint(Common.mod)
app.register_blueprint(Login.mod)
app.register_blueprint(Post.mod)
... |
login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY)
| random_line_split |
__init__.py | import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... |
return None
def init_logger():
handler = RotatingFileHandler('FlaskTest.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
def register_rest_api():
return Api(app)
def register_rest_resources():
api.add_resource(PostsList, '/api/posts')
... | return user | conditional_block |
lc003-longest-substring-without-repeating-characters.py | # coding=utf-8
import unittest
"""3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
Given a string, find the length of the **longest substring** without repeating
characters.
**Examples:**
Given `"abcabcbb"`, the answer is `"a... | (self):
self.assertEqual(self.lengthOfLongestSubstring("abcabcbb"), 3)
self.assertEqual(self.lengthOfLongestSubstring("bbbbb"), 1)
self.assertEqual(self.lengthOfLongestSubstring("pwwkew"), 3)
self.assertEqual(self.lengthOfLongestSubstring("c"), 1)
if __name__ == "__main__":
unittes... | test | identifier_name |
lc003-longest-substring-without-repeating-characters.py | # coding=utf-8
import unittest
"""3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
Given a string, find the length of the **longest substring** without repeating
characters.
**Examples:**
Given `"abcabcbb"`, the answer is `"a... | return val
def test(self):
self.assertEqual(self.lengthOfLongestSubstring("abcabcbb"), 3)
self.assertEqual(self.lengthOfLongestSubstring("bbbbb"), 1)
self.assertEqual(self.lengthOfLongestSubstring("pwwkew"), 3)
self.assertEqual(self.lengthOfLongestSubstring("c"), 1)
if __n... | pos += 1
val = max(val, len(cache)) | random_line_split |
lc003-longest-substring-without-repeating-characters.py | # coding=utf-8
import unittest
"""3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
Given a string, find the length of the **longest substring** without repeating
characters.
**Examples:**
Given `"abcabcbb"`, the answer is `"a... |
else:
cache[s[pos]] = pos
pos += 1
val = max(val, len(cache))
return val
def test(self):
self.assertEqual(self.lengthOfLongestSubstring("abcabcbb"), 3)
self.assertEqual(self.lengthOfLongestSubstring("bbbbb"), 1)
self.assertEqual(s... | pos = cache[s[pos]] + 1
val = max(val, len(cache))
cache.clear() | conditional_block |
lc003-longest-substring-without-repeating-characters.py | # coding=utf-8
import unittest
"""3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
Given a string, find the length of the **longest substring** without repeating
characters.
**Examples:**
Given `"abcabcbb"`, the answer is `"a... |
if __name__ == "__main__":
unittest.main()
| self.assertEqual(self.lengthOfLongestSubstring("abcabcbb"), 3)
self.assertEqual(self.lengthOfLongestSubstring("bbbbb"), 1)
self.assertEqual(self.lengthOfLongestSubstring("pwwkew"), 3)
self.assertEqual(self.lengthOfLongestSubstring("c"), 1) | identifier_body |
mail.py | """
KaraCos - web platform engine - http://karacos.org/
Copyright (C) 2009-2010 Nicolas Karageuzian - Cyril Gratecis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either... | server.ehlo()
if 'site_email_service_secure' in domain:
if domain['site_email_service_secure'] or domain['site_email_service_secure'] == True:
server.starttls()
server.ehlo()
if 'site_email_service_password' in domain:
server.login(domain['... | domain['site_email_service_port']) | random_line_split |
mail.py | """
KaraCos - web platform engine - http://karacos.org/
Copyright (C) 2009-2010 Nicolas Karageuzian - Cyril Gratecis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either... |
def send_mail(destmail, msg):
"""
"""
try:
server = smtplib.SMTP(karacos.config.get('mail','smtp_server'),
karacos.config.get('mail','smtp_server_port'))
server.ehlo()
if karacos.config.has_option('mail', 'smtp_ssl'):
if karacos.co... | import re
reg = re.compile("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$")
return reg.match(email) | identifier_body |
mail.py | """
KaraCos - web platform engine - http://karacos.org/
Copyright (C) 2009-2010 Nicolas Karageuzian - Cyril Gratecis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either... |
server.sendmail(domain['site_email_from'], destmail, msg)
server.close() | server.login(domain['site_email_service_username'], domain['site_email_service_password']) | conditional_block |
mail.py | """
KaraCos - web platform engine - http://karacos.org/
Copyright (C) 2009-2010 Nicolas Karageuzian - Cyril Gratecis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either... | (email):
import re
reg = re.compile("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$")
return reg.match(email)
def send_mail(destmail, msg):
"""
"""
try:
server = smtplib.SMTP(karacos.config.get('mail','smtp_server'),
karacos.con... | valid_email | identifier_name |
api.ts | import passport from 'passport';
import app from 'server/server';
import { getPermissions } from './permissions';
import { createUser, updateUser } from './queries';
const getRequestIds = (req) => {
const user = req.user || {};
return {
userId: user.id,
submittedUserId: req.body.userId,
email: req.body.email... | return updateUser(req.body, permissions.update, req);
})
.then((updatedValues) => {
return res.status(201).json(updatedValues);
})
.catch((err) => {
console.error('Error in putUser: ', err);
return res.status(500).json(err.message);
});
}); | } | random_line_split |
api.ts | import passport from 'passport';
import app from 'server/server';
import { getPermissions } from './permissions';
import { createUser, updateUser } from './queries';
const getRequestIds = (req) => {
const user = req.user || {};
return {
userId: user.id,
submittedUserId: req.body.userId,
email: req.body.email... |
return updateUser(req.body, permissions.update, req);
})
.then((updatedValues) => {
return res.status(201).json(updatedValues);
})
.catch((err) => {
console.error('Error in putUser: ', err);
return res.status(500).json(err.message);
});
});
| {
throw new Error('Not Authorized');
} | conditional_block |
app_e2e-spec.ts | import {browser, by, element, ExpectedConditions} from 'protractor';
// This test uses Protractor without Angular, so disable Angular features
browser.waitForAngularEnabled(false);
// Since we don't have a protractor bazel rule yet, the test is brought up in
// parallel with building the service under test. So the ti... | browser.get('');
// Don't run any specs until we see a <div> on the page.
browser.wait(ExpectedConditions.presenceOf(element(by.css('div.ts1'))), timeoutMs);
browser.wait(ExpectedConditions.presenceOf(element(by.css('div.ts2'))), timeoutMs);
browser.wait(ExpectedConditions.presenceOf(element(by.css(... |
describe('app', () => {
beforeAll(() => { | random_line_split |
thickbox.js | /*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
$.noConflict();
// imagepath = images/thickbox/loadingAnimation.gif;
var tb_pathToImage = " ";
/... | () {
$("#TB_imageOff").unbind("click");
$("#TB_closeWindowButton").unbind("click");
$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
$("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
$("body","h... | tb_remove | identifier_name |
thickbox.js | /*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
$.noConflict();
// imagepath = images/thickbox/loadingAnimation.gif;
var tb_pathToImage = " ";
/... |
$("#TB_next").click(goNext);
}
document.onkeydown = function(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
if(keycode == 27){ // close
tb_remove();
} else if(keycode == 190){ // display previous image
if(!(TB_NextH... | {
$("#TB_window").remove();
$("body").append("<div id='TB_window'></div>");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);
return false;
} | identifier_body |
thickbox.js | /*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
$.noConflict();
// imagepath = images/thickbox/loadingAnimation.gif;
var tb_pathToImage = " ";
/... |
if(keycode == 27){ // close
tb_remove();
}
};
}
} catch(e) {
//nothing here
}
}
//helper functions below
function tb_showIframe(){
$("#TB_load").remove();
$("#TB_window").css({display:"block"});
}
function tb_remove() {
$("#TB_imageOff").unbind("click");
$("#TB_closeWindowButton").unbi... | { // mozilla
keycode = e.which;
} | conditional_block |
thickbox.js | /*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
$.noConflict();
// imagepath = images/thickbox/loadingAnimation.gif;
var tb_pathToImage = " ";
/... | if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
}
}
// End Resizing
TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+... | } else if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y; | random_line_split |
reset.js | 'use strict';
const CONSTANTS = require('./../constants');
const resetRoles = (data, message) => {
let reply = 'You have no roles to reset ' + message.author.toString();
if (message.member.roles.cache) {
var found = false;
//reset user roles
message.member.roles.cache.forEach( (role) => {
if (CONSTANTS.PR... |
});
}
message.channel.send(reply);
return reply;
};
module.exports = (data) => ( (message) => {
return resetRoles(data, message);
});
| {
let foundOverwrite = channel.permissionOverwrites.get(message.author.id);
if(foundOverwrite) {
if(!found) reply += '\n' + message.author.toString() + ', I am unhiding these neighborhood channels: ';
found = true; // do not repeat found message
reply += `#${channel.name}`;
foundOverwrite.de... | conditional_block |
reset.js | 'use strict';
const CONSTANTS = require('./../constants');
const resetRoles = (data, message) => {
let reply = 'You have no roles to reset ' + message.author.toString();
if (message.member.roles.cache) {
var found = false;
//reset user roles
message.member.roles.cache.forEach( (role) => {
if (CONSTANTS.PR... | }
}
});
}
message.channel.send(reply);
return reply;
};
module.exports = (data) => ( (message) => {
return resetRoles(data, message);
}); | found = true; // do not repeat found message
reply += `#${channel.name}`;
foundOverwrite.delete(); | random_line_split |
sensorsregistrar.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | (ResourceRegistrar):
ALLOWED_EXTENSIONS = ALLOWED_EXTS
def register_sensors_from_packs(self, base_dirs):
"""
Discover all the packs in the provided directory and register sensors from all of the
discovered packs.
:return: Number of sensors registered.
:rtype: ``int``
... | SensorsRegistrar | identifier_name |
sensorsregistrar.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
def register_sensors(packs_base_paths=None, pack_dir=None, use_pack_cache=True,
fail_on_failure=False):
if packs_base_paths:
assert isinstance(packs_base_paths, list)
if not packs_base_paths:
packs_base_paths = content_utils.get_packs_base_paths()
registrar = Sensor... | ALLOWED_EXTENSIONS = ALLOWED_EXTS
def register_sensors_from_packs(self, base_dirs):
"""
Discover all the packs in the provided directory and register sensors from all of the
discovered packs.
:return: Number of sensors registered.
:rtype: ``int``
"""
# Regis... | identifier_body |
sensorsregistrar.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
return registered_count
def _register_sensor_from_pack(self, pack, sensor):
sensor_metadata_file_path = sensor
LOG.debug('Loading sensor from %s.', sensor_metadata_file_path)
content = self._meta_loader.load(file_path=sensor_metadata_file_path)
pack_field = content.get('... | LOG.debug('Sensor "%s" successfully registered', sensor)
registered_count += 1 | conditional_block |
sensorsregistrar.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
i... | # http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
urls.py | from django.conf.urls import url
from rpi.beehive.views import AddBeehiveView, delete_readering_view, \
ChartReaderingView, export_view, ListReaderingView, DeleteBeehiveView, \
ModifyBeehiveView, summary_view
urlpatterns = [
url(r'^ajouter$', AddBeehiveView.as_view(), name='add-beehive'),
url(r'^(?P<... | url(r'^(?P<pk>\d+)/modifier/$', ModifyBeehiveView.as_view(),
name='modify-beehive'),
url(r'^(?P<pk>\d+)/supprimer/$', DeleteBeehiveView.as_view(),
name='delete-beehive'),
url(r'^supprimer-releve/(?P<pk>\d+)/$', delete_readering_view,
name='delete-readering'),
] | name='charts'),
url(r'^(?P<pk>\d+)/exporter/$', export_view, name='export'), | random_line_split |
mock-heroes.ts | import { Hero } from './hero';
export var HEROES: Hero[] = [
{ id: 40, isSecret: false, name: 'Mr. Nice' },
{ id: 41, isSecret: false, name: 'Narco' }, | { id: 45, isSecret: false, name: 'RubberMan' },
{ id: 46, isSecret: false, name: 'Dynama' },
{ id: 47, isSecret: true, name: 'Dr IQ' },
{ id: 48, isSecret: true, name: 'Magma' },
{ id: 49, isSecret: true, name: 'Tornado' }
]; | { id: 42, isSecret: false, name: 'Bombasto' },
{ id: 43, isSecret: false, name: 'Celeritas' },
{ id: 44, isSecret: false, name: 'Magneta' }, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.