file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
self.project1 = self.env["project.project"].create({"name": ... | (self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
)
| test_check_subtasks | identifier_name |
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
|
def test_check_subtasks(self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been ... | super().setUp()
self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create(
{"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id"... | identifier_body |
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
| {"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id": self.project1.id, "parent_id": self.task1.id}
)
self.subtask2 = self.env["project.task"].create(
{"name": "3", "project_id"... | self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create( | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (AutotoolsPackage):
"""The ViennaRNA Package consists of a C code library and several
stand-alone programs for the prediction and comparison of RNA secondary
structures.
"""
homepage = "https://www.tbi.univie.ac.at/RNA/"
url = "https://www.tbi.univie.ac.at/RNA/download/sourcecode/2_4_x/Vie... | Viennarna | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place,... | #
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
def configure_args(self):
args = self.enable_or_disable('sse')
args += self.with_or_without('python')
args += self.with_or_without('perl')
if self.spec.satisfies('@2.4.3:'):
args.append('--without-swig')
if 'python@3:' in self.spec:
args.append('--... | url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.format(version.up_to(2).underscored, version) | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
if 'python@3:' in self.spec:
args.append('--with-python3')
return args
| args.append('--without-swig') | conditional_block |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):... | {
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"from_node" : "node1", "to_node" : "node2"
}
},
{
"allocate" : {
... | )
body = """ | random_line_split |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):... |
def test_put_settings(self):
c = ClusterClient()
body = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait()
| c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait() | identifier_body |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):... |
self.stop()
def test_health(self):
c = ClusterClient()
c.cluster_health(callback=self.handle_cb)
self.wait()
def test_pending_tasks(self):
c = ClusterClient()
c.cluster_pending_tasks(callback=self.handle_cb)
self.wait()
def test_state(self):
... | self.assertTrue(req.code in (200, 201, )) | conditional_block |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):... | (self):
c = ClusterClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
body = """
{
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"fr... | test_reroute | identifier_name |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfi... | (model_filename, featuresets, quiet=True):
# Make sure we can find java & weka.
config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
... | train | identifier_name |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfi... |
else:
for line in lines[:10]: print line
raise ValueError('Unhandled output format -- your version '
'of weka may not be supported.\n'
' Header: %s' % lines[0])
@staticmethod
... | for line in lines[1:] if line.strip()]
elif lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'distribution']:
return [self.parse_weka_distribution(line.split()[-1])
for line in lines[1:] if line.strip()] | random_line_split |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfi... |
s += '%s\n' % self._fmt_arff_val(label)
return s
def _fmt_arff_val(self, fval):
if fval is None:
return '?'
elif isinstance(fval, (bool, int, long)):
return '%s' % fval
elif isinstance(fval, float):
return '%r' % fval
els... | s += '%s,' % self._fmt_arff_val(tok.get(fname)) | conditional_block |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfi... |
class ARFF_Formatter:
"""
Converts featuresets and labeled featuresets to ARFF-formatted
strings, appropriate for input into Weka.
"""
def __init__(self, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature sp... | config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
train_filename = os.path.join(temp_dir, 'train.arff')
formatter.write(train_fil... | identifier_body |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struc... |
}
pub fn new(group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
}
| {
loop {
for cgroup in self.cgroups {
let kvs = cgroup.read();
for kv in kvs {
let (key, val) = kv;
println!("{} : {}", key, val);
}
}
}
} | identifier_body |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struc... | (group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
}
| new | identifier_name |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struc... | pub fn new(group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
} | }
}
}
| random_line_split |
interfaces.ts | import { Stats } from "fs";
import { Diagnostic } from "typescript";
import { TypescriptConfig } from "./generated/typescript-config";
export * from "./generated/typescript-config";
export type CompilerOptionsConfig = TypescriptConfig["compilerOptions"];
export interface NormalizedOptions {
workingPath: AbsolutePat... | __absolutePathBrand: any;
};
/**
* A CanonicalPath is an AbsolutePath that has been canonicalized. Primarily,
* this means that in addition to the guarantees of AbsolutePath, it has also
* had casing normalized on case-insensitive file systems. This is an alias of
* `ts.Path` type.
*/
export type CanonicalPath ... | export type AbsolutePath = string & { | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import * as uiv from 'uiv'
import Vue2Filters from 'vue2-filters'
import VueCookies from 'vue-cookies'
import App from './App'
import VueI18n from 'vue-i18n'
... |
/* eslint-disable no-new */
new Vue({
el: '#user-summary-vue',
components: {
App
},
template: '<App/>',
i18n
}) | silentTranslationWarn: true,
locale: locale, // set locale
messages // set locale messages,
}) | random_line_split |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class FieldColumn(ObjectColumn):
| """ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None: fieldname = field.... | identifier_body | |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__) | class FieldColumn(ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if ... | random_line_split | |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class FieldColumn(ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
... |
if label is None: label = field.label
ObjectColumn.__init__(self, label, fieldname, fieldtype=fieldtype)
self.field = field
self.article = article
self.valuelabels = {}
def getUnit(self, row):
return row.ca if self.article else row.cs
def getCell(self, row):
... | fieldname = field.fieldname | conditional_block |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class | (ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None... | FieldColumn | identifier_name |
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Als... | changeText = `.${path.sep}${changeText}`;
};
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(file, position - 1, specifier.specifierText, changeText);
});
changes = changes.concat(tempChanges);
... | random_line_split | |
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Als... | else {
return true;
}
});
relavantFiles.forEach(file => {
let tempChanges: ReplaceChange[] = files[file]
.map(specifier => {
let componentName = path.basename(this.oldFilePath, '.ts');
let fileDir = path.dirname(file);
... | {
return path.basename(path.basename(file, '.ts'), '.spec') !== fileBaseName;
} | conditional_block |
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Als... | (): Promise<Change[]> {
return dependentFilesUtils.getDependentFiles(this.oldFilePath, this.rootPath)
.then((files: dependentFilesUtils.ModuleMap) => {
let changes: Change[] = [];
let fileBaseName = path.basename(this.oldFilePath, '.ts');
// Filter out the spec file associated with to... | resolveDependentFiles | identifier_name |
add-keyword.modal.component.ts | import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
@Component({
moduleId: module.id,
selector: 'sd-add-keyword-modal',
styles: [],
template: ` <modal #keywordModal [size]="'sm'">
<modal-hea... | export class AddKeywordModalComponent {
@Input('word') word: string = '';
@Output('onAdd') onAdd : EventEmitter<string> = new EventEmitter();
@ViewChild('keywordModal') keywordmodal: ModalComponent;
/**
* Outer open method.
*/
open() {
this.keywordmodal.open();
}
/**
... | <modal-footer>
<button type="button" class="btn btn-primary" (click)="submitword()">Submit</button>
</modal-footer>
</modal>`
}) | random_line_split |
add-keyword.modal.component.ts | import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
@Component({
moduleId: module.id,
selector: 'sd-add-keyword-modal',
styles: [],
template: ` <modal #keywordModal [size]="'sm'">
<modal-hea... | () {
this.keywordmodal.open();
}
/**
* Opens up the add keyword dialogue
*/
openAddKeyword() {
this.keywordmodal.open();
}
/**
* Submits a new keyword
* emits the event back to parent element
*/
submitword() {
console.log(this.word);
thi... | open | identifier_name |
utils.js | var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var chalk = require('chalk');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var ngParseModule = require('ng-parse-module');
exports.JS_MARKER = "<!-- Add New Component JS Above -->";
exports.LESS_MARKER = "/* Add Comp... | else {
exports.addToFile(moduleFile,'$routeProvider.when(\''+route+'\',{templateUrl: \''+routeUrl+'\'});',exports.ROUTE_MARKER);
}
that.log.writeln(chalk.green(' updating') + ' %s',path.basename(moduleFile));
};
exports.getParentModule = function(dir){
//starting this dir, find the first module ... | {
var code = '$stateProvider.state(\''+name+'\', {\n url: \''+route+'\',\n templateUrl: \''+routeUrl+'\'\n\t\t});';
exports.addToFile(moduleFile,code,exports.STATE_MARKER);
} | conditional_block |
utils.js | var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var chalk = require('chalk');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var ngParseModule = require('ng-parse-module');
exports.JS_MARKER = "<!-- Add New Component JS Above -->";
exports.LESS_MARKER = "/* Add Comp... | }else{
that.template(templateFile, path.join(dir, customTemplateName));
}
//inject the file reference into index.html/app.less/etc as appropriate
exports.inject(path.join(dir, customTemplateName), that, module);
});
};
exports.inject = function(f... | that.template(templateFile, path.join(testDirLocation, customTemplateName)); | random_line_split |
regions-infer-invariance-due-to-decl.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 ... | {
} | identifier_body | |
regions-infer-invariance-due-to-decl.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct invariant<'a> {
marker: marker::PhantomData<*mut &'a()>
}
fn to_same_lifetime<'r>(b_isize: invariant<'r>) {
let bj: inva... | // 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 | random_line_split |
regions-infer-invariance-due-to-decl.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 ... | () {
}
| main | identifier_name |
menubutton.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_drop!(MenuButton)
impl_TraitWidget!(MenuButton)
impl gtk::ContainerTrait for MenuButton {}
impl gtk::ButtonTrait for MenuButton {}
impl gtk::ToggleButtonTrait for MenuButton {}
impl_widget_events!(MenuButton)
| unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.get_widget())
}
}
} | identifier_body |
menubutton.rs | // This file is part of rgtk. | // rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but ... | // | random_line_split |
menubutton.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | -> Option<MenuButton> {
let tmp_pointer = unsafe { ffi::gtk_menu_button_new() };
check_pointer!(tmp_pointer, MenuButton)
}
pub fn set_popup<T: gtk::WidgetTrait>(&mut self, popup: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_popup(GTK_MENUBUTTON(self.pointer), popup.get_wid... | w() | identifier_name |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
rospy... | except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
print "Service call failed: %s"%e
rate.sleep()
if __name__ == '__main__':
try:
pose_publisher()
except rospy.ROSInterruptException:
pass | if not response.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info) | random_line_split |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
rospy... | try:
pose_publisher()
except rospy.ROSInterruptException:
pass | conditional_block | |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
|
if __name__ == '__main__':
try:
pose_publisher()
except rospy.ROSInterruptException:
pass
| rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queu... | identifier_body |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def | ():
rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugI... | pose_publisher | identifier_name |
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | (SimObject):
type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to")
| RubyDirectoryMemory | identifier_name |
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | from m5.proxy import *
from m5.SimObject import SimObject
class RubyDirectoryMemory(SimObject):
type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory... | random_line_split | |
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to") | identifier_body | |
error.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | #[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Invalid bind specification '{}'", _0)]
InvalidBindSpec(String),
#[fail(display = "Invalid topology '{}'. Possible values: standalone, leader", _0)]
InvalidTopology(String),
#[fail(display = "Invalid binding \"{}\", must be of the form <NAME>:... | // See the License for the specific language governing permissions and
// limitations under the License.
use hcore;
| random_line_split |
error.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 r... | (err: hcore::Error) -> Error {
Error::HabitatCore(err)
}
}
| from | identifier_name |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the de... |
def table_busy_reason(self, table_def):
if table_def['TableStatus'] != 'ACTIVE':
return 'Table is in state %s' % table_def['TableStatus']
if 'GlobalSecondaryIndexes' in table_def:
for index in table_def['GlobalSecondaryIndexes']:
if index['IndexStatus'] != 'ACTIVE':
return 'Ind... | self.wait_for_table(client, table_name)
client.update_table(**request) | identifier_body |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the de... | params = {
'AttributeDefinitions': new_def['AttributeDefinitions'],
'TableName': table_name,
'KeySchema': new_def['KeySchema'] if 'KeySchema' in new_def else [],
'ProvisionedThroughput': self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
}
if 'LocalSecond... | def create(self, client, table_name, new_def): | random_line_split |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the de... | (self, idefs):
outs = []
for idef in idefs:
out = {
'IndexName': idef['IndexName'],
'KeySchema': idef['KeySchema'],
'Projection': idef['Projection']
}
if 'ProvisionedThroughput' in idef:
out['ProvisionedThroughput'] = self.construct_provisioned_throughput(... | construct_secondary_indexes | identifier_name |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the de... |
if updates:
request['GlobalSecondaryIndexUpdates'] = updates
request['AttributeDefinitions'] = new_def['AttributeDefinitions']
old_provisioning = self.construct_provisioned_throughput(table_def['ProvisionedThroughput'])
new_provisioning = self.construct_provisioned_throughput(new_def['Provision... | updates.append({ 'Create': index}) | conditional_block |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ra... |
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecima... | {//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
} | identifier_body |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
| (){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
... | constructor | identifier_name |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ra... |
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive... | {
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
} | conditional_block |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ra... | ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribu... | parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars | random_line_split |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // M... |
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = t... | { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.... | conditional_block |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // M... | (time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
... | runTasks | identifier_name |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // M... |
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if... | } | random_line_split |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // M... |
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
i... | { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTi... | identifier_body |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and... | return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, s... | def enter(self):
print "You won! Good job." | random_line_split |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and... |
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know: "
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts o... | print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake... | conditional_block |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and... | (self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': ... | enter | identifier_name |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and... |
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
... | def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods,... | identifier_body |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls =... | (component) {
if (component.getStateFilterKeys) {
return typeof component.getStateFilterKeys() === 'string' ?
[component.getStateFilterKeys()] : component.getStateFilterKeys();
}
return typeof component.props.stateFilterKeys === 'string' ?
[component.props.stateFilterKeys] : component.props.stateFil... | getStateFilterKeys | identifier_name |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls =... |
} catch(e) {
// eslint-disable-next-line no-console
if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage.");
}
// If we didn't set state, run the callback right away.
if (!settingState) done();
function done() {
// Flag this component as loaded.
... | {
settingState = true;
component.setState(storedState, done);
} | conditional_block |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls =... | var key = getLocalStorageKey(this);
if (key === false) return;
var prevStoredState = ls.getItem(key);
if (prevStoredState && process.env.NODE_ENV !== "production") {
warn(
prevStoredState === JSON.stringify(getSyncState(this, this.state)),
'While component ' + getDisplayName(this) ... | componentWillUpdate: function(nextProps, nextState) {
if (!hasLocalStorage || !this.__stateLoadedFromLS) return; | random_line_split |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls =... |
}
function getDisplayName(component) {
// at least, we cannot get displayname
// via this.displayname in react 0.12
return component.displayName || component.constructor.displayName || component.constructor.name;
}
function getLocalStorageKey(component) {
if (component.getLocalStorageKey) return component.ge... | {
// Flag this component as loaded.
component.__stateLoadedFromLS = true;
cb();
} | identifier_body |
beeswax.py | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
retu... | operation_state = rpc.get_query_state(
self.service, self._last_operation_handle)
if operation_state == self.query_state["FINISHED"]:
break
elif operation_state == self.query_state["EXCEPTION"]:
raise OperationalError(self.get_log())
ti... | conditional_block |
beeswax.py | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def cursor(self, user=None, configuration=None):
# PEP 249
if user is None:
user = getpass.getuser()
options = rpc.build_default_query_options_dict(self.service)
for opt in options:
self.default_query_options[opt.key.upper()] = opt.value
cursor = Bee... | """Impala doesn't support transactions; raises NotSupportedError"""
# PEP 249
raise NotSupportedError | identifier_body |
beeswax.py | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | (self):
return rpc.get_summary(self.service, self._last_operation_handle)
def build_summary_table(self, summary, output, idx=0,
is_fragment_root=False, indent_level=0):
return rpc.build_summary_table(
summary, idx, is_fragment_root, indent_level, output)
| get_summary | identifier_name |
beeswax.py | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | def query_string(self):
return self._last_operation_string
def get_arraysize(self):
# PEP 249
return self._buffersize if self._buffersize else 1
def set_arraysize(self, arraysize):
# PEP 249
self._buffersize = arraysize
arraysize = property(get_arraysize, set_a... | return self._rowcount
@property | random_line_split |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
... | (status, *args, **kwargs):
try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objec... | process_tweet | identifier_name |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
... | try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objects.get_current(), twitter_id=sta... | identifier_body | |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
... |
return True
| obj.content=expand_urls(status.text)
obj.pub_date = status.created_at
try:
obj.parent_post = Post.objects.get(tweet_id=status.in_reply_to_status_id)
except:
pass
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_statu... | conditional_block |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
... |
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_status.id)
retweeted_status.retweets.add(obj)
retweeted_status.save()
obj.retweet = True
except:
pass
obj.save()
return True | pass | random_line_split |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc... | (self, task_group=None, obj=None):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_gr... | generate_task_group_object | identifier_name |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc... | if not wf:
_, wf = self.generate_workflow()
wf = self._session_add(wf)
obj_name = "workflow"
obj_dict = builder.json.publish(wf)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
default = {obj_name: obj_dict}
response, workflow = self.modify(wf, obj_name, def... | "status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}): | random_line_split |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc... |
def activate_workflow(self, workflow):
workflow = self._session_add(workflow)
return self.modify_workflow(workflow, {
"status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}):
if not wf:
_, wf = self.generate_workflow()
... | if not workflow:
_, workflow = self.generate_workflow()
workflow = self._session_add(workflow) # this should be nicer
obj_name = "cycle"
obj_dict = {
obj_name: {
"workflow": {
"id": workflow.id,
"type": workflow.__class__.__name__,
"href": "/api/workflow... | identifier_body |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc... |
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_group.id,
context_id=task_group.context.id
)
obj_dict = self.obj_to_dict(tgo, obj_name)
r... | _, task_group = self.generate_task_group() | conditional_block |
gen_models.py | import csv
def model_name(table_name):
|
def quote(s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table... | if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_')) | identifier_body |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def | (s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table']
p... | quote | identifier_name |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '... |
if line['type'] in ['ForeignKey', 'OneToOneField']:
options.append(('to', quote(model_name(line['to']))))
options.append(('on_delete', 'models.CASCADE'))
if 'prevcd' in line['db_column'] or 'uomcd' in line['db_column']:
options.append(('related_name', quote('+')))
elif li... | options.append(('db_column', quote(line['db_column']))) | conditional_block |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '... | if line['type'] != 'BooleanField' and line['primary_key'] != 'True':
options.append(('null', 'True'))
options.append(('help_text', quote(line['descr'])))
print(f' {line["field"]} = models.{line["type"]}(')
for k, v in options:
print(f' {k}={v},')
print(' ... | random_line_split | |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item)
}
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
let Item { attrs, name, sour... | // except according to those terms. | random_line_split |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ,
VariantItem(i) => {
let i2 = i.clone(); // this clone is small
match i.kind {
StructVariant(mut j) => {
let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
let num_fields = foo.len();
... | {
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
ImplItem(i)
} | conditional_block |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;
}
}
| {
Module {
is_crate: m.is_crate,
items: m.items.move_iter().filter_map(|i| self.fold_item(i)).collect()
}
} | identifier_body |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <T: DocFolder>(this: &mut T, trm: TraitMethod) -> Option<TraitMethod> {
match trm {
Required(it) => {
match this.fold_item(it) {
Some(x) => return Some(Required(x)),
None => return Non... | vtrm | identifier_name |
issue-17718-static-unsafe-interior.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use std::cell::UnsafeCell;
struct MyUnsafe<T> {
value: UnsafeCell<T>
}
impl<T> MyUnsafe<T> {
fn forbidden(&self) {}
}
enum UnsafeEnum<T> {
VariantSafe,
VariantUnsafe(UnsafeCel... | // 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 http://opensource.org/licenses/MIT>, at your | random_line_split |
issue-17718-static-unsafe-interior.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 ... | <T> {
VariantSafe,
VariantUnsafe(UnsafeCell<T>)
}
static STATIC1: UnsafeEnum<int> = VariantSafe;
static STATIC2: UnsafeCell<int> = UnsafeCell { value: 1 };
const CONST: UnsafeCell<int> = UnsafeCell { value: 1 };
static STATIC3: MyUnsafe<int> = MyUnsafe{value: CONST};
static STATIC4: &'static UnsafeCell<int> ... | UnsafeEnum | identifier_name |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
... | (self):
first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms... | clean_first_name | identifier_name |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField() | fields = '__all__'
widgets = {
'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'})
... |
class Meta:
model = ContactUs | random_line_split |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
... |
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
... | first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name | identifier_body |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
... |
return message | raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere") | conditional_block |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::sta... | () {
let args = Args::from_args();
let source_map_extension = "mvsm";
let bytecode_bytes = fs::read(&args.module_binary_path).expect("Unable to read bytecode file");
let compiled_module =
CompiledModule::deserialize(&bytecode_bytes).expect("Module blob can't be deserialized");
let source_m... | main | identifier_name |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::sta... | {
let args = Args::from_args();
let source_map_extension = "mvsm";
let bytecode_bytes = fs::read(&args.module_binary_path).expect("Unable to read bytecode file");
let compiled_module =
CompiledModule::deserialize(&bytecode_bytes).expect("Module blob can't be deserialized");
let source_map ... | identifier_body | |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::sta... | use structopt::StructOpt;
use vm::file_format::CompiledModule;
#[derive(Debug, StructOpt)]
#[structopt(
name = "Move Bytecode Explorer",
about = "Explore Move bytecode and how the source code compiles to it"
)]
struct Args {
/// The path to the module binary
#[structopt(long = "module-path", short = "b... | use std::{fs, path::Path}; | random_line_split |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date... | else:
print_usage()
sys.exit(2)
print "Done. See {0}".format(output_file_name)
if __name__ == "__main__":
main(sys.argv[1:]) | if (left != 0 or bot != 0 or right != 0 or up != 0) and left < right and bot < up:
create_gann_sub_square_dates((left, bot, right+1, up+1), cell_size, date_a, marks, stream)
else:
create_gann_square_dates(square_size, cell_size, date_a, marks, stream)
stream.close() | random_line_split |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def | ():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <f... | print_usage | identifier_name |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
|
def main(argv):
cell_size = 30
date_format = "%d/%m/%Y"
# --------------------------------------
output_file_name = ''
marks_file_name = ''
square_size = -1
date_a = None
date_b = None
left, bot, right, up = 0, 0, 0, 0
# --------------------------------------
try:
... | print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <final dat... | identifier_body |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date... |
elif opt in ("-m", "--mfile"):
marks_file_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Fail... | date_b = datetime.strptime(arg, date_format) | conditional_block |
manual_flatten.rs | use super::utils::make_iterator_snippet;
use super::MANUAL_FLATTEN;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::higher;
use clippy_utils::visitors::is_local_used;
use clippy_utils::{is_lang_ctor, path_to_local_id};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::LangItem... | else {
None
}
} else if block.stmts.is_empty() {
block.expr
} else {
None
};
if_chain! {
if let Some(inner_expr) = inner_expr;
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: None })
... | {
Some(inner_expr)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.