prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
pass <car
et><selection>n = 0 while n: print("spam")</selecti
on> pass
""" Creates an Azure serverless function. """ from common.methods import set_progress from infrastructure.models import CustomField from common.methods import generate_string_from_template import os, json def create_custom_fields_as_needed(): CustomField.objects.get_or_create( name='azure_function_name', ...
scription': 'Used by the Azure blueprints', 'show_as_attribute': True} ) def run(job, **kwargs): resource = kwargs.get('resource') function_name = '{{ function_name }}' storage_account_name = function_name + "storageaccount" file_location = "{{ file_location }}" if file_location.sta...
file_location.replace(settings.MEDIA_URL, settings.MEDIA_ROOT) create_custom_fields_as_needed() #check if function name is already in use function_name_check = "az functionapp list" val = os.popen(function_name_check).read() function_name_check_response = json.loads(val) used_names = [] f...
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Li
cense, or # (at your option) a
ny later version. # # This program 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 of the GNU General Pub...
ult.gc_thresh1 = 1" self.assertTrue(moduletests.src.arpcache.detect()) self.assertTrue(check_output_mock.called) @mock.patch("subprocess.check_output", side_effect=subprocess.CalledProcessError( "1", "test", "/etc/sysctl.d/55-arp-gc_thresh1.conf: no such file or directory")) def test_fi...
lf.assertTrue(check_output_mock.called) self.assertTrue(exists_mock.called) self.assertTrue(open_mock.called) self.assertTrue(self.output.getvalue().endswith( "[UNFIXED] Failed to write config to /etc/sysctl.d/55-arp-gc_thresh1.conf\n")) @mock.patch("moduletests
.src.arpcache.detect", return_value=False) def test_run_success(self, detect_mock): with contextlib.redirect_stdout(self.output): self.assertTrue(moduletests.src.arpcache.run()) self.assertTrue(self.output.getvalue().endswith("Determining if aggressive ARP caching is enabled\n" ...
from .. import scalar_measures import numpy from numpy.testing import assert_array_almost_equal def test_fractional_anisotropy(N=10, random=numpy.random.RandomState(0)): tensors = random.randn(N, 3, 3) fa = numpy.empty(N) for i, t in enumerate(tensors): tt = numpy.dot(t, t.T) tensors[i] =...
i, t in enumerate(tensors): tt
= numpy.dot(t, t.T) tensors[i] = tt dt[i] = numpy.linalg.det(tt) assert_array_almost_equal(dt, scalar_measures.tensor_det(tensors)) def test_tensor_traces(N=10, random=numpy.random.RandomState(0)): tensors = random.randn(N, 3, 3) res = numpy.empty(N) for i, t in enumerate(tensors): ...
self, type_): return self.visit_SMALLINT(type_) def visit_RAW(self, type_): return "RAW(%(length)s)" % {'length' : type_.length} def visit_ROWID(self, type_): return "ROWID" class OracleCompiler(compiler.SQLCompiler): """Oracle compiler modifies the lexical structure of Select ...
middle select and add the hint limitselect = sql.select([c for c in select.c]) if select._limit and self.dialect.optimize_limits: limitselect = limitselect.prefix_with("/*+ FIRST_ROWS(%d) */" % select._limit) limitselect._oracle_visit = True ...
mitselect._is_wrapper = True # If needed, add the limiting clause if select._limit is not None: max_row = select._limit if select._offset is not None: max_row += select._offset if not self.dialect.use_bi...
import logging import traceback import numpy as np from eemeter.structures import EnergyTrace logger = logging.getLogger(__name__) class SplitModeledEnergyTrace(object): ''' Light wrapper around models applicable to a single trace which fits and predicts multiple models for different segments. Paramet...
_outputs[modeling_period_label] = { "status": "FAILURE", "traceback": traceback.format_exc(), "start_date": None, "end_date": None, "rows": No
ne, } continue else: input_description = self.formatter.describe_input(input_data) outputs = { "start_date": input_description.get('start_date'), "end_date": input_description.get('end_date'), ...
"""For seeding individual ops based on a graph-level seed. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops _DEFAULT_GRAPH_SEED = 87654321 def get_seed(op_seed): """Returns the local seeds an operation sh...
seed. Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets the graph-level seed. Its interactions with operation-level seeds is as follows: 1. If neither the graph-level nor the operation seed is set: A ra
ndom seed is used for this op. 2. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. 3. If the graph-level seed is not set, but the operation seed is se...
de
f address(self, data): self.irc.send(self.privmsg("512 Shaw Court #105, Severn, MD 21144
"))
from django.db.models.fields import related def _is_many_to_many_relation(field): """Check if a field specified a many-to-many relationship as defined by django. This is the case if the field is an instance of the ManyToManyDescriptor as generated by the django framework Args: field (django.d...
= getattr(meta, "model", None) if model is None: return [] fields = [] for field_name in dir(model): field = getattr(mo
del, field_name) if _is_field_prefetchable(field): # ManyToMany relationship can be reverse if hasattr(field, 'reverse') and field.reverse: fields.append((field_name, field.field.model)) else: fields.append((field_name, field.field.related_mode...
# context.predefined_names is filled, we stop. # We don't want to check the if stmt itself, it's just about # the content. if element.start_pos > if_stmt_test.end_pos: # Now we need to check if the names in the if_stmt match the # names in the suit...
return self._eval_element_if_evaluated(context, element) else: if predefined_if_name_dict: return self._eval_element_not_cached(context, element) else: return self._eval_element_if_evaluated(context, e
lement) def _eval_element_if_evaluated(self, context, element): """ TODO This function is temporary: Merge with eval_element. """ parent = element while parent is not None: parent = parent.parent predefined_if_name_dict = context.predefined_names.get(...
in.features: log.error("Feature unknown: '%s'" % sub) sys.exit(1) ## Check output folder if not options["output_folder"]: options["output_folder"] = path.join(os.getcwd(), path.basename(options["input_folder"])) if path.isdir(options["output_folder"])...
n options["feature_values"]: options["feature_values"][plugin.nam
e] = {} results = plugin.calculate(bgc) options["feature_values"][plugin.name]["%d" % (i)] = [float(result) for result in results] count += 1 utils.print_progress(count, len(input_files), prefix='Feature extraction..', suffix='', decimals=1) else: log....
s self.flowId = getNextFlowId() if (q != None): self.flow.append(q) if (operator != None): self.flow.append(operator) #debugLog('lib', 'new HoneDataFlow', self.flow) def __rshift__(self, other): #debugLog('lib', 'In rshift of HoneDa...
stream1.flow.append(operator) return stream1
def Print(f=None): if f: return HoneDataFlow(None, ['Print', f.__name__]) else: return HoneDataFlow(None, ['Print']) def RegisterPolicy(f=None): return HoneDataFlow(None, ['RegisterPolicy
---- DONE *. clip_to_rect is inclusive on lower end and exclusive on upper end. DONE *. clip_to_rect behaves intelligently under scaled ctm. DONE *. clip_to_rect intersects input rect with the existing clipping rect. DONE *. current rectangular clipping path is saved/restored to the stac...
, 2, 2), (0, 0, 4, 4)] self.clip_to_rect_helper(desired, 1, clip_rects) def test_empty_clip_region(self): # Thi
s tests when the clipping region is clipped down to nothing. desired = array([[255, 255, 255, 255], [255, 255, 255, 255], [255, 255, 255, 255], [255, 255, 255, 255]]) clip_rects = [(1,1,4,4), (3,3,1,1), (1,1,1,1)] self.cl...
"""The tests for the Splunk component.""" import unittest from unittest import mock from homeassistant.setup import setup_component import homeassistant.components.splunk as splunk from homeassistant.const import STATE_ON, STATE_OFF, EVENT_STATE_CHANGED from tests.common import get_test_home_assistant class TestSpl...
tp://host:8088/services/collector/event', 'event': body} self.handler_method(event) self.assertEqual(self.mock_post.call_count, 1) self.assertEqual( self.mock_post.call_args, mock.call( payload['host'], data=p...
Authorization': 'Splunk secret'}, timeout=10 ) ) self.mock_post.reset_mock()
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # 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, modi...
str) or isinstance(value, unicode): raise ValueError, 'value must be of type str' if self.allowed_values: choices = self.allowed_values.split(',') if value not in choices: raise ValueError, 'value must be in %s' % self.allowed_values self._value = valu...
value = int(value) if isinstance(value, int) or isinstance(value, long): if self.allowed_values: min, max = self.allowed_values.split('-') if value < int(min) or value > int(max): raise ValueError, 'range is %s' % self.allowed_values ...
intially None. """ global _threadPool, _threadPoolLock _threadPoolLock.acquire() try: oldThreadPool = _threadPool _threadPool = threadPool finally: _threadPoolLock.release() return oldThreadPool def getDefaultThreadPool(): """Get the current default thread pool for new tasks. If no defa...
), startAfter(), lazyStart(), lazyStartAfter() or cancel() has been called on it. """ return self._state is not Task.State.NEW @property def completed(self): """True if this task has finished execution or has been cancelled. """ s = self._state return s is Task.State.SUCCEEDED or s is T...
rue if this task successfully finished execution. """ return self._state is Task.State.SUCCEEDED @property def failed(self): """True if this task failed or was cancelled. """ return self._state is Task.State.FAILED @property def result(self): """If the task has completed succ...
# -*- coding: utf-8 -*- # # web_container.py # # Copyright © 2016-2017 Antergos # # This file is part of whither. # # whither 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...
even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # The following additional terms are in effect as per Section 7 of the license: # # The preservation of all legal notices and author attributions in # the material or in the Appr...
es displayed # by works containing it is required. # # You should have received a copy of the GNU General Public License # along with whither; If not, see <http://www.gnu.org/licenses/>.
# Copyright (c) 2011 X.commerce, a business unit of eBay 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 req...
o in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the Lic
ense. from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import network ALIAS = 'os-floating-ip-pools' authorize = extensions.os_compute_authorizer(ALIAS) def _translate_floating_ip_view(pool_name): return { 'name': pool_name, } def _translate_floating_ip_pool...
, 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url, document_class=OrderedDict) db = mc[str(database_name)] collection = db[str(collection_name)] if return_keys: return_dict = {} for k in return_keys: ...
history_object['historical_id'] = existing_mongo_id['_id'] del history_object['_id'] # print history_object # now write the record to the historical collection written_object = history_collection.insert(history_object) # update the ...
d = collection.save(document) else: # this is new so perform an insert. myobjectid = collection.insert(document) # now fetch the record we just wrote so that we write it back to the # DB. myobject = collection.find_one({'_id': myobjectid}) response_dict[...
import re import csv from urllib import parse import lxml.html from pupa.scrape import Person, Scraper class NoDetails(Exception): pass SESSION_NUMBERS = { '2011': '62nd', '2013': '63rd', '2015': '64th', '2017': '65th', } class MTPersonScraper(Scraper): def url_xpath(self, url): #...
nue # District. district = entry['district'] hd_or_sd, district = district.split()
# Party. party_letter = entry['party'] party = {'D': 'Democratic', 'R': 'Republican'}[party_letter] # Get full name properly capped. fullname = '%s %s' % (entry['first_name'].capitalize(), entry['last_name'].capitalize()) ...
import copy import pytest from peek.line import InvalidIpAddressException, Line, InvalidStatusException # 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python" test_line_contents = { 'ip_address': '127.0.0.1', 'timestamp': '[01/Jan/1970:00:00:01 +0000]', 'verb': 'GET', ...
, test_line.status), (193, test_line.byte_count), ('-', test_line.referrer), ('Python', test_line.user_agent) ]) def test_retrieval(self, expected, actual): assert expected == actual class TestLineExceptions: def test_passing_invalid_ip_address_throws_exception(self): ...
updated_line_contents({'ip_address': 'foobar'})) def test_passing_non_parseable_status_throws_exception(self): with pytest.raises(InvalidStatusException): Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
from flask import request, render_template from flask.ext.login import current_user, login_user from my
site.weibo import Clien
t from mysite import app, db from mysite.models import Wuser, User from . import weibo @weibo.route('/oauthreturn') def oauthreturn(): code = request.args.get('code', '') if code: client = Client(app.config['API_KEY'], app.config['API_SECRET'], app.config['REDIRECT_URI']) client.set_code(code) uid = client.to...
# Copyright 2012 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
ret_fields) return {'services': svcs}
def _is_valid_as_reason(self, reason): if not reason: return False try: utils.check_string_length(reason.strip(), 'Disabled reason', min_length=1, max_length=255) except exception.InvalidInput: return False r...
# Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). # # 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...
License. import sys, os, subprocess, glob script_dir = os.path.dirname(os.path.realpath(__file__)) publisher_command = os.environ.get("SIMPLE_COMMUNICATION_PUBLISHER_BIN") if not publisher
_command: publisher_files = glob.glob(os.path.join(script_dir, "**/SimpleCommunicationPublisher*"), recursive=True) publisher_command = next(iter(publisher_files), None) assert publisher_command subscriber_command = os.environ.get("SIMPLE_COMMUNICATION_SUBSCRIBER_BIN") if not subscriber_command: subscriber_...
ntactList self.groups = [] self.sub = sub self.nickname = "" self.avatar = None self.show = "" self.status = "" self.url = "" self.ptype = "unavailable" def removeMe(self): """ Destroys this object. Does not remove the contact from the server's list. """ self.contactList = None self.avatar = No...
's Jabber list with their legacy list after logon. """ if self.sub == "none": self.sub = "to" elif self.sub == "from": self.sub = "both" else: return self.updateRoster("subscribe") def syncContactRemovedAuth(self): """ Since last using the transport the user has been blocked by this
contact. Call this to synchronise the user's Jabber list with their legacy list after logon. """ if self.sub == "to": self.sub = "none" elif self.sub == "both": self.sub = "from" else: return self.updateRoster("unsubscribed") def syncUserGrantedAuth(self): """ Since last using the transport the...
_server(self, server_id, **kwargs): """Starts a stopped server and changes its status to ACTIVE. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/compute/#start-server-os-start-action """ return ...
return rest_client.ResponseBody(resp, body) def add_security_group(self, server_id, **kwargs): """Add a security group to the server. For a full list of available parameters, plea
se refer to the official API reference: https://developer.openstack.org/api-ref/compute/#add-security-group-to-a-server-addsecuritygroup-action """ return self.action(server_id, 'addSecurityGroup', **kwargs) def remove_security_group(self, server_id, **kwargs): """Remove a s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(
migrations.Migration): dependencies = [ ('article', '0001_initial'), ] operations = [ migrations.AddField( model_name='comments', name='comments_date', field=models.DateTimeField(default=datetime.datetime(2015, 2, 17, 12, 54, 47, 78000, tzinf
o=utc)), preserve_default=False, ), ]
NAME='gif
' GCC_LIST=['gif']
RROR", 4: "WARNING", 5: "NOTICE", 6: "INFORMATIONAL", 7: "DEBUG", } MY_TZ = os.environ.get('CATCHER_TZ', 'NOT_SET') TZ_INFO = pytz.timezone(MY_TZ) if MY_TZ != 'NOT_SET' else None def __init__(self, broker_uri=BROKER_URI, broker_queue=BROKER_QUEUE, hosts...
'_id': sha256(syslog_msg).hexdigest(), '@timestamp': cls.format_timestamp(datetime.now()), '@version': "1", 'message': "transformed syslog", 'path': '', 'tags': [], 'catcher_tz': catcher_tz, '
catcher_host': catcher_host, 'catcher_name': catcher_name } t, msg = cls.split_alert_message(syslog_msg) r['syslog_level'] = cls.calculate_msg_type(syslog_msg) r['syslog_msg'] = msg r['syslog_tag'] = t r['syslog_server'] = cls.resolve_host(syslog_server_...
# -*- coding: utf-'8' "-*-" import base64 import json from hashlib import sha1 import hmac import logging import urlparse from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment_adyen.controllers.main import AdyenController from openerp.osv import osv, fields from opener...
yen: received data for reference %s') % (reference) if not tx_ids: error_msg += _('; no order found') else: error_msg += _('; multiple order found') _logger.info(error_msg) raise ValidationError(error_msg) tx = self.pool['payment.tr...
x.acquirer_id, 'out', data) if shasign_check != data.get('merchantSig'): error_msg = _('Adyen: invalid merchantSig, received %s, computed %s') % (data.get('merchantSig'), shasign_check) _logger.warning(error_msg) raise ValidationError(error_msg) return tx def _a...
import json class JSON_RPCError(Exception): """ Base class for JSON-RPC errors. """ def to_json(self): return json.dumps({ 'code': self.code, 'message': self.__doc__
, }) class ParseError(JSON_RPCError): """ Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. """ code = -32700 class InvalidRequestError(JSON_RPCError): """ The JSON sent is not a valid Request object. """ code = -32600 class Metho...
""" code = -32601 class InvalidParamsError(JSON_RPCError): """ Invalid methods parameter(s). """ code = -32602 class InternalError(JSON_RPCError): """ Internal JSON-RPC error. """ code = -32603
#!/usr/bin/en
v python from distutils.core import setup setup(name='Card-Magic', version='1.0', description='The best card and decks ever', author='Juan Carlos Ferrer', author_email='juan.carlos@micronixsolutions.com', packages=['cardmagic', 'cardmagic.tests'], package_data = { 'cardma...
, )
""" ******************************************************************************** Learn Python the Hard Way Third Edition, by Zed A. Shaw ISBN: 978-0321884916 ******************************************************************************** """ import random from urllib import urlopen import sys #debug ...
hat is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)": "class %%% has-a __init__ that takes self and *** parameters.", "class %%%(object):\n\tdef ***(self,@@@)": "class %%% has-a function named *** that takes self and @@@ parameters.", "*** = %%%()": "Set *** to an instance...
*'": "From *** get the *** attribute and set it to '***'." } # do they want to drill phrases first PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True #print debug + "0" # load up the words from the website #for word in urlopen(WORD_URL).readlines(): # once dow...
from collections import OrderedDict from .. import Provider as CompanyProvider class Provider(CompanyProvider): formats = OrderedDict( ( ("{{company_limited_prefix}}{{last_name}} {{company_limited_suffix}}", 0.2), ( "{{company_limited_prefix}}{{last_name}}{{company...
"จิวเวลรี่", "อะไหล่ยนต์", "ภาพยนตร์", "ยานยนต์", "เทรดดิ้ง", "การค้า", "แลบ", "เคมิคอล", "อิมปอร์ตเอ็กซปอร์ต", "อินเตอร์เนชั่นแนล", "บรรจุภัณฑ์", "แพคกิ้ง",
"มอเตอร์", "โอสถ", "การบัญชี", "สโตร์", ) company_limited_prefixes = OrderedDict( ( ("บริษัท ", 0.95), ("ธนาคาร", 0.03), ("บริษัทหลักทรัพย์ ", 0.005), ("กองทุนรวม", 0.005), ) ) company_limited_suffixes = Or...
"""Support for raspihats board binary sensors.""" from __future__ import annotations import logging imp
ort voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import ( CONF_ADDRESS, CONF_DEVICE_CLASS, CONF_NAME, DEVICE_DEFAULT_NAME, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation a...
.helpers.typing import ConfigType, DiscoveryInfoType from . import ( CONF_BOARD, CONF_CHANNELS, CONF_I2C_HATS, CONF_INDEX, CONF_INVERT_LOGIC, DOMAIN, I2C_HAT_NAMES, I2C_HATS_MANAGER, I2CHatsException, I2CHatsManager, ) _LOGGER = logging.getLogger(__name__) DEFAULT_INVERT_LOGIC...
__author__ = 'alberto' import time from functools import wraps from config import logger def measure_time(func): """ D
ecorator that reports the execution time. """ @wraps(func) def wrapper(*args, **kwargs): logger.info("Running %s", func.__name__) start = time.time() result = func(*args, **kwargs) end = time.time() logger.info("Execution time: %s", end - start) return result...
return wrapper
import os import sys import time import pickle import threading import multiprocessing from concurrent.futures import ThreadPoolExecutor # required to reserve changed attributes from pandaserver.taskbuffer import JobSpec from pandaserver.taskbuffer import FileSpec JobSpec.reserveChangedState = True FileSpec.reserveC...
args': pickle.dumps(kwargs)}) # send notification to master self.comLock[i].release() # wait response self.resLock[i].acquire() res = pickle.loads(self.commDict[i]['res']) statusCode = self.commDict[i]['stat'] # release
lock to children self.childlock.put(i) log.debug('end') # return if statusCode == 0: return res else: errtype,errvalue = res raise RuntimeError("{0}: {1} {2}".format(self.methodName,errtype.__name__,errvalue)) # child class class TaskBuffer...
# coding=utf-8 # This file is part of SickRage. # # URL: https://sickrage.github.io # Git: https://github.com/SickRage/SickRage.git # # SickRage 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...
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from datetime import datetime f...
eParser import sickbeard from sickbeard import logger from sickbeard.classes import Proper, TorrentSearchResult from sickbeard.common import Quality from sickbeard.db import DBConnection from sickrage.helper.common import try_int from sickrage.helper.exceptions import ex from sickrage.providers.GenericProvider import...
# Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "Licens
e"); # 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 License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific ...
rs/src/main.rs") PATH_LIBS_RS = join_path("data/sample-rs/src/libs.rs") PATH_CODEACTION = join_path("data/sample-ts/src/codeAction.ts") print(PATH_MAIN_RS) def assertRetry(predicate, retry_max=100): retry_delay = 0.1 retry_count = 0 while retry_count < retry_max: if predicate(): retur...
PATH_MAIN_RS)) time.sleep(1) expect = [line.replace("greet", "hello") for line in nvim.current.buffer] nvim.funcs.cursor(3,
22) nvim.funcs.LanguageClient_textDocument_rename({"newName": "hello"}) time.sleep(1) assert nvim.current.buffer[:] == expect nvim.command("edit! {}".format(PATH_MAIN_RS)) def test_textDocument_rename_multiple_oneline(nvim): nvim.command("edit! {}".format(PATH_LIBS_RS)) time.sleep(1) exp...
# -*- coding: utf-8 -*- from __future__ imp
ort unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('applicants', '0010_auto_20151126_0525'), ] operations = [ migrations.AddField( model_name='applicant', name='number_of_mi
ssed_calls', field=models.IntegerField(default=0), ), ]
""" Author: Ali Hajimirza (ali@alihm.net) Copyright Ali Hajimirza, free for use under MIT license. """ import csv import os import sys import numpy as np import matplotlib.pyplot as plt from algorithm import EM import argparse def line_plot(data_arrays, xlabel, ylabel, labels, title, f): """ Plots a scatter c...
abel: string The label on the y axis. labels: list of string
The labels for each category. title: string The title of the graph. Will be used as the name of the graph file. dest: string, optional Path to the directory to save the image Returns ------- None: Saves the plot to the disk. """ plt.suptitle(title, fontsize=1...
#!/usr/bin/env python # Copyright 2019 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ucket = storage_client.bucket(bucket_name) # Reload fetches the current ACL from Cloud Storage. bucket.acl.reload() # You can also use `group`, `domain`, `all_authenticated` and `all` to # remove access for different types of entities. bucket.default_object_acl.user(user_email).revoke_read() b...
rint( "Removed user {} from the default acl of bucket {}.".format( user_email, bucket_name ) ) # [END storage_remove_bucket_default_owner] if __name__ == "__main__": remove_bucket_default_owner( bucket_name=sys.argv[1], user_email=sys.argv[2] )
#!/usr/bin/env python import os.path <<<<<<< HEAD import re import sys ======= import sys import gspread >>>>>>> # This is a combination of 2 commits. ======= <<<<<<< HEAD import re import sys ======= import sys import gspread >>>>>>> # This is a combination of 2 commits. >>>>>>> Update README.md try: from set...
"Topic :: Software Develop
ment :: Libraries :: Python Modules" ], license='MIT' )
# Copyright 2014 Plexxi, 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, ...
urn self.dataObject def version(self): return self.dataObject.version def addsubscriber(self, sender, type, corrId): if sender not in self.subscribers: self.subscribers[sender] = {} self.subscribers[sender]['type'] = type self.subscribers[sender]['correlatio...
elf.subscribers: del self.subscribers[sender] def getsubscribers(self, sender=""): if sender: if sender in self.subscribers: return self.subscribers[sender] else: return [] else: return self.subscribers
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, ) class YouJizzIE(InfoExtractor): _VALID_URL = r'https?://(?:\w+\.)?youjizz\.com/videos/[^/#?]+-(?P<id>[0-9]+)\.html(?:$|[?#])' _TEST = { 'url': 'http://www.youjizz.com/video...
self._download_webpage(playlist_url, video_id, 'Downloading playlist page') m_levels = list(re.finditer(r'<level bitrate="(\d+?)" file="(.*?)"', playlist_page)) if len(m_levels) == 0: raise ExtractorError('Unable to extract video...
vels] (_, video_url) = sorted(videos)[0] video_url = video_url.replace('%252F', '%2F') else: video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage, 'video URL') return...
# -*- coding:
utf8 -*- # # Copyright (C) 2014 NDP Sy
stèmes (<http://www.ndp-systemes.fr>). # # This program is free software: you can redistribute it and/or modify # 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 ...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibtokin.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
nstalled and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_comma
nd_line(sys.argv)
# coding: latin1 ## Copyright 2003-2007 Luc Saffre ## This file is part of the Lino project. ## Lino 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 your option) ...
mport Partner class Case(TestCase): def test01(self): db = startup() s1 = '' q = db.query(Contact,\ "name street city.name", orderBy="name") q.addColFilter('city',NotEmpty) ## for row in q:
## #print row[0] ## s1 += str(row[0]) + " " ## s1 += str(row[1]) + " " ## s1 += str(row[2]) + "\n" ## #print s1 ## self.assertEqual(s1,"""\ ## Arens None Eupen ## Ausdemwald None Aachen ## Bodard None Verviers ## Eesti Telefon Sõpruse pst. Tallinn ## Eiers...
r: # Python 2 from StringIO import StringIO as BytesIO from string import Template try: import urllib.request as urllib2 except ImportError: # Python 2 import urllib2 import urllib try: from PIL import Image except ImportError: # On some systems, PIL.Image is known as Image. import Imag...
elf.buffer.getvalue()) else: self.image().save(output, format) class Proxy: "
"" Proxy provider, to pass through and cache tiles from other places. This provider is identified by the name "proxy" in the TileStache config. Additional arguments: - url (optional) URL template for remote tiles, for example: "http://tile.openstree...
=None, rheader=self.rheader) else: r.error(415, current.ERROR.BAD_FORMAT) return output # ------------------------------------------------------------------------- @classmethod def write(cls, repository_id=None, res...
self._config = row
return self._config # ------------------------------------------------------------------------- def __getattr__(self, name): """ Delegate other attributes and methods to the adapter @param name: the attribute/method """ return object.__getattribute__(self.adapt...
""" A test module which has a required module and a config """ TYPE = "Test" NAME = "test_2" REQUIRES = ["test_1"] DEFAULTCONF = {'a': 1, 'b': 2} def check(conf=DEFAULTC
ONF): if None in REQUIRES: return False return True def scan(filelist, conf=DEFAULTCONF): results = [] result1, meta1 = REQUIRES[0] result1 = dict(result1) for fname in filelist: if fname in result1: results.append((fname, True)) else: results....
s, metadata
), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/e...
os.path.join(tcl, get_software_libdir('Tcl')) tk_libdir = os.path.join(tk, get_software_libdir('Tk')) tcltk_libs = "-L%(tcl_libdir)s -L%(tk_libdir)s -ltcl%(maj_min_ver)s -ltk%(maj_min_ver)s" % { 'tcl_libdir': tcl_libdir, 'tk_libdir': tk_libdir, 'm...
cltk_libs) super(EB_Python, self).configure_step() def install_step(self): """Extend make install to make sure that the 'python' command is present.""" super(EB_Python, self).install_step() python_binary_path = os.path.join(self.installdir, 'bin', 'python') if not os.path....
t uuid import subprocess from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.contrib.staticfiles.finders import find as find_static_path from olympia.lib.jingo_minify_helpers import ensure_path_exists def run_command(command): """Run a command and corr...
= 'css' and hasattr(settings, 'CLEANCSS_BIN'): opts = {'method': 'clean-css', 'bin': settings.CLEANCSS_BIN} run_command('{cleancss} -o {target} {source}'.format( cleancss=opts['bin'], target=file_out, source=file_in)) self.stdout.writ
e( 'Minifying %s (using %s)\n' % (file_in, opts['method'])) def _file_hash(self, url): """Open the file and get a hash of it.""" if url in self.checked_hash: return self.checked_hash[url] file_hash = '' try: with open(url) as f: f...
import re class UnknowItem(Exception): pass KEYWORDS = ("and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield") ...
r'-', 'MINUS'), (r'\*', 'STAR'), (r'/', 'SLASH'), (r'\|', 'VBAR'), (r'&', 'AMPER'), (r'<', 'LESS'), (r'>', 'GREATER'), (r'=', 'EQUAL'),
(r'%', 'PERCENT'), (r'\[', 'LEFT_SQUARE_BRACKET'), (r'\]', 'RIGHT_SQUARE_BRACKET'), (r'\{', 'LEFT_BRACKET'), (r'\}', 'RIGHT_BRACKET'), (r'`', 'BACKQUOTE'), (r'==', 'EQUAL_EQUAL'), (r'<>', 'NOT_EQUAL'), (r'!=', 'NOT_EQUAL'), (r'<=', 'LESS_EQUAL'), (r'>=', 'GREATER_EQUAL'), ...
import os import sys from github import Github from github.GithubException import GithubException def tag_to_tag(): SRC_TAG=os.environ.get('SRC_TAG') ORG_NAME=os.environ.get('ORG_NAME') REPO_NAME=os.environ.get('REPO_NAME') USERNAME=os.environ.get('USERNAME') PASSWORD=os.environ.get('PASSWORD') ...
set new one' # existing_ref.delete() ref = repo.create_git_ref('refs/tags/%s' % TAG, tag.sha) print 'Ref Created:' print ref._rawData print 'SUCCESS' if __name__ == '__main__': try:
tag_to_tag() except: import traceback exc_type, exc_value, exc_traceback = sys.exc_info() print '-'*60 traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout) print '-'*60 sys.exit(1)
#!/usr/bin/python ################ # The MIT License (MIT) # # Copyright (c) <2013> <Martin de Bruyn> # # 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...
ct import DirectObject # MeoTech imports #----------------------------------------------------------------------# class InputHandler(DirectObject): """InputHandler. Keyboard stuff """ def __init__(self, _game): """InputHandler INIT""" # Game s
elf.game = _game # Keyboard inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputStat...
from rest_framework import generics from rest_framework import permissions as drf_permissions from rest_framework.exceptions import NotFound from framework.auth.oauth_scopes import CoreScopes from osf.models import ( Guid, BaseFileNode, FileVersion, QuickFilesNode ) from api.base.exceptions import Go...
lf.kwargs[self.file_lookup_url_kwarg], self.request, display_name='file') except NotFound: obj = utils.get_object_or_error(Guid, self.kwargs[self.file_lookup_url_kwarg], self.request).referent if obj.is_deleted: raise Gone(detail='The requested file is no longer available...
d if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, obj) return obj class FileDetail(JSONAPIBaseView, generics.RetrieveUpdateAPIView, FileMixin): """The documentation for this endpoint can be found [here](https://developer.os...
#/usr/bin/env python import os import cv2 import sys import time import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score disp_n = 200 s_time = 3 radius = 3 thickness = 3 cls_color = (23, 119, 188) colors = [...
y2] fh.close() assert pd_c == len(pd_dt.keys()) return pd_dt # multiple or one for prediction def _read_pd(filepath, in_dire, is_in_dire=False): '''f
ormat: imgidx score bbox cls''' gt_dt = {} gt_c = 0 fh = open(filepath) imgidxs = [] for line in fh.readlines(): gt_c = gt_c + 1 line = line.strip() info = line.split() assert len(info) >= 1 im_path, info = info[0], info[1:] assert len(info) == 6 im_path = im_path.strip() score = info[0].str...
# based on https://github.com/pypa/sampleproject/blob/master/setup.py # see http://packaging.python.org/en/latest/tutorial.html#creating-your-own-project from setuptools import setup, find_packages from setuptools.command.install import install as stdinstall import codecs import os import re import sys def find_v...
h(r"^__version__ = ['\
"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") def get_file_contents(filename): with codecs.open(filename, encoding='utf-8') as f: contents = f.read() return conten...
elay, ACTION_WAIT_TEMPLATE: self._async_wait_template, ACTION_CHECK_CONDITION: self._async_check_condition, ACTION_FIRE_EVENT: self._async_fire_event, ACTION_CALL_SERVICE: self._async_call_service, } @property def is_running(self) -> bool: """Retu...
ice(self, action, variables, context): """Call the service specified in the action. This method is a coroutine. """ self.last_action = action.get(CONF_ALIAS, 'call service') self._log("Executing step %s" % self.last_action) await service.async_call_from_config( ...
blocking=True, variables=variables, validate_config=False, context=context ) async def _async_fire_event(self, action, variables, context): """Fire an event.""" self.last_action = action.get(CONF_ALIAS, action[CONF_EVENT]) self._log("Ex...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRvcheck(RPackage): """Check latest release version of R and R package (both in 'CRAN', ...
f943bea92') depends_on('r@3.3.0:', when='@:0.1.1', type=('build', 'run')) depends_on('r@3.
4.0:', when='@0.1.3:', type=('build', 'run')) depends_on('r-rlang', when='@0.1.1:', type=('build', 'run'))
impor
t numpy as np import tensorflow as tf import dists from misc import
*
# Copyright 2019-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
Other Parameters ---------------- qval : int The length of each q-gram. Using this parameter and tokenizer=None will cause the instance to use the QGram tokenizer with this q value. .. versionadded:: 0.4.0 """ super(Roberts, self)._...
str, tar: str) -> float: """Return the Roberts similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison Returns ...
# subSystemBonusGallenteElectronic2TractorBeamVelocity # # Used by: # Subsy
stem: Proteus Electronics - Emergent Locus Analyzer type = "passive" def handler(fit, module, context): fit.modules.filteredItemBoost(lambda mod: mod.item.group.name == "Tractor Beam", "maxTractorVelocity", module.getModifiedItemAttr("s
ubsystemBonusGallenteElectronic2"), skill="Gallente Electronic Systems")
from django.db import models from django.db.models.fields.files import FieldFile from django.core.files import File def get_video_dimensions(path): from ffvideo import VideoStream vs = VideoStream(path) return (vs.frame_width, vs.frame_height) class VideoFile(File): """ A mixin for use alongsi...
] width = property(_get_width) def _get_height(self): return self._get_video_dimensions()[1] height = property(_get_height) def _get_video_dimensions(self): if not hasattr(self, '_dimensions_cache'): close = self.closed self.open() self._di
mensions_cache = get_video_dimensions(self.path) return self._dimensions_cache # A video field is exactly a file field with a different signature class VideoFieldFile(VideoFile, FieldFile): pass class VideoField(models.FileField): attr_class = VideoFieldFile
# 5% elif num < 10: planet.type = 'G'; planet.diameter = dice(3, 6, 0) * 10000 # 5% elif num < 60: planet.type = 'R'; planet.diameter = dice(1, 10, 0) * 1000 # 50% - rock elif num < 70: planet.type = 'D'; planet.diameter = dice(2, 6, 2) * 1000 # 10% - desert elif num < 100: ...
1000 # Else / 20% - hostile elif num
< 100: if isFGK: # planet.type = 'E'; planet.diameter = dice(2, 6, 5) * 1000 planet.type = 'E'; planet.diameter = dice(1, 4, 13) * 1000 # FGK / 10% - terran else: planet.type = 'H'; planet.diameter = dice(3, 6, 1) * 1000 # Else / 10% - hostile elif zone == 2: # Zone C if num < 15: planet.type =...
from data.database.sourceGroupAssignmentTable import getSourceIdToAssignedGroups from data.database.sourceGroupTable import getAllSourceGroupNames from data.
database.sourceTable import getAllSources (categoryToSourceObjects, sourceCategoryNames, sourceIdToAssignments, sourceIdToSourceObject, unCategorizedSource) = ({}, None, None, None, None) def getSourceById(sourceId):
return sourceIdToSourceObject[sourceId] def getSourceCategoryNames(): return sourceCategoryNames def getSources(categoryName): return categoryToSourceObjects[categoryName] def getUncategorizedSource(): return unCategorizedSource def _addToCategoryLookup(source): global categoryToSourceObjects ...
import logging import math from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.db.models import Q from django.shortcuts import get_object_or_404, redirect, render from django.views.generic import View from experiments_ma...
else: return render(request, 'user_manager/register.html', {'form': form}) def existing_user_check(email_address): return User.objects.filter(email=email_address) class WorkbenchUserDetailView(View): def get(self, request, username):
workbench_user = get_object_or_404(WorkbenchUser, user__username=username) recent_experiments = Experiment.objects.filter(owner=workbench_user, completed=True).order_by('-created')[:5] recent_packages = Package.objects.filter(owner=workbench_user).order_by('-created')[:5] return render(requ...
#!/usr/bin/env python #Demo code # # simple demonstration script showing real-time thermal Imaging # using the MLX90620 16x4 thermopile array and the mlxd daemon # # Copyright (C) 2015 Chuck Werbick # # # # This program is free software; you can redistribute it and/or modify # it under the terms of the G...
= cmap(ir) rgb_img = np.delete(rgba_img, 3, 2)
# align the IR array with the camera tform = transform.AffineTransform(scale=SCALE, rotation=ROT, translation=OFFSET) ir_aligned = transform.warp(rgb_img, tform.inverse, mode='constant', output_shape=im.shape) # turn it back into a ubyte so it'll display on the preview overlay ir_byte = img_as_ubyte...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0002_recipecollection_title'), ] operations = [ migrations.CreateModel( name='Tag', fields...
eld(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)), ('title', models.CharField(max_length=255)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='recipe', name='ta...
recipes'), preserve_default=True, ), ]
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
o which to connect. channel_credentials: The implementations.ChannelCredentials with which to connect. server_host_override: The target name used for SSL host name checking. Returns: An implementations.Channel to the remote host through which RPCs may be conducted. """ targ
et = '%s:%d' % (host, port) channel = grpc.secure_channel( target, channel_credentials._credentials, ((b'grpc.ssl_target_name_override', server_host_override,),)) return implementations.Channel(channel)
from django.conf.urls.defaults import patterns, include, url from rest_framework.urlpatterns import format_suffix_patterns from startups import views # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('startups.views', # Examples: ...
doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^startups$', 'startup_list'), url(r'^startups/(?P<pk>[0-9]+)$', 'startup_detail'), ) urlpatterns = format_suffix_
patterns(urlpatterns)
d['source'] = 'gffutils_derived' d['frame'] = '.' d['extra'] = [] d['attributes'] = helpers._unjsonify(d['attributes']) f = feature.Feature(**d) f.id = self._id_handler(f) yield f # Drop the indexes so...
for large files you may want to use `verbose=False` to avoid this. checklines : int Number of lines to check the dialect
. merge_strategy : str One of {merge, create_unique, error, warning, replace}. This parameter specifies the behavior when two items have an identical primary key. Using `merge_strategy="merge"`, then there will be a single entry in the database, but the attributes of all f...
""" WSGI config for cv project. It exposes the WSGI callable as a module-level variable named `
`application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cv.settings") application = get
_wsgi_application()
"""Support for Spider thermostats.""" import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_T...
" return SPIDER_STATE_TO_HA[self.thermostat.operation_mode] @property def hvac_modes(self): """Return the list of available operation modes.""" return SUPPORT_HVAC def set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_T...
temperature is None: return self.thermostat.set_temperature(temperature) def set_hvac_mode(self, hvac_mode): """Set new target operation mode.""" self.thermostat.set_operation_mode(HA_STATE_TO_SPIDER.get(hvac_mode)) @property def fan_mode(self): """Return the f...
}) self.assertTrue(daemon.isAlive()) daemon.kill() @test_base.flaky def test_2_daemon_with_option(self): logger_path = test_base.getTestDirectory(test_base.TEMP_DIR) daemon = self._run_daemon( { "disable_watchdog": True, "disable_ex...
never exist
daemon = self._run_daemon( { "disable_watchdog": True, "disable_extensions": True, "disable_logging": False, }, options_only={ "logger_path": logger_path, "logger_mode": test_mode, "verbo...
# -*- coding: utf-8 -*- actions = { "up": _(u"Go up in the current buffer"), "down": _(u"Go down in the current buffer"), "left": _(u"Go to the previous buffer"), "right": _(u"Go to the next buffer"), "next_account": _(u"Focus the next session"), "previous_account": _(u"Focus the previous session"), "show_hide": _(u"Sh...
ome": _(u"Jump to the first element of a buffer"), "go_end": _(u"Jump to the last element of the current buffer"), "go_page_up": _(u"Jump 20 elements up in the current buffer"), "go_page_down": _(u"Jump 20 elements down in the current buffer"), "update_profile": _(u"Edit profile"), "delete": _(u"Delete a tweet or direc...
y_to_clipboard": _(u"Copy to clipboard"), "add_to_list": _(u"Add to list"), "remove_from_list": _(u"Remove from list"), "toggle_buffer_mute": _(u"Mute/unmute the active buffer"), "toggle_session_mute": _(u"Mute/unmute the current session"), "toggle_autoread": _(u"toggle the automatic reading of incoming tweets in the a...
# -*- coding: utf-8 -*- # # # Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>) # Author: Nico
la Malcontenti <nicola.malcontenti@agile
bg.com> # # This program is free software: you can redistribute it and/or modify # 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 h...
class R
obot: def __init__(self): self.__name = "" @property def name(self): return self.__name @name.setter def name(self, x): self.__name = x class Car: def __init__(self, model=None): self.__set_model(model) def __set_model(self, model): self.__model = model def __get_model(self): return self.__m...
x = Robot() x.name = "apo" print(x.name) c = Car() c.model = "Mercedes" print(c.model)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.test import TestCase from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject class PortalTest(TestCase): def setUp(self): self.study_group1 = StudyGroup.objects....
1 = Lab.objects.create(name="Кольца ньютона", subject=self.subject1) self.lab2 = Lab.objects.create(name="Атвуд", subject=self.subject2) def test_task_create(self): has_error = False try: task = Task(stud
ent=self.student1, lab=self.lab1) task.clean() task.save() except ValidationError: has_error = True self.assertFalse(has_error) def test_task_create_double(self): """ Должна выскочить ошибка валидации - пытаемся создать 2 одинаковых задания ...
urn routes[index.row()].routeNum elif index.column() == 1: return routes[index.row()].beginSignal.name elif index.column() == 2: return routes[index.row()].endSignal.name elif index.column() == 3: return routes[index.row()].initialState...
0 => Not activated 1 => Activated, non persistent 2 => Activated, persistent.""" if self.beginSignal.nextActiveRoute is not None and \ self.beginSignal.nextActiveRoute == self: if self._persistent: return 2 else: return 1 ...
return 0 @property def directions(self): """Returns the directions dictionary""" return self._directions def direction(self, tiId): """Returns the direction of this route at the trackItem with id tiId """ return self._directions[tiId] def appendDirection(self, ...
# -*- coding: utf-8 -*- # # # Copyright: (c) 2012, Red Hat, Inc # Written by Seth Vidal <skvidal at fedoraproject.org> # Contributing Authors: # - Ansible Core Team # - Eduard Snesarev (@verm666) # - Berend De Schouwer (@berenddeschouwer) # - Abhijeet Kasurde (@Akasurde) # GNU General Public License v3.0+ (...
son( msg='It appears that a space separated string of packages was passed in ' 'as an argument. To operate on several packages, pass a comma separated ' 'string of packages or a list of packages.' ) # This should really be redefined by both th...
timeout is a positive number''' if (os.path.isfile(self.lockfile) or glob.glob(self.lockfile)): if self.lock_timeout > 0: for iteration in range(0, self.lock_timeout): time.sleep(1) if not os.path.isfile(self.lockfile) and not glob.glob(self.l...
anField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [],...
ndex': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}), 'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'max_length': '100'})...
}, 'cms.pagemoderatorstate': { 'Meta': {'ordering': "('page', 'action', '-created')", 'object_name': 'PageModeratorState'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.Date...
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Licens
e for the specific language governing permissions and # limitations under the License. from ._query import query
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Dimitrios Tydeas Mengidis <tydeas.dr@gmail.com> # This file is part of Ansible # # Ansible 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...
required: false default: "yes" choices: [ "yes", "no" ] aliases: [ "no-dev" ] no_scripts: description: - Skips the execution of all scripts defined in composer.json ( see --no-scripts ) required: false default: "no"
choices: [ "yes", "no" ] aliases: [ "no-scripts" ] no_plugins: description: - Disables all plugins ( see --no-plugins ) required: false default: "no" choices: [ "yes", "no" ] aliases: [ "no-plugins" ] optimize_autoloader: description: ...
# jsb/plugs/core/rc.py # # """ jsonbot resource files .. files with the .jsb extension which consists of commands to be executed. """ ## jsb imports from jsb.lib.commands import cmnds from jsb.lib.examples import examples from jsb.utils.url import geturl2 from jsb.utils.exception import handle_exception from jsb.uti...
lt.waitall() teller += 1 #waitevents(waiting) event.reply("%s commands executed" % teller) except Exception, ex: event.reply("an error occured: %s" % str(ex)) ; handle_exception() cmnds.add("rc", ha
ndle_rc, ["OPER"], threaded=True) examples.add("rc", "execute a file of jsonbot commands .. from file or url", "1) rc resource.jsb 2) rc http://jsonbot.org/resource.jsb")
from __future__ import print_function import unittest import numpy as np import pydrake import os.path class TestRBTCoM(unittest.TestCase): def testCoM0(self): r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(), "examples/Pendulum/Pendulum.urdf"))...
"examples/Pendulum/Pendulum.urdf")) q = r.getRandomConfiguration() kinsol = r.doKinematics(q, np.zeros((7, 1))) J = r.centerOfMassJacobian(kinsol) self.assertTrue(np.shape(J) == (3, 7)) q = r.getZeroConfiguration(
) kinsol = r.doKinematics(q, np.zeros((7, 1))) J = r.centerOfMassJacobian(kinsol) self.assertTrue(np.allclose(J.flat, [1., 0., 0., 0., -0.2425, 0., -0.25, 0., 1., 0., 0.2425, 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], atol=1e-4)) if __name__ == '__main__': unittest.main()
inka, José Sánchez-Gallego, and Brett Andrews # @Date: 2018-07-24 # @Filename: test_rss.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # # @Last modified by: José Sánchez-Gallego (gallegoj@uw.edu) # @Last modified time: 2018-08-04 13:35:39 import astropy.io.fits import astropy.table impo...
rt len(sliced.mask) == n_elements for dm_element in rssfiber.rss.datamodel.rss + rssfiber.rss.datamodel.spectra: if dm_element.name == 'flux': continue spectrum_sliced = getattr(sliced, dm_element.name, None) assert len(spectrum_sliced) == n_elements ...
def test_rssfiber_masked(self, rssfiber): assert numpy.sum(rssfiber.masked.mask) > 0 def test_rssfiber_descale(self, rssfiber): descaled = rssfiber.descale() numpy.testing.assert_allclose(descaled.value, rssfiber.value * rssfiber.unit.scale) assert descaled.obsinfo is not N...
'''This module contains utilities for following up search triggers''' # JavaScript for searching the aLOG redirect_javascript = """<script type="text/javascript"> function redirect(form,way) { // Set location to form and submit. if(form != '') { document.forms[form].action=way; ...
s must be strings giving year, month, day resp. Returns ------- return_string : string String containing HTML for links to summary page and aLOG search """ search_form = search_form_string data = {'H1': data_h1_string, 'L1': data_l1_string} if ifo not in data: return ifo ...
# summary page is exactly the reverse ext = '%4d%02d%02d' % (utc_time[0], utc_time[1], utc_time[2]) return_string = search_form % (ifo.lower(), ifo.lower(), alog_utc, alog_utc) return return_string + data[ifo] % ext
from copy import deepcopy from sqlalchemy import inspect from sqlalchemy.orm.base import DEFAULT_STATE_ATTR from sqlalchemy.orm.state import InstanceState from mongosql.bag import ModelPropertyBags class ModelHistoryProxy: """ Proxy object to gain access to historical model attributes. This leverages SqlAlc...
://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.AttributeState.history This means that as soon as you load a relationship, model history is reset. To solve this, we have to make a copy of this model. All attributes are set on `self`, so accessing `self.attr` will not tr...
)` """ """ Copy the given list of columns from the instance onto self """ insp = self.__inspect # type: InstanceState # Copy all values onto `self` for column_name in self.__bags.columns.names: # Skip unloaded columns (because that would emit sql queries) ...
#/usr/bin/env python #Base Server -Chapter three -basicserver.py import socket, traceback host='' port=8080 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) print "Waiting for connections..." s.listen(1) while True: try: clien...
t): raise except: traceback.print_exc() try: clientsock.close() except KeyboardInterrupt:
raise except: traceback.print_exc()
, 2]] assert list(postfixes([1, 2, 3, 4, 5])) == \ [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] def test_topological_sort(): V = [2, 3, 5, 7, 8, 9, 10, 11] E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), (11, 2), (11, 9), (11, 10), (8, 9)] assert topological_sort...
2, 3], [4]], [
[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] assert list(multiset_partitions([1, 2, 2], 2)) == [ [[1, 2], [2]], [[1], [2, 2]]] assert list(multiset_partitions(3)) == [ [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0],...
# -*- encoding: utf-8 -*- ###########################
################################################### # # Daniel Campos (danielcampos@avanzosc.es) Date: 29/09/2014 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either vers...
lied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ######################################...
distribution( number_of_particles, *list_arguments, **keyword_arguments ): return new_flat_mass_distribution( number_of_particles, mass_min=stellar_mass/number_of_stars, mass_max=stellar_mass/number_of_stars, ) initi...
sition and velocity, based on the distribution model. if star_distribution == "plummer": stars = new_plummer_sphere( number_of_stars, convert_nbody=converter, ) elif star_distribution == "king": stars = new_king_model( number_of_stars,
star_distribution_w0, convert_nbody=converter, ) elif star_distribution == "fractal": stars = new_fractal_cluster_model( number_of_stars, fractal_dimension=star_distribution_fd, convert_nbody=converter, ) else: return -1, "No ...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
r the learning framework, # including the representation distribution and signal reconstruction plots rep_model.load_weights('./ckpt/glr_%s_lambda%.1f' %(args.data, args.lamda)) plot_reps(testset, rep_model, args.data) if __nam
e__=="__main__": parser = argparse.ArgumentParser() parser.add_argument('--data', type=str, default='air_quality', help="dataset to use") parser.add_argument('--lamda', type=float, default=1., help="regularization weight") parser.add_argument('--train', action='store_true') args = parser.parse_args(...
filenames = ['firstNames', 'secondNames', 'famousWrestlers', 'categories', 'jobs'] for filename in filenames: with open('%s.csv' % fi
lename, 'r') as f: namelist = [] for name in f.read().split('\n'): if len(name)>1: namelist.append(name) with
open('../js/%s.js' % filename, 'w') as dest_f: dest_f.write('%s = %s;' % (filename, namelist))
replace(' < ', ' &lt; ').\ replace(' > ', ' &gt; ').\ replace('>=', ' &ge; ') sel = Selector(text=html) item = ProblemItem() item['oj'] = 'poj' item['problem_id'] = self.problem_id item['problem_url'] = response.url item['title'] =
sel.css('.ptt').xpath('./text()').extract()[0] item['description'] = sel.css('.ptx').extract()[0] item['input'] = sel.css('.ptx').extract()[1] item['output'] = sel.css('.ptx').extract()[2] try: item['time_limit'] = sel.css('.plm').re('Case\sT[\S
*\s]*MS')[0][21:] except: item['time_limit'] = sel.css('.plm').re('T[\S*\s]*MS')[0][16:] item['memory_limit'] = sel.css('.plm').re('Me[\S*\s]*K')[0][18:] item['sample_input'] = sel.css('.sio').extract()[0] item['sample_output'] = sel.css('.sio').extract()[1] ...
########################################################################## # # Copyright (c) 2011, Image Engine Design Inc. All righ
ts reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * ...
ther materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDE...