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 |
|---|---|---|---|---|
labels.py | # -*- coding: utf-8 -*-
#
# AWL simulator - labels
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at ... | return None | random_line_split | |
labels.py | # -*- coding: utf-8 -*-
#
# AWL simulator - labels
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at ... |
labels.append(cls(insn, rawInsn.getLabel()))
# Resolve label references
for insn in insns:
for op in insn.ops:
if op.type != AwlOperator.LBL_REF:
continue
labelIndex = cls.findInList(labels, op.value)
if labelIndex is None:
raise AwlSimError("Referenced label not found",
insn =... | raise AwlSimError("Duplicate label '%s' found. "
"Label names have to be unique in a code block." %\
rawInsn.getLabel(),
insn = insn) | conditional_block |
labels.py | # -*- coding: utf-8 -*-
#
# AWL simulator - labels
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at ... | (self):
return self.insn
@classmethod
def resolveLabels(cls, insns):
# Build the label table
labels = []
for i, insn in enumerate(insns):
rawInsn = insn.getRawInsn()
if not rawInsn or not rawInsn.hasLabel():
continue
for label in labels:
if label.getLabelName() == rawInsn.getLabel():
ra... | getInsn | identifier_name |
labels.py | # -*- coding: utf-8 -*-
#
# AWL simulator - labels
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at ... | labels = []
for i, insn in enumerate(insns):
rawInsn = insn.getRawInsn()
if not rawInsn or not rawInsn.hasLabel():
continue
for label in labels:
if label.getLabelName() == rawInsn.getLabel():
raise AwlSimError("Duplicate label '%s' found. "
"Label names have to be unique in a code block.... | """AWL label."""
__slots__ = (
"insn",
"label",
)
def __init__(self, insn, label):
self.insn = insn
self.label = label
def getLabelName(self):
return self.label
def getInsn(self):
return self.insn
@classmethod
def resolveLabels(cls, insns):
# Build the label table | identifier_body |
camera.py | import os
import signal
import subprocess
class | (object):
# In order to run mjpg-streamer through Python, make sure
# mjpg-streamer-experimental is installed so the .so objects
# and mjpg-streamer are all on defualt PATH so we don't have
# to specify path (was getting a lot of errors resulting from
# files not being able to be found. Resolution ... | Camera | identifier_name |
camera.py | import os
import signal
import subprocess
class Camera(object):
# In order to run mjpg-streamer through Python, make sure
# mjpg-streamer-experimental is installed so the .so objects
# and mjpg-streamer are all on defualt PATH so we don't have
# to specify path (was getting a lot of errors resulting ... |
self.input = 'input_uvc.so -d {device}'.format(
device=self.device,
)
self.output = 'output_http.so -p {port} {web}'.format(
port=self.port,
web='-w /usr/local/www'
)
self.status = "killed"
# framerate shouldn't be changed: keep at 30, a... | self.contrast = contrast | random_line_split |
camera.py | import os
import signal
import subprocess
class Camera(object):
# In order to run mjpg-streamer through Python, make sure
# mjpg-streamer-experimental is installed so the .so objects
# and mjpg-streamer are all on defualt PATH so we don't have
# to specify path (was getting a lot of errors resulting ... | if status == 'active':
if self.status == 'suspended':
self.unsuspend()
elif self.status == 'killed':
self.start()
elif status == 'suspended':
if self.status == 'active':
self.suspend()
elif status == 'killed':
... | identifier_body | |
camera.py | import os
import signal
import subprocess
class Camera(object):
# In order to run mjpg-streamer through Python, make sure
# mjpg-streamer-experimental is installed so the .so objects
# and mjpg-streamer are all on defualt PATH so we don't have
# to specify path (was getting a lot of errors resulting ... |
return (self.process.poll() is None)
def get_status(self):
if not self.is_alive():
self.status = 'killed'
return self.status
def set_status(self, status):
if status == 'active':
if self.status == 'suspended':
self.unsuspend()
... | return False | conditional_block |
horoscope.py | '''
A simple module for Sopel (http://sopel.chat) to get horoscope
information from a JSON API and put it back into chat
All orignal code written by: BluDragyn. (www.bludragyn.net)
This module is released under the terms of the GPLv3
(https://www.gnu.org/licenses/gpl-3.0.en.html)
If you use and like this module, pl... | (bot, trigger):
signs = set(['aquarius', 'Aquarius',
'pisces', 'Pisces',
'aries', 'Aries',
'taurus', 'Taurus',
'gemini', 'Gemini',
'cancer', 'Cancer',
'leo', 'Leo',
'virgo', 'Virgo',
... | horoscope | identifier_name |
horoscope.py | '''
A simple module for Sopel (http://sopel.chat) to get horoscope
information from a JSON API and put it back into chat
| All orignal code written by: BluDragyn. (www.bludragyn.net)
This module is released under the terms of the GPLv3
(https://www.gnu.org/licenses/gpl-3.0.en.html)
If you use and like this module, please send me an email
(dragyn@bludragyn.net) or drop in to see me on Occultus IRC
(irc.occultus.net), I hang out in #sacred... | random_line_split | |
horoscope.py | '''
A simple module for Sopel (http://sopel.chat) to get horoscope
information from a JSON API and put it back into chat
All orignal code written by: BluDragyn. (www.bludragyn.net)
This module is released under the terms of the GPLv3
(https://www.gnu.org/licenses/gpl-3.0.en.html)
If you use and like this module, pl... | bot.say(nick + ', please use a valid zodiac sign and try again.')
def get_hs(sunsign):
http = urllib3.PoolManager()
url = 'http://sandipbgt.com/theastrologer/api/horoscope/' \
+ sunsign + '/today/'
response = http.request('GET', url)
raw = json.loads(response.data.decode('ut... | signs = set(['aquarius', 'Aquarius',
'pisces', 'Pisces',
'aries', 'Aries',
'taurus', 'Taurus',
'gemini', 'Gemini',
'cancer', 'Cancer',
'leo', 'Leo',
'virgo', 'Virgo',
'libra', 'Libra',... | identifier_body |
horoscope.py | '''
A simple module for Sopel (http://sopel.chat) to get horoscope
information from a JSON API and put it back into chat
All orignal code written by: BluDragyn. (www.bludragyn.net)
This module is released under the terms of the GPLv3
(https://www.gnu.org/licenses/gpl-3.0.en.html)
If you use and like this module, pl... |
else:
bot.say(nick + ', please use a valid zodiac sign and try again.')
def get_hs(sunsign):
http = urllib3.PoolManager()
url = 'http://sandipbgt.com/theastrologer/api/horoscope/' \
+ sunsign + '/today/'
response = http.request('GET', url)
raw = json.loads(response.data.... | sign = sign.lower()
hs = get_hs(sign)
sign = sign.capitalize()
bot.say('Today\'s horoscope for ' + sign + ' is: ' + hs) | conditional_block |
d3kit-timeline.js | // EDIT: List all dependencies in AMD style
define(['d3', 'd3kit', 'labella'], factory);
}
else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
// EDIT: Pass dependencies to fact... | (options.direction==='left' || options.direction==='right') ? h : w,
d
);
node.w = w;
node.h = h;
return node;
});
dummyText.remove();
force.options(options.labella)
.nodes(nodes)
.compute();
drawLabels(force.nodes());
}
... | random_line_split | |
d3kit-timeline.js | // EDIT: List all dependencies in AMD style
define(['d3', 'd3kit', 'labella'], factory);
}
else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
// EDIT: Pass dependencies to fact... | axis.orient('left');
axisTransform = 'translate('+(0)+','+(0)+')';
break;
case 'left':
axis.orient('right');
axisTransform ='translate('+(skeleton.getInnerWidth())+','+(0)+')';
break;
case 'up':
axis.orient('bottom');
axisTr... | {
if(!skeleton.hasData()) return;
var data = skeleton.data();
if(options.domain){
options.scale.domain(options.domain);
}
else{
options.scale.domain(d3.extent(data, options.timeFn))
.nice();
}
options.scale.range([0, (options.direction==='left' || op... | identifier_body |
d3kit-timeline.js | // EDIT: List all dependencies in AMD style
define(['d3', 'd3kit', 'labella'], factory);
}
else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
// EDIT: Pass dependencies to fact... | (data){
var selection = layers.get('main.dot').selectAll('circle.dot')
.data(data, options.keyFn);
var field = (options.direction==='left' || options.direction==='right') ? 'cy' : 'cx';
selection.enter().append('circle')
.classed('dot', true)
.on('click', function(d, i){
... | drawDots | identifier_name |
check_static_recursion.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 ... | ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.vis... | Some(DefAssociatedConst(def_id, _)) |
Some(DefConst(def_id)) if | random_line_split |
check_static_recursion.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 ... | (v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
idstack: Vec::new()
}
}
fn with_ite... | new | identifier_name |
check_static_recursion.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 CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
idstack: Vec<ast::NodeId>
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
... | {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
} | identifier_body |
res_company.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# res_partner
# Copyright (c) 2013 Codeback Software S.L. (http://codeback.es)
# @author: Miguel García <miguel@codeback.es>
# @author: Javier Fuentes <javier@codeback.es>
#
# This program is fr... | osv.osv):
"""añadimos los nuevos campos"""
_name = "res.company"
_inherit = "res.company"
_columns = {
'web_discount': fields.float('Descuento web (%)'),
}
| es_company( | identifier_name |
res_company.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# res_partner
# Copyright (c) 2013 Codeback Software S.L. (http://codeback.es)
# @author: Miguel García <miguel@codeback.es>
# @author: Javier Fuentes <javier@codeback.es>
#
# This program is fr... | ""añadimos los nuevos campos"""
_name = "res.company"
_inherit = "res.company"
_columns = {
'web_discount': fields.float('Descuento web (%)'),
}
| identifier_body | |
res_company.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# res_partner
# Copyright (c) 2013 Codeback Software S.L. (http://codeback.es) | # it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied ... | # @author: Miguel García <miguel@codeback.es>
# @author: Javier Fuentes <javier@codeback.es>
#
# This program is free software: you can redistribute it and/or modify | random_line_split |
samcef.py | ##
# Copyright 2015-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | txt += self.module_generator.prepend_paths('PATH', [''])
return txt | random_line_split | |
samcef.py | ##
# Copyright 2015-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
def make_module_extra(self):
"""Include Samcef install directory in $PATH."""
txt = super(EB_Samcef, self).make_module_extra()
txt += self.module_generator.prepend_paths('PATH', [''])
return txt
| """Custom sanity check for Samcef."""
custom_paths = {
'files': ['samcef'],
'dirs': [],
}
super(EB_Samcef, self).sanity_check_step(custom_paths=custom_paths) | identifier_body |
samcef.py | ##
# Copyright 2015-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | (self):
"""Custom install procedure for Samcef."""
# e.g.: 17.0-03 => 17, 17.0, 170
maj_ver = self.version.split('.')[0]
main_ver = self.version.split('-')[0]
flat_ver = ''.join(main_ver.split('.'))
qa = {
"Default language ? (E=English, F=French, default E)... | install_step | identifier_name |
EndPoint.ts | import {IEndPoint, IIndicator} from '../domain';
import {MetricsMessengerServer} from '../util/MessengerUtil';
import {IndicatorProxy} from '../indicator/IndicatorProxy';
import {IndicatorResult} from '../indicator/IndicatorResult';
const util = require('util');
const assert = require('assert');
export class EndPoint... | rn appName ? allResults[appName] : allResults;
}
/**
* 登记指标
* @param data
* @param reply
* @param client
*/
protected registerIndicator(data, reply, client) {
if (this.group !== data.group) {
// 不匹配则忽略
return;
}
if (data.type === 'singleton') {
// 单例下,每个应用只允许一个实例存在
... | ogger.error(`Query group(${result.getIndicatorGroup()}) IPC results error, message = ${result.getErrorMessage()}`);
}
}
retu | conditional_block |
EndPoint.ts | import {IEndPoint, IIndicator} from '../domain';
import {MetricsMessengerServer} from '../util/MessengerUtil';
import {IndicatorProxy} from '../indicator/IndicatorProxy';
import {IndicatorResult} from '../indicator/IndicatorResult';
const util = require('util');
const assert = require('assert');
export class EndPoint... | if (this.group !== data.group) {
// 不匹配则忽略
return;
}
if (data.type === 'singleton') {
// 单例下,每个应用只允许一个实例存在
let indicators = this.indicators.filter((indicator: IndicatorProxy) => {
return indicator.match(data.appName, data.indicatorName);
});
if (indicators.lengt... | reply, client) {
| identifier_name |
EndPoint.ts | import {IEndPoint, IIndicator} from '../domain';
import {MetricsMessengerServer} from '../util/MessengerUtil';
import {IndicatorProxy} from '../indicator/IndicatorProxy';
import {IndicatorResult} from '../indicator/IndicatorResult';
const util = require('util');
const assert = require('assert');
export class EndPoint... | }
setLogger(logger) {
this.logger = logger;
}
destory(callback?) {
// clean all indicator
for (let indicator of this.indicators) {
indicator.destory();
}
this.messengerServer.close(callback);
}
} | random_line_split | |
EndPoint.ts | import {IEndPoint, IIndicator} from '../domain';
import {MetricsMessengerServer} from '../util/MessengerUtil';
import {IndicatorProxy} from '../indicator/IndicatorProxy';
import {IndicatorResult} from '../indicator/IndicatorResult';
const util = require('util');
const assert = require('assert');
export class EndPoint... | let indicatorProxy = new IndicatorProxy(client);
// 构建指标
indicatorProxy.buildIndicator(data);
this.debug(`Client: register name = ${indicatorProxy.name}(${indicatorProxy.clientId})`);
// 连接断开后需要清理
indicatorProxy.bindRemove(this.removeClient.bind(this));
this.indicators.push(indicatorProxy);
... | data.group) {
// 不匹配则忽略
return;
}
if (data.type === 'singleton') {
// 单例下,每个应用只允许一个实例存在
let indicators = this.indicators.filter((indicator: IndicatorProxy) => {
return indicator.match(data.appName, data.indicatorName);
});
if (indicators.length) {
this.debu... | identifier_body |
conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ObservationTools documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 30 14:32:48 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... | # import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# exte... | # documentation root, use os.path.abspath to make it absolute, like shown here.
# | random_line_split |
Math.py | """
Provides mathematical functions
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass-spectrometry data #
# Copyright (C) 2005-2012 Vladimir Lik... | (v):
"""
@summary: Calculates the mean
@param v: A list or array
@type v: ListType, TupleType, or numpy.core.ndarray
@return: Mean
@rtype: FloatType
@author: Vladimir Likic
"""
if not is_list(v):
error("argument neither list nor array")
s = 0.0
for e in v:
... | mean | identifier_name |
Math.py | """
Provides mathematical functions
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass-spectrometry data #
# Copyright (C) 2005-2012 Vladimir Lik... | @param v: A list or array
@type v: ListType, TupleType, or numpy.core.ndarray
@return: Tuple (maxi, maxv), where maxv is the minimum
element in the list and maxi is its index
@rtype: TupleType
@author: Vladimir Likic
"""
if not is_list(v):
error("argument neither list nor... | random_line_split | |
Math.py | """
Provides mathematical functions
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass-spectrometry data #
# Copyright (C) 2005-2012 Vladimir Lik... | K = N/2 - 1
median = (local_data[K] + local_data[K+1])/2.0
else:
# odd number of points
K = (N - 1)/2 - 1
median = local_data[K+1]
return median
def vector_by_step(vstart,vstop,vstep):
"""
@summary: generates a list by using start, stop, and step values
@pa... | """
@summary: Returns a median of a list or numpy array
@param v: Input list or array
@type v: ListType or numpy.core.ndarray
@return: The median of the input list
@rtype: FloatType
@author: Vladimir Likic
"""
if not is_list(v):
error("argument neither list nor array")
lo... | identifier_body |
Math.py | """
Provides mathematical functions
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass-spectrometry data #
# Copyright (C) 2005-2012 Vladimir Lik... |
m = median(v)
m_list = []
for xi in v:
d = math.fabs(xi - m)
m_list.append(d)
mad = median(m_list)/0.6745
return mad
def amin(v):
"""
@summary: Finds the minimum element in a list or array
@param v: A list or array
@type v: ListType, TupleType, or numpy.core.n... | error("argument neither list nor array") | conditional_block |
Keyboard.js | /**
* @class Keyboard
* @classdesc Mixin which manages the keydown handling for a component
*
* TODO: Document collective behavior.
* TODO: Provide baseline behavior outside of a collective.
*/
export default (base) => class Keyboard extends base {
// Default keydown handler. This will typically be handled by... | () {
if (super.collectiveChanged) { super.collectiveChanged(); }
if (this.collective.outermostElement !== this) {
// We're no longer the outermost element; stop listening.
if (isListeningToKeydown(this)) {
stopListeningToKeydown(this);
}
return;
}
if (!this.getAttribute... | collectiveChanged | identifier_name |
Keyboard.js | /**
* @class Keyboard
* @classdesc Mixin which manages the keydown handling for a component
*
* TODO: Document collective behavior.
* TODO: Provide baseline behavior outside of a collective.
*/
export default (base) => class Keyboard extends base {
// Default keydown handler. This will typically be handled by... | element.removeEventListener('keydown', element._keydownListener);
element._keydownListener = null;
element.removeAttribute('tabindex');
} | }
}
function stopListeningToKeydown(element) { | random_line_split |
Keyboard.js | /**
* @class Keyboard
* @classdesc Mixin which manages the keydown handling for a component
*
* TODO: Document collective behavior.
* TODO: Provide baseline behavior outside of a collective.
*/
export default (base) => class Keyboard extends base {
// Default keydown handler. This will typically be handled by... |
if (handled) {
event.preventDefault();
event.stopPropagation();
}
}
// Return the first ARIA label defined by the collective.
function getCollectiveAriaLabel(collective) {
let labels = collective.elements.map(element => element.getAttribute('aria-label'));
// Would prefer to use Array.prototype.find... | {
let element = elements[i];
handled = element.keydown && element.keydown(event);
if (handled) {
break;
}
} | conditional_block |
Keyboard.js | /**
* @class Keyboard
* @classdesc Mixin which manages the keydown handling for a component
*
* TODO: Document collective behavior.
* TODO: Provide baseline behavior outside of a collective.
*/
export default (base) => class Keyboard extends base {
// Default keydown handler. This will typically be handled by... |
function isListeningToKeydown(element) {
return element._keydownListener != null;
}
function startListeningToKeydown(element) {
element._keydownListener = keydown.bind(element);
element.addEventListener('keydown', element._keydownListener);
// Set a default tab index of 0 (document order) if no tab index e... | {
let labels = collective.elements.map(element => element.getAttribute('aria-label'));
// Would prefer to use Array.prototype.find here, but IE 11 doesn't have it.
let nonNullLabels = labels.filter(label => label != null);
return nonNullLabels[0];
} | identifier_body |
object-editor.tsx | import * as React from 'react'
import * as common from 'schema-based-json-editor'
import { Editor } from './editor'
import { Icon } from './icon'
import { Optional } from './optional'
import { Description } from './description'
/**
* @public
*/
export type Props = common.Props<common.ObjectSchema, { [name: string]: ... | this.properties = this.properties.sort(common.compare)
}
}
componentDidMount() {
this.props.updateValue(this.value, this.invalidProperties.length === 0)
}
render() {
const childrenElement: JSX.Element[] = (!this.collapsed && this.value !== undefined)
? this.properties.filter(p => common... | {
super(props)
this.value = common.getDefaultValue(this.props.required, this.props.schema, this.props.initialValue) as { [name: string]: common.ValueType }
this.validate()
if (this.value !== undefined) {
for (const property in this.props.schema.properties) {
if (this.props.schema.propertie... | identifier_body |
object-editor.tsx | import * as React from 'react'
import * as common from 'schema-based-json-editor'
import { Editor } from './editor'
import { Icon } from './icon'
import { Optional } from './optional'
import { Description } from './description'
/**
* @public
*/
export type Props = common.Props<common.ObjectSchema, { [name: string]: ... | placeholder={this.props.locale.info.search}
defaultValue={this.filter} /></div>
: null
return (
<div className={this.className}>
<h3>
{this.titleToShow}
<div className={this.props.theme.buttonGroup} style={common.buttonGroupStyle}>
<Optional requi... | monacoEditor={this.props.monacoEditor} />)
: []
const filterElement: JSX.Element | null = (!this.collapsed && this.value !== undefined && this.showFilter)
? <div className={this.props.theme.row}><input className={this.props.theme.input}
onChange={this.onFilterChange} | random_line_split |
object-editor.tsx | import * as React from 'react'
import * as common from 'schema-based-json-editor'
import { Editor } from './editor'
import { Icon } from './icon'
import { Optional } from './optional'
import { Description } from './description'
/**
* @public
*/
export type Props = common.Props<common.ObjectSchema, { [name: string]: ... | (props: Props) {
super(props)
this.value = common.getDefaultValue(this.props.required, this.props.schema, this.props.initialValue) as { [name: string]: common.ValueType }
this.validate()
if (this.value !== undefined) {
for (const property in this.props.schema.properties) {
if (this.props.s... | constructor | identifier_name |
object-editor.tsx | import * as React from 'react'
import * as common from 'schema-based-json-editor'
import { Editor } from './editor'
import { Icon } from './icon'
import { Optional } from './optional'
import { Description } from './description'
/**
* @public
*/
export type Props = common.Props<common.ObjectSchema, { [name: string]: ... |
}
this.validate()
this.setState({ value: this.value })
common.recordInvalidPropertiesOfObject(this.invalidProperties, isValid, property)
this.props.updateValue(this.value, !this.errorMessage && this.invalidProperties.length === 0)
}
private isRequired(property: string) {
return common.isReq... | {
this.value![p] = undefined
} | conditional_block |
render.js | /*global document*/
//dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import mountedComponents from './mounted-components';
import clearComponent from './clear';
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A... | );
//Save the fact that a component is mounted.
mountedComponents[selector] = mountedComponent;
console.info('Mounted components : ', Object.keys(mountedComponents));
return mountedComponent;
} | const mountedComponent = ReactDOM.render(
React.createElement(component, options.props, options.data),
targetDOMContainer | random_line_split |
render.js | /*global document*/
//dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import mountedComponents from './mounted-components';
import clearComponent from './clear';
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A... |
// Render the component
const mountedComponent = ReactDOM.render(
React.createElement(component, options.props, options.data),
targetDOMContainer
);
//Save the fact that a component is mounted.
mountedComponents[selector] = mountedComponent;
console.info('Mounted components : ',... | {
throw new Error(`You are trying to render a component in a DOM element which is not existing, your selector is ${selector}`);
} | conditional_block |
render.js | /*global document*/
//dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import mountedComponents from './mounted-components';
import clearComponent from './clear';
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A... | {
options = options || {};
// Clear a potential previously mounted component
clearComponent(selector);
const targetDOMContainer = document.querySelector(selector);
if (!targetDOMContainer) {
throw new Error(`You are trying to render a component in a DOM element which is not existing, your se... | identifier_body | |
render.js | /*global document*/
//dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import mountedComponents from './mounted-components';
import clearComponent from './clear';
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A... | (component, selector, options) {
options = options || {};
// Clear a potential previously mounted component
clearComponent(selector);
const targetDOMContainer = document.querySelector(selector);
if (!targetDOMContainer) {
throw new Error(`You are trying to render a component in a DOM element... | renderComponent | identifier_name |
selection.py | from maya import OpenMaya
__all__ = [
"getSoftSelection"
]
def getSoftSelection():
| activeList = OpenMaya.MSelectionList()
richList = OpenMaya.MSelectionList()
softSelection = OpenMaya.MRichSelection()
# get active selection
OpenMaya.MGlobal.getActiveSelectionList(activeList)
# get rich selection
try:
OpenMaya.MGlobal.getRichSelection(softSelection, False)
... | """
Query the soft selection in the scene. If no soft selection is made empty
lists will be returned. The active selection will be returned for easy
reselection. The data structure of the soft selection weight is as
followed.
data = {
mesh:{
{index:weight},
{index:we... | identifier_body |
selection.py | from maya import OpenMaya
__all__ = [
"getSoftSelection"
]
def | ():
"""
Query the soft selection in the scene. If no soft selection is made empty
lists will be returned. The active selection will be returned for easy
reselection. The data structure of the soft selection weight is as
followed.
data = {
mesh:{
{index:weight},
{... | getSoftSelection | identifier_name |
selection.py | from maya import OpenMaya
__all__ = [
"getSoftSelection"
]
def getSoftSelection():
"""
Query the soft selection in the scene. If no soft selection is made empty
lists will be returned. The active selection will be returned for easy
reselection. The data structure of the soft selection weight is ... |
:return: Active selection list for re-selection and weight data.
:rtype: tuple(OpenMaya.MSelectionList, dict)
"""
# variables
data = {}
activeList = OpenMaya.MSelectionList()
richList = OpenMaya.MSelectionList()
softSelection = OpenMaya.MRichSelection()
# get active selection
... | random_line_split | |
selection.py | from maya import OpenMaya
__all__ = [
"getSoftSelection"
]
def getSoftSelection():
"""
Query the soft selection in the scene. If no soft selection is made empty
lists will be returned. The active selection will be returned for easy
reselection. The data structure of the soft selection weight is ... | weight = components.weight(i).influence()
data[path][index] = weight
selIter.next()
return activeList, data
| dep = OpenMaya.MObject()
obj = OpenMaya.MObject()
dag = OpenMaya.MDagPath()
selIter.getDependNode(dep)
selIter.getDagPath(dag, obj)
# add path
path = dag.fullPathName()
if path not in data.keys():
data[path] = {}
# check is selection type is... | conditional_block |
actionscript.py | AliasType', 'ApplicationDomain', 'AsBroadcaster', 'Array',
'AsyncErrorEvent', 'AVM1Movie', 'BevelFilter', 'Bitmap', 'BitmapData',
'BitmapDataChannel', 'BitmapFilter', 'BitmapFilterQuality', 'BitmapFilterType',
'BlendMode', 'BlurFilter', 'Boolean', 'ByteArray', 'Camera', '... | return 0.3 | conditional_block | |
actionscript.py | /\n])*/[gim]*', String.Regex),
(r'[~^*!%&<>|+=:;,/?\\-]+', Operator),
(r'[{}\[\]();.]+', Punctuation),
(words((
'case', 'default', 'for', 'each', 'in', 'while', 'do', 'break',
'return', 'continue', 'if', 'else', 'throw', 'try', 'catch',
... | (RegexLexer):
"""
For ActionScript 3 source code.
.. versionadded:: 0.11
"""
name = 'ActionScript 3'
aliases = ['as3', 'actionscript3']
filenames = ['*.as']
mimetypes = ['application/x-actionscript3', 'text/x-actionscript3',
'text/actionscript3']
identifier = r'[$... | ActionScript3Lexer | identifier_name |
actionscript.py | /\n])*/[gim]*', String.Regex),
(r'[~^*!%&<>|+=:;,/?\\-]+', Operator),
(r'[{}\[\]();.]+', Punctuation),
(words((
'case', 'default', 'for', 'each', 'in', 'while', 'do', 'break',
'return', 'continue', 'if', 'else', 'throw', 'try', 'catch',
... | bygroups(Keyword.Declaration, Name.Function, Text, Operator),
'funcparams'),
(r'(var|const)(\s+)(' + identifier + r')(\s*)(:)(\s*)(' +
typeidentifier + r')',
bygroups(Keyword.Declaration, Text, Name, Text, Punctuation, Text,
Keyword.T... | """
For ActionScript 3 source code.
.. versionadded:: 0.11
"""
name = 'ActionScript 3'
aliases = ['as3', 'actionscript3']
filenames = ['*.as']
mimetypes = ['application/x-actionscript3', 'text/x-actionscript3',
'text/actionscript3']
identifier = r'[$a-zA-Z_]\w*'
t... | identifier_body |
actionscript.py | /\n])*/[gim]*', String.Regex),
(r'[~^*!%&<>|+=:;,/?\\-]+', Operator),
(r'[{}\[\]();.]+', Punctuation),
(words((
'case', 'default', 'for', 'each', 'in', 'while', 'do', 'break',
'return', 'continue', 'if', 'else', 'throw', 'try', 'catch',
... | 'SoundLoaderContext', 'SoundMixer', 'SoundTransform', 'SpreadMethod', 'Sprite',
'StackFrame', 'StackOverflowError', 'Stage', 'StageAlign', 'StageDisplayState',
'StageQuality', 'StageScaleMode', 'StaticText', 'StatusEvent', 'String', 'StyleSheet',
'SWFVersi... | 'Scene', 'ScriptTimeoutError', 'Security', 'SecurityDomain', 'SecurityError',
'SecurityErrorEvent', 'SecurityPanel', 'Selection', 'Shape', 'SharedObject',
'SharedObjectFlushStatus', 'SimpleButton', 'Socket', 'Sound', 'SoundChannel', | random_line_split |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::unam... | code, errno)));
}
Ok(Uname { sys_name: CStr::from_ptr(utsname.sysname.as_ptr()).to_string_lossy()
.into_owned(),
node_name: CStr::from_ptr(utsname.nodename.as_ptr()).to_string_lossy()
... | let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
{}", | random_line_split |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn | () -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::uname(utsname.as_mut_ptr());
let utsname = utsname.assume_init();
if rv < 0 {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
... | uname_libc | identifier_name |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> |
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::uname(utsname.as_mut_ptr());
let utsname = utsname.assume_init();
if rv < 0 {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} ... | { unsafe { uname_libc() } } | identifier_body |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::unam... |
Ok(Uname { sys_name: CStr::from_ptr(utsname.sysname.as_ptr()).to_string_lossy()
.into_owned(),
node_name: CStr::from_ptr(utsname.nodename.as_ptr()).to_string_lossy()
... | {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
{}",
code, errno)));
} | conditional_block |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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
// option. This file may not be copied, modified, or distributed
// except accordin... |
}
pub fn is_match(&self, s: &str) -> bool {
// TODO: for the forward-backward engine, this could be faster because we don't need
// to run backward.
self.find(s).is_some()
}
}
| {
None
} | conditional_block |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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
// option. This file may not be copied, modified, or distributed
// except accordin... | Regex::new_bounded(re, std::usize::MAX)
}
/// Creates a new `Regex` from a regular expression string, but only if it doesn't require too
/// many states.
pub fn new_bounded(re: &str, max_states: usize) -> ::Result<Regex> {
let nfa = try!(Nfa::from_regex(re));
let nfa = nfa.remov... | pub fn new(re: &str) -> ::Result<Regex> { | random_line_split |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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
// option. This file may not be copied, modified, or distributed
// except accordin... |
}
| {
// TODO: for the forward-backward engine, this could be faster because we don't need
// to run backward.
self.find(s).is_some()
} | identifier_body |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// 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
// option. This file may not be copied, modified, or distributed
// except accordin... | (nfa: Nfa<u32, NoLooks>, max_states: usize)
-> ::Result<ForwardBackwardEngine<u8>> {
if nfa.is_anchored() {
return Err(Error::InvalidEngine("anchors rule out the forward-backward engine"));
}
let f_nfa = try!(try!(nfa.clone().byte_me(max_states)).anchor(max_states));
let... | make_forward_backward | identifier_name |
models.py | """
42. Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored. | import random
import tempfile
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
temp_storage_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location)
class Storage(models.Model):
def custom_up... | """
| random_line_split |
models.py | """
42. Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage imp... | def custom_upload_to(self, filename):
return 'foo'
def random_upload_to(self, filename):
# This returns a different result each time,
# to make sure it only gets called once.
return '%s/%s' % (random.randint(100, 999), filename)
normal = models.FileField(storage=temp_storage, u... | identifier_body | |
models.py | """
42. Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage imp... | (self, filename):
return 'foo'
def random_upload_to(self, filename):
# This returns a different result each time,
# to make sure it only gets called once.
return '%s/%s' % (random.randint(100, 999), filename)
normal = models.FileField(storage=temp_storage, upload_to='tests')
... | custom_upload_to | identifier_name |
router.js | var l_cache = SR.State.get('cache');
// language setting
var l_lang = require('./language')('english');
SR.Callback.onStart(function () {
});
var l_form = SR.State.get('FlexFormMap');
var l_accounts;
SR.Callback.onStart(function () {
l_form = SR.State.get('FlexFormMap');
l_accounts = SR.State.get('_accountMap')... | {
"path": "https://www.google.com/",
"meta": {
"title": "External Link",
"icon": "link"
}
}
]
}
];
res.send(menu);
});
}; | },
{
"path": "external-link",
"children": [ | random_line_split |
router.js |
var l_cache = SR.State.get('cache');
// language setting
var l_lang = require('./language')('english');
SR.Callback.onStart(function () {
});
var l_form = SR.State.get('FlexFormMap');
var l_accounts;
SR.Callback.onStart(function () {
l_form = SR.State.get('FlexFormMap');
l_accounts = SR.State.get('_accountMap'... |
LOG.warn('user not yet logined...');
return {control: {groups: [], permissions: []}};
};
module.exports = function (app) {
// CORS header
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Ac... | {
var login = session._user;
login.admin = (session._user.account === 'admin');
return login;
} | conditional_block |
SetRasterStyle.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
SetRasterStyle.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... |
def displayName(self):
return self.tr('Set style for raster layer')
def processAlgorithm(self, parameters, context, feedback):
layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
style = self.parameterAsFile(parameters, self.STYLE, context)
with open(style) as ... | self.tr('Style file'), extension='qml'))
self.addOutput(QgsProcessingOutputRasterLayer(self.INPUT, self.tr('Styled')))
def name(self):
return 'setstyleforrasterlayer' | random_line_split |
SetRasterStyle.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
SetRasterStyle.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... |
def groupId(self):
return 'rastertools'
def __init__(self):
super().__init__()
def flags(self):
return super().flags() | QgsProcessingAlgorithm.FlagNoThreading | QgsProcessingAlgorithm.FlagDeprecated
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessi... | return self.tr('Raster tools') | identifier_body |
SetRasterStyle.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
SetRasterStyle.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | (self):
return self.tr('Set style for raster layer')
def processAlgorithm(self, parameters, context, feedback):
layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
style = self.parameterAsFile(parameters, self.STYLE, context)
with open(style) as f:
xml =... | displayName | identifier_name |
test_overcloud_roles.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... |
@mock.patch('tuskar.db.sqlalchemy.api.Connection.create_overcloud_role')
def test_post(self, mock_db_create):
# Setup
create_me = {'name': 'new'}
fake_created = db_models.OvercloudRole(name='created')
mock_db_create.return_value = fake_created
# Test
response ... | fake_result = db_models.OvercloudRole(name='foo')
mock_db_get.return_value = fake_result
# Test
url = URL_ROLES + '/' + '12345'
response = self.app.get(url)
result = response.json
# Verify
self.assertEqual(response.status_int, 200)
self.assertEqual(resul... | identifier_body |
test_overcloud_roles.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | # Setup
fake_results = [db_models.OvercloudRole(name='foo')]
mock_db_get.return_value = fake_results
# Test
response = self.app.get(URL_ROLES)
result = response.json
# Verify
self.assertEqual(response.status_int, 200)
self.assertTrue(isinstance(r... |
@mock.patch('tuskar.db.sqlalchemy.api.Connection.get_overcloud_roles')
def test_get_all(self, mock_db_get): | random_line_split |
test_overcloud_roles.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | (self):
super(OvercloudRolesTests, self).setUp()
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'..', '..', '..', '..', 'api', 'config.py')
self.app = load_test_app(config_file)
@mock.patch('tuskar.db.sqlalchemy.api.Connection.get_... | setUp | identifier_name |
chip.rs | use common::{RingBuffer,Queue};
use ast;
//use adc;
use dma;
use nvic;
use usart;
use spi;
use gpio;
pub struct Sam4l;
const IQ_SIZE: usize = 100;
static mut IQ_BUF : [nvic::NvicIdx; IQ_SIZE] =
[nvic::NvicIdx::HFLASHC; IQ_SIZE];
pub static mut INTERRUPT_QUEUE : Option<RingBuffer<'static, nvic::NvicIdx>> = None;
... |
GPIO0 => gpio::PA.handle_interrupt(),
GPIO1 => gpio::PA.handle_interrupt(),
GPIO2 => gpio::PA.handle_interrupt(),
GPIO3 => gpio::PA.handle_interrupt(),
GPIO4 => gpio::PB.handle_interrupt(),
GPIO5 => gpio::PB.handle_interrup... | random_line_split | |
chip.rs | use common::{RingBuffer,Queue};
use ast;
//use adc;
use dma;
use nvic;
use usart;
use spi;
use gpio;
pub struct | ;
const IQ_SIZE: usize = 100;
static mut IQ_BUF : [nvic::NvicIdx; IQ_SIZE] =
[nvic::NvicIdx::HFLASHC; IQ_SIZE];
pub static mut INTERRUPT_QUEUE : Option<RingBuffer<'static, nvic::NvicIdx>> = None;
impl Sam4l {
#[inline(never)]
pub unsafe fn new() -> Sam4l {
INTERRUPT_QUEUE = Some(RingBuffer::new(&... | Sam4l | identifier_name |
moodle_grading_worksheet.py | #!/usr/bin/env python3
# Basic program to read csv file and spit it back out
import argparse
import csv
import sys
def read_worksheet(csv_file):
"""
Read contents of worksheet_csv and return (contents, dialect, fields)
"""
contents = {}
dialect = None
fields = None
with open(csv_file,... | contents, dialect, fields = read_worksheet(input_csv)
# Mutate Contents
for val in contents.values():
val['Grade'] = '99.9'
# Write Output
write_worksheet(output_csv, contents, dialect, fields)
if __name__ == "__main__":
sys.exit(_main())
| """
Module Grading Worksheet Module Unit Tests
"""
argv = argv or sys.argv[1:]
# Setup Argument Parsing
parser = argparse.ArgumentParser(description='Test Process Moodle Grading Worksheet')
parser.add_argument('input_csv', type=str,
help='Input Grading Worksheet CSV Fil... | identifier_body |
moodle_grading_worksheet.py | #!/usr/bin/env python3
# Basic program to read csv file and spit it back out
import argparse
import csv
import sys
def | (csv_file):
"""
Read contents of worksheet_csv and return (contents, dialect, fields)
"""
contents = {}
dialect = None
fields = None
with open(csv_file, 'r', newline='') as worksheet:
dialect = csv.Sniffer().sniff(worksheet.read())
worksheet.seek(0)
header = csv.S... | read_worksheet | identifier_name |
moodle_grading_worksheet.py | #!/usr/bin/env python3
# Basic program to read csv file and spit it back out
import argparse
import csv
import sys
def read_worksheet(csv_file):
"""
Read contents of worksheet_csv and return (contents, dialect, fields)
"""
contents = {}
dialect = None
fields = None
with open(csv_file,... |
# Write Output
write_worksheet(output_csv, contents, dialect, fields)
if __name__ == "__main__":
sys.exit(_main())
| val['Grade'] = '99.9' | conditional_block |
moodle_grading_worksheet.py | #!/usr/bin/env python3
# Basic program to read csv file and spit it back out
import argparse
import csv
import sys
def read_worksheet(csv_file):
"""
Read contents of worksheet_csv and return (contents, dialect, fields)
"""
contents = {}
dialect = None
fields = None
with open(csv_file,... |
"""
with open(csv_file, 'w', newline='') as worksheet:
writer = csv.DictWriter(worksheet, fields, dialect=dialect)
writer.writeheader()
for val in contents.values():
writer.writerow(val)
return None
def _main(argv=None):
"""
Module Grading Worksheet Module U... |
def write_worksheet(csv_file, contents, dialect, fields):
"""
Write contents to worksheet_csv using dialect and fields | random_line_split |
IdentifiedObject.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
def setNames(self, value):
for x in self._Names:
x.IdentifiedObject = None
for y in value:
y._IdentifiedObject = self
self._Names = value
Names = property(getNames, setNames)
def addNames(self, *Names):
for obj in Names:
obj.IdentifiedO... | """All names of this identified object.
"""
return self._Names | identifier_body |
IdentifiedObject.py | # deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notic... | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to | random_line_split | |
IdentifiedObject.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | (Element):
"""This is a root class to provide common identification for all classes needing identification and naming attributes
"""
def __init__(self, name='', aliasName='', Names=None, *args, **kw_args):
"""Initialises a new 'IdentifiedObject' instance.
@param name: The name is any free ... | IdentifiedObject | identifier_name |
IdentifiedObject.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | obj.IdentifiedObject = None | conditional_block | |
detail-quick.js | /************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com | * (at your option) any later version.
*
* EspoCRM 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 Public License for more details.
*
* You should have received a copy... | *
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or | random_line_split |
system_info.py | # -*- coding:utf-8 -*-
# @author xupingmao <578749341@qq.com>
# @since 2020/08/22 21:54:56
# @modified 2022/02/26 10:40:22
import xauth
import xtemplate
import xutils
import os
import re
import sys
import platform
import xconfig
from xutils import dateutil
from xutils import fsutil
from xutils import Storage
from xutil... | def __init__(self, name = "", value = ""):
self.name = name
self.value = value
class InfoHandler:
@xauth.login_required("admin")
def GET(self):
items = [
SystemInfoItem("Python版本", value = get_python_version()),
SystemInfoItem("Xnote版本", value = get_xnote_ve... | emInfoItem:
| identifier_name |
system_info.py | # -*- coding:utf-8 -*-
# @author xupingmao <578749341@qq.com>
# @since 2020/08/22 21:54:56
# @modified 2022/02/26 10:40:22
import xauth
import xtemplate
import xutils
import os
import re
import sys
import platform
import xconfig
from xutils import dateutil
from xutils import fsutil
from xutils import Storage
from xutil... |
def get_python_version():
return sys.version
def get_startup_time():
return dateutil.format_time(xconfig.START_TIME)
def get_free_data_space():
try:
size = fsutil.get_free_space(xconfig.get_system_dir("data"))
return xutils.format_size(size)
except:
xutils.print_exc()
... | mem_used = 0
mem_total = 0
result = mem_util.get_mem_info()
mem_used = result.mem_used
sys_mem_used = result.sys_mem_used
sys_mem_total = result.sys_mem_total
return "%s/%s/%s" % (mem_used, sys_mem_used, sys_mem_total) | identifier_body |
system_info.py | # -*- coding:utf-8 -*-
# @author xupingmao <578749341@qq.com>
# @since 2020/08/22 21:54:56
# @modified 2022/02/26 10:40:22
import xauth
import xtemplate
import xutils
import os
import re
import sys
import platform
import xconfig
from xutils import dateutil
from xutils import fsutil
from xutils import Storage
from xutil... | def get_xnote_version():
return xconfig.get_global_config("system.version")
def get_mem_info():
mem_used = 0
mem_total = 0
result = mem_util.get_mem_info()
mem_used = result.mem_used
sys_mem_used = result.sys_mem_used
sys_mem_total = result.sys_mem_total
return "%s/%s/%s" % (mem_used,... | sqlite3 = None
| random_line_split |
StreamWatcher.py | from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class | (object):
def __init__( self ):
if _best_backend is None:
raise Exception( "No poll/queue backend could be found for your OS." )
self.backend = _best_backend( )
self.fd_map = {}
self.stream_map = {}
def watch( self, fd, data=None, read=True, write=False ):
# allow python file-like objects that have a b... | StreamWatcher | identifier_name |
StreamWatcher.py | from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class StreamWatcher(object):
def __init__( self ):
if _best_backend is None:
raise Exception( "No poll/queue backend could be found for your OS." )
self.backe... |
_best_backend = None
try:
from select import kqueue, kevent
except ImportError:
pass
else:
class KQueueBackend(object):
def __init__( self ):
self.kq = kqueue( )
def watch_read( self, fd ):
event = kevent( fd, filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD )
self._add_events( [event] )
def w... | max_events=max_events,
fd_data_map=self.fd_map,
fd_stream_map=self.stream_map ) | random_line_split |
StreamWatcher.py | from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class StreamWatcher(object):
def __init__( self ):
if _best_backend is None:
raise Exception( "No poll/queue backend could be found for your OS." )
self.backe... | if fd in fd_data_map:
buf = array.array( 'i', [0] )
ioctl( fd, termios.FIONREAD, buf, 1 )
stream = fd_stream_map.get( fd, None )
data = fd_data_map.get( fd, None )
num_bytes = buf[0]
eof = ( event & (select.EPOLLHUP | select.EPOLLERR) != 0 )
if event & select.EPO... | def __init__( self ):
self.ep = epoll( )
def watch_read( self, fd ):
self.ep.register( fd, select.EPOLLIN )
def watch_write( self, fd ):
self.ep.register( fd, select.EPOLLOUT )
def wait( self, timeout=None, max_events=None, fd_data_map={}, fd_stream_map={} ):
if max_events is None:
max_events... | identifier_body |
StreamWatcher.py | from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class StreamWatcher(object):
def __init__( self ):
if _best_backend is None:
|
self.backend = _best_backend( )
self.fd_map = {}
self.stream_map = {}
def watch( self, fd, data=None, read=True, write=False ):
# allow python file-like objects that have a backing fd
if hasattr(fd, 'fileno') and callable(fd.fileno):
stream = fd
fd = stream.fileno()
self.stream_map[fd] = stream
... | raise Exception( "No poll/queue backend could be found for your OS." ) | conditional_block |
serve-static.d.ts | // Type definitions for serve-static 1.7.1
// Project: https://github.com/expressjs/serve-static
// Definitions by: Uros Smolnik <https://github.com/urossmolnik/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/* =================== USAGE ===================
import * as serveStatic from "serve-sta... | var mime: typeof m;
}
export = serveStatic;
} | import * as m from "mime";
module serveStatic { | random_line_split |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import platform
if platform.system() == 'Windows':
from compat import *
from puke.Error import *
from puke.Task import *
from puke.Tools import *
from puke.ToolsExec import *
from puke.FileList import *
from puke.Sed import *
from puke.Console import *
from puke.E... |
if options.info:
printHelp(name.strip())
else:
executeTask(name.strip(), *args)
def gettraceback(level = 0):
trace = ""
exception = ""
exc_list = traceback.format_exception_only (sys.exc_type, sys.exc_value)
reverse = -1 - level
for entry in exc_list:
... | sys.exit(1)
else:
name = args.pop(0) | random_line_split |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import platform
if platform.system() == 'Windows':
from compat import *
from puke.Error import *
from puke.Task import *
from puke.Tools import *
from puke.ToolsExec import *
from puke.FileList import *
from puke.Sed import *
from puke.Console import *
from puke.E... | try:
run()
except Exception as error:
console.fail("\n\n :puke: \n PUKE %s \n %s \n" % (error, gettraceback()))
sys.exit(1)
except KeyboardInterrupt:
console.warn("\n\n :puke: \nBuild interrupted!\n")
sys.exit(2)
if Console.SPEAK_ENABLED and Console.SPEAK_MESSAGE... | identifier_body | |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import platform
if platform.system() == 'Windows':
from compat import *
from puke.Error import *
from puke.Task import *
from puke.Tools import *
from puke.ToolsExec import *
from puke.FileList import *
from puke.Sed import *
from puke.Console import *
from puke.E... |
else:
name = args.pop(0)
if options.info:
printHelp(name.strip())
else:
executeTask(name.strip(), *args)
def gettraceback(level = 0):
trace = ""
exception = ""
exc_list = traceback.format_exception_only (sys.exc_type, sys.exc_value)
reverse = -1... | if hasDefault():
executeTask('default')
else:
logging.error("No tasks to execute. Please choose from: ")
printTasks()
sys.exit(1) | conditional_block |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import platform
if platform.system() == 'Windows':
from compat import *
from puke.Error import *
from puke.Task import *
from puke.Tools import *
from puke.ToolsExec import *
from puke.FileList import *
from puke.Sed import *
from puke.Console import *
from puke.E... | ():
try:
run()
except Exception as error:
console.fail("\n\n :puke: \n PUKE %s \n %s \n" % (error, gettraceback()))
sys.exit(1)
except KeyboardInterrupt:
console.warn("\n\n :puke: \nBuild interrupted!\n")
sys.exit(2)
if Console.SPEAK_ENABLED and Console.SPEAK... | main | identifier_name |
eventtrans.py | #Author velociraptor Genjix <aphidia@hotmail.com>
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
|
pressTransition = QEventTransition(button, QEvent.MouseButtonPress)
pressTransition.setTargetState(s3)
s2.addTransition(pressTransition)
releaseTransition = QEventTransition(button, QEvent.MouseButtonRelease)
releaseTransition.setTargetState(s2)
s3.addTransition(release... | super(MainWindow, self).__init__()
button = QPushButton(self)
button.setGeometry(QRect(100, 100, 100, 100))
machine = QStateMachine(self)
s1 = QState()
s1.assignProperty(button, 'text', 'Outside')
s2 = QState()
s2.assignProperty(button, 'text', 'Inside')
... | identifier_body |
eventtrans.py | #Author velociraptor Genjix <aphidia@hotmail.com>
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
button = QPushButton(self)
button.setGeometry(QRect(100, 100, 100, 100))
machine = QStateM... | import sys
app = QApplication(sys.argv)
mainWin = MainWindow()
sys.exit(app.exec_()) | conditional_block | |
eventtrans.py | #Author velociraptor Genjix <aphidia@hotmail.com>
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
button = QPushButton(self)
button.setGeometry(QRect(100, 100, 100, 100))
machine = QStateM... | pressTransition = QEventTransition(button, QEvent.MouseButtonPress)
pressTransition.setTargetState(s3)
s2.addTransition(pressTransition)
releaseTransition = QEventTransition(button, QEvent.MouseButtonRelease)
releaseTransition.setTargetState(s2)
s3.addTransition(releaseT... | s3 = QState()
s3.assignProperty(button, 'text', 'Pressing...')
| random_line_split |
eventtrans.py | #Author velociraptor Genjix <aphidia@hotmail.com>
from PySide.QtGui import *
from PySide.QtCore import *
class | (QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
button = QPushButton(self)
button.setGeometry(QRect(100, 100, 100, 100))
machine = QStateMachine(self)
s1 = QState()
s1.assignProperty(button, 'text', 'Outside')
s2 = QState()
s2.as... | MainWindow | identifier_name |
command-handlers.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.status = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done)... |
log('exec => mup setup');
return api.runCommand('docker.setup');
}
function start() {
log('exec => mup start');
}
function stop() {
log('exec => mup stop');
}
function ssh(api) {
var servers = api.getConfig().servers;
var serverOption = api.getArgs()[1];
if (!(serverOption in servers)) {
if (Obj... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.