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 |
|---|---|---|---|---|
font.rs | (id) => id,
None => continue,
};
let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id));
if character == ' ' {
// https://drafts.csswg.org/css-text-3/#word-spacing-property
let (length, percent) = options.word_spacing;
... | {
let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst);
TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst);
value
} | identifier_body | |
font.rs | 64;
pub type FontTableTag = u32;
trait FontTableTagConversions {
fn tag_to_str(&self) -> String;
}
impl FontTableTagConversions for FontTableTag {
fn tag_to_str(&self) -> String {
let bytes = [(self >> 24) as u8,
(self >> 16) as u8,
(self >> 8) as u8,
... | (&self, codepoint: char) -> Option<GlyphId> {
let codepoint = match self.descriptor.variant {
font_variant_caps::T::SmallCaps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938
font_variant_caps::T::Normal => codepoint,
};
self.handle.glyph_index(codepoint)
}... | glyph_index | identifier_name |
font.rs | (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32)
);
}
pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S');
pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B');
pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n');
static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE... | macro_rules! ot_tag {
($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( | random_line_split | |
utils.py | import jwt
from time import time
from partner_data import partners
"""
Returns the partner object of given partnerId
Args:
ssoId Id of the partner
Returns:
The partner object
"""
def | (ssoId):
if ssoId in partners and partners[ssoId]['is_active']:
return partners[ssoId]
raise Exception('partnerId not found or suspended')
"""
Generate JSON Web Token for partner service
Args:
ssoId Id of the partner
key Shared key to sign the token
Returns:
encoded JWT
"""
def gener... | getSSOPartnerById | identifier_name |
utils.py | import jwt
from time import time
from partner_data import partners
"""
Returns the partner object of given partnerId
Args:
ssoId Id of the partner
Returns:
The partner object
"""
def getSSOPartnerById(ssoId):
if ssoId in partners and partners[ssoId]['is_active']:
return partners[ssoId]
rais... | Decoded token content if the token is valid
"""
def verifyToken(ssoId, token):
partner = getSSOPartnerById(ssoId)
return jwt.decode(token,
partner["shared_key"],
algorithms=['HS256'],
audience=ssoId
) | Returns: | random_line_split |
utils.py | import jwt
from time import time
from partner_data import partners
"""
Returns the partner object of given partnerId
Args:
ssoId Id of the partner
Returns:
The partner object
"""
def getSSOPartnerById(ssoId):
if ssoId in partners and partners[ssoId]['is_active']:
|
raise Exception('partnerId not found or suspended')
"""
Generate JSON Web Token for partner service
Args:
ssoId Id of the partner
key Shared key to sign the token
Returns:
encoded JWT
"""
def generateToken(ssoId, key):
token ={
'email': 'example@abc.com',
'iss': 'https://lin... | return partners[ssoId] | conditional_block |
utils.py | import jwt
from time import time
from partner_data import partners
"""
Returns the partner object of given partnerId
Args:
ssoId Id of the partner
Returns:
The partner object
"""
def getSSOPartnerById(ssoId):
|
"""
Generate JSON Web Token for partner service
Args:
ssoId Id of the partner
key Shared key to sign the token
Returns:
encoded JWT
"""
def generateToken(ssoId, key):
token ={
'email': 'example@abc.com',
'iss': 'https://linways.com',
'exp': int(time() + (3*60)),
... | if ssoId in partners and partners[ssoId]['is_active']:
return partners[ssoId]
raise Exception('partnerId not found or suspended') | identifier_body |
339NestedListWeightSum.py | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single i... | return ans | random_line_split | |
339NestedListWeightSum.py | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single i... |
return ans | ans += self.depthSum(nested_integer.getList(), d + 1) | conditional_block |
339NestedListWeightSum.py | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single i... | def depthSum(self, nestedList, d = 1):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
if not nestedList: return 0
ans = 0
for nested_integer in nestedList:
if nested_integer.isInteger():
ans += nested_integer.getInte... | identifier_body | |
339NestedListWeightSum.py | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single i... | :
def depthSum(self, nestedList, d = 1):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
if not nestedList: return 0
ans = 0
for nested_integer in nestedList:
if nested_integer.isInteger():
ans += nested_integer.g... | Solution | identifier_name |
atomic_state_client.ts | /**
* @license
* 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... | () {
if (!this.sendUpdates) {
return;
}
if (!this.connected_ || (this.receiveUpdates && this.serverGeneration === '') ||
this.clientGeneration === this.state.changed.count) {
return;
}
const newStateJson = getCachedJson(this.state).value;
const newStateEncoded = JSON.stringif... | handleStateChanged | identifier_name |
atomic_state_client.ts | /**
* @license
* 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... |
get connected() {
return this.connected_;
}
/**
* @param updateDelayMilliseconds If `null`, this client is receive only. No updates are sent.
* @param receiveUpdates If `false`, this client doesn't receive updates.
*/
constructor(
public state: Trackable, updateDelayMilliseconds: number|n... | {
if (value !== this.connected_) {
this.connected_ = value;
if (value === true) {
if (this.receiveUpdates) {
this.receiveUpdateRequested.dispatch(this.serverGeneration);
}
this.handleStateChanged();
}
}
} | identifier_body |
atomic_state_client.ts | /**
* @license
* 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... |
if (!this.connected_ || (this.receiveUpdates && this.serverGeneration === '') ||
this.clientGeneration === this.state.changed.count) {
return;
}
const newStateJson = getCachedJson(this.state).value;
const newStateEncoded = JSON.stringify(newStateJson);
if (newStateEncoded === this.las... | {
return;
} | conditional_block |
atomic_state_client.ts | /**
* @license
* 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... | constructor(
public state: Trackable, updateDelayMilliseconds: number|null = 100,
public receiveUpdates = true) {
super();
if (updateDelayMilliseconds !== null) {
this.sendUpdates = true;
this.registerDisposer(state.changed.add(this.registerCancellable(throttle(
this.register... |
/**
* @param updateDelayMilliseconds If `null`, this client is receive only. No updates are sent.
* @param receiveUpdates If `false`, this client doesn't receive updates.
*/ | random_line_split |
server.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import e... |
});
res.status(statusCode);
res.send(template(data));
} catch (err) {
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) ... |
css = [];
statusCode = status;
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
return true;
}, | identifier_body |
server.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import e... | });
/* eslint-enable no-console */ | random_line_split | |
server.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import e... |
await match(routes, {
path: req.path,
query: req.query,
context: {
insertCss: styles => css.push(styles._getCss()),
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
render(component, status = 200) {
css = [];
... |
data.trackingId = analytics.google.trackingId;
}
| conditional_block |
server.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import e... | component, status = 200) {
css = [];
statusCode = status;
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
return true;
},
});
res.status(statusCode);
res.send(template(data));
} catch (err) {
next(err);
}
});
//
// Error handli... | ender( | identifier_name |
ArrayUtils.d.ts | export declare class ArrayUtils {
/**
* search item in array by function
* @param arr
* @param f
* @deprecated use Array.prototype.find
* @return {T}
*/
static search<T>(arr: T[], f: (v: T) => boolean): T;
/**
*
* @deprecated use Array.prototype.findIndex
* @para... | static argFilter<T>(arr: T[], callbackfn: (value: T, index: number) => boolean, thisArg?: any): number[];
} | * @param callbackfn
* @param thisArg
*/ | random_line_split |
ArrayUtils.d.ts | export declare class | {
/**
* search item in array by function
* @param arr
* @param f
* @deprecated use Array.prototype.find
* @return {T}
*/
static search<T>(arr: T[], f: (v: T) => boolean): T;
/**
*
* @deprecated use Array.prototype.findIndex
* @param arr
* @param f
* @r... | ArrayUtils | identifier_name |
Alias.d.ts | import type { Document } from '../doc/Document.js';
import type { FlowScalar } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { NodeBase, Range } from './Node.js';
import type { Scalar } from './Scalar';
import type { ToJSContext } from './toJS.js';
import type { YAMLM... | extends NodeBase {
source: string;
anchor?: never;
constructor(source: string);
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined;
toJSON(_arg?... | Alias | identifier_name |
Alias.d.ts | import type { Document } from '../doc/Document.js';
import type { FlowScalar } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { NodeBase, Range } from './Node.js';
import type { Scalar } from './Scalar';
import type { ToJSContext } from './toJS.js';
import type { YAMLM... | }
export declare class Alias extends NodeBase {
source: string;
anchor?: never;
constructor(source: string);
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq |... | srcToken?: FlowScalar & {
type: 'alias';
};
} | random_line_split |
event.rs | use std::io::Write;
use termion::event::Key;
use Editor;
pub type EventHandler<'a, W> = FnMut(Event<W>) + 'a;
pub struct Event<'a, 'out: 'a, W: Write + 'a> {
pub editor: &'a mut Editor<'out, W>, | pub fn new(editor: &'a mut Editor<'out, W>, kind: EventKind) -> Self {
Event {
editor: editor,
kind: kind,
}
}
}
#[derive(Debug)]
pub enum EventKind {
/// Sent before handling a keypress.
BeforeKey(Key),
/// Sent after handling a keypress.
AfterKey(Key),
... | pub kind: EventKind,
}
impl<'a, 'out: 'a, W: Write + 'a> Event<'a, 'out, W> { | random_line_split |
event.rs | use std::io::Write;
use termion::event::Key;
use Editor;
pub type EventHandler<'a, W> = FnMut(Event<W>) + 'a;
pub struct Event<'a, 'out: 'a, W: Write + 'a> {
pub editor: &'a mut Editor<'out, W>,
pub kind: EventKind,
}
impl<'a, 'out: 'a, W: Write + 'a> Event<'a, 'out, W> {
pub fn new(editor: &'a mut Edito... |
}
#[derive(Debug)]
pub enum EventKind {
/// Sent before handling a keypress.
BeforeKey(Key),
/// Sent after handling a keypress.
AfterKey(Key),
/// Sent in `Editor.complete()`, before processing the completion.
BeforeComplete,
}
| {
Event {
editor: editor,
kind: kind,
}
} | identifier_body |
event.rs | use std::io::Write;
use termion::event::Key;
use Editor;
pub type EventHandler<'a, W> = FnMut(Event<W>) + 'a;
pub struct | <'a, 'out: 'a, W: Write + 'a> {
pub editor: &'a mut Editor<'out, W>,
pub kind: EventKind,
}
impl<'a, 'out: 'a, W: Write + 'a> Event<'a, 'out, W> {
pub fn new(editor: &'a mut Editor<'out, W>, kind: EventKind) -> Self {
Event {
editor: editor,
kind: kind,
}
}
}
#[... | Event | identifier_name |
test.ts | import * as tape from 'tape';
import {TwingNodeExpressionConstant} from "../../../../../../../../src/lib/node/expression/constant";
import {TwingNodeExpressionUnaryPos} from "../../../../../../../../src/lib/node/expression/unary/pos";
import {TwingNodeType} from "../../../../../../../../src/lib/node";
import {MockCompi... |
test.same(compiler.compile(node).getSource(), '+(1)');
test.end();
});
test.end();
}); | test.test('compile', (test) => {
let compiler = new MockCompiler();
let expr = new TwingNodeExpressionConstant(1, 1, 1);
let node = new TwingNodeExpressionUnaryPos(expr, 1, 1); | random_line_split |
external-library-modal.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Library} from '../../../../entity/library';
import {LibraryService} from '../../../../service/library.service';
import {logger} from '../../../../environments/environment';
import {Mod... | ublic showModal() {
this.externalLibraryModal.show();
}
public hideModal() {
this.externalLibraryModal.hide();
}
}
| this.libraryService.findExternalLibraries()
.then(externalLibraries => this.variousItemDataService.externalLibraries = externalLibraries)
.catch(error => logger.error(error));
}
p | identifier_body |
external-library-modal.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Library} from '../../../../entity/library';
import {LibraryService} from '../../../../service/library.service';
import {logger} from '../../../../environments/environment';
import {Mod... | this.externalLibraryName = new FormControl('');
}
ngOnInit(): void {
this.externalLibraryForm = this.formBuilder.group({
'externalLibraryName': this.externalLibraryName
});
}
onLibrarySubmit(): void {
if (this.externalLibraryForm.valid) {
let value = this.externalLibraryForm.value;... | private variousItemDataService: VariousItemDataService
) { | random_line_split |
external-library-modal.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Library} from '../../../../entity/library';
import {LibraryService} from '../../../../service/library.service';
import {logger} from '../../../../environments/environment';
import {Mod... | se {
this.toastr.error('Impossible de créer la bibliothèque tiers', 'Oops');
logger.info('Invalid form :', this.externalLibraryForm);
}
}
public populateExternalLibraries(): void {
this.libraryService.findExternalLibraries()
.then(externalLibraries => this.variousItemDataService.externalL... | {
let value = this.externalLibraryForm.value;
let library: Library = new Library();
library.name = value.externalLibraryName;
this.libraryService.saveExternal(library)
.then(library => {
this.toastr.info(`Bibliothèque ${library.name} ajoutée`, 'Nouvelle bibliothèque');
... | conditional_block |
external-library-modal.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Library} from '../../../../entity/library';
import {LibraryService} from '../../../../service/library.service';
import {logger} from '../../../../environments/environment';
import {Mod... | (
private libraryService: LibraryService,
public toastr: ToastrService,
private formBuilder: FormBuilder,
private variousItemDataService: VariousItemDataService
) {
this.externalLibraryName = new FormControl('');
}
ngOnInit(): void {
this.externalLibraryForm = this.formBuilder.gro... | constructor | identifier_name |
TCNarrativeTextCtrl.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | (self, parent, winId):
wx.TextCtrl.__init__(self,parent,winId,size=(150,100),style=wx.TE_MULTILINE)
self.ctrlMenu = wx.Menu()
self.cmItem = self.ctrlMenu.Append(armid.TCNTC_LISTCHARACTERISTICS_ID,'Characteristics')
self.viItem = self.ctrlMenu.Append(armid.TCNTC_VISCHARACTERISTICS_ID,'Visualise')
wx.... | __init__ | identifier_name |
TCNarrativeTextCtrl.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
except ARMException,errorText:
dialog.destroy()
dlg = wx.MessageDialog(self,str(errorText),'Edit Task Characteristics',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
| errorTxt = 'No assumption task associations defined'
dlg = wx.MessageDialog(self,errorTxt,'View Assumption Task Model',wx.OK | wx.ICON_EXCLAMATION)
dlg.ShowModal()
dlg.Destroy() | conditional_block |
TCNarrativeTextCtrl.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | from Borg import Borg
from AssumptionTaskModel import AssumptionTaskModel
from ATModelViewer import ATModelViewer
class TCNarrativeTextCtrl(wx.TextCtrl):
def __init__(self, parent, winId):
wx.TextCtrl.__init__(self,parent,winId,size=(150,100),style=wx.TE_MULTILINE)
self.ctrlMenu = wx.Menu()
self.cmItem =... | from BehaviouralCharacteristicsDialog import BehaviouralCharacteristicsDialog | random_line_split |
TCNarrativeTextCtrl.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | dialog.ShowModal()
dialog.Destroy()
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Edit Task Characteristics',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
def Set(self,tName,ctrlVal):
self.theTaskName = tName
self.SetValue(ctr... | def __init__(self, parent, winId):
wx.TextCtrl.__init__(self,parent,winId,size=(150,100),style=wx.TE_MULTILINE)
self.ctrlMenu = wx.Menu()
self.cmItem = self.ctrlMenu.Append(armid.TCNTC_LISTCHARACTERISTICS_ID,'Characteristics')
self.viItem = self.ctrlMenu.Append(armid.TCNTC_VISCHARACTERISTICS_ID,'Visuali... | identifier_body |
lib.rs | #![recursion_limit = "1024"] // for error_chain!
extern crate rand;
extern crate scopeguard;
#[macro_use]
extern crate error_chain;
extern crate rustc_serialize;
extern crate sha2;
extern crate url;
extern crate toml;
extern crate download;
extern crate semver;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
ext... | pub use errors::*;
pub use notifications::{Notification};
pub mod notify; | random_line_split | |
verify-homepage.py | #!/usr/bin/env python
# This script is used for verify HOMEPAGE.
# The result is influenced by network environment, since the timeout of connect url is 5 seconds as default.
import sys
import os
import subprocess
import urllib2
def search_bitbakepath():
bitbakepath = ""
# Search path to bitbake lib dir in o... | (pn, homepage):
result = subprocess.call('wget ' + '-q -T 5 -t 1 --spider ' + homepage, shell = True)
if result:
bb.warn("Failed to verify HOMEPAGE (%s) of %s" % (homepage, pn))
return 1
else:
return 0
def verifyHomepage(bbhandler):
pkg_pn = bbhandler.cooker.recipecache.pkg_pn
... | wgetHomepage | identifier_name |
verify-homepage.py | #!/usr/bin/env python
# This script is used for verify HOMEPAGE.
# The result is influenced by network environment, since the timeout of connect url is 5 seconds as default.
import sys
import os
import subprocess
import urllib2
def search_bitbakepath():
bitbakepath = ""
# Search path to bitbake lib dir in o... | pkg_pn = bbhandler.cooker.recipecache.pkg_pn
pnlist = sorted(pkg_pn)
count = 0
for pn in pnlist:
fn = pkg_pn[pn].pop()
data = bb.cache.Cache.loadDataFull(fn, bbhandler.cooker.collection.get_file_appends(fn), bbhandler.config_data)
homepage = data.getVar("HOMEPAGE")
if hom... | else:
return 0
def verifyHomepage(bbhandler): | random_line_split |
verify-homepage.py | #!/usr/bin/env python
# This script is used for verify HOMEPAGE.
# The result is influenced by network environment, since the timeout of connect url is 5 seconds as default.
import sys
import os
import subprocess
import urllib2
def search_bitbakepath():
|
# For importing the following modules
sys.path.insert(0, search_bitbakepath())
import bb.tinfoil
def wgetHomepage(pn, homepage):
result = subprocess.call('wget ' + '-q -T 5 -t 1 --spider ' + homepage, shell = True)
if result:
bb.warn("Failed to verify HOMEPAGE (%s) of %s" % (homepage, pn))
re... | bitbakepath = ""
# Search path to bitbake lib dir in order to load bb modules
if os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), '../../bitbake/lib/bb')):
bitbakepath = os.path.join(os.path.dirname(sys.argv[0]), '../../bitbake/lib')
bitbakepath = os.path.abspath(bitbakepath)
else:... | identifier_body |
verify-homepage.py | #!/usr/bin/env python
# This script is used for verify HOMEPAGE.
# The result is influenced by network environment, since the timeout of connect url is 5 seconds as default.
import sys
import os
import subprocess
import urllib2
def search_bitbakepath():
bitbakepath = ""
# Search path to bitbake lib dir in o... | failcount = 0
bbhandler = bb.tinfoil.Tinfoil()
bbhandler.prepare()
print "Start to verify HOMEPAGE:"
failcount = verifyHomepage(bbhandler)
print "finish to verify HOMEPAGE."
print "Summary: %s failed" % failcount | conditional_block | |
Timezones.py | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
t... |
return self.timezones[0][0]
timezones = Timezones()
| if a == t:
return a | conditional_block |
Timezones.py | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
t... | return
environ['TZ'] = self.timezones[index][1]
try:
unlink("/etc/localtime")
except OSError:
pass
try:
symlink("/usr/share/zoneinfo/%s" %(self.timezones[index][1]), "/etc/localtime")
except OSError:
pass
try:
time.tzset()
except:
from enigma import e_tzset
e_tzset()
if path.... | random_line_split | |
Timezones.py | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
t... | (self, index):
if len(self.timezones) <= index:
return
environ['TZ'] = self.timezones[index][1]
try:
unlink("/etc/localtime")
except OSError:
pass
try:
symlink("/usr/share/zoneinfo/%s" %(self.timezones[index][1]), "/etc/localtime")
except OSError:
pass
try:
time.tzset()
except:
f... | activateTimezone | identifier_name |
Timezones.py | import xml.etree.cElementTree
from os import environ, unlink, symlink, path
from Tools.Directories import SCOPE_SKIN, resolveFilename
import time
from Tools.StbHardware import setRTCoffset
class Timezones:
def __init__(self):
self.timezones = []
self.readTimezonesFromFile()
def readTimezonesFromFile(self):
t... |
def getDefaultTimezone(self):
# TODO return something more useful - depending on country-settings?
t = "(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Vienna"
for (a,b) in self.timezones:
if a == t:
return a
return self.timezones[0][0]
timezones = Timezones()
| return [ str(x[0]) for x in self.timezones ] | identifier_body |
core_application.rs | include_generated!();
/// A struct providing valid `argc` and `argv` values for Qt application
/// objects.
///
/// Constructors of `qt_core::core_application::CoreApplication`,
/// `qt_gui::gui_application::GuiApplication` and `qt_widgets::application::Application`
/// require `argc` and `argv` values that are availa... |
#[cfg(windows)]
/// Creates an object representing real arguments of the application.
/// On Windows, this function uses empty argument list for performance reasons because
/// Qt doesn't use `argc` and `argv` on Windows at all.
pub fn from_real() -> CoreApplicationArgs {
// Qt doesn't use argc and argv ... | {
use std::os::unix::ffi::OsStringExt;
let args = ::std::env::args_os().map(|arg| arg.into_vec()).collect();
CoreApplicationArgs::from(args)
} | identifier_body |
core_application.rs | include_generated!();
/// A struct providing valid `argc` and `argv` values for Qt application
/// objects. | /// `qt_gui::gui_application::GuiApplication` and `qt_widgets::application::Application`
/// require `argc` and `argv` values that are available in C++'s `main` function but
/// not available in Rust. More importantly, `argc` and `argv` must be valid for the entire
/// life of the application. This struct stores list o... | ///
/// Constructors of `qt_core::core_application::CoreApplication`, | random_line_split |
core_application.rs | include_generated!();
/// A struct providing valid `argc` and `argv` values for Qt application
/// objects.
///
/// Constructors of `qt_core::core_application::CoreApplication`,
/// `qt_gui::gui_application::GuiApplication` and `qt_widgets::application::Application`
/// require `argc` and `argv` values that are availa... | (&mut self) -> (&mut ::libc::c_int, *mut *mut ::libc::c_char) {
(self.argc.as_mut(), self.argv.as_mut_ptr())
}
#[cfg(unix)]
/// Creates an object representing real arguments of the application.
/// On Windows, this function uses empty argument list for performance reasons because
/// Qt doesn't use `argc... | get | identifier_name |
core_application.rs | include_generated!();
/// A struct providing valid `argc` and `argv` values for Qt application
/// objects.
///
/// Constructors of `qt_core::core_application::CoreApplication`,
/// `qt_gui::gui_application::GuiApplication` and `qt_widgets::application::Application`
/// require `argc` and `argv` values that are availa... |
}
CoreApplicationArgs {
argc: Box::new(args.len() as ::libc::c_int),
argv: args
.iter_mut()
.map(|x| x.as_mut_ptr() as *mut ::libc::c_char)
.collect(),
_values: args,
}
}
/// Creates an object containing empty list of arguments.
/// Although this is the cheap... | {
arg.push(0);
} | conditional_block |
main.rs | extern crate dialoguer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
use dialoguer::Input;
use std::path::PathBuf;
use std::{
fs::{self, File},
io::Write,
path::Path,
};
mod api_generator;
mod error;
mod rest_spec;
fn main() {
// This must be run from the src root directo... |
}
}
| {
// delete existing generated files if the exist
if generated_dir.exists() {
fs::remove_dir_all(&generated_dir).unwrap();
}
fs::create_dir_all(&generated_dir).unwrap();
api_generator::generate(&branch, &download_dir, &generated_dir).unwrap()... | conditional_block |
main.rs | extern crate dialoguer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
use dialoguer::Input;
use std::path::PathBuf;
use std::{
fs::{self, File},
io::Write,
path::Path,
};
mod api_generator;
mod error;
mod rest_spec;
fn main() {
// This must be run from the src root directo... | }
// only offer to generate if there are downloaded specs
if download_dir
.read_dir()
.map(|mut r| r.next().is_some())
.unwrap_or(false)
{
let mut generate_code = true;
answer = String::new();
while answer != "y" && answer != "n" {
answer = In... | File::create(last_downloaded_version)
.expect("failed to create last_downloaded_version file")
.write_all(branch.as_bytes())
.expect("unable to write branch to last_downloaded_version file"); | random_line_split |
main.rs | extern crate dialoguer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
use dialoguer::Input;
use std::path::PathBuf;
use std::{
fs::{self, File},
io::Write,
path::Path,
};
mod api_generator;
mod error;
mod rest_spec;
fn main() | .interact()
.unwrap()
.to_lowercase();
download_specs = answer == "y";
}
if download_specs {
branch = Input::new()
.default(default_branch.clone())
.show_default(false)
.with_prompt(
format!(
... | {
// This must be run from the src root directory, with cargo run -p api_generator
let download_dir = fs::canonicalize(PathBuf::from("./api_generator/rest_specs")).unwrap();
let generated_dir = fs::canonicalize(PathBuf::from("./elasticsearch/src/generated")).unwrap();
let last_downloaded_version = "./ap... | identifier_body |
main.rs | extern crate dialoguer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
use dialoguer::Input;
use std::path::PathBuf;
use std::{
fs::{self, File},
io::Write,
path::Path,
};
mod api_generator;
mod error;
mod rest_spec;
fn | () {
// This must be run from the src root directory, with cargo run -p api_generator
let download_dir = fs::canonicalize(PathBuf::from("./api_generator/rest_specs")).unwrap();
let generated_dir = fs::canonicalize(PathBuf::from("./elasticsearch/src/generated")).unwrap();
let last_downloaded_version = ".... | main | identifier_name |
BasePicker.scss.js | "use strict"; | /* tslint:disable */
var load_themed_styles_1 = require("@microsoft/load-themed-styles");
var styles = {
pickerText: 'pickerText_56a98698',
inputFocused: 'inputFocused_56a98698',
pickerInput: 'pickerInput_56a98698',
};
load_themed_styles_1.loadStyles([{ "rawString": ".pickerText_56a98698{display:-webkit-box... | random_line_split | |
system.test.js | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | }); | random_line_split | |
zz.events.baseevents_test.js | // Copyright 2016 Artem Lytvynov <buntarb@gmail.com>. 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
//
// Unle... | var baseEvent;
function setUp( ){
baseEvent = new zz.events.BaseEvent( );
}
function testConstructor( ){
assertTrue(
'Instance must be non-null and have the expected class',
baseEvent instanceof zz.events.BaseEvent
);
}
function testInheritance( ){
assertTrue(
'Instance mu... | random_line_split | |
zz.events.baseevents_test.js | // Copyright 2016 Artem Lytvynov <buntarb@gmail.com>. 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
//
// Unle... | {
assertTrue(
'Instance must be non-null and have the expected class',
baseEvent instanceof goog.events.Event
);
} | identifier_body | |
zz.events.baseevents_test.js | // Copyright 2016 Artem Lytvynov <buntarb@gmail.com>. 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
//
// Unle... | ( ){
baseEvent = new zz.events.BaseEvent( );
}
function testConstructor( ){
assertTrue(
'Instance must be non-null and have the expected class',
baseEvent instanceof zz.events.BaseEvent
);
}
function testInheritance( ){
assertTrue(
'Instance must be non-null and have the ex... | setUp | identifier_name |
location_mock.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy, PlatformLocation} from '@angular/common';
import {EventEmitter, Injectable} from ... |
return this._baseHref + url;
}
go(path: string, query: string = '', state: any = null) {
path = this.prepareExternalUrl(path);
this.pushHistory(path, query, state);
const locationState = this._history[this._historyIndex - 1];
if (locationState.path == path && locationState.query == query) {
... | {
url = '/' + url;
} | conditional_block |
location_mock.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy, PlatformLocation} from '@angular/common';
import {EventEmitter, Injectable} from ... | (pathname: string) {
const path = this.prepareExternalUrl(pathname);
this.pushHistory(path, '', null);
this.urlChanges.push('hash: ' + pathname);
// the browser will automatically fire popstate event before each `hashchange` event, so we need
// to simulate it.
this._subject.emit({'url': pathna... | simulateHashChange | identifier_name |
location_mock.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy, PlatformLocation} from '@angular/common';
import {EventEmitter, Injectable} from ... |
onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction {
this._urlChangeListeners.push(fn);
if (!this._urlChangeSubscription) {
this._urlChangeSubscription = this.subscribe(v => {
this._notifyUrlChangeListeners(v.url, v.state);
});
}
return () => {
const fnI... | {
const nextPageIndex = this._historyIndex + relativePosition;
if (nextPageIndex >= 0 && nextPageIndex < this._history.length) {
this._historyIndex = nextPageIndex;
this._subject.emit(
{'url': this.path(), 'state': this.getState(), 'pop': true, 'type': 'popstate'});
}
} | identifier_body |
location_mock.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy, PlatformLocation} from '@angular/common';
import {EventEmitter, Injectable} from ... | const nextPageIndex = this._historyIndex + relativePosition;
if (nextPageIndex >= 0 && nextPageIndex < this._history.length) {
this._historyIndex = nextPageIndex;
this._subject.emit(
{'url': this.path(), 'state': this.getState(), 'pop': true, 'type': 'popstate'});
}
}
onUrlChange(... | {'url': this.path(), 'state': this.getState(), 'pop': true, 'type': 'popstate'});
}
}
historyGo(relativePosition: number = 0): void { | random_line_split |
createElt.ts |
class HTMLElt<M extends ReadOnly> {
constructor() { }
}
class DivElt<M extends ReadOnly> extends HTMLElt<M> {
public htmlDivElt__ = 0;
constructor() {
super();
}
}
class SpanElt<M extends ReadOnly> extends HTMLElt<M> {
public htmlSpanElt__ = 1;
| () {
super();
}
}
class CanvasElt<M extends ReadOnly> extends HTMLElt<M> {
public htmlCanvasElt__ = 2;
constructor() {
super();
}
}
/*@ predicate TT v x n e = (x = n => extends_class(v, e)) */
/*@ createElt :: (tagName: string) => {v: HTMLElt<ReadOnly> |
(TT v tagName "div" "DivEl... | constructor | identifier_name |
createElt.ts | class HTMLElt<M extends ReadOnly> {
constructor() { }
}
class DivElt<M extends ReadOnly> extends HTMLElt<M> {
public htmlDivElt__ = 0;
constructor() {
super();
}
}
class SpanElt<M extends ReadOnly> extends HTMLElt<M> {
public htmlSpanElt__ = 1;
constructor() {
super();
}
}
... | constructor() {
super();
}
}
/*@ predicate TT v x n e = (x = n => extends_class(v, e)) */
/*@ createElt :: (tagName: string) => {v: HTMLElt<ReadOnly> |
(TT v tagName "div" "DivElt") &&
(TT v tagName "span" "SpanElt") &&
(TT v tagName "canvas" "CanvasElt")
} */
export function createElt(tag... | public htmlCanvasElt__ = 2; | random_line_split |
benches.rs | #![feature(test)]
extern crate blake2b;
extern crate blake2_rfc;
extern crate test;
use test::{Bencher, black_box};
const DATA: &'static [u8] = include_bytes!("data");
#[bench]
fn blake2b_32kib(bencher: &mut Bencher) {
bencher.bytes = DATA.len() as u64;
bencher.iter(|| black_box(blake2b::blake2b(64, DATA)));
}
#... | (bencher: &mut Bencher) {
bencher.bytes = 128;
bencher.iter(|| black_box(blake2b::unbuffered::Blake2b::default().finish(&[0x5555555555555555; 16], 128)));
}
#[bench]
fn blake2_single_block_raw(bencher: &mut Bencher) {
bencher.bytes = 128;
bencher.iter(|| black_box(blake2b::compress(&[0x5555555555555555; 16], &mut ... | blake2_single_block_unbuffered | identifier_name |
benches.rs | #![feature(test)]
extern crate blake2b;
extern crate blake2_rfc;
extern crate test;
| use test::{Bencher, black_box};
const DATA: &'static [u8] = include_bytes!("data");
#[bench]
fn blake2b_32kib(bencher: &mut Bencher) {
bencher.bytes = DATA.len() as u64;
bencher.iter(|| black_box(blake2b::blake2b(64, DATA)));
}
#[bench]
fn blake2_rfc_32kib(bencher: &mut Bencher) {
bencher.bytes = DATA.len() as u6... | random_line_split | |
benches.rs | #![feature(test)]
extern crate blake2b;
extern crate blake2_rfc;
extern crate test;
use test::{Bencher, black_box};
const DATA: &'static [u8] = include_bytes!("data");
#[bench]
fn blake2b_32kib(bencher: &mut Bencher) {
bencher.bytes = DATA.len() as u64;
bencher.iter(|| black_box(blake2b::blake2b(64, DATA)));
}
#... |
#[bench]
fn blake2_single_block_raw(bencher: &mut Bencher) {
bencher.bytes = 128;
bencher.iter(|| black_box(blake2b::compress(&[0x5555555555555555; 16], &mut blake2b::ParameterBlock::new().set_digest_len(64).set_fanout(1).set_max_depth(1).xor_with_iv().0, (128, 0), (!0, 0))));
}
| {
bencher.bytes = 128;
bencher.iter(|| black_box(blake2b::unbuffered::Blake2b::default().finish(&[0x5555555555555555; 16], 128)));
} | identifier_body |
togglebuttondemo.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { <%= angularXAppName %>SharedModule } from '../../../shared/shared.module';
import {FormsModule} from '@angular/forms';
import {ToggleButtonModule} from 'primeng/togglebutton';
import {ToastModule}... | ];
@NgModule({
imports: [
<%= angularXAppName %>SharedModule,
FormsModule,
ToggleButtonModule,
ToastModule,
WizardModule,
RouterModule.forRoot(PRIMENG_STATES, { useHash: true })
],
declarations: [
ToggleButtonDemoComponent
],
providers: [Messa... |
const PRIMENG_STATES = [
spinnerDemoRoute | random_line_split |
togglebuttondemo.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { <%= angularXAppName %>SharedModule } from '../../../shared/shared.module';
import {FormsModule} from '@angular/forms';
import {ToggleButtonModule} from 'primeng/togglebutton';
import {ToastModule}... | {}
| ToggleButtonDemoModule | identifier_name |
export.js | var auth = require( './auth' ),
surveyTemplate = require( '../lib/survey_template' ),
SurveyResponse = require( '../models/survey_response' );
var ExportController = function() {
this.csv = function( req, res ) {
var now = new Date(),
cleanTitle = req.survey.title.replace( /[^a-z0-9]/ig... |
res.header('Content-Disposition', 'attachment; filename=' + today + '_' + cleanTitle + '.csv');
res.csv( csvData );
} );
};
};
exports.setup = function( app ) {
var exporter = new ExportController();
app.get( '/export/:key', auth.canAccessSurvey, exporter.csv );
};
| {
responses.forEach( function( response ) {
csvData.push( flatSurvey.map( function( q ) {
try {
return response.response[ q.name ];
} catch( e ) {
return '';
... | conditional_block |
export.js | var auth = require( './auth' ),
surveyTemplate = require( '../lib/survey_template' ),
SurveyResponse = require( '../models/survey_response' );
var ExportController = function() {
this.csv = function( req, res ) {
var now = new Date(),
cleanTitle = req.survey.title.replace( /[^a-z0-9]/ig... | responses.forEach( function( response ) {
csvData.push( flatSurvey.map( function( q ) {
try {
return response.response[ q.name ];
} catch( e ) {
return '';
... | csvData.push( flatSurvey.map( function( q ) { return q.label; } ) );
SurveyResponse.find( { surveyId: req.survey.id }, function( err, responses ) {
if( responses && responses.length ) { | random_line_split |
AccessProvider.tsx | import { ReactElement, ReactNode, useCallback, useMemo } from 'react';
import AccessContext, { IAccessContext } from '../../../contexts/AccessContext';
import { ADMIN } from './permissions';
import { IPermission } from '../../../interfaces/user';
import { useAuthPermissions } from '../../../hooks/api/getters/useAuth/us... |
if (
p.permission === permission &&
(p.project === project || p.project === '*') &&
(p.environment === environment || p.environment === '*')
) {
return true;
}
if (
p.permission === permission &&
(p.project === project || p.project === '*') &&
p... | {
return true;
} | conditional_block |
AccessProvider.tsx | import { ReactElement, ReactNode, useCallback, useMemo } from 'react';
import AccessContext, { IAccessContext } from '../../../contexts/AccessContext';
import { ADMIN } from './permissions';
import { IPermission } from '../../../interfaces/user';
import { useAuthPermissions } from '../../../hooks/api/getters/useAuth/us... |
const hasAccess = useCallback(
(permission: string, project?: string, environment?: string) => {
return checkPermissions(
permissions,
permission,
project,
environment
);
},
[permissions]
);
con... | const permissions = props.permissions ?? auth.permissions;
const isAdmin: boolean = useMemo(() => {
return checkAdmin(permissions);
}, [permissions]); | random_line_split |
generate-graphics.py | #!/usr/bin/env python
import sys
import re
import subprocess
from jinja2 import Template
import replacements
TEMPLATENAME = "base.svg.template"
# modifiers for layers in order as in keymap
MODIFIERS = [
[],
["SHIFT"],
["MOD3"],
["MOD3", "SHIFT"],
["MOD4"],
["MOD4", "... | symbols = [s.strip() for s in symbols[0].split(',')]
# replace keynames with the symbol they produce
symbols = [replacements.f(s) for s in symbols]
# Some keys aren't layered, hence the list is too short.
# pad them with the first entry.
symbols = (symbols + symbols[:1]*9... | .startswith("xkb_keymap")
KEY_PATTERN = r'\s key \s .+? \s { [^}]+? };'
SYMBOLS_PATTERN = r'\[ (.+?) \]'
text = text.split('xkb_symbols', 1)[1]
# FIXME: assumes the next section (if there is one) is
# xkb_geometry
text = text.split('xkb_geometry', 1)[0]
for k in re.findall(KEY_PATTERN, te... | identifier_body |
generate-graphics.py | #!/usr/bin/env python
import sys
import re
import subprocess
from jinja2 import Template
import replacements
TEMPLATENAME = "base.svg.template"
# modifiers for layers in order as in keymap
MODIFIERS = [
[],
["SHIFT"],
["MOD3"],
["MOD3", "SHIFT"],
["MOD4"],
["MOD4", "... | layerdict):
layerdict["numpad"] = numpad
layerdict["swap_m3r_ä"] = swap_m3r_ä
layerdict["vou"] = vou
layerdict["mine"] = mine
with open(f'{layout}-{layername}-{version}.svg', 'w') as out:
out.write(template.render(layerdict))
def make_caps_lock(text):
if len(text) == 1:
return... | layername, | identifier_name |
generate-graphics.py | #!/usr/bin/env python
import sys
import re
import subprocess
from jinja2 import Template
import replacements
TEMPLATENAME = "base.svg.template"
# modifiers for layers in order as in keymap
MODIFIERS = [
[],
["SHIFT"],
["MOD3"],
["MOD3", "SHIFT"],
["MOD4"],
["MOD4", "... | return text
# - main layers
for layer in range(7): # 7 because the last layer is empty
# create a dict with the replacements from replacements.py
layerdict = {a: b[layer] for a, b in keymap.items()}
# color modifiers accordingly
for x in MODIFIERS[layer]:
layerdict[x] = " pressed"
w... | anslate(CAPS_MAP)
else:
| conditional_block |
generate-graphics.py | #!/usr/bin/env python
import sys
import re
import subprocess
from jinja2 import Template
import replacements
TEMPLATENAME = "base.svg.template"
# modifiers for layers in order as in keymap
MODIFIERS = [
[],
["SHIFT"],
["MOD3"],
["MOD3", "SHIFT"],
["MOD4"],
["MOD4", "... |
def keymap_to_keys(text):
# simple and dump parser for xkb keymap files
#
# It simply searches all "key { … };" parts and splits them.
# A more advanced version would parts "xkb_symbols { … }" first
# and only search in this part.
assert text.startswith("xkb_keymap")
KEY_PATTERN = r'\s ke... | assert len(lower_chars) == len(upper_chars) == 30
assert len(CAPS_MAP) == len(lower_chars) + len(upper_chars)
| random_line_split |
compile.py | #!/usr/bin/env python
import argparse
import os
import logging
import cdec.configobj
import cdec.sa
from cdec.sa._sa import monitor_cpu
import sys
MAX_PHRASE_LENGTH = 4
def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases):
lcp = cdec.sa.LCP(f_sa)
stats = sorted(lcp.compute_stat... | parser.add_argument('-c', '--config', default='/dev/stdout',
help='Output configuration')
parser.add_argument('-f', '--source',
help='Source language corpus')
parser.add_argument('-e', '--target',
help='Target language corpus')
pars... | preprocess_start_time = monitor_cpu()
sys.setrecursionlimit(sys.getrecursionlimit() * 100)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('cdec.sa.compile')
parser = argparse.ArgumentParser(description='Compile a corpus into a suffix array.')
parser.add_argument('--maxnt', '-n',... | identifier_body |
compile.py | #!/usr/bin/env python
import argparse
import os
import logging
import cdec.configobj
import cdec.sa
from cdec.sa._sa import monitor_cpu
import sys
MAX_PHRASE_LENGTH = 4
def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases):
lcp = cdec.sa.LCP(f_sa)
stats = sorted(lcp.compute_stat... | ():
preprocess_start_time = monitor_cpu()
sys.setrecursionlimit(sys.getrecursionlimit() * 100)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('cdec.sa.compile')
parser = argparse.ArgumentParser(description='Compile a corpus into a suffix array.')
parser.add_argument('--maxnt... | main | identifier_name |
compile.py | #!/usr/bin/env python
import argparse
import os
import logging
import cdec.configobj
import cdec.sa
from cdec.sa._sa import monitor_cpu
import sys
MAX_PHRASE_LENGTH = 4
def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases):
lcp = cdec.sa.LCP(f_sa)
stats = sorted(lcp.compute_stat... |
param_names = ('max_len', 'max_nt', 'max_size', 'min_gap',
'rank1', 'rank2', 'tight_phrases')
params = (args.maxlen, args.maxnt, args.maxsize, args.mingap,
args.rank1, args.rank2, not args.loose)
if not os.path.exists(args.output):
os.mkdir(args.output)
f_sa_bin = os.... | parser.error('a parallel corpus is required\n'
'\tuse -f (source) with -e (target) or -b (bitext)') | conditional_block |
compile.py | #!/usr/bin/env python
import argparse
import os
import logging
import cdec.configobj
import cdec.sa
from cdec.sa._sa import monitor_cpu
import sys
MAX_PHRASE_LENGTH = 4
def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases):
lcp = cdec.sa.LCP(f_sa)
stats = sorted(lcp.compute_stat... |
def main():
preprocess_start_time = monitor_cpu()
sys.setrecursionlimit(sys.getrecursionlimit() * 100)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('cdec.sa.compile')
parser = argparse.ArgumentParser(description='Compile a corpus into a suffix array.')
parser.add_argument... | max_length=max_len,
max_nonterminals=max_nt,
train_max_initial_size=max_size,
train_min_gap_size=min_gap)
return precomp | random_line_split |
word_forms.py | from pymorphy2.analyzer import Parse
__author__ = 'moskupols'
from lang_utils.morphology import morph
# def get_forms(initial):
# """
# Get all possible forms of a given word in initial form.
#
# >>> get_forms('мама')
# ['мам', 'мама', 'мамам', 'мамами', 'мамах', 'маме', 'мамой', 'мамою', 'маму', 'ма... | return possible_forms[0].normal_form
| identifier_body | |
word_forms.py | from pymorphy2.analyzer import Parse
__author__ = 'moskupols'
from lang_utils.morphology import morph
# def get_forms(initial):
# """
# Get all possible forms of a given word in initial form.
#
# >>> get_forms('мама')
# ['мам', 'мама', 'мамам', 'мамами', 'мамах', 'маме', 'мамой', 'мамою', 'маму', 'ма... | conditional_block | ||
word_forms.py | from pymorphy2.analyzer import Parse
__author__ = 'moskupols'
from lang_utils.morphology import morph
# def get_forms(initial):
# """
# Get all possible forms of a given word in initial form.
#
# >>> get_forms('мама')
# ['мам', 'мама', 'мамам', 'мамами', 'мамах', 'маме', 'мамой', 'мамою', 'маму', 'ма... | all possible initial forms (there are several of them sometimes) of a given word.
Optional argument part_filter allows to prune unnecessary ambiguity with part of speech.
>>> get_initial_forms('Дядя')
['дядя']
>>> get_initial_forms('самых')
['самый']
>>> get_initial_forms('честных')
['чест... |
"""
Gets | identifier_name |
word_forms.py | from pymorphy2.analyzer import Parse
__author__ = 'moskupols'
from lang_utils.morphology import morph
# def get_forms(initial):
# """
# Get all possible forms of a given word in initial form.
#
# >>> get_forms('мама')
# ['мам', 'мама', 'мамам', 'мамами', 'мамах', 'маме', 'мамой', 'мамою', 'маму', 'ма... | return ret
def _is_valid_noun(parsed: Parse)->bool:
# TODO: add surname and all, see http://opencorpora.org/dict.php?act=gram
# even Init!
tag = parsed.tag
return tag.POS == 'NOUN' and 'Name' not in str(tag) # Dirty but so cool!
def get_valid_noun_initial_form(word: str)->str:
possible_form... | if norm not in met:
ret.append(norm)
met.add(norm) | random_line_split |
views.py | import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import BasecampProvider
class BasecampOAuth2Adapter(OAuth2Ad... | resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(BasecampOAuth2Adapter)
oauth2_callb... | profile_url = 'https://launchpad.37signals.com/authorization.json'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer {0}'.format(token.token)} | random_line_split |
views.py | import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import BasecampProvider
class BasecampOAuth2Adapter(OAuth2Ad... |
oauth2_login = OAuth2LoginView.adapter_view(BasecampOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(BasecampOAuth2Adapter)
| provider_id = BasecampProvider.id
access_token_url = 'https://launchpad.37signals.com/authorization/token?type=web_server' # noqa
authorize_url = 'https://launchpad.37signals.com/authorization/new'
profile_url = 'https://launchpad.37signals.com/authorization.json'
def complete_login(self, request, app... | identifier_body |
views.py | import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import BasecampProvider
class | (OAuth2Adapter):
provider_id = BasecampProvider.id
access_token_url = 'https://launchpad.37signals.com/authorization/token?type=web_server' # noqa
authorize_url = 'https://launchpad.37signals.com/authorization/new'
profile_url = 'https://launchpad.37signals.com/authorization.json'
def complete_log... | BasecampOAuth2Adapter | identifier_name |
revoke.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | pass | identifier_body | |
revoke.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (self, args):
"""Revoke Application Default Credentials."""
auth_util.RevokeCredsInWellKnownFile(args.brief)
return ''
def Display(self, unused_args, result):
pass
| Run | identifier_name |
revoke.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | pass | random_line_split | |
bitvec.rs | //! Defines basic operations defined under FixedSizeBitVectors theory in SMTLIB2.
use std::fmt;
use crate::backends::backend::SMTNode;
#[macro_export]
macro_rules! bv_const {
($solver: ident, $i: expr, $n: expr) => { $solver.new_const(bitvec::OpCodes::Const($i, $n)) }
}
#[derive(Clone, Debug)]
pub enum OpCodes... | BvNeg,
BvAdd,
BvMul,
BvUDiv,
BvURem,
BvShl,
BvLShr,
BvULt,
BvNand,
BvNor,
BvXor,
BvXnor,
BvComp,
BvSub,
BvSDiv,
BvSRem,
BvSMod,
BvAShr,
// parameterized functions
Repeat(u64),
ZeroExtend(u64),
SignExtend(u64),
RotateLeft(u64),
... | Concat,
Extract(u64, u64),
BvNot,
BvAnd,
BvOr, | random_line_split |
bitvec.rs | //! Defines basic operations defined under FixedSizeBitVectors theory in SMTLIB2.
use std::fmt;
use crate::backends::backend::SMTNode;
#[macro_export]
macro_rules! bv_const {
($solver: ident, $i: expr, $n: expr) => { $solver.new_const(bitvec::OpCodes::Const($i, $n)) }
}
#[derive(Clone, Debug)]
pub enum OpCodes... | {
BitVector(usize),
}
impl fmt::Display for Sorts {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
Sorts::BitVector(ref n) => format!("(_ BitVec {})", n),
};
write!(f, "{}", s)
}
}
| Sorts | identifier_name |
events.js | var logging = require('logging');
var Events = function(options) {
options = options || {};
};
Events.prototype.on = function(event, fn) {
var _this = this;
_this._events = _this._events || {};
_this._events[event] = this._events[event] || [];
_this._events[event].push(fn);
};
Events.prototype.off = function... |
});
};
module.exports.Events = Events;
module.exports.hub = new Events();
// This defines the list of events intended to be used with the
// global event "hub".
module.exports.EVT = {
ALIGN: 'align',
CLEAR_HIGHLIGHTS: 'clear_highlights',
DELETE_ALIGNMENTS: 'delete_alignments',
BUILD_INDEX: 'build_index',
... | {
dest[method] = Events.prototype[method];
} | conditional_block |
events.js | var logging = require('logging');
var Events = function(options) {
options = options || {};
};
Events.prototype.on = function(event, fn) {
var _this = this;
_this._events = _this._events || {};
_this._events[event] = this._events[event] || [];
_this._events[event].push(fn);
};
Events.prototype.off = function... | Events.mixin = function(dest) {
['on','off','trigger'].forEach(function(method) {
if (typeof dest === 'function') {
dest.prototype[method] = Events.prototype[method];
} else {
dest[method] = Events.prototype[method];
}
});
};
module.exports.Events = Events;
module.exports.hub = new Events... | }; | random_line_split |
CellEditing.js | - The record that was edited
* - field - The field name that was edited
* - value - The value being set
* - originalValue - The original value for the field, before the edit.
* - row - The grid table row
* - column - The grid {@link Ext.grid.column.Column Column} defining the column that was e... | {
this.lockingPartner.context = context;
} | conditional_block | |
CellEditing.js | * {header: 'Phone', dataIndex: 'phone'}
* ],
* selType: 'cellmodel',
* plugins: [
* Ext.create('Ext.grid.plugin.CellEditing', {
* clicksToEdit: 1
* })
* ],
* height: 200,
* width: 400,
* renderTo: Ext.... | * }
* }, | random_line_split | |
evaluation.ts | import { gql } from 'apollo-server-core';
import { AllowNull, Column, ForeignKey, Table } from 'sequelize-typescript';
import { ApiObject } from '../main/api';
import { createByIdLoader, createSimpleLoader, UuidBaseModel } from '../main/base-model';
import { Submission } from './submission';
export const evaluationSch... | extends UuidBaseModel<Evaluation> {
@ForeignKey(() => Submission)
@AllowNull(false)
@Column
submissionId!: string;
/** Status of this evaluation */
@AllowNull(false)
@Column
status!: EvaluationStatus;
}
/** Status of this submission */
export enum EvaluationStatus {
/** The evalua... | Evaluation | identifier_name |
evaluation.ts | import { gql } from 'apollo-server-core';
import { AllowNull, Column, ForeignKey, Table } from 'sequelize-typescript';
import { ApiObject } from '../main/api';
import { createByIdLoader, createSimpleLoader, UuidBaseModel } from '../main/base-model';
import { Submission } from './submission';
export const evaluationSch... | status!: EvaluationStatus;
}
/** Status of this submission */
export enum EvaluationStatus {
/** The evaluation not completed yet */
PENDING = 'PENDING',
/** The evaluation terminated correclty */
SUCCESS = 'SUCCESS',
/** There was an error in this evaluation */
ERROR = 'ERROR',
}
export i... | submissionId!: string;
/** Status of this evaluation */
@AllowNull(false)
@Column | random_line_split |
interfaceTest.js | /**
* Created by dt on 2016/10/18.
*/
var utils = require('../tinyTool/utils.js');
var date = require('../tinyTool/date.js');
var http = require('http');
var urlParse = require('url').parse;
var querystring = require('querystring');
var interfaceTestData = {
data_URL : [],
data_UserId : [],
d... | if(bol== -1){
interfaceTestData[arr_name].push(arr_data)
}
var l = interfaceTestData[arr_name].length;
if(l>10){
interfaceTestData[arr_name].shift();
}
} | ta);
| identifier_name |
interfaceTest.js | /**
* Created by dt on 2016/10/18.
*/
var utils = require('../tinyTool/utils.js');
var date = require('../tinyTool/date.js');
var http = require('http');
var urlParse = require('url').parse;
var querystring = require('querystring');
var interfaceTestData = {
data_URL : [],
data_UserId : [],
d... | interfaceTestData[arr_name].push(arr_data)
}
var l = interfaceTestData[arr_name].length;
if(l>10){
interfaceTestData[arr_name].shift();
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.