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 |
|---|---|---|---|---|
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... | } | random_line_split | |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
}
| main | identifier_name |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
} | identifier_body | |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca | */
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn main() {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
le... | MIT Licensed | random_line_split |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca
MIT Licensed
*/
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn | () {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
let mut dvdt: [f64; NX] = [0.0_f64;NX]; // acceleration of wave (y direction)
let mut dx: f64; ... | main | identifier_name |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca
MIT Licensed
*/
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn main() | }
x[(NX-1) as usize] = xmax;
// define t spacing
tmin = 0.0;
tmax = 10.0;
dt = (tmax-tmin)/((NT as f64)-1.0);
// instantiate y, x, dvdt arrays
// initialize arrays
// y is a peak in the middle of the wave
for i in 0..NX {
y[i as usize] = ( -(x[i as usize] - (xmax - xmin) / 2.0) * (x[i as usize] - (xm... | {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
let mut dvdt: [f64; NX] = [0.0_f64;NX]; // acceleration of wave (y direction)
let mut dx: f64; ... | identifier_body |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | {
Func = 0x70,
Extern = 0x6F,
}
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct TableType {
pub elem_type: RefType,
pub limits: Limits,
}
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct GlobalType {
pub value_... | RefType | identifier_name |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
Ok(())
}
}
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum LimitsRepr {
Min { min: u32 } = 0x00,
MinMax { min: u32, max: u32 } = 0x01,
}
encode_decode_as!(Limits, {
(Limits { min, max: None }) <=> (LimitsRepr::Min { min }),
(Limits { min, max: Some(max) }) <=> (LimitsRepr::Mi... | {
write!(f, "={}", max)?;
} | conditional_block |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | use crate::visit::Visit;
use crate::wasmbin_discriminants;
use arbitrary::Arbitrary;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
const OP_CODE_EMPTY_BLOCK: u8 = 0x40;
#[wasmbin_discriminants]
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
p... | use crate::io::{Decode, DecodeError, DecodeWithDiscriminant, Encode, PathItem, Wasmbin}; | random_line_split |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from... | (BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier'... | Command | identifier_name |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from... | 'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for... | random_line_split | |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from... | })
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for commune in AEntity.objects.filter(parent=c... | option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(o... | identifier_body |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from... | })
f.close()
| ogger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
... | conditional_block |
2.common.stories.tsx | import * as React from "react"; | import { storiesOf } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { ColorPicker } from '../components/color-picker';
import { withKnobs, text, boolean } from '@storybook/addon-knobs';
import { VectorStyleEditor } from '../components/vector-style-editor';
import "../styles/index.cs... | random_line_split | |
roles.js | var Router = require('koa-router');
var Role = require('../../lib/role');
var Middleware = require('../../lib/middleware');
var router = module.exports = new Router();
router.use(Middleware.allow('admin.roles'));
router.get('/admin/api/roles', function *() {
var page = parseInt(this.request.query.page) || 1;
var ... |
// Fetching a list with specific condition
var data = yield Role.list(conditions, _fields, _opts);
this.body = {
page: page,
perPage: perPage,
pageCount: Math.ceil(data.count / perPage),
roles: data.roles
};
});
router.post('/admin/api/roles', function *() {
if (!this.request.body.name || !this.reques... | {
_opts.populatedPermission = perms;
_fields.push('permissions');
} | conditional_block |
roles.js | var Router = require('koa-router');
var Role = require('../../lib/role');
var Middleware = require('../../lib/middleware');
var router = module.exports = new Router();
router.use(Middleware.allow('admin.roles'));
router.get('/admin/api/roles', function *() {
var page = parseInt(this.request.query.page) || 1;
var ... | // Setup options
var _opts = {
skip: (page - 1) * perPage,
limit: perPage
};
// Setup fields
var _fields = [
'name',
'desc',
'created'
];
if (perms) {
_opts.populatedPermission = perms;
_fields.push('permissions');
}
// Fetching a list with specific condition
var data = yield Role.list(condit... | var conditions = {};
if (q.name) {
conditions.name = new RegExp(q.name, 'i');
}
| random_line_split |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtool... |
else:
url = '/'
return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_selected_entry(self):
data = self.get_cleaned_data_for_step('0')
return wizard_pool.get_entry(data['entry'])
def get_origin_page(self):
data = self.get_cle... | try:
url = page.get_absolute_url(language)
except NoReverseMatch:
url = '/' | conditional_block |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtool... |
def get_form_kwargs(self, step=None):
"""This is called by self.get_form()"""
kwargs = super(WizardCreateView, self).get_form_kwargs()
kwargs['wizard_user'] = self.request.user
if self.is_second_step(step):
kwargs['wizard_page'] = self.get_origin_page()
kwar... | if step is None:
step = self.steps.current
# We need to grab the page from pre-validated data so that the wizard
# has it to prepare the list of valid entries.
if data:
page_key = "{0}-page".format(step)
self.page_pk = data.get(page_key, None)
else:
... | identifier_body |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtool... | ]
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_active or not user.is_staff:
raise PermissionDenied
self.site = get_current_site()
return super(WizardCreateView, self).dispatch(*args, **kwargs)
def get_current_step(self):
... | random_line_split | |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtool... | (SessionWizardView):
template_name = 'cms/wizards/start.html'
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'wizard_tmp_files'))
form_list = [
('0', WizardStep1Form),
# Form is used as a placeholder form.
# the real form will be loaded after st... | WizardCreateView | identifier_name |
googleAnalyticsAdapter_spec.js | import ga from 'modules/googleAnalyticsAdapter.js';
var assert = require('assert');
describe('Ga', function () {
describe('enableAnalytics', function () {
var cpmDistribution = function(cpm) {
return cpm <= 1 ? '<= 1$' : '> 1$';
}
var config = { options: { trackerName: 'foo', enableDistribution: t... |
it('should use the custom cpm distribution', function() {
assert.equal(ga.getCpmDistribution(0.5), '<= 1$');
assert.equal(ga.getCpmDistribution(1), '<= 1$');
assert.equal(ga.getCpmDistribution(2), '> 1$');
assert.equal(ga.getCpmDistribution(5.23), '> 1$');
});
});
}); | assert.equal(output, 'foo.send');
}); | random_line_split |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// u... | () {
scope.$apply(() => {
map.getView().setZoom(4);
});
}
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: ... | test | identifier_name |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// u... |
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0)).toBe(500);
// @ts-ignore: s... | {
scope.$apply(() => {
map.getView().setZoom(4);
});
} | identifier_body |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// u... | }),
});
element = angular.element('<div ngeo-scaleselector ngeo-scaleselector-map="map"></div>');
// Silent warnings throw by the ngeo-scaleselector component.
const logWarnFn = console.warn;
console.warn = () => {};
angular.mock.inject(($rootScope, $compile, $sce) => {
$rootScope... | map = new olMap({
view: new olView({
center: [0, 0],
zoom: 0, | random_line_split |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spac... | ():
"""temporary workaround to return a macOS version as a Version object
"""
return Version(py_platform.mac_ver()[0])
def macos_sdk_path():
"""Return SDK path
"""
xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
... | macos_version | identifier_name |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spac... | return self.name | identifier_body | |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spac... | xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
"""This class represents the macOS operating system. This will be
auto detected using the python platform.mac_ver. The macOS
platform will be represented using the major versio... | """ | random_line_split |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class ... | {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return {
'detail': value.detail,
'code': value.code,
};
} | identifier_body | |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class ... |
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export function JwtTokenErrorToJSON(value?: JwtTokenError | null): any {
if (value === undefined) {
return undefined;
}
if (value... | {
return json;
} | conditional_block |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class ... | (json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) {
return json;
}
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export functi... | JwtTokenErrorFromJSONTyped | identifier_name |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class ... |
export function JwtTokenErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) {
return json;
}
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefi... | }
export function JwtTokenErrorFromJSON(json: any): JwtTokenError {
return JwtTokenErrorFromJSONTyped(json, false);
} | random_line_split |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);... |
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bin... | {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
} | conditional_block |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);... |
export { graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map
| {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql",
});
} | identifier_body |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
| (request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;
// Maintains proper stack trace (only... | constructor | identifier_name |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);... | return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
... | // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
} | random_line_split |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
... |
this.dirty = false;
return this;
}
destroy () {
this.position.destroy();
this.scale.destroy();
this.local = undefined;
}
}
| {
this.local[4] = this.position[0];
this.local[5] = this.position[1];
} | conditional_block |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
... | () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this.scale[0];
this.local[1] = 0;
this.local[2] = 0;
thi... | setDirty | identifier_name |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
... |
disableImmediateUpdates () {
this.immediate = false;
this.dirty = true;
return this;
}
enableInterpolation () {
this.interpolate = true;
this.position.reset(this.position.x, this.position.y);
this.scale.reset(this.scale.x, this.scale.y);
retur... | {
this.immediate = true;
return this;
} | identifier_body |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
... | this.interpolate = false;
return this;
}
setDirty () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this... | disableInterpolation () {
| random_line_split |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
ret... |
class ILGLinesMismatchError(ParseError):
"""
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines)... | self.details += '({}, {} words) '.format(k, len(v))
self.details += ' '.join(str(x) for x in v) + '\n' | conditional_block |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
ret... | (PGError):
"""
Exception for when a problem arises while loading in the corpus.
"""
pass
class DelimiterError(PGError):
"""
Exception for mismatch between specified delimiter and the actual text
when loading in CSV files and transcriptions.
"""
pass
class ILGError(ParseError):
... | CorpusIntegrityError | identifier_name |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
ret... |
class TextGridError(ParseError):
"""
Exception class for parsing TextGrids
"""
pass
class TextGridTierError(TextGridError):
"""
Exception for when a specified tier was not found in a TextGrid.
Parameters
----------
tier_type : str
The type of tier looked for (such as sp... | """
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines):
self.main = "There doesn't appear to b... | identifier_body |
exceptions.py | # Base exception classes
| Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
return self.value
# Context Manager exceptions
class PGContext... | class PGError(Exception):
""" | random_line_split |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub cons... |
/// Tests if next table exists and allocates a new one if not
fn create_next_table<T: FrameAlloc>(allocator: &mut T, address: u64, index: isize) -> u64 {
let mut entry = Page::get_table(address, index);
if (entry & PRESENT) != 0 {
} else {
let frame = allocator.alloc();
... | } | random_line_split |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub cons... | else {
let frame = allocator.alloc();
unsafe {
*Page::get_table_mut(address, index) = (frame.unwrap().number * PAGE_SIZE) |
PRESENT |
WRITABLE;
}
... | {
} | conditional_block |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub cons... |
}
| {
// Entry in P4 (P3 location)
let p4_entry = Page::create_next_table(allocator, P4, self.p4_index() as isize);
// Entry in P3 (P2 location)
let p3_entry = Page::create_next_table(allocator,
p4_entry & NO_FLAGS,
... | identifier_body |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub cons... | (physical_addr: u64, flags: u64, address: u64, index: isize) {
unsafe {
*Page::get_table_mut(address, index) = (physical_addr * PAGE_SIZE) | flags;
}
}
/// Create page tables and allocate page
///
/// This function walks through the page tables. If the next table is present,... | create_page | identifier_name |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# 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 t... | mac = line.split()[1]
except IndexError as e:
print(line)
print(e)
header.append(mac)
elif line.startswith(" inet"):
name, mac = header
ipver, ipaddr = line.split()[:2]
ipaddr, prefixlen = ipaddr.split... | try: | random_line_split |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# 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 t... | state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"):
try:
mac = line.split()[1]
except IndexError as e:
print(line)
... | """
parse output of command ip a(ddr) s(how)
return - list of tuple (name, ipver, ipaddr, prefixlen: int, mac)
"""
state = "start"
header = list()
ret = list()
for line in out.split('\n'):
if line and line[0] != ' ':
state = "start"
header = list()
... | identifier_body |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# 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 t... | ():
return MySQLdb.connect(host="localhost", user="root", db="box_utf8")
| connect_to_db | identifier_name |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# 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 t... |
header = list()
nic_name = line.split(':')[1].strip()
header.append(nic_name)
state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"):
t... | continue | conditional_block |
utils.js | /*!
* Jade - utils
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Convert interpolation in the given string to JavaScript.
*
* @param {String} str
* @return {String}
* @api private
*/
var interpolate = exports.interpolate = function(str){
return str.replace(/(\\)?([#!]){(.... | exports.merge = function(a, b) {
for (var key in b) a[key] = b[key];
return a;
}; | */
| random_line_split |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum | # class PlatinumInline(admin.StackedInline):
# model=Platinum
# class GoldInline(admin.StackedInline):
# model=Gold
# class SilverInline(admin.StackedInline):
# model=Silver
# class BronzeInline(admin.StackedInline):
# model=Bronze
class LevelInline(admin.StackedInline):
model=Level
class AchievementAdmin(a... | from achievs.models import Level
| random_line_split |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum
from achievs.models import Level
# class PlatinumInline(admin.StackedInline):
# model=Platinum
# cla... | (admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fields=['name... | AchievementAdmin | identifier_name |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum
from achievs.models import Level
# class PlatinumInline(admin.StackedInline):
# model=Platinum
# cla... |
# admin.site.register(Gold)
# admin.site.register(Silver)
# admin.site.register(Bronze)
# admin.site.register(Platinum)
admin.site.register(Level)
admin.site.register(Achievement, AchievementAdmin) | fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fields=['name']
date_hierarchy='p... | identifier_body |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "... |
def analyze(self, item):
first_seen = item["first_seen_utc"]
ioc_value = item["ioc_value"]
ioc_type = item["ioc_type"]
threat_type = item["threat_type"]
malware_alias = item["malware_alias"]
malware_printable = item["malware_printable"]
last_seen_utc = item[... | r = self._make_request(sort=False)
if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
... | identifier_body |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class | (Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "https://threatfox.abuse.ch/export/json/recent/",
"description": "Feed ThreatFox by Abuse.ch",
}
def update(self):
for index, line in self.update_json():
self.anal... | ThreatFox | identifier_name |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "... |
except ObservableValidationError as e:
logging.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags
| obs = Observable.add_text(ioc_value) | conditional_block |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "... | if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
if self.last_run:
... | def update_json(self):
r = self._make_request(sort=False)
| random_line_split |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player... | def _fetch_image(self, current):
albuminfo = {
"artist": current.albumartist,
"album": current.album,
"file": current.file
}
def callback(result, song):
if "filename" in result and self.status.current == song:
image = load_imag... | random_line_split | |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player... | (self, image, current):
def blur_callback(result, song):
if "image" in result and self.status.current == song:
shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade)
image_rect = Rect((0, 0), image.get_size())
screen_rect... | _update_background_image | identifier_name |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player... |
image_rect = Rect((0, 0), image.get_size())
screen_rect = Rect((0, 0), self.dialog.size)
cropped = crop(image, screen_rect.fit(image_rect))
self.imagefilter.blur(cropped, 15, blur_callback, [current])
def _fetch_image(self, current):
albuminfo = {
"artist": cu... | shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade) | conditional_block |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player... |
def current_changed(self, mpd_status, current):
self._update()
def _finish_dialog(self):
self.status.remove_listener(self)
class MpdInfoDialogFactory(DialogFactory):
def create(self, element, widget_registry):
path = module_relative_path("info.xml")
dialog = self.contex... | self.status.add_listener(self)
self._update() | identifier_body |
EffectComposer.js | /**
* @author alteredq / http://alteredqualia.com/
*/
THREE.EffectComposer = function ( renderer, renderTarget ) {
this.renderer = renderer;
if ( renderTarget === undefined ) {
var width = window.innerWidth || 1;
var height = window.innerHeight || 1;
var parameters = { minFilter: THREE.LinearFilter, magFi... |
},
insertPass: function ( pass, index ) {
this.passes.splice( index, 0, pass );
},
render: function ( delta ) {
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
var maskActive = false;
var pass, i, il = this.passes.length;
for ( i = 0; i < il; i ++ ) {
pass = thi... |
addPass: function ( pass ) {
this.passes.push( pass ); | random_line_split |
res_currency.py | from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _ |
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {}
res = {}
if 'date' in context:
date = context['date']
else:
... | random_line_split | |
res_currency.py |
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = ... |
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
round=True, currency_rate_type_from=False, currency_rate | if context is None:
context = {}
ctx = context.copy()
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from')})
from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to')})
... | identifier_body |
res_currency.py |
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = ... |
raise osv.except_osv(_('Error'), _('No rate found \n' \
'for the currency: %s \n' \
'at the date: %s') % (currency_symbol, date))
return to_currency.rate/from_currency.rate
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
... | currency_symbol = to_currency.symbol | conditional_block |
res_currency.py | from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {... | (self, cr):
# CONSTRAINT/UNIQUE INDEX on (name,company_id)
# /!\ The unique constraint 'unique_name_company_id' is not sufficient, because SQL92
# only support field names in constraint definitions, and we need a function here:
# we need to special-case company_id to treat all NULL comp... | init | identifier_name |
test_xor_clasification_demo_v2.py | # Dependencias Internas
import numpy as np
import matplotlib.pyplot as plt
# Dependencias Externas
from cupydle.dnn.NeuralNetwork import NeuralNetwork
from cupydle.dnn.data import LabeledDataSet as dataSet
# Seteo de los parametros
capa_entrada = 2
capa_oculta_1 = 3
capa_salida = 2
capas = [capa_entrada, capa_oculta_... |
# -------------------------------- ENTRENAMIENTO --------------------------------------------#
tmp = datos_trn
cantidad = len(tmp)
porcentaje = 80
datos_trn = tmp[0: int(cantidad * porcentaje / 100)]
datos_vld = tmp[int(cantidad * porcentaje / 100 + 1):]
print("Training Data size: " + str(len(datos_trn)))
print("Val... | salida_tst_tmp[0][l] = 1.0
datos_tst = [(x, y) for x, y in zip(entrada_tst, salida_tst_tmp.transpose())] | random_line_split |
test_xor_clasification_demo_v2.py | # Dependencias Internas
import numpy as np
import matplotlib.pyplot as plt
# Dependencias Externas
from cupydle.dnn.NeuralNetwork import NeuralNetwork
from cupydle.dnn.data import LabeledDataSet as dataSet
# Seteo de los parametros
capa_entrada = 2
capa_oculta_1 = 3
capa_salida = 2
capas = [capa_entrada, capa_oculta_... |
datos_tst = [(x, y) for x, y in zip(entrada_tst, salida_tst_tmp.transpose())]
# -------------------------------- ENTRENAMIENTO --------------------------------------------#
tmp = datos_trn
cantidad = len(tmp)
porcentaje = 80
datos_trn = tmp[0: int(cantidad * porcentaje / 100)]
datos_vld = tmp[int(cantidad * porcen... | if salida_tst[l] < 0.0:
salida_tst_tmp[0][l] = 0.0
else:
salida_tst_tmp[0][l] = 1.0 | conditional_block |
Header.styles.ts | import { CSSObject } from '@emotion/react';
import { theme } from '../../theme';
const styles: Record<string, CSSObject> = {
root: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
overflow: 'hidden',
borderBottom: `1px solid ${theme.color.border}`,
height: 36,
li... | lineHeight: '50px'
}
},
title: {
display: 'block',
margin: 0,
padding: '0 10px',
fontSize: 16,
fontFamily: theme.typography.content,
color: theme.color.headings,
whiteSpace: 'nowrap',
letterSpacing: 0,
textTransform: 'none',
textShadow: 'none',
[theme.breakpoin... | random_line_split | |
script_task.rs | a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop... | parent_page.children.deref().borrow_mut().push(Rc::new(new_page));
}
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for ... | {
debug!("Script: new layout: {:?}", new_layout_info);
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let mut page = self.page.borrow_mut();
let parent_page = page.find(old_pipeli... | identifier_body |
script_task.rs | which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
... | handle_exit_window_msg | identifier_name | |
script_task.rs | _id: PipelineId, url: Url) {
debug!("ScriptTask: loading {:?} on page {:?}", url, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. Thi... | node.deref().set_hover_state(false);
}
}
None => {} | random_line_split | |
app.js | 'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module,
favicon = require('serve-favicon'),
express = require('express');
var System = new Module('system');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
System.register(func... | }); | random_line_split | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: ... |
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(Local... | {
return defaultLocaleData.locale;
} | conditional_block |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: ... | {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'f... | identifier_body | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: ... | return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] ... | random_line_split | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: ... | () {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(th... | getLocaleCode | identifier_name |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback i... | inventory = ['172.18.0.2']
ansible_api = Runner(inventory, 'krahser')
ansible_api.add_setup(inventory)
ansible_api.passwords = {'conn_pass': 'root'}
ansible_api.add_plays('Add ssh key', inventory, [
{'action': u'authorized_key',
'args':
{
u'user': u'root',
... | conditional_block | |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback i... | authorized_key = [{'action': u'authorized_key',
'args': {
u'user': unicode(user),
u'state': u'present',
u'key': unicode(key)
},
}]
ansible_api.add_plays('Add ssh key', hosts, authorized_... | def copy_key(hosts, key, user, password):
key = Config.KEYS + key + ".pub"
key = "{{ lookup('file', '" + key + "' ) }}"
ansible_api = Runner(hosts, user)
ansible_api.passwords = {'conn_pass': password} | random_line_split |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback i... | (hosts, user="root", private_key_file=None):
"""run ansible setup on hosts"""
key = Config.KEYS + private_key_file
ansible_game = Runner(hosts, remote_user=user,
private_key_file=key)
ansible_game.add_setup(hosts)
ansible_game.run()
response = ansible_game.callback.get_... | ansible_status | identifier_name |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback i... |
class ThreadRunner(threading.Thread):
def __init__(self, machines, playbook, user, room, username,
private_key="id_rsa",
setup=False):
threading.Thread.__init__(self)
self.room = room
self.username = username
self.machines = machines
self... | tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.vmanager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
... | identifier_body |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) {
if... | ,
],
['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'IRR', 'IRR', plural
];
//# sourceMappingURL=ckb-IR.js.map | random_line_split | |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) |
export default [
'ckb-IR',
[
['ب.ن', 'د.ن'],
,
],
,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
,
['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش']
... | {
if (n === 1)
return 1;
return 5;
} | identifier_body |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n) {
if (n === 1)
return 1;
return 5;
}
export default [
'ckb-IR',
[
['ب.ن', 'د.ن'],
,
],
,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
... | plural | identifier_name |
ja-JP.ts | import callingOptions from 'ringcentral-integration/modules/CallingSettings/callingOptions';
export default {
title: '通話',
[callingOptions.softphone]: '{brand} for Desktop',
[callingOptions.myphone]: '自分の{brand}電話',
[callingOptions.otherphone]: 'その他の電話',
[callingOptions.customphone]: 'カスタム電話',
[callingOptio... | // @key: @#@"ringoutHint"@#@ @source: @#@"Ring me at my location first, then connect the called party"@#@
// @key: @#@"myLocationLabel"@#@ @source: @#@"My Location"@#@
// @key: @#@"press1ToStartCallLabel"@#@ @source: @#@"Prompt me to dial 1 before connecting the call"@#@
// @key: @#@"[`${callingOptions.browser}Tooltip`... | random_line_split | |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_m... |
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def get_player(self):
for sprite in self.sprites:
if isinstance(... | has_no_enemies = False | conditional_block |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_m... | (self):
for sprite in self.sprites:
if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage)
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage)
| get_player | identifier_name |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_m... |
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage) | if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage) | random_line_split |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_m... |
def has_won(self):
has_no_enemies = True
for sprite in self.sprites:
if isinstance(sprite, Collectible):
has_no_enemies = False
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def rende... | self.sprites.update(delta_time, self.tiled_map)
self.player.handle_collision(self.collectibles, self.collideables)
if not self.player.alive():
self.reset()
if self.has_completed_minigame():
self.previous.open_secured_door()
self.switch_to_scene(self.previous... | identifier_body |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
... |
self.db.commit()
return success
| cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, -amount]) | conditional_block |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
... | (self, token, amount):
cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE... | deposit | identifier_name |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
... |
def withdraw(self, token, amount):
"""Remove the given amount from the token's balance."""
cursor = self.db.cursor()
cursor.execute("""
UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
... | cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE balances SET amount = amount +... | identifier_body |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
... | UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
success = (cursor.rowcount == 1)
if success:
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
... |
cursor = self.db.cursor()
cursor.execute(""" | random_line_split |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url... |
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
self.version = json_block['version']
self.block_hash = json_block['hash']
class Block_BlockR(Blocks):
def __init__(self):
BLOCKR_API = 'https://btc.blockr.io/api/'
... | TOSHI_API = 'https://bitcoin.toshi.io/api'
self.url = TOSHI_API + "/v0/blocks/{}" | random_line_split |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url... | def __init__(self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['v... | identifier_body | |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url... | (self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['version']
... | __init__ | identifier_name |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
|
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url(self, url):
try:
return urlopen(url).read().decode('utf-8')
exce... | from urllib.request import urlopen | conditional_block |
icon-dropdown-menu.tsx | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import PopupMenu from 'components/popup-menu';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
import { SlateCo... | declare context: React.ContextType<typeof SlateContext>;
render(): React.ReactNode {
return (
<PopupMenu customRender={this.renderButton} direction='right'>
{() => (
<div className='simple-menu simple-menu--popup-menu-compact'>
{this.props.menuOptions.map(this.renderMenuItem... | static contextType = SlateContext; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.