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 |
|---|---|---|---|---|
line.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* 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 3 of the License, or
* (at your option) any later ve... |
fn clear_excess(&mut self) {
while self.entries.len() > self.capacity {
self.entries.pop_front();
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
fn add(&mut self, item: String) {
self.entries.push_back(Line::new(item));
}
}
impl Extend<Stri... | {
LineCollection {
entries: VecDeque::new(),
capacity: capacity,
}
} | identifier_body |
line.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* 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 3 of the License, or
* (at your option) any later ve... |
FilterParserResult::Invalid(append) => {
self.pending.clear();
if append {
self.pending.push(line);
}
}
FilterParserResult::NoMatch => {}
}
... | {
match_found = true;
if append {
self.pending.push(line);
}
break;
} | conditional_block |
deriving-cmp-generic-struct.rs | // Copyright 2013 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 s1 = S {x: 1, y: 1};
let s2 = S {x: 1, y: 2};
// in order for both Ord and TotalOrd
let ss = [s1, s2];
for (i, s1) in ss.iter().enumerate() {
for (j, s2) in ss.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let lt = i < j;
... | identifier_body | |
deriving-cmp-generic-struct.rs | // Copyright 2013 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 ... | y: T
}
pub fn main() {
let s1 = S {x: 1, y: 1};
let s2 = S {x: 1, y: 2};
// in order for both Ord and TotalOrd
let ss = [s1, s2];
for (i, s1) in ss.iter().enumerate() {
for (j, s2) in ss.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
le... | #[deriving(Eq, TotalEq, Ord, TotalOrd)]
struct S<T> {
x: T, | random_line_split |
deriving-cmp-generic-struct.rs | // Copyright 2013 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 s1 = S {x: 1, y: 1};
let s2 = S {x: 1, y: 2};
// in order for both Ord and TotalOrd
let ss = [s1, s2];
for (i, s1) in ss.iter().enumerate() {
for (j, s2) in ss.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let lt = i < j;
... | main | identifier_name |
scp_utils.py | __author__ = 'cmantas'
#python ssh lib
import paramiko
import string
import sys
from socket import error as socketError
sys.path.append('lib/scp.py')
from lib.scp import SCPClient
from datetime import datetime, timedelta
from lib.persistance_module import env_vars, home
from time import time
import sys, traceback
ssh... | (host, user, files, remote_path='.', recursive=False):
"""
puts the specified file to the specified host
:param host:
:param user:
:param files:
:param remote_path:
:param recursive:
:return:
"""
ssh_giveup_timeout = env_vars['ssh_giveup_timeout']
private_key = paramiko.RSAK... | put_file_scp | identifier_name |
scp_utils.py | __author__ = 'cmantas'
#python ssh lib
import paramiko
import string
import sys
from socket import error as socketError
sys.path.append('lib/scp.py')
from lib.scp import SCPClient
from datetime import datetime, timedelta
from lib.persistance_module import env_vars, home
from time import time
import sys, traceback
ssh... |
@staticmethod
def get_timer():
timer = Timer()
timer.start()
return timer | end_time = int(round(time() * 1000))
if self.started is False:
print " Timer had not been started"
return 0.0
start_time = self.start_time
self.start_time = 0
self.started = False
return float(end_time - start_time)/1000 | identifier_body |
scp_utils.py | __author__ = 'cmantas'
#python ssh lib
import paramiko
import string
import sys
from socket import error as socketError
sys.path.append('lib/scp.py')
from lib.scp import SCPClient
from datetime import datetime, timedelta
from lib.persistance_module import env_vars, home
from time import time
import sys, traceback
ssh... | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, timeout=ssh_giveup_timeout, pkey=private_key)
scpc=SCPClient(ssh.get_transport())
scpc.put(files, remote_path, recursive)
ssh.close()
def test_ssh(host, user, logger=None):
ssh_giveup_timeout = env_vars[... | :return:
"""
ssh_giveup_timeout = env_vars['ssh_giveup_timeout']
private_key = paramiko.RSAKey.from_private_key_file(env_vars["priv_key_path"])
ssh = paramiko.SSHClient() | random_line_split |
scp_utils.py | __author__ = 'cmantas'
#python ssh lib
import paramiko
import string
import sys
from socket import error as socketError
sys.path.append('lib/scp.py')
from lib.scp import SCPClient
from datetime import datetime, timedelta
from lib.persistance_module import env_vars, home
from time import time
import sys, traceback
ssh... |
timer = Timer.get_timer()
try:
ssh.connect(host, username=user, timeout=ssh_timeout, pkey=private_key, allow_agent=False, look_for_keys=False)
if not logger is None:
logger.debug("connected in %d sec. now Running SSH command" % timer.stop())
timer.start()
### EX... | logger.debug("Connecting to SSH") | conditional_block |
BottomSection.test.tsx | import React from 'react';
import { shallow } from 'enzyme';
import BottomSection from './BottomSection';
jest.mock('../../config', () => ({
bootData: {
navTree: [
{
id: 'profile',
hideFromMenu: true,
},
{
hideFromMenu: true,
},
{
hideFromMenu: false, | },
{
hideFromMenu: true,
},
],
},
user: {
orgCount: 5,
orgName: 'Grafana',
},
}));
jest.mock('app/core/services/context_srv', () => ({
contextSrv: {
sidemenu: true,
isSignedIn: false,
isGrafanaAdmin: false,
hasEditPermissionFolders: false,
},
}));
descri... | random_line_split | |
index.d.ts | // Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/80060c94ef549c077a011977c2b5461bd0fd8947/electron-devtools-installer/index.d.ts
declare module "electron-devtools-installer" {
interface ExtensionReference {
id: string,
electron: string,
}
... | export const BACKBONE_DEBUGGER: ExtensionReference;
export const JQUERY_DEBUGGER: ExtensionReference;
export const ANGULARJS_BATARANG: ExtensionReference;
export const VUEJS_DEVTOOLS: ExtensionReference;
export const REDUX_DEVTOOLS: ExtensionReference;
export const REACT_PERF: ExtensionReference... | random_line_split | |
mod.rs | //! Thrift generated Jaeger client
//!
//! Definitions: <https://github.com/uber/jaeger-idl/blob/master/thrift/>
use std::time::{Duration, SystemTime};
use opentelemetry::trace::Event;
use opentelemetry::{Key, KeyValue, Value};
pub(crate) mod agent;
pub(crate) mod jaeger;
pub(crate) mod zipkincore;
impl From<super::... | (process: super::Process) -> jaeger::Process {
jaeger::Process::new(
process.service_name,
Some(process.tags.into_iter().map(Into::into).collect()),
)
}
}
impl From<Event> for jaeger::Log {
fn from(event: crate::exporter::Event) -> jaeger::Log {
let timestamp = e... | from | identifier_name |
mod.rs | //! Thrift generated Jaeger client
//!
//! Definitions: <https://github.com/uber/jaeger-idl/blob/master/thrift/>
use std::time::{Duration, SystemTime};
use opentelemetry::trace::Event;
use opentelemetry::{Key, KeyValue, Value};
|
impl From<super::Process> for jaeger::Process {
fn from(process: super::Process) -> jaeger::Process {
jaeger::Process::new(
process.service_name,
Some(process.tags.into_iter().map(Into::into).collect()),
)
}
}
impl From<Event> for jaeger::Log {
fn from(event: crate:... | pub(crate) mod agent;
pub(crate) mod jaeger;
pub(crate) mod zipkincore; | random_line_split |
mod.rs | //! Thrift generated Jaeger client
//!
//! Definitions: <https://github.com/uber/jaeger-idl/blob/master/thrift/>
use std::time::{Duration, SystemTime};
use opentelemetry::trace::Event;
use opentelemetry::{Key, KeyValue, Value};
pub(crate) mod agent;
pub(crate) mod jaeger;
pub(crate) mod zipkincore;
impl From<super::... |
}
#[rustfmt::skip]
impl From<KeyValue> for jaeger::Tag {
fn from(kv: KeyValue) -> jaeger::Tag {
let KeyValue { key, value } = kv;
match value {
Value::String(s) => jaeger::Tag::new(key.into(), jaeger::TagType::String, Some(s.into()), None, None, None, None),
Value::F64(f) =... | {
let timestamp = event
.timestamp
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_micros() as i64;
let mut event_set_via_attribute = false;
let mut fields = event
.attributes
.into_it... | identifier_body |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RReprex(RPackage):
| """Convenience wrapper that uses the 'rmarkdown' package to render small
snippets of code to target formats that include both code and output.
The goal is to encourage the sharing of small, reproducible, and
runnable examples on code-oriented websites, such as
<http://stackoverflow.com> and ... | identifier_body | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RReprex(RPackage):
"""Convenience wrapper that uses the 'rmarkdown' package to render smal... | depends_on('r-withr', when='@0.2.0:', type=('build', 'run'))
depends_on('r-fs', when='@0.2.1:', type=('build', 'run'))
depends_on('pandoc@1.12.3:') | depends_on('r-rmarkdown', type=('build', 'run'))
depends_on('r-whisker', type=('build', 'run'))
depends_on('r-rlang', when='@0.2.0:', type=('build', 'run')) | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (RPackage):
"""Convenience wrapper that uses the 'rmarkdown' package to render small
snippets of code to target formats that include both code and output.
The goal is to encourage the sharing of small, reproducible, and
runnable examples on code-oriented websites, such as
<http://stackov... | RReprex | identifier_name |
takeaway.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
from db.event import Event
from db.player import Player
from db.team import Team
class Takeaway(Base, SpecificEvent):
__tablename__ = 'takeaways'
__autoload__ = True
HUMAN_RE... | (self, event_id, data_dict):
self.takeaway_id = uuid.uuid4().urn
self.event_id = event_id
for attr in self.STANDARD_ATTRS:
if attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
setattr(self, attr, None)
def __str__(self):
... | __init__ | identifier_name |
takeaway.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
from db.event import Event
from db.player import Player
from db.team import Team
class Takeaway(Base, SpecificEvent):
__tablename__ = 'takeaways'
__autoload__ = True
HUMAN_RE... |
def __str__(self):
plr = Player.find_by_id(self.player_id)
event = Event.find_by_id(self.event_id)
team = Team.find_by_id(self.team_id)
return "Takeaway: %s (%s) - %s" % (
plr.name, team.abbr, event)
| if attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
setattr(self, attr, None) | conditional_block |
takeaway.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
from db.event import Event
from db.player import Player
from db.team import Team
class Takeaway(Base, SpecificEvent):
__tablename__ = 'takeaways'
__autoload__ = True
HUMAN_RE... | plr = Player.find_by_id(self.player_id)
event = Event.find_by_id(self.event_id)
team = Team.find_by_id(self.team_id)
return "Takeaway: %s (%s) - %s" % (
plr.name, team.abbr, event) | random_line_split | |
takeaway.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
from db.event import Event
from db.player import Player
from db.team import Team
class Takeaway(Base, SpecificEvent):
__tablename__ = 'takeaways'
__autoload__ = True
HUMAN_RE... | plr = Player.find_by_id(self.player_id)
event = Event.find_by_id(self.event_id)
team = Team.find_by_id(self.team_id)
return "Takeaway: %s (%s) - %s" % (
plr.name, team.abbr, event) | identifier_body | |
main.rs | #[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn counting_sort(array: &mut [i32], min: i32, max: i32) {
// nothing to do for arrays shorter than 2
if array.len() < 2 {
return;
}
// we count occurences of values
let size = (max - min + 1) as usize;
let mut count = vec![0; siz... | () {
let numbers = &mut [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];
check_sort(numbers, -31, 782);
}
#[test]
fn one_element_vector() {
let numbers = &mut [0i32];
check_sort(numbers, 0, 0);
}
#[test]
fn repeat_vector() {
let numbers = &mut [1i32, 1, 1, 1, 1... | rosetta_vector | identifier_name |
main.rs | #[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn counting_sort(array: &mut [i32], min: i32, max: i32) {
// nothing to do for arrays shorter than 2
if array.len() < 2 {
return;
}
// we count occurences of values
let size = (max - min + 1) as usize; | count[(*e - min) as usize] += 1;
}
// then we write values back, sorted
let mut index = 0;
for value in 0..count.len() {
for _ in 0..count[value] {
array[index] = value as i32;
index += 1;
}
}
}
fn main() {
let mut numbers = [4i32, 65, 2, -31, 0,... | let mut count = vec![0; size];
for e in array.iter() { | random_line_split |
main.rs | #[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn counting_sort(array: &mut [i32], min: i32, max: i32) {
// nothing to do for arrays shorter than 2
if array.len() < 2 {
return;
}
// we count occurences of values
let size = (max - min + 1) as usize;
let mut count = vec![0; siz... |
#[test]
fn worst_case_vector() {
let numbers = &mut [20i32, 10, 0, -1, -5];
check_sort(numbers, -5, 20);
}
#[test]
fn already_sorted_vector() {
let numbers = &mut [-1i32, 0, 3, 6, 99];
check_sort(numbers, -1, 99);
}
#[test]
#[should_panic]
fn bad_m... | {
let numbers = &mut [1i32, 1, 1, 1, 1];
check_sort(numbers, 1, 1);
} | identifier_body |
main.rs | #[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn counting_sort(array: &mut [i32], min: i32, max: i32) {
// nothing to do for arrays shorter than 2
if array.len() < 2 |
// we count occurences of values
let size = (max - min + 1) as usize;
let mut count = vec![0; size];
for e in array.iter() {
count[(*e - min) as usize] += 1;
}
// then we write values back, sorted
let mut index = 0;
for value in 0..count.len() {
for _ in 0..count[valu... | {
return;
} | conditional_block |
angular-sanitize.js | /**
* @license AngularJS v1.2.3
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $sanitizeMinErr = angular.$$minErr('$sanitize');
/**
* @ngdoc overview
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module ... | ( html, handler ) {
var index, chars, match, stack = [], last = html;
stack.last = function() { return stack[ stack.length - 1 ]; };
while ( html ) {
chars = true;
// Make sure we're not in a script or style element
if ( !stack.last() || !specialElements[ stack.last() ] ) {
// Comment
i... | htmlParser | identifier_name |
angular-sanitize.js | /**
* @license AngularJS v1.2.3
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $sanitizeMinErr = angular.$$minErr('$sanitize');
/**
* @ngdoc overview
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module ... | <div ng-controller="Ctrl">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td... | $scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}
</script> | random_line_split |
angular-sanitize.js | /**
* @license AngularJS v1.2.3
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $sanitizeMinErr = angular.$$minErr('$sanitize');
/**
* @ngdoc overview
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module ... |
}
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
var hiddenPre=document.createElement("pre");
function decodeEntities(value) {
if (!value) {
return '';
}
// Note: IE8 does not preserve spaces at the start/end of innerHTML
var spaceR... | {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if ( tagName )
// Find the closest opened tag of the same type
for ( pos = stack.length - 1; pos >= 0; pos-- )
if ( stack[ pos ] == tagName )
break;
if ( pos >= 0 ) {
// Close all the open elements, up the stack... | identifier_body |
inspectdb.py | from __future__ import unicode_literals
import keyword
import re
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.utils import six
class Command(NoArgsCommand):
help = "Introspects the database tab... | (self, options):
connection = connections[options.get('database')]
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')
table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
strip_prefix =... | handle_inspection | identifier_name |
inspectdb.py | from __future__ import unicode_literals
import keyword
import re
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.utils import six
class Command(NoArgsCommand):
help = "Introspects the database tab... |
def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_not... | connection = connections[options.get('database')]
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')
table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
strip_prefix = lambda s: s.startswith("... | identifier_body |
inspectdb.py | from __future__ import unicode_literals
import keyword
import re
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.utils import six
class Command(NoArgsCommand):
help = "Introspects the database tab... |
new_name, num_repl = re.subn(r'\W', '_', new_name)
if num_repl > 0:
field_notes.append('Field renamed to remove unsuitable characters.')
if new_name.find('__') >= 0:
while new_name.find('__') >= 0:
new_name = new_name.replace('__', '_')
if c... | if new_name.endswith('_id'):
new_name = new_name[:-3]
else:
field_params['db_column'] = col_name | conditional_block |
inspectdb.py | from __future__ import unicode_literals
import keyword
import re
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.utils import six
class Command(NoArgsCommand):
help = "Introspects the database tab... | db_module = 'django.db'
def handle_noargs(self, **options):
try:
for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line)
except NotImplementedError:
raise CommandError("Database inspection isn't supported for the currently selected d... | 'introspect. Defaults to using the "default" database.'),
)
requires_model_validation = False
| random_line_split |
MapAddIndexCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* 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 ... | (name: string, indexConfig: InternalIndexConfig): ClientMessage {
const clientMessage = ClientMessage.createForEncode();
clientMessage.setRetryable(false);
const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
clientMessage.addFrame(initialFrame);
clientMess... | encodeRequest | identifier_name |
MapAddIndexCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* 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 ... | } | IndexConfigCodec.encode(clientMessage, indexConfig);
return clientMessage;
} | random_line_split |
MapAddIndexCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* 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 ... |
}
| {
const clientMessage = ClientMessage.createForEncode();
clientMessage.setRetryable(false);
const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
clientMessage.addFrame(initialFrame);
clientMessage.setMessageType(REQUEST_MESSAGE_TYPE);
clientMessage.... | identifier_body |
TableHead.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var _extends2 = _int... | }, other)));
});
process.env.NODE_ENV !== "production" ? TableHead.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----... | role: Component === defaultComponent ? null : 'rowgroup' | random_line_split |
jstool.py | #!/usr/bin/python
import os
import sys
import argparse
import requests
import subprocess | class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbose = False
def log(self, string):
if self.verbose:
print string
console = Con... | import shutil
| random_line_split |
jstool.py | #!/usr/bin/python
import os
import sys
import argparse
import requests
import subprocess
import shutil
class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbos... |
else:
console.log('- line ' + str(index) + ': ' + bcolors.FAIL + line.lstrip().rstrip() + bcolors.ENDC)
# no filters
else:
outfile.write(line)
# newline
outfile.write("\n"... | outfile.write(line) | conditional_block |
jstool.py | #!/usr/bin/python
import os
import sys
import argparse
import requests
import subprocess
import shutil
class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbos... | (argv):
parser = argparse.ArgumentParser()
parser.add_argument('-v, --verbose', dest='verbose', default=False, action='store_true', help='detailed program output')
parser.add_argument('-i, --input', required=True, dest='input_file', type=str, help='input file (required), containing one filename per line to ... | main | identifier_name |
jstool.py | #!/usr/bin/python
import os
import sys
import argparse
import requests
import subprocess
import shutil
class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbos... |
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('-v, --verbose', dest='verbose', default=False, action='store_true', help='detailed program output')
parser.add_argument('-i, --input', required=True, dest='input_file', type=str, help='input file (required), containing one filename pe... | SERVICE_URL = 'http://closure-compiler.appspot.com/compile'
console.log('compiling with google closure API: ' + SERVICE_URL)
with open(filename, 'r') as file:
javascript = file.read()
data = {
'js_code': javascript,
'output_format': 'text',
'output_info': 'compiled_code',
... | identifier_body |
struct-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
Case1 { a: u64, b: u16, c: u16, d: u16, e: u16},
Case2 { a: u64, b: u32, c: u32},
Case3 { a: u64, b: u64 }
}
enum Univariant {
TheOnlyCase { a: i64 }
}
fn main() {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each in... | Regular | identifier_name |
struct-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular {
Case1 { a: u64, b: u16, c: u16, d: u16, e: u16},
Case2 { a: u64, b: u32, c: u32},
Case3 { a: u64, b: u64 }
}
enum Univariant {
TheOnly... |
#![allow(unused_variable)]
#![feature(struct_variant)]
// The first element is to ensure proper alignment, irrespective of the machines word size. Since | random_line_split |
template.py | #!/usr/bin/env python
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()',
'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
def compile(self, template):
python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % p... |
args.append(self.parse(tokens))
raise SyntaxError, "missing closing '%s'" % delimiter
templates = Templates()
t = templates.compile("<")
| tokens.pop(0)
return args | conditional_block |
template.py | #!/usr/bin/env python
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()',
'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
def compile(self, template):
python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % p... | (self, tokens, delimiter):
args = []
while tokens:
if tokens[0] == delimiter:
tokens.pop(0)
return args
args.append(self.parse(tokens))
raise SyntaxError, "missing closing '%s'" % delimiter
templates = Templates()
t = templates.compile("<")
| parse_args | identifier_name |
template.py | #!/usr/bin/env python
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()', | def compile(self, template):
python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % python)
def parse(self, tokens):
t = tokens.pop(0)
if t in '([':
if t == '(':
label = "'%s'" % tokens.pop(0)
args = self.parse_args(tokens, ')')
elif s[0] == '['... | 'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
| random_line_split |
template.py | #!/usr/bin/env python
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()',
'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
def compile(self, template):
|
def parse(self, tokens):
t = tokens.pop(0)
if t in '([':
if t == '(':
label = "'%s'" % tokens.pop(0)
args = self.parse_args(tokens, ')')
elif s[0] == '[':
label = 'None'
args = self.parse_args(tokens, ']')
return 'PTB(_n, %s, %s)' % (label, ', '.join(args))
... | python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % python) | identifier_body |
inspect-drawer.spec.ts | import { e2e } from '@grafana/e2e';
const PANEL_UNDER_TEST = '2 yaxis and axis labels';
e2e.scenario({
describeName: 'Inspect drawer tests',
itName: 'Tests various Inspect Drawer scenarios',
addScenarioDataSource: false,
addScenarioDashBoard: false,
skipScenario: false,
scenario: () => {
// @ts-ignore... | // drawer should take up the whole screen
e2e.components.Drawer.General.rcContentWrapper()
.should('be.visible')
.should('have.css', 'width', `${viewPortWidth}px`);
// try contract button
e2e.components.Drawer.General.contract().click();
e2e.components.Drawer.General.expand().should('be.visible');
... | random_line_split | |
inspect-drawer.spec.ts | import { e2e } from '@grafana/e2e';
const PANEL_UNDER_TEST = '2 yaxis and axis labels';
e2e.scenario({
describeName: 'Inspect drawer tests',
itName: 'Tests various Inspect Drawer scenarios',
addScenarioDataSource: false,
addScenarioDashBoard: false,
skipScenario: false,
scenario: () => {
// @ts-ignore... |
return true;
});
const viewPortWidth = e2e.config().viewportWidth;
e2e.flows.openDashboard({ uid: '5SdHCadmz' });
// testing opening inspect drawer directly by clicking on Inspect in header menu
e2e.flows.openPanelMenuItem(e2e.flows.PanelMenuItems.Inspect, PANEL_UNDER_TEST);
expectDra... | {
// On occasion monaco editor will not have the time to be properly unloaded when we change the tab
// and then the e2e test fails with the uncaught:exception:
// TypeError: Cannot read property 'getText' of null
// at Object.ai [as getFoldingRanges] (http://localhost:3001/public/bu... | conditional_block |
parameters.rs | use http_types::Method;
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub enum Parameters {
Query(String),
Body(String),
}
use std::{
iter::Map,
slice::Iter,
};
// This newtype is currently only used internally here, but we might want to move it elsewhere where
// it could be more useful because of g... | (method: &Method) -> bool {
match *method {
Method::GET | Method::HEAD | Method::DELETE => false,
_ => true,
}
}
pub fn path_and_query<'p>(&self, path: &'p str) -> Cow<'p, str> {
self.query().map_or_else(|| Cow::Borrowed(path),
|q... | method_requires_body | identifier_name |
parameters.rs | use http_types::Method;
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub enum Parameters {
Query(String),
Body(String),
}
use std::{
iter::Map,
slice::Iter,
};
// This newtype is currently only used internally here, but we might want to move it elsewhere where
// it could be more useful because of g... |
}
| {
let params_str = (1..10).map(|i| (format!("unakey{}", i), format!("unvalor{}", i)))
.collect::<Vec<_>>();
let params = params_str.iter()
.map(|(k, v)| (k.as_str().into(), v.as_str()))
.collect::<Vec<(Cow<str... | identifier_body |
parameters.rs | use http_types::Method;
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub enum Parameters {
Query(String),
Body(String),
}
use std::{
iter::Map,
slice::Iter,
};
// This newtype is currently only used internally here, but we might want to move it elsewhere where
// it could be more useful because of g... | fn params_to_query<S: AsRef<str>>(params: &[(Cow<str>, S)]) -> String {
Self::params_to_vec(params).join("&")
}
}
#[cfg(all(test, feature = "nightly"))]
mod benches {
use super::*;
use test::Bencher;
#[bench]
fn bench_params_to_query(b: &mut Bencher) {
let params_str = (1..10).... | Self::params_to_string_collection(params).collect()
}
| random_line_split |
total_count.rs | use collectors::{Collector, DocumentMatch};
#[derive(Debug)]
pub struct TotalCountCollector {
total_count: u64,
}
impl TotalCountCollector {
pub fn new() -> TotalCountCollector {
TotalCountCollector {
total_count: 0,
}
}
pub fn get_total_count(&self) -> u64 {
self.... |
#[cfg(test)]
mod tests {
use collectors::{Collector, DocumentMatch};
use super::TotalCountCollector;
#[test]
fn test_total_count_collector_inital_state() {
let collector = TotalCountCollector::new();
assert_eq!(collector.get_total_count(), 0);
}
#[test]
fn test_total_coun... |
fn collect(&mut self, _doc: DocumentMatch) {
self.total_count += 1;
}
} | random_line_split |
total_count.rs | use collectors::{Collector, DocumentMatch};
#[derive(Debug)]
pub struct TotalCountCollector {
total_count: u64,
}
impl TotalCountCollector {
pub fn new() -> TotalCountCollector {
TotalCountCollector {
total_count: 0,
}
}
pub fn get_total_count(&self) -> u64 {
self.... | () {
let collector = TotalCountCollector::new();
assert_eq!(collector.needs_score(), false);
}
#[test]
fn test_total_count_collector_collect() {
let mut collector = TotalCountCollector::new();
collector.collect(DocumentMatch::new_unscored(0));
collector.collect(Doc... | test_total_count_collector_needs_score | identifier_name |
typedefs.obj.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy | * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*,... | * of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | random_line_split |
DialogFooter.tsx | import { forwardRef, HTMLAttributes } from "react";
import cn from "classnames";
import { bem } from "@react-md/utils";
/**
* An optional alignment for the content within the footer. Since the majority
* of dialog footers are used to contain action buttons, the default alignment
* is near the end.
*
* @remarks \@... | (
block("footer", {
flex: align !== "none",
"flex-v": align === "stacked-start" || align === "stacked-end",
start: align === "start" || align === "stacked-start",
between: align === "between",
end: align === "end" || align === "stacked-end",
... | cn | identifier_name |
DialogFooter.tsx | import { forwardRef, HTMLAttributes } from "react";
import cn from "classnames";
import { bem } from "@react-md/utils";
/**
* An optional alignment for the content within the footer. Since the majority
* of dialog footers are used to contain action buttons, the default alignment
* is near the end.
*
* @remarks \@... |
</footer>
);
}
);
| {children} | identifier_body |
DialogFooter.tsx | import { forwardRef, HTMLAttributes } from "react";
import cn from "classnames";
import { bem } from "@react-md/utils";
/**
* An optional alignment for the content within the footer. Since the majority
* of dialog footers are used to contain action buttons, the default alignment
* is near the end.
*
* @remarks \@... | flex: align !== "none",
"flex-v": align === "stacked-start" || align === "stacked-end",
start: align === "start" || align === "stacked-start",
between: align === "between",
end: align === "end" || align === "stacked-end",
}),
className
... | <footer
{...props}
ref={ref}
className={cn(
block("footer", { | random_line_split |
region_BM.py | """Auto-generated file, do not edit by hand. BM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BM = PhoneMetadata(id='BM', country_code=1, international_prefix='011',
general_desc=PhoneNumberDesc(national_number_pattern='(?:441|[58]\\d\\d|900)\\d{7}', possible_l... | mobile_number_portable_region=True) | random_line_split | |
test_buffers_cleaning.py | from plenum.common.event_bus import InternalBus
from plenum.common.startable import Mode
from plenum.common.timer import QueueTimer
from plenum.common.util import get_utc_epoch
from plenum.server.consensus.primary_selector import RoundRobinConstantNodesPrimariesSelector
from plenum.server.database_manager import Databa... |
# gc is called after stable checkpoint, since no request executed
# in this test starting it manually
replica._ordering_service.gc(100)
# Requests with view lower then previous view
# should not be in ordered
assert len(replica._ordering_service.ordered) == len(total[num_requests_per_view:])
... | for seqNo in range(num_requests_per_view):
reqId = viewNo, seqNo
replica._ordering_service._add_to_ordered(*reqId)
total.append(reqId) | conditional_block |
test_buffers_cleaning.py | from plenum.common.event_bus import InternalBus
from plenum.common.startable import Mode
from plenum.common.timer import QueueTimer
from plenum.common.util import get_utc_epoch
from plenum.server.consensus.primary_selector import RoundRobinConstantNodesPrimariesSelector
from plenum.server.database_manager import Databa... | node.viewNo += 1
replica._consensus_data.view_no = node.viewNo
replica.primaryName = "Node2:0"
assert list(replica.primaryNames.items()) == \
[(0, "Node1:0"), (1, "Node2:0")]
node.viewNo += 1
replica._consensus_data.view_no = node.viewNo
replica.primaryName = "Node3:0"
assert... |
replica.primaryName = "Node1:0"
assert list(replica.primaryNames.items()) == \
[(0, "Node1:0")]
| random_line_split |
test_buffers_cleaning.py | from plenum.common.event_bus import InternalBus
from plenum.common.startable import Mode
from plenum.common.timer import QueueTimer
from plenum.common.util import get_utc_epoch
from plenum.server.consensus.primary_selector import RoundRobinConstantNodesPrimariesSelector
from plenum.server.database_manager import Databa... | (tconf):
global_view_no = 2
node = FakeSomething(
name="fake node",
ledger_ids=[0],
viewNo=global_view_no,
utc_epoch=get_utc_epoch,
get_validators=lambda: [],
db_manager=DatabaseManager(),
requests=[],
mode=Mode.participating,
timer=QueueT... | test_ordered_cleaning | identifier_name |
test_buffers_cleaning.py | from plenum.common.event_bus import InternalBus
from plenum.common.startable import Mode
from plenum.common.timer import QueueTimer
from plenum.common.util import get_utc_epoch
from plenum.server.consensus.primary_selector import RoundRobinConstantNodesPrimariesSelector
from plenum.server.database_manager import Databa... | node = FakeSomething(
name="fake node",
ledger_ids=[0],
viewNo=0,
utc_epoch=get_utc_epoch,
get_validators=lambda: [],
db_manager=DatabaseManager(),
requests=[],
mode=Mode.participating,
timer=QueueTimer(),
quorums=Quorums(4),
write_... | identifier_body | |
destructure-trait-ref.rs | // The regression test for #15031 to make sure destructuring trait
// reference work properly.
#![feature(box_patterns)]
#![feature(box_syntax)]
trait T { fn foo(&self) | }
impl T for isize {}
fn main() {
// For an expression of the form:
//
// let &...&x = &..&SomeTrait;
//
// Say we have n `&` at the left hand and m `&` right hand, then:
// if n < m, we are golden;
// if n == m, it's a derefing non-derefable type error;
// if n > m, it's a type m... | {} | identifier_body |
destructure-trait-ref.rs | // The regression test for #15031 to make sure destructuring trait
// reference work properly.
#![feature(box_patterns)]
#![feature(box_syntax)]
trait T { fn | (&self) {} }
impl T for isize {}
fn main() {
// For an expression of the form:
//
// let &...&x = &..&SomeTrait;
//
// Say we have n `&` at the left hand and m `&` right hand, then:
// if n < m, we are golden;
// if n == m, it's a derefing non-derefable type error;
// if n > m, it'... | foo | identifier_name |
destructure-trait-ref.rs | // The regression test for #15031 to make sure destructuring trait
// reference work properly.
#![feature(box_patterns)] | trait T { fn foo(&self) {} }
impl T for isize {}
fn main() {
// For an expression of the form:
//
// let &...&x = &..&SomeTrait;
//
// Say we have n `&` at the left hand and m `&` right hand, then:
// if n < m, we are golden;
// if n == m, it's a derefing non-derefable type error;
... | #![feature(box_syntax)]
| random_line_split |
detector.ts | import { BrowserDetectInfo, OsDefinition, OsDefinitionInterface } from './browser-detect.interface';
import { browsers, os, osVersions } from './definitions';
import { mobilePrefixRegExp, mobileRegExp } from './regexp';
import Process = NodeJS.Process;
export class Detector {
private userAgent: string;
public... | }
private checkBrowser(): BrowserDetectInfo {
return browsers
.filter(definition => (<RegExp>definition[1]).test(this.userAgent))
.map(definition => {
const match = (<RegExp>definition[1]).exec(this.userAgent);
const version = match && match[1].sp... | random_line_split | |
detector.ts | import { BrowserDetectInfo, OsDefinition, OsDefinitionInterface } from './browser-detect.interface';
import { browsers, os, osVersions } from './definitions';
import { mobilePrefixRegExp, mobileRegExp } from './regexp';
import Process = NodeJS.Process;
export class Detector {
private userAgent: string;
public... |
private handleMissingError() {
throw new Error('Please give user-agent.\n> browser(navigator.userAgent or res.headers[\'user-agent\']).');
}
}
| {
const definitionInterface = <OsDefinitionInterface>definition;
return (
typeof definition === 'string'
? <string>definition
: undefined
) ||
definitionInterface.pattern ||
definitionInterface.name;
} | identifier_body |
detector.ts | import { BrowserDetectInfo, OsDefinition, OsDefinitionInterface } from './browser-detect.interface';
import { browsers, os, osVersions } from './definitions';
import { mobilePrefixRegExp, mobileRegExp } from './regexp';
import Process = NodeJS.Process;
export class Detector {
private userAgent: string;
public... | (definition: OsDefinition): string {
const definitionInterface = <OsDefinitionInterface>definition;
return (
typeof definition === 'string'
? <string>definition
: undefined
) ||
definitionInterface.pattern ||
definitionInterface.name;
... | getOsPattern | identifier_name |
lib.rs | // Helianto -- static website generator
// Copyright © 2015-2016 Mickaël RAYBAUD-ROIG
//
// 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 version 3 of the License, or
// (at your... | mut self) -> Result<()> {
self.check_settings()?;
self.load_templates()?;
let entries = WalkDir::new(&self.settings.source_dir)
.min_depth(1)
.max_depth(self.settings.max_depth)
.follow_links(self.settings.follow_links)
.into_iter();
for ... | n(& | identifier_name |
lib.rs | // Helianto -- static website generator
// Copyright © 2015-2016 Mickaël RAYBAUD-ROIG
//
// 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 version 3 of the License, or
// (at your... | .and_then(|_| {
self.documents.insert(
dest.to_str().unwrap().into(),
Rc::new(document.metadata.clone()),
);
Ok(())
})
}
fn copy_file(&mut self, path: &Path) -> Result<()> {
let dest = path
... | random_line_split | |
lib.rs | // Helianto -- static website generator
// Copyright © 2015-2016 Mickaël RAYBAUD-ROIG
//
// 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 version 3 of the License, or
// (at your... | pub fn add_generator<T: Generator + 'static>(&mut self) {
self.generators.push(Rc::new(T::new()));
}
fn load_templates(&mut self) -> Result<()> {
self.handlebars.clear_templates();
templates::register_helpers(&mut self.handlebars);
let loader = &mut templates::Loader::new(&... | let reader = Rc::new(T::new(&self.settings));
for &extension in T::extensions() {
self.readers.insert(extension.into(), reader.clone());
}
}
| identifier_body |
route_user.py | # -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without res... | copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND... | random_line_split | |
route_user.py | # -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without res... | eturn render("/user/team.html")
| identifier_body | |
route_user.py | # -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without res... | ):
return render("/user/profile.html")
@app.route("/user/hackathon")
@login_required
def user_hackathon_list():
return render("/user/team.html")
| ser_profile( | identifier_name |
smtpd.py | import asyncore
import email
import email.policy
import re
from smtpd import SMTPServer
from django.core.management.base import BaseCommand
from django.db import connections
from hc.api.models import Check
RE_UUID = re.compile(
"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{... |
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
# get a new db connection in case the old one has timed out:
connections.close_all()
result = _process_message(peer[0], mailfrom, rcpttos[0], data)
self.stdout.write(result)
class Command(BaseCommand):
help ... | self.stdout = stdout
super(Listener, self).__init__(localaddr, None, decode_data=False) | identifier_body |
smtpd.py | import asyncore
import email
import email.policy
import re
from smtpd import SMTPServer
from django.core.management.base import BaseCommand
from django.db import connections
from hc.api.models import Check
RE_UUID = re.compile(
"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{... |
return False
def _process_message(remote_addr, mailfrom, mailto, data):
to_parts = mailto.split("@")
code = to_parts[0]
if not RE_UUID.match(code):
return f"Not an UUID: {code}"
try:
check = Check.objects.get(code=code)
except Check.DoesNotExist:
return f"Check not ... | s = s.strip()
if s and s in subject:
return True | conditional_block |
smtpd.py | import asyncore
import email
import email.policy
import re
from smtpd import SMTPServer
from django.core.management.base import BaseCommand
from django.db import connections
from hc.api.models import Check
RE_UUID = re.compile(
"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{... | check = Check.objects.get(code=code)
except Check.DoesNotExist:
return f"Check not found: {code}"
action = "success"
if check.subject or check.subject_fail:
action = "ign"
# Specify policy, the default policy does not decode encoded headers:
data_str = data.decode(er... | if not RE_UUID.match(code):
return f"Not an UUID: {code}"
try: | random_line_split |
smtpd.py | import asyncore
import email
import email.policy
import re
from smtpd import SMTPServer
from django.core.management.base import BaseCommand
from django.db import connections
from hc.api.models import Check
RE_UUID = re.compile(
"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{... | (self, localaddr, stdout):
self.stdout = stdout
super(Listener, self).__init__(localaddr, None, decode_data=False)
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
# get a new db connection in case the old one has timed out:
connections.close_all()
result... | __init__ | identifier_name |
wizard.js | /**
* Angular Wizard directive
* Copyright (c) 2014 Genadijus Paleckis (genadijus.paleckis@gmail.com)
* License: MIT
* GIT: https://github.com/sickelap/angular-wizard
*
* Example usage:
*
* In your template add tag:
* <div wizard="wizardConfig"></div>
*
* Then in your controller create wizard configuration... |
if (transitionTo < 0) {
return; // first step
}
scope.currentStep = transitionTo;
angular.forEach(scope.config.steps, function (step, index) {
if (index < scope.currentStep) {
step.position ... | {
return; // last step
} | conditional_block |
wizard.js | /**
* Angular Wizard directive
* Copyright (c) 2014 Genadijus Paleckis (genadijus.paleckis@gmail.com)
* License: MIT
* GIT: https://github.com/sickelap/angular-wizard
*
* Example usage:
*
* In your template add tag:
* <div wizard="wizardConfig"></div>
*
* Then in your controller create wizard configuration... | ' </li>' +
' </ul>' +
'</div>';
var linkFn = function (scope) {
scope.currentStep = 0;
/**
* set correct position for all the steps in the wizard
*/
angular.forEach(scope.config.steps, function (step, ind... | ' </ol>' +
' <ul class="wizard-steps">' +
' <li ng-repeat="s in config.steps" ng-show="isCurrent($index)">' +
' <div data-wizard-step="s"></div>' + | random_line_split |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | .span_label(sp, "impl doesn't use types inside crate")
.note("the impl does not reference any types defined in this crate")
.note("define and implement a trait or new type instead")
.emit();
return;
... | struct_span_err!(self.tcx.sess,
sp,
E0117,
"only traits defined in the current crate can be \
implemented for arbitrary types") | random_line_split |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
struct OrphanChecker<'cx, 'tcx: 'cx> {
tcx: TyCtxt<'cx, 'tcx, 'tcx>,
}
impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for OrphanChecker<'cx, 'tcx> {
/// Checks exactly one impl for orphan rules and other such
/// restrictions. In this fn, it can happen that multiple errors
/// apply to a specific impl, so ... | {
let mut orphan = OrphanChecker { tcx };
tcx.hir().krate().visit_all_item_likes(&mut orphan);
} | identifier_body |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'cx, 'tcx: 'cx> {
tcx: TyCtxt<'cx, 'tcx, 'tcx>,
}
impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for OrphanChecker<'cx, 'tcx> {
/// Checks exactly one impl for orphan rules and other such
/// restrictions. In this fn, it can happen that multiple errors
/// apply to a specific impl, so just return after repo... | OrphanChecker | identifier_name |
sre_constants.py | #
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal su... | (self, msg, pattern=None, pos=None):
self.msg = msg
self.pattern = pattern
self.pos = pos
if pattern is not None and pos is not None:
msg = '%s at position %d' % (msg, pos)
if isinstance(pattern, str):
newline = '\n'
else:
... | __init__ | identifier_name |
sre_constants.py | #
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal su... | MIN_REPEAT MAX_REPEAT
""")
del OPCODES[-2:] # remove MIN_REPEAT and MAX_REPEAT
# positions
ATCODES = _makecodes("""
AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING
AT_BOUNDARY AT_NON_BOUNDARY
AT_END AT_END_LINE AT_END_STRING
AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY
AT_UNI_BOUNDARY AT_UN... | MIN_REPEAT_ONE
RANGE_IGNORE
| random_line_split |
sre_constants.py | #
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal su... |
self.lineno = pattern.count(newline, 0, pos) + 1
self.colno = pos - pattern.rfind(newline, 0, pos)
if newline in pattern:
msg = '%s (line %d, column %d)' % (msg, self.lineno, self.colno)
else:
self.lineno = self.colno = None
super()... | newline = b'\n' | conditional_block |
sre_constants.py | #
# Secret Labs' Regular Expression Engine
#
# various symbols used by the regular expression engine.
# run this script to update the _sre include files!
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# See the sre.py file for information on usage and redistribution.
#
"""Internal su... |
def __str__(self):
return self.name
__repr__ = __str__
MAXREPEAT = _NamedIntConstant(MAXREPEAT, 'MAXREPEAT')
def _makecodes(names):
names = names.strip().split()
items = [_NamedIntConstant(i, name) for i, name in enumerate(names)]
globals().update({item.name: item for item i... | self = super(_NamedIntConstant, cls).__new__(cls, value)
self.name = name
return self | identifier_body |
quality_stats.py | #!/usr/bin/python -tt
# Quality scores from fastx
# Website: http://hannonlab.cshl.edu/fastx_toolkit/
# Import OS features to run external programs
import os
import glob
v = "Version 0.1"
# Versions:
# 0.1 - Simple script to run cutadapt on all of the files
fastq_indir = "/home/chris/transcriptome/fastq/trimmed/" | os.system("fastx_quality_stats -i %s/Sample_1_L001_trimmed.fastq %s/Sample_1_L001_trimmed.txt" % (fastq_indir, fastq_outdir))
os.system("fastx_quality_stats -i %s/Sample_1_L002_trimmed.fastq %s/Sample_1_L002_trimmed.txt" % (fastq_indir, fastq_outdir)) | fastq_outdir = "/home/chris/transcriptome/fastq/reports/quality stats"
# Sample 1
print "Analyzing Sample 1..." | random_line_split |
kpabenc_adapt_hybrid.py | from charm.toolbox.pairinggroup import PairingGroup,GT,extract_key
from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction
from charm.toolbox.ABEnc import ABEnc
from charm.schemes.abenc.abenc_lsw08 import KPabe
debug = False
class HybridABEnc(ABEnc):
"""
>>> from charm.schemes.abenc.abenc_lsw08 impo... | if debug: print("pk => ", pk)
if debug: print("mk => ", mk)
sk = hyb_abe.keygen(pk, mk, access_key)
if debug: print("sk => ", sk)
ct = hyb_abe.encrypt(pk, message, access_policy)
mdec = hyb_abe.decrypt(ct, sk)
assert mdec == message, "Failed Decryption!!!"
if debug: print("Successful Dec... | random_line_split | |
kpabenc_adapt_hybrid.py |
from charm.toolbox.pairinggroup import PairingGroup,GT,extract_key
from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction
from charm.toolbox.ABEnc import ABEnc
from charm.schemes.abenc.abenc_lsw08 import KPabe
debug = False
class HybridABEnc(ABEnc):
"""
>>> from charm.schemes.abenc.abenc_lsw08 imp... |
def main():
groupObj = PairingGroup('SS512')
kpabe = KPabe(groupObj)
hyb_abe = HybridABEnc(kpabe, groupObj)
access_key = '((ONE or TWO) and THREE)'
access_policy = ['ONE', 'TWO', 'THREE']
message = b"hello world this is an important message."
(pk, mk) = hyb_abe.setup()
if debug: pr... | c1, c2 = ct['c1'], ct['c2']
key = abenc.decrypt(c1, sk)
cipher = AuthenticatedCryptoAbstraction(extract_key(key))
return cipher.decrypt(c2) | identifier_body |
kpabenc_adapt_hybrid.py |
from charm.toolbox.pairinggroup import PairingGroup,GT,extract_key
from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction
from charm.toolbox.ABEnc import ABEnc
from charm.schemes.abenc.abenc_lsw08 import KPabe
debug = False
class HybridABEnc(ABEnc):
"""
>>> from charm.schemes.abenc.abenc_lsw08 imp... |
if __name__ == "__main__":
debug = True
main()
| print("Successful Decryption!!!") | conditional_block |
kpabenc_adapt_hybrid.py |
from charm.toolbox.pairinggroup import PairingGroup,GT,extract_key
from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction
from charm.toolbox.ABEnc import ABEnc
from charm.schemes.abenc.abenc_lsw08 import KPabe
debug = False
class HybridABEnc(ABEnc):
"""
>>> from charm.schemes.abenc.abenc_lsw08 imp... | ():
groupObj = PairingGroup('SS512')
kpabe = KPabe(groupObj)
hyb_abe = HybridABEnc(kpabe, groupObj)
access_key = '((ONE or TWO) and THREE)'
access_policy = ['ONE', 'TWO', 'THREE']
message = b"hello world this is an important message."
(pk, mk) = hyb_abe.setup()
if debug: print("pk => ", ... | main | identifier_name |
global-plugin.d.ts | // Type definitions for [~НАЗВАНИЕ БИБЛИОТЕКИ~] [~НЕОБЯЗАТЕЛЬНЫЙ НОМЕР ВЕРСИИ~]
// Project: [~НАЗВАНИЕ ПРОЕКТА~]
// Definitions by: [~ВАШЕ ИМЯ~] <[~ВАШ АДРЕС В ИНТЕРНЕТЕ~]>
/*~ Этот шаблон показывает, как создать глобальный плагин */
/*~ Напишите объявление для исходного типа и добавьте новые члены.
*~ Например, зде... | prefix?: string;
padding: number;
}
} | type BinaryFormatCallback = (n: number) => string;
interface BinaryFormatOptions { | random_line_split |
sha1.js | /**
* Copyright 2013 Google, Inc.
* @fileoverview Calculate SHA1 hash of the given content.
*/
goog.provide("adapt.sha1");
goog.require("adapt.base");
/**
* @param {number} n
* @return {string} big-endian byte sequence
*/
adapt.sha1.encode32 = function(n) {
return String.fromCharCode((n >>> 24)&0xFF, (n >>> 16... | else if (i < 60) {
f = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
f = (b ^ c ^ d) + 0xCA62C1D6;
}
f += ((a << 5) | (a >>> 27)) + e + w[i];
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = f;
}
... | {
f = (b ^ c ^ d) + 0x6ED9EBA1;
} | conditional_block |
sha1.js | /**
* Copyright 2013 Google, Inc.
* @fileoverview Calculate SHA1 hash of the given content.
*/
goog.provide("adapt.sha1");
goog.require("adapt.base");
/**
* @param {number} n
* @return {string} big-endian byte sequence
*/
adapt.sha1.encode32 = function(n) {
return String.fromCharCode((n >>> 24)&0xFF, (n >>> 16... | c = (b << 30) | (b >>> 2);
b = a;
a = f;
}
h[0] = (h[0] + a) | 0;
h[1] = (h[1] + b) | 0;
h[2] = (h[2] + c) | 0;
h[3] = (h[3] + d) | 0;
h[4] = (h[4] + e) | 0;
}
return h;
};
/**
* @param {string} bytes chars with codes 0 - 255 that represent message... | d = c; | random_line_split |
renderWithLoadProgress.tsx | import { Spinner, SpinnerProps } from "@artsy/palette"
import * as React from "react";
import { QueryRenderer, Container as RelayContainer } from "react-relay"
import styled from "styled-components"
import createLogger from "v2/Utils/logger"
type ReadyState = Parameters<
React.ComponentProps<typeof QueryRenderer>["r... | {
// TODO: We need design for retrying or the approval to use the iOS design.
// See also: https://artsyproduct.atlassian.net/browse/PLATFORM-1272
return ({ error, props, retry }) => {
if (error) {
// TODO: Should we add a callback here so that containers can gracefully
// handle an error st... | identifier_body | |
renderWithLoadProgress.tsx | import { Spinner, SpinnerProps } from "@artsy/palette"
import * as React from "react";
import { QueryRenderer, Container as RelayContainer } from "react-relay"
import styled from "styled-components"
import createLogger from "v2/Utils/logger"
| * WARNING: Do _not_ change this element to something common like a div. If the
* element of this container is the same as the element used in the RelayContainer
* then rehydration can fail and cause the RelayContainer to receive styles
* from the SpinnerContainer and Spinner.
*/
const SpinnerContainer = styled.fig... | type ReadyState = Parameters<
React.ComponentProps<typeof QueryRenderer>["render"]
>[0]
/** | random_line_split |
renderWithLoadProgress.tsx | import { Spinner, SpinnerProps } from "@artsy/palette"
import * as React from "react";
import { QueryRenderer, Container as RelayContainer } from "react-relay"
import styled from "styled-components"
import createLogger from "v2/Utils/logger"
type ReadyState = Parameters<
React.ComponentProps<typeof QueryRenderer>["r... |
}
export type LoadProgressRenderer<P> = (
// FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37950
readyState: ReadyState
) => React.ReactElement<RelayContainer<P>> | null
export function renderWithLoadProgress<P>(
Container: RelayContainer<P>,
initialProps: object = {},
wrapperProps: obje... | {
const body = networkError.response._bodyInit
try {
const data = JSON.parse(body)
console.error(`Metaphysics Error data:`, data)
logger.error(data)
} catch (e) {
logger.error("Metaphysics Error could not be parsed.", e)
}
} | conditional_block |
renderWithLoadProgress.tsx | import { Spinner, SpinnerProps } from "@artsy/palette"
import * as React from "react";
import { QueryRenderer, Container as RelayContainer } from "react-relay"
import styled from "styled-components"
import createLogger from "v2/Utils/logger"
type ReadyState = Parameters<
React.ComponentProps<typeof QueryRenderer>["r... | <P>(
Container: RelayContainer<P>,
initialProps: object = {},
wrapperProps: object = {},
spinnerProps: SpinnerProps = {
delay: 1000,
}
): LoadProgressRenderer<P> {
// TODO: We need design for retrying or the approval to use the iOS design.
// See also: https://artsyproduct.atlassian.net/browse/PLATFOR... | renderWithLoadProgress | identifier_name |
authenticator.js | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview An UI component to authenciate to Chrome. The component hosts
* IdP web pages in a webview. A client who is interested in monitoring... | (webview) {
this.webview_ = typeof webview == 'string' ? $(webview) : webview;
assert(this.webview_);
this.email_ = null;
this.password_ = null;
this.gaiaId_ = null,
this.sessionIndex_ = null;
this.chooseWhatToSync_ = false;
this.skipForNow_ = false;
this.authFlow_ = AuthFlow.DEFAUL... | Authenticator | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.