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 |
|---|---|---|---|---|
notifications-list.component.ts | import { Component, Input, EventEmitter, SimpleChanges, OnChanges } from '@angular/core';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from 'ng2-translate';
import { Notification } from '../notification.model';
import { NotificationService } from '../notification.service';
import { Pa... | {
@Input() notifications: Notification[];
// @Input() selectedStatus: String;
// @Input() selectedNotificationType: String;
translatedResponse: any;
// pagination parameters
currentPage = 1;
pageSize = 10;
totalItems: number;
// will contain the notification satisfying the selected status and type... | NotificationsListComponent | identifier_name |
mouse-dragdrop-cursor.component.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component, ElementRef, ViewChild, ViewEnca... | xtends Destroy {
@ViewChild('block', { static: true }) private icon: ElementRef<HTMLElement>;
@ViewChild('content', { static: true }) private content: ElementRef<HTMLElement>;
private position$ = new BehaviorSubject<Position>(null);
private cursor$ = new BehaviorSubject<IDragCursorInfos>(null);
priv... | jaMouseDragDropCursorComponent e | identifier_name |
mouse-dragdrop-cursor.component.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component, ElementRef, ViewChild, ViewEnca... | lse if (this.iconElement) {
this.iconElement.style.opacity = '1';
}
}),
delay(1),
takeUntil(this.destroyed$)
).subscribe(cursor => {
if (!!cursor.html && this.contentElement) {
this.contentElement.style.opacity =... | element.className = cursor.className;
if (this.contentElement) {
this.contentElement.innerHTML = cursor.html;
this.contentElement.style.width = `${cursor.width || 48}px`;
this.contentElement.style.height = `$... | conditional_block |
mouse-dragdrop-cursor.component.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component, ElementRef, ViewChild, ViewEnca... | private get contentElement(): HTMLElement {
return this.content?.nativeElement;
}
}
| return this.icon?.nativeElement;
}
| identifier_body |
mouse-dragdrop-cursor.component.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component, ElementRef, ViewChild, ViewEnca... | }
}
this.currentCursor = cursor;
}),
delay(300),
takeUntil(this.destroyed$)
).subscribe(() => {
this.position$.next(null);
element.style.display = 'none';
});
// Show
this.cur... | if (this.contentElement) {
this.contentElement.style.opacity = '0';
}
if (this.iconElement) {
this.iconElement.style.opacity = '0'; | random_line_split |
prism.js | newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
grammar[newToken] = insert[newToken];
}
}
return grammar;
}
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
... | * $ git status
* # On branch infinite-scroll
* # Your branch and 'origin/sharedBranches/frontendTeam/infinite-scroll' have diverged,
* # and have 1 and 2 different commits each, respectively.
* nothing to commit (working directory clean) | random_line_split | |
prism.js | util.clone(v); });
}
return o;
}
},
languages: {
extend: function (id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
/**
* Insert a token before another token in a language literal
* As this needs to recre... |
if (!grammar) {
return;
}
// Set language on the element, if not present
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
// Set language on the parent, for styling
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.cla... | {
language = (parent.className.match(lang) || [,''])[1];
grammar = _.languages[language];
} | conditional_block |
PerformanceMonitor.js | /*
* Atari Arcade SDK
* Developed by gskinner.com in partnership with Atari
* Visit http://atari.com/arcade/developers for documentation, updates and examples.
*
* Copyright (c) Atari Interactive, Inc. All Rights Reserved. Atari and the Atari logo are trademarks owned by Atari Interactive, Inc.
*
* Distributed under th... | /**
* If the game is currently in low quality mode.
* @property lowQualityMode
* @type Boolean
* @default false
*/
lowQualityMode: false,
/**
* The amount of time that has elapsed since the framerate has been acceptable.
* @property timeOnLow
* @type Number
... | * @type Function
*/
callback: null,
| random_line_split |
PerformanceMonitor.js | /*
* Atari Arcade SDK
* Developed by gskinner.com in partnership with Atari
* Visit http://atari.com/arcade/developers for documentation, updates and examples.
*
* Copyright (c) Atari Interactive, Inc. All Rights Reserved. Atari and the Atari logo are trademarks owned by Atari Interactive, Inc.
*
* Distributed under th... | else {
this.timeOnLow = 0;
}
}
}
scope.PerformanceMonitor = PerformanceMonitor;
}(window.GameLibs)) | {
this.timeOnLow += deltaT;
if(this.timeOnLow > this.threshold) {
/*
Atari.trace("*** Low Quality Mode toggled.")
*/
this.lowQualityMode = true;
this.callback(true);
createjs.Ticker.setFPS(30);
createjs.Ticker.removeListener(this);
}
} | conditional_block |
CommentableEditor.test.tsx | import React, { ReactNode } from 'react';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import { createEditorStateFromRaw } from 'draftail';
import { CommentApp } from '../../CommentApp/main';
import { updateGlobalSettings } from '../../CommentApp/actions/settings';
import { newComment } from... | ],
text: 'test_test_test_test_test_test_test',
entityRanges: [],
},
],
};
let commentApp: CommentApp;
let fieldNode: HTMLElement;
let getEditorComponent: (app: CommentApp) => ReactNode;
const contentpath = 'test-contentpath';
const getComments = (app: CommentApp) =>
app... | offset: 0,
length: 20,
style: 'COMMENT-1',
}, | random_line_split |
utils.py | #!coding: utf-8
import base64
import calendar
import os
import re
import paramiko
from io import StringIO
import hashlib
import threading
import time
import pyte
def ssh_key_string_to_obj(text):
key_f = StringIO(text)
key = None
try:
key = paramiko.RSAKey.from_private_key(key_f)
except para... | self.screen.reset()
return sep.join(output[0:-1])
def parse_input(self, data):
"""
Parse user input command
:param data: input data list, like [b'data', b'data']
:return: command unicode
"""
command = []
for d in data:
self.stream... | sql>\s')
def clean_ps1_etc(self, command):
return self.ps1_pattern.sub('', command)
def parse_output(self, data, sep='\n'):
"""
Parse user command output
:param data: output data list like, [b'data', b'data']
:param sep: line separator
:return: output unicode ... | identifier_body |
utils.py | #!coding: utf-8
import base64
import calendar
import os
import re
import paramiko
from io import StringIO
import hashlib
import threading
import time
import pyte
def ssh_key_string_to_obj(text):
key_f = StringIO(text)
key = None
try:
key = paramiko.RSAKey.from_private_key(key_f)
except para... |
elif type == 'dsa':
private_key_obj = paramiko.DSSKey.generate(length)
else:
raise IOError('SSH private key must be `rsa` or `dsa`')
private_key_obj.write_private_key(f, password=password)
private_key = f.getvalue()
public_key = ssh_pubkey_gen(private_key... | private_key_obj = paramiko.RSAKey.generate(length) | conditional_block |
utils.py | #!coding: utf-8
import base64
import calendar
import os
import re
import paramiko
from io import StringIO
import hashlib
import threading
import time
import pyte
def ssh_key_string_to_obj(text):
key_f = StringIO(text)
key = None
try:
key = paramiko.RSAKey.from_private_key(key_f)
except para... | identifier_name | ||
utils.py | #!coding: utf-8
import base64
import calendar
import os
import re
import paramiko
from io import StringIO
import hashlib
import threading
import time
import pyte
def ssh_key_string_to_obj(text):
key_f = StringIO(text)
key = None
try:
key = paramiko.RSAKey.from_private_key(key_f)
except para... | 'black': '30',
'red': '31',
'green': '32',
'brown': '33',
'blue': '34',
'purple': '35',
'cyan': '36',
'white': '37',
}
background_map = {
'black': '40',
'red': '41',
'green': '42',
'brown': '43',
'blue': '44'... | bolder=False, underline=False):
bolder_ = '1'
underline_ = '4'
color_map = { | random_line_split |
view.tsx | from '../../../lichess/status'
import { GameSituation } from '../../../chess'
import { renderMaterial } from '../../shared/round/view/roundView'
import * as helper from '../../helper'
import CrazyPocket from '../../shared/round/crazy/CrazyPocket'
import { OfflineRoundInterface, Position, Material } from '../round'
imp... | (ctrl)}
{renderForwardButton(ctrl)}
</section>
)
}
export function renderEndedGameStatus(ctrl: OfflineRoundInterface) {
if (!ctrl.replay) return null
const sit = ctrl.replay.situation()
if (gameStatusApi.finished(ctrl.data)) {
const result = gameApi.result(ctrl.data)
const winner = sit.winne... | renderBackwardButton | identifier_name |
view.tsx | from '../../../lichess/status'
import { GameSituation } from '../../../chess'
import { renderMaterial } from '../../shared/round/view/roundView'
import * as helper from '../../helper'
import CrazyPocket from '../../shared/round/crazy/CrazyPocket'
import { OfflineRoundInterface, Position, Material } from '../round'
imp... |
</section>
)
}
export function renderGameActionsBarTablet(ctrl: OfflineRoundInterface) {
return (
<section className="actions_bar">
<button className="action_bar_button" data-icon="U"
oncreate={helper.ontap(ctrl.newGameMenu.open, () => window.plugins.toast.show(i18n('createAGame'), 'short', ... | {renderForwardButton(ctrl)} | identifier_body |
view.tsx | from '../../../lichess/status'
import { GameSituation } from '../../../chess'
import { renderMaterial } from '../../shared/round/view/roundView'
import * as helper from '../../helper'
import CrazyPocket from '../../shared/round/crazy/CrazyPocket'
import { OfflineRoundInterface, Position, Material } from '../round'
imp... | <section id={position + '_info'} className={className} key={key}>
<div key="infos" className={'antagonistInfos offline' + (isCrazy ? ' crazy' : '')}>
<div className="antagonistUser">
{content}
{isCrazy && clock ? renderClock(clock, antagonistColor) : ''}
</div>
{ !i... |
return ( | random_line_split |
tasks.py | ########################################################################
#
# University of Southampton IT Innovation Centre, 2011
#
# Copyright in this library belongs to the University of Southampton
# University Road, Highfield, Southampton, UK, SO17 1BJ
#
# This software may not be used, sold, licensed, transferred,... | :
def __init__(self):
self.contents = []
def store(self, buf):
self.contents.append(buf) #= "%s%i: %s" % (self.contents, self.line, buf)
def __str__(self):
return ", ".join(self.contents)
@task
def copyfromurl(inputs,outputs,options={},callbacks=[]):
url = options["url"]
... | Storage | identifier_name |
tasks.py | ########################################################################
#
# University of Southampton IT Innovation Centre, 2011
#
# Copyright in this library belongs to the University of Southampton
# University Road, Highfield, Southampton, UK, SO17 1BJ
#
# This software may not be used, sold, licensed, transferred,... | for header in retrieved_headers.contents:
if header.lower().startswith("content-disposition"):
filename = re.match(".*filename=(?P<filename>.*)", header).group('filename')
if status > 400:
logging.warn("Copy From URL %s return error status code '%s' " % (url, status))
return... | f.close()
logging.debug(retrieved_headers)
filename = "Imported File" | random_line_split |
tasks.py | ########################################################################
#
# University of Southampton IT Innovation Centre, 2011
#
# Copyright in this library belongs to the University of Southampton
# University Road, Highfield, Southampton, UK, SO17 1BJ
#
# This software may not be used, sold, licensed, transferred,... |
return { "message" : "Copy from url was successful"}
# Blender Command Line API
#
# Render a Picture
# blender -b file.blend -o //file -F JPEG -x 1 -f 1
#
# Render a movie
# blender -b file.blend -x 1 -o //file -F MOVIE -s 003 -e 005 -a
#
# Render a Series
# blender -b file.blend -x 1 -o //file -F "PNG" ... | mfileid = inputs[0]
from dataservice.models import MFile
mfile = MFile.objects.get(id=mfileid)
filename = mfile.service.get_unique_name(filename)
mfile.update_mfile(filename, file=File(open(tfile.name, 'r')))
mfile.save()
for callback in callbacks:
subtask(ca... | conditional_block |
tasks.py | ########################################################################
#
# University of Southampton IT Innovation Centre, 2011
#
# Copyright in this library belongs to the University of Southampton
# University Road, Highfield, Southampton, UK, SO17 1BJ
#
# This software may not be used, sold, licensed, transferred,... | if not os.path.exists(inputfile):
logging.info("Scene %s does not exist" % inputfile)
return False
[outputdir,ffff]= os.path.split(outputfile)
hashes = "#" * padding
outputformat = "%s/%s.%s" % (outputdir,fname,hashes)
ss= string.zfill(str(frame), padding)
args = ["blender","-b... | padding = 4
frame = options["frame"]
if options.has_key("fname"):
fname = options["format"]
else:
fname="image"
if options.has_key("format"):
format = options["format"]
else:
format="PNG"
mfileid = inputs[0]
from dataservice.models import MFile
mf = MFile... | identifier_body |
helpers.py | # Copyright (C) 2015-2020 Nikos Roussos <nikos@roussos.cc>.
# This file is part of Monopati - https://github.com/comzeradd/monopati
# Monopati 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 ... | cfg = config()
Handler = http.server.SimpleHTTPRequestHandler
chdir(cfg['output'])
with socketserver.TCPServer(('', port), Handler) as httpd:
print('Serving at http://localhost:{0}'.format(port))
httpd.serve_forever() | identifier_body | |
helpers.py | # Copyright (C) 2015-2020 Nikos Roussos <nikos@roussos.cc>.
# This file is part of Monopati - https://github.com/comzeradd/monopati
# Monopati 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 ... | (port):
cfg = config()
Handler = http.server.SimpleHTTPRequestHandler
chdir(cfg['output'])
with socketserver.TCPServer(('', port), Handler) as httpd:
print('Serving at http://localhost:{0}'.format(port))
httpd.serve_forever()
| serve | identifier_name |
helpers.py | # Copyright (C) 2015-2020 Nikos Roussos <nikos@roussos.cc>.
# This file is part of Monopati - https://github.com/comzeradd/monopati
# Monopati 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 ... | httpd.serve_forever() | Handler = http.server.SimpleHTTPRequestHandler
chdir(cfg['output'])
with socketserver.TCPServer(('', port), Handler) as httpd:
print('Serving at http://localhost:{0}'.format(port)) | random_line_split |
helpers.py | # Copyright (C) 2015-2020 Nikos Roussos <nikos@roussos.cc>.
# This file is part of Monopati - https://github.com/comzeradd/monopati
# Monopati 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 ... |
try:
makedirs(output)
except OSError:
pass
return cfg
def kickstart(folder):
dest = path.abspath(folder)
if not path.isdir(dest):
mkdir(dest)
print('Creating website folder...')
else:
print('Folder already exists')
sys.exit()
skel = path... | output = output[:-1] | conditional_block |
lorenz96.rs | //! Lorenz 96 model
//! https://en.wikipedia.org/wiki/Lorenz_96_model
use crate::traits::*;
use ndarray::*;
#[derive(Clone, Copy, Debug)]
pub struct Lorenz96 {
pub f: f64,
pub n: usize,
}
impl Default for Lorenz96 {
fn default() -> Self {
Lorenz96 { f: 8.0, n: 40 }
}
}
impl ModelSpec for Lor... | <'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1>
where
S: DataMut<Elem = f64>,
{
let n = v.len();
let v0 = v.to_owned();
for i in 0..n {
let p1 = (i + 1) % n;
let m1 = (i + n - 1) % n;
let m2 = (i + n - 2) % n;
... | rhs | identifier_name |
lorenz96.rs | //! Lorenz 96 model
//! https://en.wikipedia.org/wiki/Lorenz_96_model
use crate::traits::*;
use ndarray::*;
#[derive(Clone, Copy, Debug)]
pub struct Lorenz96 {
pub f: f64,
pub n: usize,
}
impl Default for Lorenz96 {
fn default() -> Self {
Lorenz96 { f: 8.0, n: 40 }
} | impl ModelSpec for Lorenz96 {
type Scalar = f64;
type Dim = Ix1;
fn model_size(&self) -> usize {
self.n
}
}
impl Explicit for Lorenz96 {
fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1>
where
S: DataMut<Elem = f64>,
{
let n = v.len... | }
| random_line_split |
lorenz96.rs | //! Lorenz 96 model
//! https://en.wikipedia.org/wiki/Lorenz_96_model
use crate::traits::*;
use ndarray::*;
#[derive(Clone, Copy, Debug)]
pub struct Lorenz96 {
pub f: f64,
pub n: usize,
}
impl Default for Lorenz96 {
fn default() -> Self |
}
impl ModelSpec for Lorenz96 {
type Scalar = f64;
type Dim = Ix1;
fn model_size(&self) -> usize {
self.n
}
}
impl Explicit for Lorenz96 {
fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1>
where
S: DataMut<Elem = f64>,
{
let n = v... | {
Lorenz96 { f: 8.0, n: 40 }
} | identifier_body |
coulomb.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use toml::Value;
use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf};
use lumol_core::System;
use log::{info, warn};
use super::read_restriction;
use crate::{InteractionsInput, Error, FromToml, ... | self, system: &mut System) -> Result<(), Error> {
let coulomb = match self.config.get("coulomb") {
Some(coulomb) => coulomb,
None => return Ok(()),
};
let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?;
let solvers = co... | ad_coulomb(& | identifier_name |
coulomb.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use toml::Value;
use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf};
use lumol_core::System;
use log::{info, warn};
use super::read_restriction;
use crate::{InteractionsInput, Error, FromToml, ... | let ewald = Ewald::from_toml(table, &system)?;
Box::new(SharedEwald::new(ewald))
}
other => return Err(Error::from(format!("unknown coulomb solver '{}'", other))),
};
if let Some(restriction) = read_restriction(coulomb)? {
... | let coulomb = match self.config.get("coulomb") {
Some(coulomb) => coulomb,
None => return Ok(()),
};
let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?;
let solvers = coulomb.keys().cloned().filter(|key| key != "restric... | identifier_body |
coulomb.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use toml::Value;
use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf};
use lumol_core::System;
use log::{info, warn};
use super::read_restriction;
use crate::{InteractionsInput, Error, FromToml, ... | let mut total_charge = 0.0;
for (name, charge) in charges.iter() {
let charge = match *charge {
Value::Integer(val) => val as f64,
Value::Float(val) => val,
_ => {
return Err(Error::from("charges must be numbers"));
... | random_line_split | |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {... | () {
let mut a: A<T> = A { begin: 0, end: 10 };
let mut iter: &mut I = &mut a;
for x in 0..10 {
let y: Option<T> = iter.next_back();
match y {
Some(v) => { assert_eq!(v, 9 - x); }
None => { assert!(false); }
}
}
assert_eq!(iter.next(), None::<<I as Iterator>::Item>);;
}
}
| next_back_test1 | identifier_name |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {... |
}
| {
let mut a: A<T> = A { begin: 0, end: 10 };
let mut iter: &mut I = &mut a;
for x in 0..10 {
let y: Option<T> = iter.next_back();
match y {
Some(v) => { assert_eq!(v, 9 - x); }
None => { assert!(false); }
}
}
assert_eq!(iter.next(), None::<<I as Iterator>::Item>);;
} | identifier_body |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {... | } | }
}
assert_eq!(iter.next(), None::<<I as Iterator>::Item>);;
} | random_line_split |
test.matching-indexes.js | 'use strict';
testCases.push(function (dbType, context) {
var sortById = testUtils.sortById; |
describe(dbType + ': test.matching-indexes.js', function () {
beforeEach(function () {
return context.db.bulkDocs([
{ name: 'Mario', _id: 'mario', rank: 5, series: 'Mario', debut: 1981 },
{ name: 'Jigglypuff', _id: 'puff', rank: 8, series: 'Pokemon', debut: 1996 },
{ name: 'Link', ... | random_line_split | |
canvasgradient.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 cssparser::RGBA;
use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R... | self.stops.borrow_mut().push(CanvasGradientStop {
offset: (*offset) as f64,
color: parse_color(&color).unwrap_or(default_black),
});
}
}
pub trait ToFillOrStrokeStyle {
fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle;
}
impl<'a> ToFillOrStrokeStyle for JSRef<'a, ... | random_line_split | |
canvasgradient.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 cssparser::RGBA;
use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R... | ,
CanvasGradientStyle::Radial(ref gradient) => {
FillOrStrokeStyle::RadialGradient(
RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0,
gradient.x1, gradient.y1, gradient.r1,
... | {
FillOrStrokeStyle::LinearGradient(
LinearGradientStyle::new(gradient.x0, gradient.y0,
gradient.x1, gradient.y1,
gradient_stops))
} | conditional_block |
canvasgradient.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 cssparser::RGBA;
use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R... | (global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> {
reflect_dom_object(box CanvasGradient::new_inherited(style),
global, CanvasGradientBinding::Wrap)
}
}
impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> {
// https://html.spec.whatwg.org/... | new | identifier_name |
slider.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... |
self.real_widget.setScaleStart(start)
scale_start = property(_getScaleStart, _setScaleStart)
def _getScaleEnd(self):
"""getScaleEnd(self) -> double"""
return self.real_widget.getScaleEnd()
def _setScaleEnd(self, end):
"""setScaleEnd(self, double scaleEnd)"""
if type(end) != float:
raise RuntimeError(... | raise RuntimeError("Slider expects float for start scale") | conditional_block |
slider.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | (self, prefix):
sliderClone = Slider(None,
self._createNameWithPrefix(prefix),
self.size,
self.min_size,
self.max_size,
self.fixed_size,
self.margins,
self.padding,
self.helptext,
self.position,
self.style,
self.hexpand,
self.vexpand,
self.font,
se... | clone | identifier_name |
slider.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... |
step_length = property(_getStepLength, _setStepLength)
| """getStepLength(self) -> double"""
return self.real_widget.getStepLength() | identifier_body |
slider.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | from fife import fifechan
from fife.extensions.pychan.attrs import IntAttr, FloatAttr
from .widget import Widget
class Slider(Widget):
""" A slider widget
Use a callback to read out the slider value every time the marker
is moved.
New Attributes
==============
- orientation: 1 = horizontal, 0=vertical
... | # Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
from __future__ import absolute_import | random_line_split |
form_builder.ts | import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* ### Example ([live d... | else if (isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return this.co... | {
return controlConfig;
} | conditional_block |
form_builder.ts | import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* ### Example ([live d... | } else if (isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return th... | controlConfig instanceof modelModule.ControlGroup ||
controlConfig instanceof modelModule.ControlArray) {
return controlConfig;
| random_line_split |
form_builder.ts | import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* ### Example ([live d... | (controlsConfig: any[], validator: Function = null,
asyncValidator: Function = null): modelModule.ControlArray {
var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator);
}
/** @internal */
_reduceControls(controlsCon... | array | identifier_name |
form_builder.ts | import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* ### Example ([live d... |
/**
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
array(controlsConfig: any[], validator: Function = null,
asyncValidator: Function = null): modelModule.ControlArray {
var control... | {
return new modelModule.Control(value, validator, asyncValidator);
} | identifier_body |
get-file.ts | import { IProjectData } from "../../../definitions/project";
import { IOptions } from "../../../declarations";
import { ICommandParameter, ICommand } from "../../definitions/commands";
import { IErrors } from "../../declarations";
import { injector } from "../../yok";
export class GetFileCommand implements ICommand {
... | const action = async (device: Mobile.IDevice) => {
appIdentifier =
appIdentifier ||
this.$projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
];
await device.fileSystem.getFile(
args[0],
appIdentifier,
this.$options.file
);
};
await this.$devicesService.e... | {
await this.$devicesService.initialize({
deviceId: this.$options.device,
skipInferPlatform: true,
});
let appIdentifier = args[1];
if (!appIdentifier) {
try {
this.$projectData.initializeProjectData();
} catch (err) {
// ignore the error
}
if (!this.$projectData.projectIdentifiers) {... | identifier_body |
get-file.ts | import { IProjectData } from "../../../definitions/project";
import { IOptions } from "../../../declarations";
import { ICommandParameter, ICommand } from "../../definitions/commands";
import { IErrors } from "../../declarations";
import { injector } from "../../yok";
export class GetFileCommand implements ICommand {
... |
}
const action = async (device: Mobile.IDevice) => {
appIdentifier =
appIdentifier ||
this.$projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
];
await device.fileSystem.getFile(
args[0],
appIdentifier,
this.$options.file
);
};
await this.$devicesSer... | {
this.$errors.fail(
"Please enter application identifier or execute this command in project."
);
} | conditional_block |
get-file.ts | import { IProjectData } from "../../../definitions/project";
import { IOptions } from "../../../declarations";
import { ICommandParameter, ICommand } from "../../definitions/commands";
import { IErrors } from "../../declarations";
import { injector } from "../../yok";
export class GetFileCommand implements ICommand {
... | }
const action = async (device: Mobile.IDevice) => {
appIdentifier =
appIdentifier ||
this.$projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
];
await device.fileSystem.getFile(
args[0],
appIdentifier,
this.$options.file
);
};
await this.$devicesServ... | this.$errors.fail(
"Please enter application identifier or execute this command in project."
);
} | random_line_split |
get-file.ts | import { IProjectData } from "../../../definitions/project";
import { IOptions } from "../../../declarations";
import { ICommandParameter, ICommand } from "../../definitions/commands";
import { IErrors } from "../../declarations";
import { injector } from "../../yok";
export class GetFileCommand implements ICommand {
... | (args: string[]): Promise<void> {
await this.$devicesService.initialize({
deviceId: this.$options.device,
skipInferPlatform: true,
});
let appIdentifier = args[1];
if (!appIdentifier) {
try {
this.$projectData.initializeProjectData();
} catch (err) {
// ignore the error
}
if (!this.$p... | execute | identifier_name |
TwoDWalker.py | """
TwoDWalker.py is for controling the avatars in a 2D Scroller game environment.
"""
from GravityWalker import *
from panda3d.core import ConfigVariableBool
class TwoDWalker(GravityWalker):
"""
The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame.
TODO: This class is... |
def jumpPressed(self):
"""This function should be called from TwoDDrive when the jump key is pressed."""
if self.lifter.isOnGround():
if self.isAirborne == 0:
if self.mayJump:
# The jump button is down and we're close enough to the ground to jump.
... | """
Check on the arrow keys and update the avatar.
"""
# get the button states:
jump = inputState.isSet("forward")
if self.lifter.isOnGround():
if self.isAirborne:
self.isAirborne = 0
assert self.debugPrint("isAirborne 0 due to isOnGrou... | identifier_body |
TwoDWalker.py | """
TwoDWalker.py is for controling the avatars in a 2D Scroller game environment.
"""
from GravityWalker import *
from panda3d.core import ConfigVariableBool
class TwoDWalker(GravityWalker):
"""
The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame.
TODO: This class is... | self.lifter.addVelocity(self.avatarControlJumpForce)
messenger.send("jumpStart")
self.isAirborne = 1
assert self.debugPrint("isAirborne 1 due to jump") | conditional_block | |
TwoDWalker.py | """
TwoDWalker.py is for controling the avatars in a 2D Scroller game environment.
"""
from GravityWalker import *
from panda3d.core import ConfigVariableBool
class TwoDWalker(GravityWalker):
"""
The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame.
TODO: This class is... | if self.mayJump:
# The jump button is down and we're close enough to the ground to jump.
self.lifter.addVelocity(self.avatarControlJumpForce)
messenger.send("jumpStart")
self.isAirborne = 1
assert self.de... | if self.isAirborne == 0: | random_line_split |
TwoDWalker.py | """
TwoDWalker.py is for controling the avatars in a 2D Scroller game environment.
"""
from GravityWalker import *
from panda3d.core import ConfigVariableBool
class TwoDWalker(GravityWalker):
"""
The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame.
TODO: This class is... | (self, gravity = -32.1740, standableGround=0.707,
hardLandingForce=16.0):
assert self.notify.debugStateCall(self)
self.notify.debug('Constructing TwoDWalker')
GravityWalker.__init__(self)
def handleAvatarControls(self, task):
"""
Check on the arrow keys and updat... | __init__ | identifier_name |
application-types.js | /**
* Copyright 2013-2020 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see http://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the Li... | MICROSERVICE: 'microservice',
UAA: 'uaa',
GATEWAY: 'gateway',
};
ApplicationTypes.exists = applicationType => !!applicationType && !!ApplicationTypes[applicationType.toUpperCase()];
module.exports = ApplicationTypes; |
const ApplicationTypes = {
MONOLITH: 'monolith', | random_line_split |
viewport.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 app_units::Au;
use style::properties::PropertyDeclaration;
use style::properties::longhands::border_top_width;... | border_top_width::SpecifiedValue::from_length(
Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(Au(100).to_f32_px())))
)
);
assert!(!pabs.has_viewport_percentage());
} | )
);
assert!(pvw.has_viewport_percentage());
let pabs = PropertyDeclaration::BorderTopWidth( | random_line_split |
viewport.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 app_units::Au;
use style::properties::PropertyDeclaration;
use style::properties::longhands::border_top_width;... | {
//TODO: test all specified value with a HasViewportPercentage impl
let pvw = PropertyDeclaration::BorderTopWidth(
border_top_width::SpecifiedValue::from_length(
Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.)))
)
);
assert!(pvw.has_viewpor... | identifier_body | |
viewport.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 app_units::Au;
use style::properties::PropertyDeclaration;
use style::properties::longhands::border_top_width;... | () {
//TODO: test all specified value with a HasViewportPercentage impl
let pvw = PropertyDeclaration::BorderTopWidth(
border_top_width::SpecifiedValue::from_length(
Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.)))
)
);
assert!(pvw.has_view... | has_viewport_percentage_for_specified_value | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com>
# Source repository: https://github.com/jonasjberg/autonameow
#
# This file is part of autonameow.
#
# autonameow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public L... | from .extractor_guessit import GuessitMetadataExtractor
from .extractor_jpeginfo import JpeginfoMetadataExtractor
from .extractor_pandoc import PandocMetadataExtractor | from .extractor_exiftool import ExiftoolMetadataExtractor
from .extractor_filetags import FiletagsMetadataExtractor | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyLocalcider(PythonPackage): |
version('0.1.14', sha256='54ff29e8a011947cca5df79e96f3c69a76c49c4db41dcf1608663992be3e3f5f')
depends_on('py-setuptools', type='build')
depends_on('py-numpy', type=('build', 'run'))
depends_on('py-matplotlib', type=('build', 'run'))
depends_on('py-scipy', type=('build', 'run')) | """Tools for calculating sequence properties of disordered proteins"""
homepage = "http://pappulab.github.io/localCIDER"
url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz" | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyLocalcider(PythonPackage):
| """Tools for calculating sequence properties of disordered proteins"""
homepage = "http://pappulab.github.io/localCIDER"
url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz"
version('0.1.14', sha256='54ff29e8a011947cca5df79e96f3c69a76c49c4db41dcf1608663992be3e3f5f')
depe... | identifier_body | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (PythonPackage):
"""Tools for calculating sequence properties of disordered proteins"""
homepage = "http://pappulab.github.io/localCIDER"
url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz"
version('0.1.14', sha256='54ff29e8a011947cca5df79e96f3c69a76c49c4db41dcf160866399... | PyLocalcider | identifier_name |
zero-size-array-align.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... |
}
#[repr(C)]
#[derive(Debug, Default)]
pub struct dm_deps {
pub count: ::std::os::raw::c_uint,
pub filler: ::std::os::raw::c_uint,
pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>,
}
#[test]
fn bindgen_test_layout_dm_deps() {
assert_eq!(
::std::mem::size_of::<dm_deps>(),
... | {
fmt.write_str("__IncompleteArrayField")
} | identifier_body |
zero-size-array-align.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | (&mut self) -> *mut T {
self as *mut _ as *mut T
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(s... | as_mut_ptr | identifier_name |
zero-size-array-align.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | );
assert_eq!(
::std::mem::align_of::<dm_deps>(),
8usize,
concat!("Alignment of ", stringify!(dm_deps))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<dm_deps>())).count as *const _ as usize
},
0usize,
concat!(
"Offset of fi... | random_line_split | |
issue-2834.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() {
//os::getenv("FOO");
rendezvous();
} | random_line_split | |
issue-2834.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() {
//os::getenv("FOO");
rendezvous();
}
| {
let (s, c) = streamp::init();
let streams: ~[streamp::client::open<int>] = ~[c];
error!("%?", streams[0]);
} | identifier_body |
issue-2834.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (s, c) = streamp::init();
let streams: ~[streamp::client::open<int>] = ~[c];
error!("%?", streams[0]);
}
pub fn main() {
//os::getenv("FOO");
rendezvous();
}
| rendezvous | identifier_name |
ex2a_telnet.py | #!/usr/bin/env python
import telnetlib
import time
import socket
import sys
import getpass
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
'''
Initiate the Telnet Session
'''
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_ver... | def main():
'''
Connect to pynet-rtr1, login, and issue 'show ip int brief'
'''
ip_addr = raw_input("IP address: ")
ip_addr = ip_addr.strip()
username = 'pyclass'
password = getpass.getpass()
remote_conn = telnet_connect(ip_addr)
output = login(remote_conn, username, password)
... | except socket.timeout:
sys.exit("Connection timed-out")
| random_line_split |
ex2a_telnet.py | #!/usr/bin/env python
import telnetlib
import time
import socket
import sys
import getpass
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
'''
Initiate the Telnet Session
'''
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_ver... | main() | conditional_block | |
ex2a_telnet.py | #!/usr/bin/env python
import telnetlib
import time
import socket
import sys
import getpass
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
'''
Initiate the Telnet Session
'''
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_ver... |
def no_more(remote_conn, paging_cmd='terminal length 0'):
'''
No paging of Output
'''
return send_command(remote_conn, paging_cmd)
def telnet_connect(ip_addr):
'''
Establish the Telnet Connection
'''
try:
return telnetlib.Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
except... | '''
Login to pynet-rtr1
'''
output = remote_conn.read_until("sername:", TELNET_TIMEOUT)
remote_conn.write(username + '\n')
output += remote_conn.read_until("ssword:", TELNET_TIMEOUT)
remote_conn.write(password + '\n')
return output | identifier_body |
ex2a_telnet.py | #!/usr/bin/env python
import telnetlib
import time
import socket
import sys
import getpass
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
'''
Initiate the Telnet Session
'''
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_ver... | ():
'''
Connect to pynet-rtr1, login, and issue 'show ip int brief'
'''
ip_addr = raw_input("IP address: ")
ip_addr = ip_addr.strip()
username = 'pyclass'
password = getpass.getpass()
remote_conn = telnet_connect(ip_addr)
output = login(remote_conn, username, password)
time.sle... | main | identifier_name |
autocomplete.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AfterContentInit, ElementRef, QueryList, TemplateRef, ChangeDetectorRef, EventEmitter } from '@angular/core'... | implements AfterContentInit {
private _changeDetectorRef;
/** Manages active item in option list based on key events. */
_keyManager: ActiveDescendantKeyManager<MdOption>;
/** Whether the autocomplete panel should be visible, depending on option length. */
showPanel: boolean;
/** @docs-private ... | MdAutocomplete | identifier_name |
autocomplete.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AfterContentInit, ElementRef, QueryList, TemplateRef, ChangeDetectorRef, EventEmitter } from '@angular/core'... | };
} | /** Sets a class on the panel based on whether it is visible. */
_getClassList(): {
'mat-autocomplete-visible': boolean;
'mat-autocomplete-hidden': boolean; | random_line_split |
rollbar.snippet.js | (function(window, document){
var _shimCounter = 0;
function Rollbar(parentShim) {
this.shimId = ++_shimCounter;
this.notifier = null;
this.parentShim = parentShim;
this.logger = function() {};
if (window.console) {
if (window.console.shimId === undefined) {
this.logger = window.console.log;
... |
if (!f._wrapped) {
f._wrapped = function () {
try {
return f.apply(this, arguments);
} catch(e) {
window._rollbarWrappedError = e;
throw e;
}
};
f._wrapped._isWrap = true;
for (var prop in f) {
if (f.hasOwnProperty(prop)) {
... | {
return f;
} | conditional_block |
rollbar.snippet.js | (function(window, document){
var _shimCounter = 0;
function Rollbar(parentShim) {
this.shimId = ++_shimCounter;
this.notifier = null;
this.parentShim = parentShim;
this.logger = function() {};
if (window.console) {
if (window.console.shimId === undefined) {
this.logger = window.console.log;
... | }
function _extendListenerPrototype(client, prototype) {
if (prototype.hasOwnProperty && prototype.hasOwnProperty('addEventListener')) {
var oldAddEventListener = prototype.addEventListener;
prototype.addEventListener = function(event, callback, bubble) {
oldAddEventListener.call(this, event, client.w... | {
var R = Rollbar;
return _wrapInternalErr(function() {
if (this.notifier) {
return this.notifier[method].apply(this.notifier, arguments);
} else {
var shim = this;
var isScope = method === 'scope';
if (isScope) {
shim = new R(this);
}
var args = Array.prototype.s... | identifier_body |
rollbar.snippet.js | (function(window, document){
var _shimCounter = 0;
function Rollbar(parentShim) {
this.shimId = ++_shimCounter;
this.notifier = null;
this.parentShim = parentShim;
this.logger = function() {};
if (window.console) {
if (window.console.shimId === undefined) {
this.logger = window.console.log;
... | }
}
return f._wrapped;
} catch (e) {
// Try-catch here is to work around issue where wrap() fails when used inside Selenium.
// Return the original function if the wrap fails.
return f;
}
};
// Stub out rollbar.js methods
function stub(method) {
var R = Rollbar;
return _wrapInternalE... | for (var prop in f) {
if (f.hasOwnProperty(prop)) {
f._wrapped[prop] = f[prop];
} | random_line_split |
rollbar.snippet.js | (function(window, document){
var _shimCounter = 0;
function Rollbar(parentShim) {
this.shimId = ++_shimCounter;
this.notifier = null;
this.parentShim = parentShim;
this.logger = function() {};
if (window.console) {
if (window.console.shimId === undefined) {
this.logger = window.console.log;
... | (method) {
var R = Rollbar;
return _wrapInternalErr(function() {
if (this.notifier) {
return this.notifier[method].apply(this.notifier, arguments);
} else {
var shim = this;
var isScope = method === 'scope';
if (isScope) {
shim = new R(this);
}
var args = Array.pr... | stub | identifier_name |
upgrade_ng1_adapter.ts | => '-' + next.toLowerCase());
var self = this;
this.type =
Directive({selector: selector, inputs: this.inputsRename, outputs: this.outputsRename})
.Class({
constructor: [
new Inject(NG1_SCOPE), ElementRef,
function(scope: angular.IScope, element... |
}
ngOnInit() {
if (!this.directive.bindToController && this.directive.controller) {
this.buildController(this.directive.controller);
}
var link = this.directive.link;
if (typeof link == 'object') link = (<angular.IDirectivePrePost>link).pre;
if (link) {
var attrs: angular.IAttribut... | {
(this as any /** TODO #9100 */)[propOuts[k]] = new EventEmitter();
this.checkLastValues.push(INITIAL_VALUE);
} | conditional_block |
upgrade_ng1_adapter.ts | = outputName + ': ' + name;
var outputNameRenameChange = outputName + ': ' + name + 'Change';
var inputName = 'input_' + name;
var inputNameRename = inputName + ': ' + name;
switch (type) {
case '=':
this.propertyOutputs.push(outputName);
... | {
if (!require) {
return undefined;
} else if (typeof require == 'string') {
var name: string = <string>require;
var isOptional = false;
var startParent = false;
var searchParents = false;
var ch: string;
if (name.charAt(0) == '?') {
isOptional = true;
n... | identifier_body | |
upgrade_ng1_adapter.ts | => '-' + next.toLowerCase());
var self = this;
this.type =
Directive({selector: selector, inputs: this.inputsRename, outputs: this.outputsRename})
.Class({
constructor: [
new Inject(NG1_SCOPE), ElementRef,
function(scope: angular.IScope, element... | (feature: string) {
throw new Error(`Upgraded directive '${this.name}' does not support '${feature}'.`);
}
extractBindings() {
var btcIsObject = typeof this.directive.bindToController === 'object';
if (btcIsObject && Object.keys(this.directive.scope).length) {
throw new Error(
`Binding ... | notSupported | identifier_name |
upgrade_ng1_adapter.ts | => '-' + next.toLowerCase());
var self = this;
this.type =
Directive({selector: selector, inputs: this.inputsRename, outputs: this.outputsRename})
.Class({
constructor: [
new Inject(NG1_SCOPE), ElementRef,
function(scope: angular.IScope, element... | }
}
/**
* Upgrade ng1 components into Angular 2.
*/
static resolve(
exportedComponents: {[name: string]: UpgradeNg1ComponentAdapterBuilder},
injector: angular.IInjectorService): Promise<angular.ILinkFn[]> {
var promises: Promise<angular.ILinkFn>[] = [];
var compile: angular.ICompile... | var div = document.createElement('div');
div.innerHTML = html;
return compile(div.childNodes); | random_line_split |
test_utils.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | self.assertRaises(ValueError, utils.load_json_str, "BAD DATA")
# Refacter merged the init_amql and the connect_mq functions
# together. Need to fix this unit test.
#
# def test_connect_mq(self):
# """
# Check that connect_mq follows the expected connection steps
# """
... | def tearDown(self):
"""
Reset mocks.
"""
channel.reset_mock()
def test_create_json_str(self):
"""
Verify create_json_str produces proper json
"""
assert utils.create_json_str({'test': 'data'}) == '{"test": "data"}'
assert utils.create_json_str... | identifier_body |
test_utils.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | def tearDown(self):
"""
Reset mocks.
"""
channel.reset_mock()
def test_create_json_str(self):
"""
Verify create_json_str produces proper json
"""
assert utils.create_json_str({'test': 'data'}) == '{"test": "data"}'
assert utils.create_json... | class TestUtils(TestCase):
| random_line_split |
test_utils.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | (self):
"""
Verify create_json_str produces proper json
"""
assert utils.create_json_str({'test': 'data'}) == '{"test": "data"}'
assert utils.create_json_str({'test': None}) == '{"test": null}'
self.assertRaises(ValueError, utils.create_json_str, "BAD DATA")
def test... | test_create_json_str | identifier_name |
testArrays.py | # Originally contributed by Stefan Schukat as part of this arbitrary-sized
# arrays patch.
from win32com.client import gencache
from win32com.test import util
import unittest
ZeroD = 0
OneDEmpty = []
OneD = [1,2,3]
TwoD = [
[1,2,3],
[1,2,3],
[1,2,3]
]
TwoD1 = [
[
... | (self, array):
self.arr.Array = array
self.failUnlessEqual(_normalize_array(self.arr.Array), array)
def testZeroD(self):
self._doTest(ZeroD)
def testOneDEmpty(self):
self._doTest(OneDEmpty)
def testOneD(self):
self._doTest(OneD)
def testTwoD(self):
self._d... | _doTest | identifier_name |
testArrays.py | # Originally contributed by Stefan Schukat as part of this arbitrary-sized
# arrays patch.
from win32com.client import gencache
from win32com.test import util
import unittest
ZeroD = 0
OneDEmpty = []
OneD = [1,2,3]
TwoD = [
[1,2,3],
[1,2,3],
[1,2,3]
]
TwoD1 = [
[
... |
ret = []
for i in a:
ret.append(_normalize_array(i))
return ret
class ArrayTest(util.TestCase):
def setUp(self):
self.arr = gencache.EnsureDispatch("PyCOMTest.ArrayTest")
def tearDown(self):
self.arr = None
def _doTest(self, array):
self.arr.Array = array
... | return a | conditional_block |
testArrays.py | # Originally contributed by Stefan Schukat as part of this arbitrary-sized
# arrays patch.
from win32com.client import gencache
from win32com.test import util
import unittest
ZeroD = 0
OneDEmpty = []
OneD = [1,2,3]
TwoD = [
[1,2,3],
[1,2,3],
[1,2,3]
]
TwoD1 = [
[
... | [1,2,3]
]
]
OneD2 = [
[1,2,3],
[1,2,3,4,5],
[
[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5]
]
]
ThreeD = [
[
[1,2,3],
[1,2,3],
[1,2,3]
],
[... | [1,2,3], | random_line_split |
testArrays.py | # Originally contributed by Stefan Schukat as part of this arbitrary-sized
# arrays patch.
from win32com.client import gencache
from win32com.test import util
import unittest
ZeroD = 0
OneDEmpty = []
OneD = [1,2,3]
TwoD = [
[1,2,3],
[1,2,3],
[1,2,3]
]
TwoD1 = [
[
... |
if __name__ == "__main__":
try:
util.testmain()
except SystemExit as rc:
if not rc:
raise
| self._doTest(LargeD) | identifier_body |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated
// memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous
// status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting d... | (c: *mut libc::c_void) -> *mut libc::c_void {
unsafe {
let c: *mut u32 = c.cast();
*c += 1;
__tsan_testonly_barrier_wait(&raw mut BARRIER);
ptr::null_mut()
}
}
fn main() {
unsafe {
__tsan_testonly_barrier_init(&raw mut BARRIER, 2);
let c: *mut u32 = Box::into... | start | identifier_name |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated
// memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous
// status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting d... | {
unsafe {
__tsan_testonly_barrier_init(&raw mut BARRIER, 2);
let c: *mut u32 = Box::into_raw(Box::new(1));
let mut t: libc::pthread_t = mem::zeroed();
libc::pthread_create(&mut t, ptr::null(), start, c.cast());
__tsan_testonly_barrier_wait(&raw mut BARRIER);
*c += 1;... | identifier_body | |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated | // status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting data access is de-facto synchronized with a special TSAN
// barrier, which does not introduce synchronization from TSAN perspective, but
// is necessary to make the test robust. Wi... | // memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous | random_line_split |
tool.py | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- 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... | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Command-line tool
NOTE: The API for the command-line tool is experime... | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software | random_line_split |
tool.py | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- 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... | (self):
self.server_close()
self.stopped = True
self.serve_forever()
def run_server(uri, proto, msg, datum):
url_obj = urllib.parse.urlparse(uri)
server_addr = (url_obj.hostname, url_obj.port)
global responder
global server_should_shutdown
server_should_shutdown = False
responder = GenericRespo... | force_stop | identifier_name |
tool.py | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- 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... |
elif args[5] == "-data":
print("JSON Decoder not yet implemented.")
return 1
else:
print(usage_str)
return 1
run_server(uri, proto, msg, datum)
elif args[1] == "rpcsend":
usage_str = "Usage: %s rpcsend uri protocol_file " % args[0]
usage_str += "message_name (-... | reader = open(args[6], 'rb')
datum_reader = io.DatumReader()
dfr = datafile.DataFileReader(reader, datum_reader)
datum = dfr.next() | conditional_block |
tool.py | #!/usr/bin/env python3
# -*- mode: python -*-
# -*- 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... |
class StoppableHTTPServer(HTTPServer):
"""HTTPServer.shutdown added in Python 2.6. FML."""
stopped = False
allow_reuse_address = True
def __init__(self, *args, **kw):
HTTPServer.__init__(self, *args, **kw)
self.allow_reuse_address = True
def serve_forever(self):
while not self.stopped:
se... | def do_POST(self):
self.responder = responder
call_request_reader = ipc.FramedReader(self.rfile)
call_request = call_request_reader.read_framed_message()
resp_body = self.responder.respond(call_request)
self.send_response(200)
self.send_header('Content-Type', 'avro/binary')
self.end_headers(... | identifier_body |
tag_topics_in_danish.py | import zeeguu_core
from zeeguu_core.model import Article, Language, LocalizedTopic
session = zeeguu_core.db.session
counter = 0
languages = Language.available_languages()
languages = [Language.find('da')]
for language in languages:
articles = Article.query.filter(Article.language == language).order_by(Article.i... |
print("")
session.add(article)
if counter % 1000 == 0:
percentage = (100 * counter / total_articles) / 100
print(f"{counter} dorticles done ({percentage}%). last article id: {article.id}. Comitting... ")
session.commit()
percentage = (100 * counter / total_... | article.add_topic(loc_topic.topic)
print(f" #{loc_topic.topic_translated}") | conditional_block |
tag_topics_in_danish.py | import zeeguu_core
from zeeguu_core.model import Article, Language, LocalizedTopic
session = zeeguu_core.db.session
counter = 0
languages = Language.available_languages()
languages = [Language.find('da')]
for language in languages:
articles = Article.query.filter(Article.language == language).order_by(Article.i... |
percentage = (100 * counter / total_articles) / 100
print(f"{counter} dorticles done ({percentage}%). last article id: {article.id}. Comitting... ")
session.commit() | percentage = (100 * counter / total_articles) / 100
print(f"{counter} dorticles done ({percentage}%). last article id: {article.id}. Comitting... ")
session.commit() | random_line_split |
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | // let to_wr = m.as_bytes();
// let len = to_wr.len() as u32;
// let res = writer.write(&to_wr, len);
// match res {
// WriteResult::Success(_) => (),
// err => {
// error!("Write failed {:?}", err);
// ... | random_line_split | |
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | panic!("Read failed!!!!");
}
},
}
}
info!(
"We read {} bytes in {} messages. Channel state is {:?}",
reader.position(),
msg_count,
reader.exhausted()
);
Ok(())
}
fn main() {
SimpleLogger::new().init().unwrap();... | {
info!("Creating reader porcess ...{}", getpid());
let mut reader = try_shm_reader(&Path::new(Q_PATH), 1000, 2000, 200).unwrap();
let mut stop = false;
let mut msg_count = 0;
while !stop {
match reader.try_read() {
Ok(Some(_)) => msg_count += 1,
Ok(None) => (),
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.