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 |
|---|---|---|---|---|
recognition.py | # PyKinect
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON ... |
elif recognizer is None:
rec = ctypes.c_voidp()
_CreateRecognizer(None, ctypes.byref(rec))
self._rec = rec
else:
raise TypeError('Bad type for recognizer: ' + repr(recognizer))
def __del__(self):
# TODO: Need to shut down any listenin... | rec = ctypes.c_voidp()
_CreateRecognizer(recognizer._token, ctypes.byref(rec))
self._rec = rec | conditional_block |
recognition.py | # PyKinect
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON ... |
def load_grammar(self, grammar):
if isinstance(grammar, str):
grammar_obj = Grammar(grammar)
else:
grammar_obj = grammar
comGrammar = ctypes.c_voidp()
_LoadGrammar(grammar_obj.filename, self._rec, ctypes.byref(comGrammar))
grammar_obj._grammar = com... | self.recognize_async_stop()
_IUnknownRelease(self._rec) | identifier_body |
recognition.py | # PyKinect | # License at http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
# IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABLITY OR NON-INFR... | # Copyright(c) Microsoft Corporation
# 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 | random_line_split |
recognition.py | # PyKinect
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON ... | (object):
"""class used for adding/removing/invoking a set of listener functions"""
__slots__ = ['handlers']
def __init__(self):
self.handlers = []
def __iadd__(self, other):
self.handlers.append(other)
return self
def __isub__(self, other):
sel... | _event | identifier_name |
exp_app.js | var express = require('express');
var reload = require('reload');
var fs = require('fs');
var wss = new require('ws').Server({port: 3030});
var app = express();
var Chopper = require('./lib/Chopper');
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.use(require('./routes/index')... |
})
});
var chop = new Chopper();
chop.on('ready', function() {
console.log('Chopper ready');
app.set('chopper', chop);
});
chop.on('change', function(value) {
wss.clients.forEach(function (ws, index, list) {
ws.send(JSON.stringify(value));
})
});
chop.on('data', function(type,... | {
ws.close();
} | conditional_block |
exp_app.js | var express = require('express');
var reload = require('reload');
var fs = require('fs');
var wss = new require('ws').Server({port: 3030});
var app = express();
var Chopper = require('./lib/Chopper');
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.use(require('./routes/index')... | });
chop.on('data', function(type, data) {
fs.writeFile(type + Date.now() + '.csv', data, function (err) {
console.log(`${type} data saved`);
});
}); | wss.clients.forEach(function (ws, index, list) {
ws.send(JSON.stringify(value));
})
| random_line_split |
extensions.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::... | let name = T::name().to_uppercase();
self.extensions.borrow_mut().insert(name, box TypedWebGLExtensionWrapper::<T>::new());
}
pub fn get_suported_extensions(&self) -> Vec<&'static str> {
self.extensions.borrow().iter()
.filter(|ref v| v.1.is_supported(&se... | }
}
pub fn register<T:'static + WebGLExtension + JSTraceable + HeapSizeOf>(&self) { | random_line_split |
extensions.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::... |
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T: 'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
extension.as_any().downcast_ref::<Typ... | {
None
} | conditional_block |
extensions.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::... | () -> WebGLExtensionFeatures {
WebGLExtensionFeatures {
gl_extensions: HashSet::new(),
disabled_tex_types: DEFAULT_DISABLED_TEX_TYPES.iter().cloned().collect(),
not_filterable_tex_types: DEFAULT_NOT_FILTERABLE_TEX_TYPES.iter().cloned().collect(),
effective_tex_int... | default | identifier_name |
extensions.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::... |
pub fn get_query_parameter_handler(&self, name: GLenum) -> Option<Ref<Box<WebGLQueryParameterFunc>>> {
ref_filter_map(self.features.borrow(), |features| {
features.query_parameter_handlers.get(&name).map(|item| &item.func)
})
}
fn register_all_extensions(&self) {
self.... | {
let handler = WebGLQueryParameterHandler {
func: f
};
self.features.borrow_mut().query_parameter_handlers.insert(name, handler);
} | identifier_body |
literals.rs | recognize2!($i, call!($f))
);
);
/// [A literal value]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
///
/// This has to be used with the `Literal` struct
#[derive(Debug, PartialEq)]
pub enum LiteralValue {
Null,
Number(f64),
String(String),
Boolean(bool),
Regexp { p... | <'a> {
pub value: LiteralValue,
pub loc: Location<'a>
}
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LineTerminator
const LINE_TERMINATORS: &'static str = "\n\r\u{2028}\u{2029}";
// equivalent to: "\u{000a}\u{000d}\u{2028}\u{2029}";
/// null literal value parser
/// https://www.ecma-int... | Literal | identifier_name |
literals.rs | }
});
($i:expr, $f:expr) => (
recognize2!($i, call!($f))
);
);
/// [A literal value]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
///
/// This has to be used with the `Literal` struct
#[derive(Debug, PartialEq)]
pub enum LiteralValue {
Null,
Number(f64),
Str... | $crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i) | random_line_split | |
bio.js | /**
* Bio component that queries for data
* with Gatsby's StaticQuery component
*
* See: https://www.gatsbyjs.org/docs/static-query/
*/
import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Image from "gatsby-image"
import { rhythm } from "../utils/typography"
function | () {
return (
<StaticQuery
query={bioQuery}
render={data => {
const { author, social } = data.site.siteMetadata
return (
<div
style={{
display: `flex`,
marginBottom: rhythm(2.5),
}}
>
<Image
... | Bio | identifier_name |
bio.js | /**
* Bio component that queries for data
* with Gatsby's StaticQuery component
*
* See: https://www.gatsbyjs.org/docs/static-query/
*/
import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Image from "gatsby-image"
import { rhythm } from "../utils/typography"
function Bio() | borderRadius: `100%`,
}}
imgStyle={{
borderRadius: `50%`,
}}
/>
<p>
I'm <strong>{author}</strong>, a software engineer working in London.
This is my tech blog. Find out more about me via
... | {
return (
<StaticQuery
query={bioQuery}
render={data => {
const { author, social } = data.site.siteMetadata
return (
<div
style={{
display: `flex`,
marginBottom: rhythm(2.5),
}}
>
<Image
... | identifier_body |
bio.js | /**
* Bio component that queries for data
* with Gatsby's StaticQuery component
*
* See: https://www.gatsbyjs.org/docs/static-query/
*/
import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Image from "gatsby-image"
import { rhythm } from "../utils/typography"
function Bio() {
return ... | }
site {
siteMetadata {
author
social {
twitter,
github,
stackoverflow
}
}
}
}
`
export default Bio | ...GatsbyImageSharpFixed
}
} | random_line_split |
test_rxfreq_not_num.py | #!/usr/bin/python
# write an experiment that raises an exception
import sys
import os
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
import experiments.superdarn_common_fields as scf
from experiment_prototype.experiment_prototype import ExperimentPrototype
from utils.experiment_options.expe... | "beam_angle": scf.STD_16_BEAM_ANGLE,
"beam_order": beams_to_use,
"scanbound": [i * 3.5 for i in range(len(beams_to_use))], #1 min scan
"rxfreq" : '12005', # not an int or float
"acf": True,
"xcf": True, # cross-correlation processing
"... | cpid = 1
super(TestExperiment, self).__init__(cpid)
if scf.IS_FORWARD_RADAR:
beams_to_use = scf.STD_16_FORWARD_BEAM_ORDER
else:
beams_to_use = scf.STD_16_REVERSE_BEAM_ORDER
if scf.opts.site_id in ["cly", "rkn", "inv"]:
num_ranges = scf.POLARDARN_NUM_... | identifier_body |
test_rxfreq_not_num.py | #!/usr/bin/python
# write an experiment that raises an exception
import sys
import os
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
import experiments.superdarn_common_fields as scf
from experiment_prototype.experiment_prototype import ExperimentPrototype
from utils.experiment_options.expe... | num_ranges = scf.POLARDARN_NUM_RANGES
if scf.opts.site_id in ["sas", "pgr"]:
num_ranges = scf.STD_NUM_RANGES
slice_1 = { # slice_id = 0, there is only one slice.
"pulse_sequence": scf.SEQUENCE_7P,
"tau_spacing": scf.TAU_SPACING_7P,
"pulse_len... | else:
beams_to_use = scf.STD_16_REVERSE_BEAM_ORDER
if scf.opts.site_id in ["cly", "rkn", "inv"]: | random_line_split |
test_rxfreq_not_num.py | #!/usr/bin/python
# write an experiment that raises an exception
import sys
import os
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
import experiments.superdarn_common_fields as scf
from experiment_prototype.experiment_prototype import ExperimentPrototype
from utils.experiment_options.expe... | (self):
cpid = 1
super(TestExperiment, self).__init__(cpid)
if scf.IS_FORWARD_RADAR:
beams_to_use = scf.STD_16_FORWARD_BEAM_ORDER
else:
beams_to_use = scf.STD_16_REVERSE_BEAM_ORDER
if scf.opts.site_id in ["cly", "rkn", "inv"]:
num_ranges = sc... | __init__ | identifier_name |
test_rxfreq_not_num.py | #!/usr/bin/python
# write an experiment that raises an exception
import sys
import os
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
import experiments.superdarn_common_fields as scf
from experiment_prototype.experiment_prototype import ExperimentPrototype
from utils.experiment_options.expe... |
slice_1 = { # slice_id = 0, there is only one slice.
"pulse_sequence": scf.SEQUENCE_7P,
"tau_spacing": scf.TAU_SPACING_7P,
"pulse_len": scf.PULSE_LEN_45KM,
"num_ranges": num_ranges,
"first_range": scf.STD_FIRST_RANGE,
"intt": 3500, # du... | num_ranges = scf.STD_NUM_RANGES | conditional_block |
_low_test.py | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SE... |
def tearDown(self):
self.server.shutdown()
del self.client_channel
self.client_completion_queue.shutdown()
self.server_completion_queue.shutdown()
while True:
client_event, server_event = wait_for_events(
[self.client_completion_queue, self.server_completion_queue],
fl... | self.server_completion_queue = _low.CompletionQueue()
self.server = _low.Server(self.server_completion_queue, [])
self.port = self.server.add_http2_port('[::]:0')
self.client_completion_queue = _low.CompletionQueue()
self.client_channel = _low.Channel('localhost:%d'%self.port, [])
self.server.start... | identifier_body |
_low_test.py | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SE... | (completion_queues, deadline):
"""
Args:
completion_queues: list of completion queues to wait for events on
deadline: absolute deadline to wait until
Returns:
a sequence of events of length len(completion_queues).
"""
results = [None] * len(completion_queues)
lock = threading.Lock()
threads ... | wait_for_events | identifier_name |
_low_test.py | , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR S... | self.client_completion_queue.shutdown()
self.server_completion_queue.shutdown()
while True:
client_event, server_event = wait_for_events(
[self.client_completion_queue, self.server_completion_queue],
float("+inf"))
if (client_event.type == _types.EventType.QUEUE_SHUTDOWN and
... | del self.client_channel
| random_line_split |
_low_test.py | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SE... |
return results
class InsecureServerInsecureClient(unittest.TestCase):
def setUp(self):
self.server_completion_queue = _low.CompletionQueue()
self.server = _low.Server(self.server_completion_queue, [])
self.port = self.server.add_http2_port('[::]:0')
self.client_completion_queue = _low.Completion... | thread.join() | conditional_block |
constants.py | # Bzrflag
# Copyright 2008-2011 Brigham Young University
#
# This file is part of Bzrflag.
# | #
# Bzrflag is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
... | # Bzrflag 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. | random_line_split |
PhongShader.ts | import {ShaderBlocks} from "./ShaderBlocks";
export class PhongShader {
public static readonly vertexShader =
ShaderBlocks.glVersion300
.concat(ShaderBlocks.VertexInput)
.concat(ShaderBlocks.PhongVertexOutputs)
.concat(ShaderBlocks.MVPUniforms)
.concat(
[
"void main(void) {",
],... | "Light curLight = light[i];",
"vec3 DiffuseLightColor = PhongLightning(i, surfaceNormal, vWorldPos.xyz, albedo.xyz);",
"DiffuseLightColor = DiffuseLightColor * ShadowAttenuation(curLight, vWorldPos);",
"lightsColor += DiffuseLightColor;",
"}",
... | random_line_split | |
PhongShader.ts | import {ShaderBlocks} from "./ShaderBlocks";
export class | {
public static readonly vertexShader =
ShaderBlocks.glVersion300
.concat(ShaderBlocks.VertexInput)
.concat(ShaderBlocks.PhongVertexOutputs)
.concat(ShaderBlocks.MVPUniforms)
.concat(
[
"void main(void) {",
],
)
.concat(ShaderBlocks.mvpAndPosCalc)
.concat(
[
... | PhongShader | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub ... | {
let type_ = syn::parse_macro_input(input).unwrap();
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis != syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
binding.field.ide... | identifier_body | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub ... |
"".to_owned()
});
"".to_owned()
}
| {
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub ... | let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis != syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
}
"... | }
fn expand_string(input: &str) -> String {
let type_ = syn::parse_macro_input(input).unwrap();
| random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub ... | (input: &str) -> String {
let type_ = syn::parse_macro_input(input).unwrap();
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis != syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
... | expand_string | identifier_name |
svd-pgm-avg.py | (self, matrix=[[]], width=0, height=0, depth=0):
self.matrix = matrix
self.width = width
self.height = height
self.depth = depth
def set_width_and_height(self, width, height):
self.width = width
self.height = height
self.matrix = [[0 for j in xrange(height)] for i in xrange(width)]
def multiply_matric... | __init__ | identifier_name | |
svd-pgm-avg.py | iter(matrixScopy, op_flags=["readwrite"]):
if i < kmin or i >= kmax:
t[...] = 0
else:
if contrast:
t[...] = t * contrast_factor #* math.pi / 2
i += 1
# when kmax is 0 then drop eigen values less than 1.0E-14
else:
for t in numpy.nditer(matrixScopy, op_flags=["readwrite"]):
if round(t, 14) <... | for value in line.split():
if col >= image.width:
row += 1
col = 0
# rows which are all black become all white
if rownull:
for x in xrange(0, image.width):
image.matrix[row][x] = image.depth
rownull = True
image.matrix[row][col] = value
if int(value) != 0:
ro... | image.depth = int(line)
else: | random_line_split |
svd-pgm-avg.py |
def multiply_matrices(matrixU, matrixS, matrixVt, kmin, kmax, depth, rescale=False, contrast=False):
matrixScopy = matrixS.copy()
# when kmax is not 0 use the provided kmax
if kmax > 0:
i = 0
contrast_factor = (1.0 + (1 - (math.log(kmax, 2) / 10)))
for t in numpy.nditer(matrixScopy, op_flags=["readwrite"])... | self.width = width
self.height = height
self.matrix = [[0 for j in xrange(height)] for i in xrange(width)] | identifier_body | |
svd-pgm-avg.py | iter(matrixScopy, op_flags=["readwrite"]):
if i < kmin or i >= kmax:
t[...] = 0
else:
if contrast:
t[...] = t * contrast_factor #* math.pi / 2
i += 1
# when kmax is 0 then drop eigen values less than 1.0E-14
else:
for t in numpy.nditer(matrixScopy, op_flags=["readwrite"]):
if round(t, 14) <... | image.matrix[row][x] = image.depth
rownull = True
image.matrix[row][col] = value
if int(value) != 0:
rownull = False
col += 1
# columns which are all black become all white
for x in xrange(0, image.width):
colnull = True
for y in xrange(0, image.height):
if int(image.matrix[y][... | if line[0] == '#':
pass
elif line[0] == 'P' and line[1] == '2':
pass
elif image.width == 0 and image.height == 0:
x = 0
y = 0
x, y = [int(n) for n in line.split()]
image.set_width_and_height(x, y)
elif image.depth == 0:
image.depth = int(line)
else:
for value in line.split():
if col ... | conditional_block |
top-menu.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'top-menu',
template: `
<div class="ui secondary pointing inverted red menu">
<div class="header item">
The Forum
</div... |
logout() {
this.authService.deauthenticate();
this.router.navigate(['/login']);
}
}
| {
} | identifier_body |
top-menu.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
| @Component({
selector: 'top-menu',
template: `
<div class="ui secondary pointing inverted red menu">
<div class="header item">
The Forum
</div>
<a class="item" [class.active]="selected == 'threads'"
[routerLink]="['/']">
Threads
</a>
<a class="item" [class.... | import { AuthService } from '../services/auth.service';
| random_line_split |
top-menu.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'top-menu',
template: `
<div class="ui secondary pointing inverted red menu">
<div class="header item">
The Forum
</div... | {
@Input() selected: string = 'none';
constructor(
public authService: AuthService,
private router: Router) {
}
logout() {
this.authService.deauthenticate();
this.router.navigate(['/login']);
}
}
| TopMenuComponent | identifier_name |
user.info.component.ts | import {topmost} from "ui/frame";
import {Page} from "ui/page";
import {Observable, EventData} from "data/observable";
import {View} from "ui/core/view";
import {Inject, Injectable, Component, OnInit, ViewChild, Input} from '@angular/core'
import {CoinsPipe} from '../../util/pipes/currency.pipe'
import {UserService} fr... | () {
this._userService.getUser()
.then((_userFactory : UserFactory) => {
this.user = _userFactory
})
}
public goToAvatar () : void {
let avatar = this.page.getViewById('avatar')
avatar.animate({
scale: { x: 1.2, y... | ngOnInit | identifier_name |
user.info.component.ts | import {topmost} from "ui/frame";
import {Page} from "ui/page";
import {Observable, EventData} from "data/observable";
import {View} from "ui/core/view";
import {Inject, Injectable, Component, OnInit, ViewChild, Input} from '@angular/core'
import {CoinsPipe} from '../../util/pipes/currency.pipe'
import {UserService} fr... |
ngOnInit () {
this._userService.getUser()
.then((_userFactory : UserFactory) => {
this.user = _userFactory
})
}
public goToAvatar () : void {
let avatar = this.page.getViewById('avatar')
avatar.animate({
... | {
} | identifier_body |
user.info.component.ts | import {topmost} from "ui/frame";
import {Page} from "ui/page";
import {Observable, EventData} from "data/observable";
import {View} from "ui/core/view";
import {Inject, Injectable, Component, OnInit, ViewChild, Input} from '@angular/core'
import {CoinsPipe} from '../../util/pipes/currency.pipe'
import {UserService} fr... | selector: 'user-info',
templateUrl: './user.info.template.html',
styleUrls: ['./user.info.css'],
providers : [],
pipes: [CoinsPipe]
})
@Injectable()
export class UserInfoComponent implements OnInit{
constructor (private page : Page,
public user : UserFactory,
... |
@Component({
moduleId: module.id, | random_line_split |
CachedProperty.py | # NOTE: this should inherit from (object) to function correctly with python 2.7
class CachedProperty(object):
""" A property that is only computed once per instance and
then stores the result in _cached_properties of the object.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3... |
@staticmethod
def is_cached(obj, propname):
if hasattr(obj, '_cached_properties') and propname in obj._cached_properties:
return True
else:
return False | obj._cached_properties = {} | conditional_block |
CachedProperty.py | # NOTE: this should inherit from (object) to function correctly with python 2.7
class CachedProperty(object):
""" A property that is only computed once per instance and
then stores the result in _cached_properties of the object.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3... | def clear(obj):
"""clears cache of obj"""
if hasattr(obj, '_cached_properties'):
obj._cached_properties = {}
@staticmethod
def is_cached(obj, propname):
if hasattr(obj, '_cached_properties') and propname in obj._cached_properties:
return True
else:
... |
@staticmethod | random_line_split |
CachedProperty.py | # NOTE: this should inherit from (object) to function correctly with python 2.7
class CachedProperty(object):
""" A property that is only computed once per instance and
then stores the result in _cached_properties of the object.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3... |
def __get__(self, obj, cls):
if obj is None:
return self
propname = self.func.__name__
if not hasattr(obj, '_cached_properties'):
obj._cached_properties = {}
if propname not in obj._cached_properties:
obj._cached_properties[propname] = self.fu... | self.__doc__ = getattr(func, '__doc__')
self.func = func | identifier_body |
CachedProperty.py | # NOTE: this should inherit from (object) to function correctly with python 2.7
class CachedProperty(object):
""" A property that is only computed once per instance and
then stores the result in _cached_properties of the object.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3... | (obj):
"""clears cache of obj"""
if hasattr(obj, '_cached_properties'):
obj._cached_properties = {}
@staticmethod
def is_cached(obj, propname):
if hasattr(obj, '_cached_properties') and propname in obj._cached_properties:
return True
else:
ret... | clear | identifier_name |
mir_codegen_switch.rs | // run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2, | match x {
Abc::D => true,
_ => false
}
}
fn main() {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, f... | Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool { | random_line_split |
mir_codegen_switch.rs | // run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
match x {
Abc::D => true,
_ => false
}
}
fn | () {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
}
| main | identifier_name |
mir_codegen_switch.rs | // run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
match x {
Abc::D => true,
_ => false
}
}
fn main() | {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
} | identifier_body | |
abi.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... |
#[inline]
pub fn data(&self) -> &'static AbiData {
&AbiDatas[self.index()]
}
pub fn name(&self) -> &'static str {
self.data().name
}
}
impl fmt::Show for Abi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", self.name())
}
}
impl fmt::S... | {
*self as uint
} | identifier_body |
abi.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... | assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
}
#[test]
fn lookup_baz() {
let abi = lookup("baz");
assert!(abi.is_none());
}
#[test]
fn indices_are_correct() {
for (i, abi_data) in AbiDatas.iter().enumerate() {
assert_eq!(i, abi_data.abi.index());
}
} | fn lookup_cdecl() {
let abi = lookup("cdecl"); | random_line_split |
abi.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 abi = lookup("cdecl");
assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
}
#[test]
fn lookup_baz() {
let abi = lookup("baz");
assert!(abi.is_none());
}
#[test]
fn indices_are_correct() {
for (i, abi_data) in AbiDatas.iter().enumerate() {
assert_eq!(i, abi_data.abi.ind... | lookup_cdecl | identifier_name |
test.rs | extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex... | () {
//PollRound::make_poll();
//VoteRound::form_vote();
println!("{:?}", VotingOutcome::validate_outcome());
/*
let the_keys = KeyPair::create().unwrap();
let omni_list = get_omniwalletorg(56);
let our_keys = PollPersona::import_keys();
let keys = our_keys.return_keys();
let our_po... | main | identifier_name |
test.rs | extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex... |
if list_elements[thethings].balance > 0 {
int_new += 1;
println!("#{:?}", int_new);
println!("address: {:?}", &list_elements[thethings].address);
println!("safe exchange coin balance: {:?}", &list_elements[thethings].balance);
... | for thethings in 0..list_elements.len() { | random_line_split |
test.rs | extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex... |
print!("\n");
let contains_or = the_list.check_existence("15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh".to_string());
print!("Does the address contain? 15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh : {:?} \n", contains_or);
let mut int_new = 0;
for thethings in 0..list_elements.len() {
if list_... | {
//PollRound::make_poll();
//VoteRound::form_vote();
println!("{:?}", VotingOutcome::validate_outcome());
/*
let the_keys = KeyPair::create().unwrap();
let omni_list = get_omniwalletorg(56);
let our_keys = PollPersona::import_keys();
let keys = our_keys.return_keys();
let our_poll ... | identifier_body |
index.ts | import * as PIXI from "pixi.js";
import { Chart } from "./chart";
import { CandleSeries, CandleData } from "./series/candle-series/candle-series";
| } ();
// PIXI.DisplayObject.prototype.transform.prototype.position = new PIXI.Point(100, 100);
let chart = new Chart(800, 600);
document.body.appendChild(chart.Renderer.view);
let series: CandleSeries;
$.getJSON("../example/sample-data/eurusd.json", (response: Array<CandleData>) => {
console.log(response);
s... | PIXI.Transform.prototype.position = function (): PIXI.Point {
console.log("injection hack");
return new PIXI.Point(100, 100); | random_line_split |
setup.py | """
flask.ext.acl
=============
This extension provides an Access Control implementation for `tipfy <http://www.tipfy.org/>`_. | -----
* `Documentation <http://www.tipfy.org/wiki/extensions/acl/>`_
* `Source Code Repository <http://code.google.com/p/tipfy-ext-acl/>`_
* `Issue Tracker <http://code.google.com/p/tipfy-ext-acl/issues/list>`_
About tipfy
-----------
* `Home page <http://www.tipfy.org/>`_
* `Extension list <http://www.tipfy.org/wiki/... |
Links | random_line_split |
spinner-store.js | var AppDispatcher = require('../dispatcher/app-dispatcher'),
EventEmitter = require('events').EventEmitter,
JPSConstants = require('../constants/jetpack-onboarding-constants');
var CHANGE_EVENT = 'change';
var spinnerEnabled = false,
spinnerMessage = null;
function show(message) {
spinnerEnabled = true;
spinner... | // no op
}
});
module.exports = SpinnerStore; | break;
default: | random_line_split |
spinner-store.js | var AppDispatcher = require('../dispatcher/app-dispatcher'),
EventEmitter = require('events').EventEmitter,
JPSConstants = require('../constants/jetpack-onboarding-constants');
var CHANGE_EVENT = 'change';
var spinnerEnabled = false,
spinnerMessage = null;
function | (message) {
spinnerEnabled = true;
spinnerMessage = message;
}
function hide() {
spinnerEnabled = false;
spinnerMessage = null;
}
var SpinnerStore = _.extend({}, EventEmitter.prototype, {
showing: function() {
return spinnerEnabled;
},
getMessage: function() {
return spinnerMessage;
},
addChangeListene... | show | identifier_name |
spinner-store.js | var AppDispatcher = require('../dispatcher/app-dispatcher'),
EventEmitter = require('events').EventEmitter,
JPSConstants = require('../constants/jetpack-onboarding-constants');
var CHANGE_EVENT = 'change';
var spinnerEnabled = false,
spinnerMessage = null;
function show(message) {
spinnerEnabled = true;
spinner... |
var SpinnerStore = _.extend({}, EventEmitter.prototype, {
showing: function() {
return spinnerEnabled;
},
getMessage: function() {
return spinnerMessage;
},
addChangeListener: function(callback) {
this.on( CHANGE_EVENT, callback );
},
removeChangeListener: function(callback) {
this.removeListener( C... | {
spinnerEnabled = false;
spinnerMessage = null;
} | identifier_body |
watch.ts | import { Command, flags } from "@oclif/command";
import chalk from "chalk";
import chokidar from "chokidar";
import fs from "fs";
import path from "path";
import WebSocket from "ws";
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const fsp = fs.promises;
interface Args {
[type: string]: strin... | ordered[type] = filename;
}
return ordered;
};
readFile = async (fileName: string): Promise<string | undefined> => {
try {
const read = await fsp.readFile(fileName, "utf8");
return read;
} catch (error) {
console.error(`❌ Could not open ${fileName}: ${error}`);
return und... | console.error(
`❌ Duplicate ${type} files: ${ordered[type]} and ${filename}`
);
this.exit(1);
}
| conditional_block |
watch.ts | import { Command, flags } from "@oclif/command";
import chalk from "chalk";
import chokidar from "chokidar";
import fs from "fs";
import path from "path";
import WebSocket from "ws";
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const fsp = fs.promises;
interface Args {
[type: string]: strin... | onst { args: unorderedArgs, flags } = this.parse(Watch);
const args = this.reorder(unorderedArgs);
console.info(chalk.blue(`💂 starting on port ${flags.port}...`));
await this.watchFile(args.substance, "substance");
await this.watchFile(args.style, "style");
await this.watchFile(args.domain, "doma... | c | identifier_name |
watch.ts | import { Command, flags } from "@oclif/command";
import chalk from "chalk";
import chokidar from "chokidar";
import fs from "fs";
import path from "path";
import WebSocket from "ws";
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const fsp = fs.promises;
interface Args {
[type: string]: strin... | { name: "domain", required: true },
];
current: Args = {
substance: "",
style: "",
domain: "",
};
currentFilenames: Args = {
substance: "",
style: "",
domain: "",
};
wss: WebSocket.Server | undefined = undefined;
sendFiles = async () => {
const {
substance: substa... | };
static args = [
{ name: "substance", required: true },
{ name: "style", required: true }, | random_line_split |
githubcron.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License... | import os, sys, re, urllib, json, subprocess
import time
import urllib.request
import smtplib
from email.mime.text import MIMEText
# Function for fetching JSON via HTTPS
def getJSON(url, creds = None, cookie = None):
headers = {}
if creds and len(creds) > 0:
xcreds = creds.encode(encoding='ascii', erro... | # limitations under the License.
| random_line_split |
githubcron.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License... |
# Get the current queue
js = getJSON("https://reporeq.apache.org/queue.json")
created = 0
# If queue is valid:
if js:
print("analysing %u items" % len(js))
# For each item:
# - Check that it hasn't been mirrored yet
# - Check that a repo with this name doesn't exist already
# - Check that n... | headers = {}
if creds and len(creds) > 0:
xcreds = creds.encode(encoding='ascii', errors='replace')
auth = base64.encodebytes(xcreds).decode('ascii', errors='replace').replace("\n", '')
headers = {"Content-type": "application/json",
"Accept": "*/*",
... | identifier_body |
githubcron.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License... | (url, creds = None, cookie = None):
headers = {}
if creds and len(creds) > 0:
xcreds = creds.encode(encoding='ascii', errors='replace')
auth = base64.encodebytes(xcreds).decode('ascii', errors='replace').replace("\n", '')
headers = {"Content-type": "application/json",
... | getJSON | identifier_name |
githubcron.py | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License... | if os.path.exists("/x1/git/mirrors/%s" % reponame):
print("%s is there, adding web hooks" % reponame)
try:
xreponame = reponame.replace(".git", "") # Cut off the .git part, so GH will not bork
inp = subprocess.check_output("/usr/local/e... | print("analysing %u items" % len(js))
# For each item:
# - Check that it hasn't been mirrored yet
# - Check that a repo with this name doesn't exist already
# - Check that name is valid
# - Mirror repo if all is okay
for item in js:
# Make sure this is a GH integration request AND i... | conditional_block |
vcard.py | # Xandikos
# Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
#
# 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; version 3
# of the License or (at your option) any later version of
# ... |
class VCardFile(File):
content_type = "text/vcard"
def __init__(self, content, content_type):
super(VCardFile, self).__init__(content, content_type)
self._addressbook = None
def validate(self):
c = b"".join(self.content).strip()
# TODO(jelmer): Do more extensive checking ... | random_line_split | |
vcard.py | # Xandikos
# Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
#
# 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; version 3
# of the License or (at your option) any later version of
# ... | self.content_type,
self.content,
"Invalid VCard file")
@property
def addressbook(self):
if self._addressbook is None:
import vobject
text = b"".join(self.content).decode('utf-8', 'surrogateescape')
try:
... | ontent_type = "text/vcard"
def __init__(self, content, content_type):
super(VCardFile, self).__init__(content, content_type)
self._addressbook = None
def validate(self):
c = b"".join(self.content).strip()
# TODO(jelmer): Do more extensive checking of VCards
if not c.sta... | identifier_body |
vcard.py | # Xandikos
# Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
#
# 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; version 3
# of the License or (at your option) any later version of
# ... | return self._addressbook
| mport vobject
text = b"".join(self.content).decode('utf-8', 'surrogateescape')
try:
self._addressbook = vobject.readOne(text)
except vobject.base.ParseError as e:
raise InvalidFileContents(self.content_type, self.content, str(e))
| conditional_block |
vcard.py | # Xandikos
# Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
#
# 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; version 3
# of the License or (at your option) any later version of
# ... | self):
c = b"".join(self.content).strip()
# TODO(jelmer): Do more extensive checking of VCards
if not c.startswith((b"BEGIN:VCARD\r\n", b"BEGIN:VCARD\n")) or not c.endswith(
b"\nEND:VCARD"
):
raise InvalidFileContents(
self.content_type,
... | alidate( | identifier_name |
sticky-header.component.ts | import {Component, OnInit, NgZone, Inject} from 'angular2/core';
import {FrontEnd} from './objects/frontEnd.interface';
import {ProgressTrackerComponent} from './progress-tracker.component';
import {SwapPageComponent} from './swap-page.component';
import {StyleConstants} from './Constants';
import EventRegistrar from '... | } | return (document.documentElement.scrollTop || document.body.scrollTop) > this.headerOffset;
}
| random_line_split |
sticky-header.component.ts | import {Component, OnInit, NgZone, Inject} from 'angular2/core';
import {FrontEnd} from './objects/frontEnd.interface';
import {ProgressTrackerComponent} from './progress-tracker.component';
import {SwapPageComponent} from './swap-page.component';
import {StyleConstants} from './Constants';
import EventRegistrar from '... | () : boolean {
return (document.documentElement.scrollTop || document.body.scrollTop) > this.headerOffset;
}
}
| checkVisible | identifier_name |
sticky-header.component.ts | import {Component, OnInit, NgZone, Inject} from 'angular2/core';
import {FrontEnd} from './objects/frontEnd.interface';
import {ProgressTrackerComponent} from './progress-tracker.component';
import {SwapPageComponent} from './swap-page.component';
import {StyleConstants} from './Constants';
import EventRegistrar from '... |
checkVisible () : boolean {
return (document.documentElement.scrollTop || document.body.scrollTop) > this.headerOffset;
}
}
| {
this.EventRegistrar.register(window, 'onscroll', () => {
this.zone.run(() => {
this.isVisible = this.checkVisible();
});
});
this.WatchCSSMedia.onWidthGreaterThan(StyleConstants.WIDTH_BREAKPOINT,
(event) => {
this.zone.run(() => {
this.headerOffset = event.matches ? S... | identifier_body |
cr1.rs | #[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `CR1` reader - Compare Register for Channel 1"]
pub struct CR1_R(crate::FieldReader<u16, u16>);
impl CR1_R {
pub(crate) fn new(bits: u16) -> Self {
CR1_R(... | {
&self.0
} | identifier_body |
cr1.rs | #[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) ... | (&self) -> CR1_R {
CR1_R::new((self.bits & 0xffff) as u16)
}
}
#[doc = "Channel 1 Compare Value\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr1](index.html) module"]
pub struct CR1_... | cr1 | identifier_name |
cr1.rs | #[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R { | &self.0
}
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `CR1` reader - Compare Register for Channel 1"]
pub struct CR1_R(crate::FieldReader<u16, u16>);
impl CR1_R {
pub(crate) fn new(bits: u16) -> ... | type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target { | random_line_split |
bitfield-enum-repr-c.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types, | impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitOr<Foo> for Foo {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
... | non_upper_case_globals
)]
| random_line_split |
bitfield-enum-repr-c.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitO... |
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo(pub ::std::os::raw::c_int);
| {
self.0 &= rhs.0;
} | identifier_body |
bitfield-enum-repr-c.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitO... | (self, other: Self) -> Self {
Foo(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for Foo {
#[inline]
fn bitand_assign(&mut self, rhs: Foo) {
self.0 &= rhs.0;
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo(pub ::std::os::raw::c_int);
| bitand | identifier_name |
ApplicationCacheItemsView.js | conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AN... | {
var data = {};
var resource = this._resources[i];
data[0] = resource.url;
data[1] = resource.type;
data[2] = Number.bytesToString(resource.size);
var node = new WebInspector.DataGridNode(data);
node.resource = resource;
no... | conditional_block | |
ApplicationCacheItemsView.js | 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IM... | function localeCompare(field, resource1, resource2)
{
return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + "")
}
var comparator;
switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) {
case 0: comparator = localeCompare.bi... |
function numberCompare(field, resource1, resource2)
{
return sortDirection * (resource1[field] - resource2[field]);
} | random_line_split |
ApplicationCacheItemsView.js | 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IM... |
function localeCompare(field, resource1, resource2)
{
return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + "")
}
var comparator;
switch (parseInt(this._dataGrid.sortColumnIdentifier, 10)) {
case 0: comparator = localeCompare.b... | {
return sortDirection * (resource1[field] - resource2[field]);
} | identifier_body |
ApplicationCacheItemsView.js | 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IM... | (field, resource1, resource2)
{
return sortDirection * (resource1[field] - resource2[field]);
}
function localeCompare(field, resource1, resource2)
{
return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + "")
}
var compar... | numberCompare | identifier_name |
cnos_factory.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... |
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# initiate SSH connection with the switch
remote_conn... | module = AnsibleModule(
argument_spec=dict(
outputfile=dict(required=True),
host=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
enablePassword=dict(required=False, no_log=True),
deviceType=dict... | identifier_body |
cnos_factory.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... | extends_documentation_fragment: cnos
options: {}
'''
EXAMPLES = '''
Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory.
---
- name: Test Reset to factory
cnos_factory:
host: "{{ inventory_hostname }}"
username: "{{ hostvars[in... | random_line_split | |
cnos_factory.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... |
else:
module.fail_json(msg=errorMsg)
if __name__ == '__main__':
main()
| module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") | conditional_block |
cnos_factory.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... | ():
module = AnsibleModule(
argument_spec=dict(
outputfile=dict(required=True),
host=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
enablePassword=dict(required=False, no_log=True),
deviceT... | main | identifier_name |
scroll-animation.directive.ts | import {ElementRef, Directive, OnInit, Input, HostListener, Renderer, Inject} from '@angular/core';
import {Window} from '../../utils/window/window';
@Directive({selector: '[sc-animation]'})
export class ScrollAnimationDirective implements OnInit {
constructor(
private _el: ElementRef,
private _ren... |
} | {
this._renderer.setElementStyle(this._el.nativeElement, 'opacity', '0');
} | identifier_body |
scroll-animation.directive.ts | import {ElementRef, Directive, OnInit, Input, HostListener, Renderer, Inject} from '@angular/core'; |
@Directive({selector: '[sc-animation]'})
export class ScrollAnimationDirective implements OnInit {
constructor(
private _el: ElementRef,
private _renderer: Renderer,
@Inject(Window) private _window: Window
) {}
// Element that triggers the reached state
@Input('sc-animation') s... | import {Window} from '../../utils/window/window'; | random_line_split |
scroll-animation.directive.ts | import {ElementRef, Directive, OnInit, Input, HostListener, Renderer, Inject} from '@angular/core';
import {Window} from '../../utils/window/window';
@Directive({selector: '[sc-animation]'})
export class ScrollAnimationDirective implements OnInit {
constructor(
private _el: ElementRef,
private _ren... | () {
if (this.options.hideInitial) this._hideInitial();
this._setTop();
this.onScroll();
}
private _setTop() {
this.top = this.options.ref.nativeElement.getBoundingClientRect ? this.options.ref.nativeElement.getBoundingClientRect().top : 0;
}
private _hideInitial() {
... | ngOnInit | identifier_name |
tt_postscript.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Michael Droettboom All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, t... | """
TT_Postscript_min_mem_type42 = """
Minimum memory usage when the font is downloaded as a Type 42 font.
"""
TT_Postscript_max_mem_type42 = """
Maximum memory usage when the font is downloaded as a Type 42 font.
"""
TT_Postscript_min_mem_type1 = """
Minimum memory usage when the font is downloaded as a Type 1 font... | TT_Postscript_is_fixed_pitch = """
If `True`, the font is monospaced. | random_line_split |
prompt.rs |
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env... |
pub fn update_error(&mut self, error: i8) {
self.error = error;
}
}
#[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert... | {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~{}", cwd.spl... | identifier_body |
prompt.rs |
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env... | else {
format!("{}:{} > ", self.user, self.cwd)
}
}
pub fn update_cwd(&mut self) {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_stri... | {
format!("{} {}:{} > ", Red.paint(format!("\u{2718} {}", self.error)).to_string(), self.user, self.cwd)
} | conditional_block |
prompt.rs |
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env... | (&mut self) {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~... | update_cwd | identifier_name |
prompt.rs | use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env:... | #[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert_eq!(testp.get_cwd(), current_dir().ok()
.expect("Couldn't get current... | }
| random_line_split |
logs.py | import sys
from traceback import format_exception
import colorama
def color(color_, settings):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
else:
return color_
def exception(title, exc_info, settings):
sys.stderr.write(
u'{warn}[WARN... | red=color(colorama.Fore.RED, settings),
reset=color(colorama.Style.RESET_ALL, settings))) | random_line_split | |
logs.py | import sys
from traceback import format_exception
import colorama
def color(color_, settings):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
else:
return color_
def exception(title, exc_info, settings):
sys.stderr.write(
u'{warn}[WARN... | (new_command, settings):
sys.stderr.write('{bold}{command}{reset}\n'.format(
command=new_command,
bold=color(colorama.Style.BRIGHT, settings),
reset=color(colorama.Style.RESET_ALL, settings)))
def confirm_command(new_command, settings):
sys.stderr.write(
'{bold}{command}{reset}... | show_command | identifier_name |
logs.py | import sys
from traceback import format_exception
import colorama
def color(color_, settings):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
else:
return color_
def exception(title, exc_info, settings):
sys.stderr.write(
u'{warn}[WARN... |
def confirm_command(new_command, settings):
sys.stderr.write(
'{bold}{command}{reset} [{green}enter{reset}/{red}ctrl+c{reset}]'.format(
command=new_command,
bold=color(colorama.Style.BRIGHT, settings),
green=color(colorama.Fore.GREEN, settings),
red=color(c... | sys.stderr.write('{bold}{command}{reset}\n'.format(
command=new_command,
bold=color(colorama.Style.BRIGHT, settings),
reset=color(colorama.Style.RESET_ALL, settings))) | identifier_body |
logs.py | import sys
from traceback import format_exception
import colorama
def color(color_, settings):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
else:
|
def exception(title, exc_info, settings):
sys.stderr.write(
u'{warn}[WARN] {title}:{reset}\n{trace}'
u'{warn}----------------------------{reset}\n\n'.format(
warn=color(colorama.Back.RED + colorama.Fore.WHITE
+ colorama.Style.BRIGHT, settings),
reset... | return color_ | conditional_block |
signalfd.rs | //! Interface for the `signalfd` syscall.
//!
//! # Signal discarding
//! When a signal can't be delivered to a process (or thread), it will become a pending signal.
//! Failure to deliver could happen if the signal is blocked by every thread in the process or if
//! the signal handler is still handling a previous sign... | (mask: &SigSet, flags: SfdFlags) -> Result<SignalFd> {
let fd = try!(signalfd(SIGNALFD_NEW, mask, flags));
Ok(SignalFd(fd))
}
pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> {
signalfd(self.0, mask, SfdFlags::empty()).map(|_| ())
}
pub fn read_signal(&mut self) -> Resu... | with_flags | identifier_name |
signalfd.rs | //! Interface for the `signalfd` syscall.
//!
//! # Signal discarding
//! When a signal can't be delivered to a process (or thread), it will become a pending signal.
//! Failure to deliver could happen if the signal is blocked by every thread in the process or if
//! the signal handler is still handling a previous sign... |
#[test]
fn create_signalfd_with_opts() {
let mask = SigSet::empty();
let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK);
assert!(fd.is_ok());
}
#[test]
fn read_empty_signalfd() {
let mask = SigSet::empty();
let mut fd = Sig... | {
let mask = SigSet::empty();
let fd = SignalFd::new(&mask);
assert!(fd.is_ok());
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.