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 |
|---|---|---|---|---|
create_azure_ad_context_feed.py | #!/usr/bin/env python3
# Copyright 2022 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... | (http_session: requests.AuthorizedSession,
tokenendpoint: str, clientid: str,
clientsecret: str, retrievedevices: bool,
retrievegroups: bool) -> Mapping[str, Any]:
"""Creates a new Azure AD Context feed.
Args:
ht... | create_azure_ad_context_feed | identifier_name |
create_azure_ad_context_feed.py | #!/usr/bin/env python3
# Copyright 2022 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... |
response.raise_for_status()
return response.json()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
chronicle_auth.add_argument_credentials_file(parser)
regions.add_argument_region(parser)
parser.add_argument(
"-te",
"--tokenendpoint",
type=str,
required=True,
h... | print(response.text) | conditional_block |
addschnelleinstieg.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { EinzelbuchungserviceService } from '../einzelbuchungservice.service';
import { Observable } from 'rxjs';
import { KategorieService } from '../kategorie.service';
import { EinzelbuchungAnlegen... | } | gemeinsameBuchung: this.buchungForm.get('gemeinsameBuchung').value
});
} | random_line_split |
addschnelleinstieg.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { EinzelbuchungserviceService } from '../einzelbuchungservice.service';
import { Observable } from 'rxjs';
import { KategorieService } from '../kategorie.service';
import { EinzelbuchungAnlegen... |
if (this.buchungForm.get('gemeinsameBuchung').value) {
const neueBuchung: GemeinsameBuchungAnlegen = {
name: this.buchungForm.get('name').value,
datum: this.buchungForm.get('datum').value,
kategorie: this.buchungForm.get('kategorie').value,
wert: this.buchungForm.get('wert').... | {
return;
} | conditional_block |
addschnelleinstieg.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { EinzelbuchungserviceService } from '../einzelbuchungservice.service';
import { Observable } from 'rxjs';
import { KategorieService } from '../kategorie.service';
import { EinzelbuchungAnlegen... | () {
this.kategorien = this.kategorieService.getAll();
this.authService.getLogin().pipe(first()).toPromise().then(data => this.personenName = data.username);
}
onFormSubmit() {
if (!this.buchungForm.valid) {
return;
}
if (this.buchungForm.get('gemeinsameBuchung').value) {
const neu... | ngOnInit | identifier_name |
context.rs | .org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use option::*;
use super::stack::StackSegment;
use libc::c_void;
use cast::{transmute, transmute_mut_unsafe,... | (regs: &mut Registers, fptr: *c_void, arg: *c_void,
sp: *mut uint, _stack_base: *uint) {
let sp = align_down(sp);
// sp of mips o32 is 8-byte aligned
let sp = mut_offset(sp, -2);
// The final return address. 0 indicates the bottom of the stack
unsafe { *sp = 0; }
regs[... | initialize_call_frame | identifier_name |
context.rs | It would be nice to define regs as `~Option<Registers>` since
// the registers are sometimes empty, but the discriminant would
// then misalign the regs again.
pub struct Context {
/// The context entry point, saved here for later destruction
start: Option<~~fn()>,
/// Hold the registers while the task or ... | {
use std::sys::size_of;
(ptr as int + count * (size_of::<T>() as int)) as *mut T
} | identifier_body | |
context.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use option::*;
use ... | // | random_line_split | |
binaryauthorization_v1beta1_generated_binauthz_management_service_v1_beta1_get_attestor_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 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... |
# Initialize request argument(s)
request = binaryauthorization_v1beta1.GetAttestorRequest(
name="name_value",
)
# Make the request
response = await client.get_attestor(request=request)
# Handle the response
print(response)
# [END binaryauthorization_v1beta1_generated_BinauthzMana... | client = binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient() | random_line_split |
binaryauthorization_v1beta1_generated_binauthz_management_service_v1_beta1_get_attestor_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 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... | ():
# Create a client
client = binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient()
# Initialize request argument(s)
request = binaryauthorization_v1beta1.GetAttestorRequest(
name="name_value",
)
# Make the request
response = await client.get_attestor(request=r... | sample_get_attestor | identifier_name |
binaryauthorization_v1beta1_generated_binauthz_management_service_v1_beta1_get_attestor_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 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... |
# [END binaryauthorization_v1beta1_generated_BinauthzManagementServiceV1Beta1_GetAttestor_async]
| client = binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient()
# Initialize request argument(s)
request = binaryauthorization_v1beta1.GetAttestorRequest(
name="name_value",
)
# Make the request
response = await client.get_attestor(request=request)
# Handle the resp... | identifier_body |
test_stmt.rs | #![allow(clippy::non_ascii_literal)]
#[macro_use]
mod macros;
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::Stmt;
#[test]
fn test_raw_operator() {
let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap();
snapshot!(stmt, @r###"
... | output: Default,
},
block: Block,
})
"###);
}
| {
// <Ø async fn f() {} Ø>
let tokens = TokenStream::from_iter(vec![TokenTree::Group(Group::new(
Delimiter::None,
TokenStream::from_iter(vec![
TokenTree::Ident(Ident::new("async", Span::call_site())),
TokenTree::Ident(Ident::new("fn", Span::call_site())),
Toke... | identifier_body |
test_stmt.rs | #![allow(clippy::non_ascii_literal)]
#[macro_use]
mod macros;
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::Stmt;
#[test]
fn test_raw_operator() {
let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap();
snapshot!(stmt, @r###"
... | Local(Local {
pat: Pat::Wild,
init: Some(Expr::Reference {
expr: Expr::Path {
path: Path {
segments: [
PathSegment {
ident: "raw",
arguments: None,
... | let stmt = syn::parse_str::<Stmt>("let _ = &raw;").unwrap();
snapshot!(stmt, @r###" | random_line_split |
test_stmt.rs | #![allow(clippy::non_ascii_literal)]
#[macro_use]
mod macros;
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::Stmt;
#[test]
fn test_raw_operator() {
let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap();
snapshot!(stmt, @r###"
... | () {
let stmt = syn::parse_str::<Stmt>("let _ = &raw;").unwrap();
snapshot!(stmt, @r###"
Local(Local {
pat: Pat::Wild,
init: Some(Expr::Reference {
expr: Expr::Path {
path: Path {
segments: [
PathSegment {
... | test_raw_variable | identifier_name |
no_0014_longest_common_prefix.rs | struct Solution;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
match strs.len() {
0 => return String::new(),
1 => return strs[0].clone(),
_ => (),
};
let mut buf = String::new();
for (i, c) in strs[0].as_bytes().iter... | }
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_longest_common_prefix() {
let strs = vec!["flower", "flow", "flight"]
.iter()
.map(|x| x.to_string())
.collect();
assert_eq!(Solution::longest_common_prefix(strs), "fl".to_owned());
l... | buf.push(*c as char);
}
buf | random_line_split |
no_0014_longest_common_prefix.rs | struct Solution;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
match strs.len() {
0 => return String::new(),
1 => return strs[0].clone(),
_ => (),
};
let mut buf = String::new();
for (i, c) in strs[0].as_bytes().iter... |
}
buf.push(*c as char);
}
buf
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_longest_common_prefix() {
let strs = vec!["flower", "flow", "flight"]
.iter()
.map(|x| x.to_string())
.collect();
assert... | {
return buf;
} | conditional_block |
no_0014_longest_common_prefix.rs | struct Solution;
impl Solution {
pub fn | (strs: Vec<String>) -> String {
match strs.len() {
0 => return String::new(),
1 => return strs[0].clone(),
_ => (),
};
let mut buf = String::new();
for (i, c) in strs[0].as_bytes().iter().enumerate() {
for j in 1..strs.len() {
... | longest_common_prefix | identifier_name |
edmunds.py | import os, requests, time
import mydropbox
edmunds = mydropbox.get_keys('edmunds')
api_key = edmunds['api_key']
api_secret = edmunds['api_secret']
vin = mydropbox.read_dropbox_file(os.path.join('Records', 'Financials', 'Car', 'VIN')).strip()
r = requests.get("https://api.edmunds.com/api/vehicle/v2/vins/%s?&fmt=json&a... |
# User-supplied
condition = "Clean"
mileage = "6000"
zipcode = "60613"
r = requests.get(
"https://api.edmunds.com/v1/api/tmv/tmvservice/calculateusedtmv" +
"?styleid=%s" % styleid +
''.join(map(lambda optionid: "&optionid=%s" % optionid, optionids)) +
''.join(map(lambda colorid: "&colorid=%s" % color... | for opt in colorcat['options']:
colorids.append(str(opt['id'])) | conditional_block |
edmunds.py | import os, requests, time
import mydropbox
edmunds = mydropbox.get_keys('edmunds')
api_key = edmunds['api_key']
api_secret = edmunds['api_secret']
vin = mydropbox.read_dropbox_file(os.path.join('Records', 'Financials', 'Car', 'VIN')).strip()
r = requests.get("https://api.edmunds.com/api/vehicle/v2/vins/%s?&fmt=json&a... | "&condition=%s" % condition +
"&mileage=%s" % mileage +
"&zip=%s" % zipcode +
"&fmt=json&api_key=%s" % api_key
)
data = r.json()
totalWithOptions = data['tmv']['totalWithOptions']
disp = [
('Used Trade-in', 'usedTradeIn'),
('Used Private Party', 'usedPrivateParty'),
('Used TMV Retail', 'us... | "?styleid=%s" % styleid +
''.join(map(lambda optionid: "&optionid=%s" % optionid, optionids)) +
''.join(map(lambda colorid: "&colorid=%s" % colorid, colorids)) + | random_line_split |
cookies.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil ... | (self):
# We expanduser to make it easy for the user to config the cookies into their homedir.
return os.path.realpath(os.path.expanduser(self.get_options().path))
@memoized_property
def _lock(self):
"""An identity-keyed inter-process lock around the cookie file."""
lockfile = "... | _get_cookie_file | identifier_name |
cookies.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil ... | cookie_jar.set_cookie(cookie)
with self._lock:
cookie_jar.save()
def get_cookie_jar(self):
"""Returns our cookie jar."""
cookie_file = self._get_cookie_file()
cookie_jar = LWPCookieJar(cookie_file)
if os.path.exists(cookie_file):
cookie_ja... | """
cookie_jar = self.get_cookie_jar()
for cookie in cookies: | random_line_split |
cookies.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil ... | for cookie in cookies:
cookie_jar.set_cookie(cookie)
with self._lock:
cookie_jar.save()
def get_cookie_jar(self):
"""Returns our cookie jar."""
cookie_file = self._get_cookie_file()
cookie_jar = LWPCookieJar(cookie_file)
if os.path.exists(cook... | options_scope = "cookies"
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--path",
advanced=True,
fingerprint=True,
default=os.path.join(register.bootstrap.pants_bootstrapdir, "auth", "cookies"),
... | identifier_body |
cookies.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil ... |
return cookie_jar
def _get_cookie_file(self):
# We expanduser to make it easy for the user to config the cookies into their homedir.
return os.path.realpath(os.path.expanduser(self.get_options().path))
@memoized_property
def _lock(self):
"""An identity-keyed inter-process ... | safe_mkdir_for(cookie_file)
# Save an empty cookie jar so we can change the file perms on it before writing data to it.
with self._lock:
cookie_jar.save()
os.chmod(cookie_file, 0o600) | conditional_block |
odyssey.py | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
__version__=''' $Id$ '''
___doc__=''
#odyssey.py
#
#Demo/benchmark of PDFgen rendering Homer's Odyssey.
#results on my humble P266 with 64MB:
# Without page compression:
# 239 pages in 3.76 seconds = 77 pages per second
# With textOut r... |
def run(verbose=1):
if sys.platform[0:4] == 'java':
impl = 'Jython'
else:
impl = 'Python'
verStr = '%d.%d' % (sys.version_info[0:2])
if ACCEL:
accelStr = 'with _rl_accel'
else:
accelStr = 'without _rl_accel'
print 'Benchmark of %s %s %s' % (impl, verStr, accel... | canv.line(left_margin, top_margin, right_margin, top_margin)
canv.setFont('Times-Italic',12)
canv.drawString(left_margin, top_margin + 2, "Homer's Odyssey")
canv.line(left_margin, top_margin, right_margin, top_margin)
canv.line(left_margin, bottom_margin, right_margin, bottom_margin)
canv.drawCent... | identifier_body |
odyssey.py | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
__version__=''' $Id$ '''
___doc__=''
#odyssey.py
#
#Demo/benchmark of PDFgen rendering Homer's Odyssey.
#results on my humble P266 with 64MB:
# Without page compression:
# 239 pages in 3.76 seconds = 77 pages per second
# With textOut r... | (verbose=1):
if sys.platform[0:4] == 'java':
impl = 'Jython'
else:
impl = 'Python'
verStr = '%d.%d' % (sys.version_info[0:2])
if ACCEL:
accelStr = 'with _rl_accel'
else:
accelStr = 'without _rl_accel'
print 'Benchmark of %s %s %s' % (impl, verStr, accelStr)
s... | run | identifier_name |
odyssey.py | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
__version__=''' $Id$ '''
___doc__=''
#odyssey.py
#
#Demo/benchmark of PDFgen rendering Homer's Odyssey.
#results on my humble P266 with 64MB:
# Without page compression:
# 239 pages in 3.76 seconds = 77 pages per second
# With textOut r... |
if tx:
canv.drawText(tx)
canv.showPage()
drawPageFrame(canv)
if verbose:
print 'about to write to disk...'
canv.save()
finished = time.time()
elapsed = finished - started
pages = canv.getPageNumber()-1
speed = pages / elapsed
fileSize = os.stat('odys... | print 'formatted page %d' % canv.getPageNumber() | conditional_block |
odyssey.py | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
__version__=''' $Id$ '''
___doc__=''
#odyssey.py
#
#Demo/benchmark of PDFgen rendering Homer's Odyssey.
#results on my humble P266 with 64MB:
# Without page compression:
# 239 pages in 3.76 seconds = 77 pages per second
# With textOut r... | tx.textLine(line.rstrip())
#page breaking
y = tx.getY() #get y coordinate
if y < bottom_margin + 0.5*inch:
canv.drawText(tx)
canv.showPage()
drawPageFrame(canv)
canv.setFont('Times-Roman', 12)
tx = canv.beginText(left_margin,... | break
data = open(fn,'r').readlines()
for line in data:
#this just does it the fast way... | random_line_split |
input.ts | import diff from 'fast-diff';
import Editor from '../Editor';
import Delta from '../delta/Delta';
import TextChange from '../doc/TextChange';
import { deltaFromDom } from '../rendering/html';
import { getLineNodeEnd, getLineNodeStart, HTMLLineElement } from '../rendering/rendering';
import { getSelection } from '../ren... |
gboardEnter = false;
}
if (change && change.ops.length) {
cleanText(change);
const old = editor.doc;
editor.update(new TextChange(editor.doc, change, selection, editor.activeFormats), Source.input);
if (editor.doc.lines === old.lines) {
editor.render();
}
}
}
... | {
selection[0]++;
selection[1]++;
} | conditional_block |
input.ts | import diff from 'fast-diff';
import Editor from '../Editor';
import Delta from '../delta/Delta';
import TextChange from '../doc/TextChange';
import { deltaFromDom } from '../rendering/html';
import { getLineNodeEnd, getLineNodeStart, HTMLLineElement } from '../rendering/rendering';
import { getSelection } from '../ren... | if (count < list.length) return null;
if (textAdd && textAdd.addedNodes[0] !== text.target) return null;
return text;
}
function getChangedLineRange(root: HTMLElement, records: MutationRecord[]): HTMLLineRange | undefined {
let start: HTMLLineElement | undefined, end: HTMLLineElement | undefined;
for (let... | {
// Shrink the list down to one entry per text node
const textNodes = new Set();
list = list.filter(record => {
if (record.type !== 'characterData') return true;
if (textNodes.has(record.target)) return false;
textNodes.add(record.target);
return true;
});
if (list.length > 3) return null;
... | identifier_body |
input.ts | import diff from 'fast-diff';
import Editor from '../Editor';
import Delta from '../delta/Delta';
import TextChange from '../doc/TextChange';
import { deltaFromDom } from '../rendering/html';
import { getLineNodeEnd, getLineNodeStart, HTMLLineElement } from '../rendering/rendering';
import { getSelection } from '../ren... | }
// Function to detect if Gboard is sending new lines with composed input
function onBeforeInput(event: InputEvent) {
if (! event.data) return;
if (event.data.includes('\n')) {
gboardEnter = true;
}
}
return {
init() {
editor.root.addEventListener('input', onInput);
editor... | observer.disconnect();
}
function onRender() {
observer.observe(editor.root, MUTATION_OPTIONS); | random_line_split |
input.ts | import diff from 'fast-diff';
import Editor from '../Editor';
import Delta from '../delta/Delta';
import TextChange from '../doc/TextChange';
import { deltaFromDom } from '../rendering/html';
import { getLineNodeEnd, getLineNodeStart, HTMLLineElement } from '../rendering/rendering';
import { getSelection } from '../ren... | (list: MutationRecord[]) {
if (!editor.enabled) {
return editor.render();
}
// Optimize for text changes (typing text)
let change = getTextChange(list) as Delta;
let selection = getSelection(editor);
if (!change) {
const range = getChangedLineRange(editor.root, list);
change ... | onMutate | identifier_name |
app.module.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R... | var common_1 = require('@angular/common');
var router_1 = require('@angular/router');
var app_routing_1 = require('./app.routing');
var main_1 = require('ag-grid-ng2/main');
var ng2_dropdown_1 = require("ng2-dropdown");
var core_2 = require('angular2-google-maps/core');
var ng2_auto_complete_1 = require('ng2-auto... | random_line_split | |
app.module.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R... | () {
}
AppModule = __decorate([
core_1.NgModule({
imports: [router_1.RouterModule, platform_browser_1.BrowserModule, http_1.HttpModule, ng2_bootstrap_1.Ng2BootstrapModule, ng2_dropdown_1.DropdownModule, main_1.AgGridModule.withAotSupport(),
app_routing_1.routing, ng2_aut... | AppModule | identifier_name |
app.module.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R... |
AppModule = __decorate([
core_1.NgModule({
imports: [router_1.RouterModule, platform_browser_1.BrowserModule, http_1.HttpModule, ng2_bootstrap_1.Ng2BootstrapModule, ng2_dropdown_1.DropdownModule, main_1.AgGridModule.withAotSupport(),
app_routing_1.routing, ng2_auto_complete_... | {
} | identifier_body |
test_analyzers.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from socorro.lib import datetimeutil
from socorro.unittest.external.es.base import (
ElasticsearchTestCase,
Supe... | (self):
super(IntegrationTestAnalyzers, self).setUp()
self.api = SuperSearchWithFields(config=self.config)
self.now = datetimeutil.utc_now()
@minimum_es_version('1.0')
def test_semicolon_keywords(self):
"""Test the analyzer called `semicolon_keywords`.
That analyzer cr... | setUp | identifier_name |
test_analyzers.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from socorro.lib import datetimeutil
from socorro.unittest.external.es.base import (
ElasticsearchTestCase,
Supe... | })
self.index_crash({
'date_processed': self.now,
'app_init_dlls': '/path/to/dll;D:\\bar\\boo',
})
self.refresh_index()
res = self.api.get(
app_init_dlls='/path/to/dll',
_facets=['app_init_dlls'],
)
assert res['tota... | semicolons (;) only.
"""
self.index_crash({
'date_processed': self.now,
'app_init_dlls': '/path/to/dll;;foo;C:\\bar\\boo', | random_line_split |
test_analyzers.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from socorro.lib import datetimeutil
from socorro.unittest.external.es.base import (
ElasticsearchTestCase,
Supe... | 'date_processed': self.now,
'app_init_dlls': '/path/to/dll;D:\\bar\\boo',
})
self.refresh_index()
res = self.api.get(
app_init_dlls='/path/to/dll',
_facets=['app_init_dlls'],
)
assert res['total'] == 2
assert 'app_init_dlls... | """Test the custom analyzers we create in our indices. """
def setUp(self):
super(IntegrationTestAnalyzers, self).setUp()
self.api = SuperSearchWithFields(config=self.config)
self.now = datetimeutil.utc_now()
@minimum_es_version('1.0')
def test_semicolon_keywords(self):
""... | identifier_body |
development.js | 'use strict';
module.exports = {
db: 'mongodb://localhost/gadgetboy-dev',
app: {
title: 'gadgetboy - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || '750701491722559',
clientSecret: process.env.FACEBOOK_SECRET || '0678f654f3f4e001fea07e3af7e53d44',
callbackURL: '/api/auth/faceb... | clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID ||... | twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', | random_line_split |
position.py |
from math import fabs
"""Kept these functions outside the class, since they are static
for the search and movement functions for board. The downside is it creates
an object for search purposes, which seems relatively heavy. I'll
optimize later if necessary
"""
def shift_up(pos):
"""returns new position... | (pos):
"""returns new position that has shifted down"""
return Position(pos.x - 1, pos.y - 1)
def shift_up_right(pos):
"""returns new position that has shifted right"""
return Position(pos.x + 1, pos.y + 1)
def shift_down_right(pos):
"""returns new position that has shifted left"""
return Po... | shift_down_left | identifier_name |
position.py | from math import fabs
"""Kept these functions outside the class, since they are static
for the search and movement functions for board. The downside is it creates
an object for search purposes, which seems relatively heavy. I'll
optimize later if necessary
"""
def shift_up(pos):
"""returns new position ... |
@property
def x(self):
return self._x
@property
def y(self):
return self._y
# ############################### Discovery ###############################
def is_diagonal(self, pos):
"""Verify if points are diagonal"""
return fabs(self.x - pos.x) == fabs(self.y -... | # ##################### Accessors/Modifiers ############################### | random_line_split |
position.py |
from math import fabs
"""Kept these functions outside the class, since they are static
for the search and movement functions for board. The downside is it creates
an object for search purposes, which seems relatively heavy. I'll
optimize later if necessary
"""
def shift_up(pos):
"""returns new position... |
def __str__(self):
return '({0},{1})'.format(self._x, self._y)
# ##################### Accessors/Modifiers ###############################
@property
def x(self):
return self._x
@property
def y(self):
return self._y
# ############################### Discovery ####... | def __init__(self, x, y):
self._x, self._y = x, y
# TODO: test the speed of this implementation
# def __cmp__(self, other):
# if (self.width != other.width):
# return cmp(self.width, other.width)
# return cmp(self.height, other.height)
def __eq__(self, pos):
return self... | identifier_body |
my_plugin.py | # -*- coding: utf-8 -*-
# Author: <Your name>
# License see LICENSE
from PyKDE4.kdecore import i18n
from PyKDE4.kdeui import KAction, KIcon
from PyQt4.QtCore import QObject
from PyQt4.QtGui import QMenu
from libkatepate.errors import showOk, showError
import kate
class | (QObject):
def __init__(self):
QObject.__init__(self)
self.window = kate.mainInterfaceWindow().window()
showOk('MyPlugin inits!')
# self.act = KAction(KIcon("reload"), i18n("Auto Reload"), self)
# self.act.setObjectName("test")
# self.window.actionCollection().addAction(sel... | MyPlugin | identifier_name |
my_plugin.py | # -*- coding: utf-8 -*-
# Author: <Your name>
# License see LICENSE
from PyKDE4.kdecore import i18n
from PyKDE4.kdeui import KAction, KIcon
from PyQt4.QtCore import QObject
from PyQt4.QtGui import QMenu
from libkatepate.errors import showOk, showError
import kate
class MyPlugin(QObject):
def __init__(self):
... | # self.act.changed.connect(self.onActionChange)
# self.act.toggled.connect(self.toggle)
# kate.mainInterfaceWindow().viewChanged.connect(self.onViewChanged)
def onActionChange(self):
kate.configuration[self.sender().objectName()] = self.sender().shortcut().toString()
kate.configurati... | QObject.__init__(self)
self.window = kate.mainInterfaceWindow().window()
showOk('MyPlugin inits!')
# self.act = KAction(KIcon("reload"), i18n("Auto Reload"), self)
# self.act.setObjectName("test")
# self.window.actionCollection().addAction(self.act.objectName(), self.act)
# s... | identifier_body |
my_plugin.py | # -*- coding: utf-8 -*-
|
from PyQt4.QtCore import QObject
from PyQt4.QtGui import QMenu
from libkatepate.errors import showOk, showError
import kate
class MyPlugin(QObject):
def __init__(self):
QObject.__init__(self)
self.window = kate.mainInterfaceWindow().window()
showOk('MyPlugin inits!')
# self.act = KActio... | # Author: <Your name>
# License see LICENSE
from PyKDE4.kdecore import i18n
from PyKDE4.kdeui import KAction, KIcon | random_line_split |
test_edw_hash.py | import pytest
TEST_HASHES = {
"test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc",
"test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0",
"testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG",
}
@pytest.mark.parametrize(('passwo... | (password, pwhash):
from encoded.edw_hash import EDWHash
assert EDWHash.hash(password) == pwhash
| test_edw_hash | identifier_name |
test_edw_hash.py | import pytest
TEST_HASHES = {
"test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc",
"test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0",
"testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG",
}
@pytest.mark.parametrize(('passwo... | from encoded.edw_hash import EDWHash
assert EDWHash.hash(password) == pwhash | identifier_body | |
test_edw_hash.py | import pytest
TEST_HASHES = {
"test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc",
"test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0",
"testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG",
} |
@pytest.mark.parametrize(('password', 'pwhash'), TEST_HASHES.items())
def test_edw_hash(password, pwhash):
from encoded.edw_hash import EDWHash
assert EDWHash.hash(password) == pwhash | random_line_split | |
test_filter2d.py | #! /usr/bin/env python
# ______________________________________________________________________
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
# ______________________________________________________________________
import numpy
from numba import *
from numba.decorators import jit
im... |
# ______________________________________________________________________
@autojit
def func():
return numpy.empty(10)
if __name__ == "__main__":
# func()
# TestFilter2d('test_vectorized_filter2d').debug()
unittest.main(*sys.argv[1:])
# __________________________________________________________________... | def test_vectorized_filter2d(self):
ufilter2d = jit(argtypes=[double[:,:], double[:,:]],
restype=double[:,:])(filter2d)
image = numpy.random.random((50, 50))
filt = numpy.random.random((5, 5))
filt /= filt.sum()
plain_old_result = filter2d(image,... | identifier_body |
test_filter2d.py | #! /usr/bin/env python
# ______________________________________________________________________
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
# ______________________________________________________________________
import numpy
from numba import *
from numba.decorators import jit
im... | ():
return numpy.empty(10)
if __name__ == "__main__":
# func()
# TestFilter2d('test_vectorized_filter2d').debug()
unittest.main(*sys.argv[1:])
# ______________________________________________________________________
# End of test_filter2d.py
| func | identifier_name |
test_filter2d.py | #! /usr/bin/env python
# ______________________________________________________________________
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
# ______________________________________________________________________
import numpy
from numba import *
from numba.decorators import jit
im... | num = 0.0
for ii in range(Mf):
for jj in range(Nf):
num += (filt[Mf-1-ii, Nf-1-jj] * image[i-Mf2+ii, j-Nf2+jj])
result[i, j] = num
return result
# ______________________________________________________________________
class TestFilter2d(unitt... | random_line_split | |
test_filter2d.py | #! /usr/bin/env python
# ______________________________________________________________________
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
# ______________________________________________________________________
import numpy
from numba import *
from numba.decorators import jit
im... |
return result
# ______________________________________________________________________
class TestFilter2d(unittest.TestCase):
def test_vectorized_filter2d(self):
ufilter2d = jit(argtypes=[double[:,:], double[:,:]],
restype=double[:,:])(filter2d)
image = numpy... | num = 0.0
for ii in range(Mf):
for jj in range(Nf):
num += (filt[Mf-1-ii, Nf-1-jj] * image[i-Mf2+ii, j-Nf2+jj])
result[i, j] = num | conditional_block |
test-whatwg-url-searchparams-has.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_false, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
h... | () { throw new Error('valueOf'); }
};
const sym = Symbol();
assert.throws(() => params.has(obj), /^Error: toString$/);
assert.throws(() => params.has(sym),
/^TypeError: Cannot convert a Symbol value to a string$/);
}
| valueOf | identifier_name |
test-whatwg-url-searchparams-has.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_false, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
h... |
};
const sym = Symbol();
assert.throws(() => params.has(obj), /^Error: toString$/);
assert.throws(() => params.has(sym),
/^TypeError: Cannot convert a Symbol value to a string$/);
}
| { throw new Error('valueOf'); } | identifier_body |
test-whatwg-url-searchparams-has.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_false, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
h... | }, {
code: 'ERR_INVALID_THIS',
type: TypeError,
message: 'Value of "this" must be of type URLSearchParams'
});
common.expectsError(() => {
params.has();
}, {
code: 'ERR_MISSING_ARGS',
type: TypeError,
message: 'The "name" argument must be specified'
});
const obj = {
toStrin... | // Tests below are not from WPT.
{
const params = new URLSearchParams();
common.expectsError(() => {
params.has.call(undefined); | random_line_split |
GetWordsComp.tsx | import React, { useContext, useState } from 'react'
import { dictionaryFromAndroid } from '../function/dictionaryFromAndroid'
import { dictionaryFromExport } from '../function/dictionaryFromExport'
import { readJsonFromFile } from '../function/readJsonFromFile'
import { wordFromAndroid } from '../function/wordFromAndro... | ({ _setImportableDictionary }: GetWordsCompProps) {
const [$json, set$json] = useState('')
const showMessage = useContext(ShowMessageContext)
return (
<ContentRowComp>
<FormRowComp>
<LabelComp>Fájlból</LabelComp>
<input
autoFocus
type='file'
onChange={async e => {
try {
const... | GetWordsComp | identifier_name |
GetWordsComp.tsx | import React, { useContext, useState } from 'react'
import { dictionaryFromAndroid } from '../function/dictionaryFromAndroid'
import { dictionaryFromExport } from '../function/dictionaryFromExport'
import { readJsonFromFile } from '../function/readJsonFromFile'
import { wordFromAndroid } from '../function/wordFromAndro... | _setImportableDictionary({
dictionary: dictionaryFromExport(
dictionary,
),
words: dictionary.words.map(wordFromExport),
})
} else {
_setImportableDictionary({
dictionary: dictionaryFromAndroid(
dictionary,
),
words... | {
const [$json, set$json] = useState('')
const showMessage = useContext(ShowMessageContext)
return (
<ContentRowComp>
<FormRowComp>
<LabelComp>Fájlból</LabelComp>
<input
autoFocus
type='file'
onChange={async e => {
try {
const files = e.target.files
if (!files) return
... | identifier_body |
GetWordsComp.tsx | import React, { useContext, useState } from 'react'
import { dictionaryFromAndroid } from '../function/dictionaryFromAndroid'
import { dictionaryFromExport } from '../function/dictionaryFromExport'
import { readJsonFromFile } from '../function/readJsonFromFile'
import { wordFromAndroid } from '../function/wordFromAndro... | <LabelComp>Vágólapról</LabelComp>
<textarea
placeholder={`Illeszd be ide...`}
rows={1}
cols={`Illeszd be ide...`.length}
value={$json}
onChange={e => {
try {
const json = e.currentTarget.value
set$json(json)
if (!json) return
try {
var dictionar... | <FormRowComp> | random_line_split |
i_positionable.js | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview The interface for a positionable UI element.
*/
'use strict';
| /**
* The interface for a positionable UI element.
* @namespace Blockly.IPositionable
*/
goog.module('Blockly.IPositionable');
/* eslint-disable-next-line no-unused-vars */
const {IComponent} = goog.require('Blockly.IComponent');
/* eslint-disable-next-line no-unused-vars */
const {MetricsManager} = goog.requireTyp... | random_line_split | |
parse_movie.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::path::Path;
use failure::Error;
use regex::Regex;
use data::Movie;... | Some (cap) => {
let title = cap.get(1).map(|m| m.as_str()).ok_or(format_err!("failed to parse title"))?;
Ok((title, None))
},
None => {
Ok((folder_name, None))
},
}
},
}
}
... | {
lazy_static! {
static ref TITLE_FORMAT_1: Regex = Regex::new(r"([^']+)\s+\((\d{4})\)").unwrap();
}
lazy_static! {
static ref TITLE_FORMAT_2: Regex = Regex::new(r"([^']+)\.").unwrap();
}
let folder_name =
path.strip_prefix(base_path)?.components().next().ok_or(format_err!("... | identifier_body |
parse_movie.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::path::Path;
use failure::Error;
use regex::Regex;
use data::Movie;... | } | random_line_split | |
parse_movie.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::path::Path;
use failure::Error;
use regex::Regex;
use data::Movie;... | (){
match parse(Path::new("/storage/movies/"), Path::new("/storage/movies/Great Escape.m4v")) {
Ok(Movie { ref title, year: None,.. }) if title == "Great Escape" => (),
result => assert!(false, "{:?}", result)
}
}
#[test]
fn die_hard(){
match parse(Path::new("/storage/movies/"), Path::new("... | great_escape | identifier_name |
tableresponsive.js | (function ($, Drupal, window) {
"use strict";
/**
* Attach the tableResponsive function to Drupal.behaviors.
*/
Drupal.behaviors.tableResponsive = {
attach: function (context, settings) {
var $tables = $(context).find('table.responsive-enabled').once('tableresponsive');
if ($tables.length) {
for (va... | .trigger('resize.tableresponsive');
}
/**
* Extend the TableResponsive function with a list of managed tables.
*/
$.extend(TableResponsive, {
tables: []
});
/**
* Associates an action link with the table that will show hidden columns.
*
* Columns are assumed to be hidden if their header has the class prio... | {
this.table = table;
this.$table = $(table);
this.showText = Drupal.t('Show all columns');
this.hideText = Drupal.t('Hide unimportant columns');
// Store a reference to the header elements of the table so that the DOM is
// traversed only once to find them.
this.$headers = this.$table.find('th');
// Ad... | identifier_body |
tableresponsive.js | (function ($, Drupal, window) {
"use strict";
/**
* Attach the tableResponsive function to Drupal.behaviors.
*/
Drupal.behaviors.tableResponsive = {
attach: function (context, settings) {
var $tables = $(context).find('table.responsive-enabled').once('tableresponsive');
if ($tables.length) {
for (va... | (table) {
this.table = table;
this.$table = $(table);
this.showText = Drupal.t('Show all columns');
this.hideText = Drupal.t('Hide unimportant columns');
// Store a reference to the header elements of the table so that the DOM is
// traversed only once to find them.
this.$headers = this.$table.find('th')... | TableResponsive | identifier_name |
tableresponsive.js | (function ($, Drupal, window) {
"use strict";
/**
* Attach the tableResponsive function to Drupal.behaviors.
*/
Drupal.behaviors.tableResponsive = {
attach: function (context, settings) {
var $tables = $(context).find('table.responsive-enabled').once('tableresponsive');
if ($tables.length) {
for (va... | /**
* Associates an action link with the table that will show hidden columns.
*
* Columns are assumed to be hidden if their header has the class priority-low
* or priority-medium.
*/
$.extend(TableResponsive.prototype, {
eventhandlerEvaluateColumnVisibility: function (e) {
var pegged = parseInt(this.$link.da... | random_line_split | |
tableresponsive.js | (function ($, Drupal, window) {
"use strict";
/**
* Attach the tableResponsive function to Drupal.behaviors.
*/
Drupal.behaviors.tableResponsive = {
attach: function (context, settings) {
var $tables = $(context).find('table.responsive-enabled').once('tableresponsive');
if ($tables.length) {
for (va... |
// Hide revealed columns.
else {
this.$revealedCells.hide();
// Strip the 'display:none' declaration from the style attributes of
// the table cells that .hide() added.
this.$revealedCells.each(function (index, element) {
var $cell = $(this);
var properties = $cell.attr(... | {
$hiddenHeaders.each(function (index, element) {
var $header = $(this);
var position = $header.prevAll('th').length;
self.$table.find('tbody tr').each(function () {
var $cells = $(this).find('td:eq(' + position + ')');
$cells.show();
// Keep track of the reve... | conditional_block |
revision.py | # encoding=utf-8
# vim: fenc=utf-8 et sw=4 ts=4 sts=4 ai
import weakref
import re
import urllib
from collections import OrderedDict
from datetime import datetime
import logging
import pytz
from mwtemplates import TemplateEditor
from mwtextextractor import get_body_text
from .common import _
logger = logging.getLogger(... |
def get_parent_link(self):
""" returns a link to parent revision """
q = OrderedDict([('oldid', self.parentid)])
return '//' + self.article().site().host + self.article().site().site['script'] + '?' + urllib.parse.urlencode(q)
def add_point_deduction(self, points, reason):
logg... | "" returns a link to revision """
q = OrderedDict([('oldid', self.revid)])
if not self.new:
q['diff'] = 'prev'
if self.article().site().host == homesite.host:
host_prefix = ''
else:
host_prefix = '//' + self.article().site().host
return host_pr... | identifier_body |
revision.py | # encoding=utf-8
# vim: fenc=utf-8 et sw=4 ts=4 sts=4 ai
import weakref
import re
import urllib
from collections import OrderedDict
from datetime import datetime
import logging
import pytz | logger = logging.getLogger(__name__)
class Revision(object):
def __init__(self, article, revid, **kwargs):
"""
A revision is uniquely identified by its revision id and its site
Arguments:
- article: (Article) article object reference
- revid: (int) revision id
... | from mwtemplates import TemplateEditor
from mwtextextractor import get_body_text
from .common import _
| random_line_split |
revision.py | # encoding=utf-8
# vim: fenc=utf-8 et sw=4 ts=4 sts=4 ai
import weakref
import re
import urllib
from collections import OrderedDict
from datetime import datetime
import logging
import pytz
from mwtemplates import TemplateEditor
from mwtextextractor import get_body_text
from .common import _
logger = logging.getLogger(... |
else:
words1 = len(mt1.split())
words0 = len(mt0.split())
charcount = len(mt1) - len(mt0)
self._wordcount = words1 - words0
logger.debug('Wordcount: Revision %s@%s: %+d bytes, %+d characters, %+d words',
self.revid, self.article().site().ke... | words1 = len(mt1) / 2.0
words0 = len(mt0) / 2.0 | conditional_block |
revision.py | # encoding=utf-8
# vim: fenc=utf-8 et sw=4 ts=4 sts=4 ai
import weakref
import re
import urllib
from collections import OrderedDict
from datetime import datetime
import logging
import pytz
from mwtemplates import TemplateEditor
from mwtextextractor import get_body_text
from .common import _
logger = logging.getLogger(... | self):
""" returns a link to parent revision """
q = OrderedDict([('oldid', self.parentid)])
return '//' + self.article().site().host + self.article().site().site['script'] + '?' + urllib.parse.urlencode(q)
def add_point_deduction(self, points, reason):
logger.info('Revision %s: Rem... | et_parent_link( | identifier_name |
webpack.config.js | var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pkg = require(path.join(process.cwd(), 'package.json'));
var assetsPath = path.join(__dirname, "public","js");
var publicPath = "/public/";
var commonLoaders = [
{
te... | new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('ant.css', {
disable: false,
allChunks: true
}),
]
}; | },
plugins: [
new webpack.HotModuleReplacementPlugin(),
| random_line_split |
sample.e2e-spec.ts | import { AppiumDriver, createDriver, SearchOptions } from "nativescript-dev-appium";
import { assert } from "chai";
describe("sample scenario", () => {
const defaultWaitTime = 5000;
let driver: AppiumDriver;
before(async () => {
driver = await createDriver();
});
after(async () => {
... | it("should find an element by text", async () => {
const btnTap = await driver.findElementByText("TAP", SearchOptions.exact);
await btnTap.click();
const message = " taps left";
const lblMessage = await driver.findElementByText(message, SearchOptions.contains);
assert.equal(... | await driver.logTestArtifacts(this.currentTest.title);
}
});
| random_line_split |
sample.e2e-spec.ts | import { AppiumDriver, createDriver, SearchOptions } from "nativescript-dev-appium";
import { assert } from "chai";
describe("sample scenario", () => {
const defaultWaitTime = 5000;
let driver: AppiumDriver;
before(async () => {
driver = await createDriver();
});
after(async () => {
... |
});
it("should find an element by text", async () => {
const btnTap = await driver.findElementByText("TAP", SearchOptions.exact);
await btnTap.click();
const message = " taps left";
const lblMessage = await driver.findElementByText(message, SearchOptions.contains);
ass... | {
await driver.logTestArtifacts(this.currentTest.title);
} | conditional_block |
utils.py | import json
try:
from urllib.parse import urljoin
from urllib.parse import urlencode
except ImportError:
from urlparse import urljoin
from urllib import urlencode
import facepy
from django.conf import settings
from django.utils import timezone
from django.conf import settings
from django.core import s... | (access_token):
return utils.get_long_lived_access_token(
access_token=access_token,
client_id=settings.FACEBOOK_APP_ID,
client_secret=settings.FACEBOOK_APP_SECRET,
)
def get_access_token(code=None, redirect_uri=None):
return utils.get_access_token(
code=code,
redir... | get_long_lived_access_token | identifier_name |
utils.py | import json
try:
from urllib.parse import urljoin
from urllib.parse import urlencode
except ImportError:
from urlparse import urljoin
from urllib import urlencode
import facepy
from django.conf import settings
from django.utils import timezone
from django.conf import settings
from django.core import s... | signing.Signer(salt=self.salt).unsign(s))
data = signing.b64_decode(base64d)
return json.loads(data.decode('utf-8'))
def redirect_uri(next, close):
return urljoin(
settings.FACEBOOK_CANVAS_URL,
reverse('facebook-auth-handler') + "?" +
Next().encode({'next': nex... | salt = 'facebook_auth.urls.Next'
def encode(self, data):
data = self.dumps(data)
return urlencode({'next': data})
def decode(self, data):
try:
return self.loads(data)
except signing.BadSignature:
raise InvalidNextUrl()
def dumps(self, obj):
... | identifier_body |
utils.py | import json
try:
from urllib.parse import urljoin
from urllib.parse import urlencode
except ImportError:
from urlparse import urljoin
from urllib import urlencode
import facepy
from django.conf import settings
from django.utils import timezone
from django.conf import settings
from django.core import s... |
def get_application_graph(version=None):
version = version or FACEBOOK_API_VERSION
token = (facepy.utils
.get_application_access_token(settings.FACEBOOK_APP_ID,
settings.FACEBOOK_APP_SECRET,
api_version=version... | try:
return graphAPI.get(query)
except facepy.FacepyError as e:
if i == GRAPH_MAX_TRIES - 1 or getattr(e, 'code', None) != 1:
raise | conditional_block |
utils.py | import json
try:
from urllib.parse import urljoin
from urllib.parse import urlencode
except ImportError:
from urlparse import urljoin
from urllib import urlencode
import facepy
from django.conf import settings
from django.utils import timezone
from django.conf import settings
from django.core import s... |
def get_application_graph(version=None):
version = version or FACEBOOK_API_VERSION
token = (facepy.utils
.get_application_access_token(settings.FACEBOOK_APP_ID,
settings.FACEBOOK_APP_SECRET,
api_version=version))... | random_line_split | |
vnstat.py | # -*- coding: utf-8 -*-
"""
Display vnstat statistics.
Coloring rules.
If value is bigger that dict key, status string will turn to color, specified
in the value.
Example:
coloring = {
800: "#dddd00",
900: "#dd0000",
}
(0 - 800: white, 800-900: yellow, >900 - red)
Format of s... |
try:
type, number, ts, rxm, txm, rxk, txk, fill = filter_stat().split(";")
except OSError as e:
print("Looks like you haven't installed or configured vnstat!")
raise e
except ValueError:
err = "vnstat returned wrong output, "
err += "maybe it's configured wrong or m... | if x.startswith("{};0;".format(statistics_type)):
return x | conditional_block |
vnstat.py | # -*- coding: utf-8 -*-
"""
Display vnstat statistics.
Coloring rules.
If value is bigger that dict key, status string will turn to color, specified
in the value.
Example:
coloring = {
800: "#dddd00",
900: "#dd0000",
}
(0 - 800: white, 800-900: yellow, >900 - red)
Format of s... | ():
out = check_output(["vnstat", "--dumpdb"]).decode("utf-8").splitlines()
for x in out:
if x.startswith("{};0;".format(statistics_type)):
return x
try:
type, number, ts, rxm, txm, rxk, txk, fill = filter_stat().split(";")
except OSError as e:
print(... | filter_stat | identifier_name |
vnstat.py | # -*- coding: utf-8 -*-
"""
Display vnstat statistics.
Coloring rules.
If value is bigger that dict key, status string will turn to color, specified
in the value.
Example:
coloring = {
800: "#dddd00",
900: "#dd0000",
}
(0 - 800: white, 800-900: yellow, >900 - red)
Format of s... | keys.sort()
for k in keys:
if stat["total"] < k * 1024 * 1024:
break
else:
color = self.coloring[k]
response = {
'cached_until': time() + self.cache_timeout,
'full_text': self.format.format(
total=se... | def currentSpeed(self, i3s_output_list, i3s_config):
stat = get_stat(self.statistics_type)
color = None
keys = list(self.coloring.keys()) | random_line_split |
vnstat.py | # -*- coding: utf-8 -*-
"""
Display vnstat statistics.
Coloring rules.
If value is bigger that dict key, status string will turn to color, specified
in the value.
Example:
coloring = {
800: "#dddd00",
900: "#dd0000",
}
(0 - 800: white, 800-900: yellow, >900 - red)
Format of s... |
def _divide_and_format(self, value):
"""
Divide a value and return formatted string
"""
value /= self.initial_multi
for i, unit in enumerate(self.units):
if value > self.multiplier_top:
value /= self.unit_multi
else:
b... | """
Format of total, up and down placeholders under FORMAT.
As default, substitutes left_align and precision as %s and %s
Placeholders:
value - value (float)
unit - unit (string)
"""
self.last_stat = get_stat(self.statistics_type)
self.last_time = ... | identifier_body |
art-track.js | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvArtTrack = (props) => (
<SvgIcon {...props}>
<path d="M22 13h-8v-2h8v2zm0-6h-8v2h8V7zm-8 10h8v-2h-8v2zm-2-8v6c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2zm-1.5 6l-2.25-3-1.75 2.26-1.25-1.51L3.5 15h7z"/>
</SvgIcon> | AvArtTrack.muiName = 'SvgIcon';
export default AvArtTrack; | );
AvArtTrack.displayName = 'AvArtTrack'; | random_line_split |
ExecutionRole.tsx | import type { FormikErrors, FormikProps } from 'formik';
import React from 'react';
import type { IWizardPageComponent } from '@spinnaker/core';
import { FormikFormField, FormValidator, TextInput } from '@spinnaker/core';
import { iamRoleValidator } from '../../aws.validators';
import type { IAmazonFunction } from '..... | (values: IAmazonFunctionUpsertCommand): FormikErrors<IAmazonFunctionUpsertCommand> {
const validator = new FormValidator(values);
validator.field('role', 'Role ARN').required().withValidators(iamRoleValidator);
return validator.validateForm();
}
public render() {
return (
<div className="form... | validate | identifier_name |
ExecutionRole.tsx | import type { FormikErrors, FormikProps } from 'formik';
import React from 'react';
import type { IWizardPageComponent } from '@spinnaker/core';
import { FormikFormField, FormValidator, TextInput } from '@spinnaker/core';
import { iamRoleValidator } from '../../aws.validators';
import type { IAmazonFunction } from '..... | } | random_line_split | |
Search.ts | "Add";
source: SubStmt<A>;
}
export interface DeleteDiff {
diffType: "Delete";
source: SubStmt<A>;
}
const generalizedEdits = (
original: SubProg<A>,
editedProgs: SubProg<A>[],
mode: "exact"
): Edit => {
switch (mode) {
case "exact":
return {} as any; // COMBAK: complete the function
}
};
/... |
}
if (!tag) return diff.path.join(".");
else return tag;
};
export const showStmtDiff = (d: StmtDiff): string =>
`Changed ${prettyStmt(d.stmt)} ${d.diffType ? `(${d.diffType})` : ""}: ${
d.originalValue
} (${d.diff.path}) -> ${d.diff.val}`;
export const applyStmtDiff = (
prog: SubProg<A>,
stmtDiff:... | {
tag = currNode.tag;
} | conditional_block |
Search.ts | "Add";
source: SubStmt<A>;
}
export interface DeleteDiff {
diffType: "Delete";
source: SubStmt<A>;
}
const generalizedEdits = (
original: SubProg<A>,
editedProgs: SubProg<A>[],
mode: "exact"
): Edit => {
switch (mode) {
case "exact":
return {} as any; // COMBAK: complete the function
}
};
/... | * @param node the top-level node changed
* @param diff the diff defined for the node
* @returns
*/
const diffType = (node: AbstractNode, diff: rdiffResult): DiffType => {
let tag = undefined;
let currNode: AbstractNode = node;
for (const prop of diff.path) {
currNode = currNode[prop];
if (currNode.tag... |
/**
* Infer the diff type from the AST-level diff by looking up the deepest tagged AST node in the diff path.
* | random_line_split |
eth_pubsub.rs | 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 later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... |
})
.map_err(|e| warn!("Unable to fetch latest logs: {:?}", e))
);
}
}
}
/// A light client wrapper struct.
pub trait LightClient: Send + Sync {
/// Get a recent block header.
fn block_header(&self, id: BlockId) -> Option<encoded::Header>;
/// Fetch logs.
fn logs(&self, filter: EthFilter) -> BoxFutu... | {
Self::notify(&remote, &subscriber, pubsub::Result::Logs(logs));
} | conditional_block |
eth_pubsub.rs | 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 later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... | (
&self,
_meta: Metadata,
subscriber: Subscriber<pubsub::Result>,
kind: pubsub::Kind,
params: Trailing<pubsub::Params>,
) {
match (kind, params.into()) {
(pubsub::Kind::NewHeads, None) => {
self.heads_subscribers.write().push(subscriber)
},
(pubsub::Kind::Logs, Some(pubsub::Params::Logs(filter... | subscribe | identifier_name |
eth_pubsub.rs | 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 later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... |
fn notify_logs<F>(&self, enacted: &[H256], logs: F) where
F: Fn(EthFilter) -> BoxFuture<Vec<Log>, Error>,
{
for &(ref subscriber, ref filter) in self.logs_subscribers.read().values() {
let logs = futures::future::join_all(enacted
.iter()
.map(|hash| {
let mut filter = filter.clone();
filter... | {
for subscriber in self.heads_subscribers.read().values() {
for &(ref header, ref extra_info) in headers {
Self::notify(&self.remote, subscriber, pubsub::Result::Header(RichHeader {
inner: header.into(),
extra_info: extra_info.clone(),
}));
}
}
} | identifier_body |
eth_pubsub.rs | 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 later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WA... | .notify(Ok(result))
.map(|_| ())
.map_err(|e| warn!(target: "rpc", "Unable to send notification: {}", e))
);
}
fn notify_heads(&self, headers: &[(encoded::Header, BTreeMap<String, String>)]) {
for subscriber in self.heads_subscribers.read().values() {
for &(ref header, ref extra_info) in headers {
... | remote.spawn(subscriber | random_line_split |
mutability-inherits-through-fixed-length-vec.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | for i in ints.iter_mut() { *i += 22; }
for i in ints.iter() { assert!(*i == 22); }
}
pub fn main() {
test1();
test2();
} | }
fn test2() {
let mut ints = [0i, ..32]; | random_line_split |
mutability-inherits-through-fixed-length-vec.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test2() {
let mut ints = [0i, ..32];
for i in ints.iter_mut() { *i += 22; }
for i in ints.iter() { assert!(*i == 22); }
}
pub fn main() {
test1();
test2();
}
| {
let mut ints = [0i, ..32];
ints[0] += 1;
assert_eq!(ints[0], 1);
} | identifier_body |
mutability-inherits-through-fixed-length-vec.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut ints = [0i, ..32];
for i in ints.iter_mut() { *i += 22; }
for i in ints.iter() { assert!(*i == 22); }
}
pub fn main() {
test1();
test2();
}
| test2 | identifier_name |
pyku-web.py | #!/usr/bin/python
#
# pyku
# ====
# Python-based random haiku generator
#
# Chris Collins, <collins.christopher@gmail.com>
#
# v0.5 - 2013-11-15
#
# Copyright (C) 2013 Chris Collins
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | syllables += vowelcount
vowelcontext(random_word)
else:
randomword()
def vowelcontext(random_word):
"""
Container module for running through
the list of checks we need to do to count
syllables.
"""
if debug:
print "Going into 'vowelcontext':"
print ... | vowelcount = len(vowels)
if debug:
print vowels
global syllables | random_line_split |
pyku-web.py | #!/usr/bin/python
#
# pyku
# ====
# Python-based random haiku generator
#
# Chris Collins, <collins.christopher@gmail.com>
#
# v0.5 - 2013-11-15
#
# Copyright (C) 2013 Chris Collins
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... |
syldec(1)
if debug:
print "Leaving 'trailing_e':"
print "Number of Syllables, maybe: ", syllables
modcount("trailing_e")
def sylinc(i):
global syllables
syllables += i
def syldec(i):
global syllables
if syllables > 1: # Can't reduce to 0
syllabl... | print trail_e_que
print """
Trailing '-e(s)' or '-que' characters
and no trailing '-ble' or '-ses'.""" | conditional_block |
pyku-web.py | #!/usr/bin/python
#
# pyku
# ====
# Python-based random haiku generator
#
# Chris Collins, <collins.christopher@gmail.com>
#
# v0.5 - 2013-11-15
#
# Copyright (C) 2013 Chris Collins
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | (i):
global syllables
syllables += i
def syldec(i):
global syllables
if syllables > 1: # Can't reduce to 0
syllables -= i
def syleq():
global syllables
syllables = 0
def modcount(mod):
if debug:
print "Leaving '" + mod + "' - "
print "Number of Syllables is, ma... | sylinc | identifier_name |
pyku-web.py | #!/usr/bin/python
#
# pyku
# ====
# Python-based random haiku generator
#
# Chris Collins, <collins.christopher@gmail.com>
#
# v0.5 - 2013-11-15
#
# Copyright (C) 2013 Chris Collins
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... |
def syldec(i):
global syllables
if syllables > 1: # Can't reduce to 0
syllables -= i
def syleq():
global syllables
syllables = 0
def modcount(mod):
if debug:
print "Leaving '" + mod + "' - "
print "Number of Syllables is, maybe: ", syllables
app = web.application(ur... | global syllables
syllables += i | identifier_body |
CopyFiles.py | from __future__ import print_function
from Components.Task import PythonTask, Task, Job, job_manager as JobManager
from Tools.Directories import fileExists
from enigma import eTimer | self.fileList = fileList
def work(self):
print("[DeleteFolderTask] files ", self.fileList)
errors = []
try:
rmtree(self.fileList)
except Exception as e:
errors.append(e)
if errors:
raise errors[0]
class CopyFileJob(Job):
def __init__(self, srcfile, destfile, name):
Job.__init__(self, _("Copyi... | from os import path
from shutil import rmtree, copy2, move
class DeleteFolderTask(PythonTask):
def openFiles(self, fileList): | random_line_split |
CopyFiles.py | from __future__ import print_function
from Components.Task import PythonTask, Task, Job, job_manager as JobManager
from Tools.Directories import fileExists
from enigma import eTimer
from os import path
from shutil import rmtree, copy2, move
class DeleteFolderTask(PythonTask):
def openFiles(self, fileList):
self.fil... |
def deleteFiles(fileList, name):
job = Job(_("Deleting files"))
task = DeleteFolderTask(job, name)
task.openFiles(fileList)
JobManager.AddJob(job)
| if path.isdir(src) or int(path.getsize(src))/1000/1000 > 100:
JobManager.AddJob(MoveFileJob(src, dst, name))
else:
move(src, dst) | conditional_block |
CopyFiles.py | from __future__ import print_function
from Components.Task import PythonTask, Task, Job, job_manager as JobManager
from Tools.Directories import fileExists
from enigma import eTimer
from os import path
from shutil import rmtree, copy2, move
class DeleteFolderTask(PythonTask):
def openFiles(self, fileList):
self.fil... | job = Job(_("Deleting files"))
task = DeleteFolderTask(job, name)
task.openFiles(fileList)
JobManager.AddJob(job) | identifier_body | |
CopyFiles.py | from __future__ import print_function
from Components.Task import PythonTask, Task, Job, job_manager as JobManager
from Tools.Directories import fileExists
from enigma import eTimer
from os import path
from shutil import rmtree, copy2, move
class DeleteFolderTask(PythonTask):
def openFiles(self, fileList):
self.fil... | (fileList, name):
job = Job(_("Deleting files"))
task = DeleteFolderTask(job, name)
task.openFiles(fileList)
JobManager.AddJob(job)
| deleteFiles | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.