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 |
|---|---|---|---|---|
socialcoffee.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//var MODAL = $("#modalProducto");
var URL = Define.URL_BASE;
window.onload=function(){
//toastr.error("Ingresaaaaaaaaa");
... | rl_direccionar){
setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos
}
$("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd
var usuario_a_buscar = $("#username").val();
var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué u... | direccionar(u | identifier_name |
Toolbar.tsx | import React, { Fragment, FunctionComponent } from 'react';
import { styled } from '@storybook/theming';
import { window } from 'global';
import { FlexBar } from '../bar/bar';
import { Icons } from '../icon/icon';
import { IconButton } from '../bar/button';
interface ZoomProps {
zoom: (val: number) => void;
reset... | onClick={e => {
e.preventDefault();
resetZoom();
}}
title="Reset zoom"
>
<Icons icon="zoomreset" />
</IconButton>
</>
);
const Eject: FunctionComponent<EjectProps> = ({ baseUrl, storyId }) => (
<IconButton
key="opener"
onClick={() => window.open(`${baseUrl}?i... | random_line_split | |
mixins.py | from collections import OrderedDict
from django.http import HttpResponse
import simplejson
class | (object):
"""This class was designed to be inherited and used to return JSON objects from an Ordered Dictionary
"""
## Ordered Dictionary used to create serialized JSON object
# return_rderedDict() #This will enforce the ordering that we recieve from the database
def __init__(self):
"""
... | JSONMixin | identifier_name |
mixins.py | from collections import OrderedDict
from django.http import HttpResponse
import simplejson
class JSONMixin(object):
"""This class was designed to be inherited and used to return JSON objects from an Ordered Dictionary
"""
## Ordered Dictionary used to create serialized JSON object |
def __init__(self):
"""
Init function for the JSON Mixin class
"""
self.return_list=OrderedDict()
return
def render_to_response(self, context):
"""Extends default render to response to return serialized JSON.
"""
return self.get_json_response(se... | # return_rderedDict() #This will enforce the ordering that we recieve from the database | random_line_split |
mixins.py | from collections import OrderedDict
from django.http import HttpResponse
import simplejson
class JSONMixin(object):
"""This class was designed to be inherited and used to return JSON objects from an Ordered Dictionary
"""
## Ordered Dictionary used to create serialized JSON object
# return_rderedDict(... |
def convert_to_json(self):
"""Serialized the return_list into JSON
"""
return simplejson.dumps(self.return_list) | """Returns JSON to calling object in the form of an http response.
"""
return HttpResponse(content,content_type='application/json',**httpresponse_kwargs) | identifier_body |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... | () {
let mut lim = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(20u32));
let now = current_moment();
let ms = Duration::from_millis(1);
let mut children = vec![];
lim.check_at(now).unwrap();
for _i in 0..20 {
let mut lim = lim.clone();
children.push(thread::spawn(move |... | actual_threadsafety | identifier_name |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... |
#[test]
fn never_allows_more_than_capacity() {
let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32));
let now = current_moment();
let ms = Duration::from_millis(1);
// Should not allow the first 15 cells on a capacity 5 bucket:
assert_ne!(Ok(()), lb.check_n_at(15, now));
... | {
let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(2u32));
let now = current_moment();
let ms = Duration::from_millis(1);
assert_eq!(Ok(()), lb.check_at(now));
assert_eq!(Ok(()), lb.check_at(now));
assert_ne!(Ok(()), lb.check_at(now + ms * 2));
// should be ok again in 1s... | identifier_body |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... | let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32));
let now = current_moment();
let ms = Duration::from_millis(1);
// Should not allow the first 15 cells on a capacity 5 bucket:
assert_ne!(Ok(()), lb.check_n_at(15, now));
// After 3 and 20 seconds, it should not allow 15... | }
#[test]
fn never_allows_more_than_capacity() { | random_line_split |
map-types.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
}
| main | identifier_name |
map-types.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
} | identifier_body | |
map-types.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let x: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
} |
use std::collections::HashMap;
// Test that trait types printed in error msgs include the type arguments. | random_line_split |
CloudMailRu.py | # -*- coding: utf-8 -*-
import base64
import json
import re
from ..base.downloader import BaseDownloader
class CloudMailRu(BaseDownloader):
__name__ = "CloudMailRu"
__type__ = "downloader"
__version__ = "0.04"
__status__ = "testing"
__pattern__ = r"https?://cloud\.mail\.ru/dl\?q=(?P<QS>.+)"
... | def get_info(cls, url="", html=""):
info = super().get_info(url, html)
qs = re.match(cls.__pattern__, url).group('QS')
file_info = json.loads(base64.b64decode(qs).decode("utf-8"))
info.update({
'name': file_info['n'],
'size': file_info['s'],
'u':... | OFFLINE_PATTERN = r'"error":\s*"not_exists"'
@classmethod | random_line_split |
CloudMailRu.py | # -*- coding: utf-8 -*-
import base64
import json
import re
from ..base.downloader import BaseDownloader
class CloudMailRu(BaseDownloader):
__name__ = "CloudMailRu"
__type__ = "downloader"
__version__ = "0.04"
__status__ = "testing"
__pattern__ = r"https?://cloud\.mail\.ru/dl\?q=(?P<QS>.+)"
... | (self):
self.chunk_limit = -1
self.resume_download = True
self.multi_dl = True
def process(self, pyfile):
self.download(self.info["u"], disposition=False)
| setup | identifier_name |
CloudMailRu.py | # -*- coding: utf-8 -*-
import base64
import json
import re
from ..base.downloader import BaseDownloader
class CloudMailRu(BaseDownloader):
__name__ = "CloudMailRu"
__type__ = "downloader"
__version__ = "0.04"
__status__ = "testing"
__pattern__ = r"https?://cloud\.mail\.ru/dl\?q=(?P<QS>.+)"
... |
def process(self, pyfile):
self.download(self.info["u"], disposition=False)
| self.chunk_limit = -1
self.resume_download = True
self.multi_dl = True | identifier_body |
config.py | # -*- coding: utf-8 -*-
# ***********************************************************************
# Copyright (C) 2014 - 2017 Oscar Gerardo Lazo Arjona *
# <oscar.lazo@correo.nucleares.unam.mx> *
# *... |
# The install directory for FAST:
fast_path = __file__[:-len("__init__.pyc")] | use_netcdf = False
# An integer between 0 and 2 to control which tests are ran.
run_long_tests = 0 | random_line_split |
google-charts-datatable.ts | declare var google: any;
export interface ArrowFormatInterface {
base: number;
}
export interface BarFormatInterface {
base?: number;
colorNegative?: string;
colorPositive?: string;
drawZeroLine?: boolean;
max?: number;
min?: number;
showValue?: boolean;
width?: number;
}
export interface RangeInte... | (private opt: GoogleChartsDataTableInterface) {
if (opt) {
this._setDataTable(opt.dataTable, opt.firstRowIsData);
}
}
private send() {
if (this.query === undefined) {
return;
}
this.query.send((queryResponse: any) => {
this.setDataTable(queryResponse.getDataTable());
if ... | constructor | identifier_name |
google-charts-datatable.ts | declare var google: any;
export interface ArrowFormatInterface {
base: number;
}
export interface BarFormatInterface {
base?: number;
colorNegative?: string;
colorPositive?: string;
drawZeroLine?: boolean;
max?: number;
min?: number;
showValue?: boolean;
width?: number;
}
export interface RangeInte... |
public setDataTable(dt: any, firstRowIsData?: boolean) {
if (firstRowIsData === undefined) {
firstRowIsData = this.opt.firstRowIsData;
}
this._setDataTable(dt, firstRowIsData);
this.dataTableChanged.emit(this.dataTable);
}
private _setDataTable(dt: any, firstRowIsData?: boolean) {
if ... | {
return this.dataTable;
} | identifier_body |
google-charts-datatable.ts | declare var google: any;
export interface ArrowFormatInterface {
base: number;
}
export interface BarFormatInterface {
base?: number;
colorNegative?: string;
colorPositive?: string;
drawZeroLine?: boolean;
max?: number;
min?: number;
showValue?: boolean;
width?: number;
}
export interface RangeInte... |
}
for (const col of formatterConfig.columns) {
formatter.format(dt, col);
}
}
}
}
| {
for (const range of fmtOptions.ranges) {
if (typeof (range.fromBgColor) !== 'undefined'
&& typeof (range.toBgColor) !== 'undefined') {
formatter.addGradientRange(range.from, range.to,
range.color, range.fromBgColor, range.toBgColor);
} el... | conditional_block |
google-charts-datatable.ts | declare var google: any;
export interface ArrowFormatInterface {
base: number;
}
export interface BarFormatInterface {
base?: number;
colorNegative?: string;
colorPositive?: string;
drawZeroLine?: boolean;
max?: number;
min?: number;
showValue?: boolean;
width?: number;
}
export interface RangeInte... | dataSourceUrl?: string;
/** Refresh interval, in seconds, when using remote data source. */
refreshInterval?: number;
/** Timeout in seconds, when using remote data source */
timeout?: number;
/** Called after query executed. DataTable is updated automatically.
* @param queryResponse google.visualizat... | query?: string; | random_line_split |
IntCartesianProduct.tsx | import * as _ from 'lodash';
import * as collections from 'typescript-collections';
export class IntCartesianProduct {
private _lengths:Array<number>=[];
private _indices:Array<number> = [];
private maxIndex:number;
private _hasNext:boolean = true;
constructor(lengths:Array<number>) {
thi... |
return maxIndex;
}
public hasNext():boolean {
return this._hasNext;
}
public next():Array<number> {
var result: Array<number> = collections.arrays.copy(this._indices);
for(var i:number = this._indices.length - 1; i >= 0; i--) {
if (this._indices[i] == this.... | {
var length = this._lengths[i];
maxIndex*=length;
} | conditional_block |
IntCartesianProduct.tsx | import * as _ from 'lodash';
import * as collections from 'typescript-collections';
export class IntCartesianProduct {
private _lengths:Array<number>=[];
private _indices:Array<number> = [];
private maxIndex:number;
private _hasNext:boolean = true;
constructor(lengths:Array<number>) {
thi... |
} | {
//console.log("MaxIndex=" + this.maxIndex);
return this.maxIndex;
} | identifier_body |
IntCartesianProduct.tsx | import * as _ from 'lodash';
import * as collections from 'typescript-collections';
export class | {
private _lengths:Array<number>=[];
private _indices:Array<number> = [];
private maxIndex:number;
private _hasNext:boolean = true;
constructor(lengths:Array<number>) {
this._lengths = collections.arrays.copy(lengths);
this._indices = new Array<number>(lengths.length);
for... | IntCartesianProduct | identifier_name |
IntCartesianProduct.tsx | import * as _ from 'lodash';
import * as collections from 'typescript-collections';
export class IntCartesianProduct {
private _lengths:Array<number>=[];
private _indices:Array<number> = [];
private maxIndex:number;
private _hasNext:boolean = true;
constructor(lengths:Array<number>) {
thi... | for (var i: number = 0; i < this._indices.length;i++) {
this._indices[i]=0;
}
this.maxIndex = this.findMaxIndex();
}
public findMaxIndex():number {
let max:number = -1;
let maxIndex:number = 1;
for (var i:number = 0; i < this._lengths.length; i++) {
... | random_line_split | |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if !valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if !valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let... | else {
sum.push(r);
next_r = digits_r.next();
}
},
(Some(l), None) => {
sum.push(l);
next_l = digits_l.next();
},
(None, Some(r)) => {
sum.push(r);
nex... | {
sum.push(l);
next_l = digits_l.next();
} | conditional_block |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if !valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if !valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let... | assert_eq!("LI", add("L", "I").unwrap());
}
#[test]
fn add_l_xi_understands_l_x_sort_order() {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test... | fn add_l_i_supports_l() { | random_line_split |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if !valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if !valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let... |
#[test]
fn add_l_xi_understands_l_x_sort_order() {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test]
fn add_fails_when_lhs_is_invalid() {
asse... | {
assert_eq!("LI", add("L", "I").unwrap());
} | identifier_body |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if !valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if !valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let... | () {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test]
fn add_fails_when_lhs_is_invalid() {
assert!(add("J", "I").is_err());
}
#[test]
fn a... | add_l_xi_understands_l_x_sort_order | identifier_name |
conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | #
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. L... |
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). | random_line_split |
select2_locale_fr.js | /**
* Select2 French translation
*/
(function ($) {
"use strict";
| $.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "Aucun résultat trouvé"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Merci de saisir " + n + " caractère" + (n == 1? "" : "s") + " de plus"; },
formatInputTooLong: function (input,... | random_line_split | |
JsonLogger.ts | import { currentTimestampSeconds } from "util/Time";
import { Loggable, Logger, AbstractLogger, LogLevel } from "logger/Logger";
import { Logging } from "logger/Logging";
| /**
* Logger that outputs messages formatted as JSON objects.
*
* Example output:
* {
* "time": "2019-07-01T21:55:00.342Z",
* "message": "wawawa",
* "level": "4",
* "context": "MyClass"
* }
*/
export class JsonLogger extends AbstractLogger {
private readonly context: Loggable[] = [];
... | random_line_split | |
JsonLogger.ts | import { currentTimestampSeconds } from "util/Time";
import { Loggable, Logger, AbstractLogger, LogLevel } from "logger/Logger";
import { Logging } from "logger/Logging";
/**
* Logger that outputs messages formatted as JSON objects.
*
* Example output:
* {
* "time": "2019-07-01T21:55:00.342Z",
* "messa... | (): JsonLogger {
return new JsonLogger();
}
public withContext(...args: Loggable[]): Logger {
const logger = new JsonLogger();
logger.context.push(...this.context, ...args);
return logger;
}
public log(logLevel: LogLevel, message: string, ...args: Loggable[]): void {
... | create | identifier_name |
JsonLogger.ts | import { currentTimestampSeconds } from "util/Time";
import { Loggable, Logger, AbstractLogger, LogLevel } from "logger/Logger";
import { Logging } from "logger/Logging";
/**
* Logger that outputs messages formatted as JSON objects.
*
* Example output:
* {
* "time": "2019-07-01T21:55:00.342Z",
* "messa... |
public log(logLevel: LogLevel, message: string, ...args: Loggable[]): void {
if (logLevel < Logging.getLogLevel()) {
return;
}
let level: string;
switch (logLevel) {
case LogLevel.DEBUG:
level = "DEBUG";
break;
c... | {
const logger = new JsonLogger();
logger.context.push(...this.context, ...args);
return logger;
} | identifier_body |
__init__.py | """
run tests against a webserver running in the same reactor
NOTE: this test uses port 8888 on localhost
"""
import os
import ujson as json
import cyclone.httpclient
from twisted.internet import defer
from twisted.application import internet
from twisted.trial.unittest import TestCase
from twisted.python import log
... | 'pg-username': 'bitwrap',
'pg-password': 'bitwrap',
'pg-database': 'bitwrap'
}
class ApiTest(TestCase):
""" setup rpc endpoint and invoke ping method """
def setUp(self):
""" start tcp endpoint """
set_pnml_path(OPTIONS['machine-path'])
self.options = OPTIONS
#pyli... | 'listen-ip': IFACE,
'listen-port': PORT,
'machine-path': os.path.abspath(os.path.dirname(__file__) + '/../../schemata'),
'pg-host': '127.0.0.1',
'pg-port': 5432, | random_line_split |
__init__.py | """
run tests against a webserver running in the same reactor
NOTE: this test uses port 8888 on localhost
"""
import os
import ujson as json
import cyclone.httpclient
from twisted.internet import defer
from twisted.application import internet
from twisted.trial.unittest import TestCase
from twisted.python import log
... | (resource):
""" rpc client """
return cyclone.httpclient.JsonRPC(ApiTest.url(resource))
@staticmethod
def fetch(resource, **kwargs):
""" async request with httpclient"""
return cyclone.httpclient.fetch(ApiTest.url(resource), **kwargs)
@staticmethod
def dispatch(**event)... | client | identifier_name |
__init__.py | """
run tests against a webserver running in the same reactor
NOTE: this test uses port 8888 on localhost
"""
import os
import ujson as json
import cyclone.httpclient
from twisted.internet import defer
from twisted.application import internet
from twisted.trial.unittest import TestCase
from twisted.python import log
... | """ bulid a url using test endpoint """
return 'http://%s:%s/%s' % (IFACE, PORT, resource)
@staticmethod
def client(resource):
""" rpc client """
return cyclone.httpclient.JsonRPC(ApiTest.url(resource))
@staticmethod
def fetch(resource, **kwargs):
""" async requ... | """ setup rpc endpoint and invoke ping method """
def setUp(self):
""" start tcp endpoint """
set_pnml_path(OPTIONS['machine-path'])
self.options = OPTIONS
#pylint: disable=no-member
self.service = internet.TCPServer(PORT, Api(self.options), interface=self.options['listen-i... | identifier_body |
__init__.py | """
run tests against a webserver running in the same reactor
NOTE: this test uses port 8888 on localhost
"""
import os
import ujson as json
import cyclone.httpclient
from twisted.internet import defer
from twisted.application import internet
from twisted.trial.unittest import TestCase
from twisted.python import log
... |
else:
data = json.dumps(event['payload'])
return cyclone.httpclient.fetch(url, postdata=data)
@staticmethod
def broadcast(**event):
""" rpc client """
resource = 'broadcast/%s/%s' % (event['schema'], event['id'])
url = ApiTest.url(resource)
data = ... | data = event['payload'] | conditional_block |
_y.py | import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="y", parent_name="volume.caps", **kwargs):
| """,
),
**kwargs
)
| super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Y"),
data_docs=kwargs.pop(
"data_docs",
"""
fill
Sets the fill ratio of the `caps`.... | identifier_body |
_y.py | import _plotly_utils.basevalidators
class | (_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="y", parent_name="volume.caps", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Y"),
da... | YValidator | identifier_name |
_y.py | class YValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="y", parent_name="volume.caps", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Y")... | import _plotly_utils.basevalidators
| random_line_split | |
ui.d.ts | import { DeviceService } from './device';
import { SessionService } from './session';
import { ViewService } from './view';
import { RealityService, RealityServiceProvider } from './reality';
/**
* Provides a default UI
*/
export declare class | {
private sessionService;
private viewService;
private realityService;
private realityServiceProvider;
private deviceService;
private element?;
private realityViewerSelectorElement;
private realityViewerListElement;
private menuBackgroundElement;
private realityViewerItemElement... | DefaultUIService | identifier_name |
ui.d.ts | import { DeviceService } from './device';
import { SessionService } from './session';
import { ViewService } from './view';
import { RealityService, RealityServiceProvider } from './reality';
/**
* Provides a default UI
*/
export declare class DefaultUIService {
private sessionService;
private viewService;
... | private _createMenuItem(icon, hint, onSelect?);
private onSelect(element, cb);
private toggleMenu();
private _hideMenuItem(e);
updateMenu(): void;
} | private realityMenuItem;
private maximizeMenuItem;
constructor(sessionService: SessionService, viewService: ViewService, realityService: RealityService, realityServiceProvider: RealityServiceProvider, deviceService: DeviceService); | random_line_split |
help-dialog.component.d.ts | import { OnDestroy, OnInit } from '@angular/core';
import { MediaObserver } from '@angular/flex-layout';
import { MimeViewerIntl } from '../core/intl/viewer-intl';
import { MimeResizeService } from '../core/mime-resize-service/mime-resize.service'; | private mimeResizeService;
tabHeight: {};
private mimeHeight;
private subscriptions;
constructor(mediaObserver: MediaObserver, intl: MimeViewerIntl, mimeResizeService: MimeResizeService);
ngOnInit(): void;
ngOnDestroy(): void;
private resizeTabHeight;
static ɵfac: i0.ɵɵFactoryDeclara... | import * as i0 from "@angular/core";
export declare class HelpDialogComponent implements OnInit, OnDestroy {
mediaObserver: MediaObserver;
intl: MimeViewerIntl; | random_line_split |
help-dialog.component.d.ts | import { OnDestroy, OnInit } from '@angular/core';
import { MediaObserver } from '@angular/flex-layout';
import { MimeViewerIntl } from '../core/intl/viewer-intl';
import { MimeResizeService } from '../core/mime-resize-service/mime-resize.service';
import * as i0 from "@angular/core";
export declare class | implements OnInit, OnDestroy {
mediaObserver: MediaObserver;
intl: MimeViewerIntl;
private mimeResizeService;
tabHeight: {};
private mimeHeight;
private subscriptions;
constructor(mediaObserver: MediaObserver, intl: MimeViewerIntl, mimeResizeService: MimeResizeService);
ngOnInit(): void... | HelpDialogComponent | identifier_name |
conf_fixture.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | # under the License.
import os
from oslo_policy import opts
from oslo_service import wsgi
from manila.common import config
CONF = config.CONF
def set_defaults(conf):
_safe_set_of_opts(conf, 'verbose', True)
_safe_set_of_opts(conf, 'state_path', os.path.abspath(
os.path.join(os.path.dirname(__fi... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations | random_line_split |
conf_fixture.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | _safe_set_of_opts(conf, 'zfs_share_export_ip', '1.1.1.1')
_safe_set_of_opts(conf, 'zfs_service_ip', '2.2.2.2')
_safe_set_of_opts(conf, 'zfs_zpool_list', ['foo', 'bar'])
_safe_set_of_opts(conf, 'zfs_share_helpers', 'NFS=foo.bar.Helper')
_safe_set_of_opts(conf, 'zfs_replica_snapshot_prefix', 'foo_pref... | _safe_set_of_opts(conf, 'verbose', True)
_safe_set_of_opts(conf, 'state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__),
'..',
'..')))
_safe_set_of_opts(conf, 'connection', "sqlite://", group='database')
_safe_set_of_opts(conf, 'sqlite_synchro... | identifier_body |
conf_fixture.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | (conf, *args, **kwargs):
try:
conf.set_default(*args, **kwargs)
except config.cfg.NoSuchOptError:
# Assumed that opt is not imported and not used
pass
| _safe_set_of_opts | identifier_name |
bounds.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 ... | (cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: |P<Item>|) {
let name = match mitem.node {
MetaWord(ref tname) => {
match tname.get() {
"Copy" ... | expand_deriving_bound | identifier_name |
bounds.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 ... | ,
_ => {
return cx.span_err(span, "unexpected value in deriving, expected \
a trait")
}
};
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "kinds", name)),
additional_bou... | {
match tname.get() {
"Copy" => "Copy",
"Send" => "Send",
"Sync" => "Sync",
ref tname => {
cx.span_bug(span,
format!("expected built-in trait name but \
... | conditional_block |
bounds.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 ... | };
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "kinds", name)),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!()
};
trait_def.expand(cx, mitem, item, push)
}
| {
let name = match mitem.node {
MetaWord(ref tname) => {
match tname.get() {
"Copy" => "Copy",
"Send" => "Send",
"Sync" => "Sync",
ref tname => {
cx.span_bug(span,
format!("expect... | identifier_body |
bounds.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 ... | }
}
},
_ => {
return cx.span_err(span, "unexpected value in deriving, expected \
a trait")
}
};
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std"... | cx.span_bug(span,
format!("expected built-in trait name but \
found {}",
*tname).as_slice()) | random_line_split |
meteor-methods.js | import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function | (config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: config.modelFields,
});
config.saveMethod = 'save' + config.modelName;
config.removeMethod = 'remove'... | init | identifier_name |
meteor-methods.js | import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function init(config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: co... |
}
return result;
}
config.colFields = colFieldsFunc();
}
export function saveDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
try {
doc.save();
} catch (e) {
Errors.handle(e);
}
}
export function removeDoc (doc) {
if ( !Meteor.userId() ) {
... | {
result[i] = config.formFields[i];
} | conditional_block |
meteor-methods.js | import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function init(config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: co... | }
try {
doc.save();
} catch (e) {
Errors.handle(e);
}
}
export function removeDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
doc.remove();
} | random_line_split | |
meteor-methods.js | import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function init(config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: co... | {
if ( !Meteor.userId() ) {
return;
}
doc.remove();
} | identifier_body | |
0006_auto__add_field_reference_year.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Reference.year'
db.add_column(u'citations_reference', 'year',
self.gf(... | 'volume': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'year': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['citations'] | 'series': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'Tr... | random_line_split |
0006_auto__add_field_reference_year.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class | (SchemaMigration):
def forwards(self, orm):
# Adding field 'Reference.year'
db.add_column(u'citations_reference', 'year',
self.gf('django.db.models.fields.IntegerField')(null=True, blank=True),
keep_default=False)
def backwards(self, orm):
#... | Migration | identifier_name |
0006_auto__add_field_reference_year.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Reference.year'
|
def backwards(self, orm):
# Deleting field 'Reference.year'
db.delete_column(u'citations_reference', 'year')
models = {
u'citations.reference': {
'Meta': {'object_name': 'Reference'},
'abstract': ('django.db.models.fields.TextField', [], {'null': 'True', 'bla... | db.add_column(u'citations_reference', 'year',
self.gf('django.db.models.fields.IntegerField')(null=True, blank=True),
keep_default=False) | identifier_body |
IMainInputButtonAction.ts | /*
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
... | type: InputToolbarButtonsActionType;
} | export interface IInputToolbarButtonAction extends Action {
button?: JSX.Element;
side: "left" | "right"; | random_line_split |
localrepocache_tests.py | # Copyright (C) 2012-2015 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but ... | raise cliapp.AppException('Not found')
def test_has_not_got_shortened_repo_initially(self):
self.assertFalse(self.lrc.has_repo(self.reponame))
def test_has_not_got_absolute_repo_initially(self):
self.assertFalse(self.lrc.has_repo(self.repourl))
def test_caches_shortened_repository... | FakeApplication(), *args)
def not_found(self, url, path): | random_line_split |
localrepocache_tests.py | # Copyright (C) 2012-2015 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but ... |
class LocalRepoCacheTests(unittest.TestCase):
def setUp(self):
aliases = ['upstream=git://example.com/#example.com:%s.git']
repo_resolver = morphlib.repoaliasresolver.RepoAliasResolver(aliases)
tarball_base_url = 'http://lorry.example.com/tarballs/'
self.reponame = 'upstream:repo... | def __init__(self):
self.settings = {
'verbose': True
}
def status(self, msg):
pass | identifier_body |
localrepocache_tests.py | # Copyright (C) 2012-2015 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but ... | (self):
self.assertFalse(self.lrc.has_repo(self.reponame))
def test_has_not_got_absolute_repo_initially(self):
self.assertFalse(self.lrc.has_repo(self.repourl))
def test_caches_shortened_repository_on_request(self):
self.lrc.cache_repo(self.reponame)
self.assertTrue(self.lrc.ha... | test_has_not_got_shortened_repo_initially | identifier_name |
localrepocache_tests.py | # Copyright (C) 2012-2015 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but ... |
elif args[0:2] == ['remote', 'set-url']:
remote = args[2]
url = args[3]
self.remotes[remote] = {'url': url}
elif args[0:2] == ['config', 'remote.origin.url']:
remote = 'origin'
url = args[2]
self.remotes[remote] = {'url': url}
... | self.assertEqual(len(args), 5)
remote = args[3]
local = args[4]
self.remotes['origin'] = {'url': remote, 'updates': 0}
self.lrc.fs.makedir(local, recursive=True) | conditional_block |
models.py | from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identi... | return self.name or ''
def get_absolute_url(self):
return reverse('identity-detail', kwargs={'pk': self.id})
class Meta:
verbose_name = 'identity'
verbose_name_plural = 'identities'
ordering = ['name']
class Person(TimeStampedModel):
first_name = models.CharField(... | def __str__(self): | random_line_split |
models.py | from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identi... |
if self.identifier_type is 'UNAME' or self.identifier_type is 'NAME':
try:
validate_slug(self.identifier)
except ValidationError:
raise ValidationError('Identifier is not a valid username or name')
if self.identifier_type is 'SKYPE':
... | try:
validate_ipv46_address(self.identifier)
except ValidationError:
raise ValidationError('Identifier is not a valid IPv4/IPv6 address') | conditional_block |
models.py | from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identi... |
def clean(self):
if self.identifier_type is 'EMAIL':
try:
validate_email(self.identifier)
except ValidationError:
raise ValidationError('Identifier is not a valid email address')
if self.identifier_type is 'IPADD':
try:
... | return reverse('identifier-detail', kwargs={'pk': self.id}) | identifier_body |
models.py | from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identi... | :
verbose_name = 'identity'
verbose_name_plural = 'identities'
ordering = ['name']
class Person(TimeStampedModel):
first_name = models.CharField(max_length=75, validators=[validate_slug])
surname = models.CharField(max_length=75, validators=[validate_slug])
identity = models.ManyTo... | Meta | identifier_name |
SPFormField.tsx | import * as React from 'react';
import { ControlMode } from '../../../../common/datatypes/ControlMode';
import { IFieldSchema } from '../../../../common/services/datatypes/RenderListData';
import FormField from './FormField';
import { IFormFieldProps } from './FormField';
import { IDatePickerStrings } from 'offi... |
underlined
/>;
}
}
return (fieldControl)
? <FormField
{...props}
label={props.label || props.fieldSchema.Title}
description={props.description || props.fieldSchema.Description}
required={props.fieldSchema.Required}
errorMessage={props.errorMessage}
... | {
const isObjValue = (props.value) && (typeof props.value !== 'string');
const value = (props.value) ? ((typeof props.value === 'string') ? props.value : JSON.stringify(props.value)) : '';
fieldControl = <TextField
readOnly
multiline={isObjValue}
value={value}
er... | conditional_block |
SPFormField.tsx | import * as React from 'react';
import { ControlMode } from '../../../../common/datatypes/ControlMode';
import { IFieldSchema } from '../../../../common/services/datatypes/RenderListData';
import FormField from './FormField';
import { IFormFieldProps } from './FormField';
import { IDatePickerStrings } from 'offi... | Attachments: null,
*/
};
export interface ISPFormFieldProps extends IFormFieldProps {
extraData?: any;
fieldSchema: IFieldSchema;
hideIfFieldUnsupported?: boolean;
}
const SPFormField: React.SFC<ISPFormFieldProps> = (props) => {
let fieldControl = null;
const fieldType = props.fieldSchema.Fi... | File: { component: SPFieldTextDisplay },
TaxonomyFieldType: { component: SPFieldTextDisplay, valuePreProcess: (val) => val ? val.Label : '' },
TaxonomyFieldTypeMulti: { component: SPFieldTextDisplay, valuePreProcess: (val) => val ? val.map((v) => v.Label).join(', ') : '' },
/* The following are known but uns... | random_line_split |
db.js | import Dexie from 'dexie'
const db = new Dexie('metaDb')
db.version(1).stores({
player: '++id, name',
game: '++id, team, season, day'
})
db.open().catch(e => {
console.error(`metaDb open failed: ${e.stack}`)
})
export const resetPlayer = () => db.table('player').clear()
.catch(e => console.log(`error resetti... | // {
// DB.table.put( objectList[i] )
// }
// }) | random_line_split | |
webcore.py | _get):
if self.path == "/":
self.send_info(is_get)
elif self.path.startswith("/favicon."):
self.send_favicon(is_get)
else:
self.send_error(404, "File not found on CoreHandler")
def send_favicon (self, is_get = False):
self.send_response(200)
self.send_header("Content-type", "ima... | set_handler | identifier_name | |
webcore.py | dirpath is an OS path
try:
d = os.listdir(dirpath)
except OSError as e:
if e.errno == errno.EACCES:
self.send_error(403, "This directory is not listable")
elif e.errno == errno.ENOENT:
self.send_error(404, "This directory does not exist")
else:
self.send_error(40... | prefix,directory = entry.split(":")
directory = os.path.expanduser(directory) | random_line_split | |
webcore.py | a in attrs:
setattr(child, a, getattr(parent, a))
setattr(child, 'parent', parent)
import SimpleHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class SplitRequestHandler (BaseHTTPRequestHandler):
"""
To write HTTP handlers for POX, inherit from this class instead of
BaseHTTPRequestHand... | if i > 0: part += "/"
r.write('<a href="%s">%s</a>' % (link, cgi.escape(part)))
r.write("\n" + "-" * (0+len(path)) + "\n")
dirs = []
files = []
for f in d:
if f.startswith("."): continue
if os.path.isdir(os.path.join(dirpath, f)):
dirs.append(f)
else:
files... | try:
d = os.listdir(dirpath)
except OSError as e:
if e.errno == errno.EACCES:
self.send_error(403, "This directory is not listable")
elif e.errno == errno.ENOENT:
self.send_error(404, "This directory does not exist")
else:
self.send_error(400, "Unknown error")
r... | identifier_body |
webcore.py | >\n\n<h2>Web Prefixes</h2>"
r += "<ul>"
m = [map(cgi.escape, map(str, [x[0],x[1],x[3]]))
for x in self.args.matches]
m.sort()
for v in m:
r += "<li><a href='{0}'>{0}</a> - {1} {2}</li>\n".format(*v)
r += "</ul></body></html>\n"
self.send_response(200)
self.send_header("Conten... | www_path = '/' + www_path | conditional_block | |
EditAdminProductCard.tsx | import { useState, useContext } from 'react';
import * as React from 'react';
import { ApolloError } from '@apollo/client';
import {
ErrorDisplay,
MultipleChoiceInput,
useUniqueId,
BooleanInput,
BootstrapFormSelect,
usePropertySetters,
} from '@neinteractiveliterature/litform';
import AdminProductVariantsT... |
export default EditAdminProductCard; | random_line_split | |
EditAdminProductCard.tsx | import { useState, useContext } from 'react';
import * as React from 'react';
import { ApolloError } from '@apollo/client';
import {
ErrorDisplay,
MultipleChoiceInput,
useUniqueId,
BooleanInput,
BootstrapFormSelect,
usePropertySetters,
} from '@neinteractiveliterature/litform';
import AdminProductVariantsT... | else {
await createProduct({
variables: { product: productInput },
update: (cache, result) => {
const data = cache.readQuery<AdminProductsQueryData>({ query: AdminProductsQueryDocument });
const newProduct = result.data?.createProduct?.product;
if (!data || !newProdu... | {
await updateProduct({
variables: { id: product.id, product: productInput },
});
} | conditional_block |
center-ellipses.pipe.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | ? value.substring(0, tLimit / 2) + this.trail + value.substring(value.length - tLimit / 2, value.length)
: value;
}
} | if (!length) {
return value;
}
return value.length > tLimit | random_line_split |
center-ellipses.pipe.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
return value.length > tLimit
? value.substring(0, tLimit / 2) + this.trail + value.substring(value.length - tLimit / 2, value.length)
: value;
}
}
| {
return value;
} | conditional_block |
center-ellipses.pipe.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | (value: any, length?: number): any {
let tLimit = length ? length : limit;
if (!value) {
return '';
}
if (!length) {
return value;
}
return value.length > tLimit
? value.substring(0, tLimit / 2) + this.trail + value.substring(value.length - tLimit / 2, valu... | transform | identifier_name |
public_api.spec.ts | /*
* Copyright 2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
const file2 = fakeFile('test.image.jpg');
const density2 = getImageFileDensity(file2);
expect(density2).toEqual(1);
const file3 = fakeFile('test.image');
const density3 = getImageFileDensity(file3);
expect(density3).toEqual(1);
});
it('Should return 1 if density info in fi... | random_line_split | |
PortalUIEditorDialog.controller.ts | /// <reference path="../main/Resource.ts" />
/// <reference path="../../../typings/index.d.ts" />
module PortalUIEditor {
export class ResourceEditorController {
private $modalInstance: any;
private $http: any;
private $window: any;
json: string;
validationResult: string;
/** @ngInject */
... | var obj: any;
try {
obj = JSON.parse(this.json);
} catch (err) {
this.validationResult = "Invalid JSON: " + err.toString();
ArmViz.Telemetry.sendEvent('PortalUIEditor', 'Preview', 'Failed: ' + err.toString());
return null;
}
let url = 'http://armportaluire... | random_line_split | |
PortalUIEditorDialog.controller.ts | /// <reference path="../main/Resource.ts" />
/// <reference path="../../../typings/index.d.ts" />
module PortalUIEditor {
export class ResourceEditorController {
private $modalInstance: any;
private $http: any;
private $window: any;
json: string;
validationResult: string;
/** @ngInject */
... |
validate() {
try {
JSON.parse(this.json);
this.validationResult = "Valid JSON!";
ArmViz.Telemetry.sendEvent('PortalUIEditor', 'Validate', 'Passed');
} catch (err) {
this.validationResult = "Invalid JSON: " + err.toString();
ArmViz.Telemetry.sendEvent('PortalUIEd... | {
this.$modalInstance = $modalInstance;
this.$http = $http;
this.$window = $window;
ArmViz.Telemetry.sendEvent('PortalUIEditor', 'Open');
} | identifier_body |
PortalUIEditorDialog.controller.ts | /// <reference path="../main/Resource.ts" />
/// <reference path="../../../typings/index.d.ts" />
module PortalUIEditor {
export class ResourceEditorController {
private $modalInstance: any;
private $http: any;
private $window: any;
json: string;
validationResult: string;
/** @ngInject */
... | () {
this.$modalInstance.dismiss('cancel');
};
preview() {
console.log('preview!');
var obj: any;
try {
obj = JSON.parse(this.json);
} catch (err) {
this.validationResult = "Invalid JSON: " + err.toString();
ArmViz.Telemetry.sendEvent('PortalUIEditor', 'Pre... | close | identifier_name |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct | {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token... | Options | identifier_name |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const U... | cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose Use verbose output
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(options.flag_... |
Usage: | random_line_split |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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 ap... |
/// <reference types="@stdlib/types"/>
import { Complex64 } from '@stdlib/types/object';
/**
* Subtracts two single-precision complex floating-point numbers.
*
* @param z1 - complex number
* @param z2 - complex number
* @returns result
*
* @example
* var Complex64 = require( `@stdlib/complex/float32` );
* var real =... | // TypeScript Version: 2.0 | random_line_split |
Button.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import SafeAnchor from '../SafeAnchor';
import Ripple from '../Ripple';
import { withStyleProps, getUnhandledProps, defaultProps, prefix, isOneOf } from '../utils';
import {... | (unhandled.href) {
return (
<SafeAnchor {...unhandled} aria-disabled={disabled} className={classes}>
{loading && spin}
{children}
{rippleElement}
</SafeAnchor>
);
}
unhandled.type = unhandled.type || 'button';
}
return (
... | if | identifier_name |
Button.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import SafeAnchor from '../SafeAnchor';
import Ripple from '../Ripple';
import { withStyleProps, getUnhandledProps, defaultProps, prefix, isOneOf } from '../utils';
import {... |
unhandled.type = unhandled.type || 'button';
}
return (
<Component {...unhandled} disabled={disabled} className={classes}>
{loading && spin}
{children}
{rippleElement}
</Component>
);
}
}
export default compose<any, ButtonProps>(
withStyleProps<ButtonProps>({... | {
return (
<SafeAnchor {...unhandled} aria-disabled={disabled} className={classes}>
{loading && spin}
{children}
{rippleElement}
</SafeAnchor>
);
} | identifier_body |
Button.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import SafeAnchor from '../SafeAnchor';
import Ripple from '../Ripple';
import { withStyleProps, getUnhandledProps, defaultProps, prefix, isOneOf } from '../utils';
import {... | return (
<SafeAnchor {...unhandled} aria-disabled={disabled} className={classes}>
{loading && spin}
{children}
{rippleElement}
</SafeAnchor>
);
}
unhandled.type = unhandled.type || 'button';
}
return (
<Component {...unha... | random_line_split | |
linear.py | import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... | length as indexed hash codes.
:type h: numpy.ndarray[bool]
:param n: Number of nearest neighbors to find.
:type n: int
:raises ValueError: No index to query from.
:return: Tuple of nearest N hash codes and a tuple of the distance
values to those neighbo... | Distances are in the range [0,1] and are the percent different each
neighbor hash is from the query, based on the number of bits contained
in the query.
:param h: Hash code to compute the neighbors of. Should be the same bit | random_line_split |
linear.py | import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... |
def __init__(self, file_cache=None):
"""
Initialize linear, brute-force hash index
:param file_cache: Optional path to a file to cache our index to.
:type file_cache: str
"""
super(LinearHashIndex, self).__init__()
self.file_cache = file_cache
self... | return True | identifier_body |
linear.py | import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... |
def count(self):
return len(self.index)
def build_index(self, hashes):
"""
Build the index with the give hash codes (bit-vectors).
Subsequent calls to this method should rebuild the index, not add to
it, or raise an exception to as to protect the current index.
... | numpy.save(self.file_cache, self.index) | conditional_block |
linear.py | import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... | (cls):
return True
def __init__(self, file_cache=None):
"""
Initialize linear, brute-force hash index
:param file_cache: Optional path to a file to cache our index to.
:type file_cache: str
"""
super(LinearHashIndex, self).__init__()
self.file_cache... | is_usable | identifier_name |
views.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (... | return getattr(self, "_more_%s" % table.name, False)
def get_images_data(self):
marker = self.request.GET.get(ImagesTable._meta.pagination_param, None)
try:
# FIXME(gabriel): The paging is going to be strange here due to
# our filtering after the fact.
(a... | table_classes = (ImagesTable, SnapshotsTable, VolumeSnapshotsTable)
template_name = 'project/images_and_snapshots/index.html'
def has_more_data(self, table): | random_line_split |
views.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (... | return images
def get_snapshots_data(self):
req = self.request
marker = req.GET.get(SnapshotsTable._meta.pagination_param, None)
try:
snaps, self._more_snapshots = api.snapshot_list_detailed(req,
marker=mark... | table_classes = (ImagesTable, SnapshotsTable, VolumeSnapshotsTable)
template_name = 'project/images_and_snapshots/index.html'
def has_more_data(self, table):
return getattr(self, "_more_%s" % table.name, False)
def get_images_data(self):
marker = self.request.GET.get(ImagesTable._meta.pagi... | identifier_body |
views.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (... | (self, table):
return getattr(self, "_more_%s" % table.name, False)
def get_images_data(self):
marker = self.request.GET.get(ImagesTable._meta.pagination_param, None)
try:
# FIXME(gabriel): The paging is going to be strange here due to
# our filtering after the fact.... | has_more_data | identifier_name |
main.js | //defining the searched words
var searchWord1 = 'seksuaaliset vähemmistöt';
var searchWord2 = 'lhbt';
$(function () {
// getting the pictures using finna api
function getPictures(pictureSearch1, pictureSearch2) {
console.log('getPictures');
$.ajax({
'url':
'https://api... | console.log('getPictures');
$.ajax({
'url': 'https://api.finna.fi/v1/search?lookfor=' + searchBook + '&filter[]=online_boolean:"1"&filter[]=format:"0/Book/',
'dataType': 'json',
'success': onGetBooks
});
}
function onGetBooks(obj) {
if (obj) {
var boo... | }
getPictures(searchWord1, searchWord2);
/*function getBooks(searchBook) { | random_line_split |
main.js |
//defining the searched words
var searchWord1 = 'seksuaaliset vähemmistöt';
var searchWord2 = 'lhbt';
$(function () {
// getting the pictures using finna api
function getPictures(pictureSearch1, pictureSearch2) {
console.log('getPictures');
$.ajax({
'url':
'https://ap... | lse {
console.log('Not found!');
}
//This function should be in two parts but I did not know how to do it....
var firstPictureUrl = 'https://api.finna.fi' + pictureAddress[0];
$('#carousel').append('<div class="item active" id="item"><img src="'
+ firstPictureUrl +... | var records = obj.records;
var pictureAddress = records.map(
function (rec) {
return rec.images;
}
);
console.log(pictureUrl);
} e | conditional_block |
main.js |
//defining the searched words
var searchWord1 = 'seksuaaliset vähemmistöt';
var searchWord2 = 'lhbt';
$(function () {
// getting the pictures using finna api
function ge | ictureSearch1, pictureSearch2) {
console.log('getPictures');
$.ajax({
'url':
'https://api.finna.fi/v1/search?lookfor=' + pictureSearch1 + '+OR+'
+ pictureSearch2 + '&filter[]=online_boolean:"1"&filter[]=format:"0/Image/',
'dataType': 'json',
... | tPictures(p | identifier_name |
main.js |
//defining the searched words
var searchWord1 = 'seksuaaliset vähemmistöt';
var searchWord2 = 'lhbt';
$(function () {
// getting the pictures using finna api
function getPictures(pictureSearch1, pictureSearch2) {
console.log('getPictures');
$.ajax({
'url':
'https://ap... | for (var i = 1; i < pictureAddress.length; i++) {
var pictureUrl = 'https://api.finna.fi' + pictureAddress[i];
console.log(pictureUrl);
$('#carousel').append('<div class="item"><img src="' + pictureUrl
+ '" alt="pic"></div>');
}
}
getPictures... |
if (obj) {
var records = obj.records;
var pictureAddress = records.map(
function (rec) {
return rec.images;
}
);
console.log(pictureUrl);
} else {
console.log('Not found!');
}
... | identifier_body |
android_calls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# 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 L... | """Formatter for Android call history events."""
DATA_TYPE = 'android:event:call'
FORMAT_STRING_PIECES = [
u'{call_type}',
u'Number: {number}',
u'Name: {name}',
u'Duration: {duration} seconds']
FORMAT_STRING_SHORT_PIECES = [u'{call_type} Call']
SOURCE_LONG = 'Android Call History'
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.