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 |
|---|---|---|---|---|
contact-form.component.ts | import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertsService } from '@jaspero/ng2-alerts';
import { AppStateService } from '../../../services/app-state.service';
import { ApiClient, Contact, Address, UpdateContactRequ... |
public get model(): Contact { return this._model; }
constructor(private alertsService: AlertsService, private route: ActivatedRoute,
private appState: AppStateService,
private apiClient: ApiClient, private lookups: LookupsService) {
this.model = new Contact();
this.model.address = new Address();
... | {
this._model = value;
} | identifier_body |
contact-form.component.ts | import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertsService } from '@jaspero/ng2-alerts';
import { AppStateService } from '../../../services/app-state.service';
import { ApiClient, Contact, Address, UpdateContactRequ... |
}
private bak(value: any) {
this._bak = value.clone();
}
cancel() {
this.readonly = true;
this.model = this._bak;
}
displayCountryFn(country: LookupEntry): string {
return country ? country.description : '';
}
save() {
this.readonly = true;
const request: UpdateContactReque... | {
this.bak(this.model);
} | conditional_block |
unused-macro.rs | // Copyright 2017 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 ... | {} | identifier_body | |
unused-macro.rs | // Copyright 2017 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 ... | () {}
| main | identifier_name |
unused-macro.rs | // Copyright 2017 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 ... | // Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() {} | mod bar { | random_line_split |
config.js | // Don't commit this file to your public repos. This config is for first-run
//
exports.creds = {
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', // For using Microsoft you should never need to change this.... | responseMode: 'form_post', // For login only flows we should have token passed back to us in a POST
//scope: ['email', 'profile'] // additional scopes you may wish to pass
tenantName: 'argoadb2ctest.onmicrosoft.com'
}; | random_line_split | |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";... |
/**
* Creates initial contents and fake menus.
*
* @param requestedSize Size of the contents.
* @returns A Promise for the actual size of the contents.
*/
public async resetContents(requestedSize: IRelativeSizeSchema): Promise<IAbsoluteSizeSchema> {
if (this.createdElements ... | {
this.dependencies = dependencies;
this.areasFaker = new AreasFaker(this.dependencies);
} | identifier_body |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";... | {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates placeholder menu titles before a real menu is created.
*/
private readonly areasFaker: AreasFaker;
/**
* Menu and content elements, once created.
*/
... | Display | identifier_name |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";... |
const availableContainerSize: IAbsoluteSizeSchema = this.getAvailableContainerSize(this.dependencies.container);
const containerSize: IAbsoluteSizeSchema = getAbsoluteSizeInContainer(availableContainerSize, requestedSize);
const { menuArea, menuSize } = await this.areasFaker.createAndAppendMen... | {
this.dependencies.container.removeChild(this.createdElements.contentArea);
this.dependencies.container.removeChild(this.createdElements.menuArea);
} | conditional_block |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";... | * Containing IUserWrappr holding this display.
*/
userWrapper: IUserWrappr;
}
/**
* Contains contents and menus within a container.
*/
export class Display {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates pla... | styles: IStyles;
/** | random_line_split |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
... |
class WebSocketHandler(tornado.websocket.WebSocketHandler):
listenners = []
def check_origin(self, origin):
return True
@tornado.gen.engine
def open(self):
WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
We... | self.render('index.html') | identifier_body |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
... |
@tornado.gen.coroutine
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
logging.info("application running on http://localhost:8888")
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(main)
t... | listenner.write_message(wsdata) | conditional_block |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
... | (self, origin):
return True
@tornado.gen.engine
def open(self):
WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
... | check_origin | identifier_name |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
... | WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
for listenner in WebSocketHandler.listenners:
listenner.write_mess... | @tornado.gen.engine
def open(self): | random_line_split |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogge... |
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the client side.
:returns: status_body set for an error.
E.g.::
rc = {
"success": True | False,
"data": ...,
"message",... | override_method = ''
# First check the "_method" form parameter
# if 'form-urlencoded' in environ['CONTENT_TYPE']:
# from webob import Request
# request = Request(environ)
# override_method = request.str_POST.get('_method', '').upper()
... | conditional_block |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogge... |
def formatError(self):
"""Return a string representing the last traceback.
"""
exception, instance, tb = traceback.sys.exc_info()
error = "".join(traceback.format_tb(tb))
return error
def __call__(self, environ, start_response):
try:
return self.app... | self.app = application
self.log = get_log("JSONErrorHandler") | identifier_body |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogge... | (
success=True, data=None, message="", to_json=False, traceback='',
):
"""Create a JSON response body we will use for error and other situations.
:param success: Default True or False.
:param data: Default "" or given result.
:param message: Default "ok" or a user given message string.
:para... | status_body | identifier_name |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogge... | environ['http_method_override.original_method'] = method
# Override HTTP method
environ['REQUEST_METHOD'] = override_method
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the... | random_line_split | |
RangeBackgrounds.spec.ts | import {test} from 'ava';
import {Sheet, SheetConfig} from 'excol';
import {Errors} from 'excol';
const DIMENSION = 20;
const cfg: SheetConfig = {
id: 0,
name: 'test lib',
numRows: DIMENSION,
numColumns: DIMENSION
};
test('should set array of backgrounds for range A2:B3', t => {
const sheet = new Sheet(cf... |
t.deepEqual(bgs, expected);
t.is(bg, 'A2');
});
/*
test.only('should throw error on bad colors types', t => {
const grid = new Sheet(cfg);
const range = grid.getRange({A1: 'A2:B3'});
const expectedErr = Errors.INCORRECT_SET_VALUES_PARAMETERS(typeof '');
const expectedErr2 = Errors.INCORRECT_SET_VALUES_PARA... | ['A3', 'B3']
]; | random_line_split |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | post: (message: ASObject) => string;
sendToNearest: (message: ASObject, groupAddress: string) => string;
sendToNeighbor: (message: ASObject, sendMode: string) => string;
sendToAllNeighbors: (message: ASObject) => string;
addNeighbor: (peerID: string) => boolean;
addMemberHint: (peerID: string) =... | denyRequestedObject: (requestID: number /*int*/) => void;
estimatedMemberCount: number;
neighborCount: number;
receiveMode: string; | random_line_split |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
get localCoverageFrom(): string {
notImplemented("public flash.net.NetGroup::get localCoverageFrom"); return;
// return this._localCoverageFrom;
}
get localCoverageTo(): string {
notImplemented("public flash.net.NetGroup::get localCoverageTo"); return;
// return this._localCoverageT... | {
peerID = axCoerceString(peerID);
notImplemented("public flash.net.NetGroup::convertPeerIDToGroupAddress"); return;
} | identifier_body |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | (): string {
notImplemented("public flash.net.NetGroup::get localCoverageFrom"); return;
// return this._localCoverageFrom;
}
get localCoverageTo(): string {
notImplemented("public flash.net.NetGroup::get localCoverageTo"); return;
// return this._localCoverageTo;
}
}
}
| localCoverageFrom | identifier_name |
gist-article.service.spec.ts | /**
* @author Cristian Moreno <khriztianmoreno@gmail.com>
*/
import { TestBed, getTestBed, async, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {
ResponseOptions,
BaseRequestOptions,
Response,
HttpModule,
Http,
XHRBackend,
RequestMeth... | mockBackend = getTestBed().get(MockBackend);
}));
describe('When I request gists API services', () => {
it('if i do a GET api.github.com/users/:username/gists it should fetch gists list',
async(inject([GistArticleService], (appService) => {
mockBackend.connections.subscribe(
(connec... | random_line_split | |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# 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... | raise exception.NotAuthorized(action=action)
| """Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthor... | identifier_body |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# 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... |
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dicti... | with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime | conditional_block |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# 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... | except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.p... | return matches[0] | random_line_split |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# 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... | (self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches =... | load_rules | identifier_name |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::ne... | We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait | conditional_block |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | }
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::ne... | /// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )* | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progre... | gistry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let b... | identifier_body |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot:... | registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq... | () {
let | identifier_name |
Success.js | import PropTypes from "prop-types";
import { Link } from "react-router"; |
<h4 className="text-center push-ends">
Welcome{person.nickName ? ` ${(person.nickName || person.firstName)}` : ""}!
</h4>
<p className="text-left">
Congratulations on setting up your NewSpring account!
This account will help us to serve you better in your walk with Jesus.
To help u... |
const Success = ({ person, onExit }) => (
<div className="soft soft-double-ends one-whole text-center"> | random_line_split |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
if wall_is_above() != True: | while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_lef... | while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
| random_line_split |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
|
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_l... | move_left() | conditional_block |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def | ():
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
... | task_8_28 | identifier_name |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
|
if __name__ == '__main__':
run_tasks() | if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
whi... | identifier_body |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {Tool... |
}
| {
if (isDevMode) {
this.logService.setLogLevel(LogLevel.DEBUG);
}
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'... | identifier_body |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {Tool... |
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'), require('./assets/i18n/de.json')));
translate.use('en');
}
}
| {
this.logService.setLogLevel(LogLevel.DEBUG);
} | conditional_block |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {Tool... | {path: '/tabs', component: TabsDemoComponent},
{path: '/tooltip', component: TooltipDemoComponent},
{path: '/select2', component: Select2DemoComponent},
{path: '/radio-button-group', component: RadioButtonGroupDemoComponent},
])
export class AuiNgDemoAppComponent {
constructor(
private rout... | `
})
@Routes([
{path: '/', component: DialogDemoComponent}, // remove this entry as soon as useAsDefault is implemented
{path: '/dialog', component: DialogDemoComponent}, // add {useAsDefault: true} | random_line_split |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {Tool... | {
constructor(
private router: Router,
private logService: LogService,
@Inject(IS_DEV_MODE) private isDevMode: string,
translate : TranslateService
) {
if (isDevMode) {
this.logService.setLogLevel(LogLevel.DEBUG);
}
translate.setTranslation(... | AuiNgDemoAppComponent | identifier_name |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
def _patch_description(description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
... | environment = db_session.query(models.Environment).get(environment_id)
if not environment:
LOG.info(_('Environment with id {0} not found').format(environment_id))
raise exc.HTTPNotFound
if environment.tenant_id != request.context.tenant:
LOG.info(_('User is not authorized to access this... | identifier_body |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | (description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
LOG.info(_('Deployment w... | _patch_description | identifier_name |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | num_errors = unit.query(models.Status).filter_by(
level='error',
deployment_id=deployment.id).count()
num_warnings = unit.query(models.Status).filter_by(
level='warning',
deployment_id=deployment.id).count()
if deployment.finished:
if num_errors:
deploym... | def set_dep_state(deployment, unit): | random_line_split |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
if deployment.environment_id != environment_id:
LOG.info(_('Deployment with id {0} not found'
' in environment {1}').format(deployment_id,
environment_id))
raise exc.HTTPBadRequest
_patch_description(deployment.description)
... | LOG.info(_('Deployment with id {0} not found').format(deployment_id))
raise exc.HTTPNotFound | conditional_block |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} |
fn main() {
println!("{}", equal(&1, &2)); | random_line_split |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
}
| main | identifier_name |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body | |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\... | reg : {
'com' : /(\/\*[\s\S]*?\*\/)/, //注释
//'key' : /((?:\.|#)?(?:\w+(?:[,\s:#\w\.]+)?)+){/, //选择器
'key' : /([^{\n\$\|]*?){/, //选择器
'obj' : /(?:([\w-]+?)\s*\:([\w\s"',\-\#]*))/ //属性名:属性值
}
}
JSHL.extendLanguage = function(langName, langObj){
JSHL.language[langName] = la... | cls : ['com','attr','key','val'], | random_line_split |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\... | function hlbylanguage(html, lang, findParent){
//var ln = addLineNumber(html.split('\n').length);
//console.log(lang,html);
if(!(lang in JSHL.language))
return html + (findParent ? addLineNumber(html.split('\n').length) : '')
var l = JSHL.language[lang];
if(findPa... | ascript',
html,outer;
function parseHTML(html){
return html.replace(/</g,'<').replace(/>/g,'>').replace(/(\r?\n)$/g,'');
}
function addLineNumber(nums){
var html = ['<div class="','jshl-linenum','">'], i=1;
for(; i< nums; i+=1) html.push(i+'.<br/>');
html.push... | identifier_body |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\... | ang = 'javascript',
html,outer;
function parseHTML(html){
return html.replace(/</g,'<').replace(/>/g,'>').replace(/(\r?\n)$/g,'');
}
function addLineNumber(nums){
var html = ['<div class="','jshl-linenum','">'], i=1;
for(; i< nums; i+=1) html.push(i+'.<br/>');
... | l | identifier_name |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } fr... | }
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparatorResult * -1;
}
}
// All matched, we make is so that the original sort order is kept:
return sortedNodeA.currentPos - sortedNodeB.curre... | {
const nodeA: RowNode = sortedNodeA.rowNode;
const nodeB: RowNode = sortedNodeB.rowNode;
// Iterate columns, return the first that doesn't match
for (let i = 0, len = sortOptions.length; i < len; i++) {
const sortOption = sortOptions[i];
// let compared = compar... | identifier_body |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } fr... | {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[] {
const mapper = (rowNode: RowNode, pos: number) => ({currentPos: pos, ro... | RowNodeSorter | identifier_name |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } fr... | // this logic is used by both SSRM and CSRM
@Bean('rowNodeSorter')
export class RowNodeSorter {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[])... | random_line_split | |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } fr... | else {
//otherwise do our own comparison
comparatorResult = _.defaultComparator(valueA, valueB, this.gridOptionsWrapper.isAccentedSort());
}
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparat... | {
//if comparator provided, use it
comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isInverted);
} | conditional_block |
test2.js | var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var multer = require('multer');
var fs = require('fs')
var exec = require('child_process').exec;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
app.listen(8888,functio... | var cmdStr = 'rm '+req.files.tupian.path;
exec(cmdStr, function (err, stdout, stderr) {
console.log(stdout)
})
})
}) | console.log(req.files);
var cmdStr = 'mv '+req.files.tupian.path+" "+"public/wz/tx/233/";
exec(cmdStr, function (err, stdout, stderr) { | random_line_split |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Inte... | q( | identifier_name |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
... |
s1 == s2
}
| identifier_body |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | }
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let... |
return s.as_ptr();
}
| conditional_block |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Inte... | assert!(!bar_ptr.is_null());
assert!(foo_ptr != bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr != intern.add(cstr(b"fo\0")));
assert!(foo_ptr != intern.add(cstr(b"fool\0")));
assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
}
} |
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null()); | random_line_split |
ds_reference.py | print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist is just another name pointing to the same object!
mylist = shoplist
# I purchased the first item, so I remove it from the list
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# Notice that both shoplist and... | del mylist1[1]
print('shoplist is', shoplist)
print('mylist is', mylist1) |
print('shoplist is', shoplist)
print('mylist is', mylist)
| random_line_split |
biblivre.z3950.search.js | /**
* Este arquivo é parte do Biblivre5.
*
* Biblivre5 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Es... | ction(keepOrderingBar) {
Core.trigger(this.prefix + 'clear-search');
if (!keepOrderingBar) {
Core.removeMsg();
}
},
simpleSearch: function() {
var query = this.root.find('.search_box .simple_search :input[name=query]').val();
var attribute = this.root.find('.search_box .simple_search :input[name=attri... | ull) {
this.searchTerm({
query: query.value,
attribute: attribute.value,
server: server.value
});
}
}
},
clearResults: fun | conditional_block |
biblivre.z3950.search.js | /**
* Este arquivo é parte do Biblivre5.
*
* Biblivre5 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Es... | * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto
* com este programa, Se não, veja em <http://www.gnu.org/licenses/>.
*
* @author Alberto Wagner <alberto@biblivre.org.br>
* @author Danniel Willian <danniel@biblivre.org.br>
*
*/
var Z3950SearchClass = $.extend(CatalogingSearchClass, {
... | * mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
* MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
* | random_line_split |
main.rs | {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("F... | in() | identifier_name | |
main.rs | enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KE... | let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32; | random_line_split | |
main.rs | 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trai... | ,
&Event::MouseWheel { direction, y, .. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
... | {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
} | conditional_block |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is ... |
def install(self, **kwargs):
# install Nginx using the package manager.
self._simple.install()
start_msg('----- Configuring "Nginx":')
# verify that there's an init-script.
result = run('test -f /etc/init.d/nginx')
if result.failed:
raise HaltError('Uh ... | return self._simple.check() | identifier_body |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is ... |
# write nginx.conf file.
dest = path.join(cfg().nginx_conf, 'nginx.conf')
message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself.
# set Nginx so it can be managed ... | raise HaltError('Uh oh. Package manager did not install an Nginx init-script.') | conditional_block |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is ... | (self, name, server_names, proxy_pass, static_locations='', log_root=None, listen=80):
"""
Writes an Nginx server configuration file.
This function writes a specific style of configuration, that seems to be somewhat common, where
Nginx is used as a reverse-proxy for a locally-running (e... | write_config | identifier_name |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is ... | # set Nginx so it can be managed by chkconfig; and turn on boot startup.
result = run('which chkconfig')
if result.succeeded:
message('System has chkconfig; configuring.')
result = sudo('chkconfig --add nginx')
if result.failed:
raise HaltError... | message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself. | random_line_split |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
... |
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):
other = _get_variable_value(other)
assert self.is_css == other.is_css, "Both locators must be of same type"
if self.is_css:
... | raise NotImplementedError("indexing not supported for css selectors") | conditional_block |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
... |
def __getitem__(self, index):
if self.locator.startswith('css='):
raise NotImplementedError("indexing not supported for css selectors")
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):... | return self.locator.startswith('//') | identifier_body |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
... | (self):
return self.locator.startswith('css=')
@property
def is_xpath(self):
return self.locator.startswith('//')
def __getitem__(self, index):
if self.locator.startswith('css='):
raise NotImplementedError("indexing not supported for css selectors")
elif self.lo... | is_css | identifier_name |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
... |
add_talk_page = Page('/talks/new')
talk_page = Page('/talks/id/') # TODO this should be a regex
login_page = Page('/admin/login/')
add_series_page = Page('/talks/series/new')
series_page = Page('/talks/series/id/')
# dynamic pages
edit_talk_page = lambda slug: Page('/talks/id/%s/edit' % slug)
show_talk_page = la... | elif self.is_xpath:
return Element(other.locator + self.locator) # FIXME might fail for advanced xpath
# pages | random_line_split |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a... |
def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func):
result, old_wt = ewm_func(
weighted_avg,
deltas,
min_periods,
self.old_wt_factor,
self.new_wt,
self.old_wt,
self.adjust,
self.ignore_na,
)... | alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None | identifier_body |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a... |
else:
old_wt[j] = 1.0
elif is_observations[j]:
weighted_avg[j] = cur[j]
result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
return result, old_wt
return online_ewma
class EWMMean... | old_wt[j] += new_wt | conditional_block |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a... | old_wt_factor: float,
new_wt: float,
old_wt: np.ndarray,
adjust: bool,
ignore_na: bool,
):
"""
Compute online exponentially weighted mean per column over 2D values.
Takes the first observation as is, then computes the subsequent
exponentially ... | values: np.ndarray,
deltas: np.ndarray,
minimum_periods: int, | random_line_split |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a... | (self, com, adjust, ignore_na, axis, shape):
alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.sh... | __init__ | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]]
_transport_registry["grpc"] = DataCatalogGrpcTransport
_transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport
__all__ = (
"DataCatalogTransport",
"DataCatalogGrpcTransport",
... | from .grpc import DataCatalogGrpcTransport
from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport | random_line_split |
authcodes.js | module.exports = function(app) {
var _env = app.get('env');
var _log = app.lib.logger;
var _mongoose = app.core.mongo.mongoose;
var _group = 'MODEL:oauth.authcodes';
var Schema = {
authCode : {type: String, required: true, unique: true, alias: 'authCode'},
clientId : {... | });
AuthCodesSchema.method('saveAuthCode', function(code, clientId, expires, userId, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
if (userId.id)
userId = userId.id;
var fields = {
clientId : clientId,
userId : userId,
expi... |
// statics
AuthCodesSchema.method('getAuthCode', function(authCode, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
AuthCodes.findOne({authCode: authCode}, cb); | random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
... | Some(&self.layout)
}
| random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn | () -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: N... | new | identifier_name |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
... | {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
... | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App ... | Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
... | {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bo... | identifier_body |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... | """Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.pa... | identifier_body | |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... |
return main + sub
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development ve... | mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4]) | conditional_block |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... | ():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirna... | get_git_changeset | identifier_name |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... | """Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(o... | return main + sub
def get_git_changeset(): | random_line_split |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.... |
});
var result = nitpick.runTest(testType);
}); | {
Entities.deleteEntity(createdEntities[i]);
} | conditional_block |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
|
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, ... | nitpick.perform("Text Entity topMargin", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
| random_line_split |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.... | (col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Text... | getPos | identifier_name |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.... |
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(-0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.0,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Text",
... | {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... |
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new referen... | {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... | gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
))... | k_x11_window_foreign_new_for_display(
| identifier_name |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window... |
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
... | random_line_split | |
access.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive acces... | is_closed | identifier_name |
access.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
... | /// (the uv event loop).
| random_line_split |
index.js | /**
@file Export all functions in yuv-video to user
@author Gilson Varghese<gilsonvarghese7@gmail.com>
@date 13 Oct, 2016
**/
/**
Module includes
*/
var frameReader = require(./lib/framereader);
var frameWriter = require(./lib/framewriter);
var frameConverter = require(./lib/frameconverter);
/**
Global var... | */
frameConverter: frameConverter
}; | random_line_split | |
index.ts | import Module from 'ringcentral-integration/lib/di/decorators/module';
import RcUIModule from '../../lib/RcUIModule';
@Module({
name: 'ConnectivityBadgeUI',
deps: ['Locale', 'ConnectivityManager'],
})
export default class ConnectivityBadgeUI extends RcUIModule {
_locale: any;
_connectivityManager: any;
con... | getUIProps() {
return {
currentLocale: this._locale.currentLocale,
mode:
(this._connectivityManager.ready && this._connectivityManager.mode) ||
null,
webphoneConnecting:
this._connectivityManager.ready &&
this._connectivityManager.webphoneConnecting,
hasLimi... | this._connectivityManager = connectivityManager;
}
| random_line_split |
index.ts | import Module from 'ringcentral-integration/lib/di/decorators/module';
import RcUIModule from '../../lib/RcUIModule';
@Module({
name: 'ConnectivityBadgeUI',
deps: ['Locale', 'ConnectivityManager'],
})
export default class ConnectivityBadgeUI extends RcUIModule {
_locale: any;
_connectivityManager: any;
con... | () {
if (connectivityManager.isWebphoneUnavailableMode) {
connectivityManager.checkWebphoneAndConnect();
} else if (connectivityManager.hasLimitedStatusError) {
connectivityManager.checkStatus();
} else {
connectivityManager.showConnectivityAlert();
}
... | onClick | identifier_name |
index.ts | import Module from 'ringcentral-integration/lib/di/decorators/module';
import RcUIModule from '../../lib/RcUIModule';
@Module({
name: 'ConnectivityBadgeUI',
deps: ['Locale', 'ConnectivityManager'],
})
export default class ConnectivityBadgeUI extends RcUIModule {
_locale: any;
_connectivityManager: any;
con... |
getUIProps() {
return {
currentLocale: this._locale.currentLocale,
mode:
(this._connectivityManager.ready && this._connectivityManager.mode) ||
null,
webphoneConnecting:
this._connectivityManager.ready &&
this._connectivityManager.webphoneConnecting,
hasLi... | {
super({
...options,
});
this._locale = locale;
this._connectivityManager = connectivityManager;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.