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
matheuscas/django-tastypie-simple-api-doc
tastypie_api_doc/views.py
Python
mit
1,877
0.006393
from django.shortcuts import render_to_response from django.template import RequestContext import json # Create your views here. import importlib from django.http import HttpResponse from django_markup.markup import formatter def build_doc(request): try: from project.settings import API_OBJECT_LOCATION ...
er_to_response('index.html', {'api': {'data': api_json, 'name': obj.api_name, 'docstri
ngs': resources_docstrings, 'prepend_urls': resources_prepend_urls}}, context_instance=RequestContext(request)) except ImportError: return HttpResponse("No donuts for you. You have to create API_OBJECT_LOCATION in settings.py") def get_resources_...
looker/sentry
src/bitfield/models.py
Python
bsd-3-clause
9,135
0.000876
from __future__ import absolute_import import six from django.db.models import signals from django.db.models.fields import BigIntegerField, Field from bitfield.forms import BitFormField from bitfield.query import BitQueryLookupWrapper from bitfield.types import Bit, BitHandler # Count binary capacity. Truncate "0b"...
ot isinstance(value, BitHandler): # Regression for #1425: fix bad data that was created resulting # in negative values for flags. Compute the value that would # have been visible ot the application to preserve compatibility. if isinstance(value, six.integer_types) and va...
new_value = 0 for bit_number, _ in enumerate(self.flags): new_value |= (value & (2**bit_number)) value = new_value value = BitHandler(value, self.flags, self.labels) else: # Ensure flags are consistent for unpickling val...
andresriancho/HTTPretty
tests/functional/test_passthrough.py
Python
mit
2,551
0.001176
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to ...
.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response
1.content) @skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get(...
waveface/SnsManager
tests/it_TwitterBase.py
Python
bsd-3-clause
1,730
0.00578
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os.path # Hack for import module in grandparent folder sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import unittest from SnsManager import ErrorCode from SnsManager.twitter import TwitterBase CONSUMER_KEY = 'ZglRcsve...
cret=TEST_TOKEN_SECRET, consumerKey=CONSUMER_KEY, consumerSecret=CONSUMER_SECRET) self.assertTrue(obj.getMyId()) def test_GetMyId_GivenInvalidToken_None(self): obj = TwitterBase(accessToken='invalid_token', accessTokenSecret=TEST_TOKEN_SECRET, consumerKey=CONSUMER_KEY, consumer
Secret=CONSUMER_SECRET) self.assertIsNone(obj.getMyId()) def test_IsTokenValid_GivenValidToken_S_OK(self): obj = TwitterBase(accessToken=TEST_TOKEN, accessTokenSecret=TEST_TOKEN_SECRET, consumerKey=CONSUMER_KEY, consumerSecret=CONSUMER_SECRET) resp = obj.isTokenValid() self.assertEq...
jt6562/XX-Net
python27/1.0/lib/noarch/pyasn1/type/base.py
Python
bsd-2-clause
9,450
0.002011
# Base classes for ASN.1 types import sys from pyasn1.type import constraint, tagmap from pyasn1 import error class Asn1Item: pass class Asn1ItemBase(Asn1Item): # Set of tags for this ASN.1 type tagSet = () # A list of constraint.Constraint instances for checking values subtypeSpec = constraint.Const...
N1 types and values are represened by Python class instances # * Value initialization is made for defaulted components only # * Primary method of component addressing is by-position. Data model for base # type is Python sequence. Additional type-specific addressing methods # may be implemented for particular types....
s also implement by-identifier addressing # * Sequence, Set and Choice types also implement by-asn1-type (tag) addressing # * Sequence and Set types may include optional and defaulted # components # * Constructed types hold a reference to component types used for value # verification and ordering. # * Component typ...
t2mune/mrtparse
mrtparse/base.py
Python
apache-2.0
9,331
0.001608
''' mrtparse - MRT format data parser Copyright (C) 2022 Tetsumune KISO 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 applicabl...
i_list = [] while p < n: nlri = Nlri(self.buf[p:]) p += nlri.unpack(af, saf) nlri_list.append(nlri.data) # Check whether duplicate routes exist in NLRI if len(nlri_list) > 0 and len(nlri_list) != \ len(set(map(lambda x:...
raise MrtFormatError self.p = p except MrtFormatError: nlri_list = [] while self.p < n: nlri = Nlri(self.buf[self.p:]) self.p += nlri.unpack(af, saf, add_path=1) nlri_list.append(nlri.data) return nlri_list cla...
pythonlittleboy/python_gentleman_crawler
test/seleium2.py
Python
apache-2.0
268
0.011194
from selenium import webdriver from selenium.webdriver.common.keys import Keys import os,t
ime driver = webdriver.Chrome() driver.get('http://www.
ciliba.org/s/MDB-740.html') time.sleep(3) driver.execute("confirm") print(driver.page_source) driver.close() driver.quit()
ChinaMassClouds/copenstack-server
openstack/src/nova-2014.2/nova/virt/ovirt/firewall.py
Python
gpl-2.0
13,628
0.000073
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complianc...
ipv6_cidr = subnet['cidr'] net, prefix = netutils.get_net_and_prefixlen(ipv6_cidr) parameters.append(format_parameter('PROJNET6', net)) parameters.append(format_parameter('PROJMASK6', prefix)) return parameters
def _get_instance_filter_xml(self, instance, filters, vif): nic_id = vif['address'].replace(':', '') instance_filter_name = self._instance_filter_name(instance, nic_id) parameters = self._get_instance_filter_parameters(vif) uuid = self._get_filter_uuid(instance_filter_name) ...
toshi123/python4beginners
geoDistance.py
Python
mit
1,325
0.011914
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from xml.etree.ElementTree import parse from optparse import OptionParser from pyproj import Geod def adr2geo(adr): api = "http://www.geocoding.jp/api/?v=1.1&q=%s" % (urllib.quote(adr.encode('utf-8'))) xml = parse(urllib.urlopen(api)).getroot() ...
goal[1],goal[0]) return d def cutdown(num): # 距離に単位をつけて返す val = int(round(num)) if val < 1000: return '%sm' % val else: km = val * 0.001 return '%sKm' % round(km, 1) if __name__ == '__main__': usage = "usage: %prog 出発地点 到着地点" p = OptionParser(usage=usage) (optio...
ect number of arguments" ) fadr = args[0].decode('utf-8') fgeo = adr2geo(fadr) # print fgeo tadr = args[1].decode('utf-8') tgeo = adr2geo(tadr) # print tgeo distance = get_distance(fgeo,tgeo) dist_str = cutdown(distance) print u'%s から %s まで %s'%(fadr,tadr,dist_str)
MediaKraken/MediaKraken_Deployment
source/web_app_sanic/blueprint/user/bp_user_metadata_game_system.py
Python
gpl-3.0
3,005
0.006988
from common import common_global from common import common_pagination_bootstrap from sanic import Blueprint blueprint_user_metadata_game_system = Blueprint('name_blueprint_user_metadata_game_system', url_prefix='/user') @blueprint_user_metadata_game_system.route('/user...
ool.acquire() media_data = await request.app.db_functions.db_meta_game_system_by_guid(guid, db_connection=db_connection
) await request.app.db_pool.release(db_connection) return { 'guid': guid, 'data': media_data, }
dokterbob/django-shopkit
shopkit/currency/__init__.py
Python
agpl-3.0
1,300
0.002308
# Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-shopkit. # # django-shopkit 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 2, or (at...
s program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License...
are Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Currency handling for django-shopkit. It comes in a simple and an advanced variant. The simple variant assumes a single currency throughout the webshop project, advanced currency support allows for using multiple currencies throu...
suykerbuyk/hls_toolkit
HLS/fetcher.py
Python
gpl-2.0
8,189
0.002076
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Copyright (C) 2009-2010 Fluendo, S.L. (www.fluendo.com). # Copyright (C) 2009-2010 Marc-Andre Lureau <marcandre.lureau@gmail.com> # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free...
last nbuffer, but the nbuffer -1 ... if self.nbuffer > 0 and not self._cached_files.has_key(f[2]['sequence'] - (self.nbuffer - 1)): delay =
0 elif self._file_playlist.endlist(): delay = 1 return delay def _get_files_loop(self): if not self._seg_task: self._seg_task = task.LoopingCall(self._get_next_file) d = self._get_next_file() d.addCallback(self._next_file_delay) d.addCallback...
lueschem/edi
tests/test_command_line_interface.py
Python
lgpl-3.0
1,276
0.000784
# -*- coding: utf-8 -*- # Copyright (C) 2017 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Gen
eral Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # edi is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTAB
ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with edi. If not, see <http://www.gnu.org/licenses/>. import edi def test_command_line_interface_setup(empty_config_file): ...
uclouvain/osis
base/views/entity/detail.py
Python
agpl-3.0
5,701
0.001404
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
y_version.get_parent_version() descendants = entity_version.descendants calendar = LearningUnitSummaryEditionCalendar() target_years_opened = calendar.get_target_years_opened() if target_years_opened: target_year_displayed = target_years_opened[0] else: pr...
ndar.get_previous_academic_event() target_year_displayed = previous_academic_event.authorized_target_year academic_year = AcademicYear.objects.get(year=target_year_displayed) calendar_summary_course_submission = find_summary_course_submission_dates_for_entity_version( entity_vers...
leonlcw92/myScrapy
tut/tut/items.py
Python
gpl-3.0
333
0
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See
documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class TutItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() image_urls = scrapy.Field() images =
scrapy.Field()
eeshangarg/zulip
zerver/webhooks/greenhouse/view.py
Python
apache-2.0
2,154
0.000929
from typing import Any, Dict, List from django.http import HttpRequest, HttpResponse from zerver.decorator import webhook_view from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.lib.webhooks.common import check_send_webhook_message from zerver.models imp...
em_type = item.get("type", "").title() item_value = item.get("value") item_url = item.get("url") if i
tem_type and item_value: internal_template += f"{item_value} ({item_type}), " elif item_type and item_url: internal_template += f"[{item_type}]({item_url}), " internal_template = internal_template[:-2] return internal_template @webhook_view("Greenhouse") @has_request_variables...
wolfram74/numerical_methods_iserles_notes
venv/lib/python2.7/site-packages/IPython/kernel/tests/test_kernelspec.py
Python
mit
2,717
0.003312
import json import os from os.path import join as pjoin import unittest from IPython.testing.decorators import onlyif from IPython.utils.tempdir import TemporaryDirectory from IPython.kernel import kernelspec sample_kernel_json = {'argv':['cat', '{connection_file}'], 'display_name':'Test kernel'...
th open(json_file, 'w') as f: json.dump(sample_kernel_json, f) self.ksm = kernelspec.KernelSpecManager(ipython_dir=td.name) td2 = TemporaryDirectory() self.addCleanup(td2.cleanup) self.installable_kernel = td2.name with open(pjoin(self.installable_kernel, 'k...
json.dump(sample_kernel_json, f) def test_find_kernel_specs(self): kernels = self.ksm.find_kernel_specs() self.assertEqual(kernels['sample'], self.sample_kernel_dir) def test_get_kernel_spec(self): ks = self.ksm.get_kernel_spec('SAMPLE') # Case insensitive self.assertEqua...
pakal/django-compat-patcher
src/django_compat_patcher/__init__.py
Python
mit
928
0.001078
from __future__ import absolute_import, print_function, unicode_literals from compat_patcher_core import generic_patch_software, make_safe_patcher @make_safe_patcher def patch(settings=None): """Load every dependency, and apply registered fixers according to provided settings (or Django settings as a fallback)."...
stry from .deprecation import warnings as warnings_proxy from .config import DjangoSettingsProvider from .utilities import DjangoPatchingUtilities from .runner import DjangoPatchingRunner django_settings_provid
er = DjangoSettingsProvider(settings=settings) generic_patch_software( settings=django_settings_provider, patching_registry=django_patching_registry, patching_utilities_class=DjangoPatchingUtilities, patching_runner_class=DjangoPatchingRunner, warnings_proxy=warnings_proxy, ...
mitsuhiko/celery
celery/utils/__init__.py
Python
bsd-3-clause
8,111
0.000863
from __future__ import generators import time import operator try: import ctypes except ImportError: ctypes = None import importlib from uuid import UUID, uuid4, _uuid_generate_random from inspect import getargspec from itertools import islice from carrot.utils import rpartition from celery.utils.compat impo...
unction over and over until max retries is exceeded. For each retry we sleep a for a while before we try again, this interval is increased for every retry
until the max seconds is reached. :param fun: The function to try :param catch: Exceptions to catch, can be either tuple or a single exception class. :keyword args: Positional arguments passed on to the function. :keyword kwargs: Keyword arguments passed on to the function. :keyword errbac...
zakandrewking/cobrapy
cobra/manipulation/validate.py
Python
lgpl-2.1
2,116
0
# -*- coding: utf-8 -*- from __future__ import absolute_import from math import isinf, isnan from warnings import warn NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE "SBO:0000628", # DEMAND "SBO:0000629", # BIOMASS "SBO:0000631...
action.id) if isinf(reaction.lower_bound): errors.append("Reaction '%s' has infinite lower_bound" % reaction.id) elif isnan(reaction.lower_bound): errors.append("Reaction '%s' has NaN for
lower_bound" % reaction.id) if isinf(reaction.upper_bound): errors.append("Reaction '%s' has infinite upper_bound" % reaction.id) elif isnan(reaction.upper_bound): errors.append("Reaction '%s' has NaN for upper_bound" % ...
YuMao1993/DRL
PG/main.py
Python
mit
2,270
0.006167
import argparse from PGEnv import PGEnvironment from PGAgent import PGAgent if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--gym_environment', type=str, default='Pong-v0', help='OpenAI Gym Environment to be used (default to Pong-v0)') parser.add_...
s.model_save_path, check_point = args.check_point, use_gpu=args.use_gpu, gpu_id=args.gpu_id) else: # disable frame skipping during testing result in better performance (because the agent can take more actions) env = PGEnvironment(environment_name=args.gym_environment, display=arg...
nv) assert(args.check_point is not None) agent.test(model_save_path = args.model_save_path, check_point=args.check_point, use_gpu=args.use_gpu, gpu_id=args.gpu_id) print('finished.')
JoelBondurant/RandomCodeSamples
python/proc.py
Python
apache-2.0
312
0.044872
"""A module to deal with processes.
""" import datetime def uptime(asstr = False): """Get system uptime>""" raw = '' with open('/proc/uptime','r') as ut: raw = ut.read()[:-1] uts = list(map(lambda x: int(float(x)), raw.split(' '))) if asstr: uts = str(datetime.timedelta(seconds = uts[0])) retur
n uts
Azure/azure-sdk-for-python
tools/azure-devtools/src/azure_devtools/perfstress_tests/__init__.py
Python
mit
1,479
0.000676
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
def run_perfstress_debug_cmd(): main_loop
= _PerfStressRunner(debug=True) loop = asyncio.get_event_loop() loop.run_until_complete(main_loop.start()) def run_system_perfstress_tests_cmd(): root_dir = os.path.dirname(os.path.abspath(__file__)) sys_test_dir = os.path.join(root_dir, "system_perfstress") main_loop = _PerfStressRunner(test_fol...
Magnus1990P/pyBiometricKeyLogger
api.py
Python
mit
1,126
0.062167
#!/usr/bin/env python #-*- coding: utf-8 -*- import datetime import sys import MySQLdb HOST = "127.0.0.1" USER = "root" PASSWD = "toor" DB = "pyKeyLog" def getSampleText( fname ): filehandle = open( fname, "r" ) text = filehandle.read().decode("utf-8") filehandle.close() lines = [] for i in text.split("...
ASE" sys.exit() def execute( CON, QUERY, DATA ): CRSR = CON.cursor() try: if DATA is not None: CRSR.execute( QUERY, (DATA) ) else: CRSR.execute( QUERY ) if "INSERT" in QUERY: QUERY = "SELECT LAST_INSERT_ID()" CRSR.execute( Q
UERY ) CON.commit() if "SELECT" in QUERY: RES = CRSR.fetchall() return RES return None; except MySQLdb.Error, e: CON.rollback() print e print "ERROR: FAILED TO EXECUTE QUERY" return None;
sdispater/pendulum
tests/localization/test_nb.py
Python
mit
3,021
0.000332
import pendulum locale = "nb" def test_diff_for_humans(): with pendulum.test(pendulum.datetime(2016, 8, 29)): diff_for_humans() def diff_for_humans(): d = pendulum.now().subtract(seconds=1) assert d.diff_for_humans(locale=locale) == "for 1 sekund siden" d = pendulum.now().subtract(seconds...
, 6, 123456) assert d.format("dddd", locale=locale) == "søndag" assert d.format("ddd", locale=locale) == "søn." assert d.format("MMMM", locale=locale) == "august" assert d.format("MMM", locale=locale) == "aug." assert d.format("A", locale=locale) == "a.m." assert d.format("Qo", locale=loca
le) == "3." assert d.format("Mo", locale=locale) == "8." assert d.format("Do", locale=locale) == "28." assert d.format("LT", locale=locale) == "07:03" assert d.format("LTS", locale=locale) == "07:03:06" assert d.format("L", locale=locale) == "28.08.2016" assert d.format("LL", locale=locale) == ...
mrniranjan/python-scripts
reboot/math27.py
Python
gpl-2.0
24
0
from sys import arg
v
|
bwildenhain/virt-manager
tests/test_urls.py
Python
gpl-2.0
11,455
0.001135
# Copyright (C) 2013 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in ...
since there's no treeinfo _add(OLD_CENTOS_URL % ("4.0", "x86_64"), hasxen=False, name="centos-4.0") _add(OLD_CENTOS_URL % ("4.9", "x86_64"), name="centos-4.9") # One old centos 5 _add(OLD_CENTOS_URL % ("5.0", "x86_64"), name="centos-5.0") # Latest centos 5 w/ i686 _add(CENTOS_URL % ("5", "x86_64"), "rhel5.11", name="c...
86=CENTOS_URL % ("6", "i386")) # Latest centos 7, but no i686 as of 2014-09-06 _add(CENTOS_URL % ("7", "x86_64"), "centos7.0", name="centos-7-latest") _set_distro(SLDistro) # scientific 5 _add(OLD_SCIENTIFIC_URL % ("55", "x86_64"), "rhel5.5", name="sl-5latest") # Latest scientific 6 _add(SCIENTIFIC_URL % ("6", "x86_6...
kostans3k/DistributedCounters
zemantaCounter/wsgi.py
Python
mit
403
0.002481
""" WSGI config for zemantaCounter project. It exposes the WSGI callable as a module-level variable n
amed ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zemantaCounter.settings") from django.core.wsgi import
get_wsgi_application application = get_wsgi_application()
jmeline/wifi_signal_analysis
src/tests/test_sampleParser.py
Python
mit
1,146
0.00349
# test_sampleParser.py import os from ..sampleParser import SampleParser class TestSampleParser: def set
up(self): self.folderName = os.path.join('.', 'tests', 'Export') self.parser = SampleParser(self.folderName) def test_getDirectoryFiles(self): files = self._obtainDirectory() asser
t len(files) > 0 def test_storeFileNamesByPatternInDictionary(self): files = self._obtainDirectory() assert len(files) > 0 for _file in files: self.parser.storeFileNamesByPatternInDictionary(_file) sampleDictionary = self.parser.getSampleDictionary() assert len(s...
SCUEvals/scuevals-api
tests/resources/test_search.py
Python
agpl-3.0
709
0.00141
import json from urllib.parse import urlencode from tests import TestCase from tests.fixtures.factories import ProfessorFactory, CourseFactory class SearchTestCase(TestCase): def setUp
(self): super().setUp() ProfessorFactory(first_name='Mathias') CourseFactory(title='Math Stuff') def test_search(self): rv = self.client.get('/search', headers=self.head_auth, query_string=urlencode({'q': 'mat'})) self.assertEqual(rv.status_code, 200) data = json.l...
sertIn('courses', data) self.assertIn('professors', data) self.assertEqual(len(data['courses']), 1) self.assertEqual(len(data['professors']), 1)
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/application_gateway_url_path_map.py
Python
mit
3,378
0.002368
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'k
ey': 'id', 'type': 'str'}, 'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'}, 'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'}, 'default_redirect_configuration': {'key': 'properties.defau...
yasir1brahim/OLiMS
lims/monkey/utils.py
Python
agpl-3.0
1,303
0.00307
from dependencies.dependency import base_hasattr, safe_callable, isIDAutoGenerated, \ getEmptyTitle, safe_unicode from lims.utils import t from dependencies.dependency import MessageFactory _marker = [] def _pretty_title_or_id(context, obj, empty_value=_marker): """Return the best possible title or id of an i...
.translate(_(safe_unicode(title)))
)
gromacs/copernicus
cpc/network/http/http_method_parser.py
Python
gpl-2.0
9,130
0.017087
# This file is part of Copernicus # http://www.copernicus-computing.org/ # # Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others. # # 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 Soft...
ders) if(ServerRequest.isFile(headers['Content-Disposition'])): file = tempfile.TemporaryFile(mode="w+b") name = ServerRequest.getFie
ldName(headers['Content-Disposition']) notused,contentDispositionParams = cgi.parse_header(headers['Content-Disposition']) name = contentDispositionParams['name'] #if we have a content length we just read it and store the...
oroxo/LPPDP
cliente.py
Python
mit
1,465
0.012287
''' Created on 20/02/2009 @author: Chuidiang Ejemplo de cliente de socket. Establece conexion con el servidor, envia "hola", recibe y escribe la respuesta, espera 2 segundos, envia "adios", recibe y escribe la respuesta y cierrra la conexion ''' import socket #import time if __name__ == '__main__': # Se establece ...
## Se envia "adios" #s.send("adios") # ## Se espera respuesta, se escribe en pantalla y se cierra la ## conexion #datos = s.recv(1000) #print datos #s
.close()
ranog/coursera_python
quadrado.py
Python
gpl-3.0
202
0.015
#!/usr/bin/env python3 lad
o = input("Digite o
valor correspondente ao lado de um quadrado: ") perimetro = ( int(lado) * 4 ) area = ( int(lado) ** 2) print("perímetro:", perimetro, "- área:", area)
katrid/django
django/db/migrations/autodetector.py
Python
bsd-3-clause
56,243
0.002045
from __future__ import unicode_literals import datetime import re from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOpti...
._meta.manag
ed: self.old_unmanaged_keys.append((al, mn)) elif al not in self.from_state.real_apps: if model._meta.proxy and not model._meta.local_fields: self.old_proxy_keys.append((al, mn)) else: self.old_model_keys.append((al, mn)...
GuoDuanLZ/sdustoj-judge-webserver
sdustoj_server/sdustoj_server/wsgi.py
Python
apache-2.0
406
0
""" WSGI config for sdustoj_server project. It exposes the WSGI
callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sdu
stoj_server.settings") application = get_wsgi_application()
matt-dale/designdb
DESIGNDB_REBUILD/DESIGNDB_REBUILD/settings.py
Python
apache-2.0
3,383
0.001182
""" Django settings for DESIGNDB_REBUILD project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ imp...
}, }, ] WSGI_APPLICATION = 'DESIGNDB_REBUILD.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https...
ATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { ...
Merino/poc-cbb
vesper/fields.py
Python
bsd-3-clause
1,042
0.001919
import bleach from django.db.models.fields import TextField from django.utils.encoding import smart_text from .widgets import RichTextareaWidget class RichTextarea(TextField): """ """ def to_python(self, value): """ """ if value: html = value.replace('&nbsp;', ' ') ...
, 'table', 'tr', 'th', 'td', ] ALLOWED_ATTRIBUTES = { } html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, strip=True) return html else: return valu...
d(**kwargs)
alex/sqlalchemy
lib/sqlalchemy/orm/persistence.py
Python
mit
41,002
0.002
# orm/persistence.py # Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """private module containing functions used to emit INSERT, UPDATE and DELETE state...
s(existing) row_switch = existing if not has_identity and not row_switch: states_to_insert.append( (state, dict_, mapper, connection, has_identity, instance_key, row_switch) ) else: states_to_update.append( ...
nce_key, row_switch) ) return states_to_insert, states_to_update def _organize_states_for_post_update(base_mapper, states, uowtransaction): """Make an initial pass across a set of states for UPDATE corresponding to post_update. This include...
ivansib/sibcoin
contrib/auto_gdb/simple_class_obj.py
Python
mit
2,004
0.002495
#!/usr/bin/python # try: import gdb except ImportError as e: raise ImportError("This script must be run in GDB: ", str(e)) import sys import os sys.path.append(os.getcwd()) import common_helpers
simple_types = ["CMasternode", "CMasternodeVerification", "CMasternodeBroadcast", "CMasternodePing", "CMasternodeMan", "CDarksendQueue", "CDarkSendEntry", "CTransaction", "CMutableTransaction", "CPrivateSendBaseSession", "CPrivateSendBaseManager", "CPrivat...
"CMasternodePayee", "CInstantSend", "CTxLockRequest", "CTxLockVote", "CTxLockCandidate", "COutPoint", "COutPointLock", "CSporkManager", "CMasternodeSync", "CGovernanceManager", "CRateCheckBuffer", "CGovernanceObject", "CGovernanceVote", "CGovernanceOb...
rwatson/chromium-capsicum
webkit/tools/layout_tests/test_output_formatter.py
Python
bsd-3-clause
4,736
0.018581
#!/usr/bin/env python # Copyright (c) 2006-2009 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. """ This is a script for generating easily-viewable comparisons of text and pixel diffs. """ import optparse from layout_pack...
on_parser.add_option("-z", "--zip-file", default = None, help = ("Use the local test output zip file "
"instead of scraping the buildbots")) option_parser.add_option("-l", "--local", action = "store_true", default = False, help = ("Use local baselines instead of scraping " "baselines from source websites")) options, args = ...
trondhindenes/ansible
test/units/modules/network/f5/test_bigip_profile_oneconnect.py
Python
gpl-3.0
3,947
0.001773
# -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys from nose.plugins.skip i...
tSpec() def test_create(self, *args): # Configure the arguments that would be sent to the Ansible module set_module_args(dict( name='foo', parent='bar', maximum_reuse=1000, password='password', server='localhost', user='admin' ...
ager(module=module) # Override methods to force specific logic in the module to happen mm.exists = Mock(return_value=False) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['maximum_reuse'] == 100...
ltworf/relational
setup/python3-relational.setup.py
Python
gpl-3.0
846
0
# -*- coding: utf-8 -*- # Relational # Copyright (C) 2008-2011 Salvo "LtWorf" Tomaselli # # Relational 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) an...
without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it> import installer_common installer_common.c_setup('relational'...
dantebarba/docker-media-server
plex/Sub-Zero.bundle/Contents/Libraries/Shared/ftfy/streamtester/twitter_tester.py
Python
gpl-3.0
3,155
0
""" Implements a StreamTester that runs over Twit
ter data. See the class docstring. This module is written for Python 3 only. The __future__ imports you see here are just to let Python 2 scan the file without crashing with a SyntaxError. """ from __future__ import print_function, unicode_literals import os from collections import defaultdict from ftfy.streamtester i...
ined in `__init__.py`) to evaluate ftfy's real-world performance, by feeding it live data from Twitter. This is a semi-manual evaluation. It requires a human to look at the results and determine if they are good. The three possible cases we can see here are: - Success: the process takes in...
cdegroc/scikit-learn
examples/decomposition/plot_sparse_coding.py
Python
bsd-3-clause
3,808
0.001838
""" =========================================== Sparse coding with a precomputed dictionary =========================================== Transform a signal as a sparse combination of Ricker wavelets
. This example visually compares different sparse coding methods using the :class:`sklearn.decomposition.SparseCoder` estimator. The Ricker (also known as mexican hat or the second derivative of a gaussian) is not a particularily good kernel to represent piecewise constant signals like this one.
It can therefore be seen how much adding different widths of atoms matters and it therefore motivates learning the dictionary to best fit your type of signals. The richer dictionary on the right is not larger in size, heavier subsampling is performed in order to stay on the same order of magnitude. """ print __doc__ ...
jmluy/xpython
exercises/practice/acronym/acronym.py
Python
mit
32
0
def abbreviate(words): pass
doug-fish/neutron-lbaas-dashboard
neutron_lbaas_dashboard/dashboards/project/loadbalancersv2/workflows/__init__.py
Python
apache-2.0
672
0
# Copyright 2015, eBay Inc. # # Licensed under the Apache License, Versio
n 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on...
d. See the # License for the specific language governing permissions and limitations # under the License. from . create_lb import * # noqa from update_lb import * # noqa
dhhagan/py-openaq
examples/pm25_histogram_delhi.py
Python
mit
833
0.002401
""" Distribution of PM2.5 at Various Sites across Delhi =================================================== _thumb: .2, .6 """ import matplotlib.pyplot as plt import seaborn as sns import openaq sns.set(style="ticks", font_scale=1.) api = openaq.OpenAQ() # grab the data res = api.measurements(city='Delhi', parameter...
=False) # Map a histogram for each location g.map(plt.hist, "value") # Set the titles g.set_titles("{col_name}") # Set the axis labels g.set_axis_labels("$PM_{2.
5}$ [$\mu g m^{-3}$]", None) # Remove the left axis sns.despine(left=True) # Remove the yticks g.set(yticks=[])
tetherless-world/dtdi-geologic-time-resolver
app.py
Python
mit
1,824
0.001096
from flask import Flask, request, abort import json from ReverseProxied import ReverseProxied app = Flask(__name__) app.wsgi_app = ReverseProxied(app.wsgi_app) with open("intervals.json") as b: data = json.load(b) def intersects(interval, min_age, max_age): if interval["lag"] <= min_age <= interval["eag"]: ...
_age = request.args.get('max', None, type=float) if min_age is None or max_age is None: abort(400) return min_age, max_age @app.route("/resolve-within", methods=['GET']) def resolve_within(): min_age, max_age = process_inputs() return resolve_geologic_time_within(min_age, max_age) @app.rou...
ntersects(): min_age, max_age = process_inputs() return resolve_geologic_time_intersects(min_age, max_age) if __name__ == "__main__": app.run()
jravey7/Joe2Music
mopidy_touchscreen/screens/search_screen.py
Python
mit
7,928
0.002144
from base_screen import BaseScreen import pygame from ..graphic_utils import ListView,\ ScreenObjectsManager, TouchAndTextItem from ..input import InputManager from play_options import PlayOptions mode_track_name = 0 mode_album_name = 1 mode_artist_name = 2 class SearchScreen(BaseScreen): def __init__(se...
lf.base_size, self.manager, self.fonts, self.results[clicked].uri, self.playqueues) #self.manager.core.tracklist.clear()
#self.manager.core.tracklist.add( # uri=self.results[clicked].uri) # javey: pull up play options dialog #self.manager.core.playback.play() else: clicked = self.screen_objects.get_touch_objects_in_pos( ...
hofmannedv/training-python
loops/while-else.py
Python
gpl-2.0
630
0.011111
# ----------------------------------------------------------- # demonstrates the usage of a while loop with else condition #o # (C) 2017 Frank Hofmann, Berlin, Germany # Released under GNU Public License (GPL) # email frank.hofmann@efho.de # --------------------------------
--------------------------- # define list shoppingCart = ["banana", "apple", "grapefruit"] # output list content # # simple version with index # initiate index itemIndex = 0 # use an endless loop while itemIndex < len(shoppingCart): print (itemIndex, shoppingCart[itemIndex]) # increment itemIndex
itemIndex += 1 else: print ("reached end of list")
johnnadratowski/git-reviewers
python_lib/shell.py
Python
mit
8,544
0.001287
"""Contains utility functions for working with the shell""" from contextlib import contextmanager import datetime from decimal import Decimal import json import pprint import sys import time import traceback SHELL_CONTROL_SEQUENCES = { 'BLUE': '\033[34m', 'LTBLUE': '\033[94m', 'GREEN': '\033[32m', 'LT...
"Write the output to the writer, used for printing to stdout/stderr""" to_print = kwargs.get("sep", " ").join(output) + kwargs
.get("end", "\n") if isinstance(writer, list): writer.append(to_print) else: writer.write(to_print) if kwargs.get("flush"): writer.flush() def write_json(output, end='', raw=False, file=None, flush=False): file = file or sys.stdout if len(output) == 1: outp...
Vambok/Tanook-Lebot
Run.py
Python
cc0-1.0
24,528
0.039102
import string import pickle import time import threading import re from urllib.request import urlopen from Socket import openSocket,sendMessage,joinRoom,getUser,getMessage from Settings import CHANNEL,MBALL,COOLDOWNCMD,VERSION,UNMOD #from pastebin import getChangelog s=openSocket("#"+CHANNEL) joinRoom(s) #...
tualtime=time.time() EMOTELIST=[":)",":(",":D",">(",":|","O_o","B)",":O","<3",":/",";)",":P",";P","R)"] data=urlopen("https://twitchemotes.com/api_cache/v2/global.json").read(40000).decode("utf-8") data=data.split("\"emotes\":{\"")[1] data=data.split("},\"") for emoteline in data:
EMOTELIST.append(emoteline.split("\":{")[0]) # for user in SEEN: # if actualtime-SEEN[user] > 36000: # SEEN.pop(user,None) for user in PERMITTED: if actualtime-PERMITTED[user] > 120: PERMITTED.pop(user,None) ouaisCpt=0 ggCpt=0 lastUptimeUpdate=actualtime lastCo...
ryfeus/lambda-packs
Tensorflow_Pandas_Numpy/source3.6/gast/gast.py
Python
mit
9,289
0.000108
import sys as _sys import ast as _ast from ast import boolop, cmpop, excepthandler, expr, expr_context, operator from ast import slice, stmt, unaryop, mod, AST def _make_node(Name, Fields, Attributes, Bases): def create_node(self, *args, **kwargs): nbparam = len(args) + len(kwargs) assert nbparam ...
Load': ((), (), (expr_context,)), 'Store': ((), (), (expr_context,)), 'Del': ((), (), (expr_context,)), 'AugLoad': ((), (), (expr
_context,)), 'AugStore': ((), (), (expr_context,)), 'Param': ((), (), (expr_context,)), # slice 'Slice': (('lower', 'upper', 'step'), (), (slice,)), 'ExtSlice': (('dims',), (), (slice,)), 'Index': (('value',), (), (slice,)), # boolop 'And': ((), (), (boolop,)), 'Or': ((), (), (bool...
blaze/distributed
distributed/tests/test_worker.py
Python
bsd-3-clause
46,667
0.000557
from concurrent.futures import ThreadPoolExecutor import importlib import logging from numbers import Number from operator import add import os import psutil import sys from time import sleep import traceback import asyncio import dask from dask import delayed from dask.utils import format_bytes from dask.system impor...
ory, pyzname)) assert os.path.exists(os.path.join(b.local_directory, pyzname)) def g(x): from mytest import mytest return mytest.inc(x) future = c.submit(g, 10, workers=a.address) result = await future assert result == 10 + 1 await c.close() await s.close() await a.cl...
async def test_upload_large_file(c, s, a, b): pytest.importorskip("crick") await asyncio.sleep(0.05) with rpc(a.address) as aa: await a
spulec/moto
moto/stepfunctions/exceptions.py
Python
apache-2.0
931
0
from moto.core.exceptions import AWSError class ExecutionAlreadyExists(AWSError): TYPE = "ExecutionAlreadyExists" STATUS = 400 class ExecutionDoesNotExist(AWSError): TYPE = "ExecutionDoesNotExist" STATUS = 400 class InvalidArn(AWSError): TYPE = "InvalidArn" STATUS = 400 class InvalidName...
token"): super().__init__("Invalid Token: {}".format(message)) class ResourceNotFound(AWSError): TYPE = "ResourceNotFound" STATUS = 400 def __i
nit__(self, arn): super().__init__("Resource not found: '{}'".format(arn))
stefan-jonasson/home-assistant
tests/components/notify/test_html5.py
Python
mit
15,352
0
"""Test HTML5 notify platform.""" import asyncio import json from unittest.mock import patch, MagicMock, mock_open from aiohttp.hdrs import AUTHORIZATION from homeassistant.components.notify import html5 from tests.common import mock_http_component_app SUBSCRIPTION_1 = { 'browser': 'chrome', 'subscription': ...
handle = m() assert json.loads(handle.write.call_args[0][0]) == expected @asyncio.coroutine def test_registering_new_device_validation(self, loop, test_client): """Test various errors when registering a new device.""" hass = MagicMock() m = mock_open() with...
turn_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] hass.loop = loop app = mock_http_component_app(hass) ...
tex0l/JukeBox
parser.py
Python
apache-2.0
4,608
0.003906
from __future__ import unicode_literals # !/usr/bin/env python # -*- coding: utf-8 -*- import glob import os from tags import tag_finder import logging from operator import itemgetter, attrgetter, methodcaller def path_leaf(path): """ It gets the path final leaf """ head, tail = os.path....
od") tags = tag_finder(self.path) #Audio file mode #index index = self.file_name.split("-")[0] index = Index(index[:1], int(index[1:])) logging.debug(index)
#artiste try: artist = tags['artist'] except KeyError: artist = "unknown" #nom logging.debug("Artist:" + artist) try: name = tags['title'] except KeyError: name = "unknown" #format logging.debug...
columbiaviz/columbiaviz.github.io
build.py
Python
mit
3,474
0.012378
# encoding: utf-8 import re import jinja2 import jinja2.ext import markdown2 import os import sys sys.path.append(".") from staticjinja import make_site from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup # remove annoying characters def cleanitup(text): chars = { '\xe2': '', '\x80': '', '...
_title, ) post_template.stream(**kwargs).dump(out) if __name__ == "__main__": site = make_site(extensions=[ Markdown2Extension, ], contexts=[ ('.*.md', get_pos
t_contents), ], rules=[ ('.*.md', render_post), ]) site.render(use_reloader=False)
luoq/pyspider
pyspider/database/couchdb/taskdb.py
Python
apache-2.0
3,764
0.00186
import json, time from pyspider.database.base.taskdb import TaskDB as BaseTaskDB from .couchdbbase import SplitTableMixin class TaskDB(SplitTableMixin, BaseTaskDB): collection_prefix = '' def __init__(self, url, database='taskdb', username=None, password=None): self.username = username self.p...
fields is None: fields = [] collection_name = self._get_collection_name(project) ret = self.get_docs(collection_name, {"selector": {"taskid": taskid}, "fields": fields}) if len(ret) == 0: return None return ret[0] def status_count(self, project): if ...
collection_name = self._get_collection_name(project) def _count_for_status(collection_name, status): total = len(self.get_docs(collection_name, {"selector": {'status': status}})) return {'total': total, "_id": status} if total else None c = collection_name ret ...
CourseTalk/edx-platform
common/lib/xmodule/xmodule/modulestore/__init__.py
Python
agpl-3.0
55,549
0.002844
""" This module provides an abstraction for working with XModuleDescriptors that are stored in a database an accessible using their Location as an identifier """ import logging import re import json import datetime from pytz import UTC from collections import defaultdict import collections from contextlib import cont...
e_key, record) def _clear_bulk_ops_record(self, course_key): """ Clear the record for this course ""
" if course_key.for_branch(None) in self._active_bulk_ops.records: del self._active_bulk_ops.records[course_key.for_branch(None)] def _start_outermost_bulk_operation(self, bulk_ops_record, course_key): """ The outermost nested bulk_operation call: do the actual begin of the bulk...
hickey/amforth
core/devices/atmega644pa/device.py
Python
gpl-2.0
7,376
0.071448
# Partname: ATmega644PA # generated automatically, do not edit MCUREGS = { 'ADCSRB': '&123', 'ADCSRB_ACME': '$40', 'ACSR': '&80', 'ACSR_ACD': '$80', 'ACSR_ACBG': '$40', 'ACSR_ACO': '$20', 'ACSR_ACI': '$10', 'ACSR_ACIE': '$08', 'ACSR_ACIC': '$04', 'ACSR_ACIS': '$03', 'DIDR1': '&127', 'DIDR...
'TCCR1B_ICNC1': '$80', 'TCCR1B_ICES1': '$40', 'TCCR1B_WGM1': '$18', 'TCCR1B_CS1': '$07', 'TCCR1C'
: '&130', 'TCCR1C_FOC1A': '$80', 'TCCR1C_FOC1B': '$40', 'TCNT1': '&132', 'OCR1A': '&136', 'OCR1B': '&138', 'ICR1': '&134', 'EEAR': '&65', 'EEDR': '&64', 'EECR': '&63', 'EECR_EEPM': '$30', 'EECR_EERIE': '$08', 'EECR_EEMPE': '$04', 'EECR_EEPE': '$02', 'EECR_EERE': '$01', 'TWAMR': '&189', '...
vdloo/raptiformica
tests/unit/raptiformica/settings/load/test_purge_local_config_mapping.py
Python
mit
698
0
from raptiformica.setting
s import conf from raptiformica.settings.load import purge_local_config_mapping from tests.testcase import TestCase class TestPurgeLocalConfigMapping(TestCase): def setUp(self): self.remove = self.set_up_patch( 'raptiformica.settings.load.remove' ) def test_purge_local_config_mapp...
) def test_purge_local_config_mapping_ignores_file_not_found(self): self.remove.side_effect = FileNotFoundError # Does not raise error purge_local_config_mapping()
artish/tera
example/docker/hdfs.py
Python
bsd-3-clause
1,496
0.027406
import time class Hdfs: def __init__(self, ip, mode, log_prefix): self.ip = ip self.mode = mode self.path = self.get_log_path(log_prefix) def get_log_path(self, log_prefix): path = '{pre}/hdfs/{ip}-{mode}-{time}'.format(pre=log_prefix, ip=self.ip, mode=self.mode, time=time.strftime('%Y%m%d%H%M%S')) return...
es): cmd = 'docker run -t -d -v {dir}
:/opt/share -p 9000:9000 -p 9001:9001 --net=host {docker} /usr/bin/python /opt/hdfs_setup.py --masters {master} --slaves {slaves} --mode {mode}'.\ format(dir=self.path, docker=docker, master=masters, slaves=slaves, mode=self.mode) return cmd class HdfsCluster: def __init__(self, ip_list, num_of_hdfs, log_prefix)...
jopohl/urh
src/urh/controller/dialogs/FuzzingDialog.py
Python
gpl-3.0
15,833
0.00379
import math from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtGui import QCloseEvent from PyQt5.QtWidgets import QDialog, QInputDialog from urh import settings from urh.models.FuzzingTableModel import FuzzingTableModel from urh.signalprocessing.ProtocoLabel import ProtocolLabel from urh.signalprocessing.ProtocolAnal...
self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages) self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type]) self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index) self.proto_view = proto_view self.fuzz_table_model = FuzzingTableModel(self.c...
self.fuzz_table_model.update() self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1) self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end) self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data)) self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data)) ...
plilja/adventofcode
common/test_timer.py
Python
gpl-3.0
695
0
from unittest import TestCase from common.timer import timed @timed def fib(n): ls = [1, 1] if n == 0: return 0 if n <= 2: return ls[n - 1] for i in range(3, n + 1): tmp = ls[1] ls[1] = ls[0] + ls[1] ls[0] = tmp return ls[-1] class Test(TestCase): def...
# timed should not do anything to the decorated method, # just make some calls to verify that the function works unaffected self.assertEqual(0, fib(0)) self.assertEqual(1, fib(1)) self.assertEqual(1, fib(2
)) self.assertEqual(2, fib(3)) self.assertEqual(3, fib(4)) self.assertEqual(5, fib(5))
asl97/MANGAdownloader
scrapers/e621.py
Python
bsd-3-clause
1,343
0.003723
########################
######################################## # File: e621.py # Title: MANGAdownloader's site scraper # Author: ASL97/ASL <asl97@outlook.com> # Version: 1 # Notes : DON'T EMAIL ME UNLESS YOU NEED TO # TODO: *blank* ################################################################ import misc # used in __main__, download us...
.isdigit(): id_ = tmp link = "http://e621.net/pool/show.json?id=%s"%(id_) j = misc.download_json(link) name = j["name"] total = j["post_count"] page_ = 1 page = 0 for d in j["posts"]: chapter[1][page] = {"link": d['file_url'], ...
mouadino/scrapy
scrapyd/app.py
Python
bsd-3-clause
1,522
0.001971
from twisted.application.service import Application from twisted.application.internet import TimerService, TCPServer from twisted.web import server from twisted.python import log from scrapy.utils.misc import load_object from .interfaces import IEggStorage, IPoller, ISpiderScheduler, IEnvironment from .launcher impor...
nfig.get('bind_address', '0.0.0.0') poller = QueuePoller(config) eggstorage = FilesystemEggStorage(config) scheduler = SpiderScheduler(config) environment = Environment(config) app.setComponent(IPoller, poller) app.setComponent(IEggStorage, eggstorage) app.setComponent(ISpiderScheduler, sc...
Environment, environment) laupath = config.get('launcher', 'scrapyd.launcher.Launcher') laucls = load_object(laupath) launcher = laucls(config, app) timer = TimerService(5, poller.poll) webservice = TCPServer(http_port, server.Site(Root(config, app)), interface=bind_address) log.msg("Scrapyd w...
pavdpr/svcread
python/__init__.py
Python
mit
106
0
from readSVCsig
import readSVCdata from readSVCsig import readSVCheader from readS
VCsig import readSVCsig
Transkribus/TranskribusDU
TranskribusDU/tasks/tabulate_final.py
Python
bsd-3-clause
9,416
0.012107
# -*- coding: utf-8 -*- """ We expect XML file with TextLine having the row, col, rowSpan, colSpan attributes For each Page: We delete any empty table (or complain if not empty) We select TextLine with rowSPan=1 and colSpan=1 We create one
cell for each pair of row and col number We inject the TexLine into its cell We create a TableRegion to contain the cells We delete empty regions We resize non-empty regions We compute the cell and table geometries and store them
. Created on 21/10/2019 Copyright NAVER LABS Europe 2019 @author: JL Meunier """ import sys, os from optparse import OptionParser from collections import defaultdict from lxml import etree from shapely.ops import cascaded_union try: #to ease the use without proper Python installation import Transkribu...
akx/requiem
requiem.py
Python
mit
2,960
0.004054
from subprocess import check_call, call, Popen, PIPE import os import textwrap import glob os.putenv("DEBIAN_FRONTEND", "noninteractive") ####### ## Plumbing ####### def get_output(cmd, **kwargs): check = kwargs.pop("check", True) kwargs["stdout"] = PIPE p
= Popen(cmd, **kwargs) stdout, stderr = p.communicate() if check and p.returncode: raise Value
Error("%r return code %s" % (cmd, p.returncode)) return stdout def sh(cmd): check_call(cmd, shell=True) def shh(cmd): get_output(cmd, shell=True) ####### ## Packages ####### def add_apt_key(url): sh("wget -O - %s | apt-key add -" % url) def add_apt_repo(name, spec): with file("/etc/apt/sour...
spacy-io/spaCy
spacy/lang/uk/__init__.py
Python
mit
903
0.002215
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZ
ER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .lemmatizer import UkrainianLemmatizer from ...language import Language class Ukrainia
nDefaults(Language.Defaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS class Ukrainian(Language): lang = "uk" Defaults = UkrainianDefaults @Ukrainian.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None,...
soker90/betcon
src/stats_tipster.py
Python
gpl-3.0
2,869
0.005228
import sys, os, inspect from PyQt5.QtWidgets import QWidget, QTreeWidgetItem from PyQt5 import uic directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])) sys.path.append(directory + "/lib") from libstats import LibStats from func_aux import paint_row, key_from_value fro...
self.setEnabled(False) self.cmbYear.activated.connect(self.updateMonths) self.cmbMonth.activated.connect(self.updateTree) def translate(self): header = [_("Tipster"), _("Sport"), _("Bets"), _("Success"), _("Money Bet"), _("Profit"), _("Stake"), _("Quota")] self.treeMonth.s...
Labels(header) self.lblYear.setText(_("Year")) self.lblMonth.setText(_("Month")) self.lblTotalMonth.setText(_("Total of the month")) self.lblTotal.setText(_("Totals")) def initData(self): self.years, self.months = LibStats.getYears() self.cmbYear.addItems(self.year...
glomex/gcdt-bundler
tests/test_python_bundler.py
Python
mit
7,149
0.004756
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import os import logging from textwrap import dedent import collections import pytest import mock from gcdt_testtools.helpers import temp_folder, create_tempfile, cleanup_tempfiles from gcdt_testtools import helpers from gcdt_bundler.pyth...
r)
for package in packages: log.debug(package) assert 'werkzeug' in packages
nacc/cobbler
cobbler/cli.py
Python
gpl-2.0
28,939
0.011023
""" Command line interface for cobbler. Copyright 2006-2009, Red Hat, Inc and Others Michael DeHaan <michael.dehaan AT gmail> 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 ...
port os import utils import module_loader import item_distro import item_profile import item_system import item_repo import item_image import item_mgmtclass import item_package import item_file import settings OBJECT_ACTIONS_MAP = { "distro" : "add copy edit find list remove rename report".split(" "), "pro...
weroff powerstatus reboot".split(" "), "image" : "add copy edit find list remove rename report".split(" "), "repo" : "add copy edit find list remove rename report".split(" "), "mgmtclass" : "add copy edit find list remove rename report".split(" "), "package" : "add copy edit find list remove rena...
Eric89GXL/scipy
scipy/interpolate/ndgriddata.py
Python
bsd-3-clause
7,557
0.000662
""" Convenience interface to N-D interpolation .. versionadded:: 0.9 """ from __future__ import division, print_function, absolute_import import numpy as np from .interpnd import LinearNDInterpolator, NDInterpolatorBase, \ CloughTocher2DInterpolator, _ndim_coords_from_arrays from scipy.spatial import cKDTree _...
): ... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 on a grid in [0, 1]x[0, 1] >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j] but we only know its values at 1000 data points: >>> points = np.random.rand(1000, 2) >>> values = func(points[:,0], points[:,1]) This can b...
griddata(points, values, (grid_x, grid_y), method='nearest') >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear') >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic') One can see that the exact result is reproduced by all of the methods to some degree, but for t...
testlnord/entity_matching_tool
entity_matching_tool/__init__.py
Python
mit
2,695
0.005566
import logging from logging import FileHandler import psycopg2 import sqlalchemy from sqlalchemy_utils import database_exists, create_database from mongoengine import * from flask import Flask from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from .config import test_config from .config import app...
engine = sqlalchemy.create_engine("postgres://{}:{}@{}/{}".format(app_config.POSTGRES['user'], app_config.POSTGRES['pw'], app_config.POSTGRES['host'],
app_config.POSTGRES['db'])) if not database_exists(engine.url): create_database(engine.url)
Leo-g/Selenium
python-selenium.py
Python
gpl-2.0
1,713
0.013427
from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Chrome('/home/leo/Downloads/chromedriver') driver.get("http://your-url") assert "Post Title" in driver.title link=driver.find_element_by_link_text("Add new") NewWindow=link.click() assert "Save" in driver.page_source #A...
.find_element_by_link_text("Edit") NewWindow=link.click() assert "Save" in driver.page_source title=driver.find_element_by_name("title") title.send_keys("Selenium web test edit") content=driver.find_elemen
t_by_name("content") content.send_keys("Selenium web test edit") category=driver.find_element_by_name("category") category.send_keys("Selenium web test edit") #http://selenium-python.readthedocs.org/en/latest/navigating.html select = Select(driver.find_element_by_name('published')) published=select.select_by_value("0"...
openstack/watcher
watcher/api/controllers/v1/data_model.py
Python
apache-2.0
2,661
0
# -*- encoding: utf-8 -*- # Copyright (c) 2019 ZTE Corporation # # 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 applica...
e DataModel.""" @wsme_pecan.wsexpose(wtypes.text, wtypes.text, types.uuid) def get_all(self, data_model_type
='compute', audit_uuid=None): """Retrieve information about the given data model. :param data_model_type: The type of data model user wants to list. Supported values: compute. Future support values: storage, baremetal. ...
MiLk/youtube-dl
youtube_dl/extractor/malemotion.py
Python
unlicense
1,665
0.001802
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ) class MalemotionIE(InfoExtractor): _VALID_URL = r'^(?:https?://)?malemotion\.com/video/(.+?)\.(?P<id>.+?)(#|$)' _TEST = { 'url': 'http://malemotion.com/video/bien-dur.1...
deo_url, 'ext': 'mp4', 'format_id': 'mp4', 'preference': 1, }] return { 'id': video_id, 'formats': formats, 'uploader': None, 'upload_date': None, 'title': video_title, 'thumbnail': video_thumbna...
'age_limit': 18, }
ashvina/heron
heron/tools/common/src/python/access/query.py
Python
apache-2.0
1,797
0.006121
#!/usr/bin/env python # -*- encoding: utf-8 -*- # 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...
iting, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions an
d limitations # under the License. ''' query.py ''' class QueryHandler(object): ''' QueryHandler ''' def fetch(self, cluster, metric, topology, component, instance, timerange, envirn=None): ''' :param cluster: :param metric: :param topology: :param component: :param instance: :param...
apenwarr/sshuttle
docs/conf.py
Python
lgpl-2.1
8,316
0.00012
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # sshuttle documentation build configuration file, created by # sphinx-quickstart on Sun Jan 17 12:13:47 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # a...
l manuals. # texinfo_app
endices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline
apache/incubator-airflow
tests/ti_deps/deps/test_pool_slots_available_dep.py
Python
apache-2.0
2,317
0
# # 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...
th create_session() as session: test_pool = Pool(pool='test_pool') session.add(test_pool) session.commit() def tearDown(self): db.clear_db_pools() @patch('airflow.models.Pool.open_slots', return_value=0) def test_pooled_task_reached_concurrency(self, mock_open_s...
s.Pool.open_slots', return_value=1) def test_pooled_task_pass(self, mock_open_slots): ti = Mock(pool='test_pool', pool_slots=1) assert PoolSlotsAvailableDep().is_met(ti=ti) @patch('airflow.models.Pool.open_slots', return_value=0) def test_running_pooled_task_pass(self, mock_open_slots): ...
McIntyre-Lab/papers
lehmann_2015/mapping_and_overall_expression/scripts/logParser.py
Python
lgpl-3.0
5,162
0.032739
# # DESCRIPTION: This script parses the given input bowtie and/or LAST files and creates a csv row of their data in the given output csv. # # AUTHOR: Chelsea Tymms import sys, os.path import argparse def getOptions(): """Function to pull in arguments from the command line""" description="""This script takes an i...
_uniq','last_per_aln'])+',') outputFile.write('per_uniq_aln'+'\n') outputFile.write(','.join(str(i) for i in treatmentArray)+',') if args.bowtie: #Get some important counts from the first and the final bowtie logs proc,aln,unaln,ambig=parseBowtieLog(args.bowtie[0]) ...
he counts for each Bowtie log for bowtieLog in args.bowtie: proc,aln,unaln,ambig=(parseBowtieLog(bowtieLog)) perUniq,perAln=0,0 if proc!=0: perUniq=float(aln)/proc * 100 perAln=(float(aln)+ambig)/proc * 100 uniqAln=uniqAln+aln ...
cgwire/zou
zou/app/blueprints/crud/__init__.py
Python
agpl-3.0
5,848
0
from flask import Blueprint from zou.app.utils.api import configure_api_from_blueprint from .asset_instance import AssetInstanceResource, AssetInstancesResource from .attachment_file import AttachmentFilesResource, AttachmentFileResource from .comments import CommentsResource, CommentResource from .custom_action impo...
nstance_id>", ScheduleItemResource), ("/data/news/", NewssResource), ("/data/news/<instance_id>", NewsResource), ("/data/milestones/", MilestonesResource), ("/data/milestones/<instance_id>", MilestoneResource),
("/data/metadata-descriptors/", MetadataDescriptorsResource), ("/data/metadata-descriptors/<instance_id>", MetadataDescriptorResource), ("/data/subscriptions/", SubscriptionsResource), ("/data/subscriptions/<instance_id>", SubscriptionResource), ("/data/entity-links/", EntityLinksResource), ("/dat...
codeofdusk/ProjectMagenta
src/keys/__init__.py
Python
gpl-2.0
847
0.025974
# -*- coding: utf-8 -*- import application im
port platform import exceptions from ctypes import c_char_p from libloader import load_library import paths if platform.architecture()[0][:2] == "32": lib = load_library("ap
i_keys32", x86_path=paths.app_path("keys/lib")) else: lib = load_library("api_keys64", x64_path=paths.app_path("keys/lib")) # import linuxKeys # lib = linuxKeys keyring = None def setup(): global keyring if keyring == None: keyring = Keyring() class Keyring(object): def __init__(self): super(Keyring, self)._...
iulian787/spack
var/spack/repos/builtin/packages/guidance/package.py
Python
lgpl-2.1
1,751
0.001142
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import glob class Guidance(MakefilePackage): """Guidance: Accurate detection of unreliable align...
perl.filter('#!/usr/bin/perl -w', '#!/usr/bin/env perl') def install(self, spac, prefix): mkdir(prefix.bin) install_tree('libs', prefix.bin.libs) install_tree('programs', prefix.bin.programs) install_tree('www', prefix.bin.www) with
working_dir(join_path('www', 'Guidance')): # copy without suffix install('guidance.pl', join_path(prefix.bin.www.Guidance, 'guidance')) def setup_run_environment(self, env): env.prepend_path('PATH', prefix.bin.www.Guidance)
ESOedX/edx-platform
lms/djangoapps/course_api/blocks/transformers/block_depth.py
Python
agpl-3.0
2,059
0.000971
""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case o...
ock_structure.get_parents(block_key) if parents: block_de
pth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, ...
damianavila/nikola
nikola/data/themes/base/messages/messages_hr.py
Python
mit
824
0
# -*- encoding:utf-8 -*- from __future__ import unicode_literals MESSAGES = { "Also available in": "Također dostupno i u", "Archive": "Arhiva", "Categories": "", "LANGUAGE": "hrvatski", "More posts about": "Više postova o", "Newer posts": "Noviji postovi", "Next post": "Sljedeći post", ...
nth} {year}": "P
ostovi za {month} {year}", "Previous post": "Prethodni post", "Read in English": "Čitaj na hrvatskom", "Read more": "Čitaj dalje", "Source": "Izvor", "Tags and Categories": "", "Tags": "Tagovi", "old posts page %d": "stari postovi stranice %d", }
Karaage-Cluster/karaage-debian
karaage/legacy/admin/south_migrations/0004_auto__del_logentry.py
Python
gpl-3.0
237
0
# -*- coding: utf-8 -*- from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): pas
s def backwards(self, orm): p
ass models = { } complete_apps = ['admin']
Ecotrust/cogs-priorities
priorities/seak/migrations/0002_auto__add_definedgeography.py
Python
bsd-3-clause
12,162
0.007811
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'DefinedGeography' db.create_table('seak_definedgeography', ( ('id', self.gf('d...
ateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}), 'id': ('...
', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'sharing_groups': ('django.db.models.fields.related.ManyToManyField', [],...
CMUSV-VisTrails/WorkflowRecommendation
vistrails/packages/componentGraph/__init__.py
Python
bsd-3-clause
1,248
0.004808
identifier = 'edu.cmu.sv.componentGraph' name = 'Component Graph' version = '1.0.0' def menu_items(): """menu_items() -> tuple of (str,function) It returns a list of pairs containing text for the menu and a callback
function that will be executed when that menu item is selected.
""" from test_form import TestForm test_form = TestForm() def show_test_form(): test_form.show() test_form.activateWindow() test_form.draw_graph() test_form.raise_() def show_api_form(): test_form.show() test_form.activateWindow() ...
jmacleod/dotr
GameStates.py
Python
gpl-2.0
3,904
0.013576
from StateMachine.State import State from StateMachine.StateMachine import StateMachine from StateMachine.InputAction import InputAction from GameData.GameData import GameData class StateT(State): state_stack = list() game_data = GameData() def __init__(self): self.transitions = None def next(...
StateT.next(self, input) class ExecuteDSCard(StateT): def run(self): print("Darkness Spreads - executing card") StateT.current_ds_card.execute(StateT.game_data) print "STACK: " + str(StateT.state_stack) def next(self, input): StateT.state_stack.append(self) if not self.transitions: ...
ayHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, InputAction.advanceToDay : GameStates.dayBegins, } return StateT.next(self, input) class DayBegins(StateT): def run(...
indexofire/gravoicy
gravoicy/libs/category/templatetags/__init__.py
Python
bsd-3-clause
2,558
0.001564
# -*- coding: utf-8 -*- from django import template from django.db import models from django.utils.html import escape register = template.Library() class TreeTrunkNode(template.Node): """ Render the first few levels of a topic tree as an unordered HTML list. """ def __init__(self, model_name, levels=...
"<li>%s" % escape(node.name)) elif diff > 0: pieces.append(u"<ul>\n<li>%s" %
escape(node.name)) current_level += 1 else: while diff: pieces.append(u"</li></ul>") diff += 1 current_level -= 1 pieces.append(u"</li>\n<li>%s" % escape(node.name)) if len(pieces) == 1: ...
mgavrin/Punkemon
level builder v0+0-0-1i.py
Python
mit
21,712
0.029477
###Level builder feature list #preview of current section of level #background texture pallete #foreground texture pallete #save/load/new interface #addition of item balls #addition of npcs #screenchangers: addition, connection, and #reciprocity checking (for indivdual and level) #is there another world at the...
if event.type==KEYDOWN: if event.key==K_n: self.createNewWorldFile() #write this function elif event.key==K_s: self.saveWorldFile() #write this function elif event.key==K_l: self.loadWorldFile() ...
t.key==K_p: self.setPaddingCharacter() #do we still need to write this? elif event.key==K_r: self.offset=[0,0] elif event.key==K_m: self.terrainDebugMode=not self.terrainDebugMode elif (pygame.key.get_pressed()[...
grantmcconnaughey/django-app-gen
appgen/templates/appgen/python/urls.py
Python
bsd-3-clause
479
0.02714
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.{{ model_name }}List.as_view(), name='list'), url(r'^new/$', vi
ews.{{ model_name }}Create.as_view(), name='create'), url(r'^(?P<pk>\d+)/$', views.{{ model_nam
e }}Detail.as_view(), name='detail'), url(r'^(?P<pk>\d+)/update/$', views.{{ model_name }}Update.as_view(), name='update'), url(r'^(?P<pk>\d+)/delete/$', views.{{ model_name }}Delete.as_view(), name='delete'), ]
gkc1000/pyscf
pyscf/nao/test/test_0052_gw_rf0_ref.py
Python
apache-2.0
1,018
0.022593
from __future__ import print_function, division import unittest, numpy as np from pyscf import gto, scf from pyscf.nao import gw as gw_c class KnowValues(unittest.TestCase): def test_rf0_ref(self): """ This is GW """ mol =
gto.M( verbose = 1, atom = '''H 0 0 0; H 0.17 0.7 0.587''', basis = 'cc-pvdz',) gto_mf = scf.RHF(mol) gto_mf.kernel() gw = gw_c(mf=gto_mf, gto=mol) ww = [0.0+1j*4.0, 1.0+1j*0.1, -2.0-1j*0.1] rf0_fm = gw.rf0_cmplx_vertex_ac(ww) rf0_mv = np.zeros_like(rf0_fm) vec = np.zeros((gw.nprod), dtyp...
x) for iw,w in enumerate(ww): for mu in range(gw.nprod): vec[:] = 0.0; vec[mu] = 1.0 rf0_mv[iw, mu,:] = gw.apply_rf0(vec, w) #print(rf0_fm.shape, rf0_mv.shape) #print('abs(rf0_fm-rf0_mv)', abs(rf0_fm-rf0_mv).sum()/rf0_fm.size) #print(abs(rf0_fm[0,:,:]-rf0_mv[0,:,:]).sum()) #pr...
rshk/config-gen
config_gen/commands/quickstart.py
Python
gpl-3.0
1,027
0.000974
""" :author: samu :created: 2/20/13 8:46 PM """ import os from cool_logging import getLogger logger = getLogger('config-gen') STANDARD_DIRS = [ 'templates', 'extra_templates', 'data', 'build', # No real need.. ] STANDARD_FILES = {} STANDARD_FILES['templates/example.html.jinja'] = \ '<h1>{{ ex...
.pyc /build/* """ def command(): root_dir = os.getcwd() for dirname in STANDARD_DIRS: os.makedirs(os.path.join(root_dir, dirname)) for file_name, file_content in STANDARD_FILES.iteritems(): with open(file_name, 'w') as f: f.write(file_content) print "Done. Now run 'make'...
me__ == '__main__': command()
ryfeus/lambda-packs
pytorch/source/torch/nn/_VF.py
Python
mit
310
0.003226
import torch import sys import types class VFModule(types.ModuleType): de
f __init__(s
elf, name): super(VFModule, self).__init__(name) self.vf = torch._C._VariableFunctions def __getattr__(self, attr): return getattr(self.vf, attr) sys.modules[__name__] = VFModule(__name__)