prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from . import _ccallback_c
import ctypes
PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
ffi = None
class CData(object):
pass
def _import_cffi():
global ffi, CData
if ffi is not None:
return
try:
import cffi
ffi = cffi.FFI()
CData = ffi.CData
except... | ]
if pointer_level > 0:
name += " " + "*"*pointer_level
return name
def _get_ctypes_data(data):
# Get voidp pointer
return ctypes.cast(data, ctypes.c_void_p).value
#
# CFFI helpers
#
def _get_cffi_func(func, signature=None):
# Get function point | er
func_ptr = ffi.cast('uintptr_t', func)
# Get signature
if signature is None:
signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')
return func_ptr, signature
def _get_cffi_data(data):
# Get pointer
return ffi.cast('uintptr_t', data)
|
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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
Unle... | """
Swagger model
:param dict | swaggerTypes: The key is attribute name and the value is attribute type.
:param dict attributeMap: The key is attribute name and the value is json key in definition.
"""
self.swagger_types = {
'status': 'str',
'message': 'str'
}
self.attribute_map = {
... |
# -*- coding: utf-8 -*-
appid = 'example'
apikey = 'c5dd7e7dkjp27377l903c42c032b413b'
sender = '01000000000' | # FIXME - MUST BE CHANGED AS REAL PHONE NUMBER
receivers = ['01000000000', ] | # FIXME - MUST BE CHANGED AS REAL PHONE NUMBERS
content = u'나는 유리를 먹을 수 있어요. 그래도 아프지 않아요'
|
##
# Copyright 2009-2017 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... | lib/spack/spack/build_environment.py#L416
options.append('-DCMAKE_SKIP_RPATH=ON')
# show what CMake is doing by default
options.append('-DCMAKE_VERBOSE_MAKEFILE=ON')
options_string = ' '.join(options)
command = "%s cmake %s %s %s" % (self.cfg['preconfigopts'], srcdir, opti... | elf.cfg['configopts'])
(out, _) = run_cmd(command, log_all=True, simple=False)
return out
|
# coding=utf-8
from __future__ import unicode_literals
"""
Name: MyArgparse
Author: Andy Liu
Email : andy.liu.ud@hotmail.com
Created: 3/26/2015
Copyright: All rights reserved.
Licence: This program is free software: you can redistribute it
and/or modify it under the te... | .org/licenses/>.
"""
import argparse
import logging
def parse_command_line():
parser = argparse.ArgumentParser(prog='PROG', description='%(prog)s can ...')
parser.add_argument('NoPre', action="store", help='help information')
parser.add_argument('-t', action="store_true", | dest='boolean_switch', default=False, help='Set a switch to true')
parser.add_argument('-f', action="store_false", dest='boolean_switch', default=True, help='Set a switch to false')
parser.add_argument('-s', action="store", dest='simple_value', help="Store a simple value")
parser.add_argument('-st', action... |
from dj | ango.contrib import admin
from trainer.models import Language, Word, Card, Set
admin.site.register(Language)
admin.site.register(Word)
admin.site.register(Card)
admin.site.regis | ter(Set)
|
oint registration or to quit
event_first_of(
event_healthy,
event_stop,
).wait()
while True:
data_or_stop.wait()
if event_stop.is_set():
return
# The queue is not empty at this point, so this won't raise Empty.
# This task being the only consume... | _max_timeout,
)
acknowledged = retry_with_recovery(
protocol,
data,
receiver_address,
event_stop,
event_healthy,
event_unhealthy,
backoff,
)
i | f acknowledged:
queue.get()
# Checking the length of the queue does not trigger a
# context-switch, so it's safe to assume the length of the queue
# won't change under our feet and when a new item will be added the
# event will be set again.
if no... |
# Copyright (C) 2012-2015 ASTRON (Netherlands Institute for Radio Astronomy)
# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as p... | her version 3 of the License, or
# (at your option) any later version.
#
# The LOF | AR software suite is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along... |
convertPrio(cal.vtodo.priority.value) if hasattr(cal.vtodo, 'priority') else None
}
fakePOST = QueryDict(mutable=True)
fakePOST.update(params)
form = SimpleTickets(fakePOST)
if form.is_valid():
cd = form.cleaned_data
... | else:
tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMP... | tic.uuid = cal.vtodo.uid.value
tic.save(user=request.user)
if tic.assigned:
touch_ticket(tic.assigned, tic.pk)
for ele in form.changed_data:
form.initial[ele] = ''
... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... | om mcfw.properties import bool_property, unicode_list_property, unicode_property, typed_property
class BankDataTO(object):
bankCode = unicode_property('bankCode')
name = unicode_property('name')
bic = unicode_property('bic')
class OpenIbanResultTO(object):
valid = bool_property('valid')
messages... |
bankData = typed_property('bankData', BankDataTO) # type: BankDataTO
checkResults = typed_property('checkResults', dict)
|
# -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it | under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABI... | icense for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .module import CmsoModule
__all__ = ['CmsoModule']
|
if self.status == self.INACTIVE:
# If these fields have already been changed, don't
# override those changes. Don't unset the name field
# if no further data is available.
if self.name == self.feed_url:
self.name = video_iter.title or self.name
... | show it."))
parent = models.ForeignKey(
'self', blank=True, null=True,
related_name='child_set',
verbose_name='Category Parent',
help_text=_("Categories, unlike tags, can have a hierarchy."))
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
unique_t... | lf):
return self.name
def dashes(self):
"""
Returns a string of em dashes equal to the :class:`Category`\ 's
level. This is used to indent the category name in the admin
templates.
"""
return mark_safe('—' * self.level)
@models.permalink
def g... |
from rest_framework import exceptions as drf_exceptions
from rest_framework import versioning as drf_versioning
from rest_framework.compat import unicode_http_header
from rest_framework.utils.mediatypes import _MediaType
from api.base import exceptions
from api.base import utils
from api.base.renderers import Browsabl... | verse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra):
url_path_version = self.get_url_path_version(kwargs)
major_version = get_major_version(url_path_version)
query_parameter_version = self.get_query_param_version(request, major_version)
kwargs = {} if (kwar... | rsion': query_parameter_version} if query_parameter_version else None
return utils.absolute_reverse(
viewname, query_kwargs=query_kwargs, args=args, kwargs=kwargs,
)
|
# -*- coding: utf-8 -*-
from module.plugins.internal.XFSAccount import XFSAccount
class FilerioCom(XFSAccount):
__name__ = "FilerioCom"
__type__ = "ac | count"
__version__ = "0.07"
__status__ = "testing"
__description__ = """FileRio.in account plugin"""
__license__ = "GP | Lv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
PLUGIN_DOMAIN = "filerio.in"
|
import pytest
from ray.train.callbacks.results_preprocessors import (
ExcludedKeysResultsPreprocessor,
IndexedResultsPreprocessor,
SequentialResultsPreprocessor,
AverageResultsPreprocessor,
MaxResultsPreprocessor,
WeightedAverageResultsPreprocessor,
)
def test_excluded_keys_results_preprocess... | ss(results)
assert preprocessed_results == expected
def test_weighted_average_results_preprocessor():
from copy import deepcopy
import numpy | as np
results = [{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, {"a": 7, "b": 8}]
expected = deepcopy(results)
total_weight = np.sum([result["b"] for result in results])
for res in expected:
res.update(
{
"weight_avg_b(a)": np.sum(
[result... |
import re
from django.core.exceptions import ImproperlyConfigured
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from tranquil.models import Importer
__all__ = ( 'engine', 'meta', 'Session', )
class EngineCache(object):
__shared_state = dict(
engine = None,
meta = None,
... | self.engine = backend.engine
else:
options = {
'protocol': self._mappings.get( settings.DATABASE_ENGINE ),
'name': settings.DATABASE_NAME,
'user': settings.DATABASE_USER, |
'pass': settings.DATABASE_PASSWORD,
'host': settings.DATABASE_HOST,
'port': settings.DATABASE_PORT,
}
if options['protocol'] is None:
raise ImproperlyConfigured( 'Unknown database engine: %s' % settings.DATABASE_ENGINE )
url = '{protocol}://{user}:{pass}@{host}{port}/{name}'
for p in option... |
"""
Tests outgoing calls created with InitialAudio and/or InitialVideo, and
exposing the initial contents of incoming calls as values of InitialAudio and
InitialVideo
"""
import operator
from servicetest import (
assertContains, assertEquals, assertLength,
wrap_channel, EventPattern, call_async, make_channel_... | ath),
cs.CHANNEL_TYPE_STREAMED_MEDIA, ['MediaSignalling'])
props = chan.Properties.GetAll(cs.CHANNEL_TYPE_STREAMED_MEDIA)
assertContains(('InitialAudio', False), props.items())
assertContains(('InitialVideo', False), props.items())
# W | e shouldn't have started a session yet, so there shouldn't be any
# session handlers. Strictly speaking, there could be a session handler
# with no stream handlers, but...
session_handlers = chan.MediaSignalling.GetSessionHandlers()
assertLength(0, session_handlers)
def check_iav(jt, q, conn, bus, stre... |
e('\n'.join(lines).encode('utf-8'))
pipeline = TestPipeline()
pcoll = pipeline | 'Read' >> ReadFromText(
file_name,
compression_type=CompressionTypes.BZIP2)
assert_that(pcoll, equal_to(lines))
pipeline.run()
def test_read_corrupted_bzip2_fails(self):
_, lines = write_... | \n'.join(lines).encode('utf-8'))
with open(file_name, 'wb') as f:
f.write(b'corrupt')
pipeline = TestPipeline()
pcoll = pipeline | 'Read' >> ReadFromText(
fi | le_name,
compression_type=CompressionTypes.BZIP2)
assert_that(pcoll, equal_to(lines))
with self.assertRaises(Exception):
pipeline.run()
def test_read_bzip2_concat(self):
with TempDir() as tempdir:
bzip2_file_name1 = tempdir.create_temp_file()
lines = ['a', 'b', 'c']
... |
fro | m django.dispatch import receiver
from pretix.base.signals import register_payment_providers
|
@receiver(register_payment_providers, dispatch_uid="payment_paypal")
def register_payment_provider(sender, **kwargs):
from .payment import Paypal
return Paypal
|
from django.db import models
class AdjacencyListModel(models.Model):
title = models.CharField(max_length=100)
parent = models.ForeignKey(
'self', related_name='%(class)s_parent', on_delete=models.CASCADE, db_index=True, null=True, blank=True)
def __str__(self):
return 'adjacencylistmode... | dex=True)
level = models.IntegerField(db_index=Tru | e)
def __str__(self):
return 'nestedsetmodel_%s' % self.title
|
# -*- coding: utf-8 -*-
# Generate | d by Django 1.11.13 on 2019-04-10 03:58
from __future__ import | unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('netdevice', '0006_auto_20190409_0325'),
]
operations = [
migrations.RenameField(
model_name='vrf',
old_name='vrf_name',
new_name='name',
... |
from functools import reduce
class ScopedString (object):
def __init__ (self):
self._stack = []
def push (self, frame):
self._stack.append (frame)
def pop (self):
frame = self._stack.pop()
return frame
def __str__ (self... | self._stack.insert (0, {})
def pop (self):
if (len (self._stack) <= 1):
raise IndexError ("Attempt to pop global scope")
tem | p = self._stack[0]
del (self._stack[0])
return temp
def _normalize (self):
normal = {}
for frame in self._stack:
for key, value in frame.items():
if key not in normal:
... |
"""A likelihood function representing a Student-t distribution.
Author:
Ilias Bilionis
Date:
1/21/2013
"""
__all__ = ['StudentTLikelihoodFunction']
import numpy as np
import scipy
import math
from . import GaussianLikelihoodFunction
class StudentTLikelihoodFunction(GaussianLikelihoodFunction):
"""An... | Likelihood Function'):
"""Initialize the object.
Arguments:
nu --- The degrees of freedom of the dist | ribution.
Keyword Arguments
num_input --- The number of inputs. Optional, if
mean_function is a proper Function.
data --- The observed data. A vector. Optional,
if mean_funct... |
# 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.
# --------------------------------------------------------------------... | eld(name="state", type=SearchFieldDataType.String),
], collection=True)
]
cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60)
scoring_profile = ScoringProfile(
name="MyProfile"
)
scoring_profiles = []
scoring_profiles.append(scoring_profile)
index = Sear... | wait client.create_or_update_index(index=index)
# [END update_index_async]
async def delete_index():
# [START delete_index_async]
name = "hotels"
await client.delete_index(name)
# [END delete_index_async]
async def main():
await create_index()
await get_index()
await update_index()
... |
def RGB01ToHex(rgb):
"""
Return an RGB color | value as a hex color string.
"""
return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb])
def hexToRGB01(hexColor):
"""
Return a hex color string as an RGB tuple of floats in the range 0..1
"""
h = hexColor.lstrip('#')
return tuple([x / 255.0 for x in [int(h[i:i + 2], 16) for i in (0, 2... | ]])
|
"""
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 this ... | copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific languag... | ):
import params
env.set_params(params)
# run fs list command to make sure ECS client can talk to ECS backend
list_command = format("fs -ls /")
if params.security_enabled:
Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"),
user=params.hdfs_user
)... |
# Copyright (c) 2008 Mikeal Rogers
#
# 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 agre... | imitations under the License.
from dealer.git import git
from django.template import RequestContext
requestcontext = None
class MakoMiddleware(object):
def process_request(self, request):
global requestcontext
requestcontext = RequestContext(request)
| requestcontext['is_secure'] = request.is_secure()
requestcontext['site'] = request.get_host()
requestcontext['REVISION'] = git.revision
|
"""
Module with functionality for splitting and shuffling datasets.
"""
import numpy as np
from sklearn.utils import murmurhash3_32
from spotlight.interactions import Interactions
def _index_or_none(array, shuffle_index):
if array is None:
return None
else:
return array[shuffle_index]
de... | random_state=random_state)
cutoff = int((1.0 - test_percentage) * len(interactions))
train_idx = slice(None, cutoff)
test_idx = slice(cutoff, None)
train = Interaction | s(interactions.user_ids[train_idx],
interactions.item_ids[train_idx],
ratings=_index_or_none(interactions.ratings,
train_idx),
timestamps=_index_or_none(interactions.timestamps,
... |
, {'primary_key': 'True'}),
'mep': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['meps.MEP']"}),
'party': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Party']"})
},
'meps.delegation': {
'Meta': {'object_name': 'Delegation'},
... | s.fields.AutoField', [], {'primary_key': 'True'}),
'opinion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Opinion']"}),
'representative': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Representative']"})
},
'reps.party': {
... | unique': 'True', 'max_length': '255'})
},
'reps.partyrepresentative': {
'Meta': {'object_name': 'PartyRepresentative'},
'current': ( |
# importing libraries:
import maya.cmds as cmds
import maya.mel as mel
# global variables to this module:
CLASS_NAME = "Arm"
TITLE = "m028_arm"
DESCRIPTION = "m029_armDesc"
ICON = "/Icons/dp_arm.png"
def Arm(dpAutoRigInst):
""" This function will create all guides needed to compose an arm.
"""
# chec... | langName]['e001_GuideNotChecked'] +' - '+ (", ").join(checkResultList) +' | \";')
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-28 15:26
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations. | Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('genevieve_client', '0003_variant_myvariant_dbsnp'),
]
operations = [
migrations.CreateModel(
name='OpenHumansUser',
fields=[
('id', models.AutoField(aut... | ize=False, verbose_name='ID')),
('access_token', models.CharField(blank=True, max_length=30)),
('refresh_token', models.CharField(blank=True, max_length=30)),
('token_expiration', models.DateTimeField(null=True)),
('connected_id', models.CharField(max_leng... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
from distribution import *
import operator as o
from utils.lib import gt, lt, gte, lte, neq, eq
__author__ = "bigfatnoob"
def sample(values, size=100):
return np.random.choice(v... |
"uniform": Uniform,
"random": Random,
"exp": Exponential,
"binomial": Binomial,
"geometric": Geometric,
"triangular": Triangular
}
operations = {
"+": o.add,
"-": o.sub,
"*": o.mul,
"/": o.div,
"|": max,
"&": o.mul,
">": to_int(gt),
| "<": to_int(lt),
">=": to_int(gte),
"<=": to_int(lte),
"==": to_int(eq),
"!=": to_int(neq)
}
|
#!/usr/bin/env python
"""Distutils setup file, used to install or test 'setuptools'"""
import textwrap
import sys
try:
import setuptools
except ImportError:
sys.stderr.write("Distribute 0.7 may only upgrade an existing "
"Distribute 0.6 installation")
raise SystemExit(1)
long_description = textwr... | Topic :: Software Development :: Libraries :: Python Modules
Topic :: System :: Archiving :: Packaging
Topic :: System :: Systems Administration
Topic :: Utilities
""").strip().splitlines(),
install_requires=[
'setuptools>=0.7',
],
)
|
if __name__ == '__main__':
setuptools.setup(**setup_params)
|
from django.core.management.base import BaseCommand, CommandError
from t | weets.tasks import stream
#The class must be named | Command, and subclass BaseCommand
class Command(BaseCommand):
# Show this when the user types help
help = "My twitter stream command"
# A command must define handle()
def handle(self, *args, **options):
stream()
|
#!/usr/bin/env python
# coding=utf-8
"""
Created on April 15 2017
@author: yytang
"""
from scrapy import Selector
from libs.misc import get_spider_name_from_domain
from libs.polish import polish_title, polish_subtitle, polish_content
from novelsCrawler.spiders.novelSpider import NovelSpider
class PiaotianSpider(No... | # sel = Selector(response)
# content = sel.xpath('//div[@id="content"]/p/text()').extract()
# content = polish_content(content)
html = str(response.body.decode('GBK'))
pattern = r' (.*)'
import re
m = re.search(pattern, html)
if m:
... | p(1)
else:
content = ''
content = content.replace('<br /><br /> ', '\n\n')
return content
|
a, b = <warning descr="Need more val | ues to unpack">None | </warning> |
"""
@author: dhoomake | thu
"""
from __future__ import absolute_import | , unicode_literals |
#!/usr/env/bin/ python3
from setuptools import setup, Extension
#
#CXX_FLAGS = "-O3 -std=gnu++11 -Wall -Wno-comment"
#
## List of C/C++ sources that will conform the library
#sources = [
#
# "andrnx/clib/android.c",
#
#]
setup(name="andrnx",
version="0.1",
description="Package to convert from GNSS log... | nfo@rokubun.cat',
url='https://www.rokubun.cat',
packages=['andrnx'],
te | st_suite="andrnx.test",
scripts=['bin/gnsslogger_to_rnx'])
|
class DrawingDimensioningWorkbench (Workbench):
# Icon generated using by converting linearDimension.svg to xpm format using Gimp
Icon = '''
/* XPM */
static char * linearDimension_xpm[] = {
"32 32 10 1",
" c None",
". c #000000",
"+ c #0008FF",
"@ c #0009FF",
"# c #000AFF",
"$ c ... | weldingCommandList = weldingSymbols.weldingCmds
self.appendToolbar('Drawing Dimensioning Welding Symbols', weldingCommandList)
| self.appendToolbar('Drawing Dimensioning Help', [ 'dd_help' ])
FreeCADGui.addIconPath(iconPath)
FreeCADGui.addPreferencePage( os.path.join( __dir__, 'Resources', 'ui', 'drawing_dimensioing_prefs-base.ui'),'Drawing Dimensioning' )
Gui.addWorkbench(DrawingDimensioningWorkbench())
|
# Copyright (c) 2009-2010 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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, o... | ibuted 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,... | Boston, MA 02110-1301 USA.
from tortoisehg.util import hglib, patchctx
from tortoisehg.hgqt.qtlib import geticon, getoverlaidicon
from PyQt4.QtCore import *
from PyQt4.QtGui import *
nullvariant = QVariant()
def getSubrepoIcoDict():
'Return a dictionary mapping each subrepo type to the corresponding icon'
... |
"""Maya initialisation for Mindbender pipeline"""
from maya import cmds
def setup():
assert __import__("pyblish_maya").is_setup(), (
"pyblish-mindbender dep | ends on pyblish_maya which has not "
"yet | been setup. Run pyblish_maya.setup()")
from pyblish import api
api.register_gui("pyblish_lite")
from mindbender import api, maya
api.install(maya)
# Allow time for dependencies (e.g. pyblish-maya)
# to be installed first.
cmds.evalDeferred(setup)
|
""":mod:`kinsumer.checkpointer` --- Persisting positions for Kinesis shards
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import abc
import json
import os.path
from typing import Optional, Dict
class Checkpointer(abc.ABC, object):
"""Checkpointer is the interface for persisting ... | of the last record processed for
its shard
"""
@abc.abstractmethod
def checkpoint(self, shard_id: str, sequence: str) -> None:
"""Persist the sequence number for a given shard"""
@abc.abstractmethod
def get_checkpoint(self, shard_id: str) -> Optional[str]:
" | ""Get the sequence number of the last successfully processed record"""
class InMemoryCheckpointer(Checkpointer):
def __init__(self) -> None:
self._checkpoints = {}
def get_checkpoints(self) -> Dict[str, str]:
return self._checkpoints.copy()
def checkpoint(self, shard_id: str, sequence: s... |
class ParametrizedError(Exception):
def __init__(self, problem, invalid):
self.problem = str(problem)
self.invalid = str(invalid)
def __str__(self):
print('--- Error: {0}\n--- Caused by: {1}'.format(self.problem, self.invalid))
class InvalidToken(ParametrizedError):
pass
class ToneError(Parametri... | class ComposingError(P | arametrizedError):
pass |
# Copyright 2016 F5 Networks 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 writi... | get_status(self, request, mgmt_root):
failover_status = | mgmt_root.tm.cm.failover_status
assert failover_status._meta_data['uri'].endswith(
"/mgmt/tm/cm/failover-status/")
failover_status.refresh()
des =\
(failover_status.entries['https://localhost/mgmt/tm/cm/failover-status/0']
['nestedStats']
['entri... |
# third party
# third party
import numpy as np
import pytest
# syft absolute
# absolute
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def test | _bit_extraction() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
exp_res1 = np.array([[False | , False], [True, False]], dtype=np.bool_)
res = share.bit_extraction(31).child
assert (res == exp_res1).all()
exp_res2 = np.array([[True, False], [False, False]], dtype=np.bool_)
res = share.bit_extraction(2).child
assert (res == exp_res2).all()
@pytest.mark.smpc
def test_bit_extraction_exceptio... |
/Code/AltAnalyze/AltDatabase/EnsMart72/ensembl/Mm/Mm_Ensembl_exon.txt'
reference_rows=0
if '.gtf' in refExonCoordinateFile: firstLine = False
else: firstLine = True
for line in open(refExonCoordinateFile,'rU').xreadlines():
if firstLine: firstLine=False
else:
line = line.rstr... | elif opt == '--m': ### Run each BAM file on a different processor
if arg == 'yes': useMultiProcessing=True
elif arg == 'True': useMultiProce | ssing=True
else: useMultiProcessing=False
else:
print "Warning! Command-line argument: %s not recognized. Exiting..." % opt; sys.exit()
if len(analysisType) == 0:
analysisType = ['exon','junction','reference']
try:
refExonCoordi... |
#!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... | ds_arr
def get_home_data(request):
if not request.method == 'GET':
raise HttpResponseNotAllowed('GET')
lastID = request.GET.get('lastid')
limit = request.GET.get('limit') or 20
session = DBSession()
datas = None
| if lastID:
datas = session.query(Article).order_by(desc(Article.id)).filter(and_(Article.introduction != None, Article.id < lastID)).limit(limit).all()
else:
datas = session.query(Article).order_by(desc(Article.id)).limit(limit).all()
values = []
for data in datas:
values.append({... |
ET,
CONF_DEVICE_ID,
CONF_ENTITIES,
CONF_NAME,
CONF_TRACK,
DEVICE_SCHEMA,
SERVICE_SCAN_CALENDARS,
do_setup,
)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.setup import async_setup_component
from homeassistant... | AME,
"message": event["summary"],
"all_day": True,
"offset_reached": False,
"start_time": week_from_today.strftime(DATE_STR_FORMA | T),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
async def test_future_event(hass, mock_next_event):
"""Test that we can create an event trigger on device."""
one_hour_from_now = dt_util.now() + dt_util.dt.ti... |
# Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of t... | pp.__Int3D.x(v, [0)
:param v:
:param [0:
:type v:
:type [0:
:rtype:
.. funct | ion:: espressopp.__Int3D.y(v, [1)
:param v:
:param [1:
:type v:
:type [1:
:rtype:
.. function:: espressopp.__Int3D.z(v, [2)
:param v:
:param [2:
:type v:
:type [2:
:rtype:
.. function:: espressopp.toInt3DFromVector(\*args)
:param \*args:
:type \*args:
.. function:: espressopp.t... |
# -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2018-2020)
#
# This file is part of GWpy.
#
# GWpy 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)... | c.get_paths()) == len(segments)
assert ax.get_epoch() == segments[0][0]
# test y
p = ax.plot_segmentlist(segments).get_paths()[0].get_extents()
assert p.y0 + p.height/2. == 1.
| p = ax.plot_segmentlist(segments, y=8).get_paths()[0].get_extents()
assert p.y0 + p.height/2. == 8.
# test kwargs
c = ax.plot_segmentlist(segments, label='My segments',
rasterized=True)
assert c.get_label() == 'My segments'
assert c.get_rasterize... |
# Copyright (c) 2008 Chris Moyer http://coredumped.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, ... | R IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Qualifications:
def __init__(self, requirements=None):
if requirements == None:
requirements = []
self.requirements = requireme... | self.requirements.append(req)
def get_as_params(self):
params = {}
assert(len(self.requirements) <= 10)
for n, req in enumerate(self.requirements):
reqparams = req.get_as_params()
for rp in reqparams:
params['QualificationRequirement.%s.%s' % ((n+1... |
# Determine whether an integer is a palindrome. Do this without extra space.
class Solution:
# @return a boolean
def isPalindrome1(self, x):
if x < 0 or x % 10 == 0 and x: |
return False
xhalf = 0
while x > xhalf:
xhalf = xhalf * 10 + x % 10
x /= 10
return (x == xhalf or x == xhalf/10
)
def isPalindrome(self, x):
if x < 0:
return False |
size, xreverse = x, 0
while size:
xreverse = xreverse * 10 + size % 10
size = (size - (size % 10)) / 10
return True if xreverse==x else False
if __name__ == '__main__':
s = Solution()
print s.isPalindrome1(0) |
'''
Created on Aug 27, 2013
@author: De | von
Define gui events
'''
from pyHopeEngine import BaseEvent
class Event_ButtonPressed(BaseEvent):
'''Sent when a button is pressed'''
eventType = "ButtonPressed"
def | __init__(self, value):
'''Contains a value identifying the button'''
self.value = value
class Event_ScreenResize(BaseEvent):
'''Sent when a screen resize is requestsed'''
eventType = "ScreenResize"
def __init__(self, width, height):
self.width = width
self.height = hei... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
import time
import datetime
conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal")
cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather")... | at(row[1], row[0]))
cursar.execute("""UPDATE new_v4_users_probes_edit SET email = %s WHERE userid = %s""", | (row[1], row[0]))
cursar.execute("""SELECT probename, probeid FROM new_v4_sonde""")
rows = cursar.fetchall()
for row in rows:
cursar.execute("""SHOW TABLES LIKE %s""",("%" + row[0] + "%",))
rowsbis = cursar.fetchall()
for rowbis in rowsbis:
result = rowbis[0].split("_")
month = 1 + int(result[4])... |
# I made some modifications to termcolor so you can pass HEX colors to
# the colored function. It then chooses the nearest xterm 256 color to
# that HEX color. This requires some color functions that I have added
# in my python path.
#
# 2015/02/16
#
#
# coding: utf-8
# Copyright (c) 2008-2011 Volvox Development Team
... | , color)
RGB = rgb(color)
x256_color_index = from_rgb(RGB[0], RGB[1], RGB[2])
text = "\033[38;5;%dm | %s" % (x256_color_index, text)
else:
text = fmt_str % (COLORS[color], text)
if on_color is not None:
if "#" in on_color:
on_color = re.sub("[#]", "", on_color)
RGB = rgb(on_color)
x256_color_index = from_rgb(RGB[0], RGB[1],... |
#! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... | array.
def findMinDuplicate(self, num):
INT_MIN_VALUE = -(2**32)
size = len(num)
if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_i... | [mid_index] > num[high_index]):
low_index = mid_index
elif (num[mid_index] < num[high_index]):
high_index = mid_index
else:
high_index -= 1
return min(num[low_index], num[high_index])
if __name__ == '__main__':
solution = Solution()
... |
import pytest
import re
import capybara
class TestHasSelector:
@pytest.fixture(autouse=True)
def setup_session(self, session):
session.visit("/with_html")
def test_is_true_if_the_given_selector_is_on_the_page(self, session):
assert session.has_selector("xpath", "//p")
assert sess... | test_only_matches_elements_that_match_exactly_when_exact_text_true(self, session):
assert session.has_selector("id", "h2one", text="Header Class Test One", exact_text=True)
assert not session.has_selector("id", "h2one", text="Header Class Test", ex | act_text=True)
def test_matches_substrings_when_exact_text_false(self, session):
assert session.has_selector("id", "h2one", text="Header Class Test One", exact_text=False)
assert session.has_selector("id", "h2one", text="Header Class Test", exact_text=False)
class TestHasNoSelector:
@pytest.f... |
#
# Copyright (C) 2017 Smithsonian Astrophysical Observatory
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#... | h this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
This is based on sherpa/sim/tests_sim_unit.py.
"""
from sherpa.astro import sim
# This is part of #3 | 97
#
def test_list_samplers():
"""Ensure list_samplers returns a list."""
mcmc = sim.MCMC()
samplers = mcmc.list_samplers()
assert isinstance(samplers, list)
assert len(samplers) > 0
def test_list_samplers_contents():
"""Are the expected values included"""
# Test that the expected value... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 12