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 |
|---|---|---|---|---|
message_builder.rs | //! Builder for constructing Asynchronous message interactions
use std::collections::HashMap;
use bytes::Bytes;
use log::*;
use maplit::hashmap;
use pact_models::content_types::ContentType;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::MatchingRuleCategory;
use pact_models::path_exp::Do... | <G: Into<String>>(&mut self, given: G) -> &mut Self {
self.provider_states.push(ProviderState::default(&given.into()));
self
}
/// Adds a text comment to this interaction. This allows to specify just a bit more information
/// about the interaction. It has no functional impact, but can be displayed in th... | given | identifier_name |
message_builder.rs | //! Builder for constructing Asynchronous message interactions
use std::collections::HashMap;
use bytes::Bytes;
use log::*;
use maplit::hashmap;
use pact_models::content_types::ContentType;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::MatchingRuleCategory;
use pact_models::path_exp::Do... | self.message_contents = InteractionContents {
body : OptionalBody::from(Value::Object(contents_map.clone())),
.. InteractionContents::default()
};
}
self
}
fn setup_core_matcher(
&mut self,
content_type: &ContentType,
config: &HashMap<String, Value>,
content_mat... | debug!("No content matcher found, will use the internal implementation");
self.setup_core_matcher(&ct, &contents_hashmap, None);
}
} else { | random_line_split |
message_builder.rs | //! Builder for constructing Asynchronous message interactions
use std::collections::HashMap;
use bytes::Bytes;
use log::*;
use maplit::hashmap;
use pact_models::content_types::ContentType;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::MatchingRuleCategory;
use pact_models::path_exp::Do... |
/// Specify the body as `JsonPattern`, possibly including special matching
/// rules.
///
/// ```
/// use pact_consumer::prelude::*;
/// use pact_consumer::*;
/// use pact_consumer::builders::MessageInteractionBuilder;
///
/// MessageInteractionBuilder::new("hello message", "core/interaction/message... | {
self.contents_plugin.as_ref().map(|plugin| {
let config = if let Some(config) = self.plugin_config.get(plugin.name.as_str()) {
config.pact_configuration.clone()
} else {
hashmap!{}
};
PluginData {
name: plugin.name.clone(),
version: plugin.version.clone(),
... | identifier_body |
pp.rs | 0us;
self.right = 0us;
} else { self.advance_right(); }
debug!("pp Break({})/buffer ~[{},{}]",
b.offset, self.left, self.right);
self.check_stack(0);
let right = self.right;
self.scan_push(right);
self.token[self... | {
rbox(p, indent, Breaks::Consistent)
} | identifier_body | |
pp.rs | (s, len);
self.size[self.right] = len;
self.right_total += len;
self.check_stream()
}
}
}
}
pub fn check_stream(&mut self) -> io::IoResult<()> {
debug!("check_stream ~[{}, {}] with left_total={}, right_total={}",
... | zero_word | identifier_name | |
pp.rs | match *token {
Token::String(ref s, len) => format!("STR({},{})", s, len),
Token::Break(_) => "BREAK".to_string(),
Token::Begin(_) => "BEGIN".to_string(),
Token::End => "END".to_string(),
Token::Eof => "EOF".to_string()
}
}
pub fn buf_str(toks: &[Token],
szs:... | top: 0,
bottom: 0,
print_stack: Vec::new(),
pending_indentation: 0
}
}
/// In case you do not have the paper, here is an explanation of what's going
/// on.
///
/// There is a stream of input tokens flowing through this printer.
///
/// The printer buffers up to 3N tokens inside it... | random_line_split | |
pp.rs | (if there is any) on top of it. Stuff is flushed off the
/// bottom as it becomes irrelevant due to the primary ring-buffer
/// advancing.
scan_stack: Vec<usize> ,
/// Top==bottom disambiguator
scan_stack_empty: bool,
/// Index of top of scan_stack
top: usize,
/// Index of bottom of sca... | {
debug!("print Begin -> push fitting block");
self.print_stack.push(PrintStackElem {
offset: 0,
pbreak: PrintStackBreak::Fits
});
} | conditional_block | |
keyboardKey.ts | module Inknote.Drawing {
export class KeyboardKey {
hover: boolean;
draw(ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) {
if (this.name == "") {
| ctx.beginPath();
ctx.rect(this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
var grd = ctx.createLinearGradient(this.x - this.width / 2, this.y - this.height / 2, this.x + this.width / 2, this.y + this.height / 2);
if (this.hover) {
... | return;
}
| conditional_block |
keyboardKey.ts | module Inknote.Drawing {
export class KeyboardKey {
hover: boolean;
draw(ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) {
if (this.name == "") {
return;
}
ctx.beginPath();
ctx.rect(this.x - this.width / 2, this.y - this... | var keys: KeyboardKey[] = [];
var itemWidth = totalWidth / charArray.length;
var maxWidth = 10000;
var column = 0;
for (var i = 0; i < charArray.length; i++) {
keys.push(new KeyboardKey(charArray[i], x + itemWidth * column + itemWidth / 2, y + itemHeight / 2, itemW... |
var charArray = text.split(""); | random_line_split |
keyboardKey.ts | module Inknote.Drawing {
export class KeyboardKey {
hover: boolean;
draw(ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) {
if (this.name == "") {
return;
}
ctx.beginPath();
ctx.rect(this.x - this.width / 2, this.y - this... | ublic name: string, public x: number, public y: number, public width: number, public height: number) {
}
}
export function keysFromString(text: string, x: number, y: number, totalWidth: number, itemHeight) {
var charArray = text.split("");
var keys: KeyboardKey[] = [];
... | nstructor(p | identifier_name |
keyboardKey.ts | module Inknote.Drawing {
export class KeyboardKey {
hover: boolean;
draw(ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) {
if (this.name == "") {
return;
}
ctx.beginPath();
ctx.rect(this.x - this.width / 2, this.y - this... | }
export function keysFromString(text: string, x: number, y: number, totalWidth: number, itemHeight) {
var charArray = text.split("");
var keys: KeyboardKey[] = [];
var itemWidth = totalWidth / charArray.length;
var maxWidth = 10000;
var column = 0;
for (var i... |
}
| identifier_body |
mva-w15.js | /**
*
* STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. athan@nodeprime.com. 2014.
*
*/... | () {
this.name = '';
this._window = 15;
// ACCESSORS:
this._value = function( d ) {
return d.y;
};
return this;
} // end FUNCTION Stream()
/**
* ATTRIBUTE: type
* Defines the stream type.
*/
Stream.prototype.type = 'mva-w15';
/**
* METHOD: metric( metric )
* Metric setter and getter. If a me... | Stream | identifier_name |
mva-w15.js | /**
* | * STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. athan@nodeprime.com. 2014.
*
*/
(fun... | random_line_split | |
mva-w15.js | /**
*
* STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. athan@nodeprime.com. 2014.
*
*/... |
if ( !metric.value ) {
throw new Error( 'metric()::invalid input argument. Metric must be an object with a \'value\' method.' );
}
// Extract the method to calculate the metric value and bind the metric context:
this._value = metric.value.bind( metric );
// If the metric has a name, set the transform name... | {
return this._value;
} | conditional_block |
mva-w15.js | /**
*
* STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. athan@nodeprime.com. 2014.
*
*/... |
/**
* ATTRIBUTE: type
* Defines the stream type.
*/
Stream.prototype.type = 'mva-w15';
/**
* METHOD: metric( metric )
* Metric setter and getter. If a metric instance is supplied, sets the metric. If no metric is supplied, returns the instance metric value function.
*
* @param {object} metric - an object w... | {
this.name = '';
this._window = 15;
// ACCESSORS:
this._value = function( d ) {
return d.y;
};
return this;
} // end FUNCTION Stream() | identifier_body |
839_similar-string-groups.py | import collections
class Solution:
def numSimilarGroups(self, A):
UF = {}
for i in range(len(A)): UF[i] = i
def find(x):
if x != UF[x]:
UF[x] = find(UF[x])
return UF[x]
def | (x, y):
UF.setdefault(x, x)
UF.setdefault(y, y)
UF[find(x)] = find(y)
def match(s1, s2):
i = 0
j = -1
while i<len(s1):
if s1[i] != s2[i]:
if j == -1: j = i
else: break
... | union | identifier_name |
839_similar-string-groups.py | import collections
class Solution:
def numSimilarGroups(self, A):
UF = {}
for i in range(len(A)): UF[i] = i
def find(x):
if x != UF[x]:
UF[x] = find(UF[x])
return UF[x]
def union(x, y):
UF.setdefault(x, x)
UF.setdefault(... | while i<len(s1):
if s1[i] != s2[i]:
if j == -1: j = i
else: break
i += 1
return s1[i+1:] == s2[i+1:]
N, W = len(A), len(A[0])
if N < W*W:
for i in range(len(A)): UF[i] = i
for i in ra... | def match(s1, s2):
i = 0
j = -1 | random_line_split |
839_similar-string-groups.py | import collections
class Solution:
def numSimilarGroups(self, A):
UF = {}
for i in range(len(A)): |
def find(x):
if x != UF[x]:
UF[x] = find(UF[x])
return UF[x]
def union(x, y):
UF.setdefault(x, x)
UF.setdefault(y, y)
UF[find(x)] = find(y)
def match(s1, s2):
i = 0
j = -1
while i<len... | UF[i] = i | conditional_block |
839_similar-string-groups.py | import collections
class Solution:
def numSimilarGroups(self, A):
UF = {}
for i in range(len(A)): UF[i] = i
def find(x):
|
def union(x, y):
UF.setdefault(x, x)
UF.setdefault(y, y)
UF[find(x)] = find(y)
def match(s1, s2):
i = 0
j = -1
while i<len(s1):
if s1[i] != s2[i]:
if j == -1: j = i
else: bre... | if x != UF[x]:
UF[x] = find(UF[x])
return UF[x] | identifier_body |
provision_encap.py | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
from vnc_api.vnc_api import *
class EncapsulationProvision(object):
| print 'Created.UUID is %s'%(result)
return
current_linklocal=current_config.get_linklocal_services()
encapsulation_priorities=encap_obj
vxlan_network_identifier_mode=current_config.get_vxlan_network_identifier_mode()
if self._args.oper != "add":
e... | def __init__(self, args_str=None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._parse_args(args_str)
self._vnc_lib = VncApi(
self._args.admin_user, self._args.admin_password,
self._args.admin_tenant_name,
self... | identifier_body |
provision_encap.py | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
from vnc_api.vnc_api import *
class | (object):
def __init__(self, args_str=None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._parse_args(args_str)
self._vnc_lib = VncApi(
self._args.admin_user, self._args.admin_password,
self._args.admin_tenant_name,
... | EncapsulationProvision | identifier_name |
provision_encap.py | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
from vnc_api.vnc_api import *
class EncapsulationProvision(object):
def __init__(self, args_str=None):
self._args = None
if not args_str:
args_str = '... | --api_server_ip 127.0.0.1
--api_server_port 8082
--encap_priority "MPLSoUDP,MPLSoGRE,VXLAN"
--vxlan_vn_id_mode "automatic"
... | Eg. python provision_encap.py | random_line_split |
provision_encap.py | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
from vnc_api.vnc_api import *
class EncapsulationProvision(object):
def __init__(self, args_str=None):
self._args = None
if not args_str:
args_str = '... |
# Override with CLI options
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
... | config = ConfigParser.SafeConfigParser()
config.read([args.conf_file])
defaults.update(dict(config.items("DEFAULTS")))
if 'KEYSTONE' in config.sections():
ksopts.update(dict(config.items("KEYSTONE"))) | conditional_block |
owned.rs | use super::*;
use std::borrow::Cow;
#[cfg(feature = "lazy")]
include!("lazy.rs");
#[allow(non_snake_case)]
#[derive(Debug, Default, Clone, PartialEq)]
pub struct OwnedIpInfo {
pub city_id: u32,
pub country: String,
pub region: String,
pub province: String,
pub city: String,
pub ISP: String,
}
... |
if data_ptr == 0 {
Err(Error::NotFound)?;
}
let data_len = (data_ptr >> 24) & 0xff;
data_ptr = data_ptr & 0x00FFFFFF;
get_ip_info(
get_u32(&self.db_bin_bytes[..], data_ptr),
&self.db_bin_bytes[(data_ptr + 4) as usize..(data_ptr + data_len) as... | } | random_line_split |
owned.rs | use super::*;
use std::borrow::Cow;
#[cfg(feature = "lazy")]
include!("lazy.rs");
#[allow(non_snake_case)]
#[derive(Debug, Default, Clone, PartialEq)]
pub struct OwnedIpInfo {
pub city_id: u32,
pub country: String,
pub region: String,
pub province: String,
pub city: String,
pub ISP: String,
}
... |
}
if data_ptr == 0 {
Err(Error::NotFound)?;
}
let data_len = (data_ptr >> 24) & 0xff;
data_ptr = data_ptr & 0x00FFFFFF;
get_ip_info(
get_u32(&self.db_bin_bytes[..], data_ptr),
&self.db_bin_bytes[(data_ptr + 4) as usize..(data_ptr + d... | {
let eip = get_u32(&self.db_bin_bytes[..], p + 4);
if ip > eip {
l = m + 1;
} else {
data_ptr = get_u32(&self.db_bin_bytes[..], p + 8);
break;
}
} | conditional_block |
owned.rs | use super::*;
use std::borrow::Cow;
#[cfg(feature = "lazy")]
include!("lazy.rs");
#[allow(non_snake_case)]
#[derive(Debug, Default, Clone, PartialEq)]
pub struct OwnedIpInfo {
pub city_id: u32,
pub country: String,
pub region: String,
pub province: String,
pub city: String,
pub ISP: String,
}
... |
}
pub struct OwnedIp2Region {
// super block index info
first_index_ptr: u32,
// last_index_ptr: u32,
total_blocks: u32,
db_bin_bytes: Cow<'static, [u8]>,
}
impl OwnedIp2Region {
pub fn new(path: &str) -> io::Result<Self> {
let mut file = File::open(path)?;
Self::new2(&mut fil... | {
write!(f, "{}", self.as_ref())
} | identifier_body |
owned.rs | use super::*;
use std::borrow::Cow;
#[cfg(feature = "lazy")]
include!("lazy.rs");
#[allow(non_snake_case)]
#[derive(Debug, Default, Clone, PartialEq)]
pub struct OwnedIpInfo {
pub city_id: u32,
pub country: String,
pub region: String,
pub province: String,
pub city: String,
pub ISP: String,
}
... | (file: &mut File) -> io::Result<Self> {
let file_size = file.metadata()?.len();
let mut bytes = Vec::with_capacity(file_size as usize);
file.read_to_end(&mut bytes)?;
let first_index_ptr = get_u32(&bytes[..], 0);
let last_index_ptr = get_u32(&bytes[..], 4);
let total_blo... | new2 | identifier_name |
version.component.ts | import { Component } from '@angular/core'
@Component({
selector: 'version',
template: `
<h1>Version</h1>
<p>
There are 3 major versions available, and each of them is not backwards
compatible. Version of <code>angular2-baidu-map</code> is consistent with
angular. Below are documentation r... | {}
| VersionComponent | identifier_name |
version.component.ts | import { Component } from '@angular/core'
@Component({
selector: 'version',
template: `
<h1>Version</h1>
<p>
There are 3 major versions available, and each of them is not backwards
compatible. Version of <code>angular2-baidu-map</code> is consistent with
angular. Below are documentation r... | </li>
<li>
<a
href="https://github.com/leftstick/angular2-baidu-map/tree/4.x"
target="_blank"
>version 4.x</a
>
</li>
<li>
current, 8.x
</li>
</ul>
`
})
export class VersionComponent {} | href="https://github.com/leftstick/angular2-baidu-map/tree/3.x"
target="_blank"
>version 3.x</a
> | random_line_split |
app.ts | import {
Inject,
Component,
ElementRef
} from 'angular2/core';
import {
Router,
RouteConfig,
ROUTER_DIRECTIVES
} from "angular2/router";
import {ProfileForm} from './form/profile.form';
import {TodoComponent} from "./todo/todo";
import {TabComponent} from "./tabs/tabs"; | directives: [ROUTER_DIRECTIVES],
template: `
<nav class="navbar navbar-diy">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand">
<a href="#/">
{{title}}
</a>
</div>
</div>
<ul class="nav navba... | import {ModalComponent} from './modal/modal'
@Component({
selector: "angular2-demo", | random_line_split |
app.ts | import {
Inject,
Component,
ElementRef
} from 'angular2/core';
import {
Router,
RouteConfig,
ROUTER_DIRECTIVES
} from "angular2/router";
import {ProfileForm} from './form/profile.form';
import {TodoComponent} from "./todo/todo";
import {TabComponent} from "./tabs/tabs";
import {ModalComponent} from './mod... | outer.subscribe((path:string)=>{
this.currentRoute=path;
});
}
}
| identifier_body | |
app.ts | import {
Inject,
Component,
ElementRef
} from 'angular2/core';
import {
Router,
RouteConfig,
ROUTER_DIRECTIVES
} from "angular2/router";
import {ProfileForm} from './form/profile.form';
import {TodoComponent} from "./todo/todo";
import {TabComponent} from "./tabs/tabs";
import {ModalComponent} from './mod... | eturn nav.path.indexOf(this.currentRoute)>-1;
}
ngOnInit(){
this.router.subscribe((path:string)=>{
this.currentRoute=path;
});
}
}
| ter(nav){
r | identifier_name |
main.js | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
require('electron-context-menu')({
prepend: (params, browserWindow) => [{
label: 'Rainbow',
// only show it when right-c... | () {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 900, height: 600 })
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/app/index.html`)
// Open the DevTools.
//mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow... | createWindow | identifier_name |
main.js | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
require('electron-context-menu')({
prepend: (params, browserWindow) => [{
label: 'Rainbow',
// only show it when right-c... |
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applicat... | {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 900, height: 600 })
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/app/index.html`)
// Open the DevTools.
//mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on... | identifier_body |
main.js | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
require('electron-context-menu')({
prepend: (params, browserWindow) => [{
label: 'Rainbow',
// only show it when right-c... |
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
| {
createWindow()
} | conditional_block |
main.js | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
require('electron-context-menu')({
prepend: (params, browserWindow) => [{
label: 'Rainbow',
// only show it when right-c... |
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's ... | // initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow) | random_line_split |
apps.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | = "weblate.metrics"
label = "metrics"
verbose_name = "Metrics"
| identifier_body | |
apps.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | onfig):
name = "weblate.metrics"
label = "metrics"
verbose_name = "Metrics"
| csConfig(AppC | identifier_name |
apps.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | label = "metrics"
verbose_name = "Metrics" | random_line_split | |
query.py | constants
from c7n_azure.actions.logic_app import LogicAppAction
from azure.mgmt.resourcegraph.models import QueryRequest
from c7n_azure.actions.notify import Notify
from c7n_azure.filters import ParentFilter
from c7n_azure.provider import resources
from c7n.actions import ActionRegistry
from c7n.exceptions import Po... | (self, resources):
return resources
def get_permissions(self):
return ()
def get_source(self, source_type):
return sources.get(source_type)(self)
def get_session(self):
if self._session is None:
self._session = local_session(self.session_factory)
return... | augment | identifier_name |
query.py | constants
from c7n_azure.actions.logic_app import LogicAppAction
from azure.mgmt.resourcegraph.models import QueryRequest
from c7n_azure.actions.notify import Notify
from c7n_azure.filters import ParentFilter
from c7n_azure.provider import resources
from c7n.actions import ActionRegistry
from c7n.exceptions import Po... |
return results
@sources.register('describe-child-azure')
class ChildDescribeSource(DescribeSource):
resource_query_factory = ChildResourceQuery
class TypeMeta(type):
def __repr__(cls):
return "<Type info service:%s client: %s>" % (
cls.service,
cls.client)
@six.a... | raise e | conditional_block |
query.py | constants
from c7n_azure.actions.logic_app import LogicAppAction
from azure.mgmt.resourcegraph.models import QueryRequest
from c7n_azure.actions.notify import Notify
from c7n_azure.filters import ParentFilter
from c7n_azure.provider import resources
from c7n.actions import ActionRegistry
from c7n.exceptions import Po... | class QueryResourceManager(ResourceManager):
class resource_type(TypeInfo):
pass
def __init__(self, data, options):
super(QueryResourceManager, self).__init__(data, options)
self.source = self.get_source(self.source_type)
self._session = None
def augment(self, resources):
... |
return super(QueryMeta, cls).__new__(cls, name, parents, attrs)
@six.add_metaclass(QueryMeta) | random_line_split |
query.py | constants
from c7n_azure.actions.logic_app import LogicAppAction
from azure.mgmt.resourcegraph.models import QueryRequest
from c7n_azure.actions.notify import Notify
from c7n_azure.filters import ParentFilter
from c7n_azure.provider import resources
from c7n.actions import ActionRegistry
from c7n.exceptions import Po... |
class TypeMeta(type):
def __repr__(cls):
return "<Type info service:%s client: %s>" % (
cls.service,
cls.client)
@six.add_metaclass(TypeMeta)
class TypeInfo(object):
doc_groups = None
"""api client construction information"""
service = ''
client = ''
# Def... | resource_query_factory = ChildResourceQuery | identifier_body |
UserSession.d.ts | /add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
clientId: string;
/**
* A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/secur... | implements IAuthenticationManager {
/**
* Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is true the
* authentication window will open in a new tab/window otherwise the user will
* be redirected to the authorization page in their current tab.
*
* @browserOnly
*/
... | UserSession | identifier_name |
UserSession.d.ts | .
*/
redirectUri?: string;
/**
* OAuth 2.0 refresh token from a previous user session.
*/
refreshToken?: string;
/**
* Expiration date of the `refreshToken`
*/
refreshTokenExpires?: Date;
/**
* The authenticated user's username. Guaranteed to be unique across ArcGIS... | /**
* Refreshes the current `token` and `tokenExpires` with `refreshToken`.
*/
private refreshWithRefreshToken; | random_line_split | |
actor.ts | /**
* Vaudeville Actor
*/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { ActorMsg, ClientReceiveLogic, IActor } from './actor.d';
import { ActorRef } from './actorRef';
/* tslint:disable-next-line no-any interface-over-type-literal */
export type ActorType = { new (.... | else if (
this.receive.hasOwnProperty('_')
) {
this.receive['_'](actorMsg);
}
}
}
| {
this.receive[actorMsg.msg](actorMsg);
} | conditional_block |
actor.ts | /**
* Vaudeville Actor
*/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { ActorMsg, ClientReceiveLogic, IActor } from './actor.d';
import { ActorRef } from './actorRef';
/* tslint:disable-next-line no-any interface-over-type-literal */
export type ActorType = { new (.... | (
actorType: ActorType,
/* tslint:disable-next-line no-any */
...args: Array<any>,
): ActorRef {
const actor: Actor = new actorType(...args);
actor.path = `${this.path}/${actor.name}`;
this.children.add(actor);
return new ActorRef(actor.path);
}
/**
* When a message is received by ... | actorOf | identifier_name |
actor.ts | /**
* Vaudeville Actor
*/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { ActorMsg, ClientReceiveLogic, IActor } from './actor.d';
import { ActorRef } from './actorRef';
/* tslint:disable-next-line no-any interface-over-type-literal */
export type ActorType = { new (.... | }
}
}
| {
if (
typeof actorMsg.msg === 'object' &&
this.receive.hasOwnProperty(actorMsg.msg.constructor.name)
) {
this.receive[actorMsg.msg.constructor.name](actorMsg);
} else if (
typeof actorMsg.msg === 'number' &&
this.receive.hasOwnProperty(actorMsg.msg)
) {
this.receive[... | identifier_body |
actor.ts | /**
* Vaudeville Actor
*/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { ActorMsg, ClientReceiveLogic, IActor } from './actor.d';
import { ActorRef } from './actorRef';
/* tslint:disable-next-line no-any interface-over-type-literal */
export type ActorType = { new (.... | /* Actor message mailbox */
/* tslint:disable-next-line no-any */
protected mailbox: Subject<any> = new Subject<any>();
/* Actors created under implemented actor */
protected children: WeakSet<Actor>;
/* Path of this actor to the system root */
public path: string;
constructor(
public name: strin... | private self: this = this;
/* Implementation defined message handler */
protected abstract receive: ClientReceiveLogic;
| random_line_split |
task-comm-10.rs | // Copyright 2012-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... | (tx: &Sender<Sender<String>>) {
let (tx2, rx) = channel();
tx.send(tx2).unwrap();
let mut a;
let mut b;
a = rx.recv().unwrap();
assert!(a == "A".to_string());
println!("{}", a);
b = rx.recv().unwrap();
assert!(b == "B".to_string());
println!("{}", b);
}
pub fn main() {
let ... | start | identifier_name |
task-comm-10.rs | // Copyright 2012-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... | let (tx, rx) = channel();
let _child = thread::scoped(move|| { start(&tx) });
let mut c = rx.recv().unwrap();
c.send("A".to_string()).unwrap();
c.send("B".to_string()).unwrap();
thread::yield_now();
} | assert!(b == "B".to_string());
println!("{}", b);
}
pub fn main() { | random_line_split |
task-comm-10.rs | // Copyright 2012-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... | {
let (tx, rx) = channel();
let _child = thread::scoped(move|| { start(&tx) });
let mut c = rx.recv().unwrap();
c.send("A".to_string()).unwrap();
c.send("B".to_string()).unwrap();
thread::yield_now();
} | identifier_body | |
model_manager.py | from datetime import datetime
class ModelManager(object):
def __init__(self, db, collection_name, has_stats=False, **kwargs):
self.property_helper = None
self.log_helper = None
self.collection_name = collection_name
self.db = db
if 'logger' in kwargs:
self.log_... | pass
def save_object(self, instance):
instance.validate_fields()
return self.collection.save(instance.get_as_dict())
#deprecated: name is confusing
def save_document(self, document):
document.validate_fields()
return self.collection.save(document.get_as_dict())
... | self.stats_collection = self.db[self.stats_collection_name]
else:
self.stats_collection = self.db.create_collection(self.stats_collection_name)
def close_connection(self): | random_line_split |
model_manager.py | from datetime import datetime
class ModelManager(object):
def __init__(self, db, collection_name, has_stats=False, **kwargs):
self.property_helper = None
self.log_helper = None
self.collection_name = collection_name
self.db = db
if 'logger' in kwargs:
self.log_... | (self, document):
document.validate_fields()
return self.collection.save(document.get_as_dict())
def set_property_helper(self, property_helper):
self.property_helper = property_helper
def set_log_helper(self, log_helper):
self.log_helper = log_helper
def __getattr__(se... | save_document | identifier_name |
model_manager.py | from datetime import datetime
class ModelManager(object):
def __init__(self, db, collection_name, has_stats=False, **kwargs):
self.property_helper = None
self.log_helper = None
self.collection_name = collection_name
self.db = db
if 'logger' in kwargs:
self.log_... | self.stats_collection.drop() | conditional_block | |
model_manager.py | from datetime import datetime
class ModelManager(object):
def __init__(self, db, collection_name, has_stats=False, **kwargs):
|
def add_stats_collection(self):
self.stats_collection_name = '%s_stats' % self.collection_name
if self.stats_collection_name in self.db.collection_names():
self.stats_collection = self.db[self.stats_collection_name]
else:
self.stats_collection = self.db.create_colle... | self.property_helper = None
self.log_helper = None
self.collection_name = collection_name
self.db = db
if 'logger' in kwargs:
self.log_helper = kwargs['logger']
if collection_name in self.db.collection_names():
self.collection = self.db[collection_name]
... | identifier_body |
quicksort.js | const Comparator = require('../../util/comparator');
/**
* Swaps two elements in the array
*/
const swap = (array, x, y) => {
const tmp = array[y];
array[y] = array[x];
array[x] = tmp;
};
/**
* Chooses a pivot and makes every element that is
* lower than the pivot move to its left, and every
* greater elem... |
return array;
})(array, 0, array.length - 1);
};
module.exports = quicksortInit;
| {
const p = partition(array, comparator, lo, hi);
// Chooses only the smallest partition to use recursion on and
// tail-optimize the other. This guarantees O(log n) space in worst case.
if (p - lo < hi - p) {
quicksort(array, lo, p - 1);
lo = p + 1;
} else {
quicks... | conditional_block |
quicksort.js | const Comparator = require('../../util/comparator');
/**
* Swaps two elements in the array
*/
const swap = (array, x, y) => {
const tmp = array[y];
array[y] = array[x];
array[x] = tmp;
};
/**
* Chooses a pivot and makes every element that is
* lower than the pivot move to its left, and every
* greater elem... | if (p - lo < hi - p) {
quicksort(array, lo, p - 1);
lo = p + 1;
} else {
quicksort(array, p + 1, hi);
hi = p - 1;
}
}
return array;
})(array, 0, array.length - 1);
};
module.exports = quicksortInit; | random_line_split | |
test_template.py | #!/usr/bin/env python
#pylint: disable=missing-docstring
####################################################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simu... | unittest.main(verbosity=2) | conditional_block | |
test_template.py | #!/usr/bin/env python
#pylint: disable=missing-docstring
####################################################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simu... | (self):
html = str(self.soup)
self.assertIn('href="https://github.com/idaholab/moose/blob/master/framework/include/'\
'markers/BoxMarker.h"', html)
self.assertIn('href="https://github.com/idaholab/moose/blob/master/framework/src/'\
'markers/BoxMarker.C... | testCode | identifier_name |
test_template.py | #!/usr/bin/env python
#pylint: disable=missing-docstring
####################################################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simu... | root = moose_docs_file_tree({'framework': config})
node = root.findall('/BoxMarker')[0]
cls.html = cls.parser.convert(node)
#with open(node.markdown(), 'r') as fid:
# cls.html = fid.read()
cls.soup = bs4.BeautifulSoup(cls.html, "html.parser")
def testContent(self... | EXTENSIONS = ['MooseDocs.extensions.template', 'MooseDocs.extensions.app_syntax', 'meta']
@classmethod
def updateExtensions(cls, configs):
"""
Method to change the arguments that come from the configuration file for
specific tests. This way one can test optional arguments without perma... | identifier_body |
test_template.py | #!/usr/bin/env python
#pylint: disable=missing-docstring
####################################################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simu... | import bs4
import MooseDocs
from MooseDocs.common import moose_docs_file_tree
from MooseDocs.testing import MarkdownTestCase
class TestTemplate(MarkdownTestCase):
EXTENSIONS = ['MooseDocs.extensions.template', 'MooseDocs.extensions.app_syntax', 'meta']
@classmethod
def updateExtensions(cls, configs):
... | # See COPYRIGHT for full restrictions #
####################################################################################################
import unittest | random_line_split |
main.rs | fn is_prime(number: i32) -> bool {
if number % 2 == 0 && number != 2 || number == 1 {
return false;
}
let limit = (number as f32).sqrt() as i32 + 1;
// We test if the number is divisible by any odd number up to the limit
(3..limit).step_by(2).all(|x| number % x != 0)
}
fn main() {
pri... | () {
assert!(is_prime(2));
}
#[test]
fn test_many() {
let primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31];
assert!(primes.iter().all(|&x| is_prime(x)));
}
| test_two | identifier_name |
main.rs | fn is_prime(number: i32) -> bool {
if number % 2 == 0 && number != 2 || number == 1 {
return false;
}
let limit = (number as f32).sqrt() as i32 + 1;
// We test if the number is divisible by any odd number up to the limit
(3..limit).step_by(2).all(|x| number % x != 0)
}
fn main() {
pri... | } | random_line_split | |
main.rs | fn is_prime(number: i32) -> bool {
if number % 2 == 0 && number != 2 || number == 1 |
let limit = (number as f32).sqrt() as i32 + 1;
// We test if the number is divisible by any odd number up to the limit
(3..limit).step_by(2).all(|x| number % x != 0)
}
fn main() {
println!("{}", is_prime(15_485_863)); // The 1 000 000th prime.
println!("{}", is_prime(62_773_913)); // The product... | {
return false;
} | conditional_block |
main.rs | fn is_prime(number: i32) -> bool {
if number % 2 == 0 && number != 2 || number == 1 {
return false;
}
let limit = (number as f32).sqrt() as i32 + 1;
// We test if the number is divisible by any odd number up to the limit
(3..limit).step_by(2).all(|x| number % x != 0)
}
fn main() {
pri... |
#[test]
fn test_two() {
assert!(is_prime(2));
}
#[test]
fn test_many() {
let primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31];
assert!(primes.iter().all(|&x| is_prime(x)));
}
| {
// https://primes.utm.edu/notes/faq/one.html
assert!(!is_prime(1));
} | identifier_body |
bytecode-templates-test.ts | import { AST, ASTPlugin } from "@glimmer/syntax";
import GlimmerApp from '../../lib/broccoli/glimmer-app';
import { GlimmerAppOptions } from '../../lib/interfaces';
import { buildOutput, createTempDir, TempDir } from 'broccoli-test-helper';
import path = require('path');
import { readFileSync } from 'fs';
import * as ... | extends GlimmerApp {
public getRegistry() { return this.registry; }
}
describe('Bytecode Template Compilation', function() {
this.timeout(20000);
let input: TempDir;
const pkg = {
name: 'glimmer-app-test',
version: '0.1.0'
};
beforeEach(function() {
return createTempDir().then(tempDir => (in... | TestGlimmerApp | identifier_name |
bytecode-templates-test.ts | import { AST, ASTPlugin } from "@glimmer/syntax";
import GlimmerApp from '../../lib/broccoli/glimmer-app';
import { GlimmerAppOptions } from '../../lib/interfaces';
import { buildOutput, createTempDir, TempDir } from 'broccoli-test-helper';
import path = require('path');
import { readFileSync } from 'fs';
import * as ... |
const tsconfigContents = stripIndent`
{
"compilerOptions": {
"target": "es6",
"module": "es2015",
"inlineSourceMap": true,
"inlineSources": true,
"moduleResolution": "node",
"experimentalDecorators": true
},
"exclude": [
"node_modules",
... | {
let cli = new MockCLI();
let project = new Project(input.path(), pkg, cli.ui, cli);
project.initializeAddons();
project.addons = project.addons.concat(addons);
return new TestGlimmerApp({
project
}, options);
} | identifier_body |
bytecode-templates-test.ts | import { AST, ASTPlugin } from "@glimmer/syntax";
import GlimmerApp from '../../lib/broccoli/glimmer-app';
import { GlimmerAppOptions } from '../../lib/interfaces';
import { buildOutput, createTempDir, TempDir } from 'broccoli-test-helper';
import path = require('path');
import { readFileSync } from 'fs';
import * as ... | const wrapper = `(function(exports) { ${source}\n; return exports; })`;
const func = eval(wrapper);
const moduleExports = func({});
return moduleExports;
} | random_line_split | |
FlagsSeries.js | ates: {
hover: {
lineColor: 'black',
fillColor: '#FCFFC5'
}
},
style: {
fontSize: '11px',
fontWeight: 'bold',
textAlign: 'center'
},
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
y: -30
});
// 2 - Create the CandlestickSeries object
seriesTypes.flags = extendClass(seriesTypes... | // sort the data points
points.sort(function (a, b) {
return (a.x - b.x);
});
while (i-- && points[cursor]) {
point = points[cursor];
leftPoint = onData[i];
if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) {
if (point.x <= lastX) { // #803
point.plotY = lef... | currentDataGrouping = onSeries.currentDataGrouping;
lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374
| random_line_split |
FlagsSeries.js | 'fillColor',
stroke: 'color',
'stroke-width': 'lineWidth',
r: 'radius'
},
/**
* Extend the translate method by placing the point on the related series
*/
translate: function () {
seriesTypes.column.prototype.translate.apply(this);
var series = this,
options = series.options,
chart = series.ch... | {
each(['flag', 'circlepin', 'squarepin'], function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
} | conditional_block | |
IndicatorModel.js | /** |
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 version.
This program is distributed in the hope that it will be useful,
but WITHOUT AN... | EuBrazilCC UC3 Gateway
Copyright 2014-2015 EUBrazilCC (EU‐Brazil Cloud Connect) | random_line_split |
passability.py | # Passability types.
#
# @author Oktay Acikalin <oktay.acikalin@gmail.com>
# @copyright Oktay Acikalin
# @license MIT (LICENSE.txt)
# from json import load
from collections import OrderedDict
# from os.path import splitext, dirname, join
from os.path import dirname, join
# locals().update(load(open('%s.json' % ... | ('climb', {'none': [[[32, 0, 16, 16], [32, 0], [0, 0], 60]]}),
))
tile_size = [16, 16] | ('climb_platform', {'none': [[[16, 0, 16, 16], [16, 0], [0, 0], 60]]}), | random_line_split |
build_insert_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Phot... | (dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _val... | from_dao | identifier_name |
build_insert_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool; | #[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao... | random_line_split | |
build_insert_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Phot... |
}
#[test]
fn test_insert_query() {
let url = "postgres://postgres:p0stgr3s@localhost/bazaar_v6";
let pool = ManagedPool::init(&url, 1).unwrap();
let db = pool.connect().unwrap();
let mut query = Query::insert();
query.into_table("bazaar.product")
.set("name", &"product1")
.ret... | {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _value),
None => dao.set_null("url"),
}
dao
} | identifier_body |
vs9to10.py | #Run this file after automatic conversion of the VisualStudio 2008 solution by VisualStudio 2010.
#This can be done whenever the 2008 solution changes.
#It will make the necessary cleanup and updates to the vcxproj files
#the .props files need to be maintained by hand if the .vsprops files change
from __future__ ... | (src, dest):
for name in os.listdir(src):
path, ext = os.path.splitext(name)
if ext.lower() not in ('.vcxproj',):
continue
filename = os.path.normpath(os.path.join(src, name))
destname = os.path.normpath(os.path.join(dest, name))
print("%s -> %s" % (filen... | vs9to10 | identifier_name |
vs9to10.py | #Run this file after automatic conversion of the VisualStudio 2008 solution by VisualStudio 2010.
#This can be done whenever the 2008 solution changes.
#It will make the necessary cleanup and updates to the vcxproj files
#the .props files need to be maintained by hand if the .vsprops files change
from __future__ ... | if b"<ImportLibrary>" in line and b"</ImportLibrary>" in line:
continue
#add new property sheet to the pythoncore
if importgroup and "pythoncore" in name.lower():
if b"</ImportGroup>" in line:
if b"deb... | continue
if b"<ProgramDatabaseFile>" in line:
continue
| random_line_split |
vs9to10.py | #Run this file after automatic conversion of the VisualStudio 2008 solution by VisualStudio 2010.
#This can be done whenever the 2008 solution changes.
#It will make the necessary cleanup and updates to the vcxproj files
#the .props files need to be maintained by hand if the .vsprops files change
from __future__ ... |
if b"<ImportGroup Condition" in line:
importgroup = True
elif b"</ImportGroup>" in line:
importgroup = False
lines.append(line)
lastline = line
with open(destname, 'wb') as fout:
for line... | if b"debug.props" in lastline:
lines.append(b' <Import Project="pythoncore_d.props" />\r\n')
elif b"pythoncore" not in lastline:
lines.append(b' <Import Project="pythoncore.props" />\r\n') | conditional_block |
vs9to10.py | #Run this file after automatic conversion of the VisualStudio 2008 solution by VisualStudio 2010.
#This can be done whenever the 2008 solution changes.
#It will make the necessary cleanup and updates to the vcxproj files
#the .props files need to be maintained by hand if the .vsprops files change
from __future__ ... | continue
#add new property sheet to the pythoncore
if importgroup and "pythoncore" in name.lower():
if b"</ImportGroup>" in line:
if b"debug.props" in lastline:
lines.append(b' <Import P... | for name in os.listdir(src):
path, ext = os.path.splitext(name)
if ext.lower() not in ('.vcxproj',):
continue
filename = os.path.normpath(os.path.join(src, name))
destname = os.path.normpath(os.path.join(dest, name))
print("%s -> %s" % (filename, destname))
... | identifier_body |
index.ts | import { declare } from "@babel/helper-plugin-utils";
import syntaxFlow from "@babel/plugin-syntax-flow";
import { types as t } from "@babel/core";
export default declare((api, opts) => {
api.assertVersion(7);
const FLOW_DIRECTIVE = /(@flow(\s+(strict(-local)?|weak))?|@noflow)/;
let skipStrip = false;
const... | (
path,
{
file: {
ast: { comments },
},
},
) {
skipStrip = false;
let directiveFound = false;
if (comments) {
for (const comment of comments) {
if (FLOW_DIRECTIVE.test(comment.value)) {
directiveFo... | Program | identifier_name |
index.ts | import { declare } from "@babel/helper-plugin-utils";
import syntaxFlow from "@babel/plugin-syntax-flow";
import { types as t } from "@babel/core";
export default declare((api, opts) => {
api.assertVersion(7);
const FLOW_DIRECTIVE = /(@flow(\s+(strict(-local)?|weak))?|@noflow)/;
let skipStrip = false;
const... | ,
TypeCastExpression(path) {
if (skipStrip) return;
let { node } = path;
do {
node = node.expression;
} while (t.isTypeCastExpression(node));
path.replaceWith(node);
},
CallExpression({ node }) {
if (skipStrip) return;
node.typeArgume... | {
if (skipStrip) return;
if (
node.params.length > 0 &&
node.params[0].type === "Identifier" &&
node.params[0].name === "this"
) {
node.params.shift();
}
for (let i = 0; i < node.params.length; i++) {
const param = node.params[i];... | identifier_body |
index.ts | import { declare } from "@babel/helper-plugin-utils";
import syntaxFlow from "@babel/plugin-syntax-flow";
import { types as t } from "@babel/core";
export default declare((api, opts) => {
api.assertVersion(7);
const FLOW_DIRECTIVE = /(@flow(\s+(strict(-local)?|weak))?|@noflow)/;
let skipStrip = false;
const... | },
};
}); | }, | random_line_split |
nnet_lasagne.py |
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_scheme='Lin... |
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def sgd(cost, params, gamma):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
updates.append([p, p - g * gamma])
return updates
def model(X, w_h, w_o):
h = T.nn... | return np.zeros(X, dtype=theano.config.floatX) | identifier_body |
nnet_lasagne.py | time
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_scheme... | for start, end in batch_ids(batch_size, x_train,
train_idx):
err, acc = val_fn(x_train[val_idx], y_train[val_idx])
val_err += err
val_acc += acc
val_batches... | val_acc = 0
val_batches = 0 | random_line_split |
nnet_lasagne.py |
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_scheme='Lin... |
else:
network = lasagne.layers.DenseLayer(network,
widths[i],
nonlinearity=nonlins[i])
if drops[i] != None:
network = lasagne.layers.DropoutLayer(network, p=drops[i])
return netw... | network = lasagne.layers.InputLayer(shape=input_shape,
input_var=input_var) | conditional_block |
nnet_lasagne.py |
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_scheme='Lin... | (inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + b... | iterate_minibatches | identifier_name |
type-params-in-for-each.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 ... | pub fn main() { } | random_line_split | |
type-params-in-for-each.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 ... | <F>(lo: usize, hi: usize, mut it: F) where F: FnMut(usize) {
let mut lo_ = lo;
while lo_ < hi { it(lo_); lo_ += 1; }
}
fn create_index<T>(_index: Vec<S<T>> , _hash_fn: extern fn(T) -> usize) {
range_(0, 256, |_i| {
let _bucket: Vec<T> = Vec::new();
})
}
pub fn main() { }
| range_ | identifier_name |
images.py | import logging
from collections import Counter
from udata.commands import cli, header, success
log = logging.getLogger(__name__)
@cli.group('images')
def grp():
'''Images related operations'''
pass
def render_or_skip(obj, attr):
|
@grp.command()
def render():
'''Force (re)rendering stored images'''
from udata.core.organization.models import Organization
from udata.core.post.models import Post
from udata.core.reuse.models import Reuse
from udata.core.user.models import User
header('Rendering images')
count = Count... | try:
getattr(obj, attr).rerender()
obj.save()
return 1
except Exception as e:
log.warning('Skipped "%s": %s(%s)', obj, e.__class__.__name__, e)
return 0 | identifier_body |
images.py | import logging
from collections import Counter
from udata.commands import cli, header, success
log = logging.getLogger(__name__)
@cli.group('images')
def grp():
'''Images related operations'''
pass
def render_or_skip(obj, attr):
try:
getattr(obj, attr).rerender()
obj.save()
re... |
reuses = Reuse.objects(image__exists=True)
total['reuses'] = reuses.count()
log.info('Processing {0} reuse images'.format(total['reuses']))
for reuse in reuses:
count['reuses'] += render_or_skip(reuse, 'image')
log.info('''Summary:
Organization logos: {count[orgs]}/{total[orgs]}
U... | count['posts'] += render_or_skip(post, 'image') | conditional_block |
images.py | import logging
from collections import Counter
from udata.commands import cli, header, success
log = logging.getLogger(__name__)
@cli.group('images')
def grp():
'''Images related operations'''
pass
def render_or_skip(obj, attr):
try:
getattr(obj, attr).rerender()
obj.save()
re... | success('Images rendered') | '''.format(count=count, total=total)) | random_line_split |
images.py | import logging
from collections import Counter
from udata.commands import cli, header, success
log = logging.getLogger(__name__)
@cli.group('images')
def grp():
'''Images related operations'''
pass
def render_or_skip(obj, attr):
try:
getattr(obj, attr).rerender()
obj.save()
re... | ():
'''Force (re)rendering stored images'''
from udata.core.organization.models import Organization
from udata.core.post.models import Post
from udata.core.reuse.models import Reuse
from udata.core.user.models import User
header('Rendering images')
count = Counter()
total = Counter()
... | render | identifier_name |
mod.rs | use std::fmt;
use std::error::Error;
use std::sync::Mutex;
use CapabilitiesSource;
use gl;
use version::Api;
use version::Version;
pub use self::compute::{ComputeShader, ComputeCommand};
pub use self::program::Program;
pub use self::reflection::{Uniform, UniformBlock, BlockLayout, OutputPrimitives};
pub use self::ref... | <'a> {
/// Use GLSL source code.
SourceCode {
/// Source code of the vertex shader.
vertex_shader: &'a str,
/// Source code of the optional tessellation control shader.
tessellation_control_shader: Option<&'a str>,
/// Source code of the optional tessellation evaluation... | ProgramCreationInput | identifier_name |
mod.rs | use std::fmt;
use std::error::Error;
use std::sync::Mutex;
use CapabilitiesSource;
use gl;
use version::Api;
use version::Version;
pub use self::compute::{ComputeShader, ComputeCommand};
pub use self::program::Program;
pub use self::reflection::{Uniform, UniformBlock, BlockLayout, OutputPrimitives};
pub use self::ref... |
/// Source code of the optional tessellation evaluation shader.
pub tessellation_evaluation_shader: Option<&'a str>,
/// Source code of the optional geometry shader.
pub geometry_shader: Option<&'a str>,
/// Source code of the fragment shader.
pub fragment_shader: &'a str,
}
impl<'a> From<So... | pub tessellation_control_shader: Option<&'a str>, | random_line_split |
mod.rs | use std::fmt;
use std::error::Error;
use std::sync::Mutex;
use CapabilitiesSource;
use gl;
use version::Api;
use version::Version;
pub use self::compute::{ComputeShader, ComputeCommand};
pub use self::program::Program;
pub use self::reflection::{Uniform, UniformBlock, BlockLayout, OutputPrimitives};
pub use self::ref... |
/// Some shader compilers have race-condition issues, so we lock this mutex
/// in the GL thread every time we compile a shader or link a program.
// TODO: replace by a StaticMutex
lazy_static! {
static ref COMPILER_GLOBAL_LOCK: Mutex<()> = Mutex::new(());
}
/// Error that can be triggered when creating a `Progr... | {
ctxt.get_version() >= &Version(Api::Gl, 4, 1) || ctxt.get_version() >= &Version(Api::GlEs, 2, 0)
|| ctxt.get_extensions().gl_arb_get_programy_binary
} | identifier_body |
parser.js | function decodeCoordinate(coordinate, encodeOffset) {
var result = []
var cx, cy
var offset = encodeOffset.slice()
for (var i = 0, L = coordinate.length; i < L; i += 2) {
cx = coordinate.charCodeAt(i) - 64
cy = coordinate.charCodeAt(i + 1) - 64
cx = ((cx >> 1) ^ (-(cx & 1))) + offset[0]
cy = ((cy >> 1) ^ (... | (geoJSON) {
var decoder = {
MultiPolygon: function (coordinates, encodeOffset) {
return coordinates.map(function (coordinate, index) {
return decodeCoordinate(coordinate, encodeOffset[index])
})
},
Polygon: decodeCoordinate
}
var features = []
if (typeof geoJSON === 'string') {
geoJSON = JSON.pa... | decodeGeoJSON | identifier_name |
parser.js | function decodeCoordinate(coordinate, encodeOffset) {
var result = []
var cx, cy
var offset = encodeOffset.slice()
for (var i = 0, L = coordinate.length; i < L; i += 2) {
cx = coordinate.charCodeAt(i) - 64
cy = coordinate.charCodeAt(i + 1) - 64
cx = ((cx >> 1) ^ (-(cx & 1))) + offset[0]
cy = ((cy >> 1) ^ (... | )
})
} |
return new Region(
feature.properties.name,
coordinates,
feature.properties.cp | random_line_split |
parser.js | function decodeCoordinate(coordinate, encodeOffset) |
function decodeGeoJSON(geoJSON) {
var decoder = {
MultiPolygon: function (coordinates, encodeOffset) {
return coordinates.map(function (coordinate, index) {
return decodeCoordinate(coordinate, encodeOffset[index])
})
},
Polygon: decodeCoordinate
}
var features = []
if (typeof geoJSON === 'string... | {
var result = []
var cx, cy
var offset = encodeOffset.slice()
for (var i = 0, L = coordinate.length; i < L; i += 2) {
cx = coordinate.charCodeAt(i) - 64
cy = coordinate.charCodeAt(i + 1) - 64
cx = ((cx >> 1) ^ (-(cx & 1))) + offset[0]
cy = ((cy >> 1) ^ (-(cy & 1))) + offset[1]
offset[0] = cx
offset[1]... | identifier_body |
parser.js | function decodeCoordinate(coordinate, encodeOffset) {
var result = []
var cx, cy
var offset = encodeOffset.slice()
for (var i = 0, L = coordinate.length; i < L; i += 2) {
cx = coordinate.charCodeAt(i) - 64
cy = coordinate.charCodeAt(i + 1) - 64
cx = ((cx >> 1) ^ (-(cx & 1))) + offset[0]
cy = ((cy >> 1) ^ (... |
return new Region(
feature.properties.name,
coordinates,
feature.properties.cp
)
})
}
| {
coordinates = coordinates.map(function (coordinate) {
return [coordinate]
})
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.