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 |
|---|---|---|---|---|
Update_W_each_3it_5s_rademacher.py | cell lengthts in each direction
hx = [(csx,npad, -1.5),(csx,ncx),(csx,npad, 1.5)]
hz= [(csz,npad,-1.5),(csz,ncz)]
# Create mesh
mesh = Mesh.TensorMesh([hx, hz],x0="CN")
# Map mesh coordinates from local to UTM coordiantes
#mesh.x0[2] = mesh.x0[2]-mesh.vectorCCz[-npad-1]
mesh.x0[1] = mesh.x0[1]+csz/2.
#mesh.x0[0] = mes... | x1,z1, r1 = 6., -4., 3.
ln_sigback = -5.
ln_sigc = -3.
ln_sigr = -7.
noisemean = 0.
noisevar = 0.0
overburden_extent = 0.
ln_over = -4.
#m = (lnsig_background)*np.ones(mesh.nC);
#mu =np.ones(mesh.nC);
mtrue = ln_sigback*np.ones(mesh.nC) + norm(noisemean,noisevar).rvs(mesh.nC)
overb = (mesh.gridCC[:,1] >-overburden_... | #Model Creation
lnsig_air = 1e-8;
x0,z0, r0 = -6., -4., 3. | random_line_split |
Update_W_each_3it_5s_rademacher.py | cell lengthts in each direction
hx = [(csx,npad, -1.5),(csx,ncx),(csx,npad, 1.5)]
hz= [(csz,npad,-1.5),(csz,ncz)]
# Create mesh
mesh = Mesh.TensorMesh([hx, hz],x0="CN")
# Map mesh coordinates from local to UTM coordiantes
#mesh.x0[2] = mesh.x0[2]-mesh.vectorCCz[-npad-1]
mesh.x0[1] = mesh.x0[1]+csz/2.
#mesh.x0[0] = mes... |
class SimultaneousRx(DC.Rx.BaseRx):
"""
SimultaneousRx receiver
"""
def __init__(self, locs, rxType='phi', **kwargs):
# We may not need this ...
SimPEG.Survey.BaseRx.__init__(self, locs, rxType)
@property
def nD(self):
"""Number of data in the rece... | return self.QW | identifier_body |
en.js | /
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'Source',
preview : 'Preview',
undo : 'Undo(Ctrl+Z)',
redo : 'Redo(Ctrl+Y)',
cut : 'Cut(Ctrl+X)',
copy : 'Copy(Ctrl+C)',
paste : 'Paste(Ctrl+V)',
plainpas... | 'Courier New' : 'Courier New',
'Garamond' : 'Garamond',
'Georgia' : 'Georgia',
'Tahoma' : 'Tahoma',
'Times New Roman' : 'Times New Roman',
'Trebuchet MS' : 'Trebuchet MS',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{' | 'fontname.fontName' : {
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Comic Sans MS' : 'Comic Sans MS', | random_line_split |
runfiles.py | dev_params.append(arg)
else:
if not found_other_test_framework_param:
found_other_test_framework_param = arg
else:
other_test_framework_params.append(arg)
# Here we'll run either with nose or with the pydev_runfiles.
import pydev_runfiles
im... |
except:
| thread_id_to_name[t.ident] = '%s (daemon: %s)' % (t.name, t.daemon) | conditional_block |
runfiles.py | pydev_params.append(arg)
else:
if not found_other_test_framework_param:
found_other_test_framework_param = arg
else:
other_test_framework_params.append(arg)
# Here we'll run either with nose or with the pydev_runfiles.
import pydev_runfiles
... | if hasattr(sys, '_current_frames') and hasattr(threading, 'enumerate'):
import time
import traceback
class DumpThreads(threading.Thread):
def run(self):
time.sleep(10)
thread_id_to_name = {}
try:
for t in threa... | import threading | random_line_split |
runfiles.py | dev_params.append(arg)
else:
if not found_other_test_framework_param:
found_other_test_framework_param = arg
else:
other_test_framework_params.append(arg)
# Here we'll run either with nose or with the pydev_runfiles.
import pydev_runfiles
im... |
curr_dir = os.path.realpath('.')
curr_dotted = dotted(curr_dir) + '.'
# Overcome limitation on py.test:
# When searching conftest if we have a structure as:
# /my_package
# /my_package/conftest.py
# /my_package/tests
# /m... | return os.path.normpath(p).replace(os.sep, "/").replace('/', '.') | identifier_body |
runfiles.py | dev_params.append(arg)
else:
if not found_other_test_framework_param:
found_other_test_framework_param = arg
else:
other_test_framework_params.append(arg)
# Here we'll run either with nose or with the pydev_runfiles.
import pydev_runfiles
im... | (self):
time.sleep(10)
thread_id_to_name = {}
try:
for t in threading.enumerate():
thread_id_to_name[t.ident] = '%s (daemon: %s)' % (t.name, t.daemon)
except:
| run | identifier_name |
linked_list.rs | use core::alloc::{GlobalAlloc, Layout};
use core::ptr::{self, NonNull};
use linked_list_allocator::Heap;
use spin::Mutex;
use crate::paging::{ActivePageTable, TableKind};
static HEAP: Mutex<Option<Heap>> = Mutex::new(None);
pub struct Allocator;
impl Allocator {
pub unsafe fn | (offset: usize, size: usize) {
*HEAP.lock() = Some(Heap::new(offset, size));
}
}
unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
while let Some(ref mut heap) = *HEAP.lock() {
match heap.allocate_first_fit(layout) {
Err(()) ... | init | identifier_name |
linked_list.rs | use core::alloc::{GlobalAlloc, Layout};
use core::ptr::{self, NonNull};
use linked_list_allocator::Heap;
use spin::Mutex;
use crate::paging::{ActivePageTable, TableKind};
static HEAP: Mutex<Option<Heap>> = Mutex::new(None);
pub struct Allocator;
impl Allocator {
pub unsafe fn init(offset: usize, size: usize) {
... | }
panic!("__rust_allocate: heap not initialized");
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if let Some(ref mut heap) = *HEAP.lock() {
heap.deallocate(NonNull::new_unchecked(ptr), layout)
} else {
panic!("__rust_deallocate: heap not init... | super::map_heap(&mut ActivePageTable::new(TableKind::Kernel), crate::KERNEL_HEAP_OFFSET + size, crate::KERNEL_HEAP_SIZE);
heap.extend(crate::KERNEL_HEAP_SIZE);
},
other => return other.ok().map_or(ptr::null_mut(), |allocation| allocation.as_ptr()),... | random_line_split |
linked_list.rs | use core::alloc::{GlobalAlloc, Layout};
use core::ptr::{self, NonNull};
use linked_list_allocator::Heap;
use spin::Mutex;
use crate::paging::{ActivePageTable, TableKind};
static HEAP: Mutex<Option<Heap>> = Mutex::new(None);
pub struct Allocator;
impl Allocator {
pub unsafe fn init(offset: usize, size: usize) {
... | ,
other => return other.ok().map_or(ptr::null_mut(), |allocation| allocation.as_ptr()),
}
}
panic!("__rust_allocate: heap not initialized");
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if let Some(ref mut heap) = *HEAP.lock() {
heap... | {
let size = heap.size();
super::map_heap(&mut ActivePageTable::new(TableKind::Kernel), crate::KERNEL_HEAP_OFFSET + size, crate::KERNEL_HEAP_SIZE);
heap.extend(crate::KERNEL_HEAP_SIZE);
} | conditional_block |
Codigo.py |
#Aqui resolveremos los puntos de la tarea
import time
import matplotlib.pyplot as plt
import numpy as np
from astropy import constants as const
from astropy import units as un
from scipy import integrate
#PRIMERA PARTE
#Cargamos los datos y definimos arreglos para la Longitud y el Flujo
Datos = np.loadtxt("s... |
FlujoSolar = Constantes*AreaS # las constantes por el area calculada (integral)
TSimpson= time.time() - TSimpson #Cerramos el contador
#Y ahora usamos el metodo de comparacion Quad de python
TCompSimpson=time.time() #iniciamos el contador
FlujoCom = integrate.quad(Integral, 0, np.pi/2)
FlujoCom = FlujoCom... | impson = (Paso/6.0)*((Integral(Intervalo[k])) + 4*Integral(Intervalo[k+1]) + Integral(Intervalo[k+2]))
AreaS += simpson
| conditional_block |
Codigo.py |
#Aqui resolveremos los puntos de la tarea
import time
import matplotlib.pyplot as plt
import numpy as np
from astropy import constants as const
from astropy import units as un
from scipy import integrate
#PRIMERA PARTE
#Cargamos los datos y definimos arreglos para la Longitud y el Flujo
Datos = np.loadtxt("s... | y): #Definimos el argumento de la integral como una funcion para simplificar los calculos
funcion = (np.tan(y)**3 + np.tan(y)**5) / ((np.exp(np.tan(y)))-1)
return funcion
#Ahora iteramos para integrar a los largo de los elementos [k] del intervalo evaluados en la funcion
for k in range(0, (Tamano-2)):
... | ntegral( | identifier_name |
Codigo.py |
#Aqui resolveremos los puntos de la tarea
import time
import matplotlib.pyplot as plt
import numpy as np
from astropy import constants as const
from astropy import units as un
from scipy import integrate
#PRIMERA PARTE
#Cargamos los datos y definimos arreglos para la Longitud y el Flujo
Datos = np.loadtxt("s... |
#Ahora iteramos para integrar a los largo de los elementos [k] del intervalo evaluados en la funcion
for k in range(0, (Tamano-2)):
simpson = (Paso/6.0)*((Integral(Intervalo[k])) + 4*Integral(Intervalo[k+1]) + Integral(Intervalo[k+2]))
AreaS += simpson
FlujoSolar = Constantes*AreaS # las constantes por... | uncion = (np.tan(y)**3 + np.tan(y)**5) / ((np.exp(np.tan(y)))-1)
return funcion
| identifier_body |
Codigo.py | #Aqui resolveremos los puntos de la tarea
import time
import matplotlib.pyplot as plt
import numpy as np
from astropy import constants as const
from astropy import units as un
from scipy import integrate
#PRIMERA PARTE
#Cargamos los datos y definimos arreglos para la Longitud y el Flujo
Datos = np.loadtxt("sun... | print TCompSimpson | random_line_split | |
login-form-dialog.component.ts | import { IUser } from './../../user.model';
import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef } from '@angular/material';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ValidationService } from '../../../shared/validation.service';
import { AuthS... | });
} else {
console.log('invalido');
}
}
}
| {
if (this.loginForm.valid) {
const values = this.loginForm.value;
console.log('Login user with values: ' + values);
this._authService.doLogin( {
email: values.email,
password: values.password
} as IUser).subscribe( result => {
if (result) {
console.log('... | identifier_body |
login-form-dialog.component.ts | import { IUser } from './../../user.model';
import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef } from '@angular/material';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ValidationService } from '../../../shared/validation.service';
import { AuthS... |
}
}
| {
console.log('invalido');
} | conditional_block |
login-form-dialog.component.ts | import { IUser } from './../../user.model';
import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef } from '@angular/material';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ValidationService } from '../../../shared/validation.service';
import { AuthS... |
} | }
} | random_line_split |
login-form-dialog.component.ts | import { IUser } from './../../user.model';
import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef } from '@angular/material';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ValidationService } from '../../../shared/validation.service';
import { AuthS... | implements OnInit {
loginForm: FormGroup;
constructor( public dialogRef: MdDialogRef<LoginFormDialogComponent>,
@Inject(FormBuilder) private formBuilder: FormBuilder,
private _validationService: ValidationService,
private _authService: AuthService) {}
ngOnInit(... | LoginFormDialogComponent | identifier_name |
boot-client.tsx | import './css/site.css';
import 'bootstrap';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
impor... | {
module.hot.accept('./routes', () => {
routes = require<typeof RoutesModule>('./routes').routes;
renderApp();
});
} | conditional_block | |
boot-client.tsx | import './css/site.css';
import 'bootstrap';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
impor... |
renderApp();
// Allow Hot Module Replacement
if (module.hot) {
module.hot.accept('./routes', () => {
routes = require<typeof RoutesModule>('./routes').routes;
renderApp();
});
}
| {
// This code starts up the React app when it runs in a browser. It sets up the routing configuration
// and injects the app into a DOM element.
ReactDOM.render(
<AppContainer>
<Provider store={ store }>
<ConnectedRouter history={ history } children={ routes } />
... | identifier_body |
boot-client.tsx | import './css/site.css';
import 'bootstrap';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
impor... | () {
// This code starts up the React app when it runs in a browser. It sets up the routing configuration
// and injects the app into a DOM element.
ReactDOM.render(
<AppContainer>
<Provider store={ store }>
<ConnectedRouter history={ history } children={ routes } /... | renderApp | identifier_name |
helloworld_el_GR.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.0">
<context>
<name>HelloWorld</name>
<message> | <source>Display Text Configuretion</source>
<translation>Εμφάνιση διαμόρφωσης κειμένου</translation>
</message>
<message>
<source>Edit HTML</source>
<translation>Επεξεργασία HTML</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<sou... | <source>Hello World:</source>
<translation>Γεια σου κόσμε:</translation>
</message>
<message> | random_line_split |
server.js | import path from 'path';
import express from 'express';
import https from 'https';
import fallback from 'express-history-api-fallback'
const webpack = require('webpack');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Addi... | }); | app.use(fallback(path.resolve(__dirname, '../public/index.html'))); // when requested route does not exist here in express app, return this file; for react.js route when using history.
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get(... | random_line_split |
server.js | import path from 'path';
import express from 'express';
import https from 'https';
import fallback from 'express-history-api-fallback'
const webpack = require('webpack');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Addi... |
// serve html regardless whether the middleware is enabled or not
app.use(express.static(path.resolve(__dirname, '../public/')));
app.use(fallback(path.resolve(__dirname, '../public/index.html'))); // when requested route does not exist here in express app, return this file; for react.js route when using history.
a... | {
console.log('in development, node only serve APIs, please make sure webpack dev server is running.');
} | conditional_block |
nounwind.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 ... | () {
nounwind::bar();
// CHECK: @foo() unnamed_addr #0
// CHECK: @bar() unnamed_addr #0
// CHECK: attributes #0 = { {{.*}}nounwind{{.*}} }
}
| foo | identifier_name |
nounwind.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 ... | {
nounwind::bar();
// CHECK: @foo() unnamed_addr #0
// CHECK: @bar() unnamed_addr #0
// CHECK: attributes #0 = { {{.*}}nounwind{{.*}} }
} | identifier_body | |
nounwind.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 ... | #[no_mangle]
pub fn foo() {
nounwind::bar();
// CHECK: @foo() unnamed_addr #0
// CHECK: @bar() unnamed_addr #0
// CHECK: attributes #0 = { {{.*}}nounwind{{.*}} }
} |
extern crate nounwind;
| random_line_split |
stream.tsx | /**
* Converts a stream query to an object representation, with
* keys representing tag names, and the magic __text key
* representing the text component of the search.
*
* Example:
*
* "python is:unresolved assigned:foo@bar.com"
* => {
* __text: "python",
* is: "unresolved",
* assigned: "foo@... | {
const {__text, ...tags} = queryObj;
const parts = Object.entries(tags).map(([tagKey, value]) => {
if (value.indexOf(' ') > -1) {
value = `"${value}"`;
}
return `${tagKey}:${value}`;
});
if (queryObj.__text) {
parts.push(queryObj.__text);
}
return parts.join(' ');
} | identifier_body | |
stream.tsx | /**
* Converts a stream query to an object representation, with
* keys representing tag names, and the magic __text key
* representing the text component of the search.
*
* Example:
*
* "python is:unresolved assigned:foo@bar.com"
* => {
* __text: "python",
* is: "unresolved",
* assigned: "foo@... | (queryStr = ''): QueryObj {
const text: string[] = [];
const queryItems = queryStr.match(/\S+:"[^"]*"?|\S+/g);
const queryObj: QueryObj = (queryItems || []).reduce((obj, item) => {
const index = item.indexOf(':');
if (index === -1) {
text.push(item);
} else {
const tagKey = item.slice(0, ... | queryToObj | identifier_name |
stream.tsx | /**
* Converts a stream query to an object representation, with
* keys representing tag names, and the magic __text key
* representing the text component of the search.
*
* Example:
*
* "python is:unresolved assigned:foo@bar.com"
* => {
* __text: "python",
* is: "unresolved",
* assigned: "foo@... |
return `${tagKey}:${value}`;
});
if (queryObj.__text) {
parts.push(queryObj.__text);
}
return parts.join(' ');
}
| {
value = `"${value}"`;
} | conditional_block |
stream.tsx | /**
* Converts a stream query to an object representation, with
* keys representing tag names, and the magic __text key
* representing the text component of the search.
*
* Example:
*
* "python is:unresolved assigned:foo@bar.com"
* => {
* __text: "python",
* is: "unresolved",
* assigned: "foo@... | } | if (queryObj.__text) {
parts.push(queryObj.__text);
}
return parts.join(' '); | random_line_split |
index_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::Index;
use core::ops::IndexMut;
struct Pixel<T> {
r: T,
g: T,
b: T
}
impl Index<usize> for Pixel<T> {
type Output = T;
fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
match index {
0 => &self.... | pixel[2] = 0x58;
assert_eq!(pixel[0], 0x01);
assert_eq!(pixel[1], 0x98);
assert_eq!(pixel[2], 0x58);
assert_eq!(pixel[3], 0x58);
}
} | random_line_split | |
index_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::Index;
use core::ops::IndexMut;
struct Pixel<T> {
r: T,
g: T,
b: T
}
impl Index<usize> for Pixel<T> {
type Output = T;
fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
match index {
0 => &self.... | <'a>(&'a mut self, index: usize) -> &'a mut Self::Output {
match index {
0 => &mut self.r,
1 => &mut self.g,
2 | _ => &mut self.b
}
}
}
type T = u8;
#[test]
fn index_test1() {
let mut pixel: Pixel<T> = Pixel { r: 0xff, g: 0x92, b: 0x24 };
pixel[0] = 0x01;
pixel[1] = 0x98;
... | index_mut | identifier_name |
app-details.po.ts | import { browser, by, element } from 'protractor';
/**
* E2E Page Object for app details page.
*
* @author Damien Vitrac
*/
export class AppDetailsPage {
/**
* Navigates to the app details page.
* @returns {wdpromise.Promise<any>}
*/
| (type, name) {
return browser.get(`#/apps/${type}/${name}`);
}
/**
* Retrieves text of the title.
* @returns {any}
*/
getHeaderText() {
return element(by.css('.heading h1')).getText();
}
/**
* Retrieves text of the app details info.
* @returns {any}
*/
getInfo() {
return elem... | navigateTo | identifier_name |
app-details.po.ts | import { browser, by, element } from 'protractor';
/**
* E2E Page Object for app details page.
*
* @author Damien Vitrac
*/
export class AppDetailsPage {
/**
* Navigates to the app details page.
* @returns {wdpromise.Promise<any>}
*/
navigateTo(type, name) {
return browser.get(`#/apps/${type}/${n... |
/**
* Retrieves text of the app details info.
* @returns {any}
*/
getInfo() {
return element(by.css('.app-details-info')).getText();
}
/**
* Retrieves properties of the app details info.
* @returns {any}
*/
getProperties() {
return element.all(by.css('#table-properties tbody tr'));... | return element(by.css('.heading h1')).getText();
} | random_line_split |
app-details.po.ts | import { browser, by, element } from 'protractor';
/**
* E2E Page Object for app details page.
*
* @author Damien Vitrac
*/
export class AppDetailsPage {
/**
* Navigates to the app details page.
* @returns {wdpromise.Promise<any>}
*/
navigateTo(type, name) {
return browser.get(`#/apps/${type}/${n... |
/**
* Retrieves properties of the app details info.
* @returns {any}
*/
getProperties() {
return element.all(by.css('#table-properties tbody tr'));
}
/**
* Click on cancel button.
* @returns {any}
*/
getCancel() {
return element(by.css('#back-button'));
}
}
| {
return element(by.css('.app-details-info')).getText();
} | identifier_body |
shell.py | import time
import traceback
SHELL_CONTROL_SEQUENCES = {
'BLUE': '\033[34m',
'LTBLUE': '\033[94m',
'GREEN': '\033[32m',
'LTGREEN': '\033[92m',
'YELLOW': '\033[33m',
'LTYELLOW': '\033[93m',
'RED': '\033[31m',
'LTRED': '\033[91m',
'CYAN': '\033[36m',
'LTCYAN': '\033[96m',
'MA... | (color, *output, **kwargs):
"""Prints a section title header"""
output = ["\n\n", 60 * "#", "\n", "# "] + list(output) + ["\n", 60 * "#", "\n"]
print_color(color, *output, end="\n", **kwargs)
def print_table(headers, *table_data, **kwargs):
if not table_data:
return
if isinstance(table_da... | print_section | identifier_name |
shell.py |
import time
import traceback
SHELL_CONTROL_SEQUENCES = {
'BLUE': '\033[34m',
'LTBLUE': '\033[94m',
'GREEN': '\033[32m',
'LTGREEN': '\033[92m',
'YELLOW': '\033[33m',
'LTYELLOW': '\033[93m',
'RED': '\033[31m',
'LTRED': '\033[91m',
'CYAN': '\033[36m',
'LTCYAN': '\033[96m',
'M... |
def ask(*args, **kwargs):
"""Ask for input"""
if not sys.stdin.isatty():
error("Cannot ask user for input, no tty exists")
sys.exit(1)
print_args = list(args)
print_args.append(kwargs.get("end", "\n"))
if kwargs["color"]:
print_args.insert(0, "{" + kwargs["color"] + "}")
... | return choices[int(output)] | conditional_block |
shell.py | import time
import traceback
SHELL_CONTROL_SEQUENCES = {
'BLUE': '\033[34m',
'LTBLUE': '\033[94m',
'GREEN': '\033[32m',
'LTGREEN': '\033[92m',
'YELLOW': '\033[33m',
'LTYELLOW': '\033[93m',
'RED': '\033[31m',
'LTRED': '\033[91m',
'CYAN': '\033[36m',
'LTCYAN': '\033[96m',
'MA... |
def elapsed_decorator(output):
"""Decorator that prints to stderr how long a process took"""
def wrapper(fn):
def wrapped_fn(*args, **kwargs):
with elapsed(output, **kwargs):
fn(*args, **kwargs)
return wrapped_fn
return wrapper
def print_section(color, *outpu... | """Context Manager that prints to stderr how long a process took"""
start = timestamp()
info("Starting: ", output, **kwargs)
yield
info("Completed: " + output + " {MAGENTA}(Elapsed Time: {elapsed}s){ENDC}", elapsed=timestamp()-start, **kwargs) | identifier_body |
shell.py | 033[32m',
'LTGREEN': '\033[92m',
'YELLOW': '\033[33m',
'LTYELLOW': '\033[93m',
'RED': '\033[31m',
'LTRED': '\033[91m',
'CYAN': '\033[36m',
'LTCYAN': '\033[96m',
'MAGENTA': '\033[35m',
'LTMAGENTA': '\033[95m',
'ENDC': '\033[0m',
'BOLD': '\033[1m',
'UNDERLINE': '\033[4m',
}... | random_line_split | ||
apkbuilder.py | ksigner-jar', help='Path to the apksigner executable.')
parser.add_argument('--zipalign-path',
help='Path to the zipalign executable.')
parser.add_argument('--key-path',
help='Path to keystore for signing.')
parser.add_argument('--key-passwd',
help... |
def main(args):
build_utils.InitLogging('APKBUILDER_DEBUG')
args = build_utils.ExpandFileArgs(args)
options = _ParseArgs(args)
# Until Python 3.7, there's no better way to set compression level.
# The default is 6.
if options.best_compression:
# Compresses about twice as slow as the default.
zli... | """Creates list of native libraries and assets."""
native_libs = sorted(native_libs)
assets = sorted(assets)
ret = []
for apk_path, _, compress, alignment in native_libs + assets:
ret.append('apk_path=%s, compress=%s, alignment=%s\n' %
(apk_path, compress, alignment))
return ''.join(ret) | identifier_body |
apkbuilder.py | GnList(options.java_resources)
options.native_libs = build_utils.ParseGnList(options.native_libs)
options.secondary_native_libs = build_utils.ParseGnList(
options.secondary_native_libs)
options.library_always_compress = build_utils.ParseGnList(
options.library_always_compress)
options.library_rename... | # <other-file> -> root/<other-file>
#
# Hence, the following variables are used to control the location of files in
# the final archive.
if options.format == 'bundle-module': | random_line_split | |
apkbuilder.py | (args):
parser = argparse.ArgumentParser()
build_utils.AddDepfileOption(parser)
parser.add_argument(
'--assets',
help='GYP-list of files to add as assets in the form '
'"srcPath:zipPath", where ":zipPath" is optional.')
parser.add_argument(
'--java-resources', help='GYP-list of java_reso... | _ParseArgs | identifier_name | |
apkbuilder.py | UILDER_DEBUG')
args = build_utils.ExpandFileArgs(args)
options = _ParseArgs(args)
# Until Python 3.7, there's no better way to set compression level.
# The default is 6.
if options.best_compression:
# Compresses about twice as slow as the default.
zlib.Z_DEFAULT_COMPRESSION = 9
else:
# Compress... | continue | conditional_block | |
pagerank.rs | // extern crate rand;
// extern crate time;
// extern crate columnar;
// extern crate timely;
// extern crate differential_dataflow;
//
// use std::mem;
//
// use std::hash::Hash;
// use timely::example_shared::*;
// use timely::example_shared::operators::*;
// use timely::communication::ThreadCommunicator;
//
// use r... | //
// // let mut sent = 0;
// // let mut buffer = Vec::new();
// // let mut offset = nodes.read_u64::<LittleEndian>().unwrap();
// // assert!(offset == 0);
// // for node in (0..60000000) {
// // let read = nodes.read_u64::<LittleEndian>().unwr... | {
//
// let start = time::precise_time_s();
// let start2 = start.clone();
// let mut computation = GraphRoot::new(ThreadCommunicator);
//
// let mut input = computation.subcomputation(|builder| {
//
// let (input, mut edges) = builder.new_input();
//
// ... | identifier_body |
pagerank.rs | // extern crate rand;
// extern crate time;
// extern crate columnar;
// extern crate timely;
// extern crate differential_dataflow;
//
// use std::mem;
//
// use std::hash::Hash;
// use timely::example_shared::*;
// use timely::example_shared::operators::*;
// use timely::communication::ThreadCommunicator;
//
// use r... | // input.send_at(0, (0..next).map(|_| ((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)), 1)));
// computation.step();
// left -= next;
// }
//
// println!("input ingested after {}", time::precise_time_s() - start);
// //
// ... | //
// let mut left = edges;
// while left > 0 {
// let next = if left < 1000 { left } else { 1000 }; | random_line_split |
pagerank.rs | // extern crate rand;
// extern crate time;
// extern crate columnar;
// extern crate timely;
// extern crate differential_dataflow;
//
// use std::mem;
//
// use std::hash::Hash;
// use timely::example_shared::*;
// use timely::example_shared::operators::*;
// use timely::communication::ThreadCommunicator;
//
// use r... | () {
//
// let start = time::precise_time_s();
// let start2 = start.clone();
// let mut computation = GraphRoot::new(ThreadCommunicator);
//
// let mut input = computation.subcomputation(|builder| {
//
// let (input, mut edges) = builder.new_input();
//
/... | main | identifier_name |
toolStrips.js | isc.Menu.create({
ID: "menu",
autoDraw: false,
showShadow: true,
shadowDepth: 10,
data: [
{title: "New", keyTitle: "Ctrl+N", icon: "icons/16/document_plain_new.png"},
{title: "Open", keyTitle: "Ctrl+O", icon: "icons/16/folder_out.png"},
{isSeparator: true},
{title: "S... | actionType: "radio",
radioGroup: "textAlign"
});
isc.ToolStripButton.create({
ID: "alignRight",
icon: "[SKIN]/RichTextEditor/text_align_right.png",
actionType: "radio",
radioGroup: "textAlign"
});
isc.ToolStripButton.create({
ID: "alignCenter",
icon: "[SKIN]/RichTextEditor/text_al... | random_line_split | |
audio_settings_page.py | import fsui
from fswidgets.widget import Widget
from launcher.i18n import gettext
from launcher.option import Option
from launcher.settings.settings_page import SettingsPage
from system.prefs.components.notworking import PrefsNotWorkingWarningPanel
class AudioSettingsPage(SettingsPage):
| self.add_option("audio_frequency")
self.add_option("audio_buffer_target_size")
| def __init__(self, parent: Widget) -> None:
super().__init__(parent)
PrefsNotWorkingWarningPanel(parent=self)
self.layout.add_spacer(20)
icon = fsui.Icon("audio-settings", "pkg:workspace")
gettext("Audio Settings")
title = gettext("Audio")
subtitle = ""
... | identifier_body |
audio_settings_page.py | import fsui
from fswidgets.widget import Widget
from launcher.i18n import gettext
from launcher.option import Option
from launcher.settings.settings_page import SettingsPage
from system.prefs.components.notworking import PrefsNotWorkingWarningPanel
class AudioSettingsPage(SettingsPage):
def | (self, parent: Widget) -> None:
super().__init__(parent)
PrefsNotWorkingWarningPanel(parent=self)
self.layout.add_spacer(20)
icon = fsui.Icon("audio-settings", "pkg:workspace")
gettext("Audio Settings")
title = gettext("Audio")
subtitle = ""
self.add_hea... | __init__ | identifier_name |
audio_settings_page.py | import fsui
from fswidgets.widget import Widget
from launcher.i18n import gettext
from launcher.option import Option
from launcher.settings.settings_page import SettingsPage
from system.prefs.components.notworking import PrefsNotWorkingWarningPanel
class AudioSettingsPage(SettingsPage):
def __init__(self, parent:... | gettext("Audio Settings")
title = gettext("Audio")
subtitle = ""
self.add_header(icon, title, subtitle)
self.add_option("volume")
self.add_option("stereo_separation")
self.add_section(gettext("Floppy Drive Sound Emulation"))
self.add_option("floppy_drive... | icon = fsui.Icon("audio-settings", "pkg:workspace") | random_line_split |
io.rs | //! SOLID-specific extensions to general I/O primitives
#![deny(unsafe_op_in_unsafe_fn)]
#![unstable(feature = "solid_ext", issue = "none")]
use crate::net;
use crate::sys;
use crate::sys_common::{self, AsInner, FromInner, IntoInner};
/// Raw file descriptors.
pub type RawFd = i32;
/// A trait to extract the raw SO... |
}
#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
impl FromRawFd for RawFd {
#[inline]
unsafe fn from_raw_fd(fd: RawFd) -> RawFd {
fd
}
}
macro_rules! impl_as_raw_fd {
($($t:ident)*) => {$(
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::$t ... | {
self
} | identifier_body |
io.rs | //! SOLID-specific extensions to general I/O primitives
#![deny(unsafe_op_in_unsafe_fn)]
#![unstable(feature = "solid_ext", issue = "none")]
use crate::net;
use crate::sys;
use crate::sys_common::{self, AsInner, FromInner, IntoInner};
/// Raw file descriptors.
pub type RawFd = i32;
/// A trait to extract the raw SO... | }
}
#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
impl FromRawFd for RawFd {
#[inline]
unsafe fn from_raw_fd(fd: RawFd) -> RawFd {
fd
}
}
macro_rules! impl_as_raw_fd {
($($t:ident)*) => {$(
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net... | impl IntoRawFd for RawFd {
#[inline]
fn into_raw_fd(self) -> RawFd {
self | random_line_split |
io.rs | //! SOLID-specific extensions to general I/O primitives
#![deny(unsafe_op_in_unsafe_fn)]
#![unstable(feature = "solid_ext", issue = "none")]
use crate::net;
use crate::sys;
use crate::sys_common::{self, AsInner, FromInner, IntoInner};
/// Raw file descriptors.
pub type RawFd = i32;
/// A trait to extract the raw SO... | (&self) -> RawFd {
*self
}
}
#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
impl IntoRawFd for RawFd {
#[inline]
fn into_raw_fd(self) -> RawFd {
self
}
}
#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
impl FromRawFd for RawFd {
#[inline]
unsafe... | as_raw_fd | identifier_name |
app.ts | import "reflect-metadata"; |
const options: ConnectionOptions = {
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "admin",
database: "test",
logging: ["query", "error"],
synchronize: true,
entities: [EverythingEntity]
};
createConnection(options).then(connection => {
let entity =... | import {ConnectionOptions, createConnection} from "../../src/index";
import {EverythingEntity, SampleEnum} from "./entity/EverythingEntity"; | random_line_split |
gestalt-tests.tsx | import {
Avatar,
AvatarPair,
Badge,
Box,
Button,
ButtonGroup,
Callout,
Card,
Checkbox,
Collage,
Column,
Container,
Divider, | Icon,
IconButton,
Image,
Label,
Layer,
Letterbox,
Link,
Mask,
Masonry,
Modal,
Pog,
Provider,
Pulsar,
RadioButton,
Row,
SearchField,
SegmentedControl,
SelectList,
Spinner,
Stack,
Sticky,
Switch,
Table,
Tabs,
TapArea,
... | Flyout,
GroupAvatar,
Heading, | random_line_split |
index.rs | extern crate iron;
extern crate staticfile;
extern crate mount;
use iron::{status, Iron, Request, Response, IronResult, IronError};
use iron::mime::Mime;
use staticfile::Static;
use mount::Mount;
use std::process::{Command, Output};
use std::error::Error;
#[derive(Debug)]
struct ServerError(String);
impl ::std::fmt... | {
let mut root = Mount::new();
root.mount("/", Static::new("../"))
.mount("/server", serve);
Iron::new(root).http("localhost:8081").unwrap();
} | identifier_body | |
index.rs | extern crate iron;
extern crate staticfile;
extern crate mount;
use iron::{status, Iron, Request, Response, IronResult, IronError};
use iron::mime::Mime;
use staticfile::Static;
use mount::Mount;
use std::process::{Command, Output};
use std::error::Error;
#[derive(Debug)]
struct ServerError(String);
impl ::std::fmt... | (s: &'static str) -> ServerError { ServerError(s.to_owned()) }
}
fn serve(req: &mut Request) -> IronResult<Response> {
match req.url.query {
Some(ref param) if param.starts_with("module=") => {
let module = ¶m[7..];
match Command::new(format!("modules/shell_files/{}.sh", module)... | from | identifier_name |
index.rs | extern crate iron;
extern crate staticfile;
extern crate mount;
use iron::{status, Iron, Request, Response, IronResult, IronError};
use iron::mime::Mime;
use staticfile::Static;
use mount::Mount;
use std::process::{Command, Output};
use std::error::Error;
#[derive(Debug)]
struct ServerError(String);
impl ::std::fmt... | }
fn serve(req: &mut Request) -> IronResult<Response> {
match req.url.query {
Some(ref param) if param.starts_with("module=") => {
let module = ¶m[7..];
match Command::new(format!("modules/shell_files/{}.sh", module)).output() {
Ok(Output { stdout, .. }) => Ok(Re... | fn from(s: &'static str) -> ServerError { ServerError(s.to_owned()) } | random_line_split |
ChannelGuide.js | import {bind, wire} from 'hyperhtml';
import config from '../../../config.json';
/**
* The HyperHTML view displaying the channel guide.
*/
export default class | {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Array<Object>} [programs=null] - The array containing program data POJOs
*/
constructor(element, programs = null) {
this.element = element;
this.programs = programs;... | ChannelGuide | identifier_name |
ChannelGuide.js | import {bind, wire} from 'hyperhtml';
import config from '../../../config.json';
/**
* The HyperHTML view displaying the channel guide.
*/
export default class ChannelGuide {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Arr... | * Source: https://github.com/GoogleChromeLabs/web-push-codelab/blob/master/app/scripts/main.js
*
* @param {String} base64String - The Base64 encoded string
* @return {Uint8Array} The converted array in unsigned 8-bit integer
*/
static urlB64ToUint8Array(base64String) {
const padding = '='.repeat(... | * | random_line_split |
ChannelGuide.js | import {bind, wire} from 'hyperhtml';
import config from '../../../config.json';
/**
* The HyperHTML view displaying the channel guide.
*/
export default class ChannelGuide {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Arr... |
/**
* Creates a CTA for the element. In case the video is directly available,
* show it. Otherwise create a an element to notify when it is available
*
* @param {Object} program - The POJO containing program details
* @return {HTMLElement} element created by hyperHTML (a link or empty text)
*/
c... | {
// Update the handle to support PUSH or not
this.supportsPUSH = 'serviceWorker' in navigator && 'PushManager' in window
&& swRegistration && typeof swRegistration.pushManager === 'object';
this.swRegistration = swRegistration;
console.log('Registering worker for channel guide', this.supportsPUS... | identifier_body |
ChannelGuide.js | import {bind, wire} from 'hyperhtml';
import config from '../../../config.json';
/**
* The HyperHTML view displaying the channel guide.
*/
export default class ChannelGuide {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Arr... |
// Else create no action (empty string)
return wire()``;
}
/**
* A helper to transform Base64 encoded string into a Uint8Array.
*
* Source: https://github.com/GoogleChromeLabs/web-push-codelab/blob/master/app/scripts/main.js
*
* @param {String} base64String - The Base64 encoded string
*... | {
const element = wire()`
<button class="mdc-button mdc-button--raised mdc-card__action">Tilaa</button>
`;
element.onclick = (event) => this.registerForProgram(event, program);
return element;
} | conditional_block |
AvahiBroadcaster.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import dbus
import avahi
import socket
from folavirt.networking.NetworkInterface import NetworkInterface
"""
Klasa służy do rozgłąszania czegoś poprzez Avahi
"""
class AvahiBroadcaster():
def __init__(self, name, avahiname, avahiport):
self._service_name = n... | raw_server = self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER)
self.server = dbus.Interface(raw_server, avahi.DBUS_INTERFACE_SERVER)
self.group = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP)
"""
... | random_line_split | |
AvahiBroadcaster.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import dbus
import avahi
import socket
from folavirt.networking.NetworkInterface import NetworkInterface
"""
Klasa służy do rozgłąszania czegoś poprzez Avahi
"""
class AvahiBroadcaster():
def __init__(self, name, avahiname, avahiport):
self._service_name = n... |
def unpublish(self):
self.group.Reset() | group.AddService(
NetworkInterface().getIndex(),
avahi.PROTO_INET,
0,
self._service_name,
self.avahiname,
'',
... | identifier_body |
AvahiBroadcaster.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import dbus
import avahi
import socket
from folavirt.networking.NetworkInterface import NetworkInterface
"""
Klasa służy do rozgłąszania czegoś poprzez Avahi
"""
class AvahiBroadcaster():
def __init__(self, name, avahiname, avahiport):
self._service_name = n... | ):
self.group.Reset() | lish(self | identifier_name |
toc.js | IfMicro.toc = {
tocEffect: function () {
if (window.innerWidth < 460) return ;
var menu = $("<div class='menu' title='点击展开/收起,Shift+Z 隐藏或打开'>目录</div>");
var toc = $("ul#markdown-toc");
//wrap toc into div which class is 'tocWrap'
toc.wrap('<div class="tocWrap">');
//set mouseenter and mouseo... | curH = windowH*percent;
$tocNode.animate({height: curH});
}
else {
$tocNode.animate({height: originH});
}
})
}// end markdwon-toc size
}
}
| odeStr);
var originH = $tocNode[0].offsetHeight;
var curH = originH;
var windowH = window.innerHeight;
var cssH = $tocNode.css('height');
if(originH > windowH*percent) {
curH = windowH*percent;
$tocNode.animate({height: curH});
}
$(window).resizeend({
... | conditional_block |
toc.js | IfMicro.toc = {
tocEffect: function () {
if (window.innerWidth < 460) return ;
var menu = $("<div class='menu' title='点击展开/收起,Shift+Z 隐藏或打开'>目录</div>");
var toc = $("ul#markdown-toc");
//wrap toc into div which class is 'tocWrap'
toc.wrap('<div class="tocWrap">');
//set mouseenter and mouseo... | }// end markdwon-toc size
}
} | random_line_split | |
diff.rs | use ansi_term::{ANSIStrings, Style};
use ansi_term::Colour::{Green, Red};
use config::use_ansi;
use diff;
use std::borrow::Borrow;
use std::cmp::max;
use std::fmt::{Debug, Write};
use unicode_width::UnicodeWidthStr;
/// Can be diffed
pub trait Diffable<T: ?Sized>: PartialEq<T> {
fn diff(&self, to: &T) -> S... | <A: ?Sized + Diffable<To>, To: ?Sized>() {}
_assert::<str, str>();
_assert::<String, str>();
_assert::<Vec<u8>, Vec<u8>>();
_assert::<Vec<u8>, Vec<u8>>();
_assert::<[u8; 4], [u8; 4]>();
_assert::<Vec<&str>, Vec<&str>>();
} | _assert | identifier_name |
diff.rs | use ansi_term::{ANSIStrings, Style};
use ansi_term::Colour::{Green, Red};
use config::use_ansi;
use diff;
use std::borrow::Borrow;
use std::cmp::max;
use std::fmt::{Debug, Write};
use unicode_width::UnicodeWidthStr;
/// Can be diffed
pub trait Diffable<T: ?Sized>: PartialEq<T> {
fn diff(&self, to: &T) -> S... | }
buf
}
impl Diffable<str> for str {
fn diff(&self, to: &str) -> String {
diff_str(self, to)
}
}
impl Diffable<str> for String {
fn diff(&self, to: &str) -> String {
diff_str(self, to)
}
}
impl<'a, 'b> Diffable<&'b str> for &'a str {
fn diff(&self, to: &&str) -> String {
diff_str(s... | }
| random_line_split |
diff.rs | use ansi_term::{ANSIStrings, Style};
use ansi_term::Colour::{Green, Red};
use config::use_ansi;
use diff;
use std::borrow::Borrow;
use std::cmp::max;
use std::fmt::{Debug, Write};
use unicode_width::UnicodeWidthStr;
/// Can be diffed
pub trait Diffable<T: ?Sized>: PartialEq<T> {
fn diff(&self, to: &T) -> S... |
diff::Result::Both(..) => i += 1,
diff::Result::Right(r) => {
right_diffs.push((i, r));
i += 1;
}
}
}
let mut lmax = 3;
let mut rmax = 8;
let mut buf = String::new();
for (&(_, l), &(_, r)) in left_diffs.as_slice().iter().zip(right_diffs.as_slice().iter()) {
write!(buf, "{:?... | {
left_diffs.push((i, l));
} | conditional_block |
diff.rs | use ansi_term::{ANSIStrings, Style};
use ansi_term::Colour::{Green, Red};
use config::use_ansi;
use diff;
use std::borrow::Borrow;
use std::cmp::max;
use std::fmt::{Debug, Write};
use unicode_width::UnicodeWidthStr;
/// Can be diffed
pub trait Diffable<T: ?Sized>: PartialEq<T> {
fn diff(&self, to: &T) -> S... |
}
lazy_static!{
static ref DIFF_LEFT: Style = {
if use_ansi() {
Style::new().fg(Red)
} else {
Style::new()
}
};
static ref DIFF_RIGHT: Style = {
if use_ansi() {
Style::new().fg(Green)
} else {
Style:... | {
diff_str(self, to)
} | identifier_body |
files.py | import mapper
from addon.routes import my_library
from addon.routes import actions
from addon.routes import generic
MPR = mapper.Mapper.get()
@MPR.s_url('/track/<track_id>/')
@MPR.s_url('/track/<track_id>/<title>/')
def track(track_id, title=''):
actions.play_track(track_id, track_title=title)
@MPR.s_url('/a... | (album_id):
generic.album(album_id)
@MPR.s_url('/playlist/')
def playlist(playlist_id=None, playlist_token=None):
if playlist_id:
my_library.my_library_playlist(playlist_id)
elif playlist_token:
generic.listen_now_shared_playlist(playlist_token)
@MPR.s_url('/station/')
def station(stati... | album | identifier_name |
files.py | import mapper
from addon.routes import my_library
from addon.routes import actions
from addon.routes import generic
MPR = mapper.Mapper.get()
@MPR.s_url('/track/<track_id>/')
@MPR.s_url('/track/<track_id>/<title>/')
def track(track_id, title=''):
actions.play_track(track_id, track_title=title)
@MPR.s_url('/a... |
@MPR.s_url('/station/')
def station(station_id=None, station_name=None, artist_id=None, album_id=None,
genre_id=None, track_id=None, curated_station_id=None,
playlist_token=None):
generic.station(station_id, station_name, artist_id, album_id,
track_id, genre_id, curat... | if playlist_id:
my_library.my_library_playlist(playlist_id)
elif playlist_token:
generic.listen_now_shared_playlist(playlist_token) | identifier_body |
files.py | import mapper
from addon.routes import my_library
from addon.routes import actions
from addon.routes import generic
MPR = mapper.Mapper.get()
@MPR.s_url('/track/<track_id>/')
@MPR.s_url('/track/<track_id>/<title>/')
def track(track_id, title=''):
actions.play_track(track_id, track_title=title)
@MPR.s_url('/a... | def playlist(playlist_id=None, playlist_token=None):
if playlist_id:
my_library.my_library_playlist(playlist_id)
elif playlist_token:
generic.listen_now_shared_playlist(playlist_token)
@MPR.s_url('/station/')
def station(station_id=None, station_name=None, artist_id=None, album_id=None,
... | @MPR.s_url('/playlist/') | random_line_split |
files.py | import mapper
from addon.routes import my_library
from addon.routes import actions
from addon.routes import generic
MPR = mapper.Mapper.get()
@MPR.s_url('/track/<track_id>/')
@MPR.s_url('/track/<track_id>/<title>/')
def track(track_id, title=''):
actions.play_track(track_id, track_title=title)
@MPR.s_url('/a... |
elif playlist_token:
generic.listen_now_shared_playlist(playlist_token)
@MPR.s_url('/station/')
def station(station_id=None, station_name=None, artist_id=None, album_id=None,
genre_id=None, track_id=None, curated_station_id=None,
playlist_token=None):
generic.station(station... | my_library.my_library_playlist(playlist_id) | conditional_block |
main.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 ... | {
task::try(proc() {
let _a = A;
lib::callback(|| fail!());
1i
});
unsafe {
assert!(lib::statik == 1);
assert!(statik == 1);
}
} | identifier_body | |
main.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate lib;
use std::task;
static mut statik: int = 0;
struct A;
impl Drop for ... | // 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 | random_line_split |
main.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 ... | (&mut self) {
unsafe { statik = 1; }
}
}
fn main() {
task::try(proc() {
let _a = A;
lib::callback(|| fail!());
1i
});
unsafe {
assert!(lib::statik == 1);
assert!(statik == 1);
}
}
| drop | identifier_name |
switch_file.py | import sublime, sublime_plugin
import os.path
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
return x == y
class SwitchFileCommand(sublime_plugin.WindowCommand):
def run(self, extensions=... |
if ext != "":
ext = ext[1:]
for i in range(0, len(extensions)):
if compare_file_names(extensions[i], ext):
start = i + 1
count -= 1
break
for i in range(0, count):
idx = (start + i) % len(e... | count = len(extensions) | random_line_split |
switch_file.py | import sublime, sublime_plugin
import os.path
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
return x == y
class | (sublime_plugin.WindowCommand):
def run(self, extensions=[]):
if not self.window.active_view():
return
fname = self.window.active_view().file_name()
if not fname:
return
path = os.path.dirname(fname)
base, ext = os.path.splitext(fname)
start... | SwitchFileCommand | identifier_name |
switch_file.py | import sublime, sublime_plugin
import os.path
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
return x == y
class SwitchFileCommand(sublime_plugin.WindowCommand):
def run(self, extensions=... | break
for i in range(0, count):
idx = (start + i) % len(extensions)
new_path = base + '.' + extensions[idx]
if os.path.exists(new_path):
self.window.open_file(new_path)
break
| if not self.window.active_view():
return
fname = self.window.active_view().file_name()
if not fname:
return
path = os.path.dirname(fname)
base, ext = os.path.splitext(fname)
start = 0
count = len(extensions)
if ext != "":
ex... | identifier_body |
switch_file.py | import sublime, sublime_plugin
import os.path
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
|
class SwitchFileCommand(sublime_plugin.WindowCommand):
def run(self, extensions=[]):
if not self.window.active_view():
return
fname = self.window.active_view().file_name()
if not fname:
return
path = os.path.dirname(fname)
base, ext = os.path.split... | return x == y | conditional_block |
12.9-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... | () {
var sum = 0;
(function innerTest() {
for (var i = 1; i <= 10; i++) {
if (i === 6) {
return
;
}
sum += i;
}
})();
return sum === 15;
}
runTestCase(testcase... | testcase | identifier_name |
12.9-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... |
runTestCase(testcase);
| {
var sum = 0;
(function innerTest() {
for (var i = 1; i <= 10; i++) {
if (i === 6) {
return
;
}
sum += i;
}
})();
return sum === 15;
} | identifier_body |
12.9-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... | if (i === 6) {
return
;
}
sum += i;
}
})();
return sum === 15;
}
runTestCase(testcase); |
function testcase() {
var sum = 0;
(function innerTest() {
for (var i = 1; i <= 10; i++) {
| random_line_split |
12.9-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... |
})();
return sum === 15;
}
runTestCase(testcase);
| {
if (i === 6) {
return
;
}
sum += i;
} | conditional_block |
__init__.py | #
# Copyright 2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | #
from __future__ import absolute_import
from __future__ import division | # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license | random_line_split |
shared_styles_host.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 {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {getDO... | (hostNode: Node): void { this._hostNodes.delete(hostNode); }
onStylesAdded(additions: Set<string>): void {
this._hostNodes.forEach(hostNode => this._addStylesToHost(additions, hostNode));
}
ngOnDestroy(): void { this._styleNodes.forEach(styleNode => getDOM().remove(styleNode)); }
}
| removeHost | identifier_name |
shared_styles_host.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 {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {getDO... |
}
| { this._styleNodes.forEach(styleNode => getDOM().remove(styleNode)); } | identifier_body |
shared_styles_host.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 {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {getDO... |
});
this.onStylesAdded(additions);
}
onStylesAdded(additions: Set<string>): void {}
getAllStyles(): string[] { return Array.from(this._stylesSet); }
}
@Injectable()
export class DomSharedStylesHost extends SharedStylesHost implements OnDestroy {
private _hostNodes = new Set<Node>();
private _style... | {
this._stylesSet.add(style);
additions.add(style);
} | conditional_block |
shared_styles_host.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 {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {getDO... | styleEl.textContent = style;
this._styleNodes.add(host.appendChild(styleEl));
});
}
addHost(hostNode: Node): void {
this._addStylesToHost(this._stylesSet, hostNode);
this._hostNodes.add(hostNode);
}
removeHost(hostNode: Node): void { this._hostNodes.delete(hostNode); }
onStylesAdded... | random_line_split | |
layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# --------------------------------------------------------
# R*CNN
# Wri... | (self, roidb):
"""Set the roidb to be used by this layer during training."""
self._roidb = roidb
self._shuffle_roidb_inds()
if cfg.TRAIN.USE_PREFETCH:
self._blob_queue = Queue(10)
self._prefetch_process = BlobFetcher(self._blob_queue,
... | set_roidb | identifier_name |
layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# --------------------------------------------------------
# R*CNN
# Wri... |
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
def _get_next_minibatch(self):
"""Return the blobs to be used for the next minibatch.
If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in ... | self._shuffle_roidb_inds() | conditional_block |
layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# --------------------------------------------------------
# R*CNN
# Wri... |
def _shuffle_roidb_inds(self):
"""Randomly permute the training roidb."""
# TODO(rbg): remove duplicated code
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next mini... | super(BlobFetcher, self).__init__()
self._queue = queue
self._roidb = roidb
self._num_classes = num_classes
self._perm = None
self._cur = 0
self._shuffle_roidb_inds()
# fix the random seed for reproducibility
np.random.seed(cfg.RNG_SEED) | identifier_body |
layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# --------------------------------------------------------
# R*CNN
# Wri... | """Return the roidb indices for the next minibatch."""
# TODO(rbg): remove duplicated code
if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAI... |
def _get_next_minibatch_inds(self): | random_line_split |
lib.rs | #![warn(rust_2018_idioms)]
#[macro_use]
extern crate tracing;
use std::collections::hash_map::{Entry, HashMap};
use conduit::{box_error, Handler, HandlerResult, Method, RequestExt};
use route_recognizer::{Match, Params, Router};
#[derive(Default)]
pub struct RouteBuilder {
routers: HashMap<Method, Router<Wrappe... |
}
};
// We don't have `pub` access to the fields to destructure `Params`, so swap with an empty
// value to avoid an allocation.
let mut params = Params::new();
std::mem::swap(m.params_mut(), &mut params);
let pattern = m.handler().pattern;
debug!(p... | {
info!("{}", e);
return Err(box_error(e));
} | conditional_block |
lib.rs | #![warn(rust_2018_idioms)]
#[macro_use]
extern crate tracing;
use std::collections::hash_map::{Entry, HashMap};
use conduit::{box_error, Handler, HandlerResult, Method, RequestExt};
use route_recognizer::{Match, Params, Router};
#[derive(Default)]
pub struct RouteBuilder {
routers: HashMap<Method, Router<Wrappe... |
impl conduit::Handler for WrappedHandler {
fn call(&self, request: &mut dyn RequestExt) -> HandlerResult {
self.handler.call(request)
}
}
#[derive(Debug, thiserror::Error)]
pub enum RouterError {
#[error("Invalid method")]
UnknownMethod,
#[error("Path not found")]
PathNotFound,
}
impl... |
struct WrappedHandler {
pattern: RoutePattern,
handler: Box<dyn Handler>,
} | random_line_split |
lib.rs | #![warn(rust_2018_idioms)]
#[macro_use]
extern crate tracing;
use std::collections::hash_map::{Entry, HashMap};
use conduit::{box_error, Handler, HandlerResult, Method, RequestExt};
use route_recognizer::{Match, Params, Router};
#[derive(Default)]
pub struct RouteBuilder {
routers: HashMap<Method, Router<Wrappe... | <H: Handler>(
&mut self,
method: Method,
pattern: &'static str,
handler: H,
) -> &mut Self {
{
let router = match self.routers.entry(method) {
Entry::Occupied(e) => e.into_mut(),
Entry::Vacant(e) => e.insert(Router::new()),
... | map | identifier_name |
buffer_tests.rs | //! Tests for `IBuffer`.
use buffer::IBuffer;
use std::io::Read;
#[test]
fn read_from_string() {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let res = in_buf.read(&mut buf);
assert_eq!(6, res.expect("read must be ok"));
assert_eq!([b'H', b'e', b'l', b'l', b'o', b' ... | () {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let _ = in_buf.read(&mut buf);
let _ = in_buf.read(&mut buf);
let res = in_buf.read(&mut buf);
assert_eq!(0, res.expect("read must be ok"));
}
| read_from_string_eof | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.