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
loading-mask.js
'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor))
} var _jquery = require('jquery'); var _jquery2 = _interopRequireDefault(_jquery); require('./loading-mask.css!'); var _locale = require('../locale'); var LoadingMask = (function () { function LoadingMask(resources) { _classCallCheck(this, LoadingMask); this.loadingMask = undefined; this.dimScreen ...
{ throw new TypeError('Cannot call a class as a function'); }
conditional_block
log.js
'use strict'; const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN...
} module.exports = { error(/* msg */) { log.apply(this, ['error'].concat(Array.from(arguments))); }, warn(/* msg */) { log.apply(this, ['warn'].concat(Array.from(arguments))); }, info(/* msg */) { log.apply(this, ['info'].concat(Array.from(arguments))); }, debug(/* msg */) { log.apply(th...
{ process.stdout.write(msg); }
conditional_block
log.js
'use strict'; const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN...
};
{ log.apply(this, ['debug'].concat(Array.from(arguments))); }
identifier_body
log.js
const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN')); bre...
'use strict';
random_line_split
log.js
'use strict'; const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN...
(/* msg */) { log.apply(this, ['warn'].concat(Array.from(arguments))); }, info(/* msg */) { log.apply(this, ['info'].concat(Array.from(arguments))); }, debug(/* msg */) { log.apply(this, ['debug'].concat(Array.from(arguments))); } };
warn
identifier_name
confirm-dialog.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
(public dialogRef: MatDialogRef<GioConfirmDialogComponent>, @Inject(MAT_DIALOG_DATA) confirmDialogData: GioConfirmDialogData) { this.title = confirmDialogData?.title ?? 'Are you sure ?'; this.content = confirmDialogData?.content; this.confirmButton = confirmDialogData?.confirmButton ?? 'Yes'; this.cance...
constructor
identifier_name
confirm-dialog.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
} }
this.confirmButton = confirmDialogData?.confirmButton ?? 'Yes'; this.cancelButton = confirmDialogData?.cancelButton ?? 'Cancel';
random_line_split
NavBarLoggedInActions.tsx
import { useContext } from "react"; import * as React from "react"; import { NavBarNotificationsQueryRenderer, NavBarUserMenu } from "./Menus" import { AnalyticsSchema, SystemContext, useTracking } from "v2/System" import { BellIcon, Dropdown, EnvelopeIcon, Flex, SoloIcon, } from "@artsy/palette" import { gra...
<NavBarLoggedInActionsNotificationIndicator /> )} </NavBarItemButton> )} </Dropdown> <NavBarItemLink href="/user/conversations"> <EnvelopeIcon title="Inbox" // @ts-ignore fill="currentColor" /> {hasUnreadConv...
fill="currentColor" /> {hasUnreadNotifications && (
random_line_split
bootstrap.py
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def calc_auc(predictions):
if __name__ == '__main__': parser = argparse.ArgumentParser(description='bootstrap(sampling with replacement) test') parser.add_argument('-m','--model',type=str,required=True,help="Model template. Must use TESTFILE with unshuffled, unbalanced input") parser.add_argument('-w','--weights',type=str,required=True,help...
y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append(float(values[0])) auc = sklearn.metrics.roc_auc_score(y_true,y_score) return auc
identifier_body
bootstrap.py
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def
(predictions): y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append(float(values[0])) auc = sklearn.metrics.roc_auc_score(y_true,y_score) return auc if __name__ == '__main__': parser = argparse.ArgumentParser(description='bootstrap(sampling w...
calc_auc
identifier_name
bootstrap.py
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def calc_auc(predictions): y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append...
mean=np.mean(all_aucs) std_dev = np.std(all_aucs) txt = 'mean: %.2f standard deviation: %.2f'%(mean,std_dev) print(txt) output = open(output, 'w') output.writelines('%.2f\n' %auc for auc in all_aucs) output.write(txt) output.close() plt.figure() plt.boxplot(all_aucs,0,'rs',0) plt.title('%s AUCs'%args.outpu...
sample = np.random.choice(predictions,len(predictions), replace=True) all_aucs.append(calc_auc(sample))
conditional_block
bootstrap.py
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def calc_auc(predictions): y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append...
sample = np.random.choice(predictions,len(predictions), replace=True) all_aucs.append(calc_auc(sample)) mean=np.mean(all_aucs) std_dev = np.std(all_aucs) txt = 'mean: %.2f standard deviation: %.2f'%(mean,std_dev) print(txt) output = open(output, 'w') output.writelines('%.2f\n' %auc for auc in all_aucs) outpu...
for _ in range(args.iterations):
random_line_split
parser_testing.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { let ps = ParseSess::new(FilePathMapping::empty()); with_error_checking_parse(source_str, &ps, |p| { p.parse_pat(None) }) } /// Convert a ...
{ let ps = ParseSess::new(FilePathMapping::empty()); with_error_checking_parse(source_str, &ps, |p| { p.parse_item() }) }
identifier_body
parser_testing.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!(matches_codepattern("",""),true); assert_eq!(matches_codepattern("","a"),false); assert_eq!(matches_codepattern("a",""),false); assert_eq!(matches_codepattern("a","a"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); assert_eq!(matches_c...
eqmodws
identifier_name
parser_testing.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
return false } } // check if a has *only* trailing whitespace a_iter.all(is_pattern_whitespace) } /// Advances the given peekable `Iterator` until it reaches a non-whitespace character fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) { while lexer::is_patt...
b_iter.next(); } else {
random_line_split
__init__.py
from cpptrimesh import CppTriMesh from menpo.shape.mesh.base import TriMesh from menpo.shape.mesh.coloured import ColouredTriMesh from menpo.shape.pointcloud import PointCloud class FastTriMesh(TriMesh, CppTriMesh): """A TriMesh with an underlying C++ data structure, allowing for efficient iterations around m...
from .textured import TexturedTriMesh from .coloured import ColouredTriMesh
return len(self.polylist)
identifier_body
__init__.py
from cpptrimesh import CppTriMesh from menpo.shape.mesh.base import TriMesh from menpo.shape.mesh.coloured import ColouredTriMesh from menpo.shape.pointcloud import PointCloud class FastTriMesh(TriMesh, CppTriMesh): """A TriMesh with an underlying C++ data structure, allowing for efficient iterations around m...
return len(self.polylist) from .textured import TexturedTriMesh from .coloured import ColouredTriMesh
self.polylist = polylist @property def n_polys(self):
random_line_split
__init__.py
from cpptrimesh import CppTriMesh from menpo.shape.mesh.base import TriMesh from menpo.shape.mesh.coloured import ColouredTriMesh from menpo.shape.pointcloud import PointCloud class FastTriMesh(TriMesh, CppTriMesh): """A TriMesh with an underlying C++ data structure, allowing for efficient iterations around m...
(self, points, polylist): PointCloud.__init__(self, points) self.polylist = polylist @property def n_polys(self): return len(self.polylist) from .textured import TexturedTriMesh from .coloured import ColouredTriMesh
__init__
identifier_name
xul.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> // Non-standard properties t...
alias="-webkit-box-direction", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-direction)", )} ${helpers.predefined_type( "-moz-box-flex", "NonNegativeNumber", "From::from(0.)", products="gecko", gecko_ffi_name="mBoxFlex", animation_value_type="NonNegativeNumber"...
random_line_split
issue-3121.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
meal::for_here(_) if cond => {} meal::for_here(order::hamburger) => {} meal::for_here(order::fries(_s)) => {} meal::for_here(order::shake) => {} } } pub fn main() { foo(box meal::for_here(order::hamburger), true) }
{ }
conditional_block
issue-3121.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { foo(box meal::for_here(order::hamburger), true) }
random_line_split
issue-3121.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ hamburger, fries(side), shake } #[derive(Copy, Clone)] enum meal { to_go(order), for_here(order) } fn foo(m: Box<meal>, cond: bool) { match *m { meal::to_go(_) => { } meal::for_here(_) if cond => {} meal::for_here(order::hamburger) => {} meal::for_here(order::fries(_s)) => {} meal:...
order
identifier_name
test_auth.py
from __future__ import absolute_import from sentry.testutils import AcceptanceTestCase class AuthTest(AcceptanceTestCase):
def test_success(self): email = 'dummy@example.com' password = 'dummy' user = self.create_user(email=email) user.set_password(password) user.save() self.enter_auth(email, password) self.browser.snapshot(name='login success')
def enter_auth(self, username, password): # disable captcha as it makes these tests flakey (and requires waiting # on external resources) with self.settings(RECAPTCHA_PUBLIC_KEY=None): self.browser.get('/auth/login/') self.browser.find_element_by_id('id_username').send_ke...
identifier_body
test_auth.py
from __future__ import absolute_import from sentry.testutils import AcceptanceTestCase class AuthTest(AcceptanceTestCase): def enter_auth(self, username, password): # disable captcha as it makes these tests flakey (and requires waiting # on external resources) with self.settings(RECAPTCHA...
self.enter_auth(email, password) self.browser.snapshot(name='login success')
user = self.create_user(email=email) user.set_password(password) user.save()
random_line_split
test_auth.py
from __future__ import absolute_import from sentry.testutils import AcceptanceTestCase class AuthTest(AcceptanceTestCase): def enter_auth(self, username, password): # disable captcha as it makes these tests flakey (and requires waiting # on external resources) with self.settings(RECAPTCHA...
(self): self.browser.get('/auth/login/') self.browser.snapshot(name='login') def test_no_credentials(self): self.enter_auth('', '') self.browser.snapshot(name='login fields required') def test_invalid_credentials(self): self.enter_auth('bad-username', 'bad-username') ...
test_renders
identifier_name
index.ts
'use strict'; const electron : Electron.ElectronMainAndRenderer = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; const google = require('googleapis'); const youtube = google.youtube('v3'); var mainWindow : Electron.BrowserWindow = null; ...
ipcMain.on('message', (event, arg) => { console.log(`Received ${arg}`); event.sender.send("reply", "pong"); }); ipcMain.on('search', (event, arg) => { youtube.search.list({ q: arg, part: 'snippet', regionCode: 'KR', key: 'AIzaSyBC896i0COJfC5IsZ72nQepumCHoMd_IqI' }, (err: any, data: any) => {...
app.quit(); } })
random_line_split
index.ts
'use strict'; const electron : Electron.ElectronMainAndRenderer = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; const google = require('googleapis'); const youtube = google.youtube('v3'); var mainWindow : Electron.BrowserWindow = null; ...
if(data) { console.log(data); event.sender.send('search:result', data); } }) })
{ console.error('Error: ' + err); event.sender.send('search:error', err); }
conditional_block
userscloud.py
# -*- coding: UTF-8 -*- """ Copyright (C) 2014 smokdpi 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 3 of the License, or (at your option) any later version. ...
def get_media_url(self, host, media_id): web_url = self.get_url(host, media_id) stream_url = None self.headers['Referer'] = web_url html = self.net.http_GET(web_url, headers=self.headers).content r = re.search('>(eval\(function\(p,a,c,k,e,d\).+?)</script>', html, re.DOTALL) ...
random_line_split
userscloud.py
# -*- coding: UTF-8 -*- """ Copyright (C) 2014 smokdpi 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 3 of the License, or (at your option) any later version. ...
def get_host_and_id(self, url): r = re.search(self.pattern, url) if r: return r.groups() else: return False def valid_url(self, url, host): return re.search(self.pattern, url) or self.name in host
return 'https://%s/%s' % (host, media_id)
identifier_body
userscloud.py
# -*- coding: UTF-8 -*- """ Copyright (C) 2014 smokdpi 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 3 of the License, or (at your option) any later version. ...
(self, url, host): return re.search(self.pattern, url) or self.name in host
valid_url
identifier_name
userscloud.py
# -*- coding: UTF-8 -*- """ Copyright (C) 2014 smokdpi 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 3 of the License, or (at your option) any later version. ...
def valid_url(self, url, host): return re.search(self.pattern, url) or self.name in host
return False
conditional_block
app.module.ts
import { AppRoutingModule } from './app-routing.module'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { MarkdownToHtmlModule } from 'ng2-markdown-to-html'; import { AppComponent } from './app.component'; import {...
bootstrap: [AppComponent], }) export class AppModule { }
AppComponent, HeaderComponent, FooterComponent ], providers: [ ],
random_line_split
app.module.ts
import { AppRoutingModule } from './app-routing.module'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { MarkdownToHtmlModule } from 'ng2-markdown-to-html'; import { AppComponent } from './app.component'; import {...
{ }
AppModule
identifier_name
sha1Hash_test.py
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import struct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """ SHA-1...
(binaryString): """ Convert binary string to blocks of 5 words of uint32() """ return [uint32(word) for word in struct.unpack('!IIIII', binaryString)] def _toBString(block): """ Convert block (5 words of 32 bits to binary string """ return ''.join([struct.pack('!I',word) for word ...
_toBlock
identifier_name
sha1Hash_test.py
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import struct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """ SHA-1...
unittest.main()
conditional_block
sha1Hash_test.py
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import struct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """ SHA-1...
message_digest = 0xA9993E36L, 0x4706816AL, 0xBA3E2571L, 0x7850C26CL, 0x9CD0D89DL md_string = _toBString(message_digest) assert( hashAlg(message) == md_string ), 'FIPS180 Appendix A test Failed' def testFIPS180_1_Appendix_B(self): """ APPENDIX B. A SECOND SAMPLE MESSAGE AND...
random_line_split
sha1Hash_test.py
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import struct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """ SHA-1...
if __name__ == '__main__': # Run the tests from the command line unittest.main()
""" Convert block (5 words of 32 bits to binary string """ return ''.join([struct.pack('!I',word) for word in block])
identifier_body
Dir.py
# # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 use, copy, modify, merge...
(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir) return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs retu...
only_dirs
identifier_name
Dir.py
# # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 use, copy, modify, merge...
skip_entry = {} skip_entry_list = [ '.', '..', '.sconsign', # Used by the native dblite.py module. '.sconsign.dblite', # Used by dbm and dumbdbm. '.sconsign.dir', # Used by dbm. '.sconsign.pag', # Used by dumbdbm. '.sconsign.dat', '.sconsign.bak', # Used by some dbm emulations ...
"""Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
identifier_body
Dir.py
# # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 use, copy, modify, merge...
return scan_in_memory(node, env, path) def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), whic...
e('./' + f)
conditional_block
Dir.py
# # Copyright (c) 2001 - 2014 The SCons Foundation # # 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 use, copy, modify, merge...
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) skip_entry = {} skip_entry_list = [ '.', '..', '.sconsign', # Used by the native dblite.py module. '.sconsign.dblite', # Used by dbm and dumbdbm. '.sconsign.dir', # Used by dbm. '.sconsign.pag', # Used by dumbdbm. ...
kw['recursive'] = None
random_line_split
SipNonce.py
# Copyright (c) 2020 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this ...
ho = HashOracle() expthr = TestExpiration(ho.emit_challenge(DGST_PRIOS)) i = 0 min_ts = None while i < 10000: cryptic = ho.emit_challenge(DGST_PRIOS) if not ho.validate_challenge(cryptic, DGST_PRIOS): raise Exception('Basic Test Failed') i += 1 print(crypti...
self.excpt = Exception('Expiration Test Failed #3')
conditional_block
SipNonce.py
# Copyright (c) 2020 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this ...
(object): bpad = '='.encode() cipher = None def __init__(self, key): self.cipher = AES.new(key, AES.MODE_ECB) def encrypt(self, raw): iv = Random.new().read(AES.block_size) raw = bxor(raw, iv) eraw = self.cipher.encrypt(iv + raw) return b64encode(eraw)[:-1] ...
AESCipher
identifier_name
SipNonce.py
# Copyright (c) 2020 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this ...
ho = HashOracle() expthr = TestExpiration(ho.emit_challenge(DGST_PRIOS)) i = 0 min_ts = None while i < 10000: cryptic = ho.emit_challenge(DGST_PRIOS) if not ho.validate_challenge(cryptic, DGST_PRIOS): raise Exception('Basic Test Failed') i += 1 print(crypti...
from time import sleep if not self.ho.validate_challenge(self.nonce, DGST_PRIOS): self.excpt = Exception('Expiration Test Failed #1') return sleep(30) if not self.ho.validate_challenge(self.nonce, DGST_PRIOS): self.excpt = Exception('Ex...
identifier_body
SipNonce.py
# Copyright (c) 2020 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this ...
return bxor(raw[AES.block_size:], iv) DGST_MD5 = (1 << 0) DGST_MD5SESS = (1 << 1) DGST_SHA256 = (1 << 2) DGST_SHA256SESS = (1 << 3) DGST_SHA512 = (1 << 4) DGST_SHA512SESS = (1 << 5) DGST_PRIOS = (DGST_SHA512, DGST_SHA512SESS, DGST_SHA256, DGST_SHA256SESS, DGST_MD5, DGST_MD5SESS) class HashO...
iv = raw[:AES.block_size]
random_line_split
skia.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use libc::*; pub type S...
pub fn SkiaSkNativeSharedGLContextGetFBOID(aGLContext: SkiaSkNativeSharedGLContextRef) -> c_uint; pub fn SkiaSkNativeSharedGLContextStealSurface(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrGLSharedSurfaceRef; pub fn SkiaSkNativeSharedGLContextGetGrContext(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrCo...
random_line_split
mod.py
from __future__ import print_function, division from sympy.core.numbers import nan from .function import Function class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder a...
d = int(r) except TypeError: pass else: if type(d) is int: rv = p - d*q if (rv*q < 0) == True: rv += q return rv # by difference d = p - q ...
return S.One # by ratio r = p/q try:
random_line_split
mod.py
from __future__ import print_function, division from sympy.core.numbers import nan from .function import Function class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder a...
# simple -1 extraction if p.could_extract_minus_sign() and q.could_extract_minus_sign(): G, p, q = [-i for i in (G, p, q)] # check again to see if p and q can now be handled as numbers rv = doit(p, q) if rv is not None: return rv*G # put 1.0 fr...
p = cp*p q = cq*q
conditional_block
mod.py
from __future__ import print_function, division from sympy.core.numbers import nan from .function import Function class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder a...
def _eval_is_nonnegative(self): if self.args[1].is_positive: return True def _eval_is_nonpositive(self): if self.args[1].is_negative: return True
from sympy.core.logic import fuzzy_and, fuzzy_not p, q = self.args if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]): return True
identifier_body
mod.py
from __future__ import print_function, division from sympy.core.numbers import nan from .function import Function class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder a...
(self): from sympy.core.logic import fuzzy_and, fuzzy_not p, q = self.args if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]): return True def _eval_is_nonnegative(self): if self.args[1].is_positive: return True def _eval_is_nonpositive(sel...
_eval_is_integer
identifier_name
osresources.py
# 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 law or agreed to in...
def list_roles(self): return self.client.roles.list() class Nova(ResourceManager): def list_flavors(self): return self.client.flavors.list() def list_floating_ip_pools(self): return self.client.floating_ip_pools.list() def list_floating_ips(self): return self.clien...
return self.client.tenants.list()
identifier_body
osresources.py
# 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 law or agreed to in...
# under the License. """List and compare most used OpenStack cloud resources.""" import argparse import json import subprocess import sys from rally.common.plugin import discover from rally import consts from rally import osclients class ResourceManager(object): REQUIRED_SERVICE = None REPR_KEYS = ("...
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations
random_line_split
osresources.py
# 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 law or agreed to in...
(self): return self.client.tenants.list() def list_roles(self): return self.client.roles.list() class Nova(ResourceManager): def list_flavors(self): return self.client.flavors.list() def list_floating_ip_pools(self): return self.client.floating_ip_pools.list() def l...
list_tenants
identifier_name
osresources.py
# 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 law or agreed to in...
class Glance(ResourceManager): def list_images(self): return self.client.images.list() class Heat(ResourceManager): REQUIRED_SERVICE = consts.Service.HEAT def list_resource_types(self): return self.client.resource_types.list() def list_stacks(self): return self.client.st...
return self.client.list_vips()["vips"]
conditional_block
style.tsx
/* * Copyright (c) 2021 Charles University in Prague, Faculty of Arts, * Institute of the Czech National Corpus * Copyright (c) 2021 Martin Zimandl <martin.zimandl@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public ...
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import styled from 'styled-components'; import * as theme from '../../../theme/default'; // ---------------- <WdgTooltip /> -------------------------------------- export const WdgTooltip = styled.div<{multiword?:boolean}>` bac...
* You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software
random_line_split
AdminItemsView.js
import React, { Component } from 'react' import { FlexGrid, Content, Container, AdminItemsViewTable, Table, Button } from 'components' import { AddItemAboutContainer, AddItemPhotoContainer, SpecialSetupContainer } from 'containers' import { adminLink } from 'config' import s from './AdminItemsView.sass' c...
<div className={s.actions}> <Button type="blue" to={`${adminLink.path}/items/${parent_id}`}> Отредактировать модель </Button> <Button className={s.btn} type="pink" onClick={onDelete}> Удалить </Button> </...
random_line_split
AdminItemsView.js
import React, { Component } from 'react' import { FlexGrid, Content, Container, AdminItemsViewTable, Table, Button } from 'components' import { AddItemAboutContainer, AddItemPhotoContainer, SpecialSetupContainer } from 'containers' import { adminLink } from 'config' import s from './AdminItemsView.sass' c...
() { const { children } = this.props; const { onClick } = this; const { value } = this.state; return ( <FlexGrid className={s.toggle} direction="column" justify="center" align="center"> <Content size="5" center gray>{children}</Content> <Table.RowItem className={s.t...
render
identifier_name
__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
since it makes no sense of keeping multiple instances of this. ''' BACKEND_PREFIX = "backend_" def __init__(self): """ Creates a dictionary of the currently available backend modules """ Borg.__init__(self) if hasattr(self, "backend_modules"): # Thi...
It is a Borg for what matters its only state (_backend_modules),
random_line_split
__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
''' Reads the file describing the current backend configuration (project.xml) and returns a list of dictionaries, each containing: - the xml object defining the backend characteristics under "xmlobject" - the name of the backend under "module" ''' # Read c...
identifier_body
__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
dic = {} module = self.get_backend(backend_name) # Different pids are necessary to discern between backends of the same # type parameters = module.Backend.get_static_parameters() # we all the parameters and their default values in dic for param_name, param_dic in...
return None
conditional_block
__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
(self, dic): ''' Function restoring a backend from its xml description. dic should be a dictionary containing at least the key - "module", with the module name - "xmlobject", with its xml description. Every other key is passed as-is to the backend, as parameter. ...
restore_backend_from_xml
identifier_name
op.rs
is important in a // scenario like `1_u32 << 2`, because it lets us quickly // deduce that the result type should be `u32`, even // though we don't know yet what type 2 has and hence // can't pin this down to a specific impl. let rhs_ty = fcx.resolve_type_var...
{ let method_ty = method.ty; // HACK(eddyb) Fully qualified path to work around a resolve bug. let method_call = ::middle::ty::MethodCall::expr(expr.id); fcx.inh.method_map.borrow_mut().insert(method_call, method); // extract return type for method; all late...
conditional_block
op.rs
rhs_ty); } // result type is same as LHS always lhs_ty } BinOpCategory::Math | BinOpCategory::Bitwise => { // both LHS and RHS and result will have the same type demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty); lhs_ty...
/// everything uniformly through the trait system and intrinsics or /// something like that): ///
random_line_split
op.rs
Op, lhs_expr: &'tcx ast::Expr, rhs_expr: &'tcx ast::Expr) { let tcx = fcx.ccx.tcx; debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})", expr.id, expr, op, lhs_expr, rh...
<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, expr: &'tcx ast::Expr, lhs_expr: &'tcx ast::Expr, lhs_ty: Ty<'tcx>, rhs_expr: &'tcx ast::Expr, op: ast::B...
check_overloaded_binop
identifier_name
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
let slice = unsafe { slice::from_raw_parts(msg_c, len) }; let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str"); let ret = String::from(res_str); unsafe { turtlc_free(msg_c, len); } Some(ret) } pub fn lasterr() -> Option<String> { let ptr ...
{ return None; }
conditional_block
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
handle } /// Send a message to the core pub fn send(msg: &str) { let msg_vec = Vec::from(String::from(msg).as_bytes()); let ret = unsafe { turtlc_send(msg_vec.as_ptr(), msg_vec.len()) }; if ret != 0 { panic!("Error sending msg: err {}", ret); } } /// Receive a message from the...
{ if env::var("TURTL_CONFIG_FILE").is_err() { env::set_var("TURTL_CONFIG_FILE", "../config.yaml"); } let config_copy = String::from(app_config); let handle = thread::spawn(move || { // send in a the config options we need for our tests let app_config = config_copy.as_str(); ...
identifier_body
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
} } let slice = unsafe { slice::from_raw_parts(msg_c, len) }; let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str"); let ret = String::from(res_str); unsafe { turtlc_free(msg_c, len); } ret } /// Receive a core event (non blocking) pub...
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
random_line_split
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
(msg: &str) { let msg_vec = Vec::from(String::from(msg).as_bytes()); let ret = unsafe { turtlc_send(msg_vec.as_ptr(), msg_vec.len()) }; if ret != 0 { panic!("Error sending msg: err {}", ret); } } /// Receive a message from the core, blocking (note that if you are not using /// {"req...
send
identifier_name
daclips.py
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 3 of the License, or (at your option) any later version. ...
(self, url, host): if self.get_setting('enabled') == 'false': return False return re.match(self.pattern, url) or self.name in host
valid_url
identifier_name
daclips.py
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 3 of the License, or (at your option) any later version. ...
post_url = resp.get_url() form_values = {} for i in re.finditer('<input type="hidden" name="(.+?)" value="(.+?)">', html): form_values[i.group(1)] = i.group(2) html = self.net.http_POST(post_url, form_data=form_values).content r = re.search('f...
raise Exception ('File Not Found or removed')
conditional_block
daclips.py
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 3 of the License, or (at your option) any later version. ...
return re.match(self.pattern, url) or self.name in host
random_line_split
daclips.py
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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 3 of the License, or (at your option) any later version. ...
def get_host_and_id(self, url): r = re.search(self.pattern, url) if r: return r.groups() else: return False def valid_url(self, url, host): if self.get_setting('enabled') == 'false': return False return re.match(self.pattern, url) or self.name ...
return 'http://daclips.in/%s' % (media_id)
identifier_body
giftaid_hmrc_spreadsheet.js
/*global $, jQuery, _, asm, common, config, controller, dlgfx, format, header, html, validate */ $(function() { "use strict"; const giftaid_hmrc_spreadsheet = { render: function() { return [ html.content_header("HMRC Gift Aid Spreadsheet"), html.warn("WARN...
}); }, sync: function() { }, name: "giftaid_hmrc_spreadsheet", animation: "report", autofocus: "#fromdate", title: function() { return _("HMRC Gift Aid Spreadsheet"); }, routes: { "giftaid_hmrc_spreadsheet": function() { common.m...
{ $("#hmrcform").submit(); }
conditional_block
giftaid_hmrc_spreadsheet.js
/*global $, jQuery, _, asm, common, config, controller, dlgfx, format, header, html, validate */ $(function() { "use strict"; const giftaid_hmrc_spreadsheet = { render: function() { return [ html.content_header("HMRC Gift Aid Spreadsheet"), html.warn("WARN...
title: function() { return _("HMRC Gift Aid Spreadsheet"); }, routes: { "giftaid_hmrc_spreadsheet": function() { common.module_start("giftaid_hmrc_spreadsheet"); } } }; common.module_register(giftaid_hmrc_spreadsheet); });
animation: "report", autofocus: "#fromdate",
random_line_split
comment.py
import json from boxsdk.object.base_object import BaseObject from ..util.api_call_decorator import api_call class Comment(BaseObject): """An object that represents a comment on an item""" _item_type = 'comment' @staticmethod def construct_params_from_message(message: str) -> dict: message_ty...
(self, message: str) -> 'Comment': """ Edit the message of the comment. :param message: The content of the reply comment. """ data = self.construct_params_from_message(message) return self.update_info(data=data)
edit
identifier_name
comment.py
import json from boxsdk.object.base_object import BaseObject from ..util.api_call_decorator import api_call class Comment(BaseObject): """An object that represents a comment on an item""" _item_type = 'comment' @staticmethod def construct_params_from_message(message: str) -> dict: message_ty...
""" Edit the message of the comment. :param message: The content of the reply comment. """ data = self.construct_params_from_message(message) return self.update_info(data=data)
identifier_body
comment.py
import json from boxsdk.object.base_object import BaseObject from ..util.api_call_decorator import api_call class Comment(BaseObject): """An object that represents a comment on an item""" _item_type = 'comment' @staticmethod
message_type: message } @api_call def reply(self, message: str) -> 'Comment': """ Add a reply to the comment. :param message: The content of the reply comment. """ url = self.get_type_url() data = self.construct_params_from_messag...
def construct_params_from_message(message: str) -> dict: message_type = 'tagged_message' if '@[' in message else 'message' return {
random_line_split
views.py
import datetime import uuid import pytz import os import time from django.contrib.sites.shortcuts import get_current_site from django.core.servers.basehttp import FileWrapper from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse, resolve from django.db.models import FieldDoes...
(build_info): """ Check whether the build can begin immediately or needs to be queued. If it can start; start it, else set queued to True and save build_info. :param build_info: BuildInfo instance to queue or start :returns: True if build started, else False """ if BuildInfo.objects.filter...
_start_queue_build
identifier_name
views.py
import datetime import uuid import pytz import os import time from django.contrib.sites.shortcuts import get_current_site from django.core.servers.basehttp import FileWrapper from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse, resolve from django.db.models import FieldDoes...
if not project: return HttpResponse('no project created', status=403) # this makes it even more impossible to guess key via brute force time.sleep(0.2) build_info = BuildInfo.objects.create(project=project) response_code, build_info2 = cid.process_github_webhook(request, build_info) if r...
@csrf_exempt @require_POST def webhook(request, pk): project = get_project(pk)
random_line_split
views.py
import datetime import uuid import pytz import os import time from django.contrib.sites.shortcuts import get_current_site from django.core.servers.basehttp import FileWrapper from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse, resolve from django.db.models import FieldDoes...
""" gets the first project, stop gap until we support more than one project """ projects = Project.objects.all() if pk is not None: projects = projects.filter(pk=pk) return projects.first()
identifier_body
views.py
import datetime import uuid import pytz import os import time from django.contrib.sites.shortcuts import get_current_site from django.core.servers.basehttp import FileWrapper from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse, resolve from django.db.models import FieldDoes...
return not build_info.queued def check(request, build_info): bi = build_info try: set_site(bi.project, request) bi = cid.check(build_info) except cid.KnownError, e: messages.error(request, str(e)) bi = build_info finally: return bi def check_build(request...
cid.build(build_info)
conditional_block
bootstrap.js
'use strict';
* your application gets started. * * This gives you an opportunity to set up your data model, * run jobs, or perform some special logic. */ const path = require('path'); const fs = require('fs'); const _ = require('lodash'); module.exports = async cb => { // set plugin store const pluginStore = strapi.store(...
/** * An asynchronous bootstrap function that runs before
random_line_split
bootstrap.js
'use strict'; /** * An asynchronous bootstrap function that runs before * your application gets started. * * This gives you an opportunity to set up your data model, * run jobs, or perform some special logic. */ const path = require('path'); const fs = require('fs'); const _ = require('lodash'); module.exports...
} catch (err) { strapi.log.error(`Can't load ${config.provider} upload provider.`); strapi.log.warn(`Please install strapi-provider-upload-${config.provider} --save in ${path.join(strapi.config.appPath, 'plugins', 'upload')} folder.`); strapi.stop(); } cb(); }); }; /...
{ const provider = _.find(strapi.plugins.upload.config.providers, {provider: 'local'}); const value = _.assign({}, provider, { enabled: true, // by default limit size to 1 GB sizeLimit: 1000000 }); await pluginStore.set({key: 'provider', valu...
conditional_block
v-mask.js
Property(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescri...
} var conformedValue = emptyString; var someCharsRejected = false; placeholderLoop: for (var _i2 = 0; _i2 < placeholderLength; _i2++) { var charInPlaceholder = placeholder[_i2]; if (charInPlaceholder === placeholderChar$1) { if (rawValueArr.length > 0) { while (rawValue...
{ var shouldOffset = _i >= indexOfFirstChange && previousConformedValueLength === maskLength; if (char === placeholder[shouldOffset ? _i - editDistance : _i]) { rawValueArr.splice(_i, 1); } }
conditional_block
v-mask.js
CaretTrap), indexOfCaretTrap !== -1) { indexes.push(indexOfCaretTrap); mask.splice(indexOfCaretTrap, 1); } return { maskWithoutCaretTraps: mask, indexes: indexes }; } var emptyArray$1 = []; var emptyString = ''; function conformToMask() { var rawValue = arguments.length...
{ elementOptions.set(el, _objectSpread2({}, get(el), {}, newOptions)); }
identifier_body
v-mask.js
Property(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescri...
var conformedValue = emptyString; var someCharsRejected = false; placeholderLoop: for (var _i2 = 0; _i2 < placeholderLength; _i2++) { var charInPlaceholder = placeholder[_i2]; if (charInPlaceholder === placeholderChar$1) { if (rawValueArr.length > 0) { while (rawValueArr.len...
} } }
random_line_split
v-mask.js
Property(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescri...
(value) { return Array.isArray && Array.isArray(value) || value instanceof Array; } var strCaretTrap = '[]'; function processCaretTraps(mask) { var indexes = []; var indexOfCaretTrap; while (indexOfCaretTrap = mask.indexOf(strCaretTrap), indexOfCaretTrap !== -1) { indexes.push(indexOfCaretT...
isArray
identifier_name
build_docs.py
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from google.protobuf.reflection import GeneratedProtocolMessageType flags.DEFINE_string('output_dir', '/tmp/mlmd_api', 'Where to output the docs') flags.DEFINE_string( 'code_url_prefix', 'https://github.com/google/ml-metadata/tree/master/ml_metadata', 'The url prefix for links to code.') flags.DEFINE_bool...
from tensorflow_docs.api_generator import generate_lib from tensorflow_docs.api_generator import public_api import ml_metadata as mlmd
random_line_split
build_docs.py
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
suppress_docs_for = [] for name in ['version', 'goo'+'gle', 'metadata_store', 'pywrap']: submodule = getattr(mlmd, name, None) if submodule is not None: suppress_docs_for.append(submodule) for obj in suppress_docs_for: doc_controls.do_not_generate_docs(obj) doc_generator = generate_lib.Doc...
raise ValueError('Unrecognized command line args', args[1:])
conditional_block
build_docs.py
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
return new_children def main(args): if args[1:]: raise ValueError('Unrecognized command line args', args[1:]) suppress_docs_for = [] for name in ['version', 'goo'+'gle', 'metadata_store', 'pywrap']: submodule = getattr(mlmd, name, None) if submodule is not None: suppress_docs_for.append(su...
"""Remove auto generated attrs methods. Args: path: A tuple of name parts forming the attribute-lookup path to this object. For `tf.keras.layers.Dense` path is: ("tf","keras","layers","Dense") parent: The parent object. children: A list of (name, value) pairs. The attributes of the patent. ...
identifier_body
build_docs.py
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(path, parent, children): """Remove all the proto inherited methods. Args: path: A tuple of name parts forming the attribute-lookup path to this object. For `tf.keras.layers.Dense` path is: ("tf","keras","layers","Dense") parent: The parent object. children: A list of (name, value) pairs....
ignore_proto_method
identifier_name
scanner.py
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FL...
(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None: ...
iterscan
identifier_name
scanner.py
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FL...
p.append(subpattern) self.actions.append(token) p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = sel...
raise
random_line_split
scanner.py
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object):
def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is ...
def __init__(self, lexicon, flags=FLAGS): self.actions = [None] # combine phrases into a compound pattern s = sre_parse.Pattern() s.flags = flags p = [] for idx, token in enumerate(lexicon): phrase = token.pattern try: subpattern = ...
identifier_body
scanner.py
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FL...
yield rval, matchend lastend = matchend def pattern(pattern, flags=FLAGS): def decorator(fn): fn.pattern = pattern fn.regex = re.compile(pattern, flags) return fn return decorator
matchend = next_pos match = self.scanner.scanner(string, matchend).match
conditional_block
basic.py
wb_messages, } ) def search(request): """ Performs site-wide search on units. """ search_form = SearchForm(request.GET) context = { 'search_form': search_form, } if search_form.is_valid(): units = Unit.objects.search( None, search_form....
_language(re
identifier_name
basic.py
Project, SubProject, Translation, Check, Dictionary, Change, Unit, WhiteboardMessage ) from weblate.requirements import get_versions, get_optional_versions from weblate.lang.models import Language from weblate.trans.forms import ( get_upload_form, SearchForm, AutoForm, ReviewForm, NewLanguageForm, User...
units = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. units = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of # results. units = pagina...
ts = Unit.objects.search( None, search_form.cleaned_data, ).select_related( 'translation', ) # Filter results by ACL acl_projects, filtered = Project.objects.get_acl_status(request.user) if filtered: units = units.filter( ...
conditional_block
basic.py
Project, SubProject, Translation, Check, Dictionary, Change, Unit, WhiteboardMessage ) from weblate.requirements import get_versions, get_optional_versions from weblate.lang.models import Language from weblate.trans.forms import ( get_upload_form, SearchForm, AutoForm, ReviewForm, NewLanguageForm, User...
projects = Project.objects.all_acl(request.user) if projects.count() == 1: projects = SubProject.objects.filter( project=projects[0] ).select_related() # Warn about not filled in username (usually caused by migration of # users from older system if not request.user.is_a...
) ) return redirect('password') wb_messages = WhiteboardMessage.objects.all()
random_line_split
basic.py
Project, SubProject, Translation, Check, Dictionary, Change, Unit, WhiteboardMessage ) from weblate.requirements import get_versions, get_optional_versions from weblate.lang.models import Language from weblate.trans.forms import ( get_upload_form, SearchForm, AutoForm, ReviewForm, NewLanguageForm, User...
# Review form for logged in users if request.user.is_anonymous(): review_form = None else: review_form = ReviewForm( initial={ 'date': datetime.date.today() - datetime.timedelta(days=31) } ) return render( request, 'transla...
= get_translation(request, project, subproject, lang) last_changes = Change.objects.prefetch().filter( translation=obj )[:10] # Check locks obj.is_locked(request.user) # Get form form = get_upload_form(request)() # Is user allowed to do automatic translation? if request.user....
identifier_body
concat.spec.js
const test = require('tape') const helpers = require('../test/helpers') const Last = require('../test/LastMonoid') const bindFunc = helpers.bindFunc const isFunction = require('../core/isFunction') const unit = require('../core/_unit') const concat = require('./concat') test('concat pointfree', t => { const f = ...
}) test('concat pointfree strings', t => { const a = 'one' const b = 'two' const ab = a + b t.equal(concat(b, a), ab, 'concats the first string to the second') t.end() }) test('concat pointfree arrays', t => { t.same(concat( [ 2 ], [ 1 ]), [ 1, 2 ], 'concats number on array') t.same(concat( [ '2' ], [...
random_line_split