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 |
|---|---|---|---|---|
test_migration_0005.py | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | or unit in collection.find({}):
self.assertTrue(LAST_UPDATED in unit)
unit_id = unit[ID]
last_updated = unit[LAST_UPDATED]
if unit_id % 2 == 0:
self.assertEqual(last_updated, 1)
else:
self.assertTrue(... | conditional_block | |
test_migration_0005.py | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | for name in [n for n in database.collection_names() if n in TEST_COLLECTIONS]:
database.drop_collection(name)
def test(self):
# migrate
module = MigrationModule(MIGRATION)._module
module.migrate()
# validation
for collection in [connection.get_collection(... | def clean(self):
database = connection.get_database() | random_line_split |
test_migration_0005.py | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | self):
self.clean()
super(TestMigration_0005, self).setUp()
for collection in [connection.get_collection(n, True) for n in TEST_COLLECTIONS]:
for unit in TEST_UNITS:
collection.save(unit, safe=True)
def tearDown(self):
super(TestMigration_0005, self).tear... | etUp( | identifier_name |
test_migration_0005.py | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | # validation
for collection in [connection.get_collection(n) for n in TEST_COLLECTIONS]:
for unit in collection.find({}):
self.assertTrue(LAST_UPDATED in unit)
unit_id = unit[ID]
last_updated = unit[LAST_UPDATED]
if unit_id % 2 ... | ef setUp(self):
self.clean()
super(TestMigration_0005, self).setUp()
for collection in [connection.get_collection(n, True) for n in TEST_COLLECTIONS]:
for unit in TEST_UNITS:
collection.save(unit, safe=True)
def tearDown(self):
super(TestMigration_0005, s... | identifier_body |
wp8.js | /*
*
* Copyright 2013 Jesse MacFadyen
*
* 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 agree... | var isCustom = obj.custom;
if(isCustom) {
dest = path.join('plugins', plugin_id, path.basename(src));
common.copyFile(plugin_dir, src, project_dir, dest);
}
project_file.addReference(dest);
},
uninstall:function(obj, proj... | var src = obj.src;
var dest = src; // if !isCustom, we will just add a reference to the file in place | random_line_split |
wp8.js | /*
*
* Copyright 2013 Jesse MacFadyen
*
* 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 agree... |
return new csproj(path.join(project_dir, project_files[0]));
},
'source-file':{
install:function(obj, plugin_dir, project_dir, plugin_id, options, project_file) {
var dest = path.join('Plugins', plugin_id, obj.targetDir ? obj.targetDir : '', path.basename(obj.src));
com... | {
throw new Error('does not appear to be a Windows Phone project (no .csproj file)');
} | conditional_block |
traits.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
.to_bits(pointer_size)? as u64;... | identifier_body |
traits.rs | // Copyright 2018 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 ... |
}
self.memory.mark_immutable(vtable.alloc_id)?;
assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
Ok(vtable)
}
/// Return the drop fn instance as well as the actual dynamic type
pub fn read_drop_type_from_vtable(
&self,
vtable:... | {
let instance = self.resolve(def_id, substs)?;
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
self.memory
.get_mut(method_ptr.alloc_id)?
... | conditional_block |
traits.rs | // Copyright 2018 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 ... | ) -> EvalResult<'tcx, (Size, Align)> {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
... | pub fn read_size_and_align_from_vtable(
&self,
vtable: Pointer<M::PointerTag>, | random_line_split |
traits.rs | // Copyright 2018 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 ... | (
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
if let Some(... | get_vtable | identifier_name |
Promise.d.ts | export = Promise;
declare function Promise(executor: ((arg0: () => any, arg1: () => any) => any) | null): void;
declare class Promise {
constructor(executor: ((arg0: () => any, arg1: () => any) => any) | null);
listeners_: Array<{
onFulfilled: (arg0: any) => any;
onRejected: (arg0: any) => any;
... | value: any
): void;
function rejectListener_(
listener: {
onFulfilled: (arg0: any) => any;
onRejected: (arg0: any) => any;
promise: Promise;
},
reason: any
): void;
function resolve(value: any): Promise;
function reject(reason: any)... | listener: {
onFulfilled: (arg0: any) => any;
onRejected: (arg0: any) => any;
promise: Promise;
}, | random_line_split |
Promise.d.ts | export = Promise;
declare function Promise(executor: ((arg0: () => any, arg1: () => any) => any) | null): void;
declare class | {
constructor(executor: ((arg0: () => any, arg1: () => any) => any) | null);
listeners_: Array<{
onFulfilled: (arg0: any) => any;
onRejected: (arg0: any) => any;
promise: Promise;
}>;
private state_;
private value_;
private logger_;
private resolve_;
private reje... | Promise | identifier_name |
staribuscrc.py | __author__ = 'mark'
# StarinetPython3Logger a data logger for the Beaglebone Black.
# Copyright (C) 2015 Mark Horn
#
# This file is part of StarinetPython3Logger.
#
# StarinetPython3Logger is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the... | return '0'
def newcrc(buffer0):
logger.debug("New crc was called.")
buffer0 = buffer0.encode('UTF-8')
datacrc = str(hex(crc16(buffer0)).replace('x', '')[1:].zfill(4)).upper()
value = datacrc
logger.debug("%s %s", "Calculated new message crc -", datacrc)
return value
if __name__ ... | logger.debug("Check crc was called.")
buffer0 = buffer0.encode('utf-8')
rxcrc = buffer0[-4:] # assign the received crc to rxcrc
logger.debug("%s %s", "Received data crc - ", rxcrc)
newrxcrc = str(hex(crc16(buffer0[:-4])).replace('x', '')[1:].zfill(4)).upper() # new crc
newrxcrc = newrxcrc.enc... | identifier_body |
staribuscrc.py | __author__ = 'mark'
# StarinetPython3Logger a data logger for the Beaglebone Black.
# Copyright (C) 2015 Mark Horn
#
# This file is part of StarinetPython3Logger.
#
# StarinetPython3Logger is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the... |
def checkcrc(buffer0):
logger.debug("Check crc was called.")
buffer0 = buffer0.encode('utf-8')
rxcrc = buffer0[-4:] # assign the received crc to rxcrc
logger.debug("%s %s", "Received data crc - ", rxcrc)
newrxcrc = str(hex(crc16(buffer0[:-4])).replace('x', '')[1:].zfill(4)).upper() # new crc... |
## initialise logger
logger = logging.getLogger('utilities.staribuscCrc')
| random_line_split |
staribuscrc.py | __author__ = 'mark'
# StarinetPython3Logger a data logger for the Beaglebone Black.
# Copyright (C) 2015 Mark Horn
#
# This file is part of StarinetPython3Logger.
#
# StarinetPython3Logger is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the... | (buffer0):
logger.debug("Check crc was called.")
buffer0 = buffer0.encode('utf-8')
rxcrc = buffer0[-4:] # assign the received crc to rxcrc
logger.debug("%s %s", "Received data crc - ", rxcrc)
newrxcrc = str(hex(crc16(buffer0[:-4])).replace('x', '')[1:].zfill(4)).upper() # new crc
newrxcr... | checkcrc | identifier_name |
staribuscrc.py | __author__ = 'mark'
# StarinetPython3Logger a data logger for the Beaglebone Black.
# Copyright (C) 2015 Mark Horn
#
# This file is part of StarinetPython3Logger.
#
# StarinetPython3Logger is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the... |
else:
logger.debug("CRC' match")
return '0'
def newcrc(buffer0):
logger.debug("New crc was called.")
buffer0 = buffer0.encode('UTF-8')
datacrc = str(hex(crc16(buffer0)).replace('x', '')[1:].zfill(4)).upper()
value = datacrc
logger.debug("%s %s", "Calculated new message crc ... | logger.debug("%s %s %s %s", "Received crc - ", rxcrc, "does not match our generated crc - ", newrxcrc)
return '0200' | conditional_block |
update-translations.py | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... | # assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format_specifiers(find_format_specifiers(translation))
except IndexError:... |
def check_format_specifiers(source, translation, errors):
source_f = split_format_specifiers(find_format_specifiers(source)) | random_line_split |
update-translations.py | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... |
errors = []
valid = check_format_specifiers(source, translation, errors)
for error in errors:
print('%s: %s' % (filename, error))
if not valid: # set type to unfinished and clear string if invalid
... | continue | conditional_block |
update-translations.py | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... |
def all_ts_files(suffix=''):
for filename in os.listdir(LOCALE_DIR):
# process only language files, and do not process source language
if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = f... | source_f = split_format_specifiers(find_format_specifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format_spe... | identifier_body |
update-translations.py | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... | ():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f']):
print('Error while fetching translations', file=sys.stder... | check_at_repository_root | identifier_name |
ExitCodes.js | /* | * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CoreWorker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General... | * This file is part of CoreWorker.
*
* CoreWorker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by | random_line_split |
associated-types-simple.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
struct Struct {
x: isize,
}
impl Get for Struct {
type Value = isize;
fn get(&self) -> &isize {
&self.x
}
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
} | trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value; | random_line_split |
associated-types-simple.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> &isize {
&self.x
}
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
}
| get | identifier_name |
associated-types-simple.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
}
| {
&self.x
} | identifier_body |
ManageCoursePage.js | import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseForm from './CourseForm';
import {authorsFormattedForDropdown} from '../../selectors/selectors';
import toastr from 'toastr';
... | id: "",
title: "",
watchHref: "",
authorId: "",
length: "23",
category: ""
};
const courseId = ownProps.params.id; // from the path `/course/:id`
if (courseId && state.courses.length > 0) {
course = getCourseById(state.courses, courseId);
}
return {
course: course,
authors: authorsFormattedForD... | let course = { | random_line_split |
ManageCoursePage.js | import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseForm from './CourseForm';
import {authorsFormattedForDropdown} from '../../selectors/selectors';
import toastr from 'toastr';
... |
render() {
return (
<CourseForm allAuthors={this.props.authors}
onChange={this.updateCourseState}
onSave={this.saveCourse}
errors={this.state.errors}
course={this.state.course}
saving={this.state.saving}/>
);
}
}
ManageCoursePage.propTypes = {
course: PropTypes.object.isRequired,
... | {
// redirect to courses route
this.setState({saving: false});
toastr.success('Course saved!');
this.context.router.push('/courses');
} | identifier_body |
ManageCoursePage.js | import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseForm from './CourseForm';
import {authorsFormattedForDropdown} from '../../selectors/selectors';
import toastr from 'toastr';
... | extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
course: Object.assign({}, props.course),
errors: {},
saving: false
};
this.updateCourseState = this.updateCourseState.bind(this);
this.saveCourse = this.saveCourse.bind(this);
}
componentWillReceiveP... | ManageCoursePage | identifier_name |
repolist.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# repolist.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://gitlab.com/dslackw/slpkg
# Slpkg is free software: you can redis... | "Repo URL", " " * 44,
"Default", " " * 3,
"Status"))
self.msg.template(78)
for repo_id, repo_URL in sorted(self.all_repos.items()):
status, COLOR = "disabled", self.red
default = "yes"
if len(repo_URL) > 49:
repo_URL... | """List of repositories
"""
def __init__(self):
self.meta = _meta_
self.green = self.meta.color["GREEN"]
self.red = self.meta.color["RED"]
self.grey = self.meta.color["GREY"]
self.endc = self.meta.color["ENDC"]
self.msg = Msg()
self.all_repos = Repo().defa... | identifier_body |
repolist.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# repolist.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://gitlab.com/dslackw/slpkg
# Slpkg is free software: you can redis... |
print("\nRepositories summary")
print("=" * 79)
print(f"{self.grey}{def_cnt}/{len(self.all_repos)} enabled default "
f"repositories and {cus_cnt} custom.")
print("Edit the file '/etc/slpkg/repositories.conf' for enable "
"and disable default\nrepositories or... | status, COLOR = "disabled", self.red
default = "yes"
if len(repo_URL) > 49:
repo_URL = repo_URL[:48] + "~"
if repo_id in self.meta.repositories:
def_cnt += 1
status, COLOR = "enabled", self.green
if repo_id not in self.meta.... | conditional_block |
repolist.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# repolist.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://gitlab.com/dslackw/slpkg
# Slpkg is free software: you can redis... | "Default", " " * 3,
"Status"))
self.msg.template(78)
for repo_id, repo_URL in sorted(self.all_repos.items()):
status, COLOR = "disabled", self.red
default = "yes"
if len(repo_URL) > 49:
repo_URL = repo_URL[:48] + "~"
... | "| Repo id", " " * 2,
"Repo URL", " " * 44, | random_line_split |
repolist.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# repolist.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://gitlab.com/dslackw/slpkg
# Slpkg is free software: you can redis... | (self):
self.meta = _meta_
self.green = self.meta.color["GREEN"]
self.red = self.meta.color["RED"]
self.grey = self.meta.color["GREY"]
self.endc = self.meta.color["ENDC"]
self.msg = Msg()
self.all_repos = Repo().default_repository()
self.all_repos["slack"]... | __init__ | identifier_name |
mini.js | const nest = require('depnest')
const { h, Value } = require('mutant')
exports.needs = nest({
'app.sync.goTo': 'first',
'message.html.backlinks': 'first',
'message.html.author': 'first',
'message.html.meta': 'map',
'message.html.timestamp': 'first'
})
exports.gives = nest('message.html.layout')
|
var rawMessage = Value(null)
return h('Message -mini', {
attributes: {
tabindex: '0'
}
}, [
h('section.timestamp', {}, api.message.html.timestamp(msg)),
h('header.author', {}, api.message.html.author(msg, { size: 'mini' })),
h('section.meta', {}, api.message.html.meta... | exports.create = (api) => {
return nest('message.html.layout', miniLayout)
function miniLayout (msg, opts) {
if (opts.layout !== 'mini') return | random_line_split |
mini.js | const nest = require('depnest')
const { h, Value } = require('mutant')
exports.needs = nest({
'app.sync.goTo': 'first',
'message.html.backlinks': 'first',
'message.html.author': 'first',
'message.html.meta': 'map',
'message.html.timestamp': 'first'
})
exports.gives = nest('message.html.layout')
exports.cre... |
}
| {
if (opts.layout !== 'mini') return
var rawMessage = Value(null)
return h('Message -mini', {
attributes: {
tabindex: '0'
}
}, [
h('section.timestamp', {}, api.message.html.timestamp(msg)),
h('header.author', {}, api.message.html.author(msg, { size: 'mini' })),
h(... | identifier_body |
mini.js | const nest = require('depnest')
const { h, Value } = require('mutant')
exports.needs = nest({
'app.sync.goTo': 'first',
'message.html.backlinks': 'first',
'message.html.author': 'first',
'message.html.meta': 'map',
'message.html.timestamp': 'first'
})
exports.gives = nest('message.html.layout')
exports.cre... | (msg, opts) {
if (opts.layout !== 'mini') return
var rawMessage = Value(null)
return h('Message -mini', {
attributes: {
tabindex: '0'
}
}, [
h('section.timestamp', {}, api.message.html.timestamp(msg)),
h('header.author', {}, api.message.html.author(msg, { size: 'mini' ... | miniLayout | identifier_name |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
... | (pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner {
TaskRunner {
timer: Timer::new(),
pg_pool: pg_pool,
redis_pool: redis_pool,
}
}
pub fn run(&self) -> Vec<Guard> {
let mut guards = Vec::<Guard>::new();
guards.push({
le... | new | identifier_name |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool, | macro_rules! get_conn {
($pool:ident) => {
match $pool.get() {
Ok(conn) => conn,
Err(err) => {
error!("Failed to get pooled connection: {}", err);
return;
}
}
}
}
impl TaskRunner {
pub fn new(pg_pool: PostgresPool, redis_po... | redis_pool: RedisPool,
}
| random_line_split |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
... |
};
if let Err(err) = streak.save(rds) {
error!("Failed to save streak: {}", err);
} else {
trace!("Streak updated: {:?}", streak);
}
}
| {
error!("Failed to calculate streak: {}", err);
return;
} | conditional_block |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
... |
}
fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) {
let streak = match Streak::calculate(pg) {
Ok(streak) => streak,
Err(err) => {
error!("Failed to calculate streak: {}", err);
return;
}
};
if let Err(err) = streak.save(rds) {
error... | {
let mut guards = Vec::<Guard>::new();
guards.push({
let pg_pool = self.pg_pool.clone();
let redis_pool = self.redis_pool.clone();
self.timer.schedule(Local::now(), Some(Duration::days(1)), move || {
let pg_conn = get_conn!(pg_pool);
l... | identifier_body |
backend.ts | /**
* @license
* Copyright 2019 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... |
}
| {
const {parameters} = this;
const {chunkGridPosition} = chunk;
const url =
`${parameters.url}/${chunkGridPosition[0]}/${chunkGridPosition[1]}/${chunkGridPosition[2]}`;
const response = await cancellableFetchOk(url, {}, responseArrayBuffer, cancellationToken);
await decodeChunk(chunk, cancel... | identifier_body |
backend.ts | /**
* @license
* Copyright 2019 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... | (chunk: VolumeChunk, cancellationToken: CancellationToken) {
const {parameters} = this;
const {chunkGridPosition} = chunk;
const url =
`${parameters.url}/${chunkGridPosition[0]}/${chunkGridPosition[1]}/${chunkGridPosition[2]}`;
const response = await cancellableFetchOk(url, {}, responseArrayBuff... | download | identifier_name |
backend.ts | /**
* @license
* Copyright 2019 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... | throw new Error(`Unsupported mode: ${mode}.`);
}
const numDimensions = dv.getUint16(2, /*littleEndian=*/ false);
if (numDimensions !== 3) {
throw new Error(`Number of dimensions must be 3.`);
}
let offset = 4;
const shape = new Uint32Array(numDimensions);
for (let i = 0; i < numDimensions; ++i) {
... | const mode = dv.getUint16(0, /*littleEndian=*/ false);
if (mode !== 0) { | random_line_split |
backend.ts | /**
* @license
* Copyright 2019 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... |
chunk.chunkDataSize = vec3.fromValues(shape[0], shape[1], shape[2]);
let buffer = new Uint8Array(response, offset);
if (encoding === VolumeChunkEncoding.GZIP) {
buffer = await requestAsyncComputation(decodeGzip, cancellationToken, [buffer.buffer], buffer);
}
await decodeRawChunk(
chunk, cancellatio... | {
shape[i] = dv.getUint32(offset, /*littleEndian=*/ false);
offset += 4;
} | conditional_block |
releasetools.py | #
# Copyright (C) 2015 The CyanogenMod Project | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing... | #
# 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 | random_line_split |
releasetools.py | #
# Copyright (C) 2015 The CyanogenMod Project
#
# 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 agr... |
def FullOTA_InstallEnd(info):
info.script.AppendExtra('mount("ext4", "EMMC", "/dev/block/platform/msm_sdcc.1/by-name/system", "/system", "");');
info.script.AppendExtra('run_program("/tmp/install/bin/nfcchecker.sh");');
info.script.AppendExtra('unmount("/system");');
| info.script.AppendExtra('run_program("/sbin/e2fsck", "-fy", "/dev/block/platform/msm_sdcc.1/by-name/system");');
info.script.AppendExtra('run_program("/tmp/install/bin/resize2fs_static", "/dev/block/platform/msm_sdcc.1/by-name/system");');
info.script.AppendExtra('run_program("/sbin/e2fsck", "-fy", "/dev/block/... | identifier_body |
releasetools.py | #
# Copyright (C) 2015 The CyanogenMod Project
#
# 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 agr... | (info):
info.script.AppendExtra('mount("ext4", "EMMC", "/dev/block/platform/msm_sdcc.1/by-name/system", "/system", "");');
info.script.AppendExtra('run_program("/tmp/install/bin/nfcchecker.sh");');
info.script.AppendExtra('unmount("/system");');
| FullOTA_InstallEnd | identifier_name |
struct-destructuring-cross-crate.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() {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
} | random_line_split | |
struct-destructuring-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
| main | identifier_name |
struct-destructuring-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
} | identifier_body | |
App.ts | // https://www.electronjs.org/docs/api/app
import { BrowserWindow, BrowserWindowStatic, makeBrowserWindow } from './BrowserWindow'
type AppEvent
= 'browser-window-focus'
| 'browser-window-blur'
| 'browser-window-created' | | 'will-quit'
| 'child-process-gone'
| 'render-process-gone'
export class App {
private readonly callbacks: { [event in AppEvent]: Function[] } = {
ready: [],
'will-quit': [],
'browser-window-blur': [],
'browser-window-focus': [],
'browser-window-created': [],
'child-process-gone': [],
... | | 'ready' | random_line_split |
App.ts | // https://www.electronjs.org/docs/api/app
import { BrowserWindow, BrowserWindowStatic, makeBrowserWindow } from './BrowserWindow'
type AppEvent
= 'browser-window-focus'
| 'browser-window-blur'
| 'browser-window-created'
| 'ready'
| 'will-quit'
| 'child-process-gone'
| 'render-process-gone'
export clas... | ({
locale = 'en-GB',
BrowserWindow = makeBrowserWindow(),
isPackaged = true,
version = '1.2.3',
name = 'my cool app :^)'
} = {}): App {
return new App(locale, BrowserWindow, isPackaged, version, name)
}
| makeApp | identifier_name |
App.ts | // https://www.electronjs.org/docs/api/app
import { BrowserWindow, BrowserWindowStatic, makeBrowserWindow } from './BrowserWindow'
type AppEvent
= 'browser-window-focus'
| 'browser-window-blur'
| 'browser-window-created'
| 'ready'
| 'will-quit'
| 'child-process-gone'
| 'render-process-gone'
export clas... |
_createWindow () {
const newWindow = this.BrowserWindow._create()
this.callbacks['browser-window-created'].forEach(cb => { cb(null, newWindow) })
this._emitFocusEvent(newWindow)
}
_closeWindow (window: BrowserWindow) {
// electron doesn't blur the very last window to close
if (this.Browser... | {
const window = maybeWindow === undefined
? this.BrowserWindow.getAllWindows()[0]
: maybeWindow
this.BrowserWindow._focus(window.index)
this.callbacks['browser-window-focus'].forEach(cb => { cb(null, window) })
} | identifier_body |
isEmpty.js | /* */
var getTag = require('./_getTag'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isBuffer = require('./isBuffer'),
isFunction = require('./isFunction'),
isObjectLike = require('./isObjectLike'),
isString = require('./is... | (value) {
if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value) || isBuffer(value))) {
return !value.length;
}
if (isObjectLike(value)) {
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
}
for (v... | isEmpty | identifier_name |
isEmpty.js | /* */
var getTag = require('./_getTag'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isBuffer = require('./isBuffer'),
isFunction = require('./isFunction'),
isObjectLike = require('./isObjectLike'),
isString = require('./is... |
module.exports = isEmpty;
| {
if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value) || isBuffer(value))) {
return !value.length;
}
if (isObjectLike(value)) {
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
}
for (var key i... | identifier_body |
isEmpty.js | /* */
var getTag = require('./_getTag'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isBuffer = require('./isBuffer'),
isFunction = require('./isFunction'),
isObjectLike = require('./isObjectLike'),
isString = require('./is... |
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return !(nonEnumShadows && keys(value).length);
}
module.exports = isEmpty;
| {
return !value.size;
} | conditional_block |
isEmpty.js | /* */
var getTag = require('./_getTag'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isBuffer = require('./isBuffer'),
isFunction = require('./isFunction'),
isObjectLike = require('./isObjectLike'),
isString = require('./is... | module.exports = isEmpty; | random_line_split | |
sentiment_anaylsis_twitter_data.py | from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import twitter_credentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd | class TwitterClient():
def __init__(self, twitter_user=None):
self.auth = TwitterAuthenticator().authenticate_twitter_app()
self.twitter_client = API(self.auth)
self.twitter_user = twitter_user
def get_twitter_client_api(self):
return self.twitter_client
def get_user_timel... | import re
# # # # TWITTER CLIENT # # # # | random_line_split |
sentiment_anaylsis_twitter_data.py | from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import twitter_credentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re
# # # # TWITTER CLIENT #... |
else:
return -1
def tweets_to_data_frame(self, tweets):
df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['tweets'])
df['id'] = np.array([tweet.id for tweet in tweets])
df['len'] = np.array([len(tweet.text) for tweet in tweets])
df['date'] = np.... | return 0 | conditional_block |
sentiment_anaylsis_twitter_data.py | from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import twitter_credentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re
# # # # TWITTER CLIENT #... | (self, num_friends):
friend_list = []
for friend in Cursor(self.twitter_client.friends, id=self.twitter_user).items(num_friends):
friend_list.append(friend)
return friend_list
def get_home_timeline_tweets(self, num_tweets):
home_timeline_tweets = []
for tweet in ... | get_friend_list | identifier_name |
sentiment_anaylsis_twitter_data.py | from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import twitter_credentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re
# # # # TWITTER CLIENT #... |
def analyze_sentiment(self, tweet):
analysis = TextBlob(self.clean_tweet(tweet))
if analysis.sentiment.polarity > 0:
return 1
elif analysis.sentiment.polarity == 0:
return 0
else:
return -1
def tweets_to_data_frame(self, tweets):
... | return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) | identifier_body |
browsingcontext.rs | , SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session hist... | (cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
bp: *mut bool)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
| has | identifier_name |
browsingcontext.rs | , SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session hist... |
}
}
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn push_child_context(&self, context: &BrowsingContext) {
s... | {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
} | conditional_block |
browsingcontext.rs | , SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session hist... |
pub fn active_document(&self) -> Root<Document> {
Root::from_ref(&self.history.borrow()[self.active_index.get()].document)
}
pub fn maybe_active_document(&self) -> Option<Root<Document>> {
self.history.borrow().get(self.active_index.get()).map(|entry| {
Root::from_ref(&*entry.... | {
let mut history = self.history.borrow_mut();
// Clear all session history entries after the active index
history.drain((self.active_index.get() + 1)..);
history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
self.active_index.set(self.active... | identifier_body |
browsingcontext.rs | use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtr... | use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector};
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable; | random_line_split | |
history.js | var https = require( 'https' ),
zlib = require( 'zlib' ),
path = require( 'path' ),
fs = require( 'fs' );
var count = 0;
var resolved = 0;
var outputs = [];
var done;
function check()
{
if (resolved === count) {
normalize();
display();
}
}
function makeBar( length )
{
var i ... | for (i = 0; i < new_versions.length; i++) {
getSizeAtVersion( new_versions[i], '/min/moment.min.js' );
}
}
function getLocal()
{
count++;
var op = {};
outputs.push( op );
fs.readFile( path.normalize( __dirname + '/../min/moment.min.js' ), 'utf8', function( err, data )
{
if (... | } | random_line_split |
history.js | var https = require( 'https' ),
zlib = require( 'zlib' ),
path = require( 'path' ),
fs = require( 'fs' );
var count = 0;
var resolved = 0;
var outputs = [];
var done;
function check()
|
function makeBar( length )
{
var i = '';
while (i.length < length) {
i += '=';
}
return i;
}
function normalize()
{
var i,
max = 0,
max2 = 0;
for (i = 0; i < count; i++) {
max = Math.max( max, outputs[i].gzip );
max2 = Math.max( max2, outputs[i].origina... | {
if (resolved === count) {
normalize();
display();
}
} | identifier_body |
history.js | var https = require( 'https' ),
zlib = require( 'zlib' ),
path = require( 'path' ),
fs = require( 'fs' );
var count = 0;
var resolved = 0;
var outputs = [];
var done;
function check()
{
if (resolved === count) {
normalize();
display();
}
}
function makeBar( length )
{
var i ... |
zlib.gzip( data, function( error, result )
{
op.version = '.next';
op.gzip = result.length;
op.original = data.length;
resolved++;
check();
} );
} );
}
module.exports = function( grunt )
{
grunt.registerTask( 'history', 'Check... | {
throw err;
} | conditional_block |
history.js | var https = require( 'https' ),
zlib = require( 'zlib' ),
path = require( 'path' ),
fs = require( 'fs' );
var count = 0;
var resolved = 0;
var outputs = [];
var done;
function | ()
{
if (resolved === count) {
normalize();
display();
}
}
function makeBar( length )
{
var i = '';
while (i.length < length) {
i += '=';
}
return i;
}
function normalize()
{
var i,
max = 0,
max2 = 0;
for (i = 0; i < count; i++) {
max = M... | check | identifier_name |
tokenizer.js | 'use strict';module.exports = function(css){var TokenType=require('../token-types');var tokens=[],urlMode=false,blockMode=0,c, // current character
cn, // next character
pos=0,tn=0,ln=1,col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationM... | * @param {string} css Unparsed part of CSS string
*/function parseSLComment(css){var start=pos; // Read the string until we meet line break.
// Since we already know first 2 characters (`//`), start reading
// from `pos + 2`:
for(pos += 2;pos < css.length;pos++) {if(css.charAt(pos) === '\n' || css.charAt(pos) =... | for(pos += 2;pos < css.length;pos++) {if(css.charAt(pos) === '*' && css.charAt(pos + 1) === '/'){pos++;break;}} // Add full comment (including `/*` and `*/`) to the list of tokens:
var comment=css.substring(start,pos + 1);pushToken(TokenType.CommentML,comment,col);var newlines=comment.split('\n');if(newlines.length > 1... | random_line_split |
tokenizer.js | 'use strict';module.exports = function(css){var TokenType=require('../token-types');var tokens=[],urlMode=false,blockMode=0,c, // current character
cn, // next character
pos=0,tn=0,ln=1,col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationM... | (css){var start=pos; // Read the string until we meet line break.
// Since we already know first 2 characters (`//`), start reading
// from `pos + 2`:
for(pos += 2;pos < css.length;pos++) {if(css.charAt(pos) === '\n' || css.charAt(pos) === '\r'){break;}} // Add comment (including `//` and line break) to the list of tok... | parseSLComment | identifier_name |
tokenizer.js | 'use strict';module.exports = function(css){var TokenType=require('../token-types');var tokens=[],urlMode=false,blockMode=0,c, // current character
cn, // next character
pos=0,tn=0,ln=1,col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationM... | /**
* Check if a character is a decimal digit
* @param {string} c Character
* @returns {boolean}
*/function isDecimalDigit(c){return '0123456789'.indexOf(c) >= 0;} /**
* Parse spaces
* @param {string} css Unparsed part of CSS string
*/function parseSpaces(css){var start=pos; // Read ... | {tokens.push({tn:tn++,ln:ln,col:column,type:type,value:value});} | identifier_body |
tokenizer.js | 'use strict';module.exports = function(css){var TokenType=require('../token-types');var tokens=[],urlMode=false,blockMode=0,c, // current character
cn, // next character
pos=0,tn=0,ln=1,col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationM... | var ident=css.substring(start,pos--); // Enter url mode if parsed substring is `url`:
urlMode = urlMode || ident === 'url'; // Add identifier to tokens:
pushToken(TokenType.Identifier,ident,col);col += pos - start;} /**
* Parse equality sign
* @param {string} sass Unparsed part of SASS string
*/function ... | { // Skip all '\':
if(css.charAt(pos) === '\\')pos++;else if(css.charAt(pos) in Punctuation)break;} | conditional_block |
input_cells.py | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
def _input_family(identifier_prefix: str, letter: str, rev: bool = False) -> Iterator[CellMaker]:
for n in CELL_SIZES:
yield CellMaker(
identifier=identifier_prefix + str(n),
size=n,
maker=lambda args: InputCell(
qubits=args.qubits[::-1] if rev else arg... | yield from _input_family("inputA", "a")
yield from _input_family("inputB", "b")
yield from _input_family("inputR", "r")
yield from _input_family("revinputA", "a", rev=True)
yield from _input_family("revinputB", "b", rev=True)
# Classical inputs.
yield CellMaker("setA", 2, lambda args: SetDefaul... | identifier_body |
input_cells.py | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | (self, column: List[Optional['Cell']]):
for i in range(len(column)):
cell = column[i]
if cell is not None:
column[i] = cell.with_input(self.letter, self.qubits)
class SetDefaultInputCell(Cell):
"""A persistent modifier that provides a fallback classical input."""
... | modify_column | identifier_name |
input_cells.py | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
def with_line_qubits_mapped_to(self, qubits: List['cirq.Qid']) -> 'Cell':
return InputCell(qubits=Cell._replace_qubits(self.qubits, qubits), letter=self.letter)
def modify_column(self, column: List[Optional['Cell']]):
for i in range(len(column)):
cell = column[i]
if cel... |
def gate_count(self) -> int:
return 0 | random_line_split |
input_cells.py | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | yield CellMaker(
identifier=identifier_prefix + str(n),
size=n,
maker=lambda args: InputCell(
qubits=args.qubits[::-1] if rev else args.qubits, letter=letter
),
) | conditional_block | |
toolset_requirements.py | #!/usr/bin/python
# Copyright 2014 Steven Watanabe
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt)
# Test the handling of toolset.add-requirements
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, ignore_toolset_requi... | import toolset ;
import errors ;
rule test-rule ( properties * )
{
return <define>TEST_INDIRECT_CONDITIONAL ;
}
toolset.add-requirements
<define>TEST_MACRO
<conditional>@test-rule
<link>shared:<define>TEST_CONDITIONAL
;
rule check-requirements ( target : sources * : properties * )
{
local macros = TEST_MAC... | t.write('jamroot.jam', ''' | random_line_split |
variables_61.js | var searchData=
[
['a',['a',['../structRREP.html#abe45cd7d5c14dc356ecab531b2176242',1,'RREP']]],
['ack_5ftimer',['ack_timer',['../structrt__table.html#a4b5c6baab186ae8733b48cf2d5172852',1,'rt_table']]],
['active',['active',['../classNA__NesgLog.html#a0ce1b63fe991dc4304cb30d703aadcd6',1,'NA_NesgLog']]],
['active... | ['attacktype',['attackType',['../classNA__Attack.html#ac4cf8ddfd1c47f348f057f49382f5323',1,'NA_Attack']]],
['avhopcount',['avHopCount',['../classNA__UDPBasicBurst.html#a8c9180eebb4ba6a44ab2ca3bc5052426',1,'NA_UDPBasicBurst']]]
]; | ['aodvrttablemap',['aodvRtTableMap',['../classNA__AODVUU.html#ae0d6f9d77438a52f9c571a77e2151a48',1,'NA_AODVUU']]],
['aodvtimermap',['aodvTimerMap',['../classNA__AODVUU.html#ab1245e4e87b93a0416f42606da162489',1,'NA_AODVUU']]], | random_line_split |
document_library_tags.py | """Templatetags for the ``document_library`` app."""
from django import template
from ..models import Document
register = template.Library()
@register.assignment_tag
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another ... |
return files
@register.assignment_tag(takes_context=True)
def get_frontpage_documents(context):
"""Returns the library favs that should be shown on the front page."""
req = context.get('request')
qs = Document.objects.published(req).filter(is_on_front_page=True)
return qs
@register.assignment_t... | doc_trans.filer_file.language = doc_trans.language_code
files.append(doc_trans.filer_file) | conditional_block |
document_library_tags.py | """Templatetags for the ``document_library`` app."""
from django import template
from ..models import Document
register = template.Library()
@register.assignment_tag
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another ... | (context, count=5):
"""
Returns the latest documents.
:param count: Number of documents to be returned. Defaults to 5.
"""
req = context.get('request')
qs = Document.objects.published(req)[:count]
return qs
| get_latest_documents | identifier_name |
document_library_tags.py | """Templatetags for the ``document_library`` app."""
from django import template
from ..models import Document
register = template.Library()
@register.assignment_tag
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another ... |
@register.assignment_tag(takes_context=True)
def get_latest_documents(context, count=5):
"""
Returns the latest documents.
:param count: Number of documents to be returned. Defaults to 5.
"""
req = context.get('request')
qs = Document.objects.published(req)[:count]
return qs
| """Returns the library favs that should be shown on the front page."""
req = context.get('request')
qs = Document.objects.published(req).filter(is_on_front_page=True)
return qs | identifier_body |
document_library_tags.py | """Templatetags for the ``document_library`` app."""
from django import template
from ..models import Document
register = template.Library()
@register.assignment_tag
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another ... | req = context.get('request')
qs = Document.objects.published(req)[:count]
return qs | random_line_split | |
util.py | = m.end()
if end == len(s):
words.append(s[:end])
break
if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
words.append(s[:end]) # we definitely have a word delimiter
s = string.lstrip(s[end:])
pos = 0
... | log.info("byte-compiling %s to %s", file, cfile_base)
if not dry_run:
compile(file, cfile, dfile) | conditional_block | |
util.py | # if some suspicious happens.
bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
machine += ".%s" % bitness[sys.maxint]
# fall through to standard osname-release-machine representation
elif osname[:4] == "irix": # could be "irix64"!
retu... | (s, local_vars):
"""Perform shell/Perl-style variable substitution on 'string'. Every
occurrence of '$' followed by a name is considered a variable, and
variable is substituted by the value found in the 'local_vars'
dictionary, or in 'os.environ' if it's not in 'local_vars'.
'os.environ' is f... | subst_vars | identifier_name |
util.py | ] + s[end+1:]
pos = end+1
else:
if s[end] == "'": # slurp singly-quoted string
m = _squote_re.match(s, end)
elif s[end] == '"': # slurp doubly-quoted string
m = _dquote_re.match(s, end)
else:
... | """Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
lines = string.split(header, '\n')
header = string.join(lines, '\n' + 8*' ')
return header | identifier_body | |
util.py | # At least on Linux/Intel, 'machine' is the processor --
# i386, etc.
# XXX what about Alpha, SPARC, etc?
return "%s-%s" % (osname, machine)
elif osname[:5] == "sunos":
if release[0] >= "5": # SunOS 5 == Solaris 2
osname = "solaris"
r... | machine = string.replace(machine, '/', '-')
if osname[:5] == "linux":
| random_line_split | |
Animation.ts | module WebGLEngine.Types {
export class Animation {
public static Types = {
WITH_CHANGES : 0,
WITHOUT_CHANGES: 1
};
private static _pool = new Pool<Animation>();
private _type : number;
private _frames : Frame[];
private _initialFrame : Frame;
private _targets : AnimationTarget[];
// TODO :... | mesh.rotation.copyFrom(vector);
}
}
}
} | random_line_split | |
Animation.ts | module WebGLEngine.Types {
export class Animation {
public static Types = {
WITH_CHANGES : 0,
WITHOUT_CHANGES: 1
};
private static _pool = new Pool<Animation>();
private _type : number;
private _frames : Frame[];
private _initialFrame : Frame;
private _targets : AnimationTarget[];
// TODO :... |
while (elapsedTime >= this._frames[frameIndex].getTime());
}
}
private _updateTarget(target : AnimationTarget, frameIndex : number, percents : number) : void {
var frame : Frame,
previousFrame : Frame = frameIndex > 0 ? this._frames[frameIndex - 1] : this._initialFrame,
mesh : Transformations,
... | {
elapsedTime = Date.now() - target.getStartTime();
if (elapsedTime >= this._frames[frameIndex].getTime()) {
target.shiftStartTime(this._frames[frameIndex].getTime());
frameIndex = target.nextFrame();
if (frameIndex >= this._frames.length) {
// last update
this._updateTarget(ta... | conditional_block |
Animation.ts | module WebGLEngine.Types {
export class Animation {
public static Types = {
WITH_CHANGES : 0,
WITHOUT_CHANGES: 1
};
private static _pool = new Pool<Animation>();
private _type : number;
private _frames : Frame[];
private _initialFrame : Frame;
private _targets : AnimationTarget[];
// TODO :... | () : boolean {
for (var i = 0; i < this._targets.length; i++) {
this._targets[i].pause();
}
return Animation._pool.remove(this);
}
private _update(deltaTime : number) : void {
var elapsedTime : number,
frameIndex : number,
targetRemoved : boolean,
target : AnimationTarget,
i : numb... | turnOff | identifier_name |
Animation.ts | module WebGLEngine.Types {
export class Animation {
public static Types = {
WITH_CHANGES : 0,
WITHOUT_CHANGES: 1
};
private static _pool = new Pool<Animation>();
private _type : number;
private _frames : Frame[];
private _initialFrame : Frame;
private _targets : AnimationTarget[];
// TODO :... | // search for current frame
do {
elapsedTime = Date.now() - target.getStartTime();
if (elapsedTime >= this._frames[frameIndex].getTime()) {
target.shiftStartTime(this._frames[frameIndex].getTime());
frameIndex = target.nextFrame();
if (frameIndex >= this._frames.length) {
// l... | {
var elapsedTime : number,
frameIndex : number,
targetRemoved : boolean,
target : AnimationTarget,
i : number;
for (i = 0; i < this._targets.length; i++) {
target = this._targets[i];
if (target.isPaused()) {
continue;
}
if (this._type === Animation.Types.WITHOUT_CHANGES) {... | identifier_body |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xact... | attempts += 1;
if attempts >= 10 {
break
}
// Attempt to lock the pidfile
let pid_file = MachineConfig::pid_file_path(&self.id);
let lock_result = Pidfile::new(
&pid_file,
std::fs::Permissions::from... | {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print_queues
WHERE machine_id = $1
"#,
self.id,
)
.fetch_optional(&self.db)
.await?;
// Delete the machi... | identifier_body |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xact... | )
.fetch_optional(&self.db)
.await?;
// Delete the machine config
let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id));
let _ = std::fs::remove_file(config_path);
let mut attempted_sig_int = false;
let mut attemp... | WHERE machine_id = $1
"#,
self.id, | random_line_split |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xact... |
};
async_std::task::sleep(std::time::Duration::from_millis(10)).await;
}
ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id)));
Ok(())
}
}
| {
// Other weirdness - let's try again in a little bit
} | conditional_block |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct | ;
#[async_trait::async_trait]
impl xactor::Handler<DeleteMachine> for Machine {
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print... | DeleteMachine | identifier_name |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> | 意理解错了
// 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。
pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// 练习下动态规划
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
let mut pos = (0, 0);
for i in (0..... | {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num in nums2 {
if let Some(count) = ma... | identifier_body |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
... | if nums1[i] == nums2[j] {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = 0;
}
if max_len <= dp[i][j] {
max_len = dp[i][j];
pos = (i, j);
}
}
... |
for i in (0..m).rev() {
for j in (0..n).rev() { | random_line_split |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn | (nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num... | intersect | identifier_name |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
... | pos = (i, j);
}
}
}
nums1
.get(pos.0..(pos.0 + max_len))
.map(|x| x.iter().map(|x| *x).collect())
.unwrap_or(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersect1() {
let mut res = ... | max_len = dp[i][j];
| conditional_block |
tag_ports_during_bulk_creation.py | # Copyright (c) 2019 Verizon Media
# 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 require... | ACTION_STATUS = {} | RESOURCE_ATTRIBUTE_MAP = {}
SUB_RESOURCE_ATTRIBUTE_MAP = {}
ACTION_MAP = {}
REQUIRED_EXTENSIONS = []
OPTIONAL_EXTENSIONS = [] | random_line_split |
hooksError.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. |
import {Circus} from '@jest/types';
import circus from '../';
describe.each(['beforeEach', 'beforeAll', 'afterEach', 'afterAll'])(
'%s hooks error throwing',
(fn: Circus.HookType) => {
test.each([
['String'],
[1],
[[]],
[{}],
[Symbol('hello')],
[true],
[null],
[... | *
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ | random_line_split |
ClipboardScreen.tsx | import * as Clipboard from 'expo-clipboard';
import * as React from 'react';
import { Button, Text, TextInput } from 'react-native';
import { Page, Section } from '../components/Page';
export default function ClipboardScreen() {
return (
<Page>
<Section title="Set String">
<SetStringExample /> | </Section>
<Section title="Get String">
<GetStringExample />
</Section>
<Section title="Clipboard listener">
<ListenerExample />
</Section>
</Page>
);
}
ClipboardScreen.navigationOptions = {
title: 'Clipboard',
};
function GetStringExample() {
const [value, setV... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.