prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
"""Command line interface for echo server.""" import fnmatch import asyncio import argparse from aioconsole import AsynchronousCli, start_interactive_server from aioconsole.server import parse_server, print_server from . import echo async def get_history(reader, writer, pattern=None): history = asyncio.get_eve...
serve_cli = None return host, port, serve_cli def main(args=None): host, port, serve_cli = parse_args(args) if serve_cli: cli_host, cli_port = serve_cli coro = start_interactive_server(make_cli, cli_host, cli_port) server = asyncio.get_event_loop().run_until_complete(coro)...
()) return echo.run(host, port) if __name__ == "__main__": main()
U Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Found
ation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # """Module with utility functions that act on molecule objects.""" from typing import Dict, Tuple, Union import numpy as np import qcelemental as qcel from psi4 import core from psi4.driver.p4util import temp_circular_import...
ptions import * def molecule_set_attr(self, name, value): """Function to redefine __setattr__ method of molecule class.""" fxn = object.__getattribute__(self, "is_variable") isvar = fxn(name) if isvar: fxn = object.__getattribute__(self, "set_variable") fxn(name, value) return ...
: return Vector3(self.x + v.x, self.y + v.y, self.z + v.z) __radd__ = __add__ def __sub__(self, v): return Vector3(self.x - v.x, self.y - v.y, self.z - v.z) def __neg__(self): return Vector...
* g.x - c.x * g.z temp_matrix.c.z = c.x * g.y - c.y * g.x self.a += temp_matrix.a self.b += temp_matrix.b self.c += temp_matrix.c def normalize(self): '''re-normalise a rotation matrix''' error = self.a * self.b t0 = self.a - (self.b * (0.5 * error)) ...
* (1.0 / t0.length()) self.b = t1 * (1.0 / t1.length()) self.c = t2 * (1.0 / t2.length()) def trace(self): '''the trace of the matrix''' return self.a.x + self.b.y + self.c.z def from_axis_angle(self, axis, angle): '''create a rotation matrix from axis and angle''' ...
# -*- coding: utf-8 -*- ############################################################################### # # GetInstance # Retrieves information about the specified Instance. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may n...
aphy from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import Ch
oreographyExecution import json class GetInstance(Choreography): def __init__(self, temboo_session): """ Create a new instance of the GetInstance Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(GetInstance, self).__...
# -*- coding: utf-8 -*- # crunchyfrog - a database schema browser and query tool # Copyright (C) 2008 Andi Albrecht <albrecht.andi@gmail.com> # # 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, e...
:Usage example: .. sourcecode:: python
>>> app.config.get("foo.bar") # Not set yet, None is default None >>> app.config.set("foo.bar", True) >>> app.config.get("foo.bar") True >>> app.config.set("foo.bar", ["Completely", "different"]) # No type check! >>> print " ".join(app.config.get("foo.bar")) Complete...
#!/usr/bin
/env python from __future__ import print_function import sys import numpy import pni.io.nx.h5 as nexus f = nexus.create_file("test_string2.nxs",True); d = f.root().create_group("scan_1","NXentry").\ create_group("detector","NXdetector") sa= d.create_field("ListofStrings","string",shape=(3,2)) ...
()
"""Drafts as required folder Revision ID: 41a7e825d108 Revises: 269247bc37d3 Create Date: 2014-0
3-13 21:14:25.652333 """ # revision identifiers, used by Alembic. revision = '41a7e825d108' down_revision = '269247bc37d3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('imapaccount', sa.Column('drafts_folder_name', sa.String(255),
nullable=True)) def downgrade(): op.drop_column('imapaccount', 'drafts_folder_name')
#!/usr/bin/python # # Copyright 2008-2010 WebDriver committers # Copyright 2008-2010 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CO...
the License for the specific language governing permissions and # limitations under the License. from selenium import webdriver from selenium.test.selenium.webdriver.common import api_examples from selenium.test.selenium.webdriver.common.webserver import SimpleWebServer def setup_module(module): webserver = Simp...
from application import app as application from gevent import monkey from socketio.server import SocketIOServer
monkey.patch_all() if __name__ == '__main__': # SocketIOServer( # ('', application.config['PORT']), # application, # resource="socket.io").serv
e_forever() socketio.run(application)
# browsershots.org - Test your web design in different browsers # Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org> # # Browsershots 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 ...
the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ URL configuration for the accounts app. """ __revision__ = "$Rev: 2160 $" __date__ = "$Date: 2007-09-18 19:12:50 -0400 (Tue, 18 Sep 2007) $" __author__ = "$Author: johann $" from django.conf.urls.defaults import...
ns = patterns('shotserver04.accounts.views', (r'^login/$', 'login'), (r'^logout/$', 'logout'), (r'^profile/$', 'profile'), (r'^email/$', 'email'), (r'^verify/(?P<hashkey>[0-9a-f]{32})/$', 'verify'), )
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from openiv.settings import * # Create your views here. def index(request): return redirect(reverse('public:event')) # Comment the above to have an independent home page. context = { 'imagesource': ...
by ' + EVENT_HOSTED_BY + '. Choristers from across the country will be in ' + EVENT_CITY + ' for intensive rehearsals to produce a grand concert.', 'Out
of courtesy to the upcoming festivals (' + EVENT_UPCOMING_EVENTS + '), we won’t have any news until ' + EVENT_PRIOR_CITY + ' ' + EVENT_PRIOR_YEAR + ' has begun. Festival details will be revealed in ' + EVENT_PRIOR_YEAR + '.', ORGANISATION_SHORT_NAME + ' acknowledges that ' + EVENT_SHORT_NAME + ' is being held on ...
ly wrong import pygments import pygments.lexers import pygments.token @neovim.plugin class Neosyntax(object): def __init__(self, nvim): self.nvim = nvim # swap src_ids. from brefdl: allocate two ids, and swap, adding before clearing, so things that don't change won't appear to flicker ...
self.msg("lni : " + str(lastnewlineindex)) self.msg("tok : " + str(tokentype)) self.msg("val : " + str(value)) self.msg("--------") # XXX issue with highlight groups # if `:syntax off` is set from vimrc, which is the entire goal of this plugin ...
hlight group will probably exist (assuming the colorscheme # defines it), but "pythonComment" will not. # This isn't great, because I want to maintain the ability of users to modify individual # language highlight groups if they feel like it # I am not going to worry abou...
import unittest import logging from harmoniccontext.harmonic_context import HarmonicContext from harmoniccontext.harmonic_context_track import HarmonicContextTrack from harmonicmodel.secondary_chord_template import SecondaryChordTemplate from harmonicmodel.tertian_chord_template import TertianChordTemplate from struc...
tonicPitch(5, 'c') f = TChromaticReflection(target_line, target_hct, cue) score_line, score_hct = f.apply() print('--- after transformation ---') TestTChromaticFlip.print_notes(score_line) TestTChromaticFlip.print_hct(score_hct) print('--- transformation ---') T...
et_hct) notes = score_line.get_all_notes() assert 'C:5' == str(notes[0].diatonic_pitch) assert 'Ab:4' == str(notes[1].diatonic_pitch) assert 'F:4' == str(notes[2].diatonic_pitch) assert 'Db:5' == str(notes[3].diatonic_pitch) assert 'C:5' == str(notes[4].diatonic_pitch) ...
# generated from catkin/cmake/template/__init__.py.in # keep symbol table as clean as possible by deleting all unnecessary symbols from os import path as os_path from sys import path as sys_path from pkgutil import extend_path __extended_path = "/home/rss-student/rss-2014-team-3/src/robotbrain/src".split(";") for p ...
__, '__init__.py')
if os_path.isfile(src_init_file): __execfiles.append(src_init_file) del src_init_file del p del os_path del __extended_path for __execfile in __execfiles: with open(__execfile, 'r') as __fh: exec(__fh.read()) del __fh del __execfile del __execfiles
# Constants SSD1351_I2C_ADDRESS = 0x3C # 011110+SA0+RW - 0x3C or 0x3D SSD1351_SETCONTRAST = 0x81 SSD1351_DISPLAYALLON_RESUME = 0xA4 SSD1351_DISPLAYALLON = 0xA5 SSD1351_NORMALDISPLAY = 0xA6 SSD1351_INVERTDISPLAY = 0xA7 SSD1351_DISPLAYOFF = 0xAE SSD1351_DISPLAYON = 0xAF SSD1351_SETDISPLAYOFFSET = 0xD3 SSD1351_SETCOMPINS...
ast of the display. Contrast
should be a value between 0 and 255.""" if contrast < 0 or contrast > 255: raise ValueError('Contrast must be a value from 0 to 255 (inclusive).') self.command(SSD1351_CONTRASTMASTER) self.command(contrast) def dim(self, dim): """Adjusts contrast to dim the display if dim is True, otherwise sets the c...
+= 1 def pop(self): (_, _, item) = heapq.heappop(self.heap) # (_, item) = heapq.heappop(self.heap) return item def isEmpty(self): return len(self.heap) == 0 class PriorityQueueWithFunction(PriorityQueue): """ Implements a priority queue with the same push/pop signatu...
not implemented: %s at line %s of %s" % (method, line, fileName) sys.exit(1) def normalize(vectorOrCounter): """ normalize a vector or counter by dividing each value by the sum of all values """ normalizedCounter = Counter() if type(vectorOrCounter) == type(normalizedCounter): counter ...
value = counter[key] normalizedCounter[key] = value / total return normalizedCounter else: vector = vectorOrCounter s = float(sum(vector)) if s == 0: return vector return [el / s for el in vector] def nSample(distribution, values, n): if sum(distri...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
anty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ###############################...
ces', 'description': """ This module aims to manage employee's attendances. ================================================== Keeps account of the attendances of the employees on the basis of the actions(Sign in/Sign out) performed by them. """, 'author': 'OpenERP SA', 'images': ['images/hr_attenda...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'replace_with_ref_dialog_ui.ui' # # Created: Fri Nov 18 22:58:33 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Dia...
self.horizontalLayout.addWidget(self.uiLBL_text) self.verticalLayout.addWidget(self.groupBox) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtW...
ayout_2.addItem(spacerItem) self.uiBTN_saveReplace = QtWidgets.QPushButton(Dialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self....
# $Id: 201_codec_l16_160
00.py 369517 2012-07-01 17:28:57Z file $ # from inc_cfg import * # Call with L16/16000/1 codec test_param = TestParam
( "PESQ codec L16/16000/1 (RX side uses snd dev)", [ InstanceParam("UA1", "--max-calls=1 --add-codec L16/16000/1 --clock-rate 16000 --play-file wavs/input.16.wav --null-audio"), InstanceParam("UA2", "--max-calls=1 --add-codec L16/16000/1 --clock-rate 16000 --rec-file wavs/tmp.16.wav --auto-answer 200") ]...
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 rest...
===== """ Redis dataset - Populated the Redis server with the supervised games - Saves the redis database on disk for faster boot time. """ import logging import os import pickle import shutil from threading import Thread from tqdm import tqdm from diplomacy_research.models.training.memory_buffer import MemoryB...
.training.memory_buffer.expert_games import save_expert_games from diplomacy_research.proto.diplomacy_proto.game_pb2 import SavedGame as SavedGameProto from diplomacy_research.utils.process import start_redis from diplomacy_research.utils.proto import bytes_to_zlib, bytes_to_proto, read_next_bytes from diplomacy_resear...
#!/usr/bin/env python3 # vim: tw=76 import kxg import random import pygle
t LOWER_BOUND, UPPER_BOUND = 0, 5000 class World(kxg.World): """ Keep track of the secret number, the range of numbers that haven't been eliminated yet, and the winner (if there is one). """ def __init__(self): super().__init__() self.number = 0 self.lower_bound = 0 ...
" def on_start_game(self, num_players): number = random.randint(LOWER_BOUND + 1, UPPER_BOUND - 1) self >> PickNumber(number, LOWER_BOUND, UPPER_BOUND) class PickNumber(kxg.Message): """ Pick the secret number and communicate that choice to all the clients. """ def __init__(self, ...
from selenium_test_case import SeleniumTestCase class Do
csTest(SeleniumTestCase): def test_links_between_pages(self): self.open_path('/help') self.assert_text_present('Frequently Asked Questions') s
elf.click_and_wait('link=Terms of Service') self.assert_text_present('Terms of Service for Google Resource Finder') self.click_and_wait('link=Privacy') self.assert_text_present('Google Resource Finder Privacy Policy') self.click_and_wait('link=Help') self.assert_text_present('F...
(fil.read()).hexdigest() #print('Uploaded file %s md5=%s size_local=%s size_remote=%s' % (f, md5, size_local, size_remote)) fil.close() if size_remote != size_local: raise Exception("Sizes don't match!") def getProgress(self): # return current progress percent i...
ist: if os.path.isdir(f):
subdirfiles = [os.path.join(f, i) for i in os.listdir(f)] self.enqueueFiles(subdirfiles) else: self.fileslist.append(f) self.startlen += 1 # self.fileslist.extend(fileslist) # self.startlen += len(fileslist) class Alb...
0}".format(value)) elif key in ('warn_unused', 'control_scoping'): # TODO deprecate control_scoping? or add it to compiler? if not isinstance(value, bool): raise SassError("The '{0}' @option requires a bool, not {1!r}".format(key, value)) else...
# but keywords() is never called on it try: self.manage_children(_rule, scope) except SassReturn as e: return e.retval else: return Null() return __call ...
mixin = _mixin if block.directive == '@mixin': add = rule.namespace.set_mixin elif block.directive == '@function': add = rule.namespace.set_function # Register the mixin for every possible arity it takes if argspec_node.slurp or argspec_node.inject: ...
ssType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="value", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, ...
tp://openco
nfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=False, ) except (TypeError, ValueError): raise ValueError( { "error-string": """value must be ...
ngo administration</a></h1>') self.client.logout() response = self.client.get(reverse('django-admindocs-docroot'), follow=True) # Should display the login screen self.assertContains(response, '<input type="hidden" name="next" value="/admindocs/" />', html=True) def test_bookmarklets...
jects. Deleting settings is fine here as UserSettingsHolder is used. """ Site.objects.all().delete() del settings.S
ITE_ID response = self.client.get(reverse('django-admindocs-views-index')) self.assertContains(response, 'View documentation') @override_settings(TEMPLATES=[{ 'NAME': 'ONE', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, { 'NAME': 'TWO', 'BACKEND...
_method", "Comment packing method") yield UInt16(s, "comment_crc16", "Comment CRC") def commentBody(s): size = s["total_size"].value - s.current_size if size > 0: yield RawBytes(s, "comment_data", size, "Compressed comment data") def signatureHeader(s): yield TimeDateMSDOS32(s, "creation_time"...
elf, "has_salt", "Has salt for encryption") yield Bit(self, "uses_file_version", "File versio
ning is used") yield Bit(self, "has_ext_time", "Extra time info present") yield Bit(self, "has_ext_flags", "Extra flag ??") for field in commonFlags: yield field[0](self, *field[1:]) def fileFlags(s): yield FileFlags(s, "flags", "File block flags") class ExtTimeFlags(FieldSet):...
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChec...
ry: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def edit_jsonschema_validation(context, params): schema = context.schema schema_validator = Draft4Validator(schema, fo...
0]: e.message for e in err.errors}) return normalize(params, schema) def delete_jsonschema_validation(context, params): return params
# -*- coding: utf-8 -*- # Copyright © 2014-2016 Digital Catapult and The Copyright Hub Foundation # (together the Open Permissions Platform Coalition) # # 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 Found...
ributed 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 Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """API Roles handler. Allows to create and modify roles """ from koi import auth from perch import Token, User from tornado.gen import coroutine from .base import BaseHandler...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-05 10:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('account', '0003_auto_20170705_0958'), ] operations = [ migrations.RenameField( ...
_name='oauthtoken',
old_name='renew_token_expiration', new_name='refresh_token_expiration', ), ]
import logging import sys from cliff.app import App from cliff.commandmanager import CommandManager # from .utils import ColorLogFormatter from nicelog.formatters import ColorLineFormatter class HarvesterApp(App): logger = logging.getLogger(__name__) def __init__(self): super(HarvesterApp, self).__...
.options.verbose_level, logging.DEBUG) console.setLevel(console_level) # formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT) formatter = ColorLineFormatter( show_date=True, show_function=True, show_filename=True) console
.setFormatter(formatter) root_logger.addHandler(console) return def main(argv=sys.argv[1:]): myapp = HarvesterApp() return myapp.run(argv) if __name__ == '__main__': sys.exit(main())
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab # Copyright © 2010-2012 Greek Research and Technology Network (GRNET S.A.) # # Permission to use, copy, modify, and/or dis
tribute this software for any # purpose
with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS. IN NO EVENT SHALL ISC...
hidd
enimports = ['decim
al']
#Problem 1: #Python provides a built-in function called len th
at returns the length of a string #so the value of len('allen') is 5. #Write a function named right_justify that takes a string named s as a parameter and prints #the string with enough leading spaces so that the last letter of the string is in column 70 #of the display. #word = raw_input('Type a word to send over th...
. Type this example into a script and test it: #def do_twice(f): #f() #f() #2. Modify do_twice so that it takes two arguments, a function object and a value, #and calls the function twice, passing the value as an argument. #3. Write a more general version of print_spam, called print_twice, that takes a #string as a...
impor
t pytest from
punch import vcs_configuration as vc @pytest.fixture def global_variables(): return { 'serializer': '{{ major }}.{{ minor }}.{{ patch }}', 'mark': 'just a mark' } @pytest.fixture def vcs_config_dict(): return { 'name': 'git', 'commit_message': "Version updated to {{ new_v...
from django.conf.urls.defaults import patterns # noqa fr
om django.conf.urls.defaults import url # noqa from openstack_dashboard.dashboards.fogbow.usage import views from openstack_dashboard.dashboards.fogbow.u
sage.views import IndexView urlpatterns = patterns('', url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P<member_id>.*)/usage$', views.getSpecificMemberUsage, name='usage'), )
amework.exceptions import NotFound, ValidationError, PermissionDenied from modularodm import Q from modularodm.exceptions import NoResultsFound from api.base.exceptions import Gone from api.base import permissions as base_permissions from api.base.views import JSONAPIBaseView from api.comments.permissions import ( ...
ed and stringified, but we make no promises about the stringification output. So don't do that. To restore a deleted comment, issue a PATCH request against the `/links/self` URL, with `deleted: False`. ###Delete Method: DELETE URL: /link
s/self Query Params: <none> Success: 204 No Content To delete a comment send a DELETE request to the `/links/self` URL. Nothing will be returned in the response body. Attempting to delete an already deleted comment will result in a 400 Bad Request response. ##Query Params *Non...
from vsg.vhdlFile.extract import tokens def get_n_token_after_tokens(iToken, lTokens, lAllTokens, oTokenMap): lReturn = [] lIndexes = [] for oToken in lTokens: lTemp = oTokenMap.get_token_indexes(oToken) for iTemp in lTemp: iTokenIndex = iTemp for iCount in range(0...
oTokenMap.get_line_number_of_index(iIndex) lReturn.append(tokens.New(iIndex, iLine, [lAllTokens[iIndex]])) return lReturn
#!/usr/bin/en
v python3 number = 23 guess = int(input('Enter an integer : ')) if guess == number: # 新块从这里开始 print('Congratulations, you guessed it.') print('(but you do not win any pizzas!)') # 新块在这里结束 elif guess < number: # 另一代码块 print('No, it is a little higher than tha
t') # 你可以在此做任何你希望在该代码块内进行的事情 else: print('No, it is a little lower than that') # 你必须通过猜测一个大于(>)设置数的数字来到达这里 print('Done') # 这最后一句语句将在 # if 语句执行完毕后执行。
import os import re from conans.model import Generator from conans.paths import BUILD_INFO_VISUAL_STUDIO from conans.client.tools.files import VALID_LIB_EXTENSIONS class VisualStudioGenerator(Generator): template = '''<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.micro...
;{bin_dirs}</LocalDebuggerEnvironment> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> <ItemDefinitionGroup{condition}> <ClCompile> <AdditionalIncludeDirectories>$(ConanIncludeDirectories)%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <P
reprocessorDefinitions>$(ConanPreprocessorDefinitions)%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalOptions>$(ConanCompilerFlags) %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <AdditionalLibraryDirectories>$(ConanLibraryDirectories)%(AdditionalLibraryDirectories)</Ad...
'url': url, } db_query(self.db, 'INSERT OR REPLACE INTO build_res (repo, num, builder, res, url, merge_sha) VALUES (?, ?, ?, ?, ?, ?)', [ self.repo_label, self.num, builder, res, url, self.merge_sha, ]) def build...
ommit remained in the history, you can safely reset HEAD to {}. This is possibly due to protected branches, which forbids force-pushing. You are advised
to turn off protected branches, or disable certain Homu features that require force-pushing, such as linear history or auto-squashing. [ci skip]'''.format(self.num, self.merge_sha) def inner(): # `merge()` will return `None` if the `head_sha` commit is already part of the `base_ref` branch...
__author__ = 'Fabrizio Lungo<fab@lungo.co.uk>' import os import yaml from __exceptions__.FileNotFound import FileNotFound from section import ConfigurationSection class Configuration(ConfigurationSection): def __init__(self, fn='config.yml', name=None, crea
te=False): self._fn = fn self._create = create self.reload() if name is None: name=fn self._name = name def reload(self): if self._create and not os.path.exists(self._fn): self._config = {} elif os.path.exists(self._fn): wi...
raise FileNotFound(filename=self._fn) def save(self): with open(self._fn, "w") as f: yaml.dump(self._config, f)
cla
ss Solution(object): def missingNumber(self, nums):
""" :type nums: List[int] :rtype: int """ xor = len(nums) for i, n in enumerate(nums): xor ^= n xor ^= i return xor inputs = [ [0], [1], [3,0,1], [9,6,4,2,3,5,7,0,1] ] s = Solution() for i in inputs: print s.missing...
eek, NextWeek, ThisMonth, LastMonth, NextMonth) from stoqlib.gui.test.uitestutils import GUITest from stoqlib.lib.defaults import get_weekday_start from stoqlib.lib.introspection import get_all_classes class TestDateOptions(unittest.TestCase): def setUp(self): ...
self.assertEquals(column._format_func(obj, True), u"\u221E") class TestSearchGeneric(DomainTest): """Generic tests for searches""" # Those are base classes for other s
earches, and should not be instanciated ignored_classes = [
# -*- coding: utf-8 -*- """ Production settings file for project 'project' """ from project.settings import * DEBUG = False SITE_DOMAIN = 'sveetch.github.io/Sveetoy' # Directory where all stuff will be builded PUBLISH_DIR = os.path.join(PROJECT_DIR, '../docs') # Path where will be moved all the static files, usually...
)
from pudzu.charts import * df = pd.read_csv("datasets/flagstriband.csv") df = pd.concat([pd.DataFrame(df.colours.apply(list).tolist(), columns=list("TMB")), df], axis=1).set_index("colours") FONT, SIZE = calibri, 24 fg, bg = "black", "#EEEEEE" default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a4...
size, bg), 0.3) return flaglabel def grid(middle): ms = df[df.M == middle] colors = "".join(COLORS).replace(middle,"") array = [[dict(ms.loc[b+middle+t][["name", "description", "flag"]]) for b in colors] for t in colors] data = pd.DataFrame(array, index=list(colors), columns=list(colors)) grid ...
_label=lambda row: label(data.index[row], (100, H)), col_label=lambda col: label(data.columns[col], (W,100)), corner_label=label(middle, (100,100))) return grid PAD = 100 grids = list(generate_batches([grid(c) for c in COLORS], 2)) grid = Image.from_array(grids, padding=(PAD,PAD//2), bg=bg) title = Image.from_co...
# -*- coding: utf-8 -*- # # gPodder - A media aggregator and podcast client # Copyright (c) 2005-2014 Thomas Perl and the gPodder Team # # gPodder 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...
s/list/([1-9][0-9]*)\.xml') # This matches the flash player's configuration. It's a JSON, but it's always malformed DATA_CONFIG_RE = re.compile(r'flashvars=.*config=(http.*\.js)', re.IGNORECASE) # This matches the actual MP4 url, inside the "JSON" DATA_CONFIG_DATA_RE = re.compile(r'http[:/\w.?&-]*\.mp4') # This matches...
le(r'<url>(http:.+\.jpg)</url>') class EscapistError(BaseException): pass def get_real_download_url(url): video_id = get_escapist_id(url) if video_id is None: return url web_data = get_escapist_web(video_id) data_config_frag = DATA_CONFIG_RE.search(web_data) if data_config_frag is None:...
(isinstance(res, AtomGroup)) (AAN_part, res_part) = self._match_residues(AAN['2'], res) # for NME if next_aa is not None: if next_aa.has_atom('C'): AAN_part.set_atom('C2', AAN['1']['C']) res_part.set_atom('C2', next_aa['C']) if next_aa.has...
position=Position(0.93818, -0.44696, -0.35051))) ethane.set_atom('C2', Atom(symbol='C', name='C2', position=Position(0.00000, 0.00000, 1.47685))) ethane.set_atom('H21', Atom(symbol='H', name='H21', position=Positi
on(-0.93818, 0.44696, 1.82736))) ethane.set_atom('H22', Atom(symbol='H', name='H22', position=Position(0.85617, 0.58901, 1.82736))) ethane.set_atom('H23', Atom(symbol='H', name='H23', position=Position(0.08202, -1.03597, 1.82736))) ...
self.assertCountEqual(trek.services, []) @skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only') def test_deleted_pois(self): p1 = PathFactory.create(geom=LineString((0, 0), (4, 4))) trek = TrekFactory.create(paths=[p1]) poi = POIFactory.create(paths...
def test_pois_is_not_ordered_by_progression(self): self.trek = TrekFactory.create(geom=LineString((0, 0)
, (8, 8))) self.trek_reverse = TrekFactory.create(geom=LineString((6.4, 6.4), (0.8, 0.8))) self.poi1 = POIFactory.create(geom=Point(3.2, 3.2)) self.poi2 = POIFactory.create(geom=Point(1.2, 1.2)) self.poi3 = POIFactory.create(geom=Point(4, 4)) pois = self.trek.pois self...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-20 23:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.
deletion class Migration(migrations.Migration): dependencies = [ ('authentication', '0003_aut
o_20160620_2027'), ('feed', '0005_auto_20160620_1547'), ] operations = [ migrations.AddField( model_name='post', name='author', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='authentication.Profile'),...
ort HTTMock from django_dynamic_fixture import G, N from postnl_checkout.contrib.django_postnl_checkout.models import Order from .base import PostNLTestMixin class OrderTests(PostNLTestMixin, TestCase): """ Tests for Order model. """ maxDiff = None def setUp(self): super(OrderTests, self).setU...
'Consument': { 'GeboorteDatum': datetime.datetime(1977, 6, 15, 0, 0), 'ExtRef'
: u'jjansen', 'TelefoonNummer': u'06-12345678', 'Email': u'j.jansen@e-id.nl' }, 'Facturatie': { 'Adres': { 'Huisnummer': u'1', 'Initialen': u'J', 'Geslacht': u'Meneer', ...
# bibliography.py r''' Defines the BibItem() and Bibliography() classes (both sub-classed from Node) The Bibliography() object is initialized directly from a .bib file using the `bibtexparser` package. We use registry.ClassFactory for unlisted fields ''' import os import logging log = logging.getLogger(__name__) i...
Factory from .command import Command from .content import Text class BibItem(Command): def __init__(self, citation_key=None): Comman
d.__init__(self) self.citation_key = citation_key def __repr__(self): if self.citation_key: return '{}:{}({})'.format(self.genus, self.species, self.citation_key) return '{}:{}()'.format(self.genus, self.species) def harvard_dict(self): ''' Create a dictiona...
import yaml header=""" <?x
ml version="1.0" encoding="UTF-8"?> <MemInfo Version="1" Minor="
0"> <Processor Endianness="Little" InstPath="design/cortex"> <AddressSpace Name="design_1_i_microblaze_0.design_1_i_microblaze_0_local_memory_dlmb_bram_if_cntlr" Begin="0" End="8191"> <BusBlock> """ footer=""" </BusBlock> </AddressSpace> </Processor> <Config> ...
import pytest import salt.states.openvswitch_port as openvswitch_port from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {openvswitch_port: {"__opts__": {"test": False}}} def test_present(): """ Test to verify that the named port exists on bridge, even...
on bridge br-salt.", "old": "No port named salt present.", }, }, } ) assert openvswitch_port.present(name, bridge) == ret with patch.dict( openvswitch_port.__salt__, { "openvswitch.bridge_exists": moc...
openvswitch.port_list": mock_n, "openvswitch.port_add": mock, "openvswitch.interface_get_options": mock_n, "openvswitch.interface_get_type": MagicMock(return_value=""), "openvswitch.port_create_gre": mock, "dig.check_ip": mock, }, ): comt =...
# Handy for debugging setup.py """Utilities creating reusable, DRY, setup.py installation scripts Typical usage in setup.py: >>> global_env, local_env = {}, {} >>> execfile(join('pug', 'setup_util.py'), global_env, local_env) >>> get_variable = local_env['get_variable'] """ import os def s...
'):
if keyword in line: if '"' in line: return line.split('"')[1] elif "'" in line: return line.split("'")[1]
permissions = ("cloudWatch:PutMetricData",) retry = staticmethod(get_retry(('Throttling',))) BUFFER_SIZE = 20 @staticmethod def select(metrics_selector): if not metrics_selector: return NullMetricsOutput # Compatibility for boolean configuration if isinstance(metr...
for f in files: key = "%s/%s%s" % ( self.key_prefix, self.date_path, "%s/%s" % ( root[len(self.root_dir):], f)) key = key.strip('/') self.transfer.
upload_file( os.path.join(root, f), sel
#!/usr
/bin/env python import sys urllib_urlretrieve = None try: # Python 3.x or later import urllib.request urllib_urlretrieve = urllib.request.urlretrieve except ImportError: # Python 2.x import urllib urllib_urlretrieve = urllib.urlretrieve def download(url, target_path): urllib_urlretrieve...
path = sys.argv[2] download(url, target_path)
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import Cont
actHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox(capabilities={"marionette": False}, firefox_binary="C:/Program Files/Mozilla Firefox/firefox.exe") elif browser == "chrome": self.wd = webdriver.Chrome()...
raise ValueError("Unrecognized browser %s" % browser) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self) self.base_url = base_url def is_valid(self): try: self.wd.current_url return True ...
nova.policies import keypairs as kp_policies class KeypairController(wsgi.Controller): """Keypair API controller for the OpenStack API.""" _view_builder_class = keypairs_view.ViewBuilder def __init__(self): super(KeypairController, self).__init__() self.api = compute_api.KeypairAPI() ...
uery_schema_v275, '2.75') @validation.query_schema(keypairs.index_query_schema_v235, '2.35', '2.74') @wsgi.expected_errors(400) def index(self, req):
user_id = self._get_user_id(req) return self._index(req, key_type=True, user_id=user_id, links=True) @wsgi.Controller.api_version("2.10", "2.34") # noqa @validation.query_schema(keypairs.index_query_schema_v210) @wsgi.expected_errors(()) def index(self, req): # noqa # handle ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 dl1ksv. # # SPDX-License-Identifier: GPL-3.0-or-later # from gnuradio import gr, gr_unittest from PyQt5 import Qt import sip # from gnuradio import blocks try: from display import text_msg except ImportError
: import os import sys dirname, filename = os.path.split(os.path.abspath(__file__)) sys.path.append(os.path.join(dirname, "bindings")) from display import display_text_msg class qa_display_text_msg(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self)...
QWidget) def test_001_descriptive_test_name(self): # set up fg self.tb.run() # check data if __name__ == '__main__': gr_unittest.run(qa_display_text_msg)
akelists(mock_pack, 'groovy') self.assertTrue('project(foo)' in result, result) self.assertTrue('find_package(catkin REQUIRED)' in result, result) mock_pack.catkin_deps = ['bar', 'baz'] result = create_cmakelists(mock_pack, 'groovy') self.assertTrue('project(foo)' in result, res...
os.path.join(rootdir, 'CMakeLists.txt') file2 = os.path.join(rootdir, PACKAGE_MANIFEST_FILENAME) create_package_files(rootdir, pack, 'groo
vy') self.assertTrue(os.path.isfile(file1)) self.assertTrue(os.path.isfile(file2)) pack_result = parse_package(file2) self.assertEqual(pack.name, pack_result.name) self.assertEqual(pack.package_format, pack_result.package_format) self.assertEqual(...
#!/usr/bin/env python # encoding: utf-8 import glob import os import subprocess ''' Convert 23andMe files to PLINK format ''' def twenty3_and_me_files(): """Return the opensnp files that are 23 and me format""" all_twenty3_and_me_files= glob.glo
b('../opensnp_datadump.current/*.23andme.txt') fifteen_mb = 15 * 1000 * 1000 non_junk_files = [path for path in all_twenty3_and_me_files if os.path.getsize(path) > fifteen_mb] return non_junk_files def run_plink_format(usable_files): """Reformat the 23andMe files into plink binary stuff""" for f in usable_files:...
+ "ID" + gid + "I 1" call += " --out ../plink_binaries/" + gid print "convert gid " + gid subprocess.call(call,shell=True) usable_files = twenty3_and_me_files() run_plink_format(usable_files)
# -*- coding: utf-8 -*- """ Contains data that initially get added to the database to bootstrap it. """ from __future__ import unicode_literals # pylint: disable=invalid-name prophet_muhammad = { 'title': u'Prophet', 'display_name': u'النبي محمد (صلى الله عليه وآله وسلم)'.strip(), 'full_name': u'محمد بن...
لفتح", u"الحجرات", u"ق", u"الذاريات", u"الطور", u"النجم", u"الق
مر", u"الرحمن", u"الواقعة", u"الحديد", u"المجادلة", u"الحشر", u"الممتحنة", u"الصف", u"الجمعة", u"المنافقون", u"التغابن", u"الطلاق", u"التحريم", u"الملك", u"القلم", u"الحاقة", u"المعارج", u"نوح", u"الجن", u"المزمل", u"المدثر", u"القيامة"...
class Solution(object): def checkPossibility(self, n
ums): """ :type nums: List[int] :rtype: bool """ n = len(nums) t = 0 for i in xrange(n-1): if nums[i] > nums[i+1]: if i-1 < 0 or i+2 > n-1: t += 1 elif nums[i-1] <= nums[i+1]: t +=...
1 else: return False return True if t <= 1 else False
Mock import pytest from pants.base.exceptions import ResolveError from pants.build_graph.address import Address from pants.engine.fs import ( EMPTY_DIRECTORY_DIGEST, Digest, FileContent, InputFilesContent, Workspace, ) from pants.engine.interactive_runner import InteractiveProcessRequest, Interact...
return InteractiveProcessRequest( argv=("/usr/bin/python", "program.py",), run_in_workspace=False, input_files=digest, ) def run_test_rule( self, *, test_runner: Type[TestRunner], t
argets: List[HydratedTargetWithOrigin], debug: bool = False, ) -> Tuple[int, str]: console = MockConsole(use_colors=False) options = MockOptions(debug=debug, run_coverage=False) interactive_runner = InteractiveRunner(self.scheduler) workspace = Workspace(self.scheduler) ...
#!/usr/bin/env python2.7 import logging import num
py as np from .analysis import Analysis class HopCountAnalysis(Analysis): def __init__(self, scenario, locati
on, repetitions, csv): Analysis.__init__(self, scenario, location, "hopCount", repetitions, csv) self.logger = logging.getLogger('baltimore.analysis.HopCountAnalysis') self.logger.debug('creating an instance of HopCountAnalysis for scenario %s', scenario) self.data_min = {} sel...
or arg in args: fixed_parts = [] if arg.startswith("$<BUILD_INTERFACE:"): arg = arg[len("$<BUILD_INTERFACE:"): -1] parts = rex.split(arg) for part in parts: if part.startswith("${"): name = part[2:-1].lower() if name in variables:...
dataengine.h dataenginemanager.h delegate.h dialog.h extender.h extenderitem.h paintutils.h panelsvg.h plasma.h plasma_export.h popupapplet.h querymatch.h runnercontext.h runnermanager.h service.h servicejob.h svg.h theme.h tooltipmanager.h ...
(plasma_LIB_INCLUDES ${plasma_LIB_INCLUDES} glapplet.h) endif(QT_QTOPENGL_FOUND AND OPENGL_FOUND) install(FILES ${plasma_LIB_INCLUDES} DESTINATION ${INCLUDE_INSTALL_DIR}/plasma COMPONENT Devel) install(FILES widgets/checkbox.h widgets/combobox.h widgets/flash.h widgets/frame.h ...
import os import re im
port cmd import sys import time import util host = sys.argv[1] cmd.ru
n ("virsh shutdown %s"%(host)) while util.vm_is_running(host): time.sleep(1)
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C)
2017 Lenovo, Inc. # # 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 3 of the License, or # (at your option) any later version. # # Ansible is distribu...
License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status'...
import os import unittest from conans.client.cache.cache import CONAN_CONF from conans.client.conf import ConanClientConfigParser from conans.paths import DEFAULT_PROFILE_NAME from conans.test.utils.test_files import temp_folder from conans.util.files import save default_client_conf = '''[storage] path: ~/.conan/data...
ual(None, config.proxies) save(os.path.
join(tmp_dir, CONAN_CONF), "[proxies]") config = ConanClientConfigParser(os.path.join(tmp_dir, CONAN_CONF)) self.assertNotIn("no_proxy", config.proxies) save(os.path.join(tmp_dir, CONAN_CONF), "[proxies]\nno_proxy=localhost") config = ConanClientConfigParser(os.path.join(tmp_dir, CONAN_C...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, filter_strip_join from frappe.website.website_generator import WebsiteGenerator from frappe.contacts.addres...
ner_name) super(SalesPartner, self).validate() if self.partner_website and not self.partner_website.startswith("http"): self.partner_website = "http://" + self.partner_website def get_context(self, context): address = frappe.db.get_value("Address", {"sales_partner": self.name, "is_primary_address": 1}, ...
ty_state, address.pincode, address.country] context.update({ "email": address.email_id, "partner_address": filter_strip_join(address_rows, "\n<br>"), "phone": filter_strip_join(cstr(address.phone).split(","), "\n<br>") }) return context
gment_assembler del fragment_assembler[stream_id] else: # append data to stream fragment_assembler[stream_id][2] += data #print repr(fragment_assembler[stream_id][2]) else: # start stream, if not existing data_arr = [src, dst, data] fragment_assembler[stream_id] = data_arr def send_datas...
eam(qout, 4, 4, "BEGINFILE " + filename + " " + varname) # send filecontent (sould be chunked into multiple streams, but would need reassembling on layer5) # note: The client has to read (and recognize) ASCII based header and footer streams, but content could be in binary form
if content == None: send_datastream(qout, 4, 3, "Error on getfile: No file content read") else: #send_datastream(qout, 4, 4, content) streamchunksize=600 for chunk in chunks(content, streamchunksize): send_datastream(qout, 4, 4, chunk) # send footer send_datastr...
bundle_5 = Bundle(data={'time': None}) field_5 = TimeField(attribute='created', null=True) field_5.instance_name = 'time' self.assertEqual(field_5.hydrate(bundle_5), None) class DateFieldTestCase(TestCase): fixtures = ['note_testdata.json'] def test_init(self): field_1 ...
ual(field_1.full, False) self.assertEqual(field_1.readonly, False) self.assertEqual(field_1.help_text, 'A single related resource. Can
be either a URI or set of nested resource data.') field_2 = ToOneField(UserResource, 'author', null=True, help_text="Points to a User.") self.assertEqual(field_2.instance_name, None) self.assertEqual(issubclass(field_2.to, UserResource), True) self.assertEqual(field_2.attribute, 'autho...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.gis.geos import geometry from PIL import Image from PIL.ExifTags import TAGS from ..util import point_from_exif class Migration(DataMigr...
= { u'photomap.photo': { 'Meta': {'object_name': 'Photo'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100
'}), 'location': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True'}) } } complete_apps = ['photomap'] symmetrical = True
#Licensed to the Apache Software Foundation (ASF) under one #or more contributor license agreements. See the NOTICE file #distributed with this work for additional information #regarding copyright ownership. The ASF licenses this file #to you under the Apache License, Version 2.0 (the #"License"); you may not use thi...
permissions and #limitations under the License. """Gold Allocation Manager Implementation""" # -*- python -*- import sys, httplib import sha, base64, hmac import xml.dom.minidom from hodlib.Common.util import * class goldAllocationManager: def __init__(self, cfg, log): self.__GOLD_SEC
RET_KEY_FILE = cfg['auth-file'] (self.__goldHost, self.__goldPort) = (cfg['allocation-manager-address'][0], cfg['allocation-manager-address'][1]) self.cfg = cfg self.log = log def getQuote(self, user, project, ignoreErrors=True): # Get Secret Key from File ...
"""Tests for two-process terminal frontend Currently only has the most simple test possible, starting a console and running a single command. Authors: * Min RK """ #----------------------------------------------------------------------------- # Imports #---------------------------------------
-------------------------------------- import sys import time import nose.tools as nt from nose import SkipTest import IPython.testing.tools as tt from IPython.testing import decorators as dec from IPython.utils import py3compat #--
--------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- @dec.skip_win32 def test_console_starts(): """test that `ipython console` starts a terminal""" from IPython.external import pexpect args = ...
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
attr(self, attr) if isinstance(value, list): result[attr] = list(map
( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lamb...
# Copyright 2021 Alfredo de la Fuente - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged @tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def setUpClass(cls): sup...
cls.skill_filipino = cls.env.ref('hr_skills.hr_skill_filipino') cls.skill_type_lang.skill_language = True cls.skill_spanish.code = 'SP' cls.skill_filipino.code = 'FI' def test_event_name_code_year_id(self): vals = {'name': 'User for event lang level', 'date_begin...
'lang_id': self.skill_spanish.id} event = self.event_obj.create(vals) name = 'SP-{}-2025'.format(event.id) self.assertEqual(event.name, name) vals = {'date_begin': '2024-01-06 08:00:00', 'lang_id': self.skill_filipino.id} event.write(vals) name ...
import traceback from sqlalchemy import Column, Boolean, Integer, String, ForeignKey, create_engine from sqlalchemy.orm import relationship, sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('sqlite:///bag_of_holding.db') Base.metadata...
on = Session() class UserManager: def build_db(self): Base.metadata.create_all(engine) def add_user(self, user_name): """ Create a new user :return: """ def remove_user(self, user_name): """ Remove a current user :param user_name: :...
): """ Add a service profile to a user_name :param user_name: :param service_name: :return: """ def remove_user_profile(self, user_name, service_id): """ remove a service profile from a user_name :param user_name: :param service_id: ...
def get_encrypted_char(k, ascii_val, ascii_list, limit): diff = k % 26 rotate_val = ascii_val + diff encrypted_char = '' if rotate_val not in ascii_list: rotate_val -= limit for i in ascii_list: rotate_val -= 1 if rotate_val == 0: encrypted_char +=...
scii_list if ascii_val in upper_ascii_list: limit = upper_case_limit ascii_list = upper_ascii_list encrypted_string += get_encrypted_char(k, ascii_val, ascii_list, limit) else: encrypted_string...
return encrypted_string l = raw_input() s = raw_input() k = int(raw_input()) print encrypt(s, k)
# -*- coding: utf-8 -*- # © 2015 Compassion CH (Nicolas Tran) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class AccountPaymentOrder(models.Model): _inherit = 'account.payment.order' @api.multi def open2generated(self): """ Replace act...
countPaymentOrder, self).open2generated()
if self.payment_method_id.code == 'sepa_credit_transfer': upload_obj = self.env['payment.order.upload.sepa.wizard'] attachment_id = action['res_id'] upload_wizard = upload_obj.create({ 'attachment_id': attachment_id, 'payment_order_id': self.id, ...
from flask import Blueprint, render_template, redirect, url_for from flask_blog.extensions import mongo from flask_blog.helpers import convertToObj from flask.ext.login import login_re
quired, current_user from forms import PostsForm posts = Blueprint('posts', __name__, template_folder='templates', static_folder='static', static_url_path='/%s' % __name__) @posts.route("/posts") @login_required def list(): posts = mongo.db.posts.find() return render_template('posts_list.ht...
posts/add", methods=['GET', 'POST']) @login_required def add(): form = PostsForm() if form.validate_on_submit(): mongo.db.posts.insert(_add_username(form.data)) return redirect(url_for("posts.list")) return render_template('post_add.html', form=form) @posts.route("/posts/get/<ObjectId:id>")...
# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of Logilab-Common. # # Logilab-Common is free software: you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as publ...
def __call__(self, *args, **kwargs): return 0 def _2_(*args, **kwargs): return 2 class SelectorsTC(TestCase): def test_basic_and(self): selector = _1_() & _1_() self.assertEqual(selector(None), 2) selector = _1_() & _0_() self.assertEqual(selector(None), 0) sel...
sic_or(self): selector = _1_() | _1_() self.assertEqual(selector(None), 1) selector = _1_() | _0_() self.assertEqual(selector(None), 1) selector = _0_() | _1_() self.assertEqual(selector(None), 1) selector = _0_() | _0_() self.assertEqual(selector(None), 0...
# /usr/bin/env python import os # Context manager class cd: """ Context manager f
or safely changing the current working directory """ def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir
(self.savedPath)
] = {'buffer_length' : 60.,} info['subdevices'] = [ ] info['subdevices'].append(create_analog_subdevice_param(_channel_names)) quality_name = ['Quality {}'.format(n) for n in _channel_names] info['subdevices'].append(create_analog_subdevice_param(quality_name)) info['subdevices'].append(create_analo...
= f.readline().strip() if serial not in serials: serials[serial] = [ ] seri
als[serial].append(name) except IOError as e: print "Couldn't open file: %s" % e for serial, names in serials.items(): device_path = '/dev/'+names[1] info = get_info(device_path) devices['Emotiv '+device_path] = info ...
import json import pathlib import re import pytest import snafu.versions version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir()) version_names = [p.stem for p in version_paths] @pytest.mark.parametrize('path', version_paths, ids=version_names) def test_version_definitions(path): assert path.suffix ==...
-32', False, {'3.6-
32'}), ('3.4', False, {'3.4'}), ('3.4', True, {'3.4'}), ]) def test_script_version_names(name, force_32, result): version = snafu.versions.get_version(name, force_32=force_32) assert version.script_version_names == result def test_is_installed(tmpdir, mocker): mock_metadata = mocker.patch.object(s...
imp
ort json from os.path import join, dirname from jsonschema import validate SCHEMA_FILE = "normandy-schema.json" def assert_valid_schema
(data): schema = _load_json_schema() return validate(data, schema) def _load_json_schema(): relative_path = join("schemas", SCHEMA_FILE) absolute_path = join(dirname(__file__), relative_path) with open(absolute_path) as schema_file: return json.loads(schema_file.read())
ce: - `inputs`: (structure of) Tensors and TensorArrays that is passed as input to the RNN cell composing the decoder, at each time step. - `state`: (structure of) Tensors and TensorArrays that is passed to the RNN cell instance as the state. - `memory`: tensor that is usually the full output of...
nd TensorArrays, `next_inputs` is the tensor that should be used as input for the next step, `finished` is
a boolean tensor telling whether the sequence is complete, for each sequence in the batch. """ raise NotImplementedError def finalize(self, outputs, final_state, sequence_lengths): raise NotImplementedError @property def tracks_own_finished(self): """Describes...
# author : Etienne THIERY from matgen import * import random import numpy def test_symmetricPositiveDefinite(): for i in range(10): print(".", end="", flush=True) size = random.randint(400, 500) maxVal = random.randint(0, 1000) M = symmetricPositiveDefinite(size, maxVal) if...
f test_symmetricSparsePositiveDefinite(): for i in range(10): print(".", end="", flush=True) size = random.randint(400, 500) maxVal = rand
om.randint(0, 1000) nbZeros = random.randint(0, size*(size-1)) M = symmetricSparsePositiveDefinite(size, nbZeros, maxVal) if not (isSymmetric(M) and isDefinitePositive(M) and abs(numberOfZeros(M)-nbZeros) <= 1): return False return True def numberOfZeros(M): count = 0 fo...
# -*- coding: utf-8 -*- # # HelixMC documentation build configuration file, created by # sphinx-quickstart on Thu Mar 21 15:51:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
h Chou', 'manual' )] # The name of an image file (relative to this directory) to place at the top of # the title page. latex_logo = '_static/logo.png' # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal l...
an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). ma...
from syzoj.mo
dels import JudgeState from syzoj import db db.create_all() all_judge = JudgeState.query.all() for item in all_judge: item.update_usera
c_info()
import subprocess as Subprocess import pymel.all as pm class CapsDisabler(object): def __init__(self, parentRef, go=False): self.parentRef = parentRef self.ini = self.parentRef.ini sel
f.conf = self.ini.conf self.enabled = False
self.autohotkeyProcess = None if go==True: self.go() def go(self): try: if int( self.ini.getItem("disable_capslock") ) == 1: self.enabled = True else: #print("Hotkeys not enabled....
from yowsup.structs import ProtocolEntity, ProtocolTreeNode class IqProtocolEntity(ProtocolEntity): ''' <iq type="{{get | set}}" id="{{id}}" xmlns="{{xmlns}}" to="{{TO}}" from="{{FROM}}"> </iq> ''' TYPE_SET = "set" TYPE_GET = "get" TYPE_ERROR = "error" TYPE_RESULT = "result" TYPE_D...
full else self._from.split('@')[0] def getTo(self): return self.to def toProtocolTreeNode(self): attribs = { "id" : self._id, "type" : self._type
} if self.xmlns: attribs["xmlns"] = self.xmlns if self.to: attribs["to"] = self.to elif self._from: attribs["from"] = self._from return self._createProtocolTreeNode(attribs, None, data = None) def __str__(self): out = "Iq:\n" ...
import unittest from tito.buildparser import BuildTargetParser from ConfigParser import ConfigParser from tito.exception import TitoException class BuildTargetParserTests(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.valid_branches = ["branch1", "branch2"] self...
"invalid-branch:project-x.y.z-candidate") parser = BuildTargetParser(self.releasers_config, self.rele
ase_target, self.valid_branches) self.assertRaises(TitoException, parser.get_build_targets) def test_missing_semicolon_raises_exception(self): self.releasers_config.set(self.release_target, "build_targets", "invalid-branchproject-...
from django.forms.formsets import BaseFormSet, formset_factory from django.forms.models import BaseModelFormSet from django.forms.models import modelformset_factory from django import forms from models import PlanillaHistoricas, ConceptosFolios, Folios, Tomos class PlanillaHistoricasForm(forms.Form): codi_empl_pe...
campos[codigo] = 1 index = campos[codigo] flag = '_%s' % index self.fields['%s%s' % (codigo, flag)] = forms.CharField(widget=forms.TextInput(attrs=attrs)) self.fields['codigos'] = forms.Ch
arField(max_length=700, widget=forms.HiddenInput()) class BasePlanillaHistoricasFormSet(BaseFormSet): def __init__(self, *args, **kwargs): self.concepto = kwargs['concepto'] del kwargs['concepto'] super(BasePlanillaHistoricasFormSet, self).__init__(*args, **kwargs) def _construct_form...
t in mount_result.splitlines(): if mount_str in result: if options: options = options.split(",") options_result = result.split()[3].split(",") for op in options: if op not in options_result: if verbose: ...
ons=None, verbose=False, session=None): """ Mount src under dst if
it's really mounted, then remout with options. :param src: source device or directory :param dst: mountpoint :param fstype: filesystem type need to mount :param options: mount options :param session: mount within the session if given :return: if mounted return True else return False """ ...
from injector import Module from cassandra.cqlengine import connection from cassandra.cluster import Cluster from cassandra.cqlengine.management import create_keyspace_simple, sync_table, sync_type from cassandra.cqlengine.usertype import UserType from ...entities.track_type import TrackType from cassandra_users_reposi...
ry, to=users_repository_instance)
spots_repository_instance = CassandraSpotsRepository(cluster, session) binder.bind(SpotsRepository, to=spots_repository_instance) runs_repository_instance = CassandraRunsRepository(cluster, session) binder.bind(RunsRepository, to=runs_repository_instance) checkpoint_passes_rep...
import sys, math # **************** Main program ********************************************* def main(): # File IO ############################################### txt = open("in9.txt", 'r') N = int (txt.readline()) n = 2 * N a = [[0 for x in range(1)] for y in range(n)] ...
ppend(elem) print >> sys.stderr, "countONe:", countOne # print >> sys.stderr,"oneList:", oneList print >> sys.stderr, "Done Var init \n \n" # ------------------------------------------------------------- # Engine ------------------------------------------------...
node = oneList[i] level[i] = findSingleMaxLength(node, node, oneList, countOne, relationship, n) # ------------------------------------------------------------ # Report ------------------------------------------------- #--------------------------------------...
import time import sublime import sublime_plugin ST3 = int(sublime.version()) >= 3000 if ST3: from .view_collection im
port ViewCollection from .git_gutter_popup import show_diff_popup else: from view_collection import ViewCollection from git_gutter_popup import show_diff_popup def async_event_listener(EventListe
ner): if ST3: async_methods = set([ 'on_new', 'on_clone', 'on_load', 'on_pre_save', 'on_post_save', 'on_modified', 'on_selection_modified', 'on_activated', 'on_deactivated', ]) for att...
# Copyright (c) 2016 Cisco Systems # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
.obj['manager'] = aim_cfg.ConfigManager(aim_ctx, '') @config.comm
and(name='update') @click.argument('host', required=False) @click.pass_context def update(ctx, host): """Current database version.""" host = host or '' ctx.obj['manager'].to_db(ctx.obj['conf'], host=host) @config.command(name='replace') @click.argument('host', required=False) @click.pass_context def repla...