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
service.py
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
else: return response def DeleteContact(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an event with the specified ID from Google Contacts. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google...
return gdata.contacts.ContactEntryFromString(response.ToString())
conditional_block
service.py
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
class ContactsService(gdata.service.GDataService): """Client for the Google Contats service.""" def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None): gdata.service.GDataService.__init__(self, email=email, password=passwor...
pass
identifier_body
Directory.js
{ 'use strict'; const fs = require('fs'); const path = require('path'); class _MkPath { constructor(dir) { this._stack = []; this._dir = dir; } _mkPath() { fs.mkdir(this._dir, (err) => { if (err && 'EEXIST' !== err.code) { if ('ENOENT' === err.code) { ...
// 成功写入 callback && callback(); }); }, walk: function(dir) { return new _Walk(dir)._walk(); } }; }
this.mkPath(path.dirname(file), (err) => { if (err) { callback && callback(err); return; } fs.writeFile(file, content, callback); }); }
conditional_block
Directory.js
{ 'use strict'; const fs = require('fs'); const path = require('path'); class _MkPath { constructor(dir) { this._stack = []; this._dir = dir; } _mkPath() { fs.mkdir(this._dir, (err) => { if (err && 'EEXIST' !== err.code) { if ('ENOENT' === err.code) { ...
} fs.writeFile(file, content, callback); }); } // 成功写入 callback && callback(); }); }, walk: function(dir) { return new _Walk(dir)._walk(); } }; }
if (err && 'ENOENT' === err.code) { this.mkPath(path.dirname(file), (err) => { if (err) { callback && callback(err); return;
random_line_split
Directory.js
{ 'use strict'; const fs = require('fs'); const path = require('path'); class _MkPath { constructor(dir) { this._stack = []; this._dir = dir; } _mkPath() { fs.mkdir(this._dir, (err) => { if (err && 'EEXIST' !== err.code) { if ('ENOENT' === err.code) { ...
(dir = '.') { return new Promise((resolve, reject) => { // read dir fs.readdir(path.join(this._root, dir), (err, files) => { err ? reject(err) : resolve(files); }); }) .then((fileList) => { // get file stat fileList = fileList.map((item) => { ...
_walk
identifier_name
Directory.js
{ 'use strict'; const fs = require('fs'); const path = require('path'); class _MkPath { constructor(dir)
_mkPath() { fs.mkdir(this._dir, (err) => { if (err && 'EEXIST' !== err.code) { if ('ENOENT' === err.code) { let dirObj = path.parse(this._dir); this._stack.push(dirObj.name); this._dir = dirObj.dir; return this._mkPath(); } ...
{ this._stack = []; this._dir = dir; }
identifier_body
online_accounts.py
#! /usr/bin/env python3 from collections import OrderedDict import datetime import os import sys import textwrap from plaid import Client from plaid import errors as plaid_errors import plaid2text.config_manager as cm from plaid2text.interact import prompt, clear_screen, NullValidator from plaid2text.interact import...
self.client = Client(self.client_id, self.secret, "development", suppress_warnings=True) def get_transactions(self, access_token, start_date, end_date, account_ids): """Get transaction for a given ...
self.client_id, self.secret = cm.get_plaid_config()
conditional_block
online_accounts.py
#! /usr/bin/env python3 from collections import OrderedDict import datetime import os import sys import textwrap from plaid import Client from plaid import errors as plaid_errors import plaid2text.config_manager as cm from plaid2text.interact import prompt, clear_screen, NullValidator from plaid2text.interact import...
(): def __init__(self, client_id=None, secret=None): if client_id and secret: self.client_id = client_id self.secret = secret else: self.client_id, self.secret = cm.get_plaid_config() self.client = Client(self.client_id, self.secret, "development", suppre...
PlaidAccess
identifier_name
online_accounts.py
#! /usr/bin/env python3 from collections import OrderedDict import datetime import os import sys import textwrap from plaid import Client from plaid import errors as plaid_errors import plaid2text.config_manager as cm from plaid2text.interact import prompt, clear_screen, NullValidator from plaid2text.interact import...
offset=len(ret)) except plaid_errors.ItemError as ex: print("Unable to update plaid account [%s] due to: " % account_ids, file=sys.stderr) print(" %s" % ex, file=sys.stderr ) sys.exit(1) total_transactions = resp...
"""Get transaction for a given account for the given dates""" ret = [] total_transactions = None page = 0 account_array = [] account_array.append(account_ids) while True: page += 1 if total_transactions: print("Fetching page %d, a...
identifier_body
online_accounts.py
#! /usr/bin/env python3 from collections import OrderedDict import datetime import os import sys import textwrap from plaid import Client from plaid import errors as plaid_errors import plaid2text.config_manager as cm from plaid2text.interact import prompt, clear_screen, NullValidator from plaid2text.interact import...
if total_transactions: print("Fetching page %d, already fetched %d/%d transactions" % ( page, len(ret), total_transactions)) else: print("Fetching page 1") try: response = self.client.Transactions.get( a...
while True: page += 1
random_line_split
__init__.py
################################################################## # Copyright 2018 Open Source Geospatial Foundation and others # # licensed under MIT, Please consult LICENSE.txt for details # ################################################################## from pywps import Process from pywps.inout import L...
def __init__(self): self.add_input(LiteralInput()) class UltimateQuestion(Process): def __init__(self): super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', title='Ultimate Question', outputs=[LiteralOutput('outv...
random_line_split
__init__.py
################################################################## # Copyright 2018 Open Source Geospatial Foundation and others # # licensed under MIT, Please consult LICENSE.txt for details # ################################################################## from pywps import Process from pywps.inout import L...
a_string = request.inputs['string'][0].data response.outputs['string'].data = "".format(a_string) return response
identifier_body
__init__.py
################################################################## # Copyright 2018 Open Source Geospatial Foundation and others # # licensed under MIT, Please consult LICENSE.txt for details # ################################################################## from pywps import Process from pywps.inout import L...
(self): super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', title='Ultimate Question', outputs=[LiteralOutput('outvalue', 'Output Value', data_type='string')]) @staticmethod def _handler(request, response): respo...
__init__
identifier_name
analysis-form-view.spec.js
var Backbone = require('backbone'); var camshaftReference = require('builder/data/camshaft-reference'); var areaOfInfluenceTemplate = require('builder/editor/layers/layer-content-views/analyses/analysis-form-models/area-of-influence-form.tpl'); var BaseAnalysisFormModel = require('builder/editor/layers/layer-content-vi...
expect(camshaftReference.validate).not.toHaveBeenCalled(); }); describe('when form changes with erroneous data', function () { beforeEach(function () { camshaftReference.validate.and.returnValue({radius: '42 is not the answer, you fool!'}); // simulate change this.view._formView.setValue...
random_line_split
generators.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete use std::marker::Unpin; use std::ops::{Generator, GeneratorState}; use std::pin::Pin; enum YieldOrReturn<Y, R> { Yield(Y), Retur...
<T>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERROR item has unused generic parameters || { //~^ ERROR item has unused generic parameters yield 1; 2 } } #[rustc_polymorphize_error] pub fn used_type_in_yield<Y: Default>() -> impl Generator<(), Yield = Y, Retur...
unused_type
identifier_name
generators.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete use std::marker::Unpin; use std::ops::{Generator, GeneratorState}; use std::pin::Pin; enum YieldOrReturn<Y, R> { Yield(Y), Retur...
} #[rustc_polymorphize_error] pub fn used_type_in_return<R: Default>() -> impl Generator<(), Yield = u32, Return = R> + Unpin { || { yield 3; R::default() } } #[rustc_polymorphize_error] pub fn unused_const<const T: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERR...
random_line_split
stringify-mark.js
const test = require('tape'); const Mark = require('./../mark.js'); function
(str) { var buffer = new ArrayBuffer(str.length); var bytes = new Uint8Array(buffer); str.split('').forEach(function(str, i) { bytes[i] = str.charCodeAt(0); }); return buffer; } test('Stringify JSON object', function(assert) { assert.equal(Mark.stringify(Mark.parse(`{a:12.4, b:true...
stringArrayBuffer
identifier_name
stringify-mark.js
const test = require('tape'); const Mark = require('./../mark.js'); function stringArrayBuffer(str) { var buffer = new ArrayBuffer(str.length); var bytes = new Uint8Array(buffer); str.split('').forEach(function(str, i) { bytes[i] = str.charCodeAt(0); }); return buffer; } test('St...
// stringify base85 data var bin = stringArrayBuffer('hello'); bin.encoding = 'a85'; assert.equal(Mark.stringify(bin), "[#~BOu!rDZ~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~\n@p\ns7\ntD.3~]")), "[#~@ps7tD.3~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~ @<5pm \rBfIs ~]")), ...
assert.equal(Mark.stringify(stringArrayBuffer('Hello worlds!')), '[#SGVsbG8gd29ybGRzIQ==]', "Stringify binary data 'Hello worlds!'"); var doc = Mark('doc', {mime:'text/html', data:stringArrayBuffer("<h1>Mark binary!</h1>")}); assert.equal(Mark.stringify(doc), '{doc mime:"text/html" data:[#PGgxPk1hcmsgYmluYXJ5ITwva...
random_line_split
stringify-mark.js
const test = require('tape'); const Mark = require('./../mark.js'); function stringArrayBuffer(str)
test('Stringify JSON object', function(assert) { assert.equal(Mark.stringify(Mark.parse(`{a:12.4, b:true, c:false, d:'str', e:null, g:1, h:[1,2,3], i:-12, j:[], k:{}, l:'', m:"", n:0, p:1e-2}`)), `{a:12.4 b:true c:false d:"str" e:null g:1 h:[1 2 3] i:-12 j:[] k:{} l:"" m:"" n:0 p:0.01}`, "Stringify JSON objec...
{ var buffer = new ArrayBuffer(str.length); var bytes = new Uint8Array(buffer); str.split('').forEach(function(str, i) { bytes[i] = str.charCodeAt(0); }); return buffer; }
identifier_body
success.js
(function($){ $(function(){ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document,...
{ if(camName != "") { FB.api('/' + holdingvalue[0] + '/tabs/app_'+idApp, 'post', { access_token: holdingvalue[1], custom_name: camName ...
}, function (response) { // alert(JSON.stringify(response)); if(JSON.stringify(response))
random_line_split
success.js
(function($){ $(function(){ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document,...
//alert(camName); $.ajax({ type : "POST", url : base_url+"/frontend/linkforfb", data : {appId : 'appId',pageId : holdingvalue[0],camName : 'pageTab',tempName : encoded}, success : function (data) { var idApp = data.trim(); FB.a...
{ // alert(value); var tempName = tempName; var encoded = ""; var i; for (i=0; i<tempName.length;i++) { var a = tempName.charCodeAt(i); var b = a ^ 123; // bitwise XOR with any number, e.g. 123 encoded = encoded+String.fromCharCode(b); } var holdingvalue =...
identifier_body
success.js
(function($){ $(function(){ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document,...
(appId,pageId,accessToken) { //alert(appId+" $$$$$ "+pageId); FB.api("/"+pageId+"/tabs","GET",{ "access_token" : accessToken, }, function (response) { //console.log(response); for(var i=2;i<response.data.length; i++) { if(typeof response.data[i].application != ...
fetchPage2
identifier_name
success.js
(function($){ $(function(){ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document,...
}); // fetchPage2(idApp,holdingvalue[0],holdingvalue[1]); } } } ); } }); } function fetchPage2(appId,pageId,accessToken) { //alert(appId+" $$$$$ "+pageI...
{ FB.api('/' + holdingvalue[0] + '/tabs/app_'+idApp, { access_token: holdingvalue[1], }, function(response){ if(JSON.stringify(response)){ FB.api('/' + holdingvalue...
conditional_block
env.rs
use std::process::Command; use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); asser...
#[test] fn test_unset_variable() { // This test depends on the HOME variable being pre-defined by the // default shell let po = Command::new(PROGNAME) .arg("-u") .arg("HOME") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).u...
{ let po = Command::new(PROGNAME) .arg("-i") .arg("--null") .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, "FOO=bar\0ABC=xyz\0"); }
identifier_body
env.rs
use std::process::Command; use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); asser...
() { // This test depends on the HOME variable being pre-defined by the // default shell let po = Command::new(PROGNAME) .arg("-u") .arg("HOME") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.line...
test_unset_variable
identifier_name
env.rs
use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert!(out.lines_any().any(|lin...
use std::process::Command;
random_line_split
rand.js
/* global padlock */ padlock.rand = (function() { "use strict"; var chars = { numbers: "0123456789", lower: "abcdefghijklmnopqrstuvwxyz", upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", other: "/+()%\"=&-!:'*#?;,_.@`~$^[{]}\\|<>" }; var charSets = { full: chars.numbers + ...
(length, charSet) { length = length || 32; charSet = charSet || charSets.full; var rndm = ""; while (rndm.length < length) { rndm += randomItem(charSet); } return rndm; } return { randomString: randomString }; })();
randomString
identifier_name
rand.js
/* global padlock */ padlock.rand = (function() { "use strict"; var chars = { numbers: "0123456789", lower: "abcdefghijklmnopqrstuvwxyz", upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", other: "/+()%\"=&-!:'*#?;,_.@`~$^[{]}\\|<>" }; var charSets = { full: chars.numbers + ...
//* Creates a random string with a given _length_ comprised of given set or characters function randomString(length, charSet) { length = length || 32; charSet = charSet || charSets.full; var rndm = ""; while (rndm.length < length) { rndm += randomItem(charSet); ...
{ return choices[Math.floor(Math.random()*choices.length)]; }
identifier_body
rand.js
/* global padlock */ padlock.rand = (function() { "use strict"; var chars = { numbers: "0123456789", lower: "abcdefghijklmnopqrstuvwxyz", upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", other: "/+()%\"=&-!:'*#?;,_.@`~$^[{]}\\|<>" }; var charSets = { full: chars.numbers + ...
return rndm; } return { randomString: randomString }; })();
{ rndm += randomItem(charSet); }
conditional_block
rand.js
/* global padlock */ padlock.rand = (function() { "use strict"; var chars = { numbers: "0123456789", lower: "abcdefghijklmnopqrstuvwxyz", upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", other: "/+()%\"=&-!:'*#?;,_.@`~$^[{]}\\|<>" }; var charSets = { full: chars.numbers + ...
} return { randomString: randomString }; })();
return rndm;
random_line_split
_document.tsx
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document' import classnames from 'classnames' class MyDocument extends Document { static async
(ctx: DocumentContext) { const initialProps = await Document.getInitialProps(ctx) return { ...initialProps } } render() { const pageProps = this.props?.__NEXT_DATA__?.props?.pageProps const appWrapperClasses = classnames( 'app-wrapper', pageProps?.serverCookies?.lightMode ? 'theme-light...
getInitialProps
identifier_name
_document.tsx
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document' import classnames from 'classnames' class MyDocument extends Document { static async getInitialProps(ctx: DocumentContext) { const initialProps = await Document.getInitialProps(ctx) return { ...initialProps } } rende...
} export default MyDocument
</Html> ) }
random_line_split
windowToggle.d.ts
import { Observable } from '../Observable'; import { OperatorFunction } from '../types'; /** * Branch out the source Observable values as a nested Observable starting from * an emission from `openings` and ending when the output of `closingSelector` * emits. * * <span class="informal">It's like {@link bufferToggle...
* @see {@link bufferToggle} * * @param {Observable<O>} openings An observable of notifications to start new * windows. * @param {function(value: O): Observable} closingSelector A function that takes * the value emitted by the `openings` observable and returns an Observable, * which, when it emits (either `next` ...
random_line_split
index.d.ts
// Type definitions for csso 3.5 // Project: https://github.com/css/csso // Definitions by: Christian Rackerseder <https://github.com/screendriver> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 declare namespace csso { interface Result { /** * Result...
* Generate a source map when true. * @default false */ sourceMap?: boolean; /** * Filename of input CSS, uses for source map generation. * @default '<unknown>' */ filename?: string; /** * Output debug information to stderr. ...
logger?: () => void; } interface MinifyOptions { /**
random_line_split
Matrix.ts
translate each point along the y axis. */ constructor(a:number = 1, b:number = 0, c:number = 0, d:number = 1, tx:number = 0, ty:number = 0) { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; } /** * The value that affects...
deltaTransformPoint
identifier_name
Matrix.ts
= this.ty = 0; } /** * Performs the opposite transformation of the original matrix. You can apply an inverted matrix to an object to * undo the transformation performed when applying the original matrix. */ public invert():void { if (this.b == 0 && this.c == 0) { if (thi...
tmp = y2; y2 = y3; y3 = tmp; }
random_line_split
Matrix.ts
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image.. * @param tx The distance by which to translate each point along the x axis. * @param ty The distance by which to translate each point along the y axis. */ constructor(a:number = 1, b:numb...
/** * The value that affects the positioning of pixels along the x axis when scaling or rotating an image. * @default 1 */ public a:number; /** * The value that affects the positioning of pixels along the y axis when rotating or skewing an image. * @default 0 */ public b:...
{ this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; }
identifier_body
Matrix.ts
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image.. * @param tx The distance by which to translate each point along the x axis. * @param ty The distance by which to translate each point along the y axis. */ constructor(a:number = 1, b:numb...
} /** * Applies a scaling transformation to the matrix. The x axis is multiplied by sx, and the y axis it is multiplied by sy. * The scale() method alters the a and d properties of the Matrix object. * @param sx A multiplier used to scale the object along the x axis. * @param sy A multipli...
{ angle = angle / cyder.DEG_TO_RAD; let u = cyder.cos(angle); let v = cyder.sin(angle); let ta = this.a; let tb = this.b; let tc = this.c; let td = this.d; let ttx = this.tx; let tty = this.ty; this.a...
conditional_block
badgeCustomProps.spec.tsx
import * as React from 'react'; import Badge from '@mui/material/Badge'; import { createTheme } from '@mui/material/styles'; // Update the Button's extendable props options declare module '@mui/material/Badge' { interface BadgePropsVariantOverrides { action: true; } interface BadgePropsColorOverrides { s...
backgroundColor: 'green', }, }, ], }, }, }); <Badge variant="action" color="success" badgeContent={123} />; // @ts-expect-error typo <Badge variant="Action" />; // @ts-expect-error typo <Badge color="Success" />;
style: {
random_line_split
login.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { HttpClient, HttpErrorResponse } from "@angular/common/http"; import { JwtToken } from "../../commo...
); } } }
The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, // console.log(`Backend returned code ${error.status}, body was: ${error.error.message}`); this.loginError = error.error.message; } }
conditional_block
login.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { HttpClient, HttpErrorResponse } from "@angular/common/http"; import { JwtToken } from "../../commo...
templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit{ public static redirectUrl: string; // Store the url so we can redirect after logging in public login_url_api = "/api/admin/login"; public loginForm: FormGroup; public loginError: st...
* Login component * Created by maxu0 on 2017/5/31. */ @Component({
random_line_split
login.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { HttpClient, HttpErrorResponse } from "@angular/common/http"; import { JwtToken } from "../../commo...
); } } }
ginForm.valid) { this.http.post<JwtToken>(this.login_url_api, values).subscribe( data => { sessionStorage.setItem("jwtToken", `Bearer ${data.token}`); let redirect = LoginComponent.redirectUrl ? LoginComponent.redirectUrl : "/admin/index"; this.router.navigate([redirect]); ...
identifier_body
login.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { HttpClient, HttpErrorResponse } from "@angular/common/http"; import { JwtToken } from "../../commo...
implements OnInit{ public static redirectUrl: string; // Store the url so we can redirect after logging in public login_url_api = "/api/admin/login"; public loginForm: FormGroup; public loginError: string; constructor(private fb: FormBuilder, private http: HttpClient, private rou...
LoginComponent
identifier_name
linear-interpolator.js
import TransitionInterpolator from './transition-interpolator'; import {lerp} from 'math.gl'; const DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch']; const DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom']; /** * Performs linear interpolation of two view states. */ export default class...
interpolateProps(startProps, endProps, t) { const propsInTransition = {}; for (const key of this._propsToExtract) { propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t); } if (endProps.aroundLngLat) { // Linear transition should be performed in common space c...
{ const result = super.initializeProps(startProps, endProps); const {makeViewport, around} = this.opts; if (makeViewport && around) { const startViewport = makeViewport(startProps); const endViewport = makeViewport(endProps); const aroundLngLat = startViewport.unproject(around); res...
identifier_body
linear-interpolator.js
import TransitionInterpolator from './transition-interpolator'; import {lerp} from 'math.gl'; const DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch']; const DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom']; /** * Performs linear interpolation of two view states. */ export default class...
extends TransitionInterpolator { /** * @param {Object} opts * @param {Array} opts.transitionProps - list of props to apply linear transition to. * @param {Array} opts.around - a screen point to zoom/rotate around. * @param {Function} opts.makeViewport - construct a viewport instance with given props. ...
LinearInterpolator
identifier_name
linear-interpolator.js
import TransitionInterpolator from './transition-interpolator'; import {lerp} from 'math.gl'; const DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch']; const DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom']; /** * Performs linear interpolation of two view states. */ export default class...
const startViewport = makeViewport(startProps); const endViewport = makeViewport(endProps); const aroundLngLat = startViewport.unproject(around); result.start.around = around; Object.assign(result.end, { around: endViewport.project(aroundLngLat), aroundLngLat, width...
random_line_split
linear-interpolator.js
import TransitionInterpolator from './transition-interpolator'; import {lerp} from 'math.gl'; const DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch']; const DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom']; /** * Performs linear interpolation of two view states. */ export default class...
return result; } interpolateProps(startProps, endProps, t) { const propsInTransition = {}; for (const key of this._propsToExtract) { propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t); } if (endProps.aroundLngLat) { // Linear transition should be performed...
{ const startViewport = makeViewport(startProps); const endViewport = makeViewport(endProps); const aroundLngLat = startViewport.unproject(around); result.start.around = around; Object.assign(result.end, { around: endViewport.project(aroundLngLat), aroundLngLat, wid...
conditional_block
input_hook.py
# This file is part of the Diamond cothread library. # # Copyright (C) 2007 James Rowland, 2007-2012 Michael Abbott, # Diamond Light Source Ltd. # # The Diamond cothread library 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 Soft...
_qapp = QtWidgets.QApplication(argv) # Arrange to get a Quit event when the last window goes. This allows the # application to simply rest on WaitForQuit(). _qapp.aboutToQuit.connect(cothread.Quit) # Create timer. Hang onto the timer to prevent it from vanishing. _timer = _timer_iqt(poll...
'''Installs Qt event handling hook. The polling interval is in seconds.''' from .qt import QtCore, QtWidgets global _qapp, _timer # Importing PyQt4 has an unexpected side effect: it removes the input hook! # So we put it back again... _install_readline_hook(True) # Repeated calls to iqt(...
identifier_body
input_hook.py
# This file is part of the Diamond cothread library. # # Copyright (C) 2007 James Rowland, 2007-2012 Michael Abbott, # Diamond Light Source Ltd. # # The Diamond cothread library 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 Soft...
(enable_hook = True): '''Install readline hook. This allows the scheduler to run in parallel with interactive python: while readline is waiting for input, the scheduler still operates. This routine can also be used to disable the input hook by setting the enable_hook parameter to False -- for e...
_install_readline_hook
identifier_name
input_hook.py
# This file is part of the Diamond cothread library. # # Copyright (C) 2007 James Rowland, 2007-2012 Michael Abbott, # Diamond Light Source Ltd. # # The Diamond cothread library 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 Soft...
# Ensure that there is a QtApplication instance, creating one if necessary. _qapp = QtCore.QCoreApplication.instance() if _qapp is None: if argv is None: argv = sys.argv _qapp = QtWidgets.QApplication(argv) # Arrange to get a Quit event when the last window goes. This all...
return _qapp
conditional_block
input_hook.py
# This file is part of the Diamond cothread library. # # Copyright (C) 2007 James Rowland, 2007-2012 Michael Abbott, # Diamond Light Source Ltd. # # The Diamond cothread library 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 Soft...
# application to simply rest on WaitForQuit(). _qapp.aboutToQuit.connect(cothread.Quit) # Create timer. Hang onto the timer to prevent it from vanishing. _timer = _timer_iqt(poll_interval) # Finally, unless we've been told not to, spawn our own exec loop. if run_exec: cothread.Spawn(_...
# Arrange to get a Quit event when the last window goes. This allows the
random_line_split
xml_module.py
older serialized version. return value class XmlParserMixin(object): """ Class containing XML parsing functionality shared between XBlock and XModuleDescriptor. """ # Extension to append to filename paths filename_extension = 'xml' xml_attributes = Dict(help="Map of unhandled xml att...
@classmethod def load_definition(cls, xml_object, system, def_id, id_generator): """ Load a descriptor definition from the specified xml_object. Subclasses should not need to override this except in special cases (e.g. html module) Args: xml_object: an lxml...
""" Open the specified file in fs, and call cls.file_to_xml on it, returning the lxml object. Add details and reraise on error. """ try: with fs.open(filepath) as xml_file: return cls.file_to_xml(xml_file) except Exception as err: ...
identifier_body
xml_module.py
older serialized version. return value class XmlParserMixin(object): """ Class containing XML parsing functionality shared between XBlock and XModuleDescriptor. """ # Extension to append to filename paths filename_extension = 'xml' xml_attributes = Dict(help="Map of unhandled xml att...
definition_xml = cls.load_file(filepath, system.resources_fs, def_id) usage_id = id_generator.create_usage(def_id) aside_children = system.parse_asides(definition_xml, def_id, usage_id, id_generator) # Add the attributes from the pointer node definition_xml...
filepath = candidate break
conditional_block
xml_module.py
older serialized version. return value class XmlParserMixin(object): """ Class containing XML parsing functionality shared between XBlock and XModuleDescriptor. """ # Extension to append to filename paths filename_extension = 'xml' xml_attributes = Dict(help="Map of unhandled xml att...
(cls, filepath, fs, def_id): # pylint: disable=invalid-name """ Open the specified file in fs, and call cls.file_to_xml on it, returning the lxml object. Add details and reraise on error. """ try: with fs.open(filepath) as xml_file: return cl...
load_file
identifier_name
xml_module.py
older serialized version. return value class XmlParserMixin(object): """ Class containing XML parsing functionality shared between XBlock and XModuleDescriptor. """ # Extension to append to filename paths filename_extension = 'xml' xml_attributes = Dict(help="Map of unhandled xml att...
@classmethod def clean_metadata_from_xml(cls, xml_object): """ Remove any attribute named for a field with scope Scope.settings from the supplied xml_object """ for field_name, field in cls.fields.items(): if field.scope == Scope.settings and xml_object.get(fi...
""" raise NotImplementedError("%s does not implement definition_from_xml" % cls.__name__)
random_line_split
enquire.py
): return len(self._matches) @property def matches(self): """ return the list of matches as xapian.MSetItem """ return self._matches def _threaded_perform_search(self): self._perform_search_complete = False # generate a name and ensure we never have two threads ...
if self.nonblocking_load:
random_line_split
enquire.py
( SearchQuery, LocaleSorter, TopRatedSorter) from softwarecenter.distro import get_distro from softwarecenter.utils import ExecutionTime LOG=logging.getLogger(__name__) class
(GObject.GObject): """ A interface to enquire data from a xapian database. It can combined with any xapian querry and with a generic filter function (that can filter on data not available in xapian) """ # signal emited __gsignals__ = {"query-complete" : (GObject.SIGNAL_RUN_FIRST, ...
AppEnquire
identifier_name
enquire.py
( SearchQuery, LocaleSorter, TopRatedSorter) from softwarecenter.distro import get_distro from softwarecenter.utils import ExecutionTime LOG=logging.getLogger(__name__) class AppEnquire(GObject.GObject): """ A interface to enquire data from a xapian database. It can combined with any xapian querry ...
LOG.debug("nearly completely filtered query: '%s'" % q) # filter out docs of pkgs of which there exists a doc of the app # FIXME: make this configurable again? enquire.set_query(xapian.Query(xapian.Query.OP_AND_NOT, q, xapian...
q = xapian.Query(xapian.Query.OP_AND, xapian.Query("ATapplication"), q)
conditional_block
enquire.py
import ( SearchQuery, LocaleSorter, TopRatedSorter) from softwarecenter.distro import get_distro from softwarecenter.utils import ExecutionTime LOG=logging.getLogger(__name__) class AppEnquire(GObject.GObject): """ A interface to enquire data from a xapian database. It can combined with any xapian ...
# call the query-complete callback self.emit("query-complete") def _get_estimate_nr_apps_and_nr_pkgs(self, enquire, q, xfilter): # filter out docs of pkgs of which there exists a doc of the app enquire.set_query(xapian.Query(xapian.Query.OP_AND, ...
self._perform_search_complete = False # generate a name and ensure we never have two threads # with the same name names = [thread.name for thread in threading.enumerate()] for i in range(threading.active_count()+1, 0, -1): thread_name = 'ThreadedQuery-%s' % i if n...
identifier_body
jquery.menuaim.d.ts
/// <reference path="../jquery/jquery.d.ts" /> interface JQueryMenuAimOptions { /** Function to call when a row is purposefully activated. Use this * to show a submenu's content for the activated row. */ activate? (): void; /** Function to call when a row is deactivated. */ deactivate? (...
/** Function to call when mouse exits a menu row. */ exit? (): void; /** Function to call when mouse exits the entire menu. If this returns * true, the current row's deactivation event and callback function * will be fired. Otherwise, if this isn't supplied or it returns * false, the curren...
* does not mean the row has been activated, as the user may be * mousing over to a submenu. */ enter? (): void;
random_line_split
icons.py
by_ext = [ ('py.png', 'py'), ('python.png', 'pyc'), ('page_white_text_width.png', ['md', 'markdown', 'rst', 'rtf']), ('page_white_text.png', 'txt'), ('page_white_code.png', ['html', 'htm', 'cgi']), ('page_white_visualstudio.png', ['asp', 'vb']), ('page_white_ruby.png', 'rb'), ('page_code...
ICONS_BY_EXT[e] = icon
conditional_block
icons.py
by_ext = [ ('py.png', 'py'), ('python.png', 'pyc'), ('page_white_text_width.png', ['md', 'markdown', 'rst', 'rtf']), ('page_white_text.png', 'txt'), ('page_white_code.png', ['html', 'htm', 'cgi']), ('page_white_visualstudio.png', ['asp', 'vb']), ('page_white_ruby.png', 'rb'), ('page_code...
('page_white_flash.png', 'swf'), ('page_white_actionscript.png', ['fla', 'as']), ('comment.png', 'smi'), ('disk.png', ['bak', 'bup']), ('application_xp_terminal.png', ['bat', 'com']), ('application.png', 'exe'), ('key.png', 'cer'), ('cog.png', ['dll', 'so']), ('pictures.png', 'ics'),...
('page_white_word.png', ['doc', 'docx']),
random_line_split
calculateTopScores.spec.ts
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law 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 under the License. */ import { ex...
random_line_split
forms.py
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.Cha...
def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( _("The two password fields didn't match."), ...
model = User fields = ("email",)
identifier_body
forms.py
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.Cha...
(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_password(self): # Regardless of what the user provides, return ...
__init__
identifier_name
forms.py
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.Cha...
return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHas...
raise forms.ValidationError( _("The two password fields didn't match."), code='password_mismatch', )
conditional_block
forms.py
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.Cha...
# field does not have access to the initial value return self.initial["password"]
def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the
random_line_split
name.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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...
{ #![allow(clippy::dbg_macro, clippy::print_stdout)] let rdata = Name::from_ascii("WWW.example.com.").unwrap(); let mut bytes = Vec::new(); let mut encoder: BinEncoder = BinEncoder::new(&mut bytes); assert!(emit(&mut encoder, &rdata).is_ok()); let bytes = encoder.into_bytes(); println!("b...
identifier_body
name.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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...
/// by the corresponding lowercase US-ASCII letters; /// ``` pub fn emit(encoder: &mut BinEncoder, name_data: &Name) -> ProtoResult<()> { let is_canonical_names = encoder.is_canonical_names(); name_data.emit_with_lowercase(encoder, is_canonical_names)?; Ok(()) } #[test] pub fn test() { #![allow(...
random_line_split
name.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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...
() { #![allow(clippy::dbg_macro, clippy::print_stdout)] let rdata = Name::from_ascii("WWW.example.com.").unwrap(); let mut bytes = Vec::new(); let mut encoder: BinEncoder = BinEncoder::new(&mut bytes); assert!(emit(&mut encoder, &rdata).is_ok()); let bytes = encoder.into_bytes(); println!...
test
identifier_name
399106d8a6ad_.py
"""empty message Revision ID: 399106d8a6ad Revises: None Create Date: 2015-03-06 03:55:19.157958 """ # revision identifiers, used by Alembic. revision = '399106d8a6ad' down_revision = None from alembic import op import sqlalchemy as sa def
(): ### commands auto generated by Alembic - please adjust! ### op.create_table('category', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=100), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('product', sa.Column('id', sa.Integer(), nul...
upgrade
identifier_name
399106d8a6ad_.py
""" # revision identifiers, used by Alembic. revision = '399106d8a6ad' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('category', sa.Column('id', sa.Integer(), nullable=False), sa.Column(...
"""empty message Revision ID: 399106d8a6ad Revises: None Create Date: 2015-03-06 03:55:19.157958
random_line_split
399106d8a6ad_.py
"""empty message Revision ID: 399106d8a6ad Revises: None Create Date: 2015-03-06 03:55:19.157958 """ # revision identifiers, used by Alembic. revision = '399106d8a6ad' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###...
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('product') op.drop_table('category') ### end Alembic commands ###
op.create_table('category', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=100), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('product', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=True...
identifier_body
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
(json_data: &[u8]) -> Vec<String> { let tests = ethjson::transaction::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let old_schedule = evm::Schedule::new_frontier(); let new_schedule = evm::Schedule::new_homestead(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title:...
do_json_test
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
let rlp: Vec<u8> = test.rlp.into(); let res = UntrustedRlp::new(&rlp) .as_val() .map_err(From::from) .and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err(), "Validity different"); if let (...
random_line_split
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
.and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err(), "Validity different"); if let (Some(tx), Some(sender)) = (test.transaction, test.sender) { let t = res.unwrap(); fail_unless(public_to_a...
{ let tests = ethjson::transaction::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let old_schedule = evm::Schedule::new_frontier(); let new_schedule = evm::Schedule::new_homestead(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title: &str| if !cond { failed.push(name...
identifier_body
grpc_vtgate_client.py
RPC. """ import logging import re from urlparse import urlparse # Import main protobuf library first # to work around import order issues. import google.protobuf # pylint: disable=unused-import from grpc.beta import implementations from grpc.beta import interfaces from grpc.framework.interfaces.face import face fr...
def is_closed(self): return self.stub is None def cursor(self, *pargs, **kwargs): cursorclass = kwargs.pop('cursorclass', None) or vtgate_cursor.VTGateCursor return cursorclass(self, *pargs, **kwargs) def begin(self, effective_caller_id=None): try: request = self.begin_request(effective_...
"""close closes the server connection and frees up associated resources. The stub object is managed by the gRPC library, removing references to it will just close the channel. """ if self.session and self.session.in_transaction: self.rollback() self.stub = None
identifier_body
grpc_vtgate_client.py
RPC. """ import logging import re from urlparse import urlparse # Import main protobuf library first # to work around import order issues. import google.protobuf # pylint: disable=unused-import from grpc.beta import implementations from grpc.beta import interfaces from grpc.framework.interfaces.face import face fr...
elif isinstance(exc, face.ExpirationError): # face.ExpirationError is returned by the gRPC library when # a request times out. Note it is a subclass of face.AbortionError # so we have to test for it before. new_exc = dbexceptions.TimeoutError(new_args) elif isinstance(exc, face.AbortionError): ...
new_exc = exc.convert_to_dbexception(new_args)
conditional_block
grpc_vtgate_client.py
RPC. """ import logging import re from urlparse import urlparse # Import main protobuf library first # to work around import order issues. import google.protobuf # pylint: disable=unused-import from grpc.beta import implementations from grpc.beta import interfaces from grpc.framework.interfaces.face import face fr...
( self, sql, bind_variables, tablet_type, keyspace_name=None, shards=None, keyspace_ids=None, keyranges=None, entity_keyspace_id_map=None, entity_column_name=None, not_in_transaction=False, effective_caller_id=None, **kwargs): # FIXME(alainjobart): keyspace should be in routing_kwargs, ...
_execute
identifier_name
grpc_vtgate_client.py
RPC. """ import logging import re from urlparse import urlparse # Import main protobuf library first # to work around import order issues. import google.protobuf # pylint: disable=unused-import from grpc.beta import implementations from grpc.beta import interfaces from grpc.framework.interfaces.face import face fr...
*args: additional args from the raising site. **kwargs: additional keyword args from the raising site. They will be converted into a single string, and added as an extra arg to the exception. Returns: Api interface exceptions - dbexceptions with new args. """ kwargs_as_str...
exc: raw protocol exception.
random_line_split
lib.rs
matrix `P0` indicates the uncertainty //! related to the guess of `x0`. extern crate rulinalg; use rulinalg::matrix::{BaseMatrix, Matrix}; use rulinalg::vector::Vector; /// Container object with values for matrices used in the Kalman filtering /// procedure as well as initial values for state variables. /// /// # ...
filter_step
identifier_name
lib.rs
variable and its covariance. This struct /// is used throughout all parts of Kalman procedure and may refer to predicted, /// filtered and smoothed variables depending on the context. #[derive(Clone, Debug)] pub struct KalmanState { pub x: Vector<f64>, // State vector pub p: Matrix<f64> // State covarianc...
{ let j: Matrix<f64> = &filtered.p * &kalman_filter.f.transpose() * &predicted.p.clone().inverse() .expect("Predicted state covariance matrix could not be inverted."); let x: Vector<f64> = &filtered.x + &j * (&init.x - &predicted.x); let p: Matrix<f64> = &filtered.p + &j * (&init.p - &predi...
identifier_body
lib.rs
'_{t} + Q_{t}` //! * `x_{t|t-1} = F_{t} x_{t-1|t-1} + B_{t} u_{t}` //! * `K_{t} = P_{t|t-1} H'_{t} * (H_{t} P_{t|t-1} H'_{t} + R_{t})^{-1}` //! * `P_{t|t} = (Id - K_{t} H_{t}) * P_{t|t-1}` //! * `x_{t|t} = x_{t|t-1} + K_{t} * (z_{t} - H_{t} x_{t|t-1})` //! //! Kalman smoothing equations: //! //! * `J_{t} = P_{t|t} F'_{...
/// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&ve...
/// use linearkalman::KalmanFilter;
random_line_split
microsoft.py
import base64 import json import requests def call_vision_api(image_filename, api_keys): api_key = api_keys['microsoft'] post_url = "https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&subscription-key=" + api_key image_data = open(image_...
# for tag in api_result['description']['tags']: # output['tags_without_score'][tag] = 'n/a' # output['image_types'] = api_result['imageType'] return output
output = { 'tags' : [], 'captions' : [], # 'categories' : [], # 'adult' : [], # 'image_types' : [] # 'tags_without_score' : {} } for tag_data in api_result['tags']: output['tags'].append((tag_data['name'], tag_data['confidence'])) for caption in api_resu...
identifier_body
microsoft.py
import base64 import json import requests def call_vision_api(image_filename, api_keys): api_key = api_keys['microsoft'] post_url = "https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&subscription-key=" + api_key image_data = open(image_...
for caption in api_result['description']['captions']: output['captions'].append((caption['text'], caption['confidence'])) # for category in api_result['categories']: # output['categories'].append(([category['name'], category['score'])) # output['adult'] = api_result['adult'] # for tag i...
output['tags'].append((tag_data['name'], tag_data['confidence']))
conditional_block
microsoft.py
import base64 import json import requests def call_vision_api(image_filename, api_keys): api_key = api_keys['microsoft'] post_url = "https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&subscription-key=" + api_key image_data = open(image_...
# # E.g., # # { # 'tags' : [('throne', 0.95), ('swords', 0.84)], # 'description' : [('A throne made of pointy objects', 0.73)] # } # def get_standardized_result(api_result): output = { 'tags' : [], 'captions' : [], # 'categories' : [], # 'adult' : [], # 'image_types' : []...
# # { # 'feature_1' : [(element, score), ...], # 'feature_2' : ... # }
random_line_split
microsoft.py
import base64 import json import requests def call_vision_api(image_filename, api_keys): api_key = api_keys['microsoft'] post_url = "https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&subscription-key=" + api_key image_data = open(image_...
(api_result): output = { 'tags' : [], 'captions' : [], # 'categories' : [], # 'adult' : [], # 'image_types' : [] # 'tags_without_score' : {} } for tag_data in api_result['tags']: output['tags'].append((tag_data['name'], tag_data['confidence'])) for c...
get_standardized_result
identifier_name
explicit_null.rs
use juniper::{ graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLInputObject, Nullable, Variables, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[derive(GraphQLInputObject)] struct ObjectInput { field: Nullable<i32>, } #[graphql_objec...
"noArgIsExplicitNull": false, "literalOneFieldIsExplicitNull": false, "literalNullFieldIsExplicitNull": true, "noFieldIsExplicitNull": false, "emptyVariableObjectFieldIsExplicitNull": false, "literalNullVariableObjectFieldIs...
"literalOneIsExplicitNull": false, "literalNullIsExplicitNull": true,
random_line_split
explicit_null.rs
use juniper::{ graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLInputObject, Nullable, Variables, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[derive(GraphQLInputObject)] struct ObjectInput { field: Nullable<i32>, } #[graphql_objec...
() { let query = r#" query Foo($emptyObj: ObjectInput!, $literalNullObj: ObjectInput!) { literalOneIsExplicitNull: isExplicitNull(arg: 1) literalNullIsExplicitNull: isExplicitNull(arg: null) noArgIsExplicitNull: isExplicitNull literalOneFieldIsExplicitNull: ob...
explicit_null
identifier_name
Result.ts
import {Serializable, Serialize, UnmarshallError} from "ts-serialize"; import {JsValue, Json} from "ts-json-definition"; import {Either, Right, Left, Optional} from "scalts"; const dateUnmarshaller = (value: JsValue, json: Json, clazz: any, classPropertyName: string, jsonPropertyName: string, target: Function, mbType...
extends Serializable { @Serialize("Date", dateUnmarshaller) date : Date; @Serialize("Num1") num1 : number; @Serialize("Num2") num2 : number; @Serialize("Num3") num3 : number; @Serialize("Num4") num4 : number; @Serialize("Num5") num5 : number; @Serialize("Star1...
Result
identifier_name
Result.ts
import {Serializable, Serialize, UnmarshallError} from "ts-serialize"; import {JsValue, Json} from "ts-json-definition"; import {Either, Right, Left, Optional} from "scalts"; const dateUnmarshaller = (value: JsValue, json: Json, clazz: any, classPropertyName: string, jsonPropertyName: string, target: Function, mbType...
return Left<UnmarshallError[], Date>([new UnmarshallError(value, mbType, jsonPropertyName, classPropertyName, target, jsonPath, classPath)]); }; class Result extends Serializable { @Serialize("Date", dateUnmarshaller) date : Date; @Serialize("Num1") num1 : number; @Serialize("Num2") num...
{ let time = parseInt(value.replace("/Date(", "").replace("+0000)/", "")); if(!isNaN(time)) { return Right<UnmarshallError[], Date>(new Date(time)); } }
conditional_block
Result.ts
import {Serializable, Serialize, UnmarshallError} from "ts-serialize"; import {JsValue, Json} from "ts-json-definition";
const dateUnmarshaller = (value: JsValue, json: Json, clazz: any, classPropertyName: string, jsonPropertyName: string, target: Function, mbType: Optional<Function>, jsonPath: string[], classPath: string[]) : Either<UnmarshallError[], Date> => { if(typeof value === "string") { let time = parseInt(value.repl...
import {Either, Right, Left, Optional} from "scalts";
random_line_split
container.js
/** Data comes from a docker inspect command output */ function
(data) { for (d in data) { this[d] = data[d]; } } Container.prototype.name = function() { return this.Name.ltrim('/'); } Container.prototype.shortName = function() { return this.name(); } Container.prototype.shortId = function() { return this.Id.substr(0, 12); } Container.prototype.links...
Container
identifier_name
container.js
/** Data comes from a docker inspect command output */ function Container(data) { for (d in data) { this[d] = data[d]; } } Container.prototype.name = function() { return this.Name.ltrim('/'); } Container.prototype.shortName = function() { return this.name(); } Container.prototype.shortId ...
return arr; }, {}); } Container.prototype.stringPorts = function() { if (this.NetworkSettings == undefined || this.NetworkSettings.Ports == undefined) { return [] } var ports = [] for (ph in this.NetworkSettings.Ports) { var list = this.NetworkSettings.Ports[ph] ...
{ arr[name] = sname; }
conditional_block
container.js
/** Data comes from a docker inspect command output */ function Container(data)
Container.prototype.name = function() { return this.Name.ltrim('/'); } Container.prototype.shortName = function() { return this.name(); } Container.prototype.shortId = function() { return this.Id.substr(0, 12); } Container.prototype.links = function() { if (this.HostConfig == undefined || this.Host...
{ for (d in data) { this[d] = data[d]; } }
identifier_body
container.js
/** Data comes from a docker inspect command output */ function Container(data) { for (d in data) { this[d] = data[d]; } } Container.prototype.name = function() { return this.Name.ltrim('/'); } Container.prototype.shortName = function() { return this.name(); } Container.prototype.shortId ...
if (this.HostConfig == undefined || this.HostConfig.Links == undefined) { return {}; } return this.HostConfig.Links.reduce(function (arr, str) { var parts = str.split(':'); var name = parts[0]; var sname = parts.last().split('/').last(); if (!(name in arr) || sname....
{
random_line_split
lovepx.py
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext import json import os ...
def processRequest(req): result = req.get("result") parameters = result.get("parameters") prt = parameters.get("any") yurt = parameters.get("any1") baseurl = "https://love-calculator.p.mashape.com/getPercentage?" mydict1 = {'fname': prt} mydict2 = {'sname': yurt} put1 = urle...
random_line_split
lovepx.py
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext import json import os ...
(req): result = req.get("result") parameters = result.get("parameters") prt = parameters.get("any") yurt = parameters.get("any1") baseurl = "https://love-calculator.p.mashape.com/getPercentage?" mydict1 = {'fname': prt} mydict2 = {'sname': yurt} put1 = urlencode(mydict1) pu...
processRequest
identifier_name
lovepx.py
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext import json import os ...
joke = prt + ' ❤️ ' + yurt + ' = ' + perc + ' % \nSo, ' + resl speech = joke print("Response:") print(speech) return { "speech": speech, "displayText": speech, # "data": data, # "contextOut": [], "source": "apiai-weather-webhook-sample" } ...
result = req.get("result") parameters = result.get("parameters") prt = parameters.get("any") yurt = parameters.get("any1") baseurl = "https://love-calculator.p.mashape.com/getPercentage?" mydict1 = {'fname': prt} mydict2 = {'sname': yurt} put1 = urlencode(mydict1) put2 = urlenco...
identifier_body
lovepx.py
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext import json import os ...
= int(os.getenv('PORT', 5000)) print("Starting app on port %d" % port) app.run(debug=False, port=port, host='0.0.0.0')
conditional_block