repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
tableau/TabPy
tabpy/tabpy_server/handlers/endpoint_handler.py
Python
mit
4,926
0.001015
""" HTTP handeler to serve specific endpoint request like http://myserver:9004/endpoints/mymodel For how generic endpoints requests is served look at endpoints_handler.py """ import json import logging import shutil from tabpy.tabpy_server.common.util import format_exception from tabpy.tabpy_server.handlers import Ma...
ts(name) if len(endpoints) == 0: self.error_out(404, f"endpoint {name} does not exist.") self.finish() return # update state try: endpoint_info = self.tabpy_state.delete_end
point(name) except Exception as e: self.error_out(400, f"Error when removing endpoint: {e.message}") self.finish() return # delete files if endpoint_info["type"] != "alias": delete_path = get_query_object_path( ...
jamesbeebop/evennia
evennia/contrib/tutorial_examples/cmdset_red_button.py
Python
bsd-3-clause
9,705
0.001443
""" This defines the cmdset for the red_button. Here we have defined the commands and the cmdset in the same module, but if you have many different commands to merge it is often better to define the cmdset separately, picking and choosing from among the available commands as to what should be included in the cmdset - t...
-------------- # We next tuck these commands into their respective command sets. # (note that we are overdoing the cdmset separation a bit here # to show how it works). class DefaultCmdSet(CmdSet): """ The default cmdset always sits on the button object and whereas other command sets may be added/mer...
using obj.cmdset.add_default(). """ key = "RedButtonDefault" mergetype = "Union" # this is default, we don't really need to put it here. def at_cmdset_creation(self): "Init the cmdset" self.add(CmdPush()) class LidClosedCmdSet(CmdSet): """ A simple cmdset tied to the red...
xbmc/xbmc-antiquated
xbmc/lib/libPython/Python/Lib/plat-sunos5/IN.py
Python
gpl-2.0
28,151
0.005044
# Generated by h2py from /usr/include/netinet/in.h # Included from sys/feature_tests.h # Included from sys/isa_defs.h _CHAR_ALIGNMENT = 1 _SHORT_ALIGNMENT = 2 _INT_ALIGNMENT = 4 _LONG_ALIGNMENT = 8 _LONG_LONG_ALIGNMENT = 8 _DOUBLE_ALIGNMENT = 8 _LONG_DOUBLE_ALIGNMENT = 16 _POINTER_ALIGNMENT = 8 _MAX_ALIGNMENT = 16 _A...
= 4 _XOPEN_VERSION = 3 from TYPES import * # Included from sys/stream.h # Included from sys/vnode.h from TYPES import * # Included from sys/t_lock.h # Included from sys/machlock.h from TYPES import * LOCK_HELD_VALUE = 0xff def SPIN_LOCK(pl): return ((pl) > iplt
ospl(LOCK_LEVEL)) def LOCK_SAMPLE_INTERVAL(i): return (((i) & 0xff) == 0) CLOCK_LEVEL = 10 LOCK_LEVEL = 10 DISP_LEVEL = (LOCK_LEVEL + 1) PTR24_LSB = 5 PTR24_MSB = (PTR24_LSB + 24) PTR24_ALIGN = 32 PTR24_BASE = 0xe0000000 # Included from sys/param.h from TYPES import * _POSIX_VDISABLE = 0 MAX_INPUT = 512 MAX_CANON = ...
Alex-Just/gymlog
gymlog/main/tests/test_models.py
Python
mit
476
0
# from test_plus.test import TestCase # # # class TestUser(TestCase): # # def setUp(self): # self.user = self.make_user() # # def test__str__(self): # self.assertEqual( # self.user.__str__()
, # 'testuser' # This is the default username for self.make_user() # ) # # def test_get_absolute_url(self): # self.assertEqual( # self.user.get_absolute_url(), #
'/users/testuser/' # )
zokeber/django-galeria
setup.py
Python
bsd-3-clause
1,378
0.002177
#/usr/bin/env python import codecs import os import sys from setuptools import setup, find_packages if 'publish' in sys.argv: os.system('python setup.py sdist upload') sys.exit() read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read() # Dynamically calculate the version based on galeria.VERSIO...
='Guilherme Gondim', a
uthor_email='semente+django-galeria@taurinus.org', maintainer='Guilherme Gondim', maintainer_email='semente+django-galeria@taurinus.org', license='BSD License', url='https://bitbucket.org/semente/django-galeria/', packages=find_packages(), zip_safe=False, include_package_data=True, class...
rackerlabs/instrumented-ceilometer
ceilometer/openstack/common/rpc/proxy.py
Python
apache-2.0
9,444
0
# Copyright 2012-2013 Red Hat, 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...
wargs): """Helper method called to serialize message arguments. This calls our serializer on eac
h argument, returning a new set of args that have been serialized. :param context: The request context :param kwargs: The arguments to serialize :returns: A new set of serialized arguments """ new_kwargs = dict() for argname, arg in kwargs.iteritems(): ...
varunnaganathan/django
tests/auth_tests/test_auth_backends.py
Python
bsd-3-clause
25,359
0.001814
from __future__ import unicode_literals from datetime import date from django.contrib.auth import ( BACKEND_SESSION_KEY, SESSION_KEY, authenticate, get_user, ) from django.contrib.auth.backends import ModelBackend from django.contrib.auth.hashers import MD5PasswordHasher from django.contrib.auth.models import Ano...
Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') ...
k) self.assertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'}) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.obj...
dajohnso/cfme_tests
cfme/intelligence/reports/dashboards.py
Python
gpl-2.0
10,188
0.001276
# -*- coding: utf-8 -*- """Page model for Cloud Intel / Reports / Dashboards""" from navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.widget import Text, Checkbox from widgetastic_manageiq import SummaryFormItem, DashboardWidgetsPicker from widgetastic_patternfly import Button, Input from utils...
el)) return items @property def is_displayed(self): return ( self.in_intel_reports and self.title.text == 'Dashboard "{} ({})"'.format( self.context["object"].title, self.context["object"].name ) and self.dashboards...
"All Groups", self.context["object"].group, self.context["object"].name ] ) class DefaultDashboardDetailsView(DashboardDetailsView): @property def is_displayed(self): return ( self.in_intel_reports and self.title.text ==...
akloster/bokeh
examples/plotting/server/burtin.py
Python
bsd-3-clause
4,826
0.005387
# The plot server must be running # Go to http://localhost:5006/bokeh to view this plot from collections import OrderedDict from math import log, sqrt import numpy as np import pandas as pd from six.moves import cStringIO as StringIO from bokeh.plotting import figure, show, output_server antibiotics = """ bacteria,...
e_color="white") p.text(x[:-1], radii[:-1], [str(r) for r in labels[:-1]], text_font_size="8pt", text_align="center", text_baseline="middle") # radial axes p.annular_wedge(x, y, inner_radius-10, outer_radius+10, -bi
g_angle+angles, -big_angle+angles, color="black") # bacteria labels xr = radii[0]*np.cos(np.array(-big_angle/2 + angles)) yr = radii[0]*np.sin(np.array(-big_angle/2 + angles)) label_angle=np.array(-big_angle/2+angles) label_angle[label_angle < -np.pi/2] += np.pi # easier to read labels on the left side p.text(xr, yr, ...
chrism333/xpcc
scons/site_tools/system_design.py
Python
bsd-3-clause
7,787
0.038012
#!/usr/bin/env python # # Copyright (c) 2009, Roboterclub Aachen e.V. # 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 # ...
CC_SYSTEM_DESIGN_SCANNERS']['XML'], single_source = True, target_factory = env.fs.Entry, src_suffix = ".xml") env['BUILDERS']['SystemCppXpccTaskCaller'] = \ SCons.Script.Builder( action = SCons.Action.Action( 'python "${XPCC_SYSTEM_BUILDER}/cpp_xpcc_task
_caller.py" ' \ '--outpath ${TARGET.dir} ' \ '--dtdpath "${dtdPath}" ' \ '--namespace "${namespace}" ' \ '$SOURCE', cmdstr="$SYSTEM_CPP_XPCC_TASK_CALLER_COMSTR"), emitter = xpcc_task_caller_emitter, source_scanner = env['XPCC_SYSTEM_DESIGN_SCANNERS']['XML'], single_source = True, tar...
zzsza/TIL
python/sacred/my_command.py
Python
mit
345
0.002899
from sacred import Experiment ex = Experiment('my_commands') @ex.config def cfg(): name = 'kyle' @ex.command def greet(name): print('Hello {}! Nice to greet you!'.format(name)) @ex.command def shout(): print
('WHAZZZUUUUUUUUUUP!!!????') @ex.automain def main(): print('This is jus
t the main command. Try greet or shout.')
Noysena/TAROT
SFile.py
Python
gpl-3.0
8,161
0.010538
# -*- coding: utf-8 -*- """ Created on Thu Jul 7 14:53:55 2016 @author: nu """ import numpy as np import timeit, os, sys from astropy.coordinates import SkyCoord from astropy.table import Column from astroquery.vizier import Vizier from astropy import units as u from TAROT_PL import TarotPIP from Filter_data import ...
ite("circle(%f, %f, 16.0\") # color=green text={NOMAD1_%d}\n" %(info_candi_2["ra"][i], info_candi_2["dec"][i], i)) Candi_reg2.close() print("Number of Candidate %d" %len(info_candi_2)) print("\n"*2) except(ValueError, NameError): print("No candidate in NOMAD1\n\n") stop = timeit.default_timer(
) runtime = stop - start print("\nRuntime = %2.2f" %runtime) #graph0 = candidateplot(TAROT_data.tbdata,XYcandi['Xpix'],XYcandi['Ypix'], 'Candidate by angular separation')
jhpyle/docassemble
docassemble_webapp/docassemble/webapp/alembic/versions/9be372ec38bc_alter_database_for_mysql_compatibility.py
Python
mit
3,895
0.001284
"""alter database for mysql compatibility Revision ID: 9be372ec38bc Revises: 4328f2c08f05 Create Date: 2020-02-16 15:43:35.276655 """ from alembic import op import sqlalchemy as sa from docassemble.webapp.database import dbtableprefix, dbprefix, daconfig import sys # revision identifiers, used by Alembic. revision =...
column_name='filename', type_=sa.String(255) ) op.alter_column( table_name='shortener', column_name='filename', type_=sa.String(255) ) op.alter_column( table_name='shortener', column_name='key', ...
ype_=sa.String(255) ) op.alter_column( table_name='machinelearning', column_name='key', type_=sa.String(1024) ) op.alter_column( table_name='machinelearning', column_name='group_id', type_=sa.String(1024) ) ...
sl2017/campos
campos_event/__openerp__.py
Python
agpl-3.0
3,874
0.001807
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of CampOS Event, # an Odoo module. # # Copyright (c) 2015 Stein & Gabelgaard ApS # http://www.steingabelgaard.dk # Hans Henrik Gaelgaard ...
', "views/scout_org_view.xml", "views/res_partner_view.xml", "views/job_view.xml", "views/job_template.xml", "views/mail_templates.xml", "views/confirm_
template.xml", "views/event_view.xml", #"views/portal_menu.xml", "views/res_users_view.xml", 'views/campos_menu.xml', 'views/campos_subcamp_exception.xml', 'views/campos_subcamp.xml', 'views/event_partner_reg_template.xml', 'views/meeting_proposal_template...
hasegaw/IkaLog
ikalog/inputs/win/directshow.py
Python
apache-2.0
4,592
0.000436
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 Takeshi HASEGAWA # # 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/l...
ributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions an
d # limitations under the License. # import time import threading import cv2 from ikalog.utils import * from ikalog.inputs.win.videoinput_wrapper import VideoInputWrapper from ikalog.inputs import VideoInput class DirectShow(VideoInput): # override def _enumerate_sources_func(self): return self._...
genius1611/Keystone
keystone/contrib/extensions/admin/__init__.py
Python
apache-2.0
1,232
0.000812
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
ksadm_extenion_handler = KSADMExtensionHandler() ksadm_extenion_handler.map_extension_methods(mapper, options) kscatalog_extension_handler = KSCATALOGExtensionHandler() kscatalog_extension_handler.map_extension_methods(mapper, options
)
SecurityFTW/cs-suite
tools/Scout2/AWSScout2/services/vpc.py
Python
gpl-3.0
7,331
0.005866
# -*- coding: utf-8 -*- import netaddr from opinel.utils.aws import get_name from opinel.utils.globals import manage_dictionary from opinel.utils.fs import load_data, read_ip_ranges from AWSScout2.utils import ec2_classic, get_keys from AWSScout2.configs.regions import RegionalServiceConfig, RegionConfig from AWSSc...
(network_acl, network_acl, 'id') manage_dictionary(network_acl, 'rules', {}) network_acl['rules']['ingress'] = self.__parse_network_acl_entries(network_acl['Entries'], False)
network_acl['rules']['egress'] = self.__parse_network_acl_entries(network_acl['Entries'], True) network_acl.pop('Entries') # Save manage_dictionary(self.vpcs, vpc_id, SingleVPCConfig(self.vpc_resource_types)) self.vpcs[vpc_id].network_acls[network_acl['id']] = network_acl def __...
alper/volunteer_planner
notifications/migrations/0004_auto_20151003_2033.py
Python
agpl-3.0
847
0.001181
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('organizations', '0002_migrate_locatio
ns_to_facilities'), ('notifications', '0003_auto_20150912_2049'), ] operations = [ migrations.AlterField( model_name='notification', name='location', field=models.ForeignKey(verbose_name='facility', to='organizations.Facility'), ), migrations....
notification', old_name='location', new_name='facility', ), migrations.AlterField( model_name='notification', name='facility', field=models.ForeignKey(to='organizations.Facility'), ), ]
dading/iphone_order
util.py
Python
apache-2.0
3,365
0.012184
#__author__ = 'hello' # -*- coding: cp936 -*- import re import os import random import json import string import ctypes from myexception import * PATH = './img/' dm2 = ctypes.WinDLL('./CrackCaptchaAPI.dll') if not os.path.exists('./img'): os.mkdir('./img') def str_tr(content): instr = "0123456789" outs...
ef getCToken(content): s = '' pattern = re.compile('securityCToken = "([+-]?\d*)"') match = pattern.search(content) if match: s = match.group(1) return s def GetCaptcha(content): global PATH filename = ''.join(random.sample(string.ascii_letters,8)) filename += '.jpg' filenam...
if img: img.close() dm2.D2File.argtypes=[ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_short, ctypes.c_int, ctypes.c_char_p] dm2.D2File.restype = ctypes.c_int key = ctypes.c_char_p('fa6fd217145f273b59d7e72c1b63386e') id = ctypes.c_long(54) user = ctypes....
zqfan/leetcode
algorithms/576. Out of Boundary Paths/solution.py
Python
gpl-3.0
918
0
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 10000
00007 paths = 0 cur = {(i, j): 1} for i in xrange(N): next = collections.defaultdict(int) for (x, y), cnt in cur.iteritems(): for dx, dy in [[-1, 0], [0, 1], [1, 0], [0, -1]]: nx = x + dx ny = y + dy ...
nt next[(nx, ny)] %= MOD cur = next return paths # 94 / 94 test cases passed. # Status: Accepted # Runtime: 232 ms # beats 75.36 %
rcucui/Pisa-util-fix
sx/pisa3/pisa_util.py
Python
apache-2.0
26,330
0.006077
# -*- coding: ISO-8859-1 -*- # Copyright 2010 Dirk Holtwick, holtwick.it # # 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 requir...
pfile import shutil rgb_re = re.compile("^.*?rgb[(]([0-9]+).*?([0-9]+).*?([0-9]+)[)].*?[ ]*$") _reportlab_version = tuple(map(int, reportlab.Version.split('.'))) if _reportlab_version < (2,1): rais
e ImportError("Reportlab Version 2.1+ is needed!") REPORTLAB22 = _reportlab_version >= (2, 2) #if not(reportlab.Version[0] == "2" and reportlab.Version[2] >= "1"): # raise ImportError("Reportlab Version 2.1+ is needed!") # #REPORTLAB22 = (reportlab.Version[0] == "2" and reportlab.Version[2] >= "2") # print "***", re...
bigfootproject/OSMEF
data_processing/aggregate_old.py
Python
apache-2.0
4,348
0.00483
#!/usr/bin/python import sys, os, re import json import argparse import pprint arg_parser = argparse.ArgumentParser(description='Define tests') arg_parser.add_argument('-p', '--pretty-print', action="store_true", help="select human friendly output, default is CSV") arg_parser.add_argument('-i', '--info', action="stor...
for key in dotted_key: value = value[key] return value def get_keys(f): keys = [] t = data[f] unvisited = list(t.keys()) while len(unvisited) > 0: k = unvisited.pop() child = dotkey(t, k) if type(child) != dict: keys.append(k) else: ...
+= t[k] # values = [] # k = key.split(".") # for d in data: # values.append(get_value(d, k)) # return values def print_csv_header(columns): out = "measurement" for title in columns: out += ", " + title print(out) def get_values_measurement(tree, keys): out = [] for key i...
Dahlgren/HTPC-Manager
htpc/updater.py
Python
mit
21,554
0.002366
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update HTPC Manager from Github. Either through git command or tarball. Updater and SourceUpdater written by styxit https://github.com/styxit Git updater written by mbw2001 https://github.com/mbw2001 Used as reference: - https://github.com/mrkipling/maraschino - htt...
nd']) + " commits behind.") return output
def behind_by(self, current, latest): """ Check how many commits between current and latest """ self.logger.debug('Checking how far behind latest') try: url = 'https://api.github.com/repos/%s/%s/compare/%s...%s' % (gitUser, gitRepo, current, latest) result = loads(urllib2...
neuroticnerd/django-demo-app
django_demo/accounts/views.py
Python
mit
1,886
0
from django.conf import settings from django.contrib import auth from django.contrib.auth.forms import AuthenticationForm from django.utils.decorators import method_decorator from django.utils.http import is_safe_url from django.views.decorators.debug import sensitive_post_parameters from django.views import generic fr...
ings.LOGIN_REDIRECT_URL form_
class = AuthenticationForm redirect_param = getattr(settings, 'REDIRECT_FIELD_NAME', 'next') template_name = 'accounts/login.html' @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs)...
lcy0321/pbaadhcpserver
pbaadhcpserver.py
Python
gpl-3.0
15,974
0.00144
#!/usr/bin/python2 # -*- encoding: utf-8 -*- #pylint: disable=W0105 import argparse import logging import configparser import requests from libpydhcpserver.dhcp import DHCPServer class PBAADHCPServer(DHCPServer): def __init__( self, server_address, server_port, client_port, aaserver_addr, ...
terface_qtags ) def _handleDHCPDecline(self, packet, source_address, port): """Processes a DECLINE packet. Override from DHCPServer. Send the packet's info to the AA server. Args: packet (dhcp_types.packet.DHCPPacket): The packet to...
The port on which the packet was received. """ logging.info('recieved DHCPDECLINE from: %s:%s', source_address.ip, source_address.port) logging.debug('\n%s\n', packet) self._get_client_options( 'DHCP_DECLINE', self._get_packet_info(packet...
danithaca/berrypicking
python/excercise/march31.py
Python
gpl-2.0
644
0.007764
def find_number(x): str_x = str(x) if len(str_x) == 1: raise Exception() left_mo
st = str_x[0] try: small_from_rest = find_number(int(str_x[1:])) return int(left_most + str(small_from_rest)) except: #
min() will throw exception if parameter is empty list, meaning no digit is greater than the left_most digit. new_left_most = min([c for c in str_x[1:] if c > left_most]) # assumption: no repeated digit rest_of_digits = ''.join(sorted([c for c in str_x if c != new_left_most])) y = new_le...
Sophist-UK/Sophist_picard
test/formats/test_asf.py
Python
gpl-2.0
6,957
0.00115
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2019-2020 Philipp Wolfer # # 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...
.assertTrue(fmt.supports_tag('copyright')) self.assertTrue(fmt.supports_tag('compilation')) self.assertTrue(fmt.sup
ports_tag('bpm')) self.assertTrue(fmt.supports_tag('djmixer')) self.assertTrue(fmt.supports_tag('discnumber')) self.assertTrue(fmt.supports_tag('lyrics:lead')) self.assertTrue(fmt.supports_tag('~length')) for tag in self.replaygain_tags.keys(): ...
ttfseiko/openerp-trunk
openerp/addons/account_asset/account_asset.py
Python
agpl-3.0
29,177
0.008568
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
if asset.prorata:
days = total_days - float(depreciation_date.strftime('%j')) if i == 1: amount = (residual_amount * asset.method_progress_factor) / total_days * days elif i == undone_dotation_number: amount = (residual_amount * asse...
andersonsilvade/5semscript
Projeto/backend/apps/classificacaodtm_app/facade.py
Python
mit
2,641
0.004165
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from gaegraph.business_base import NodeSearch, DeleteNode from classificacaodtm_
app.commands import ListClassi
ficacaodtmCommand, SaveClassificacaodtmCommand, UpdateClassificacaodtmCommand, \ ClassificacaodtmPublicForm, ClassificacaodtmDetailForm, ClassificacaodtmShortForm def save_classificacaodtm_cmd(**classificacaodtm_properties): """ Command to save Classificacaodtm entity :param classificacaodtm_propertie...
annoviko/pyclustering
pyclustering/cluster/tests/kmeans_templates.py
Python
gpl-3.0
5,793
0.008113
"""! @brief Test templates for K-Means clustering module. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ from pyclustering.tests.assertion import assertion from pyclustering.cluster.encoder import type_encoding, cluster_encoder from pyclustering.cluster....
etric(type_metric.EUCLIDEAN_SQUARE)) itermax = kwargs.get('itermax', 200) kmeans_instance = kmeans(sample, start_centers, 0.001, ccore, metric=metric, itermax=itermax) kmeans_instance.process() clusters = kmeans_instance.get_clusters() centers = kmeans_in...
otal_wce() if itermax == 0: assertion.eq(start_centers, centers) assertion.eq([], clusters) assertion.eq(0.0, wce) return expected_wce = 0.0 for index_cluster in range(len(clusters)): for index_point in clusters[index_cluste...
ANR-COMPASS/shesha
shesha/util/writers/common/fits.py
Python
gpl-3.0
5,305
0.00754
import numpy as np from shesha.util.writers.common import dm from shesha.util.writers.common import wfs from shesha.util.writers.common import imat from astropy.io import fits def wfs_to_fits_hdu(sup, wfs_id): """Return a fits Header Data Unit (HDU) representation of a single WFS Args: sup : (compasSS...
pervisor) : supervisor wfs_id : (int) : index of the DM in the supervisor Returns: hdu : (ImageHDU) : fits representation of the DM """ hdu_name = "DM" + str(dm_id) X,Y = dm.get_actu_pos_meter(sup, dm_id) valid_subap = np.array([X,Y],dtype=np.float64) hdu = fits.ImageHDU( valid...
m_id].get_nact() hdu.header["PITCH"] = sup.config.p_dms[dm_id].get_pitch() hdu.header["COUPLING"] = sup.config.p_dms[dm_id].get_coupling() hdu.header["ALT"] = sup.config.p_dms[dm_id].get_alt() return hdu def dm_influ_to_fits_hdu(sup, dm_id, *, influ_index=-1): """Return a fits Header Data Unit (HDU...
lukedeo/fancy-cnn
datasets/yelp/yelp_w2v.py
Python
mit
1,086
0.003683
""" Comp
ute WordVectors using Yelp Data """ from gensim.models.
word2vec import Word2Vec from util.language import detect_language, tokenize_text from data_handling import get_reviews_data # Set to true for zero in in English reviews. Makes the process much slower FILTER_ENGLISH = True # Name for output w2v model file OUTPUT_MODEL_FILE = "w2v_yelp_100_alpha_0.025_window_4" PICKLED...
GdZ/scriptfile
software/googleAppEngine/lib/PyAMF/doc/tutorials/examples/actionscript/bytearray/python/settings.py
Python
mit
2,999
0.003334
# Django settings for python project. DEBUG = True import logging LOG_LEVEL = logging.INFO if DEBUG: LOG_LEVEL = logging.DEBUG logging.basicConfig( level = LOG_LEVEL, format = '[%(asctime)s %(name)s %(levelname)s] %(message)s', ) TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain...
N_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '!q2sh7ue8^=bu&wj9tb9&4fx^dayk=wnxo^mtd)xmw1y2)6$w$' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django....
EWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) ROOT_URLCONF = 'python.urls' TEMPLATE_DIRS = ( # Put strings here, like "/hom...
3DGenomes/tadbit
_pytadbit/tools/tadbit_map.py
Python
gpl-3.0
26,222
0.00492
""" information needed - path to FASTQ - path to reference genome - path to indexed reference genome - read number (1/2) - restriction enzyme used - species name - chromosome names (optional) - descriptive fields (optional, e.g. --descr=flowcell:C68AEACXX,lane:4,index:24nf) mapping strategy - iterative/fra...
s.workdir, '%s_%s_%s.png' % (path.split(opts.fastq)[-1], '-'.join(map(str, opts.renz)), param_hash)) logging.info('Generating Hi-C QC plot') dangling_ends, ligated = quality_plot(opts.fastq, r_enz=opts.renz, ...
se, savefig=fig_path) for renz in dangling_ends: logging.info(' - Dangling-ends (sensu-stricto): %.3f%%', dangling_ends[renz]) for renz in ligated: logging.info(' - Ligation sites: %.3f%%', ligated[renz]) if opts.skip_mapping: save_to_db(...
google-research/federated
compressed_communication/aggregators/comparison_methods/one_bit_sgd_test.py
Python
apache-2.0
8,373
0.00203
# Copyright 2022, Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
ent(self, value_type): factory = one_bit_sgd.OneBitSGDFactory(2.) value_type = tff.to_type(value_type) process = factory.create(value_type) state = process.initialize() client_values = [[-1.0, 1.0, 2.0]]
expected_result = [0.0, 0.0, 2.0] bitstring_length = tf.size(expected_result, out_type=tf.float32) + 64. expected_avg_bitrate = bitstring_length / tf.size(expected_result, out_type=tf.float32) expected_measurements = collections.OrderedDict( avg...
XiaJieCom/change
document/Service/nagios/nrpe/check_url.py
Python
lgpl-2.1
489
0.03272
#!/usr/bin/p
ython import sys import requests try: url = sys.argv[1] r = requests.get('http://%s' %url ,timeout=3) except requests.exceptions.Timeout: print 'url timeout\n%s' %url sys.exit(2) except: print 'url error \n%s' %url sys.exit(2) url_status = r.statu
s_code if url_status == 200: print 'url_status %s\n%s' %(url_status,url) sys.exit(0) else: print 'url_status %s\n%s' %(url_status,url) sys.exit(2)
kyle8998/Practice-Coding-Questions
CTCI/Chapter1/1.3-URLify.py
Python
unlicense
1,208
0.005795
# CTCI 1.3 # URLify import unittest # My Solution #--------------------------------
----------------------------------------------- # CTCI Solution def urlify(string, length): '''function replaces single spaces with %20 and removes trailing spaces''' new_index = len(string) for i in reversed(range(length)): if string[i] == ' ': # Replace spaces string[new_...
# Move characters string[new_index - 1] = string[i] new_index -= 1 return string #------------------------------------------------------------------------------- #Testing class Test(unittest.TestCase): '''Test Cases''' # Using lists because Python strings are immutable ...
msiemens/PyGitUp
PyGitUp/tests/test_rebase_error.py
Python
mit
1,166
0.001715
# System imports import os from os.path import join import pytest from git import * from PyGitUp.git_wrapper import RebaseError from PyGitUp.tests import basepath, write_file, init_master, update_file, testfile_name test_name = 'rebase_error' repo_path = join(basepath, test_name + os.sep) def setup(): master_pa...
r, test_name) # Modify file in our repo contents = 'completely changed!' repo_file = join(path, testfile_name) write_file(repo_file, contents) repo.index.add([repo_file]) repo.index.commit(test_name) # Modify file
in master update_file(master, test_name) def test_rebase_error(): """ Run 'git up' with a failing rebase """ os.chdir(repo_path) from PyGitUp.gitup import GitUp gitup = GitUp(testing=True) with pytest.raises(RebaseError): gitup.run()
open-dcs/dcs
examples/python/ui.py
Python
mit
1,007
0.004965
#!/usr/bin/env python #! -*- coding: utf-8 -*- from gi.repository import Cld from gi.repository import DcsCore as dc
from gi.repository import DcsUI as du from gi.repository import Gtk class DcsExample(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="DCS Example") c
onfig = Cld.XmlConfig.with_file_name("examples/cld.xml") self.context = Cld.Context.from_config(config) self.chan = self.context.get_object("ai0") self.dev = self.context.get_object("dev0") self.dev.open() if(not self.dev.is_open): print "Open device " + self.dev.id +...
MediaFire/mediafire-python-open-sdk
tests/test_smoke.py
Python
bsd-2-clause
2,879
0.000347
#!/usr/bin/python import io import os import unittest import logging import uuid from mediafire import MediaFireApi, MediaFireUploader, UploadSession from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES APP_ID = '42511' MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL') MEDIAFIRE_PASSWORD = os.environ.get('MEDI...
SmokeBaseTestCase.BaseTest): """Simple tests""" def test_user_get_info(self): result = self.api.user_get_info() self.assertEqual(result["user_info"]["display_name"], u"Coalmine Smoketest") @unittest.skipIf('CI' not in os.environ, "Running outside CI environment")
class MediaFireSmokeWithDirectoryTest(MediaFireSmokeBaseTestCase.BaseTest): """Smoke tests requiring temporary directory""" def setUp(self): super(MediaFireSmokeWithDirectoryTest, self).setUp() folder_uuid = str(uuid.uuid4()) result = self.api.folder_create(foldername=folder_uuid) ...
youtube/cobalt
third_party/llvm-project/lldb/packages/Python/lldbsuite/test/dotest_args.py
Python
bsd-3-clause
13,110
0.002517
from __future__ import print_function from __future__ import absolute_import # System modules import argparse import sys import multiprocessing import os import textwrap # Third-party modules # LLDB modules from . import configuration class ArgParseNamespace(object): pass def parse_args(parser, argv): ""...
mutil', metavar='dsymutil', dest='dsymutil', help=textwrap.dedent('Specify which dsymutil to use.')) # Test filtering options group = parser.add_argument_group('Test filtering options') group.add_argument( '-f', metavar='filterspec', action='append', help='Specify a filter, ...
skip long running tests") group.add_argument( '-p', metavar='pattern', help='Specify a regexp filename pattern for inclusion in the test suite') group.add_argument('--excluded', metavar='exclusion-file', action='append', help=textwrap.dedent( '''Specify a file for tests to exclud...
mbr0wn/gnuradio
gr-analog/examples/fm_demod.py
Python
gpl-3.0
2,750
0.003273
#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import
gr from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio import audio from gnuradio.filter import firdes from gnuradio.fft import window import sys, ma
th # Create a top_block class build_graph(gr.top_block): def __init__(self): gr.top_block.__init__(self) input_rate = 200e3 # rate of a broadcast FM station audio_rate = 44.1e3 # Rate we send the signal to the speaker # resample from the output of the demodulator to the rate of...
RDCEP/atlas-viewer
run.py
Python
apache-2.0
45
0.022222
f
rom atlas_web
import app app.run(debug=True)
FuzzyHobbit/acme-tiny
acme_tiny.py
Python
mit
9,077
0.004407
#!/usr/bin/env python import argparse, subprocess, json, os, sys, base64, binascii, time, hashlib, re, copy, textwrap, logging try: from urllib.request import urlopen # Python 3 except ImportError: from urllib2 import urlopen # Python 2 #DEFAULT_CA = "https://acme-staging.api.letsencrypt.org" DEFAULT_CA = "htt...
csr, acme_dir, log=LOGGER, CA=DEFAULT_CA): # helper function base64 encode for jose spec def _b64(b): return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "") # parse account key to get public
key log.info("Parsing account key...") proc = subprocess.Popen(["openssl", "rsa", "-in", account_key, "-noout", "-text"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if proc.returncode != 0: raise IOError("OpenSSL Error: {0}".forma...
tommy-u/enable
enable/controls.py
Python
bsd-3-clause
22,474
0.02207
#------------------------------------------------------------------------------- # # Define standard Enable 'control' components, like text/image labels, # push buttons, radio buttons, check boxes, and so on. # # Written by: David C. Morrill # # Date: 10/10/2003 # # (c) Copyright 2003 by Enthought, Inc. # # Class...
lected', id = 'component' ), Group( 'text', ' ', 'font', ' ', 'color', ' ', 'shadow_color', ' ', 'style', id = 'text',
style = 'custom' ), Group( 'bg_color{Background Color}', '_', 'border_color', '_', 'border_size', id = 'border', style = 'custom' ), Group( 'text_position', '_', 'image_position', '_', 'image_orien...
plotly/plotly.py
packages/python/plotly/plotly/validators/sankey/hoverlabel/_bordercolor.py
Python
mit
482
0.002075
import _plotly_utils.basevalidators class BordercolorValidator(
_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="bordercolor", parent_name="sankey.hoverlabel", **kwargs ): super(BordercolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_o...
)
modoboa/modoboa
modoboa/policyd/handlers.py
Python
isc
1,435
0
"""App related signal handlers.""" import redis from django.conf import settings from django.db.models import signals from django.dispatch import receiver from modoboa.admin import models as admin_models from . import constants def set_message_limit(instance, key): """Store message limit in Redis.""" old_...
IS_HASHNAME, key): r
client.hdel(constants.REDIS_HASHNAME, key) return if old_message_limit is not None: diff = instance.message_limit - old_message_limit else: diff = instance.message_limit rclient.hincrby(constants.REDIS_HASHNAME, key, diff) @receiver(signals.post_save, sender=admin_models.Domain) de...
OCA/stock-logistics-workflow
stock_return_request/hooks.py
Python
agpl-3.0
3,276
0.001526
# Copyright 2019 Tecnativa - David # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import SUPERUSER_ID, api _logger = logging.getLogger(__name__) def pre_init_hook(cr): """Speed up the installation of the module on an existing Odoo instance""" cr.execute( ""...
UPDATE stock_move SET qty_returnable = 0 WHERE state IN ('draft', 'cancel') """ ) cr.execute( """ UPDATE stock_move SET qty_returnable = product_uom_qty WHERE state = 'done'
""" ) def post_init_hook(cr, registry): """Set moves returnable qty on hand""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) moves_draft = env["stock.move"].search([("state", "in", ["draft", "cancel"])]) moves_no_return_pendant = env["stock.move"...
alexeyqu/zadolbali_corpus
crawler/zadolbali/zadolbali/spiders/stories.py
Python
mit
1,809
0.006081
# -*- coding:utf8 -*- from scrapy import Request from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.loader.processors import Join from scrapy.loader import ItemLoader from scrapy.selector import HtmlXPathSelector, Selector from zadolbali.items import StoryItem cla...
ss="story"]/div[@class="id"]/span/text()') loader.add_xpath('title', '//div[@class="story"]/h1/text()') loader.add_value('published', str(response.request.meta['date'])) loader.add_xpath('tags', '//div[@
class="story"]/div[@class="meta"]/div[@class="tags"]/ul/li/a/@href') loader.add_xpath('text', 'string(//div[@class="story"]/div[@class="text"])') loader.add_xpath('likes', 'string(//div[@class="story"]/div[@class="actions"]//div[@class="rating"])') loader.add_xpath('hrefs', '//div[@class="story"...
theskyinflames/bpulse-go-client
vendor/github.com/youtube/vitess/py/vtdb/vtgate_cursor.py
Python
apache-2.0
9,742
0.005646
# Copyright 2012, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. """VTGateCursor, and StreamVTGateCursor.""" import itertools import operator import re from vtdb import base_cursor from vtdb import dbexceptions write_sql_pattern...
keyranges=keyranges, entity_keyspace_id_map=entity_keyspace_id_map, entity_column_name=entity_column_name, not_in_transaction=not self.is_writable(), effective_caller_id=self.effective_caller_id, **kwargs)) return self.rowcount def fetch_aggr...
order_by_columns, limit): """Fetch from many shards, sort, then remove sort columns. A scatter query may return up to limit rows. Sort all results manually order them, and return the first rows. This is a special-use function. Args: order_by_columns: The ORDER BY clause. Each element is ei...
johnmgregoire/JCAPRamanDataProcess
PlateAlignViaEdge_v4.py
Python
bsd-3-clause
16,899
0.016214
import sys,os, pickle, numpy, pylab, operator, itertools import cv2 from shutil import copy as copyfile from PyQt4.QtCore import * from PyQt4.QtGui import * import matplotlib.pyplot as plt from DataParseApp import dataparseDialog from sklearn.decomposition import NMF projectpath=os.path.split(os.path.abspath(__file__)...
h=1.3, bcknd_max_width=1.4, removedups=1\ # ) # # show_help_messages=True platemappath=getplatemappath_plateid(plateidstr) if not os.path.isdir(pathd['mainfolder']): print 'NOT A VALID FOLDER' if not os.path.isdir(pathd['savefolder']): os.mkd
ir(pathd['savefolder']) if not os.path.isdir(pathd['spectrafolder']): os.mkdir(pathd['spectrafolder']) class MainMenu(QMainWindow): def __init__(self, previousmm, execute=True, **kwargs): super(MainMenu, self).__init__(None) self.parseui=dataparseDialog(self, title='Visualize ANA, EXP, RUN ...
liyu1990/tensorflow
tensorflow/python/ops/control_flow_ops_test.py
Python
apache-2.0
3,164
0.006953
"""Tests for control_flow_ops.py.""" import tensorflow.python.platform from tensorflow.core.framework import graph_pb2 from tensorflow.python.framework import ops from tensorflow.python.framework.test_util import TensorFlowTestCase from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import st...
:
a = tf.constant(0, name="a") b = tf.constant(0, name="b") with g.device("/task:1"): c = tf.constant(0, name="c") d = tf.constant(0, name="d") with g.device("/task:2"): tf.group(a.op, b.op, c.op, d.op, name="root") gd = g.as_graph_def() self.assertProtoEquals(""" ...
nonZero/demos-python
src/examples/short/object_oriented/static_method_1.py
Python
gpl-3.0
881
0.001135
#!/usr/bin/pyth
on3 ''' This is a * sort * of static method but is ugly since the function is really global and not in the class. ''' class Book: num = 0 def __init__(self, price): self.__price = price Book.num += 1 def printit(self): print('price is', self.__price) def setPrice(self, newp...
14) b2 = Book(13) # lets access the static member and the static methods... print('Book.num (direct access) is ', Book.num) print('getNumBooks() is ', getNumBooks()) try: print(b1.getNumBooks()) except AttributeError as e: print('no,cannot access the static method via the instance') # access the static member ...
shacknetisp/vepybot
plugins/protocols/irc/auth/nickserv.py
Python
mit
4,789
0.000418
# -*- coding: utf-8 -*- import bot import time """ load irc/auth/nickserv nickserv set password hunter2 config set modules.nickserv.enabled True config set modules.nickserv.ghost True nickserv register email@do.main nickserv verify register myaccount c0d3numb3r nickserv identify """ class M_NickServ(bot.Module): ...
self.addcommand(self.identify_c, "identify", "Identify with NickServ.", []) self.addcommand(self.setp, "set password", "Set the NickServ password.", ["password"]) self.addcommand(self.setn, "set name", "Set the NickServ ...
ng('name') def setp(self, context, args): args.default("password", "") self.setsetting("password", args.getstr("password")) return "Set password to: %s" % self.getsetting('password') def name(self): return self.getsetting("name") or self.server.settings.get( 'server...
zhuyue1314/MITMf
plugins/BeefAutorun.py
Python
gpl-3.0
3,993
0.022039
#!/usr/bin/env python2.7 # Copyright (c) 2014-2016 Marcello Salvati # # 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. #...
ps.append(hook.ip) if mode == 'oneshot': if hook.session not in already_ran: self.execModules(hook) already_ran.append(hook.session) elif mode == 'loop': self.execModules(hook) sleep(10) sleep(1) def execModules(self, hook): all_modules
= self.config['BeEFAutorun']["ALL"] targeted_modules = self.config['BeEFAutorun']["targets"] if all_modules: mitmf_logger.info("{} [BeEFAutorun] Sending generic modules".format(hook.ip)) for module, options in all_modules.iteritems(): for m in self.beef.modules.findbyname(module): resp = m.run...
instantshare/instantshare
src/tools/shorturl.py
Python
gpl-2.0
726
0.001377
import logging from abc import abstractmethod, ABCMeta from urllib import request class UrlShortener(metaclass=ABCMeta): @abstractmethod def shorten(self, url: str) -> str: pass def log(self, url): logging.info("Short URL: {}".for
mat(url)) class Off(UrlShortener): def shorten(self, url: str): return url class TinyURL(UrlShortener): def shorten(self, url: str) -> str: response = request.urlopen("http://tinyurl.com/api-create.php?url={}".format(url)) url = str(response.read(), encoding="ascii") self.log...
return TinyURL() return Off()
Cadasta/cadasta-platform
cadasta/config/settings/default.py
Python
agpl-3.0
17,780
0
""" Django settings for cadasta project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build path...
}, { 'NAME': 'accounts.validators.EmailSimilarityValidator' }, ] OSM_ATTRIBUTION = _( "Base map data &copy; <a href=\"http://openstreetmap.org\">" "OpenStreetMap</a> contributors under " "<a href=\"http://opendatacommons.org/licenses/odbl/\">ODbL</a>" ) DIGITALGLOBE_ATTRIBUT...
}}.tiles.mapbox.com/v4/digitalglobe.{}' '/{{z}}/{{x}}/{{y}}.png?access_token=' 'pk.eyJ1IjoiZGlnaXRhbGdsb2JlIiwiYSI6ImNpaHhtenBmZjAzYW1' '1a2tvY2p3MnpjcGcifQ.vF1gH0mGgK31yeHC1k1Tqw' ) LEAFLET_CONFIG = { 'TILES': [ ( _("OpenStreetMap"), 'https://{s}.tile.openstreetmap.org/...
sirmar/tetris
tetris/visibles/component.py
Python
mit
1,102
0.002722
""" Base class for all nodes in the scene graph. It is implemented using th
e composite pattern. Responsibilities: - Hold the relative position to its parent. - Blit itself on the parent. - Dirty flag itself to trigger regeneration of surface. """ class Component(object): def __init__(self): self._position = (0, 0) self._dirty = True self._surface = None def ...
def set_position(self, position): self._position = position def surface(self): return None def dirty(self): self._dirty = True def _recreate_surface(self): if self._dirty: self._surface = self.surface() self._dirty = False """ Decorator to mark co...
gditzler/bio-course-materials
blast/get_seq.py
Python
gpl-3.0
1,093
0.014639
from Bio import Entrez from Bio import SeqIO from Bio import Seq from Bio.Alphabet import IUPAC genomes = ["Escherichia coli str. K-12 substr. MC4100 complete genome","Escherichia coli Nissle 1917, complete genome","Escherichia coli LY180, complete genome"] genomes_short = ["K12","Nissle","LY180"] for n,genome in enu...
retmode="text") record = SeqIO.read(handle, "genbank") handle.close() mygenes = ["thrA","mogA","dnaK","nhaA","ksgA"] output_handle=open("seq"+str(n+1)+".fna","w") for feature in record.features: if feature.type=='CDS': if 'gene' in feature.qualifiers: if feature...
tput_handle.close()
benogle/pylons_common
pylons_common/lib/date.py
Python
mit
3,799
0.010266
from pylons_common.lib.log import create_logger from pylons_common.lib.utils import pluralize logger = create_logger('pylons_common.lib.datetime') from datetime import datetime, timedelta DATE_FORMAT_ACCEPT = [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%SZ', u'%Y-%m-%d', u'%m-%d-%Y', u'%m/%d/%Y', u'%m.%d.%Y', u'%b %d, %...
tz.utcoffset(dt) - tz.dst(dt) # we do this try/except to avoid the possibility that pytz fails at localization # see https://bugs.
launchpad.net/pytz/+bug/207500 try: offset = dt.replace(tzinfo=pytz.utc) - tz.localize(dt) seconds = offset.days * 86400 + offset.seconds minutes = seconds / 60 hours = minutes / 60 # adjust for offsets that are greater than 12 hours (these are re...
m4773rcl0ud/launchpaddings
launchpad_utils.py
Python
gpl-3.0
4,442
0.00045
# # This file contains functions and constants to talk # to and from a Novation Launchpad via MIDI. # # Created by paul for mididings. from mididings import * # MEASURES - constants useful for the Pad side = list(range(0, 8)) longside = list(range(0, 9)) step = 16 # vertical gap on pad FirstCtrl = 104 # ctrl o...
row(x): "This tells the row of the event (square or right)" return x // step def column(x): "This tells us the column of event (right = 8)" return x % step def topcol(x): "The same as colums, but for the top row" return x - FirstCtrl # Now the inverses: functions that point exactly to a k...
ght(row): "This gives the note of a right key at position row" return (row * step) + 8 def square(row, col): "This gives the note of a square key at position row,col" return (row * step) + col def top(col): "This gives the ctrl of a top key at position col" return col + FirstCtrl # KEY FIL...
mfrey/RIOT
tests/xtimer_usleep/tests/01-run.py
Python
lgpl-2.1
2,231
0.001345
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Copyright (C) 2017 Francisco Acosta <francisco.acosta@inria.fr> # 2017 Freie Universität Berlin # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # d...
delta, error)) testtime = (time.time() - start_test) * US_PER_SEC child.expect(u"Test ran for (\\d+) us") exp = int(child.match.group(1)) lower_bound = exp - (exp * EXTERNAL_JITTER) upper_bound = exp + (exp * EXTERNAL_JITTER) if not (lower_bound < testtime <...
: raise InvalidTimeout("Host timer measured %d us (client measured %d us)" % (testtime, exp)) except InvalidTimeout as e: print(e) sys.exit(1) if __name__ == "__main__": sys.exit(run(testfunc))
MSPARP/newparp
newparp/helpers/tags.py
Python
agpl-3.0
1,613
0
from flask import g import re from sqlalchemy import and_ from sqlalchemy.orm.exc import NoResultFound from newparp.model import ( CharacterTag, Tag, ) special_char_regex = re.compile("[\\ \\./]+") underscore_strip_regex = re.compile("^_+|_+$") def name_from_alias(alias): # 1. Change to lowercase. #...
tag_type, name)] = alias character_tags = [] used_ids = set() for (tag_type, name), alias in tag_dict.items(): try: tag = g.db.query(Tag).filter(and_( Tag.type == tag_type, Tag.name == name, )).one() except NoResultFound: tag = Tag(type=t...
# Remember IDs to skip synonyms. if tag_id in used_ids: continue used_ids.add(tag_id) character_tags.append(CharacterTag(tag_id=tag_id, alias=alias)) return character_tags
nesdis/djongo
tests/django_tests/tests/v22/tests/custom_managers/tests.py
Python
agpl-3.0
25,648
0.001716
from django.db import models from django.test import TestCase from .models import ( Book, Car, CustomManager, CustomQuerySet, DeconstructibleCustomManager, FastCarAsBase, FastCarAsDefault, FunPerson, OneToOneRestrictedModel, Person, PersonFromAbstract, PersonManager, PublishedBookManager, RelatedModel,...
self.a
ssertIsInstance(self.b2.authors, PersonManager) def test_no_objects(self): """ The default manager, "objects", doesn't exist, because a custom one was provided. """ msg = "type object 'Book' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, ms...
evanmiltenburg/python-for-text-analysis
Extra_Material/Examples/Separate_Files/main_dir_script.py
Python
apache-2.0
78
0
def hello_world(): "Fu
nction that says hello." print("Hel
lo, world!")
namhyung/uftrace
tests/t001_basic.py
Python
gpl-2.0
530
0.001887
#!/usr/bin/env pyt
hon from runtest import TestBase class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'abc', """ # DURATION TID FUNCTION 62.202 us [28141] | __cxa_atexit(); [28141] | main() { [28
141] | a() { [28141] | b() { [28141] | c() { 0.753 us [28141] | getpid(); 1.430 us [28141] | } /* c */ 1.915 us [28141] | } /* b */ 2.405 us [28141] | } /* a */ 3.005 us [28141] | } /* main */ """)
salas106/lahorie
lahorie/utils/sql.py
Python
mit
886
0.002257
# -*- coding: utf8 -*- """ The ``dbs`` module =================== Contain all functions to access to main site db or any sql-lite db, in a secure way """ import sqlalchemy from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.automap import automap_base from sqlalchemy.sql import join __all__ = ['...
alects/index.html :param engine_url: :param echo: :return: "
"" engine = sqlalchemy.create_engine(engine_url, echo=echo) session_class = sessionmaker(bind=engine) session = session_class() return engine, session def auto_map_orm(engine): base_class = automap_base() base_class.prepare(engine, reflect=True)
jeffstieler/bedrock-ansible
lib/trellis/plugins/vars/version.py
Python
mit
2,048
0.007324
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import __version__ from ansible.errors import AnsibleError from distutils.version import LooseVersion from operator import eq, ge, gt from sys import version_info try: from __main__ ...
on_requirement)) elif gt(LooseVersion(__version__), LooseVersion(version_tested_max)): display.warning(u'You Ansible version is {} but this version of Trellis has only been tested for ' u'compatability with Ansible {} -> {}. It is advisable to check for Trellis updates or ' u'downgrade your ...
__version__, version_requirement, version_tested_max)) if eq(LooseVersion(__version__), LooseVersion('2.5.0')): display.warning(u'You Ansible version is {}. Consider upgrading your Ansible version to avoid ' u'erroneous warnings such as `Removed restricted key from module data...`'.format(__version__))...
OrlyMar/gasistafelice
gasistafelice/rest/views/blocks/account_state.py
Python
agpl-3.0
3,887
0.009262
from gasistafelice.rest.views.blocks.base import BlockWithList from django.utils.translation import ugettext as _, ugettext_lazy as _lazy #------------------------------------------------------------------------------# # # #------------------...
---------------------------------------------------------# class Block(BlockWithList): BLOCK_NAME = "account_state" BLOCK_DESCRIPTION = _("Economic state") BLOCK_VALID_RESOURCE_TYPES = ["gas", "site"] def _get_resource_list(self, request): return request.resource.accounts # TODO fero CHECK ...
_actions = [] # # if settings.CAN_CHANGE_CONFIGURATION_VIA_WEB == True: # user = request.user # if can_write_to_resource(user,res): # if resource_type in ['container', 'node', 'target', 'measure']: # # if (resource_type in ['targ...
dkamotsky/program-y
src/test/aiml_tests/person_tests/test_person_aiml.py
Python
mit
904
0.005531
import unittest import os from test.aiml_tests.client import TestClient from programy.config.brain import BrainFileConfiguration class BasicTestClient(TestClient): def __init__(self): TestClient.__init__(self) def load_configuration(self, arguments): super(BasicTestClient, self).load_configur...
self.configuration.brain_configuration._person = os.path.dirname(__file__)+"/person.txt" class PersonAIMLTests(unittest.TestCase): @classmethod def setUpClass(cls): PersonAIMLTests.test_client = BasicTestClient() def test_person(self): response = PersonAIMLT
ests.test_client.bot.ask_question("test", "TEST PERSON") self.assertIsNotNone(response) self.assertEqual(response, "This is your2 cat")
pdl30/pychiptools
scripts/pychip_diff_bind.py
Python
gpl-2.0
376
0
#!/usr/bin/python
######################################################################## # 1 August 2014 # Patrick Lombard, Centre for Stem Stem Research # Core Bioinformatics Group # University of Cambridge # All right reserved. ######################################################################## import pychiptools.call_diff_bi...
ptools.call_diff_bind.main()
blabla1337/skf-flask
skf/api/checklist_category/endpoints/checklist_category_update.py
Python
agpl-3.0
1,240
0.003226
from flask import request from flask_restplus import Resource from skf.api.security import security_headers, validate_privilege from skf.api.checklist_category.business import update_checklist_category from skf.api.checklist_category.serializers import checklist_type_update, message from skf.api.kb.parsers import autho...
e('checklist_category', description='Operations related to checklist items') @ns.route('/update/<int:id>') @api.doc(params={'id': 'The checklist category id'}) @api.response(404, 'Validation error', message) class ChecklistCategoryUpdate(Resource): @api.expect(authorization, checklist_type_update) @api.respon...
* Privileges required: **edit** """ data = request.json val_num(id) val_alpha_num_special(data.get('name')) val_alpha_num_special(data.get('description')) validate_privilege(self, 'edit') result = update_checklist_category(id, data) return result, 2...
flaviogrossi/billiard
billiard/pool.py
Python
bsd-3-clause
64,479
0
# -*- coding: utf-8 -*- # # Module providing the `Pool` class for managing a process pool # # multiprocessing/pool.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # from __future__ import absolute_import # # Imports # import errno import itertools import os import platform i...
try: sys.exit(self.workloop(pid=pid)) except Exception as exc: error('Pool process %r error: %r', self, exc, exc_info=1) self._do_exit(pid, _exitcode[0], exc) finally: self._do_exit(pid, _exitcode[0], None) def _do_exit(self, pid, exitcode, exc=None):...
self.on_exit(pid, exitcode) if sys.platform != 'win32': try: self.outq.put((DEATH, (pid, exitcode))) time.sleep(1) finally: os._exit(exitcode) else: os._exit(exitcode) def on_loop_start(self, pid): ...
katychuang/python-data-sci-basics
src/numpy_utils.py
Python
mit
3,188
0.016311
# coding: utf-8 # numpy_utils for Intro to Data Science with Python # Author: Kat Chuang # Created: Nov 2014 # -------------------------------------- import numpy ## Stage 2 begin fieldNames = ['', 'id', 'priceLabel', 'name','brandId', 'brandName', 'imageLink', 'desc', 'vendor', 'patterned', 'materi...
2) ax.set_title(title) ax.set_xlabel(title) ax.set_ylabel('Number of Ties') if len(pric
es) > 20: ax.set_xlim([0, round(len(prices), -1)]) else: ax.set_xlim([0, len(prices)]) fig.savefig('_charts/' + title + '.png') def prices_of_list(sampleData): temp_list = [] for row in sampleData[1:]: priceCol = float(row[2]) temp_list.append(priceCol) return temp_l...
web2py/pydal
tests/sql.py
Python
bsd-3-clause
137,514
0.001136
# -*- coding: utf-8 -*- """ Basic unit tests """ from __future__ import print_function import os import glob import datetime import json import pickle from pydal._compat import basestring, StringIO, integer_types,
xrange, BytesIO, to_bytes from pydal import DAL, Field from pydal.helpers.classes import SQLALL, OpRow from pydal.objects import Table, Expression, Row from ._compat import unittest from ._adapt import ( DEFAULT_URI, IS_POSTGRESQL, IS_SQLITE, IS_
MSSQL, IS_MYSQL, IS_TERADATA, IS_NOSQL, IS_ORACLE, ) from ._helpers import DALtest long = integer_types[-1] print("Testing against %s engine (%s)" % (DEFAULT_URI.partition(":")[0], DEFAULT_URI)) ALLOWED_DATATYPES = [ "string", "text", "integer", "boolean", "double", "blob", ...
DigitalSlideArchive/HistomicsTK
histomicstk/preprocessing/color_conversion/rgb_to_hsi.py
Python
apache-2.0
725
0
"""Placeholder.""" import numpy as np def rgb_to_hsi(im): """Convert to HSI the RGB pixels in im. Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma. """ im = np.moveaxis(im, -1, 0) if len(im) not in (3, 4): raise ValueError("Expected 3-channel RGB or 4-channel RG...
" received a {}-channel imag
e".format(len(im))) im = im[:3] hues = (np.arctan2(3**0.5 * (im[1] - im[2]), 2 * im[0] - im[1] - im[2]) / (2 * np.pi)) % 1 intensities = im.mean(0) saturations = np.where( intensities, 1 - im.min(0) / np.maximum(intensities, 1e-10), 0) return np.stack([hues, saturation...
LeMaker/LNdigitalIO
examples/presslights.py
Python
gpl-3.0
501
0
import LNdigitalIO def switch_pressed(event): event.chip.output_pins[event.pin_num].turn_on() def switch_unpressed
(event): event.chip.output_pins[event.pin_num].turn_off() if __name__ == "__main__": LNdigital = LNdigitalIO.LNdigitals() listener = LNdigitalIO.InputEventListener(chip=LNdigital) for i in range(4): listener.register(i, LNdigitalIO.IODIR_ON, switch_pressed) listener.register(i, LNdigi...
tener.activate()
eJRF/ejrf
questionnaire/tests/views/test_assign_questions_view.py
Python
bsd-3-clause
13,049
0.004598
from urllib import quote from django.test import Client from questionnaire.forms.assign_question import AssignQuestionForm from questionnaire.models import Questionnaire, Section, SubSection, Question, Region, QuestionGroup from questionnaire.models.skip_rule import SkipQuestion from questionnaire.tests.base_test imp...
.client.post(self.url) self.assertRedirects(response, expected_url='/accounts/login/?next=%s' % quote(self.url)) def test_GET_with_hide_param_puts_list_of_only_unused_questions_in_context(self): question1 = Question.objects.create(text='USed question', UID='C00033', answer_type='Number',
region=self.region) question1.question_group.create(subsection=self.subsection) hide_url = '/subsection/%d/assign_questions/?hide=1' % self.subsection.id response = self.client.get(hide_url) self.assertIn(question1, response.context['active_questions...
lahwaacz/wiki-scripts
tests/parser_helpers/test_wikicode.py
Python
gpl-3.0
18,144
0.001488
#! /usr/bin/env python3 import mwparserfromhell from ws.parser_helpers.wikicode import * class test_get_adjacent_node: def test_basic(self): snippet = "[[Arch Linux]] is the best!" wikicode = mwparserfromhell.parse(snippet) first = wikicode.get(0) last = get_adjacent_node(wikicode...
snippet = "Some text with a [[link]] inside." expected = "Some text with a inside." wikicode = mwparserfromhell.parse(snippet) self._do_test(wikicode, "[[link]]", expected) def test_around(self): snippet = """\ First paragraph [[link1]] Second paragraph [[link2]] Third paragraph "...
mwparserfromhell.parse(snippet) self._do_test(wikicode, "[[link1]]", "First paragraph\n\nSecond paragraph\n[[link2]]\n\nThird paragraph\n") self._do_test(wikicode, "[[link2]]", "First paragraph\n\nSecond paragraph\n\nThird paragraph\n") def test_lineend(self): snippet = """\ Some other tex...
iohannez/gnuradio
gr-filter/python/filter/qa_rational_resampler.py
Python
gpl-3.0
8,932
0.004478
#!/usr/bin/env python # # Copyright 2005-2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at ...
= %d\n' % (L2 - L1, ntaps, dec
im, ilen)) sys.stderr.write(' len(result_data) = %d len(expected_result) = %d\n' % (len(result_data), len(expected_result))) self.assertEqual(expected_result[0:L], result_data[0:L]) # FIXME disabled. Triggers hang on SuSE 10.0...
Crach1015/plugin.video.superpack
zip/plugin.video.SportsDevil/lib/parser.py
Python
gpl-2.0
26,568
0.00478
# -*- coding: utf-8 -*- import common import sys, os, traceback import time import random import re import urllib import string from string import lower from entities.CList import CList from entities.CItemInfo import CItemInfo from entities.CListItem import CListItem from entities.CRuleItem import CRuleItem import c...
demystify = False back = '' startUrl
= inputList.curr_url #print inputList, lItem while count == 0 and i <= maxits: if i > 1: ignoreCache = True demystify = True # Trivial: url is from known streamer if back: lItem['refere...
dwadler/QGIS
python/plugins/processing/algs/grass7/ext/r_mapcalc.py
Python
gpl-2.0
2,550
0.000786
# -*- coding: utf-8 -*- """ *************************************************************************** r_mapcalc.py ------------ Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr **********************************...
feedback): # We need to export every raster from the GRASSDB alg.exportRasterLayersIntoDirectory('output_dir',
parameters, context, wholeDB=True)
ForgottenBeast/spider_nest
database/utils.py
Python
gpl-3.0
2,171
0.015661
# -*-coding:UTF-8 -* import sqlite3 as sql import json from time import time, strftime import settings import logging as lgn lgn.basicConfig(filename = '/db/db.log',level=lgn.DEBUG,\ format='%(asctime)s %(message)s') def logit(string,*level): if(len(level) == 0): lgn.info(string) else: if(...
lgn.warning(string) elif(level[0] == 40): lgn.error(string) else: lgn.critical(string) def clean_listings(): conn,c = get_conn() #first the easy thing: let's delete all the listings that are not #linked to any search anymore c.execute('''delete ...
stingid from search_listings)''') conn.commit() #now let's delete all the listings older than max age max_age = time() - settings.n_days_before_del * 86400 c.execute('''delete from listings where date_added <= ?''',(max_age,)) conn.commit() def get_conn(): conn = sql.connect("/db/spider_nest.d...
urllib3/urllib3
src/urllib3/util/url.py
Python
mit
14,809
0.000743
import re from typing import Container, NamedTuple, Optional, overload from ..exceptions import LocationParseError from .util import to_str # We only want to normalize urls with an HTTP(S) scheme. # urllib3 infers URLs without a scheme (None) to be http. _NORMALIZABLE_SCHEMES = ("http", "https", None) # Almost all o...
roperty
instead. """ if self.host is None: return None if self.port: return f"{self.host}:{self.port}" return self.host @property def url(self) -> str: """ Convert self into a url This function should more or less round-trip with :func:`....
dwc/pi-monitoring
bin/push_temperature.py
Python
mit
1,946
0.018499
#!/usr/bin/env python import argparse import datetime import os import re import requests import subprocess import sys import time import xively DEBUG = os.environ["DEBUG"] or false def read_temperature(from_file): if DEBUG: print "Reading temperature from file: %s" % from_file temperature = None with op...
ame') parser.add_argument('--file', type=str, required=True, help='the file from which to read the temperature') args = parser.parse_args() api = xively.XivelyAPIClient(args.key) feed = api.feeds.get(args.feed) datastream = get_datastream(feed, args.na
me) datastream.max_value = None datastream.min_value = None while True: temperature = read_temperature(args.file) if DEBUG: print "Updating Xively feed with value: %s" % temperature datastream.current_value = temperature datastream.at = datetime.datetime.utcnow() try: datastrea...
tcpcloud/openvstorage
ovs/extensions/os/__init__.py
Python
apache-2.0
644
0
# Copyright 2015 CloudFounders 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 applicable law or agreed to in writing, software # d
istributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This package contains Linux OS distribution extensions """
Mytho/groceries-api
db/versions/20150505_154233_373a21295ab_db_migration.py
Python
mit
1,244
0.003215
"""db migration Revision ID: 373a21295ab Revises: 21f5b2d3905d Create Date: 2015-05-05 15:42:33.474470 """ # revision identifiers, used by Alembic. revision = '373a21295ab' down_revision = '21f5b2d3905d' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): op.dr...
sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.String(255), nullable=False), sa.Column('is_bought', sa.Boolean, default=False, nullable=False), sa.Column('created', sa.DateTime, default=sa.func.now(), nullable=False), sa.Column('modified', sa.DateTi...
nullable=False)) def downgrade(): op.drop_table('items') op.create_table('items', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.String(255), nullable=False), sa.Column('is_bought', sa.Boolean, default=False, nullable=False), sa.Column('modified', sa.DateTi...
cryvate/project-euler
project_euler/solutions/problem_56.py
Python
mit
294
0.006803
from ..libra
ry.base import number_to_list def solve(bound: int=100): maximal = 0 for a in range(bound): for b in range(bound): sum_digits = sum(number_to_list(a ** b)) if sum_digits > maximal: maximal = sum_digits re
turn maximal
mozilla-services/FunkLoad
src/funkload/ReportRenderOrg.py
Python
gpl-2.0
6,127
0.003754
# (C) Copyright 2011 Nuxeo SAS <http://nuxeo.com> # Author: bdelbosc@nuxeo.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Software Foundation. # # This program is distributed in the hope that it wil...
(self): org = ["#+BEGIN_LaTeX"] org.append('\\begin{center}') for image_name in self.image_nam
es: org.append("\includegraphics[scale=0.5]{{./%s}.png}" % image_name) org.append('\\end{center}') org.append('#+END_LaTeX') return '\n'.join(org) + '\n' def org_header(self, with_chart=False): headers = self.headers[:] if self.with_percentiles: self._attach_percentiles_header(head...
mariecpereira/IA369Z
deliver/ia870/iainfgen.py
Python
mit
261
0.019157
# -*- encoding: utf-8 -*- # Module iainfgen from numpy import * def iainfgen(f, Iab): from iaunion import iaunion from iadil import iadil from ianeg import ianeg A, Bc = I
ab y = iaunio
n( iadil(f, A), iadil( ianeg(f), Bc)) return y
unor/schemaorg
sdordf2csv.py
Python
apache-2.0
11,152
0.017755
import csv import rdflib from rdflib.namespace import RDFS, RDF, OWL from rdflib.term import URIRef import threading from apimarkdown import Markdown from apirdflib import RDFLIBLOCK import logging logging.basicConfig(level=logging.INFO) # dev_appserver.py --log_level debug . log = logging.getLogger(__name__) class ...
None or graph == None: return if not isinstance(term, URIRef): term = URIRef(term) enumType = self.graphValueToCSV(subject=term,predicate=RDF.type,graph=graph) if enumType.endswith("#Class"): enumType = "" row = [str(term)] row....
nd(self.getCSVSupertypes(term,graph=self.fullGraph)) row.append(enumType) row.append(self.graphValueToCSV(subject=term,predicate=OWL.equivalentClass,graph=graph)) row.append(self.getCSVTypeProperties(term,graph=self.fullGraph)) row.append(self.getCSVSubtypes(term,graph=self.fullGraph)) ...
dtaht/ns-3-dev-old
src/network/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
507,731
0.015106
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
Address [class] module.add_class('Ipv4Address') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask') ## ipv6-addr...
ass('Ipv6Address') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix') ## mac48-address.h (module 'network'): ns...
Bysmyyr/chromium-crosswalk
tools/telemetry/telemetry/testing/system_stub.py
Python
bsd-3-clause
14,620
0.011833
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides stubs for os, sys and subprocess for testing This test allows one to test code that itself uses os, sys, and subprocess. """ import ntpath impo...
'open':
OpenFunctionStub, 'os': OsModuleStub, 'perf_control': PerfControlModuleStub, 'raw_input': RawInputFunctionStub, 'subprocess': SubprocessModuleStub, 'sys': SysModuleStub, 'thermal_throttle': ThermalThrottleModuleStub, 'logging': L...
brendangregg/bcc
tools/kvmexit.py
Python
apache-2.0
12,070
0.002237
#!/usr/bin/env python # # kvmexit.py # # Display the exit_reason and its statistics of each vm exit # for all vcpus of all virtual machines. For example: # $./kvmexit.py # PID TID KVM_EXIT_REASON COUNT # 1273551 1273568 EXIT_REASON_MSR_WRITE 6 # 1274253 1274261 EXIT_RE...
KVM_EXIT_REASON: the reason why the vm exits. # @COUNT: the counts of the @KVM_EXIT_REASONS. # # REQUIRES: Linux 4.7+ (BPF_PROG_TYPE_TRACEPOINT support) # # Copyright (c) 2021 ByteDance Inc. All rights reserved. # # Author(s): # Fei Li <lifei.shirley@bytedance.com> from __future__
import print_function from time import sleep from bcc import BPF import argparse import multiprocessing import os import subprocess # # Process Arguments # def valid_args_list(args): args_list = args.split(",") for arg in args_list: try: int(arg) except: raise argparse....
nocarryr/vidhub-control
vidhubcontrol/backends/base.py
Python
gpl-3.0
27,623
0.004236
from loguru import logger import asyncio from typing import Optional, List, Dict, ClassVar from pydispatch import Dispatcher, Property from pydispatch.properties import ListProperty, DictProperty from vidhubcontrol.common import ConnectionState, ConnectionManager class BackendBase(Dispatcher): """Base class for ...
trol', 'input_labels':'input_label_control', 'output_labels':'output_label_c
ontrol', } _events_ = ['on_preset_added', 'on_preset_stored', 'on_preset_active'] def __init__(self, **kwargs): super().__init__(**kwargs)
davidt/reviewboard
reviewboard/hostingsvcs/codebasehq.py
Python
mit
20,408
0.000049
from __future__ import unicode_literals import logging from xml.dom.minidom import parseString from django import forms from django.utils import six from django.utils.six.moves.urllib.error import HTTPError, URLError from django.utils.translation import ugettext_lazy as _, ugettext from reviewboard.hostingsvcs.error...
required=True, widget=forms.TextInput(attrs={'size':
'60'}), help_text=_('The short name of your repository. This can be found by ' 'clicking the Settings button on the right-hand ' 'side of the repository browser.')) class CodebaseHQClient(HostingServiceClient): """Client for talking to the Codebase API. This im...
aaronsw/watchdog
vendor/rdflib-2.4.0/rdflib/store/SQLite.py
Python
agpl-3.0
18,855
0.016547
from __future__ import generators from rdflib import BNode from rdflib.Literal import Literal from pprint import pprint from pysqlite2 import dbapi2 import sha,sys,re,os from rdflib.term_utils import * from rdflib.Graph import QuotedGraph from rdflib.store.REGEXMatching import REGEXTerm, NATIVE_REGEX, PYTHON_REGEX from...
h models Class membership) The motivation for this partition is primarily query speed and scalability as most graphs will always have more rdf:type statements than others - All Quoted statements In addition it persists namespace mappings in a seperate table """ context_aware = True formula_awar...
ex_matching = PYTHON_REGEX autocommit_default = False def open(self, home, create=True): """ Opens the store specified by the configuration string. If create is True a store will be created if it does not already exist. If create is False and a store does not already exist ...
dymkowsk/mantid
Framework/PythonInterface/test/python/mantid/kernel/ConfigServiceTest.py
Python
gpl-3.0
4,880
0.002459
from __future__ import (absolute_import, division, print_function) import unittest import os import testhelpers from mantid.kernel import (ConfigService, ConfigServiceImpl, config, std_vector_str, FacilityInfo, InstrumentInfo) class ConfigServiceTest(unittest.TestCase): __dirs_to_rm =...
FacilityInfo)) def test_getFacility_With_Name_Returns_A_FacilityInfo_Object(self): facility = config.getFacility("ISIS") self.assertTrue(isinstance(facility, FacilityInfo)) self.assertRaises(RuntimeError, config.getFacility, "MadeUpFacility") def test_getFacilities_Returns_A_FacilityIn...
y_Names_are_in_sync_and_non_empty(self): facilities = config.getFacilities() names = config.getFacilityNames() self.assertTrue(len(names)>0) self.assertEquals(len(names),len(facilities)) for i in range(len(names)): self.assertEquals(names[i],facilities[i].name()) ...
ar0551/Wasp
src/ghComp/Wasp_DisCo Rule Group.py
Python
gpl-3.0
3,209
0.011218
# Wasp: Discrete Design with Grasshopper plug-in (GPL) initiated by Andrea Rossi # # This file is part of Wasp. # # Copyright (c) 2017, Andrea Rossi <a.rossi.andrea@gmail.com> # Wasp is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the ...
nses/gpl.html> # # Significant parts of Wasp have been developed by Andrea Rossi # as part of research on digital materials and discrete design at: # DDU Digital Design Unit
- Prof. Oliver Tessmann # Technische Universitt Darmstadt ######################################################################### ## COMPONENT INFO ## ######################################################################### """ Export Wasp information for DisCo...
gijigae/django-tutorial
django_tutorial/contrib/sites/migrations/0002_set_site_domain_and_name.py
Python
bsd-3-clause
949
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID...
"name": "Django Tutorial" } ) def update_site_backward(apps, schema_editor): """Rev
ert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "name": "example.com" } ) class Migration(migrations.Migration): dependencies = [ ...