prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python3
"""
URL: | http://docs.graphene-python.org/en/latest/types/enums/
"""
import graphene
class Episode(graphene.Enum):
NEWHOPE = 4
EMPIRE = 5
JEDI = 6
@property
def description(self):
if self == Episode.NEWHOPE:
return 'New Hope Episode'
return 'O | ther episode'
|
#
# Copyright (C) 2013-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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... | ##########################
# Warmup Integration #
######### | ####################################################
print("""
Start warmup integration:
At maximum {} times {} steps
Stop if minimal distance is larger than {}
""".strip().format(warm_n_times, warm_steps, min_dist))
# minimize energy using min_dist as the convergence criterion
system.integrator.set_steepest_descent(... |
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class Pose3DOF(genpy.Message):
_md5sum = "646ead44a0e6fecf4e14ca116f12b08b"
_type = "hrl_lib/Pose3DOF"
_has_header = True #flag ... | args or kwds:
super(Pose3DOF, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.header is None:
self.header = std_msgs.msg.Header()
if self.x is None:
self.x = 0.
if self.y is None:
self.y = 0.
if se... | self.header = std_msgs.msg.Header()
self.x = 0.
self.y = 0.
self.theta = 0.
self.dt = 0.
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``... |
3'}
assert data[1] == {'Column1': 'data4', 'Column_2': 'data5', 'Column_3': 'data6'}
assert data[2] == {'Column1': 'data 7', 'Column_2': '', 'Column_3': 'data 9'}
assert data[3] == {'Column1': 'data10', 'Column_2': '', 'Column_3': ''}
# Test that if we search for trailing data that is always fo... | M2_PE_START|LVM2_PV_SIZE|LVM2_PV_FREE|LVM2_PV_USED|LVM2_PV_ATTR|LVM2_PV_ALLOCATABLE|LVM2_PV_EXPORTED|LVM2_PV_MISSING|LVM2_PV_PE_COUNT|LVM2_PV_PE_ALLOC_COUNT|LVM2_PV_TAGS|LVM2_PV_MDA_COUNT|LVM2_PV_MDA_USED_COUNT|LVM2_PV_BA_START|LVM2_PV_BA_SIZE|LVM2_PV_IN_USE|LVM2_PV_DUPLICATE|LVM2_VG_NAME
WARNING: Locking disabled. B... | ""
address,port,state,read-only
0.0.0.0,3000,LISTEN,N
10.76.19.184,37500,ESTAB,Y
""".strip()
POSTGRESQL_LOG = """
schema | table | rows
public | rhnsnapshotpackage | 47428950
public | rhnpackagefile | 32174333
public | rhnpackagecapability | 12934215... |
"""Screen database."""
import redis_client
import control
import re
from twisted.internet import defer
class ScreenDB(object):
"""A screen database."""
def __init__(self):
"""Default constructor."""
pass
def set_mode(self, screen, mode):
redis_client.connection.set('screen:{0}:mod... | .connection.get('screen:{0}:mode'.format(screenID))
host = yield redis_client.connection.get('screen:{0}:host'.format(screenID))
entries[screenID] = {'mode': mode,
'host' | : host}
defer.returnValue(entries)
screens = ScreenDB()
@control.handler('screen-list')
@defer.inlineCallbacks
def perform_screen_list(responder, options):
screen_list = yield screens.list()
for screen, settings in screen_list.iteritems():
if settings['host'] is None:
online_string... |
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import render, redirect
from django.views import generic
from common.models import Discipline, Performance
# renders index / home page
def index(request):
return redirect(reverse('tournaments.main'))
# renders todo page
def proces... | index')
| def disciplines_index(request):
context = { 'disciplines': Discipline.objects.all() }
return render(request, 'gymnastics/disciplines/index.html', context)
def discipline_detail(request, id, slug):
discipline = Discipline.objects.get(id=id)
streams = discipline.stream_set.all()
performances = disci... |
"""Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import Ba... | d=locality_element.text).exists():
Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id)
stop.locality_id = locality_element.text
stop.save()
def handle_file(self, archive, filename):
with archive.open(filename) as open_file:
iterato... | for _, element in iterator:
tag = element.tag[27:]
if tag == 'StopPoint':
self.handle_stop(element)
element.clear()
def handle(self, *args, **options):
for filename in options['filenames']:
with zipfile.ZipFile(... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.modules.events.contributions.models.fields import ContributionFi... | t_to_repr
class AbstractFieldValue(ContributionFieldValueBase):
"""Store a field values related to abstracts."""
__tablename__ = 'abstract_field_values'
__table_args__ = {'schema': 'event_abstracts'}
contribution_field_backref_name = 'abstract_values'
abstract_id = db.Column(
db.Integer,... | ),
index=True,
nullable=False,
primary_key=True
)
# relationship backrefs:
# - abstract (Abstract.field_values)
def __repr__(self):
text = text_to_repr(self.data) if isinstance(self.data, str) else self.data
return format_repr(self, 'abstract_id', 'contribution_... |
"""
Infobip Client API Libraries OpenAPI Specification
OpenAPI specification containing public endpoints supported in client API libraries. # noqa: E501
The version of the OpenAPI document: 1.0.172
Contact: support@infobip.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: ... | and the value is attribute type.
"""
return {
"to": (str,), # noqa: E501
"message_id": (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
" | to": "to", # noqa: E501
"message_id": "messageId", # noqa: E501
}
_composed_schemas = {}
required_properties = set(
[
"_data_store",
"_check_type",
"_spec_property_naming",
"_path_to_item",
"_configuration",
"_visite... |
ef done():
db.session.remove()
db.drop_all()
request.addfinalizer(done)
# set token storage
blueprint.storage = SQLAlchemyStorage(OAuth, db.session)
# make users and OAuth tokens for several people
alice = User(name="Alice")
alice_token = {"access_token": "alice123", "token_ty... | )
name = db.Column(db.String(80))
class OAuth(OAuthConsumerMixin, db.Model):
user_id = db.Column(db.Integer, db.ForeignKey(User.id))
| user = db.relationship(User)
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user)
db.create_all()
def done():
db.session.remove()
db.drop_all()
request.addfinalizer(done)
# create some users
u1 = User(name="Alice")
u2 = User(name="Bob")
u3... |
ssed and which can then be used by the program as it sees fit.
'''
import argparse # This module gives powerful argument parsing abilities along with auto-generation of --help output.
# Specify the various arguments that the program expects and validate them. Additional arguments can be added as required... | "-A", "--showAll", help | = "Flag: Show all emails in specified folder, not just unseen ones.", action = "store_true" )
parser.add_argument( "--showFlags", help = "Flag: Show mutt-style flags (in square brackets) to indicate new/unseen and deleted emails when ALL emails are displayed (i.e. -A is issued).", action = "store_true" )
pars... |
# coding=UTF-8
from django.shortcuts import redirect
from bellum.common.alliance import isAllied
from bellum.common.session.login import must_be_logged
from bellum.common.session import getAccount, getRace
from bellum.common.session.mother import getCurrentMother
from djangomako.shortcuts import render_to_response, ren... | dels import LandarmyProvintionalStrikeOrder
from bellum.orders.models import LandarmyPlanetaryStrikeOrder, LandarmyProvintionalStrikeOrder, LandarmyMotherPickupOrder
from bellum.space.ajax.pinfo | import dx_html
from bellum.common.fixtures.relocation import getRelocationTime
@must_be_logged
def process_onlyprovince(request, province_id):
try: # check planet
province_id = int(province_id)
province = Province.objects.get(id=province_id)
except:
return redirect('/')
return pr... |
#
# gPrime - A web-based genealogy program
#
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2012 Paul Franklin
#
# 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 versio... | er, style, extension, docoptclass, basedocname):
"""
:param name: A friendly name to call this plugin.
Example: "Plain Text"
:type name: string
:param description: A short description of the plugin.
Example: "This plugin will generate text documents in plain text.... | the BaseDoc
interface.
:type basedoc: BaseDoc
:param paper: Indicates whether the plugin uses paper or not.
True = use paper; False = do not use paper
:type paper: bool
:param style: Indicates whether the plugin uses styles or not.
True = use styles; F... |
import traceback
from PyQt5 import QtCore
import androguard.session as session
from androguard.core import androconf
import logging
log = logging.getLogger("androguard.gui")
class FileLoadingThread(QtCore.QThread):
file_loaded = QtCore.pyqtSignal(bool)
def __init__(self, parent=None):
QtCore.QThre... | ype)
self.start(QtCore.QThread.LowestPriority)
def run(self):
if self.incoming_file:
try:
file_path, file_type = self.incoming_file
if file_type in ["APK", "DEX", "DEY"]:
| ret = self.parent.session.add(file_path,
open(file_path, 'rb').read())
self.file_loaded.emit(ret)
elif file_type == "SESSION":
self.parent.session = session.Load(file_path)
self.file_loaded.em... |
from django.contrib import admin
from puzzle_captcha.models import Puzzle, PuzzlePiece
class PuzzlePieceInline(admin.StackedInline):
model = PuzzlePiece
readonly_fields = ('key', 'image', 'order')
can_delete = False
extra = 0
class PuzzleAdmin(admin.ModelAdmin):
| list_display = ('key', 'rows', 'cols')
readonly_fields = ('key', 'rows', 'cols')
class Meta:
model = Puzzle
inlines = [
PuzzlePieceInline,
]
admin.site.r | egister(Puzzle, PuzzleAdmin)
|
"""
02-read-from-disk-2.py - Catching the `end-of-file` signal from the SfPlayer object.
This example demonstrates how to use the `end-of-file` signal |
of the SfPlayer object to trigger another playback (possibly
with another sound, another speed, etc.).
When a SfPlayer reaches the end of the file, it sends a trigger
(more on trigger later) that the user can retrieve with the
syntax :
variable_name["trig"]
"""
from pyo import *
import random
s = Server().boot()
... | snds/"
sounds = ["alum1.wav", "alum2.wav", "alum3.wav", "alum4.wav"]
# Creates the left and right players
sfL = SfPlayer(folder + sounds[0], speed=1, mul=0.5).out()
sfR = SfPlayer(folder + sounds[0], speed=1, mul=0.5).out(1)
# Function to choose a new sound and a new speed for the left player
def newL():
sfL.path... |
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resour... | self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_flavor(self):
factory = self.replay_flight_data()
policy = {
'name': 'get-server-c7n-test-1',
'resource': 'openstack.server',
'filters': [
... | "flavor_name": "m1.tiny",
},
],
}
p = self.load_policy(policy, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0].name, "c7n-test-1")
def test_server_filter_tags(self):
fac... |
# This file is NOT licensed under the GPLv3, which is the license for the re | st
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial ... | rest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# TH... |
#!/usr/bin/python2.7 -u
import os.path
if os.path.isdir('/dev/null'):
print | '/dev/null'
if os.path.isdir('/dev'):
print | '/dev'
|
import ast
import logging
import time
import unittest
from malcolm.profiler import Profiler
# https://github.com/bdarnell/plop/blob/master/plop/test/collector_test.py
class ProfilerTest(unittest.TestCase):
def filter_stacks(self, results):
# Kind of hacky, but this is the simplest way to keep the tests
... | fail("collected data did not meet expectations")
def test_collector(self):
start = time.time()
def a(end):
while time.time() < end:
pass
c(time.time() + 0.1)
def b(end):
while time.time() < end:
pass
c(time.ti... | e.time() + 0.1)
b(time.time() + 0.2)
c(time.time() + 0.3)
end = time.time()
profiler.stop("profiler_test.plop")
elapsed = end - start
self.assertTrue(0.8 < elapsed < 0.9, elapsed)
with open("/tmp/profiler_test.plop") as f:
results = f.read()
c... |
# coding=utf-8
#! /usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
import mlpy
import sys
import math
from config import loc_store_path, times_day
class LocTrain(object):
"""
"""
def __init__(self, file_name , flag):
if flag == "ridge":
self.l... | def train(self):
self.get_input(self.file_name)
for weekday in range(7):
self.lrs[weekday].learn(self.x_weekday[weekday], self.y_weekday[weekday])
def predict(self,weekday,speeds):
pre_speed = self.lrs | [weekday].pred(speeds)
return pre_speed
def test(self):
pass
def get_input(self, filename):
fin = open(filename)
x = []
y = []
for each in fin:
each = each[:each.find('\n')]
l = each.split(' ')
each_x = ... |
# -*- coding: utf-8 | -*-
#
# Copyright 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied | , including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or ... |
g: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sy... | d
as additional properties values.
"""
allowed_values = {
("operator",): {
"NONE": "NONE",
"PLUS": "PLUS",
"MINUS": "MINUS",
"TIMES": "TIMES",
"DIVIDE": "DIVIDE",
"MODULUS": "MODULUS",
"POWER": "POWER",
... | L_TO": "NOT_EQUAL_TO",
"GREATER": "GREATER",
"LESS": "LESS",
"GREATER_OR_EQUAL": "GREATER_OR_EQUAL",
"LESS_OR_EQUAL": "LESS_OR_EQUAL",
"CONCATENATE": "CONCATENATE",
"CONDITIONAL": "CONDITIONAL",
},
("documentation_type",): {
... |
from _ | _future__ import absolute_import, unicode_literals
from .api.psd_image import PSDImage
from .composer import c | ompose
__all__ = ['PSDImage', 'compose']
|
# Copyright 2009-2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
__all__ = [
'BranchRevision',
]
from storm.locals import (
Int,
Reference,
Storm,
)
from zope.interface import implements
from l... | def __init__(self, branch, revision, sequence=None):
self.branch = branch
self.revision = revision
self.sequence | = sequence
|
#!/usr/bin/python
import os
import sys
import getopt
import shutil
import string
# Globals
quiet = 0
test = 0
comments = 0
sysfsprefix = "/sys/devices/system/rttest/rttest"
statusfile = "/status"
commandfile = "/command"
# Command opcodes
cmd_opcodes = {
"schedother" : "1",
"schedfifo" : "2",
"loc... | ]):
# Seperate status value
val = s[2:].strip()
query = analyse(val, testop, dat)
break
if query or cmd == "t":
break
progress(" " + status)
if not query:
... |
cmdnr = cmd_opcodes[opc]
# Build command string and sys filename
cmdstr = "%s:%s" %(cmdnr, dat)
fname = "%s%s%s" %(sysfsprefix, tid, commandfile)
if test:
print fname
continue
fcmd = open(fname, 'w')
fcmd.write(cmdstr... |
# -*- coding: utf- | 8; -*-
#
# @file urls.py
# @brief collgate
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2018-09-20
# @copyright Copyright (c) 2018 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details coll- | gate printer module url entry point.
from django.conf.urls import include, url
urlpatterns = [
]
|
from base import Cho | icesEnum
from _version import | __version__
|
ype, codename='test')
user.user_permissions.add(perm)
user.save()
# reloading user to purge the _perm_cache
user = User.objects.get(username='test')
self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True)
self.assertEqual(user.get_group_permissions(), s... | True
# This class also supports tests for anonymous user permissions,
# via subclasses which just set the 'supports_anonymous_user' attribute.
def has_perm(self, user, perm, obj=None):
if not obj:
return # We only support row level perms
| if isinstance(obj, TestObj):
if user.username == 'test2':
return True
elif user.is_anonymous() and perm == 'anon':
# not reached due to supports_anonymous_user = False
return True
return False
def has_module_perms(self, user, ap... |
"""Interfaces with iAlarm control panels."""
from homeassistant.components.alarm_control_panel import AlarmControlPanelEntity
from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
)
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.... | anufacturer="Antifurto365 - Meian",
name=self.name,
)
| @property
def unique_id(self):
"""Return a unique id."""
return self.coordinator.mac
@property
def name(self):
"""Return the name."""
return "iAlarm"
@property
def state(self):
"""Return the state of the device."""
return self.coordinator.state
... |
elf.host, self.port = host, port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
try:
self.sock.connect((self.host, self.port))
log.debug("%s connected to DataNode" % self)
return True
except Exception:
log.deb... | log.debug("Nr of chunks: %d", chunks_per_packet)
data_len = packet_len - 4 - chunks_per_packet * checksum_len
log.debug("Payload len: %d", data_len)
byte_stream.reset()
# Collect checksums
if check_crc:
checksums = [... | checksum = struct.unpack("!I", checksum)[0]
checksums.append(checksum)
else:
self._read_bytes(checksum_len * chunks_per_packet)
# We use a fixed size buffer (a "load") to read only a couple of chunks at once.
byte... |
shuffle: Whether or not to shuffle dataset.
seed: tf.int64 scalar tf.Tensor (or None). Used as shuffle seed for tf.data.
vocabulary: unused argument, maintains compatibility with other dataaset_fns
num_inference_examples: maximum number of examples per task to do inference
on. If None or less than 0, ... | not None:
raise ValueError(
"Setting a priming sequence length only makes sense for decoder-only "
"Tasks, which have `targets` but no `inputs`.")
eos_keys = set(
k for k, f i | n mixture_or_task.output_features.items() if f.add_eos)
logging.info(
"Padding '%s' with sequence lengths: %s", task.name, sequence_length)
ds = transformer_dataset.pack_or_pad(
ds,
sequence_length,
pack=False,
feature_keys=tuple(task.output_features),
ensure_eos... |
"""
This module contains the global configurations | of the framework
"""
#: This name suppose to be used for general meta decoration for functions,
#: methods or even clas | ses
meta_field = '_pyrsmeta'
|
import feedparser
import logging
from rss import sources
from util import date, dict_tool, tags
log = logging.getLogger('app')
def parse_feed_by_name(name):
feed_params = sources.get_source(name)
if not feed_params:
raise ValueError('There is no feed with name %s' % name)
source_name = feed_par... | dburner_origlink', 'link', assert_val=True)
published = date.utc_format(
dict_tool.get_alternative(entry, 'published', 'updated', assert_val=True)
)
description = dict_tool.get_alternati | ve(entry, 'summary', 'description', 'title', assert_val=True)
picture = dict_tool.get_deep(entry, 'gd_image', 'src')
text = dict_tool.get_deep(entry, 'content', 0, 'value')
author_name = handle_default_param(
entry,
dict_tool.get_deep(entry, 'authors', 0, 'name'),
default_author_nam... |
#!/usr/bin/python3
"""
Merges raw data from geneteka into larger json files.
"""
from collections import defaultdict
import html
import json
import os
import re
INPUT_DIR = 'data_raw'
OUTPUT_DIR = 'data'
def extractNotes(value):
match = re.search(r'i.png" title="([^"]*)"', value)
if match:
return (value.s... | (1)
# URL to metryki.genealodzy.pl where scans can be found.
match = re.search(r'href="([^"]*)">[^>]*s.png', stuff)
if match:
output['metryki_url'] = html.unescape(match.group(1))
# User that entered this record to the database.
match = re.search(r'uname=([^"]*)"', stuff)
if match:
output['user_en... | ed'] = match.group(1)
return output
def convertMarriageRecord(record):
# Unparsed column with various information.
stuff = record[9]
husbandLastName, husbandLastNameNotes = extractNotes(record[3])
wifeLastName, wifeLastNameNotes = extractNotes(record[6])
output = {
'year': record[0].strip(),
'r... |
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from pygments.lexers import PythonLex | er, BashLexer
from pygments.lexer import bygroups, using
from pygments.token import Keyword, Operator, Name, Text
#-----------------------------------------------------------------------------
# Classes
#--------------------------------------------------------- | --------------------
class IPythonLexer(PythonLexer):
name = 'IPython'
aliases = ['ip', 'ipython']
filenames = ['*.ipy']
tokens = PythonLexer.tokens.copy()
tokens['root'] = [
(r'(\%+)(\w+)\s+(\.*)(\n)', bygroups(Operator, Keyword, using(BashLexer), Text)),
(r'(\%+)(\w+)\b', bygroups... |
# j4cDAC test code
#
# Copyright 2011 Jacob Potter
#
# 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, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... | r 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/>.
import socket
import time
import struct
def pack_point(x, y, r, g, b, i = -1, u1 = 0, u2 = 0, flags = 0):
"""Pack some color values into a struct dac_point.
Values must be specified for x, y, r, g, and b. If a value is not
passed in for the other fields, i will default to max(r, g, b); th... |
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect
from django.utils.translation import gettext as _
from zerver.decorator import require_realm_admin
from zerver.lib.actions import do_change_icon_source
from zerver.lib.exceptions import JsonableErro... | > HttpResponse:
if len(request.FILES) != 1:
raise JsonableError(_("You must upload exactly one | icon."))
icon_file = list(request.FILES.values())[0]
if (settings.MAX_ICON_FILE_SIZE_MIB * 1024 * 1024) < icon_file.size:
raise JsonableError(
_("Uploaded file is larger than the allowed limit of {} MiB").format(
settings.MAX_ICON_FILE_SIZE_MIB,
)
)
... |
nvalid."
USER_LINK_EXPIRED_ERROR = "The link you used to create an account may have expired."
def has_validation_errors(data, field_name):
document = html.fromstring(data)
form_field = document.xpath('//input[@name="{}"]'.format(field_name))
return 'invalid' in form_field[0].classes or 'invalid' in form_... | alue = None
data_api_client.get_user.return_value = None
res = self.client.post(self.expand_path('/login'), data={
'email_address': 'valid@email.com',
'password': '1234567890',
'csrf_token': FakeCsrf.valid_token,
})
assert self.strip_all_whitespace("M... | strip_all_whitespace(res.get_data(as_text=True))
assert res.status_code == 403
def test_should_be_validation_error_if_no_email_or_password(self):
res = self.client.post(self.expand_path('/login'), data={'csrf_token': FakeCsrf.valid_token})
data = res.get_data(as_text=True)
assert re... |
'''
AxelProxy XBMC Addon
Copyright (C) 2013 Eldorado
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later vers... | .
'''
import axelcommon
import axelproxy
# This is xbmc linked class. TODO: read the settings here and send it to proxy for port etc
#TODO: check if start at launch setting is configured!
#Address and IP for Proxy to listen on
HOST_NAME = '127.0.0.1'
#HOST_NAME = 'localhost'
PORT_NUMBER = 45550 ##move th... | _name__ == '__main__':
file_dest = axelcommon.profile_path #replace this line if you want to be specific about the download folder
print file_dest
axelproxy.ProxyManager().start_proxy(port=PORT_NUMBER, host_name=HOST_NAME,download_folder=file_dest), #more param to come
|
on(StockController):
def __init__(self, *args, **kwargs):
super(StockReconciliation, self).__init__(*args, **kwargs)
self.head_row = ["Item Code", "Warehouse", "Quantity", "Valuation Rate"]
def validate(self):
if not self.expense_account:
self.expense_account = frappe.get_cached_value('Company', self.compa... | num,
_("Negative Quantity is not allowed")))
# do not allow negative valuation
if flt(row.valuation_rate) < 0:
self.validation_messages.append(_get_msg(row_num,
_("Negative Valuation Rate is not allowed")))
if row.qty and row.valuation_rate in ["", | None]:
row.valuation_rate = get_stock_balance(row.item_code, row.warehouse,
self.posting_date, self.posting_time, with_valuation_rate=True)[1]
if not row.valuation_rate:
# try if there is a buying price list in default currency
buying_rate = frappe.db.get_value("Item Price", {"item_code": row.... |
"""Imports for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.tools.api.generator.api.keras.preprocessing import image
from tensorflow.tools.api.generator.api.keras.preprocessing import sequence
| from tensorflow.tools.api.generator.api.keras.preprocessing imp | ort text |
'''
Swap counting
Status: Accepted
'''
###############################################################################
def inversions(constants, variables):
"""Number of swaps"""
if variables:
pow2 = pow(2, variables - 1, 1_000_000_007)
return pow2 * (constants * 2 + variables)
return co... | ##############
def main():
"""Read input and print output"""
zeroes, qmarks, swaps = 0, 0, 0
for glyph in r | eversed(input()):
if glyph == '0':
zeroes += 1
else:
if glyph == '1':
swaps += inversions(zeroes, qmarks)
if glyph == '?':
swaps += inversions(zeroes, qmarks) + swaps
qmarks += 1
swaps %= 1_000_000_007
... |
tract_interface, address=to_checksum_address(contract_address)
)
def get_transaction_receipt(self, tx_hash: bytes):
return self.web3.eth.getTransactionReceipt(encode_hex(tx_hash))
def deploy_solidity_contract(
self, # pylint: disable=too-many-locals
contract_name: str,
... | ("send_raw_transaction called", **log_details)
tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction)
self._available_nonce += 1
log.debug("send_raw_transaction returned", tx_hash=encode_hex(tx_hash), **log_details)
return tx_ | hash
def poll(self, transaction_hash: bytes):
""" Wait until the `transaction_hash` is applied or rejected.
Args:
transaction_hash: Transaction hash that we are waiting for.
"""
if len(transaction_hash) != 32:
raise ValueError("transaction_hash must be a 32 ... |
t_function, unicode_literals
import itertools
import os
import sys
try:
# Work around a traceback on Python < 2.7.4 and < 3.3.1
# http://bugs.python.org/issue15881#msg170215
import multiprocessing
except ImportError:
pass
# pyflakes workaround
__unused__ = (multiprocessing, )
PYTHON_VERSION = sys.ve... | 0.28'],
'Google': ['google>=1.7'],
'IRC': [irc_dep],
'mwparserfromhell': ['mwparserfromhell>=0.3.3'],
'Tkinter': ['Pillow<3.5.0' if PY26 else 'Pillow'],
# 0.6.1 supports socket.io 1.0, but WMF is using 0.9 (T91393 and T85716)
'rcst | ream': ['socketIO-client<0.6.1'],
'security': ['requests[security]', 'pycparser!=2.14'],
'mwoauth': ['mwoauth>=0.2.4,!=0.3.1'],
'html': ['BeautifulSoup4'],
}
if PY2:
# Additional core library dependencies which are only available on Python 2
extra_deps.update({
'csv': [csv_dep],
'My... |
__author__ = 'http://www.python-course.eu/python3_inheritance.php'
class Person:
def __init__(self, first, | last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + s | elf.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self,first, last)
self.staffnumber = staffnum
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
... |
y(
payload: Dict[str, Any], action: Dict[str, Any], entity: str
) -> str:
pull_request_action: Dict[str, Any] = get_action_with_primary_id(payload)
kwargs = {
"name_template": STORY_NAME_TEMPLATE.format(**action),
"name": pull_request_action.get("number")
if entity == "pull-request"... | f it is the | only one change.
if len(templates) <= 1 or (len(templates) == 0 and last_change == "state"):
event: st |
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3])
axins1 = inset_axes(ax1,
width="50%", # width = 10% of parent_bbox width
height="5%", # height : 50%
loc=1)
im... | 1.xaxis.set_ticks_position("bottom")
axins = inset_axes(ax2,
| width="5%", # width = 10% of parent_bbox width
height="50%", # height : 50%
loc=3,
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=ax2.transAxes,
borderpad=0,
)
# Controlling the placemen... |
import os
import string
import random
import logging
from thug.ActiveX.modules import WScriptShell
from thug.ActiveX.modules import TextStream
from thug.ActiveX.modules | import File
from thug.ActiveX.modules import Folder
from thug.OS.Windows import win32_files
from thug.OS.Windows import win32_folders
log = logging.getLogger("Thug")
def BuildPath(self, arg0, arg1): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] BuildPat... | (f'[Scripting.FileSystemObject ActiveX] CopyFile("{source}", "{destination}")')
log.TextFiles[destination] = log.TextFiles[source]
def DeleteFile(self, filespec, force = False): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] DeleteFile("{filespec}", {... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 clowwindy
#
# 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 b... | lf._keys_to_last_time[key] > self.timeout:
del self._store[key]
del self._keys_to_last_time[key]
c += 1
del self._time_to_keys[least]
if c | :
logging.debug('%d keys swept' % c)
def test():
c = LRUCache(timeout=0.3)
c['a'] = 1
assert c['a'] == 1
time.sleep(0.5)
c.sweep()
assert 'a' not in c
c['a'] = 2
c['b'] = 3
time.sleep(0.2)
c.sweep()
assert c['a'] == 2
assert c['b'] == 3
time.sleep(0.... |
# -*- coding: utf-8 -*-
from __future__ import unic | ode_literals
from blinker import Namespace
namespace = Namespace()
#: Trigerred when a dataset is published
on_dataset_published = namespace.signal('on-data | set-published')
|
# AnalogClock's font selector for setup dialog
# E. A. Tacao <e.a.tacao |at| estadao.com.br>
# http://j.domaindlx.com/elements28/wxpython/
# 15 Fev 2006, 22:00 GMT-03:00
# Distributed under the wxWidgets license.
import wx
from wx.lib.newevent import NewEvent
from wx.lib.buttons import GenButton
#----... | if changed:
data = dlg.GetFontData()
self.value = data.GetChosenFont()
self.Refresh()
dlg.Destroy()
if changed:
nevt = FontSelectEvent(id=self.GetId(), obj=s | elf, val=self.value)
wx.PostEvent(self.parent, nevt)
#
##
### eof
|
import binascii |
from cryptography.hazmat.primitives import hmac
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives.constant_time import bytes_eq
import cryptography.hazmat.backends
from django.conf import settings
from django.core.mail import send_mail
from django.http im | port HttpResponse
from django.views.decorators.csrf import csrf_exempt
crypto_backend = cryptography.hazmat.backends.default_backend()
def verify_signature(request, request_body):
hmac_hmac = hmac.HMAC(settings.GITHUB_WEBHOOK_SECRET, SHA1(), crypto_backend)
hmac_hmac.update(request_body)
signature = b'sh... |
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This libra... | raise TypeError(repr(value))
def _check_kv(self, key, value):
if not isinstance(key, self._kt):
raise TypeError(repr(key))
if not isinstance(value, self._vt):
raise TypeError(repr(value))
def __setitem__(self, k | ey, value):
self.check(key, value)
super(tdict, self).__setitem__(key, value)
def update(self, E=None, **F):
try:
it = chain(E.items(), F.items())
except AttributeError:
it = chain(E, F)
for k, v in it:
self[k] = v
def setdefault(sel... |
governing permissions and
# limitations under the License.
#
# Author: mwu@google.com (Mingyu Wu)
"""Unittest for baserunner module."""
__author__ = 'mwu@google.com (Mingyu Wu)'
import os
import shutil
import sys
import tempfile
import time
import unittest
from lib import baserunner
from lib import filesystemhand... | TEST_SCRIPT'] = 'echo testRunScripts1'
config2 = pyreringutil.PRConfigParser().Default()
config2['TE | ST_SCRIPT'] = 'echo testRunScripts2'
self.scanner.SetConfig([self.one_config, config2])
result = self.runner.Run(['testRunScripts'], False)
self.assertEqual(result, 0)
self.assertEqual(self.runner.passed, 2)
# TODO(mwu): verify both scripts run fine
def testEmailSend(self):
"""Test Email sho... |
_grad}
if self.momentum > 0:
kwargs['momentum'] = self.momentum
if self.clip_gradient:
kwargs['clip_gradient'] = self.clip_gradient
if aggregate:
if not multi_precision:
if self.momentum > 0:
multi_sgd_mom_update(*_flatten_... | er described in
*FTML - Follow the Moving Leader in Deep Learning*,
available at http://proceedings.mlr.press/v70/zheng17a/zheng17a.pdf.
Denote time step by t. The optimizer updates the weight by::
rescaled_grad = clip(grad * rescale_grad + wd * weight, clip_gradient)
v = beta2 * v + (1 - ... | d_t = (1 - power(beta1, t)) / lr * square_root(v / (1 - power(beta2, t))) + epsilon)
z = beta1 * z + (1 - beta1) * rescaled_grad - (d_t - beta1 * d_(t-1)) * weight
weight = - z / d_t
For details of the update algorithm, see :class:`~mxnet.ndarray.ftml_update`.
This optimizer accepts the ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui fil | e 'qhangups/qhangupsbrowser.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_QHangupsBrowser(object):
def setupUi(self, QHangups | Browser):
QHangupsBrowser.setObjectName("QHangupsBrowser")
QHangupsBrowser.resize(600, 450)
self.verticalLayout = QtWidgets.QVBoxLayout(QHangupsBrowser)
self.verticalLayout.setObjectName("verticalLayout")
self.browserWebView = QtWebKitWidgets.QWebView(QHangupsBrowser)
sel... |
'''Test cases for QLayout handling of child widgets references'''
import unittest
from sys import getrefcount
from PySide.QtGui import QHBoxLayout, QVBoxLayout, QGridLayout, QWidget
from PySide.QtGui import QStackedLayout, QFormLayout
from PySide.QtGui import QApplication, QPushButton, QLabel
from helper import Use... | self):
mw = QWidget()
w = QWidget()
ow = QWidget()
topLayout = QGridLayout()
# unique reference
self.assertEqual(getrefcount(w), 2)
self.assertEqual(getrefcount(ow), 2)
topLayout.addWidget(w, 0, 0)
topLayout.addWidget(ow, 1, 0)
# layout... | = QGridLayout()
mainLayout.addLayout(topLayout, 1, 0, 1, 4)
# the same reference
self.assertEqual(getrefcount(w), 3)
self.assertEqual(getrefcount(ow), 3)
mw.setLayout(mainLayout)
# now trasfer the ownership to mw
self.assertEqual(getrefcount(w), 3)
se... |
# Copyright (c) by it's authors.
# Some rights reserved. See LICENSE, AUTHORS.
from peer import *
from viewer import Viewer
from editor import Editor
class SearchDocument(Peer):
#Receiving pillows:
Search = Pillow.In
Sending = [
Viewer.In.Document
]
Routings = [
(Editor.Out.Fi... | def __init__(self, searchRoom, resultRoom=None, document=None, identifier=None, appendWildcard=False):
Peer.__init__(self, searchRoom)
if not resultRoom:
resultRoom = searchRoom
self._resultRoom = resultRoom
self._identifier = identifier
self._appendWildcard = appe... | self._document = document
else:
from wallaby.common.queryDocument import QueryDocument
self._document = QueryDocument()
self._document.set('identifier', self._identifier)
self._document.set('query', '*')
self._catch(SearchDocument.In.Search, self._search)
... |
def countup(n):
if n >= 10:
print "Blastoff!"
else:
print n
countup(n+1)
def main():
countup(1)
main()
def countdown_from_to(start,stop):
if start == stop:
print "Blastoff!"
elif start <= stop:
print "Invalid pair"
else:
print start
countdown_from_to(start - 1,stop)
def main():
countdown_... | = (raw_input("Next Number"))
if (number) == "":
print "The Sum Is {}".format(sum_)
elif number == float:
print number
else:
sum_ += float(number)
print "Running total: {}".format(sum_)
| adder(sum_)
def main():
sum_ = 0
adder(sum_)
main()
|
#!/usr/bin/env python
"""zip source directory tree"""
import argparse
import fnmatch
import logging
import os
import re
import subprocess
import zipfile
def get_version():
command = ['git', 'describe', '--tags', '--dirty', '--always']
return subprocess.check_output(command).decode('utf-8')
def source_walk(r... | x.match(f) is None]
for filename in files:
fullpath = os.path.join(path, filename)
yield fullpath, os.path.relpath(fullpath, root)
def setup():
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
'-d', '--debug',
action='store_true',
he... | )
argparser.add_argument(
'-o',
metavar='zipfile',
dest='output',
help='output file name')
argparser.add_argument(
'source',
help='source directory')
args = argparser.parse_args()
loglevel = logging.DEBUG if args.debug else logging.WARNING
logging.bas... |
# -*- coding: utf-8 -*-
# File: enemy.py
# Author: Casey Jones
#
# Created on July 20, 2009, 4:48 PM
#
# This file is part of Alpha Beta Gamma (abg).
#
# ABG 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, ... | remove(self, index):
try:
to_update = self.enemies[index].enemyrect
self.screen.blit(self.blackSurface, self.enemies[index].enemyrect)
del self.enemies[index]
return to_update
except IndexError:
print("IndexError for enemy {0} of {1}".format(in... | f.enemies[i].enemyrect)
del self.enemies[:]
|
##
# Copyright 2011-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | Determine initial module paths, where the modules that are top of the hierarchy (if any) live.
"""
return []
def expand_toolchain_load(self, ec=None):
"""
Determine whether load statements for a toolchain should be expanded to load statements for its depende | ncies.
This is useful when toolchains are not exposed to users.
"""
# by default: just include a load statement for the toolchain
return False
def is_short_modname_for(self, short_modname, name):
"""
Determine whether the specified (short) module name is a module for... |
#!/usr/bin/env python
# Copyright 2018, 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 o... | : u'1',
}],
}],
}
EXPECTED_2 = {
u'tests':
1,
u'failures':
0,
u'disabled':
0,
u'errors':
0,
u'time':
u'*',
u'timestamp':
u'*',
u'name':
u'AllTests',
u'testsuites': [{
u'name':
u'PropertyTwo',
... | u'time':
u'*',
u'timestamp':
u'*',
u'testsuite': [{
u'name': u'TestSomeProperties',
u'status': u'RUN',
u'result': u'COMPLETED',
u'timestamp': u'*',
u'time': u'*',
u'classname': u'PropertyTwo',
u... |
### | #####################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
ProfileNumericComparator = Enum(
'equal',
'greaterThan',
'greaterThanEqual',
'lessTh | an',
'lessThanEqual',
'notEqual',
)
|
__author__ = 'saeedamen'
#
# Copyright 2015 Thalesians Ltd. - http//www.th | alesians.com / @thalesians
#
# 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 CONDITIONS O... |
# NamoInstaller ActiveX Control 1.x - 3.x
# CVE-NOMATCH
import logging
log = logging.getLogger("Thug")
def Install(self, arg):
if len(arg) > 1024:
log.ThugLogging.log_exploit_event(self._window.url,
"NamoInstaller ActiveX",
... | ller ActiveX",
"Insecure download from URL",
forward = False,
data = {
| "url": arg
}
)
try:
self._window._navigator.fetch(arg, redirect_type = "NamoInstaller Exploit")
except Exception:
log.ThugLogging.add_behav... |
#!/usr/bin/env python
#Alberto
from __future__ import print_function, division
import os
import glob
import argparse
from subprocess import Popen, PIPE
from argparse import RawTextHelpFormatter
import sys
import re
from textwrap import dedent
from subprocess import call
def warn(*objs):
print(*objs, file=sys.stder... | )
if not line: return None
while not GJob.COMMANDPat.match(line):
start += line
line = inFile.readRequiredLine()
while line.strip():
command += line
line = inFile.readRequiredLine()
if not GJob.SKIPGeomPat.search(command):
middle = "\n"
lin... | # read charge and multiplicity
middle += inFile.readRequiredLine()
line = inFile.readRequiredLine()
while line.strip():
coords += line
line = inFile.readRequiredLine()
while line and not GJob.LINKPat.match(line):
end += line
line = inF... |
import itertools
# Local modules
import uncertainties.core as uncert_core
from uncertainties.core import (to_affine_scalar, AffineScalarFunc,
LinearCombination)
###############################################################################
# We wrap the functions from the math modul... | ocally constant (on real
# numbers): their value does not depend o | n the uncertainty (because
# this uncertainty is supposed to lead to a good linear approximation
# of the function in the uncertainty region). The type of their output
# for floats is preserved, as users should not care about deviations
# in their value: their value is locally constant due to the nature of
# the functi... |
#forces : A fast customized optimization solver.
#
#Copyright (C) 2013-2016 EMBOTECH GMBH [info@embotech.com]. All rights reserved.
#
#
#This software is intended for simulation and testing purposes only.
#Use of this software for any commercial purpose is prohibited.
#
#This program is distributed in the hope that it... | numpy.distutils.intelccom | piler import IntelCCompiler
#c = IntelCCompiler()
import os
import sys
import distutils
# determine source file
sourcefile = os.path.join(os.getcwd(),"forces","src","forces"+".c")
# determine lib file
if sys.platform.startswith('win'):
libfile = os.path.join(os.getcwd(),"forces","lib","forces"+".lib")
else:
libfi... |
def __repr__(self):
module = self.__class__.__module__
class_name = self.__class__.__name__
return '<{0}.{1}: {2}>'.format(module, class_name, self.to_id())
class Token(namedtuple('Token', ['token', 'expires'])):
""" Wrapper around access-token. """
class EPOClient:
""" Client to... | fetch_range, service=Services.PublishedSearch,
endpoint='', extra_headers=None):
""" Post a GET-search query.
Parameters
----------
query : str
Query string.
fetch_range : tuple[int, int]
Get entries `fetch_range[0]` to `fetch_range[1]`.
... | dict, optional
Additional or custom headers to be used.
Returns
-------
requests.Response
"""
if not isinstance(service, Services):
raise ValueError('invalid service: {}'.format(service))
if not isinstance(endpoint, (list, tuple)):
en... |
import os
import re
import sys
import json
import shlex
import logging
import inspect
import functools
import importlib
from pprint import pformat
from collections import namedtuple
from traceback import format_tb
from requests.exceptions import RequestException
import strutil
from cachely.loader import Loader
from .... | ontinue
logger.debug('Lexed {} byte(s) line {}'.format(len(line), chars))
yield Instruction.parse(line, lineno)
def load_libraries(extensions=None):
if isin | stance(extensions, str):
extensions = [extensions]
libs = BASE_LIBS + (extensions or [])
for lib in libs:
importlib.import_module(lib)
class Interpreter:
def __init__(
self,
contents=None,
loader=None,
use_cache=False,
do_pm=False,
extensio... |
import unittest
import os
from sqltxt.table import Table
from sqltxt.column import Column, ColumnName, AmbiguousColumnNameError
from sqltxt.expression import Expression
class TableTest(unittest.TestCase):
def setUp(self):
self.data_path = os.path.join(os.path.dirname(__file__), '../data')
table... | rom_cmd.get_column_for_name(ColumnName('col_a'))
table_from_cmd = Table.from_cmd(
name = 'table_a',
cmd = 'echo -e ""',
columns = ['ta.col_a', 'tb.col_a'])
with self.assertRaisesRegexp(AmbiguousColumnNameError, 'Ambiguous column reference'):
table_from_ | cmd.get_column_for_name(ColumnName('col_a'))
first_column = Column('ta.col_a')
first_column.add_name('col_alpha')
second_column = Column('tb.col_a')
table_from_cmd = Table.from_cmd(
name = 'table_a',
cmd = 'echo -e ""',
columns = [first_column, secon... |
alty='l1')
self.neutral_train = None
self.vct_neutral = None
| self.neutral_labels = np.array([])
self.vcn = vcn
| self._kvalues = [10, 25, 50, 75, 100]
self.subpool = subpool
self.lambda_value = lambda_value
def pick_next(self, pool=None, step_size=1):
list_pool = list(pool.remaining)
indices = self.randgen.permutation(len(pool.remaining))
remaining = [list_pool[index] for index in ind... |
payload."""
payload = test_support.decode_task_payload(task)
return model.MapreduceSpec.from_json_str(payload["mapreduce_spec"])
def validate_map_started(self, mapreduce_id, queue_name=None):
"""Tests that the map has been started."""
queue_name = queue_name or self.QUEUE_NAME
self.assertTrue(map... | f.validate_map_started(mapreduce_id)
eta_sec = time.mktime(time.strptime(task_eta, "%Y/%m/%d %H:%M:%S"))
self.assertTrue(now_sec + 1000 <= eta_sec)
def testStartMap_Eta(self):
"""Test that MR can be scheduled into the future.
Most of start_map functionality is already tested by handlers_test.
Ju... | datetime.datetime.utcnow() + datetime.timedelta(hours=1)
shard_count = 4
mapreduce_id = control.start_map(
"test_map",
__name__ + ".test_handler",
"mapreduce.input_readers.DatastoreInputReader",
{
"entity_kind": __name__ + "." + TestEntity.__name__,
},
... |
# -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | ee the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Linux Show Player. If not, see <http://www.gnu.org/licenses/>.
import mido
from lisp.modules.midi.midi_common import MIDICommon
from lisp.modules.midi.midi_utils import mido_backen... | me='AppDefault'):
super().__init__(port_name=port_name)
def send_from_str(self, str_message):
self.send(mido.parse_string(str_message))
def send(self, message):
self._port.send(message)
def open(self):
port_name = mido_port_name(self._port_name, 'O')
self._port = m... |
# ! /usr/bin/env python
# _*_ coding:utf-8 _*_
"""
@author = lucas.wang
@create_time = 2018-01-12
"""
from xml.etree import ElementTree as ET
import fnmatch
class change_xml(object):
"""
xml main function
"""
names = ['iConn.CreateXmlTools.vshost.exe', 'AutoUpdater.dll', 'NewTonsoft.Json.dll',
... | self.file_name = file_name
self.tree = ET.parse(file_path + file_name)
self.path_name = path_name
def read_xml(self):
"""
Read xml file
:return:
"""
root = self.tree.getroot()
# print(root)
for item in root.getchildren():
# ro... | et("url", item.get('url').replace(self.old_path_name, self.path_name))
if fnmatch.filter(self.names, item.get('path')):
root.remove(item)
self.write_xml()
def write_xml(self):
self.tree.write(self.file_path + self.file_name)
print("Update xml file success. file... |
te"]
]
for r in reverse_relations:
if r.remote_field.model.objects.filter(
**{r.field.name: self}
).exists():
return False
return True
@classmethod
def check(cls, **kwargs):
errors = super().check(**kwargs)
errors.... | DOCUMENT = [
"write",
"write-tracked",
"review",
"review-tracked",
"comment",
]
# Whether the collaborator is allowed to know about other collaborators
# and communicate with them.
CAN_COMMUNICATE = ["read", "write", "comment", " | write-tracked"]
class AccessRight(models.Model):
document = models.ForeignKey(Document, on_delete=models.deletion.CASCADE)
path = models.TextField(default="", blank=True)
holder_choices = models.Q(app_label="user", model="user") | models.Q(
app_label="user", model="userinvite"
)
holder_typ... |
continuous scale
version (P-Values, expression values, ...) and a thresholded
version (0 and 1 for genelist membership).
2. The pipeline builds a matrix of gene list annotations to
test against. To this end, it collects:
ENSEMBL GO annotations
KEGG Pathways
User supplied pathways
GSEA database si... | min_threshold,
field,
max_threshold))
field = PARAMS[P.matchParameter("%s_background_field" % track)]
min_threshold = PARAMS[P.matchParameter(
"%s_background_min_thresho | ld" % track)]
max_threshold = PARAMS[P.matchParameter(
"%s_background_max_threshold" % track)]
E.info('%s: background: %f <= %s <= %f' % (track,
min_threshold,
field,
... |
import dns
import requests
import socket
from recursortests import RecursorTest
class RootNXTrustRecursorTest(RecursorTest):
def getOutgoingQueriesCount(self):
headers = {'x-api-key': self._apiKey}
url = 'http://127.0.0.1:' + str(self._wsPort) + '/api/v1/servers/localhost/statistics'
r = r... | query = dns.message.make_query('www.nx-example.', 'A')
res = self.sendUDPQuery(query)
self.assertRcodeEqual(res, dns.rcode.NXDOMAIN)
print(res)
self.assertAuthorityHasSOA(res)
# check that we sent one query to the root
after = self.getOutgoingQueriesCount()
... | then query nx2.example.
before = after
query = dns.message.make_query('www2.nx-example.', 'A')
res = self.sendUDPQuery(query)
self.assertRcodeEqual(res, dns.rcode.NXDOMAIN)
self.assertAuthorityHasSOA(res)
after = self.getOutgoingQueriesCount()
self.assertEqual(... |
# -*- coding: utf-8 -*-
import json
def json_pre_process_hook(action, request, *args, **kwargs):
json_data = request.body
if not json_data:
action.ret('002').msg('json_params_required')
return False
try:
param_dict = json.loads(json_data)
except ValueError:
action.ret... | param_dict = request.POST
if not param_dict:
action.ret('004').msg('form_params_required')
return False
for key, value in param_dict.items():
setattr(action, key, value)
return True
def jsonp_post_render_hook(action):
if action.jsonp_callback:
action.resp_data_json(
... |
else:
action.ret('005').msg('jsonp_callback_required')
if action._data:
del action._data
action.render()
return False
return True
|
import *
from dlab.meta_lib import *
from dlab.actions_lib import *
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--uuid', type=str, default='')
args = parser.parse_args()
if __name__ == "__main__":
local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.env... | user'], sudo_group)
try:
local("~/scripts/{}.py {}".format('create_ssh_user', params))
except:
traceback.print_exc()
raise Exception
except Exception as err:
append_result("Failed creating ssh user 'dlab'.", str(err))
remove_ec2(notebook_config['t... |
logging.info('[CONFIGURE PROXY ON JUPYTER INSTANCE]')
print('[CONFIGURE PROXY ON JUPYTER INSTANCE]')
additional_config = {"proxy_host": edge_instance_hostname, "proxy_port": "3128"}
params = "--hostname {} --instance_name {} --keyfile {} --additional_config '{}' --os_user {}"\
... |
# | -*- coding:utf8 -*-
# Author: shizhenyu96@gamil.com
# github: https://github.com/imndszy
from flask import Blueprint
admin = Blueprint('admin', __name__)
from . import views | |
#!/usr/bin/env | python
import sys
from setuptools import setup
if sys.hexversion < 0x030200a1:
print ("LightSweeper requires python 3.2 or higher.")
print("Exiting...")
sys.exit(1)
setup(name='LightSweeper',
version='0.6b',
description='The LightSweeper API',
author='The LightSweeper Team',
author_email... | age_data=True
)
|
from megaera import local, json
from oauth import signed_url
from google.appengine.api import urlfetch
__TWITTER_API__ = "http://api.twitter.com/1"
def tweet(status, **credentials):
if not credentials:
# shortcut for no-credentials case
credentials = local.config_get('twitter')
if not credentials:
... | al.config_get('twitter')
if not credentials:
return
destroy_url = "%s/statuses/destroy.json" % __TWITTER_API__
fetch_url = signed_url(url=destroy_url, method='POST', id=status_id, **credentials)
response = urlfetch.fetch(fetch_url, method=urlfetc | h.POST)
try:
content = json.read(response.content)
return content.get('id')
except json.ReadException:
pass
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-06 11:13
from __future__ import unic | ode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='NewsItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=Tru... | Field(max_length=256)),
('content', models.TextField()),
],
),
]
|
import unittest
import logging
logging.getLogger().setLevel(logging.DEBUG)
from ...auction.worker import Worker
from ...database import Database
from ...rc import sql
class TestCase(unittest.TestCase):
def setUp(self):
self.db | = Database.pymysql(**sql)
| self.ob = Worker(self.db, fail=True)
def test_init(self):
pass |
ipient.PERSONAL)
# Users on the different realms can not PM each other
with assert_disallowed():
self.send_message(user1_email, user2_email, Recipient.PERSONAL)
# Users on non-zulip realms can't PM "ordinary" Zulip users
with assert_disallowed():
self.send_messa... | "
Send | ing a PM containing non-ASCII characters succeeds.
"""
self.login("hamlet@zulip.com")
self.assert_personal("hamlet@zulip.com", "othello@zulip.com", u"hümbüǵ")
class StreamMessagesTest(ZulipTestCase):
def assert_stream_message(self, stream_name, subject="test subject",
... |
#
# Copyright (c) 2009--2010 Red Hat, Inc.
# |
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR | A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software ... |
# -*- coding: utf-8 -*-
# +---------------------------------------------------------------------------+
# | 01001110 01100101 01110100 01111010 01101111 01100010 |
# | |
# | Netzob : Inferring communication prot... | ractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), | sign=AbstractType.defaultSign()):
return data
@staticmethod
def canParse(data):
"""Computes if specified data can be parsed as raw which is always the case if the data is at least 1 length and aligned on a byte.
>>> from netzob.all import *
>>> Raw.canParse(TypeConverter.conver... |
import unittest
imp | ort maya.cmds as mc
import vrayformayaUtils as vfm
class TestMeshAttributes(unittest.TestCase):
"""
This is a generic TestCase for most v-ray mesh attributes.
Note that it doesn't test every single case of changes, but it should capture overall changes of the code.
"""
def setUp(self):
... | shapes=True)
vfm.attributes.vray_subdivision(self.mesh, state=True, smartConvert=True)
for shape in shapes:
self.assertTrue(mc.objExists("{0}.vraySubdivEnable".format(shape)))
vfm.attributes.vray_subdivision(self.mesh, state=True, smartConvert=True, vraySubdivEnable=False)
f... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Post-installation configuration helpers
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General P... | chart_template_id,
'company_id': company_id,
'bank_accounts_id': bank_accounts_id,
})
onchange = chart_wizard.onchange_chart_template_id(cr, uid, [], data['chart_template_id'], context=context)
data.update(onchange['value'])
if code_digits:
data.update({'code_digits': code_digit... | ry, uid, company_id, name, code, start_date, end_date, context=None):
fy_model = registry['account.fiscalyear']
fy_data = fy_model.default_get(cr, uid, ['state', 'company_id'], context=context).copy()
fy_data.update({
'company_id': company_id,
'name': name,
'code': code,
'dat... |
import cherrypy, json
from bottle import request, get
from ring_api.server.api import ring, user
class Root(object):
def __init__(self, dring):
self.dring = dring
self.user = user.User(dring)
@cherrypy.expose
def index(self):
| return 'todo'
@cherrypy.expose
def r | outes(self):
return 'todo'
|
import os
import shutil
usage = {}
usage['import'] = """catmap import <mkm-file>
Open a *.mkm project file and work with it interactively.
"""
def get_options(args=None, get_parser=False):
import optparse
import os
from glob import glob
import catmap
parser = optparse.OptionParser(
... | [0], usage, parser)
elif args[0] == 'import':
if len(args) < 2:
parser.error('mkm filename expected.')
from catmap import ReactionModel
mkm_file = args[1]
global model
model = ReactionModel(setup_file=mkm_file)
sh(banner='Note: model = | catmap.ReactionModel(setup_file=\'%s\')\n# do model.run()\nfor a fully initialized model.' %
args[1])
def sh(banner):
"""Wrapper around interactive ipython shell
that factors out ipython version depencies.
"""
from distutils.version import LooseVersion
import IPython
if hasattr(IP... |
s)
def assert_no_local_failure(contacted):
assert not contacted['local'].get('failed')
def assert_local_failure(contacted):
assert contacted['local'].get('failed')
class FakeAnsibleModuleBailout(BaseException):
def __init__(self, success, params):
super(FakeAnsibleModuleBailout, self).__init__... | mpotent
def test_lo | g_runscript(runit_sv, basedir):
"""
Adding a log_runscript creates a log/run script as well.
"""
runit_sv(
name='testsv',
runscript='spam eggs',
log_runscript='eggs spam',
**base_directories(basedir))
sv_log = basedir.join('sv', 'testsv', 'log')
assert len(sv_log.... |
"""
Parse string to create Regex object.
TODO:
- Support \: \001, \x00, \0, \ \[, \(, \{, etc.
- Support Python extensions: (?:...), (?P<name>...), etc.
- Support \<, \>, \s, \S, \w, \W, \Z <=> $, \d, \D, \A <=> ^, \b, \B, [[:space:]], etc.
"""
from hachoir_regex import (RegexString, RegexEmpty, RegexRepeat,
R... | match.group(2):
text = match.group(2)[1:]
if text:
rmax = int(text)
else:
rmax = None
else:
rmax = rmin
return (rmin, rmax, match.end(0))
CHAR_TO_FUNC = | {'[': parseRange, '(': parseOr}
CHAR_TO_CLASS = {'.': RegexDot, '^': RegexStart, '$': RegexEnd}
CHAR_TO_REPEAT = {'*': (0, None), '?': (0, 1), '+': (1, None)}
def _parse(text, start=0, until=None):
if len(text) == start:
return RegexEmpty(), 0
index = start
regex = RegexEmpty()
last = None
... |
from gpu import *
LAMP_TYPES = [
GPU_DYNAMIC_LAMP_DYNVEC,
GPU_DYNAMIC_LAMP_DYNCO,
GPU_DYNAMIC_LAMP_DYNIMAT,
GPU_DYNAMIC_LAMP_DYNPERSMAT,
GPU_DYNAMIC_LAMP_DYNENERGY,
GPU_DYNAMIC_LAMP_DYNENERGY,
GPU_DYNAMIC_LAMP_DYNCOL,
GPU_DYNAMIC_LAMP_DISTANCE,
GPU_DYNAMIC_LAMP_ATT1,
GPU_DYNAMIC... | TYPE : 'falloff',
GPU_DYNAMIC_MIST_COLOR : 'color',
GPU_DYNAMIC_HORIZON_COLOR : 'horizon_color',
GPU | _DYNAMIC_AMBIENT_COLOR : 'ambient_color',
GPU_DYNAMIC_LAMP_DYNVEC : 'dynvec',
GPU_DYNAMIC_LAMP_DYNCO : 'dynco',
GPU_DYNAMIC_LAMP_DYNIMAT : 'dynimat',
GPU_DYNAMIC_LAMP_DYNPERSMAT : 'dynpersmat',
GPU_DYNAMIC_LAMP_DYNENERGY : 'energy',
GPU_DYNAMIC_LAMP_DYNCOL : 'color',
GPU_DYNAMIC_LAMP_DISTAN... |
import os.path
from tornado import ioloop, httpserver, web, | websocket, template
from config import GameConfig
OS = os.path.dirname(__file__)
def server_path(uri):
return os | .path.join(OS, uri)
def static_path(uri):
return { "path": server_path("static/" + uri) }
level_1 = GameConfig()
class TarmHandler(web.RequestHandler):
def get(self):
self.render(server_path("html/game.html"), config = level_1)
def write_error(self, code, **kwargs):
self.render(server_path("html/error.html"... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | import RemediationsOperations
from ._policy_events_operations import Polic | yEventsOperations
from ._policy_states_operations import PolicyStatesOperations
from ._operations import Operations
from ._policy_metadata_operations import PolicyMetadataOperations
from ._policy_restrictions_operations import PolicyRestrictionsOperations
from ._attestations_operations import AttestationsOperations
__... |
import hashlib
import mock
import uuid
from django.test import TestCase
from ..models import Commander
class CommanderTestCase(TestCase):
def test_generate_token(self):
| with mock.patch.object(uuid, 'uuid4', return_value='a_test'):
cmdr = Commander(
name='Branch'
)
self.assertEqual(
cmdr.generate_token(),
hashlib.md5('a_test').hexdigest()
)
def test_save(self):
# We need to ... | sertTrue(len(cmdr.api_token) > 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.