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
BitWriters/Zenith_project
zango/lib/python3.5/site-packages/django/core/files/move.py
Python
mit
2,794
0.002147
""" Move a file in the safest way possible:: >>> from django.core.files.move import file_move_safe >>> file_move_safe("/tmp/old_file", "/tmp/new_file"
) """ import os from shutil import copystat from django.core.files import locks __all__ = ['file_move_safe'] def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path, 'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All ot...
ile_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False): """ Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to another in pure Python. I...
yephper/django
tests/middleware_exceptions/tests.py
Python
bsd-3-clause
45,313
0.00373
import sys from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.core.signals import got_request_exception from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFa...
MiddlewareTests(BaseMiddlewareExceptionTest): def test_process_request_middleware(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) ...
ight middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_pro...
xuewei4d/scikit-learn
sklearn/impute/_iterative.py
Python
bsd-3-clause
31,089
0
from time import time from collections import namedtuple import warnings from scipy import stats import numpy as np from ..base import clone from ..exceptions import ConvergenceWarning from ..preprocessing import normalize from ..utils import (check_array, check_random_state, _safe_indexing, is_...
estimator features if n_nearest_features is not None, the ``imputation_order`` if ``random``, and the sampling from posterior if ``sample_posterior`` is True. Use an integer for determinism. See :term:`the Glossary <random_state>`. add_indicator : boolean, default=False If True, a ...
of the imputer's transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won't appear on the missing indicator even if there are missing values at transform/test time. Attributes ...
JonathanFrederick/job-hunt
config.py
Python
mit
510
0.001961
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SECRET_KEY = 'this-app-will-only-ever-run-locally' SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'
] class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Con
fig): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
ranarag/theano_works
birnn_theano.py
Python
bsd-2-clause
4,947
0.00849
import numpy as np import theano import theano.tensor as T import theano.typed_list import operator class BIRNN(object): def __init__(self, word_dim, hidden_dim=10, sequence_length=3): # Assign instance variables self.word_dim = word_dim self.hidden_dim = hidden_dim self.seq_length = ...
.config.floatX)) bhh_f = np.zeros((hidden_dim,), dtype=theano.config.floatX) bhh_b = np.zeros((hidden_dim,), dtype=theano.config.floatX) bhy = np.zeros((word_dim,), dtype=theano.config.floatX) self.bhh_f = theano.shared(name='bhh_f', value=bhh_f) self.bhh_b = theano.shared(name...
'x') y = T.fmatrix('y') def forward_pass_f(x_t, st_prev, Ul, Wl, bhl): st = T.tanh(Ul.dot(x_t) + Wl.dot(st_prev) + bhl) return st Ul, Wl, bhl = self.Wxh_f, self.Whh_f, self.bhh_f hf_states, updates = theano.scan( forward_pass_f, sequences...
walste/Fish-VR
auxiliary/CS_vs_off_all_files.py
Python
gpl-2.0
2,987
0.010044
import matplotlib.pyplot as plt import numpy as np import streamingpickle as spkl import math from scipy import stats ''' This program reads all spkl files, then sorts the alphas in to CS and off, and takes the absolute values of all alphas. The upper cut off is 90 (set to 90) and the lower cut off is 5 (set to 0). The...
spkl', '../fishVR_data/20141113_153643results_file.spkl', '../fishVR_data/20141114_100453results_file.spkl', '../fishVR_data/20141118_091259results_file.spkl', '../fishVR_data/20141118_150451results_file.spkl', '../fishVR_data/20141120_100137results_file.spkl', '../fishVR_data/...
lts_file.spkl', '../fishVR_data/20141126_104159results_file.spkl', '../fishVR_data/20141127_103904results_file.spkl'] #spkl_files = ['../fishVR_data/20141112_120446results_file.spkl', '../fishVR_data/20141112_193447results_file.spkl'] w = [] for myfile in spkl_files: f = open(myfile) fl = spkl.s_...
aclifton/cpeg853-gem5
configs/network/Network.py
Python
bsd-3-clause
5,453
0.003301
# Copyright (c) 2016 Georgia Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditi...
t, ruby uses the simple timing cpu parser.set_defaults(cpu_type="timing") parser.add_option("--topology", type="string", default="Crossbar", help="check configs/topologies for complete set") parser.add_option("--mesh-rows", type="int", default=0, help="the number...
n the mesh topology") parser.add_option("--network", type="choice", default="simple", choices=['simple', 'garnet2.0'], help="'simple'|'garnet2.0'") parser.add_option("--router-latency", action="store", type="int", default=1, ...
csaez/ibl_stuff
ibl_stuff/tests/test_libs.py
Python
mit
2,944
0.00034
import os import shutil import unittest from PySide.QtCore import QSettings from ibl_stuff.libs import base as libs LIBRARY = libs.get_library() ENV_LIBRARY = os.environ.get("IBL_LIBRARY") class SimpleTests(unittest.TestCase): def test_clear_cache(self): self.assertTrue(libs.clear_cache()) def t...
bar", "baz"]): x = libs.new_ibl("test%d" % i) x["projects"] = [prj] x["tags"] = [prj] def tearDow
n(self): _library = os.path.join(os.path.expanduser("~"), "test_library") shutil.rmtree(_library) if ENV_LIBRARY: os.environ["IBL_LIBRARY"] = ENV_LIBRARY libs.set_library(LIBRARY) def test_get_library(self): os.environ["IBL_LIBRARY"] = "test" self.assertE...
sstjohn/thundergate
py/_aiotap/driver.py
Python
gpl-3.0
5,406
0.00296
''' ThunderGate - an open source toolkit for PCI bus exploration Copyright (C) 2015-2016 Saul St. John 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 Lice...
ne def help_handler(self): '''display keypress bindings''' print for k in self.keypress_handlers: print "%s - %s" % (k, self.keypress_handlers[k].__doc__) print @coroutine def verbosity_handler(self): '''toggle tap dri
ver verbosity''' self.verbose = not self.verbose print "[+] verbosity %s" % ("enabled" if self.verbose else "disabled") @coroutine def quit_handler(self): '''terminate tap driver execution and close device''' self.running = False self.loop.stop() @coroutine def ...
mikelarre/odoomrp-wip-1
mrp_operations_extension/models/mrp_routing_workcenter.py
Python
agpl-3.0
3,339
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2008-2014 AvanzOSC (Daniel). All Rights Reserved # Date: 10/07/2014 # # This program is free software: you can redistribute it and/or modify ...
: kont = 0 wkc = False for opwc_line in record.op_wc_lines: if opwc_line.default: kont += 1 if not wkc:
record.workcenter_id = opwc_line.workcenter.id if kont > 1: raise exceptions.Warning(_('There is another line set as ' 'default, disable it first.')) @api.one @api.constrains('op_wc_lines') def _check_default(self): kont = 0 ...
intel-analytics/BigDL
python/dllib/test/local_integration/commands/prepare_nltk.py
Python
apache-2.0
622
0
# # Copyright 2016 The BigDL Authors. # # 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 ...
r express or implied. # See the License for the specific language governing permissions and # limitat
ions under the License. # import nltk nltk.download('punkt')
saraivaufc/jornalEletronico
newspaper/urls/userAuthenticated/subsection.py
Python
mit
316
0.018987
from django.conf.urls import patterns, include, url from newspa
per.views.userAuthenticated import addSubSection, editSubSection, remSubSection urlpatterns = patterns('', url(r'^add/$', addSubSection), url(r'^edit/(?P<id_subsection>\d+)/$', editSubSection), url(r'^rem/(?P<id
_subsection>\d+)/$', remSubSection), )
JackKelly/neuralnilm_prototype
scripts/e405.py
Python
mit
27,430
0.003901
from __future__ import print_function, division import matplotlib import logging from sys import stdout matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import (Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer, Bidirectio...
window=("2013-06-01", "2014-07-01"), seq_length=512, # random_window=64, output_one_appliance=False, boolean_targets=False, train_buildings=[1], validation_buildings=[1], # skip_probability=0.9, one_target_per_seq=False, n_seq_per_batch=64, subsample_target=4, include
_diff=False, include_power=True, clip_appliance_power=True, target_is_prediction=False, # independently_center_inputs=True, # standardise_input=True, # standardise_targets=True, # unit_variance_targets=True, input_padding=2, lag=0 # classification=True # reshape_target_to_2D=True ...
lief-project/LIEF
examples/python/vdex_json.py
Python
apache-2.0
639
0.014107
#!/usr/bin/env python # -*- coding: utf-8 -*- # D
escription # ----------- # Print information about a DEX file in the JSON format import argparse import sys import lief import json def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='VDEX file') args = parser.parse_args() if not lief.VDEX.is_vdex(args.file):
print("{} is not a VDEX file".format(args.file)) return 1 dexfile = lief.VDEX.parse(args.file) json_data = json.loads(lief.to_json(dexfile)) print(json.dumps(json_data, sort_keys = True, indent = 4)) if __name__ == "__main__": sys.exit(main())
heartsdale/heartsdale-cogs
limin.py
Python
mit
363
0.008264
import discord from discord.e
xt import commands class Mycog: """My custom cog that does stuff!""" def __init__(self, bot): self.bot = bot @commands.command() async def mycom(self): """This does stuff!""" #Your code will go here await self.bot.say("I can do stuff!") def setup(bot): bot.ad
d_cog(Mycog(bot))
mingotang/libdata
structures/Event.py
Python
gpl-3.0
2,531
0.001185
# -*- encoding: UTF-8 -*- import datetime from sqlalchemy import MetaData, Table, Column, String, Integer from Interface import AbstractDataObject from utils.String import attributes_repr def define_event_table(meta: MetaData): return Table( 'events', meta, Column('book_id', String, primary_key=...
def compare_by(self, **kwargs): for tag in kwargs: if tag not in self.__attributes__: raise AttributeError('Event has no attribute {}'.format(tag)) else: if kwargs[tag] != getattr(self, tag): return False return True @c
lassmethod def init_from(cls, value): if isinstance(value, dict): return cls( book_id=value['sysID'], reader_id=value['userID'], event_date=value['event_date'], event_type=value['event_type'], ) else: ...
Sbalbp/DIRAC
RequestManagementSystem/Service/ReqProxyHandler.py
Python
gpl-3.0
7,200
0.034444
######################################################################## # $HeadURL$ # File: ReqProxyHandler.py # Author: Krzysztof.Ciba@NOSPAMgmail.com # Date: 2013/06/04 13:18:41 ######################################################################## """ :mod: RequestProxyHandler .. module: ReqtProxyHandler :syn...
m Careful with that axe, Eugene! Some 'transfer' requests are using local fs and they never should be forwarded to the central RequestManager. """ __RCSID__ = "$Id$" # # #
@file RequestProxyHandler.py # @author Krzysztof.Ciba@NOSPAMgmail.com # @date 2012/07/20 13:18:58 # @brief Definition of RequestProxyHandler class. # # imports import os from types import DictType try: from hashlib import md5 except ImportError: from md5 import md5 # # from DIRAC from DIRAC import S_OK, S_ERROR, g...
michaeljoseph/sealeyes
sealeyes/__init__.py
Python
apache-2.0
288
0.003472
"""Python Library Boilerplate contains all the boilerplate you need to create a Python package.""" __author__ = 'Michael Joseph' __email__ = 'michaeljoseph@gmail.com' __url__ = 'h
ttps://github.com/michaeljo
seph/sealeyes' __version__ = '0.0.1' def sealeyes(): return 'Hello World!'
GPContributors/PyGP
pygp/connection/pcsc/__init__.py
Python
lgpl-3.0
41
0
from pygp.connection.pc
sc.scard impor
t *
tadgh/ArgoRevisit
third_party/nltk/grammar.py
Python
apache-2.0
53,776
0.00398
# -*- coding: utf-8 -*- # Natural Language Toolkit: Context Free Grammars # # Copyright (C) 2001-2011 NLTK Project # Author: Steven Bird <sb@csse.unimelb.edu.au> # Edward Loper <edloper@seas.upenn.edu> # Jason Narad <jason.narad@gmail.com> # Peter Ljunglöf <peter.ljunglof@heatherleaf.se> # URL: ...
l if their symbols are equal. @see: L{ContextFreeGrammar} @see: L{Production} @type _symbol: (any) @ivar _symbol: The node value corresponding to this C{Nonterminal}. This value must be immutable and hashable. """ def __init__(self, symbol): """ Construct a new non...
bol: (any) @param symbol: The node value corresponding to this C{Nonterminal}. This value must be immutable and hashable. """ self._symbol = symbol self._hash = hash(symbol) def symbol(self): """ @return: The node value corresponding to this...
wateraccounting/wa
Functions/Five/Fraction_Based.py
Python
apache-2.0
2,304
0.006944
# -*- coding: utf-8 -*- """ Created on Mon May 15 14:27:44 2017 @author: tih """ def Calc_surface_withdrawal(Dir_Basin, nc_outname, Startdate, Enddate, Example_dataset, ETref_Product, P_Product): from netCDF4 import Dataset import wa.Functions.Four as Four import wa.General.raster_conversions as RC ...
ns DataCube_frac_sw = RC.Open_nc_array(nc_outname, "Fraction_Surface_Water_Supply") # Total amount of ETblue taken out of rivers DataCube_surface_withdrawal = Data
Cube_ETblue * DataCube_frac_sw[None,:,:] return(DataCube_surface_withdrawal) def Calc_surface_runoff(Dir_Basin, nc_outname, Startdate, Enddate, Example_dataset, ETref_Product, P_Product): from netCDF4 import Dataset import numpy as np import wa.Functions.Four as Four import wa.General.raster_con...
judithvillanueva/First_assignment
movie/imovie/views.py
Python
gpl-3.0
4,630
0.015983
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.views.generic import DetailView from django.views.generic import ListView from django.views.generic.edit import CreateView from models import MovieReview, Movie, Actor, Di...
eCreate, self).form_valid(form) def MovieDelete(request, pk): '''Movie delete''' movie = get_object_or_404(Movie, pk=pk) movie.delete() return HttpResponseRedirect(reverse('imovie:movie_list', )) class ActorDetail(DetailView): model = Actor template_name = 'actor/actor_detail.html' def get_context_data(self, ...
get_context_data(**kwargs) return context class ActorCreate(CreateView): ''' Create Actor, use template form.html ''' model = Actor template_name = 'form.html' form_class = ActorForm def form_valid(self, form): form.instance.user = self.request.user return super(ActorCreate, self).form_valid(form) def Ac...
smarie/python-classtools-autocode
autoclass/autoclass_.py
Python
bsd-3-clause
12,616
0.00539
try: # python 3.5+ from typing import Union, Tuple, TypeVar try: # python 3.5.3+ from typing import Type except ImportError: pass T = TypeVar('T') except ImportError: pass try: # python 3+ from inspect import signature except ImportError: from funcsigs import signature t...
d when `pyfields
` is installed. Please `pip install " "pyfields`") # Get constructor init_fun, is_init_inherited = get_constructor(cls) # Check for pyfields fields if WITH_PYFIELDS: all_pyfields = get_fields(cls) has_pyfields = len(all_pyfields) > 0 # 'or autofields' ?: c...
Melissa-AI/Melissa-Web
GreyMatter/open_firefox.py
Python
mit
152
0.006579
from selenium import webdriver from SenseCells.tt
s import tts def open_firefox(): tts('Aye aye captain, opening Firefox') webdriver.F
irefox()
pombredanne/SimSearch
tests/test_argsort_best.py
Python
gpl-3.0
974
0.014374
import numpy as np import random import sys from simsearch import utils @utils.time_func def argsort(arr): arr.argsort(0) def test(arr, k): best_indexes = utils.argsort_best(arr, k, reverse=True) print 'Array = %s' % arr print 'Best indexes = %s' % best_indexes print 'Best elements = %s' % a...
rr_size, k): arr = np.array(xrange(arr_size)) test(arr, k) arr = np.random.sample(arr_size) test(arr, k) arr = np.ones(arr_s
ize) test(arr, k) if __name__ == '__main__': if len(sys.argv) != 3: print 'Usage: python %s size_array number_of_k_elements' % sys.argv[0] else: main(*map(int, sys.argv[1:]))
sumanta23/pyscript
pyscript/terminal.py
Python
apache-2.0
6,496
0.003849
#!/usr/bin/env python import logging import io from time import sleep import json import requests from . import * logging.basicConfig(filename='terminal.log', level=logging.DEBUG) class PyTerminal(): """ This class allows the execution of a command in the same way as the web-cli does. The return is a Co...
self._response = response self._files = [] self.terminal = terminal def is_success_sent(self): """ :return: boolean, true if the request was successfully sent to the server """ return self._success def http_response_code(self): ...
rn self._http_response_code def get_output(self): """ :return: list of strings representing the output from the command lines are single strings table rows are single strings with tabs delimiting columns """ ...
BartMassey/blog-escape
filters/txt.py
Python
mit
319
0
# Copy
right (c) 2017 Bart Massey # This work is available under the "MIT license". # Please see the file COPYING in this distribut
ion # for license terms. # "Format" text content. # Return a protected version of # the given text content. def filter_txt(content, **args): return "<pre>\n" + content + "\n</pre>\n"
jldaniel/Gaia
setup.py
Python
mit
4,535
0.004631
__author__ = 'jdaniel' import argparse from distutils.core import setup, Command import shutil from setupto
ols import find_packages import os import sys __version__ = "1.0.0" GAIA_DIR = os.getenv("HOME") + "/Gaia_v" + __version__ #GAIA_DIR = "/my/cu
stom/install/location" + "/Gaia_" + __version__ class Color(object): """ Escape sequences for adding Color to console output. Note, that these do not write to file. """ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\...
niccokunzmann/pulse-programming
camera_pulse.py
Python
gpl-3.0
1,372
0.00656
"""Run the interactive pulse program. Keys: - Escape - Exit the program - Space - Update program image - C - Calibrate the image again """ import time import cv2 from pulse_programming import PulseField from camera_calibration import Calibration window = "Camer
a Pulse Programming" cv2.namedWindow("Threshold", cv2.WINDOW_AUTOSIZE) cv2.namedWindow("Capture", cv2.WINDOW_AUTOSIZE) calibration = Calibration((1024, 768), window_name=window) def calibrate(): calibration.record_points(20) calibration.show_area_in_camera() print("Please move the window to fill the screen an...
.waitKey(1) image = calibration.warp_camera_in_projection() cv2.imshow("Capture", image) pulse_field.set_program_image(image, blue_threshold=0.57) pulse_field = PulseField() #pulse_field.DELATION_ITERATIONS = 4 #pulse_field.EROSION_ITERATIONS = 3 update_pulse_program_from_camera() while True: key = cv2...
alexanderteves/OpsBox
mail.py
Python
mit
937
0
from email.mime.text import MIMEText from smtplib import SMTP class Gmail(object): """Send an email with Google Mail Can easily be used with other provid
ers by editing the server and port in send() Args: credentials (tuple): (username, password) """ def __init__(self, credentials): self.user, self.password = credentials def send(self, receiver, subject, body): """Send email Args: receiver (str): Address...
: Body of email """ message = MIMEText(body) message['Subject'] = subject message['From'] = self.user message['To'] = receiver server = SMTP('smtp.gmail.com', 587) server.starttls() server.login(self.user, self.password) server.sendmail(self.user,...
lefnire/tensorforce
examples/openai_gym_async.py
Python
apache-2.0
9,250
0.002919
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
pg.json -n examples/configs/mlp2_network.json -e 50000 -m 2000 -W 3 Or on CartPole-v0: $ python examples/openai_gym_async.py CartPole-v0 -a examples/configs/vpg.jso
n -n examples/configs/mlp2_network.json -e 10000 -m 200 -W 3 You can check what the workers are doing: $ tmux a -t OpenAI # `ctrl+b d` to exit tmux To kill the session: $ python examples/openai_gym_async.py CartPole-v0 -W 3 -K """ from __future__ import absolute_import from __future__ import division from __future_...
foundertherapy/django-users-plus
accountsplus/validators.py
Python
mit
711
0.014065
from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ import re class ComplexPasswordValidator(object): def validate(self, password, user=None): regex = '(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@#!%*?&])[A-Za-z\d$@#!%*?&]'
if not re.match(regex, password): raise ValidationError(_('Password should contain uppercase, lowercase, numeric values and at least ' 'one of the following $@#!%*?&'), code='password_is_weak'
) def get_help_text(self): return _('Password should contain uppercase, lowercase, numeric values and at least ' 'one of the following $@#!%*?&')
giltis/scikit-xray
skxray/core/tests/test_roi.py
Python
bsd-3-clause
14,545
0.000413
# ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # # # Redistribution and use in ...
Laboratory nor the names
of its contributors may be used # # to endorse or promote products derived from this software without # # specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBU...
RyanSkraba/beam
sdks/python/apache_beam/io/tfrecordio_test.py
Python
apache-2.0
18,843
0.008226
# # 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 us...
', num_shards=0, shard_name_template=None, compression_type=CompressionTypes.UNCOMPRESSED) self._write_lines(sink, path, [b'foo']) with open(path, 'rb') as f: self.assertEqual(f.read(), record) def test_write_record_multiple(self): w
ith TempDir() as temp_dir: path = temp_dir.create_temp_file('result') record = binascii.a2b_base64(FOO_BAR_RECORD_BASE64) sink = _TFRecordSink( path, coder=coders.BytesCoder(), file_name_suffix='', num_shards=0, shard_name_template=None, comp...
Jerad-M/ubfs
classes/custom/place/province.py
Python
apache-2.0
1,469
0.027229
import datetime from ...place import Place from ...spec import Spec from .city import City from .village import Village from .structure import Structure from .restaurant import Restaura
nt class Province(Place): """Provinces exist within territories, and can contain cities, villages, and structures Attributes allowedChildEntities Entity spec types that can be created from this context spec Spec type of this Entity""" # Things that child class SHOULDNT need to redeclare ...
s that a few child classes will need to redeclare allowedChildEntities = [Spec.CITY, Spec.VILLAGE, Spec.STRUCTURE, Spec.RESTAURANT] # Things every child class will want to redeclare spec = Spec.PROVINCE # ---- Methods ---- # def initEntityFromSpec(self, spec, key, path): """Attempt to initialize a specific ent...
Tanmay28/coala
coalib/output/Interactions.py
Python
agpl-3.0
1,188
0
def fail_acquire_settings(log_printer, settings_names_dict): """ This method throws an exception if any setting needs to be acquired. :param log_printer: Printer responsible for logging the messages. :param
settings: A dictionary with the settings name as key and
a list containing a description in [0] and the name of the bears who need this setting in [1] and following. :raises AssertionError: If any setting is required. :raises TypeError: If `settings_names_dict` is not a dictiona...
boreq/recaptcha-client-python3
captcha.py
Python
mit
3,161
0.00696
import urllib API_SSL_SERVER="https://www.google.com/recaptcha/api" API_SERVER="http://www.google.com/recaptcha/api" VERIFY_SERVER="www.google.com" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error_code = error_code def display_htm...
urns RecaptchaResponsek for the request recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form recaptcha_response_field -- The value of recaptcha_response_field from the form priva
te_key -- your reCAPTCHA private key remote_ip -- the user's ip address """ # There is no point in checking if the captcha is valid if one of the fields is empty. if not (recaptcha_response_field and recaptcha_challenge_field): return RecaptchaResponse(is_valid=False, error_code='incorrect-capt...
andrewsosa/hackfsu_com
api/api/migrations/0003_auto_20161206_0538.py
Python
apache-2.0
458
0
# -*- coding: utf-8 -*- #
Generated by Django 1.10.4 on 2016-12-06 05:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_hackathon_name'), ] operations = [ migrations.AlterField( model_name='hackat...
field=models.CharField(max_length=100, unique=True), ), ]
argonemyth/sentry
src/sentry/api/permissions.py
Python
bsd-3-clause
1,954
0
from __future__ import absolute_import from rest_framework import permissions from sentry.models import OrganizationMemberType, ProjectKey class NoPermission(permissions.BasePermission): def has_permission(self, request, view): return False class ScopedPermission(permissions.BasePermission): """ ...
not enforce organization-level (i.e. has_global-access) vs project # level so that should be done per subclass access_map = { 'GET': None, 'POST': OrganizationMemberType.ADMIN, 'PUT': OrganizationMemberType.ADMIN, 'DELETE': OrganizationMemberType.OWNER, }
def has_permission(self, request, view): # session-based auth has all scopes for a logged in user if not request.auth: return request.user.is_authenticated() allowed_scopes = set(self.scope_map[request.method]) current_scopes = request.auth.get_scopes() return any(s...
junhuqc/pybot
setup.py
Python
mit
1,259
0.002383
from os.path import join, dirname from setuptools import setup, find_packages __version__ = open(join(dirname(__file__), 'pybot/VERSION')).read().strip() i
nstall_requires = ( 'requests>=2.4.0', 'websocket-client>=0.22.0', 'slacker>=0.5.5', 'six>=1.10.0' ) # yapf: disable e
xcludes = ( '*test*', '*local_settings*', ) # yapf: disable setup(name='pybot', version=__version__, license='BSD', description='A simple slack bot for deploy, test report, and event message!', author='Wilson', author_email='blaise1190@gmail.com', url='https://github.com/jun...
rspavel/spack
var/spack/repos/builtin/packages/xbraid/package.py
Python
lgpl-2.1
1,879
0.001597
# 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 import os.path class Xbraid(MakefilePackage): """XBraid: Parallel time integration w...
) insta
ll_tree('docs', prefix.share.docs) @property def libs(self): return find_libraries('libbraid', root=self.prefix, shared=False, recursive=True)
olivierlemasle/murano
murano_tempest_tests/tests/api/application_catalog/test_environments_negative.py
Python
apache-2.0
3,454
0
# Copyright (c) 2016 Mirantis, 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...
base.BaseApplicationCatalogTest): @attr(type='negative') def test_delete_environment_with_wrong_env_id(self): self.assertRaises(exceptions.NotFound, self.application_catalog_client.delete_environment, utils.generate_uuid()) @attr(type='negative')...
utils.generate_name('double_del_negavive') environment = self.application_catalog_client.\ create_environment(name) self.application_catalog_client.delete_environment(environment['id']) self.assertRaises(exceptions.NotFound, self.application_catalog_client....
Erotemic/ubelt
dev/bench/bench_hash.py
Python
apache-2.0
2,805
0.00107
def benchmark_hash_data(): """ CommandLine: python ~/code/ubelt/dev/bench_hash.py --convert=True --show python ~/code/ubelt/dev/bench_hash.py --convert=False --show """ import ubelt as ub #ITEM = 'JUST A STRING' * 100 ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4] HASHERS = ...
=hasher, convert=convert) results[hasher].update({N: ti.mean()}) col = {h: results[h][N] for h in HASHERS} sortx = ub.argsort(col) ranking = ub.dict_subset(col, sortx) print('walltime: ' + ub.repr2(ranking, precision=9, nl=0)) best = next(iter(r
anking)) #pairs = list(ub.iter_window( 2)) pairs = [(k, best) for k in ranking] ratios = [ranking[k1] / ranking[k2] for k1, k2 in pairs] nicekeys = ['{}/{}'.format(k1, k2) for k1, k2 in pairs] relratios = ub.odict(zip(nicekeys, ratios)) print('speedup: ' + ub.repr2(relrat...
apache/incubator-superset
tests/integration_tests/reports/api_tests.py
Python
apache-2.0
57,892
0.000639
# 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 u...
report_schedule.database.database_name, }, "description": report_schedule.description, "grace_pe
riod": report_schedule.grace_period, "id": report_schedule.id, "last_eval_dttm": report_schedule.last_eval_dttm, "last_state": report_schedule.last_state, "last_value": report_schedule.last_value, "last_value_row_json": report_schedule.last_value_row_json, ...
alias-org/alias
alias/semantics/labellings/labelling_semi_stable.py
Python
gpl-3.0
1,160
0.001724
import alias as al import copy def labelling_semi_stable(af): potential_semi_stables = [] def find_semi_stables(L): for Ldash in potential_semi_stables: if Ldash.undecargs <= L.undecargs: return illegal = False for arg in L.inargs: if L.framewor...
sii = set() for arg in L.inargs: if L.framework.get_arg_obj(arg).is_super_illegally_in(L): sii.add(arg) if sii: fi
nd_semi_stables(L.transition_step(sii.pop())) for arg in L.inargs: if L.framework.get_arg_obj(arg).is_illegally_in(L): find_semi_stables(L.transition_step(arg)) find_semi_stables(af.generate_all_in()) return potential_semi_stables
Luther-Lost-and-Found/Lost-and-Found
Image_Proc/color_detect_server.py
Python
gpl-3.0
2,888
0.007271
# Do not Store images in the database, rather store True or False # and keep image names same as the primary key of the item # Delete the images of the items that have been deleted # ================================================================= # Have the images evaluated when they get uploaded # Save the evaluated...
.INTER_AREA) cv2.imwrite(directory+image_name,resized) image = cv2.imread(directory+image_name,1) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) image_mat = image.reshape((image.shape[0] * image.shape[1], 3)) clt = KMeans(n_clusters = 3) clt.fit(image_mat) perce...
olor1 = self.get_colour_name(np.array(color[0]).tolist()) percentage2, color2 = self.get_colour_name(np.array(color[1]).tolist()) percentage3, color3 = self.get_colour_name(np.array(color[2]).tolist()) print(percentage[0], color1) print(percentage[1], color2) print(percentage[2],...
zouzhberk/ambaridemo
demo-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/historyserver.py
Python
apache-2.0
7,844
0.008159
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
ms.version), '2.2.0.0') >= 0: conf_select.select(params.stack_name, "hadoop", params.version) hdp_select.select("hadoop-mapreduce-historyserver", params.version
) # MC Hammer said, "Can't touch this" copy_to_hdfs("mapreduce", params.user_group, params.hdfs_user, host_sys_prepped=params.host_sys_prepped) copy_to_hdfs("tez", params.user_group, params.hdfs_user, host_sys_prepped=params.host_sys_prepped) params.HdfsResource(None, action="execute") def st...
markodolancic/selenium
py/selenium/webdriver/__init__.py
Python
apache-2.0
1,927
0.001038
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing pe
rmissions and limitations # under the License. from .firefox.webdriver import WebDriver as Firefox # noqa from .firefox.firefox_profile import FirefoxProfile # noqa from .firefox.options import Options as FirefoxOptions # noqa from .chrome.webdriver import WebDriver as Chrome # noqa from .chrome.options import Opt...
EthanIsHere/Fury-Cogs
advancedsay/advancedsaycog.py
Python
gpl-3.0
4,513
0.001108
import logging import logging.handlers import asyncio import discord from __main__ import send_cmd_help, settings from cogs.utils.settings import Settings from cogs.utils.dataIO import dataIO from .utils import checks from discord.ext import commands import random class advancedsay: """Says things in o...
"""Make your text lower.""" await self.bot.say(message.lower()) @advancedsay.command(name="split", pass_context=True) async def split(self, ctx, *, message): "
""Split your text into chunks.""" x = message await self.bot.say(x.split(" ")) @advancedsay.command(name="one", pass_context=True) async def one(self, ctx, *, message): """Remove all spaces in your text.""" newmessage = "" things = message.split(" ") for...
eharney/cinder
cinder/api/v3/attachments.py
Python
apache-2.0
11,362
0
# 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...
eate and initialize a volume attachment based on the provided input parameters. If the caller does not yet have the connector information but needs to
reserve an attachment for the volume (ie Nova BootFromVolume) the create can be called with just the volume-uuid and the server identifier. This will reserve an attachment, mark the volume as reserved and prevent any new attachment_create calls from being made until the attachment...
nakulsolanki/HomeAutomation
python/apiUtil.py
Python
apache-2.0
4,767
0.040487
import sys import os.path import fcntl, socket, struct import json import urllib import urllib2 import httplib from json import JSONEncoder class NodeConfig: def __init__(self, debug = True): self.configDict = {} self.Name = ""; self.progId = -1 self.nodeId = -1 self.debug = debug self.Protocol = "http"...
ef getNodeInfo(self): # get the macId for eth0 for this machine macId = self.getMacId() apiUrl = self.Protocol + "://" + self.WebApiServer + "/api/Node/GetByMacId?macId=" + macId request = urllib2.urlopen(apiUrl) node = request.read() if self.debug: print "Node Exists: " + node self.Node = json.loads(...
key): if len(self.Node) == 0: self.getNodeInfo() configurations = self.Node['configurations'] for configuration in configurations: if configuration['key'] == key: return str(configuration['value']) def getProgramInfo(self, name): if self.Node is None: self.getNodeInfo() programs = self.Node...
jeremiah-c-leary/vhdl-style-guide
vsg/tests/process/test_rule_011.py
Python
gpl-3.0
1,156
0.004325
import os import unittest from vsg.rules import process from vsg import vhdlFile from vsg.tests import
utils sTestDir = os.path.d
irname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_011_test_input.vhd')) lExpected = [] lExpected.append('') utils.read_file(os.path.join(sTestDir, 'rule_011_test_input.fixed.vhd'), lExpected, False) class test_process_rule(unittest.TestCase): def setUp(self): self...
sassoftware/rmake
rmake/cmdline/helper.py
Python
apache-2.0
30,546
0.002488
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
for the specific language governing permissi
ons and # limitations under the License. # """ Client that contains most of the behavior available from the command line. This client wraps around the low-level rMake Server client to provide functionality that crosses client/server boundaries. """ import getpass import copy import itertools import os import sys fr...
zombiezen/turbohvz
hvz/json.py
Python
gpl-3.0
1,149
0
#!/
usr/bin/env python # # json.py # TurboHvZ # # Copyright (C) 2008 Ross Light # # 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)...
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/lice...
antoniomezzacapo/qiskit-tutorial
community/games/game_engines/q_tic_tac_toe.py
Python
apache-2.0
13,845
0.020224
"""A quantum tic tac toe running in command line""" from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import CompositeGate from qiskit import execute import numpy as np from composite_gates import cry,cnx,any_x,bus_or,x_bus class Move(): def __init__(self,ind...
er players can attempt to occupy it too.") print("Then the new move will be anti-correlated with the move already in that spot.") print("And so the game branches out into many simultaneous states.") print("The outcome is then computed by simulation...") print("so don't ma...
r 'q' at any time to quit") print("Enter 'end' to end the game, and compute the winner(s).") print("Good luck!") while
miminus/youtube-dl
youtube_dl/extractor/xuite.py
Python
unlicense
5,378
0.001139
# -*- coding: utf-8 -*- from __future__ import unicode_literals import base64 from .common import InfoExtractor from ..compat import compat_urllib_parse_unquote from ..utils import ( ExtractorError, parse_iso8601, parse_duration, ) class XuiteIE(InfoExtractor): IE_DESC = '隨意窩Xuite影音' _REGEX_BASE...
'ext': 'mp4', 'title': '暗殺教室 02', 'description': '字幕:【極影字幕社】', 'thumbnail': 're:^https?://.*\.jpg$', 'duration': 1384.907, 'timestamp': 1421481240, 'upload_date': '20150117', 'uploader': '我只是想認真點', 'uploader_id': '242...
BF-%E7%9C%BC%E6%B7%9A%E6%88%90%E8%A9%A9', 'only_matching': True, }] @staticmethod def base64_decode_utf8(data): return base64.b64decode(data.encode('utf-8')).decode('utf-8') @staticmethod def base64_encode_utf8(data): return base64.b64encode(data.encode('utf-8')).decode('ut...
cloudtools/awacs
awacs/budgets.py
Python
bsd-2-clause
1,133
0.000883
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Budget Service" prefix = "budgets" class Action(BaseAction): def __init__(self, action: str = None) -> None: ...
egion=region, account=account ) CreateBudg
etAction = Action("CreateBudgetAction") DeleteBudgetAction = Action("DeleteBudgetAction") DescribeBudgetAction = Action("DescribeBudgetAction") DescribeBudgetActionHistories = Action("DescribeBudgetActionHistories") DescribeBudgetActionsForAccount = Action("DescribeBudgetActionsForAccount") DescribeBudgetActionsForBudg...
yougov/librarypaste
librarypaste/jsonstore.py
Python
mit
2,641
0
import re import os import time import datetime import json from .datastore import DataStore class JsonDataStore(DataStore): """Stores using json encoded into files""" def __init__(self, repo): super(JsonDataStore, self).__init__() self.repo = repo if not os.path.exists(repo): ...
for line in self
.open(filename) ) return { key: value for key, sep, value in lines } def lookup(self, nick): return self.load_key_values('log.txt').get(nick) def _lookupUid(self, shortid): if shortid not in self.shortids: self.shortids = self.load_ke...
chronomex/pysmpp
pySMPP/pdu.py
Python
gpl-2.0
4,092
0.017351
# This file is part of pySMPP # Copyright (C) 2003 Damjan Georgievski # # 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. ...
n(s) < 16: raise PDUError("Illegal PDU (length t
oo short)") ( self.command_length, self.command_id, self.command_status, self.sequence_number ) = struct.unpack('>iiii',s[0:16]) l = len(s[16:]) if l > 0: self.body = struct.unpack(`l`+'s',s[16:])[0] else: self.body = None r...
dufferzafar/critiquebrainz
critiquebrainz/data/utils_test.py
Python
gpl-2.0
673
0
from critiquebrainz.
data.testing import DataTestCase from critiquebrainz.data import utils class DataUtilsTestCase(DataTestCase): def test_explode_db_uri(self): uri = "postgresql://cb_user:cb_password@localhost:5432/cb" hostname, db_name, username, password = utils.explode_db_u
ri(uri) self.assertEqual(hostname, "localhost") self.assertEqual(db_name, "cb") self.assertEqual(username, "cb_user") self.assertEqual(password, "cb_password") def test_slugify(self): self.assertEqual(utils.slugify(u'CC BY-NC-SA 3.0'), 'cc-by-nc-sa-30') self.assertE...
slb6968/is210-week-04-synthesizing
task_01.py
Python
mpl-2.0
1,384
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """This program ccontains functions for temperature conversions.""" import decimal ABSOLUTE_DIFFERENCE = decimal.Decima
l('273.15') def fahrenheit_to_celsius(degrees): """Converts from Fahrenheit to Celsius. Args: degrees: Fahrenheit temperature in decimal value Returns: A temperature in Celsius equivalent to the input Fahrenheit degrees. Raises: NameError: name 'x' i
s not defined (argument must be a number) """ return ((decimal.Decimal(degrees) - 32) * 5) / 9 def celsius_to_kelvin(degrees): """Converts from Celsius to Kelvin. Args: degrees: Celsius temperature in decimal value Returns: A temperature in Kelvin equivalent to the input Celsius ...
ligo-cbc/pycbc-glue
pycbc_glue/LDBDClient.py
Python
gpl-3.0
11,113
0.010348
""" The LDBDClient module provides an API for connecting to and making requests of a LDBDServer. This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}. This file is part of the Grid LSC User Environment (GLUE) GLUE is free software: you can redistribute it and/or modify it under the terms ...
t: string @param port: port on which the LDBD Server listens @type port: integer @param identity: string which the
LDBD Server identifies itself @type identity: string @return: None """ # remove the globus tcp port range environment variable if set try: port_range = os.environ["GLOBUS_TCP_PORT_RANGE"] os.environ["GLOBUS_TCP_PORT_RANGE"] = "" except: pass self.host = host self...
ntoll/Pcode
venv/__init__.py
Python
gpl-3.0
16,893
0.00071
""" Virtual environment (venv) package for Python. Based on PEP 405. Copyright (C) 2011-2012 Vinay Sajip. Licensed to the PSF under a contributor agreement. usage: python -m venv [-h] [--system-site-packages] [--symlinks] [--clear] [--upgrade] ENV_DIR [ENV_DIR ...] Creates virtual Python envi...
ValueError('Directory exists: %s' % env_dir) if os.path.exists(env_dir) and self.clear: shutil.rmtree(env_dir) context = Context() context.env_dir = env_dir context.env_name = os.path.split(env_dir)[1] context.prompt = '(%s) ' % context.env_name create_if_nee...
stalled_python_path)) context.executable = self.installed_python_path context.python_dir = dirname context.python_exe = exename if sys.platform == 'win32': binname = 'Scripts' incpath = 'Include' libpath = os.path.join(env_dir, 'Lib', 'site-packages') ...
boonchu/pykickstart
tests/parser/packages.py
Python
gpl-2.0
4,941
0.00425
import unittest import warnings from tests.baseclass import ParserTest from pykickstart.constants import KS_MISSING_IGNORE from pykickstart.errors import KickstartParseError from pykickstart.version import F21, RHEL6 from pykickstart.parser import Group class GroupsAreHashable_TestCase(ParserTest): def runTest(se...
--ignoremissing --default --instLangs="bg_BG" %end """ def runTest(self): self.parser.readKickstartFromString(self.ks) # Verify that the options are parsed as expected self.assertTrue(self.handler.packages.default) self.assertEqual(self.handler.packages.handl
eMissing, KS_MISSING_IGNORE) self.assertEqual(self.handler.packages.instLangs, "bg_BG") # extra test coverage self.assertTrue(self.parser._sections['%packages'].seen) class Packages_Contains_Comments_TestCase(ParserTest): ks = """ %packages packageA # this is an end-of-line comment # th...
Illemius/telegram-karma-bot
extensions/helper.py
Python
mit
5,918
0.003217
from TranslateLib import translate as _ from meta import bot from models.dialogs import Dialogs from utils.chat import ParseUserData, get_username_or_name, typing, crash_message @bot.message_handler(commands=['help']) def cmd_help(message): text = [ 'Я - бот, который считает карму в чатах Telegram', ...
settings') def query_settings(callbackquery): try: key, data = parse_inline_data(callbackquery.data) dialog = get_dialog_object(callbackquery.from_user.id) if data[0] == 'locale': if len(data) == 2:
dialog.locale = data[1] dialog.save() bot.edit_message_text(_('settings updated. new locale is {locale}', locale=dialog.locale).format( locale=get_locale(data[1]).get_short_name() or data[1]), callbackquery.message.chat.id, ...
isdal/raspberrypi-fan-controller
fancontroller/__init__.py
Python
apache-2.0
103
0.009709
from
fancontroller.fan_controller import Thermostat, STATE_ON, STATE_OFF Thermostat STATE_
ON STATE_OFF
joelstanner/django-imager
imager/imager/tests_selenium.py
Python
mit
2,730
0.000366
from __future__ import print_function from django.test import LiveServerTestCase from selenium import webdriver import os from django.contrib.auth.models import User import factory SCREEN_DUMP_LOCATION = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'screendumps' ) class UserFactory(factory.djang...
_by_id("id_username") username_field.send_keys("Bob") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("password") form.submit() self.assertIn('Bob', self.driver.page_source) self.assertIn('Library', self.driver.page_source) ...
hly satisfied user. self.driver.find_element_by_link_text("Log out").click() self.assertIn('Logged out', self.driver.page_source) # except Exception as e: # self.driver.save_screenshot('SCREEN_DUMP_LOCATION.png') # raise e def test_login_unauthorized_user(self): ...
4ON91/KnickKnacks
Linux/Python/Math Notes/Basic Square Root Algorithm.py
Python
mit
810
0.01358
#https://youtu.be/rAuoJCiPiGU #based on this youtube video on how to do square roots without a calculator #Only works with integer values def SquareRootAlgorith
m(VARIABLE): for i in range(0, VARIABLE+1): if( pow(i,2) >= VARIABLE): MULTIPLE = i-1 PROBLEM = VARIABLE-pow(i-1,2) FINAL_ANSWER = MULTIPLE break for i in range(1, 100): PROBLEM = PROBLEM*100 MULTIPLE = (MULTIPLE+(MULTIPLE%10))*10 f...
PROBLEM = PROBLEM - (MULTIPLE+(x-1))*(x-1) MULTIPLE = (MULTIPLE+(x-1)) FINAL_ANSWER = FINAL_ANSWER + ((x-1) * pow(10,-i)) break return(FINAL_ANSWER) print(SquareRootAlgorithm(2)) #1.414213562373
codetiger/MachineLearning-2048
trainES.py
Python
mit
3,924
0.024465
import numpy as np import gym import random import time from keras.models import Sequential, Model, Input from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import EpsGreedyQPolicy, BoltzmannQPolicy, LinearAnnealedPolicy from rl.memo...
LEARNING_RATE = 0.01 INITIAL_EXPLORATION = 1.0 FINAL_EXPLORATION = 0.01 EXPLORATION_DEC_STEPS = 50000 plotScores = [] plotEpisodes = [] plotMaxTiles = [] plotEpiCounter = 0 GRID_SIZE = 3 action_space = [0, 1, 2, 3] def __init__(self): random.seed(int(time.time())) np.random.seed(int(time.time())) ...
ctions = 4 self.env = GameLogic(size = self.GRID_SIZE) # input_layer = Input(shape=(1, self.GRID_SIZE * self.GRID_SIZE)) # layer = Dense(8)(input_layer) # output_layer = Dense(3)(layer) # self.model = Model(input_layer, output_layer) # self.model.compile(Adam(), 'mse') self.model = Sequential() s...
bharathdintakurti/Natural-Language-Processing
Training/Unigram/tenfold.py
Python
apache-2.0
1,939
0.04229
from unigram import multinomial_naive_bayes import stopwords import math import os def tenfold(data): accuracy = [] train = open(data, "r") training = [] for line in train : training.append(line) num_folds = 10 subset_size = int(len(training)/(num_folds*2)) for i in range(10): testing_this_round = trai...
" + word) testingwrite.write("\n") for k in range(len(training_this_round)): train = training_this_round[k].split()
for word in train : if word == '+' : trainingwrite.write(word) FLAG = 1 continue if word == '-' : trainingwrite.write(word) FLAG = 0 continue if FLAG == 1 : trainingwrite.write(" " + word) else : trainingwrite.write(" " + word) trainingwrite.write("\n") ...
kyvinh/home-assistant
tests/components/cover/test_rfxtrx.py
Python
apache-2.0
9,040
0
"""The tests for the Rfxtrx cover platform.""" import unittest import pytest from homeassistant.bootstrap import setup_component from homeassistant.components import rfxtrx as rfxtrx_core from t
ests.common import get_test_home_assistant @pytest.mark.skipif("os.
environ.get('RFXTRX') != 'RUN'") class TestCoverRfxtrx(unittest.TestCase): """Test the Rfxtrx cover platform.""" def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.components = set(['rfxtrx']) def tearDown(se...
bjaraujo/bombermaaan
openai-gym/gym-bombermaaan/bombermaaan.py
Python
gpl-3.0
12,907
0.002712
import os import time import argparse import atexit import gym import gym_bombermaaan import numpy as np import random import utils from pathlib import Path import pickle from DQAgent import DQAgent from evaluation import evaluate from Logger import Logger import pygame def exit_handler(): global DQA DQA.quit(...
QA.DQN_target.model.load_weights(model_file) DQA.experiences = experiences DQA.training_count = training_count if args.video: pygame.init() surface= pygame.display.set_mode((IMG_SIZE[0], IMG_SIZE[1])) pygame.display.set_caption('Image') if args.train: # Main loop while epis
ode < args.max_episodes: # Start episode logger.log("Episode %d" % episode) score = 0 # Observe reward and initialize first state obs = utils.preprocess_observation(env.reset()) # Initialize the first state with the same 4 images current_state = np.array([obs, o...
Strawhatfy/totoro
setup.py
Python
apache-2.0
4,676
0
# -*- coding: utf-8 -*- import sys import warnings try: # Use setuptools if available, for install_requires (among other things). import setuptools from setuptools import setup except ImportError: setuptools = None from distutils.core import setup # The following code is copied from # https://git...
# 2.6's distutils.msvc9compiler can raise an IOError when failing to # find the compiler build_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError, IOError) else: build_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) class custom_build_ext(buil...
ng, but is not essential. """ warning_message = """ ******************************************************************** WARNING: %s could not be compiled. No C extensions are essential for Tornado to run, although they do result in significant speed improvements for websockets. %s Here are some hints for pop...
171121130/SWI
venv/Lib/site-packages/openpyxl/packaging/relationship.py
Python
mit
3,533
0.00283
from __future__ import absolute_import # Copyright (c) 2010-2017 openpyxl import posixpath from openpyxl.descriptors import ( String, Set, NoneSet, Alias, Sequence, ) from openpyxl.descriptors.serialisable import Serialisable from openpyxl.xml.constants import REL_NS, PKG_REL_NS from openpyxl.xml...
self.Type = Type self.Target = Target self.TargetMode = TargetMode self.Id = Id class RelationshipList(Serialisable): tagname = "Relationships" Relationship = Sequence(expected_type=Relationship) def __init__(self, Relationship=()): self.Relationship = Relationship ...
.append(value) if not value.Id: value.Id = "rId{0}".format((len(values))) self.Relationship = values def __len__(self): return len(self.Relationship) def __bool__(self): return bool(self.Relationship) def find(self, content_type): """ Find re...
Azure/azure-sdk-for-python
sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/__init__.py
Python
mit
1,545
0.001294
# 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 Micros
oft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ----------
---------------------------------------------------------------- try: from ._models_py3 import Error from ._models_py3 import Key from ._models_py3 import KeyListResult from ._models_py3 import KeyValue from ._models_py3 import KeyValueListResult from ._models_py3 import Label from ._models...
rhokhh/starthilfe
starthilfe/wsgi.py
Python
mit
397
0
""" WSGI config for starthilfe 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.9/howto/deplo
yment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "starthilfe.settings") application = get_wsgi_application()
rabarona/incubator-spot
spot-ingest/pipelines/flow/collector.py
Python
apache-2.0
4,907
0.013043
#!/bin/env python # # 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 "Licens...
ers to process the file. logger.info("Sending file to worker number: {0}".format(partition)) KafkaTopic.SendMessage(hdfs_file,kafka_servers,topic,partition) logger.info("File {0} has been successfully sent to Kafka Top
ic to: {1}".format(file,topic)) except Exception as err: logger.error("There was a problem, please check the following error message:{0}".format(err.message)) logger.error("Exception: {0}".format(err))
gattazr/cohorte-platforms
repo/debug/api.py
Python
apache-2.0
19,258
0.007322
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Cohorte Debug REST API :authors: Bassem Debbabi :copyright: Copyright 2015, isandlaTech :license: Apache Software License 2.0 """ # iPOPO decorators from pelix.ipopo.decorators import ComponentFactory, Provides, Property, Instantiate, \ Validate, Invalidate, ...
for p in self._directory.get_peers(): out_data["isolates"].append({"uid": p.uid, "name": p.name, "node_uid": p.node_uid, "
node_name": p.node_name}) count += 1 out_data["meta"]["count"] = count def get_isolate(self, request, response, in_data, out_data, uuid): out_data["isolate"] = self._get_isolate_detail(uuid) def get_isolate_bundles(self, request, response, in_data, out_data, uuid):...
mancoast/CPythonPyc_test
fail/314_test_smtpnet.py
Python
gpl-3.0
806
0.003722
#!/usr/bin/env python import unittest from test import support import smtplib support.requires("network") class SmtpSSLTest(unittest.TestCase): testServer = 'smtp.gmail.com' remotePort = 465 def test_connect(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_interne...
elf.remotePort) server.ehlo() server.quit() def test_connect_default_port(self): support.get_attribute(smtplib, 'SMTP_SSL') with support.transient_internet(self.testServer): server = smtplib.SMTP_SSL(self.testServer) server.ehlo() server.quit() def test_...
test_main()
IntroSDE/introsde
projects/tutorial_django_rest_framework_2017/djangorest/manage.py
Python
gpl-3.0
808
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangorest.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that t...
issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you
sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
alex/sqlalchemy
test/aaa_profiling/test_orm.py
Python
mit
9,335
0.00632
from sqlalchemy.testing import eq_, assert_raises, \ assert_raises_message from sqlalchemy import exc as sa_exc, util, Integer, String, ForeignKey from sqlalchemy.orm import exc as orm_exc, mapper, relationship, \ sessionmaker, Session, defer from sqlalchemy import testing from sqlalchemy.testing import profili...
elf.classes.Parent sess = sessionmaker()() sess2 = sessionmaker()() p1 = sess.query(Parent).get(1) p1.children # down from 185 on this this is a small slice of a usually # bigger operation so using a small variance
@profiling.function_call_count(variance=0.10) def go1(): return sess2.merge(p1, load=False) p2 = go1() # third call, merge object already present. almost no calls. @profiling.function_call_count(variance=0.10) def go2(): return sess2.merge(p2, lo...
disqus/django-old
tests/regressiontests/defer_regress/tests.py
Python
bsd-3-clause
6,716
0.001191
from operator import attrgetter from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.backends.db import SessionStore from django.db.models import Count from django.db.models.loading import cache from django.test import TestCase from models import (ResolveThis, Item, RelatedItem, Chi...
e" or "text" should. def test(): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) self.assertNumQueries(0, test) def test(): self.assertEqual(obj.value, 42) self.assertNumQueries(1, test) def test():
self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(1, test) def test(): self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(0, test) # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred...
zonca/pycfitsio
pycfitsio/healpix.py
Python
gpl-3.0
1,092
0.007326
import numpy as np import exceptions import healpy from file import read def read_map(filename, HDU=0, field=0, nest=False): """Read Healpix map all columns of the specified HDU are read into a compound numpy MASKED array if nest is not None, the map is converted if need to NEST or RING ordering. thi...
(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] return healpy.ma(m) def read_mask(filename, HDU=0, field=0, nest=False): m = read_map(filename, HDU, field, nest) return np.logical_not(m.filled()).astype
(np.bool)
Plasticoo/Pass_Shelter3
src/encryption/aes_encryption.py
Python
mit
936
0.016026
# noinspection PyPackageRequirements from Crypto.Cipher import AES import base64 #AES256 BLOCK_SIZE = 32 PADDI
NG = '{' DECRYPTION_CHECK = "|PASSMON|" def aes_encrypt(word, key): """Encrypts password""" pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING encode_aes = lambda c, s: base64.b64encode(c.encrypt(pad(s))) cipher = AES.new(key) encoded = encode_aes(cipher, DECRYPTION_CHECK + str(word)) return encode...
cipher = AES.new(key) decoded = decode_aes(cipher, encrypted_string) if decoded[0:int(len(DECRYPTION_CHECK))] == DECRYPTION_CHECK: return decoded[len(DECRYPTION_CHECK):len(decoded)] else: return "Wrong Cipher" except: return "Cipher needs to be 32 byt...
RoPython/jarvis
jarvis/worker/client.py
Python
mit
46
0
"""
client: basic interaction with a daemon"""
sirchristian/v8DOM.NET
v8-read-only/test/test262/testcfg.py
Python
mit
3,870
0.005943
# Copyrig
ht 2011 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, t
his list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Goog...
mencattini/ideal-pancake
adt/tests/prog_test.py
Python
apache-2.0
4,066
0.003443
from adt.util.prog import Prog from adt.util.literal import Literal from adt.util.expr import Expr from adt.util.unary_op import Unary_op from adt.util.binary_op import Binary_op from adt.util.block import Block from adt.util.context import Context from adt.util.instr import Instr from adt.types.bool import Bool from ...
), expr2=Expr.expr_lit(lit_true)) assert Prog.eval_expr(expr=expr1, context=context) == lit_true assert Prog.eval_expr(expr=expr2, context=context) == lit_false assert Prog.eval_expr(expr=expr2, context=context) != lit_true # or op = Binary_op.o_or()
expr1 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_false)) expr2 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_true)) assert Prog.eval_expr(expr=expr1, context=context) == lit_false assert Prog.eval_expr(expr=expr2, context=context)...
tensorflow/quantum
tensorflow_quantum/core/ops/tfq_utility_ops.py
Python
apache-2.0
5,600
0.000358
# Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
mbol_names, tf.cast(symbol_values,
tf.float32))
EDRN/labcas-backend
common/src/main/python/gov/nasa/jpl/edrn/labcas/preprocess/dicom_make_dir_structure.py
Python
apache-2.0
1,269
0.019701
import os import sys from glob import glob import dicom # collection root directory: collection_dir = '/usr/local/labcas/backend/staging/CBIS-DDSM/' # dataset directory dataset = sys.argv[1] dataset_dir = '%s/%s' % (collection_dir, dataset) # dataset version directory version_dir = '%s/1' % dataset_dir if not os.pat...
try: ds = dicom.read_file(f) tag_names = ds.dir() #for tag_name in tag_names: # data_element = ds.data_element(tag_name) #print data_element # if tag_name != 'PixelData': # print 'key=%s --> value=%s' % (tag_name, data_element.value) fid = ds.SOP...
'\nMoving DICOM file=%s --> %s' % (src_path, dst_path) if not os.path.exists(dst_path): os.rename(src_path, dst_path) except Exception as e: print 'Error while processing file: %s' % src_path print e
cg31/tensorflow
tensorflow/contrib/metrics/python/ops/metric_ops.py
Python
apache-2.0
141,058
0.003736
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
m tensorflow.contrib.framework import tensor_util fro
m tensorflow.contrib.framework.python.ops import variables as contrib_variables from tensorflow.contrib.metrics.python.ops import confusion_matrix_ops from tensorflow.contrib.metrics.python.ops import set_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.pyth...
yujikato/DIRAC
src/DIRAC/Interfaces/scripts/dirac_admin_site_info.py
Python
gpl-3.0
1,467
0.008862
#!/usr/bin/env python ######################################################################## # File : dirac-admin-site-info # Author : Stuart Paterson ######################################################################## """ Print Configuration information for a given Site Usage: dirac-admin-site-info [opti...
ipt from DIRAC.Core.Utilities.DIRACScript import DIRACScript @DIRACScript() def main(): Script.parseCommandLine(ignoreErrors=True) args = Script.getPositionalArgs() if len(args) < 1: Script.showHelp() from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin diracAdmin = DiracAdmin() exitCode = 0 err...
result = diracAdmin.getSiteSection(site, printOutput=True) if not result['OK']: errorList.append((site, result['Message'])) exitCode = 2 for error in errorList: print("ERROR %s: %s" % error) DIRAC.exit(exitCode) if __name__ == "__main__": main()
uwgraphics/SerendipSlim
TextViewer.py
Python
bsd-2-clause
1,527
0.004584
# coding=utf-8 __author__ = 'ealexand' import os import csv import zipfile from flask import render_template, request, Response, current_app, url_for, redirect, jsonify, json import Utilities as util def get_tokens_fromCSV(model_name, text_name): html_root = os.path.join(util.get_model_root(model_name), 'HTML') ...
'), 'rb') as csvF: reader = csv.reader(csvF) return [row for row in reader] else: return def get_tokens_json(model_name, text_name): tokens = get_tokens_fromCSV(model_name, text_name)
jTokens = jsonify({'tokens': tokens}) return jTokens def view_by_name(model_name, text_name): tokenList = get_tokens_fromCSV(model_name, text_name) return render_template( "slimTV.html", model_name=model_name, text_name=text_name, tokens=tokenList ) def single_view_by_n...
gimli-org/gimli
pygimli/core/config.py
Python
apache-2.0
2,719
0.001471
"""Management of pygimli user configuration file.""" import json import os import sys from .logger import info # pyGIMLi default configuration rc = { 'lang': 'eng', # 'eng', 'german', 'de', 'ger' 'unitStyle': 2, # 1: german style: 'value in unit' # 2: default style: 'value (unit)' 'view3D': 'auto...
_CONFIG_HOME', os.path.expanduser("~/.config"))
return os.path.join(path, appname) __configpath = getConfigPath() __configfile = os.path.join(__configpath, "config.json") if os.path.isfile(__configfile): # info("Loading user configuration file at " + __configfile) with open(__configfile) as cfg: userrc = json.load(cfg) # Check if user confi...
chubbymaggie/simuvex
simuvex/procedures/stubs/UserHook.py
Python
bsd-2-clause
527
0.00759
import simuvex class UserHook(simuvex.SimProcedure): NO_RET = True # pylint: disable=arguments-differ def run(self, user_func=None, user_kwargs=None, default_return_add
r=None, length=None): result = user_func(self.state, **user_kwargs) if result is None: self.add_successor(self.state, default_return_addr, self.state.se.true, 'Ijk_NoHook') else:
for state in result: self.add_successor(state, state.ip, state.scratch.guard, state.scratch.jumpkind)
myvoice-nigeria/myvoice
myvoice/survey/tests/test_utils.py
Python
bsd-2-clause
7,181
0.002089
from django.test import TestCase from django.utils import timezone from .. import utils from .. import models as survey_models from myvoice.core.tests import factories from operator import itemgetter class TestDisplayFeedback(T
estCase): def test_false(self): bad_feedback = [None, '', ' ', ' 1', '1', 'yes', 'Yes', 'YES', 'no', 'No', 'NO', '55999', 'n0', 'start', 'Start'] for bad in bad_feedback: self.assertEqual(utils.display_feedback(bad), False) def test_true(self): go...
elf.assertEqual(utils.display_feedback(good), True) class TestSurveyUtils(TestCase): def setUp(self): self.survey = factories.Survey.create() self.question = factories.SurveyQuestion.create(survey=self.survey, label='Test') self.responses = [factories.SurveyQuestionResponse.create( ...
laborautonomo/Mailpile
mailpile/mail_source/__init__.py
Python
apache-2.0
32,212
0.000186
import os import random import re import thread import threading import traceback import time import mailpile.util from mailpile.eventlog import Event from mailpile.i18n import gettext as _ from mailpile.i18n import ngettext as _n from mailpile.mailboxes import * from mailpile.mailutils import FormatMbxId from mailpil...
# OK, everything looks complete, mark it! if complete: self._mark_mailbox_rescanned(mbx_cfg, state) else: self._last_rescan_completed = False
else: self._last_rescan_failed = True self._last_rescan_completed = False
jkramarz/zuombot
cloudbot/event.py
Python
gpl-3.0
15,299
0.003791
import asyncio import enum import logging import concurrent.futures logger = logging.getLogger("cloudbot") @enum.unique class EventType(enum.Enum): message = 0 action = 1 # TODO: Do we actually want to have a 'notice' event type? Should the NOTICE command be a 'message' type? notice = 2 join = 3 ...
database object on this event, if
the hook requires it. This method is for when the hook is threaded (event.hook.threaded is True). If you need to add a db to a coroutine hook, use prepare. """ if self.hook is None: raise ValueError("event.hook is required to prepare an event") if "db" in self.hoo...
frishberg/django
tests/m2m_through_regress/tests.py
Python
bsd-3-clause
10,478
0.002004
from __future__ import unicode_literals from django.contrib.auth.models import User from django.core import management from django.test import TestCase from django.utils.six import StringIO from .models import ( Car, CarDriver, Driver, Group, Membership, Person, UserMembership, ) class M2MThroughTestCase(TestCa...
ip__price=50), [ "<Person: Jim>", ] ) def test_join_trimming_reverse(self): sel
f.assertQuerysetEqual( self.bob.group_set.filter(membership__price=50), [ "<Group: Roll>", ] ) class M2MThroughSerializationTestCase(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name="Bob") cls.roll = Group.obje...
thinkWhere/Roadnet
tests/integration/test_wdm.py
Python
gpl-2.0
8,439
0.002607
# -*- coding: utf-8 -*- from mock import patch import os import pprint import shutil import subprocess import unittest from pyspatialite import dbapi2 as db import qgis.core # Need to import this before PyQt to ensure QGIS parts work from PyQt4.QtSql import QSqlQuery, QSqlDatabase from Roadnet.database import conne...
, NULL, NULL, NULL, NULL, NULL, 'F-5470', 50, 'Test MCL Two', NULL, 30, 'U', 'FT', 'Public', 22222, 'U', NULL, NULL, GeomFromText("MULTILINESTRING((2
93166.277 680074.52,293180.28 680074.606,293181.610 680074.83))", 27700) ); INSERT INTO mcl VALUES ( 3, 18163, NULL, 14305470, NULL, NULL, NULL, 'Grangemouth', NULL, NULL, NULL, NULL, NULL, 'F-5470', 40, 'Test MCL Three', NULL, 30, 'U', 'FT', 'Public', 33333, 'U', NULL, NULL, GeomFromText("MULTILINESTRING((293141.89199...
ddanier/django_internal_urls
django_internal_urls/autoload.py
Python
bsd-3-clause
393
0.005089
from django.conf
import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: if '.' not in app: continue mod = import_module(app) try: import_module('%s.internal_urls' % app) except: if module...
raise