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
auto-mat/stupneprovozu
tsk/models.py
Python
gpl-3.0
790
0.006345
# -*- coding: utf-8 -*- from django.db import models class SkupinaLokaci(models.Model): name = models.CharField(max_length=255) lokace = models.ManyToManyField("Lokace") class Lokace(models.Model): name = models.CharField(max_length=255) favourite = models.BooleanField(verbose_name="Oblíbená", defau...
class Meta: ordering = ['name'] def __unicode__(self): return self.name class Provoz(models.Model): ident = models.CharField(max_length=255) level = models.IntegerField() location = models.ForeignKey(Lokace)
level = models.IntegerField() time_generated = models.DateTimeField() time_start = models.DateTimeField() time_stop = models.DateTimeField() class Meta: ordering = ['time_generated']
siconos/siconos
io/swig/tests/test_native_collision.py
Python
apache-2.0
6,228
0.000803
#!/usr/bin/env python # # A circle with two disks inside under earth gravity # from siconos.mechanics.collision.tools import Contactor from siconos.io.mechanics_run import MechanicsHdf5Runner import siconos.numerics as sn import siconos.kernel as sk import siconos import numpy from math import sqrt siconos.io.mec...
# is between contactors of group id 0. io.add_Newton_impact_friction_nsl('contact', mu=0.3, e=0)
# The disk object made with an unique Contactor : the Disk shape. # As a mass is given, it is a dynamic system involved in contact # detection and in the simulation. With no group id specified the # Contactor belongs to group 0 io.add_object('disk0', [Contactor('DiskR')], ...
anu-ka/coding-problems
Python/to_lower.py
Python
mit
660
0.001515
# Implement function ToLowerCase() that has a string parameter str, an
d returns the same string in lowercase. # https://leetcode.com/problems/to-lower-case/ import pytest class Solution: def toLowerCase(self, str: str) -> str: lower = "" for i in str: ordVal = ord(i) if ordVal >= 65 and ordVal <= 90: lower += chr(or
dVal + 32) else: lower += i return lower @pytest.mark.parametrize( ("str", "expected"), [("aAbB", "aabb"), ("aabb", "aabb"), ("a1@B", "a1@b")] ) def test_basic(str: str, expected: str): assert expected == Solution().toLowerCase(str)
aspose-total/Aspose.Total-for-Cloud
Examples/Python/files/DownloadAParticularFileExample.py
Python
mit
895
0.012291
import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi from asposestoragecloud.ApiClient import ApiException from asposestoragecloud.models import FileExistResponse apiKey = "b125f13bf6b76ed81e
e990142d841195" # sepcify App Key appSid = "78946fb4-3bd4-4d3e-b309-f9e2ff9ac6f9" # sepcify App SID apiServer = "http://api.aspose.com/v1.1" data_folder = "../../data/"
try: # Instantiate Aspose Storage API SDK storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) storageApi = StorageApi(storage_apiClient) # upload file to aspose cloud storage response = storageApi.GetDownload("tester/test.pdf") if response.Status == "OK...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/elastic_demo.py
Python
apache-2.0
927
0.004315
# Copyright (c) 2021 PaddlePaddle A
uthors. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and #...
sajeeshcs/nested_projects_keystone
keystone/common/base64utils.py
Python
apache-2.0
13,107
0.000076
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
WARNING:: base64url continues to use the '=' pad character which is NOT URL safe. RFC-4648 suggests two alternate methods to deal with this: percent-encode percent-encode the pad character (e.g. '=' becomes '%3D'). This makes the base64url text fully safe. But ...
l text into a base64url decoder since most base64url decoders do not recognize %3D as a pad character and most decoders require correct padding. no-padding padding is not strictly necessary to decode base64 or base64url text, the pad can be computed f...
blaze/dask
dask/dataframe/io/io.py
Python
bsd-3-clause
22,680
0.000617
import os from math import ceil from operator import getitem from threading import Lock import numpy as np import pandas as pd from tlz import merge from ... import array as da from ...base import tokenize from ...dataframe.core import new_dd_object from ...delayed import delayed from ...highlevelgraph import HighLev...
ut index is monotonically-increasing. The ``sort=False`` option will also avoid reordering, but will not result in known divisions. Note that, despite parallelism, Dask.dataframe may not always be faster than Pandas. We recommend that you stay with Pandas for as long as possible before switching
to Dask.dataframe. Parameters ---------- data : pandas.DataFrame or pandas.Series The DataFrame/Series with which to construct a Dask DataFrame/Series npartitions : int, optional The number of partitions of the index to create. Note that depending on the size and index of the da...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/aio/operations/_load_balancer_network_interfaces_operations.py
Python
mit
5,642
0.004254
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
n [200]: map_error(status_code=response.status_code,
response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/...
YiqunPeng/Leetcode-pyq
solutions/353DesignSnakeGame.py
Python
gpl-3.0
2,009
0.008462
class SnakeGame: def __init__(self, width, height, food): """ Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1],...
on][0] n_y = head[1] + directions[direction][1] if not (0 <= n_x < self.h and 0 <= n_y < self.w): self.game_state = False return -1 if (n_x, n_y) != self.snake[-1] and (n_x, n_y) in self.snake_set: self.game_state = False
return -1 if self.idx < len(self.food) and self.food[self.idx] == [n_x, n_y]: self.idx += 1 else: self.snake_set.remove(self.snake[-1]) self.snake.pop() self.snake.appendleft((n_x, n_y)) self.snake_set.add((n_x, n_y)) ...
ArnaudBelcour/liasis
pbsea/pbsea.py
Python
gpl-3.0
28,386
0.004791
#!/usr/bin/env python3 import logging import csv import math import numpy as np import os import pandas as pa import scipy.stats as stats import six from statsmodels.sandbox.stats.multicomp import multipletests logging.basicConfig(filename='analysis.log', level=logging.DEBUG) logger = logging.getLogger(__name__) c...
-number of analyzed object of interest : the number of objects in your sample (for example the number of differentially expressed genes in a list). -num
ber of analyzed object of reference : the number of objects in your population (for example the number of genes in the genome of your species). -alpha : the alpha threshold also known as type I error. -normal approximation threshold : the threshold separating the hypergeometric test...
dontnod/weblate
weblate/trans/views/files.py
Python
gpl-3.0
5,817
0.000516
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
ed: {1}, no
t found: {2}, updated: {3}).', 'Processed {0} strings from the uploaded files ' '(skipped: {1}, not found: {2}, updated: {3}).', total ).format(total, skipped, not_found, accepted) if accepted == 0: messages.warning(request, message) ...
schwehr/gdal-autotest2
python/alg/tps_test.py
Python
apache-2.0
3,423
0.004382
# Copyright 2016 Google Inc. 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 a...
notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF O...
bitmazk/cmsplugin-blog-language-publish
cmsplugin_blog_language_publish/tests/south_settings.py
Python
mit
599
0
""" These setting
s are used by the ``manage.py`` command. With normal tests we want to use the fastest possible way which is an in-memory sqlite database bu
t if you want to create South migrations you need a persistant database. Unfortunately there seems to be an issue with either South or syncdb so that defining two routers ("default" and "south") does not work. """ from cmsplugin_blog_language_publish.tests.test_settings import * # NOQA DATABASES = { 'default':...
ywcui1990/nupic
examples/opf/experiments/classification/category_hub_TP_0/description.py
Python
agpl-3.0
1,688
0.005332
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # -----------------------------------------...
-------------- ## This file defines parameters for a prediction experiment. import os from nupic.frameworks.opf.exp_description_helpers import importBaseDescription # the sub-experiment configuration config = \ { 'claEvalClassification': True, 'dataSource': 'file://' + os.path.join(os.path.dirname(__file__), ...
idealabasu/code_pynamics
python/pynamics_examples/triple_pendulum_maximal.py
Python
mit
10,420
0.039923
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes Email: danaukes<at>gmail.com Please see LICENSE for full license. """ import pynamics from pynamics.frame import Frame from pynamics.variable_types import Differentiable,Constant from pynamics.system import System from pynamics.body import Body from pynamics.dyadi...
scalar.append(eq_dd[ii+1].dot(B2.z)) eq_dd_scalar.append(eq_dd[ii+2].dot(C2.x)) eq_dd_scalar.append(eq_dd[ii+2].dot(C2.y)) eq_dd_scalar.append(eq_dd[ii+2].dot(C2.z)) system.add_constraint(AccelerationConstraint(eq_dd_scalar)) eq_d_scalar = [] eq_d_scalar.append(eq_d[0].dot(N.x)) eq_d_scalar.appe...
q_d[1].dot(N.y)) eq_d_scalar.append(eq_d[1].dot(N.z)) eq_d_scalar.append(eq_d[2].dot(N.x)) eq_d_scalar.append(eq_d[2].dot(N.y)) eq_d_scalar.append(eq_d[3].dot(N.x)) eq_d_scalar.append(eq_d[3].dot(N.y)) eq_d_scalar.append(eq_d[3].dot(N.z)) ii=4 if constrain_base: eq_d_scalar.append(eq_d[4].dot(N.x)) eq_d_scalar....
kerneltask/micropython
tests/basics/bytearray_construct_array.py
Python
mit
314
0
# test construction of bytearray from different objects try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit # array
s print(bytearray(array('b', [1, 2]))) print(bytearray(array('h',
[0x101, 0x202])))
hexpl0it/plugin.video.genesi-ita
resources/lib/resolvers/mrfile.py
Python
gpl-3.0
1,517
0.009888
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda 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 opt...
ld have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib from resources.lib.libraries import client def resolve(url): try: result = client.request(url) pos
t = {} f = client.parseDOM(result, 'Form', attrs = {'name': 'F1'})[-1] k = client.parseDOM(f, 'input', ret='name', attrs = {'type': 'hidden'}) for i in k: post.update({i: client.parseDOM(f, 'input', ret='value', attrs = {'name': i})[0]}) post.update({'method_free': '', 'method_premiu...
rbbratta/virt-test
virttest/utils_libguestfs.py
Python
gpl-2.0
5,627
0.000711
""" libguestfs tools test utility functions. """ import logging from autotest.client import os_dep, utils from autotest.client.shared import error import propcan class LibguestfsCmdError(Exception): """ Error of libguestfs-tool command. """ def __init__(self, details=''): self.details = det...
_status = dargs.get('ignore_status', True) debug = dargs.get('debug',
False) timeout = dargs.get('timeout', 60) if debug: logging.debug("Running command %s in debug mode.", cmd) # Raise exception if ignore_status == False try: ret = utils.run(cmd, ignore_status=ignore_status, verbose=debug, timeout=timeout) except error.CmdErr...
openhatch/oh-mainline
vendor/packages/docutils/test/test_parsers/test_rst/test_paragraphs.py
Python
agpl-3.0
1,329
0.009029
#! /usr/bin/env python # $Id: test_paragraphs.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSu...
", """\ <document source="test data"> <paragraph> A. Einstein was a really smart dude. """], ] if __name__ == '__main__': import un
ittest unittest.main(defaultTest='suite')
divergentdave/inspectors-general
inspectors/sigar.py
Python
cc0-1.0
5,811
0.008092
#!/usr/bin/env python import datetime import logging import os from urllib.parse import urljoin from utils import utils, inspector # https://www
.sigar.mil/ archive = 2008 # options: # standard since/year options for a year range to fetch from. # # Notes for IG's web team: # SPOTLIGHT_REPORTS_URL = "https://www.sigar.mil/Newsroom/spotlight/spotlight.xml" SPEECHES_REPORTS_URL = "https://www.sigar.mil/Newsroom/speeches/speeches.xml" TESTIMONY_REPORTS_URL = "h...
.mil/Newsroom/testimony/testimony.xml" PRESS_RELEASES_URL = "https://www.sigar.mil/Newsroom/pressreleases/press-releases.xml" REPORT_URLS = [ ("other", SPOTLIGHT_REPORTS_URL), ("press", SPEECHES_REPORTS_URL), ("testimony", TESTIMONY_REPORTS_URL), ("press", PRESS_RELEASES_URL), ("audit", "https://www.sigar.mi...
defm03/toraeru
test/loli_GUI.py
Python
gpl-3.0
1,353
0.011086
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.image i
mport Image from kivy.uix.button import Button kivy.require('1.7.3') text ="" class ShowLogo(Image): def __init__(self,**kwargs): super(Image, self).__init__(**kwargs) class GetInfo(GridLayout): def __init__(self,**kwargs): super(GetInfo, self).__init__(**kwargs) self.cols = 2 ...
limit')) self.limit = TextInput(text="100",multiline=False) self.add_widget(self.limit) def on_text(instance,value): print('widget: ',instance,' - val: ',value) def on_enter(instance,value): print('user pressed enter in: ',instance) if self.limit.bind(...
macknowak/simtools
simtools/tests/test_base.py
Python
gpl-3.0
1,438
0.00765
# -*- coding: utf-8 -*- """Unit tests of assorted base data structures and common functions.""" import pytest from simtools.base import Dict, is_iterable, is_string def test_is_iterable(): # List of integers obj = [1, 2, 3] assert is_iterable(obj) == True # Tuple of integers obj = 1, 2, 3 a...
t.raises(AttributeError): d.
c def test_dict_attr_deletion(): d = Dict() d['a'] = 1 del d.a with pytest.raises(KeyError): d['a'] with pytest.raises(AttributeError): d.a
poppogbr/genropy
gnrpy/gnr/web/gnrwebstruct.py
Python
lgpl-2.1
85,061
0.008911
#-*- coding: UTF-8 -*- #-------------------------------------------------------------------------- # package : GenroPy web - see LICENSE for details # module gnrsqlclass : Genro Web structures implementation # Copyright (c) : 2004 - 2007 Softwell sas - Milano # Written by : Giovanni Porcari, Michele Bertoldi...
def foo(self, bc, ...): pass def somewhereElse(self, bc): bc.bar(...) """ def
register(name, func): func_name = func.__name__ existing_name = GnrDomSrc._external_methods.get(name, None) if existing_name and (existing_name != func_name): # If you want to override a struct_method, be sure to call its implementation method in the same way as the original. ...
PinguinoIDE/pinguino-ide
cmd/pinguino-reset.py
Python
gpl-2.0
59
0
#!/usr/bin/env python from pi
nguin
o import pinguino_reset
vileopratama/vitech
src/addons/event/wizard/event_confirm.py
Python
mit
441
0.002268
# -*- coding: utf-8 -*- # Part of
Odoo. See LICENSE file for full copyright and licensing details. from openerp import models, api class event_confirm(models.TransientModel): """Event Confirmation""" _name = "event.confirm" @api.multi def confirm(self): events = self.env['event.event'].br
owse(self._context.get('event_ids', [])) events.do_confirm() return {'type': 'ir.actions.act_window_close'}
manasgarg/qless-blinker-bridge
setup.py
Python
bsd-3-clause
429
0.065268
#!/usr/bin/env python from distutils.core import setup setup( name="qless_blinker", version = "0.1", d
escription = "A bridge between qless & blinker.", author = "Manas Garg", author_email = "[email protected]", license = "BSD License", url = "https://github.com/manasgarg/qless-blinker-bridge", #data_files = ["LICENSE", "Readme.md"], packages = ["qless_blinker"], long_description
= "" )
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/elan/Pools/Frank/2_speakercraft_lms.py
Python
gpl-3.0
1,883
0.013808
from ImageScripter import * from elan import * if Viewer.shudder.Exists() ==True: Viewer.shudder.Click() else: pass #Viewer.homeicon9.Click() #Viewer.homeicon9.Click() Viewer.media10items.Click() try: Viewer.audiogroup.Click() except Exception as e: print(e) if Viewer.irtester.Exists() == True: ...
break Viewer.pandoraicon.Click() Viewer.yourstations.Click() Viewer.dickdaleradio.Click() Viewer.bluearrow.Click(threshold = .92) Viewer.lmsback.Click() Viewer.lmsback.Click() Viewer.pandoradickdaleradio.Wait() Viewer.lmssettings.Click() Viewer.tidal.Click(xoffset=525,yoffset=0) Viewer.lmsback.Click() Viewer...
ffoff.ClickFast() Viewer.shudder.Click(threshold = .92) Viewer.homeicon9.Click(threshold = .92) Viewer.homeicon10items.Wait(seconds = 30) Viewer.homeicon10items.Click(threshold = .92) #Viewer.shudder.Click(threshold = .92) #Viewer.homeicon9.Click() #Viewer.homeicon9.Click()
matthiaskramm/corepy
corepy/arch/spu/platform/linux_spufs/spre_linux_spu.py
Python
bsd-3-clause
33,201
0.019698
# Copyright (c) 2006-2009 The Trustees of Indiana University. # All rights reserved. # # Redistribution and use in source and binary forms, with or without ...
# - Neither the Indiana University nor the names of its contributors may be used # to endorse or promote products derived from this software without specific # prior written permission. # ...
UT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCURE...
TravisFSmith/SweetSecurity
sweetSecurity/client/spoof.py
Python
apache-2.0
1,267
0.049724
import sqlite3 import logging from time import sleep logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * import sweet
SecurityDB dbPath="/opt/sweetsecurity/client/SweetSecurity.db" def convertMAC(mac): newMac="%s%s:%s%s:%s%s:%s%s:%s%s:%s%s" % (mac[0],mac[1],mac[2],mac[3],mac[4],mac[5],mac[6],mac[7],mac[8],mac[9],mac[10],mac[11]) return newMac def getMac(): myMac = [get_if_hwaddr(i) for i in get_if_list()] for mac in myMac: if(...
w=dfgwInfo['dfgw'] dfgwMAC=dfgwInfo['dfgwMAC'] dfgwMAC=convertMAC(dfgwMAC) conn = sqlite3.connect(dbPath) c = conn.cursor() for row in c.execute('SELECT * FROM hosts where active = 1 and ignore = 0'): logger.info("Spoofing Device: ip=%s, mac=%s",row[2],row[3]) #Spoof the things... victimMac=c...
EliotBerriot/savior
src/errors.py
Python
gpl-3.0
1,506
0.00664
# Copyright (C) 2013 Eliot Berriot <[email protected]> # # This file is part of savior. # # Savior is free software: you can redist
ribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at
your option) any later version. # # Savior is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Gen...
mayankjohri/LetsExplorePython
Section 2 - Advance Python/Chapter S2.11 Multiprocessing and Threading/code/4_threading.py
Python
gpl-3.0
651
0.013825
import threading import time def worker(): print (threading.currentThread().getName() + 'Starting') time.sleep(2) print (threading.currentThread().getName()+'Exiting') def
my_service(): print (threading.currentThread().getName()+ 'Starting') time.sleep(3) print (threading.currentThread().getName()+'Exiting') t = threading.Thread(name='my_service', target=my_service) w = threading.Th
read(name='worker bee', target=worker) w2 = threading.Thread(target=worker) # use default name w3 = threading.Thread(target=worker) # use default name w.start() w2.start() w3.start() t.start()
janies/dataleach
setup.py
Python
bsd-3-clause
868
0.021889
#!/usr/bin/env python from setuptools import setup, find_packages #try: # import setuptools_git #except ImportError: # print "WARNING!" # print "We need the setuptools-git package to be installed for" # print "some of the setup.py targets to work correctly." PACKAGE = 'dataleach' VERSION = '0.1' setup( ...
"requests", "feedparser",
"ijson", #"pysync", ], entry_points = {"console_scripts": ['leach = dataleach.leach:main']}, test_suite = "dataleach.tests", )
Shemahmforash/thisdayinmusic.net
thisdayinmusic/settings.py
Python
mit
4,625
0.00173
""" Django settings for thisdayinmusic project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ impo...
'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'thisdayinmusic.ur...
True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ...
F5Networks/f5-common-python
f5/bigip/tm/asm/policies/methods.py
Python
apache-2.0
1,405
0.001426
# coding=utf-8 # # Copyright 2017 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
lass Method(AsmResource): """BIG-IP® ASM Methods Resource.""" def __init__(self, methods_s): super(Method, self).__in
it__(methods_s) self._meta_data['required_json_kind'] = 'tm:asm:policies:methods:methodstate'
horizon-institute/chariot
hub/emonhub/src/emonhub_setup.py
Python
mit
4,819
0.005395
""" This code is released under the GNU Affero General Public License. OpenEnergyMonitor project: http://openenergymonitor.org """ import time import logging from configobj import ConfigObj """class EmonHubSetup User interface to setup the hub. The settings attribute stores the settings of the hub. It is...
'Type': class name 'init_settings': dictionary with initialization settings 'runtimesettings': dictionary with runtime settings Initialization and runtime settings depend on the interfacer and
reporter type. The run() method is supposed to be run regularly by the instantiater, to perform regular communication tasks. The check_settings() method is run regularly as well. It checks the settings and returns True is settings were changed. This almost empty class is meant to be inherited by subclasses ...
OCA/event
event_mail/models/event_mail.py
Python
agpl-3.0
1,566
0
# Copyright 2017 Tecnativa - Sergio Teruel <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class EventMailSchedulerTemplate(models.Model): _name = "event.mail.scheduler.template" _inherit = "event.mail" _description = "Even...
"interval_unit": "now", "interval_type": "after_sub",
"template_id": self.env.ref("event.event_subscription").id, }, { "notification_type": "mail", "interval_nbr": 10, "interval_unit": "days", "interval_type": "before_event", "template_id": self.env.ref("...
sarahn/ganeti
test/py/ganeti.utils.io_unittest.py
Python
gpl-2.0
36,321
0.00669
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2010, 2011 Google 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...
e, data=dummydata) datalax = utils.ReadOneLineFile(myfile, strict=False) self.assertEqual(myline, datalax) datastrict = utils.ReadOneLineFile(myfile, strict=True) self.assertEqual(myline, datastrict) def testWhitespaceAndMultipleLines(self): myfile = self._CreateTempFile() for nl in [...
, data=dummydata) datalax = utils.ReadOneLineFile(myfile, strict=False) if nl: self.assert_(set("\r\n") & set(dummydata)) self.assertRaises(errors.GenericError, utils.ReadOneLineFile, myfile, strict=True) explen = len("Foo bar baz ") + len(ws) ...
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_MovingAverage/cycle_12/ar_/test_artificial_1024_RelativeDifference_MovingAverage_12__0.py
Python
bsd-3-clause
278
0.082734
impo
rt pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "RelativeDifference", s
igma = 0.0, exog_count = 0, ar_order = 0);
WorldException/v7py
v7/utils.py
Python
gpl-2.0
3,168
0.004786
#!/usr/bin/env python # -*-coding:utf8-*- from __future__ import division import re import six from six.moves import reprlib re_unicode = re.compile(r'\\u[0-9a-f]{4}') def fixunicode(str, encoding=''): if six.PY2: newstr = str.decode('unicode_escape') if encoding: return newstr.decode...
= str(available_symbols[value % m]) value = int(value/m) else: result = '0' * value return result[::-1] def ID_36(value_10): if six.PY2: if type(value_10) is unicode: value_10 = str(value_10) else: value_10
= str(value_10) return '{:^9}'.format(convert_n_to_m2(value_10, 10, 36))
MithileshCParab/HackerRank-10DaysOfStatistics
Problem Solving/Data Structure/Trees/square-ten_three.py
Python
apache-2.0
69
0.014493
# Enter your code here. Read input
fr
om STDIN. Print output to STDOUT
antoinecarme/pyaf
tests/model_control/detailed/transf_Fisher/model_control_one_enabled_Fisher_Lag1Trend_Seasonal_MonthOfYear_LSTM.py
Python
bsd-3-clause
161
0.049689
import tests.model_control.test_ozone_custom_models_enabled as tes
tmod testmod.build_model( ['Fisher'] , ['Lag1Trend'] , ['Seasonal_MonthOfYear'] , ['LST
M'] );
Pitmairen/hamlish-jinja
tests/test_debug_output.py
Python
bsd-3-clause
3,732
0.002413
# -*- coding: utf-8 -*- import unittest from hamlish_jinja import Hamlish, Output import testing_base class TestDebugOutput(testing_base.TestCase): def setUp(self): self.hamlish = Hamlish( Output(indent_string=' ', newline_string='\n', debug=True)) def test_html_tags(self): ...
_empty_lines_bellow(self): s = self._h(''' %br %span << test''') r = ''' <br /> <span>test</span> ''' self.assertEqual(s, r) def test_nested_tags(self): s = self._h(''' %ul -for i in range(10): %li -> %a href="{{ i }}" << {{ i }} %span << test ''') ...
Equal(s, r) def test_nested_tags2(self): s = self._h(''' %ul -for i in range(10): %li -> %a href="{{ i }}" -> {{ i }} %span << test ''') r = ''' <ul> {% for i in range(10): %} <li><a href="{{ i }}">{{ i }}</a></li>{% endfor %} <span>test</span></ul> ''' self.asser...
madarche/jack
jack_m3u.py
Python
gpl-2.0
1,306
0
# jack_m3u: generate a m3u playl
ist - a module for # jack - tag audio from a CD and enc
ode it using 3rd party software # Copyright (C) 1999-2003 Arne Zellentin <[email protected]> # 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 opt...
civilian/competitive_programing
leetcode/0/88/best.py
Python
mit
1,092
0.003663
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ ''' for i in range(n): nums1[m + i] = nums2[i] nums1.sort() ''' ...
1 else: nums1[p] = nums2[p2] p += 1 p2 += 1 if p1 < m: nums1[p:] = nums1copy[p1:] elif p2 < n: nums1[p:] = nums2[p2:] ''' p1 = m - 1 p2 = n - 1 for p in range(n + m - 1, -1, -1): ...
[p] = nums2[p2] p2 -= 1
michaelarnauts/home-assistant
homeassistant/components/media_player/cast.py
Python
mit
8,631
0
""" homeassistant.components.media_player.chromecast ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to interact with Cast devices on the network. WARNING: This platform is currently not working due to a changed Cast API """ import logging from homeassistant.const import ( STATE_PLAYING, ...
_status.volume_muted if self.cast_status else None
@property def media_content_id(self): """ Content ID of current playing media. """ return self.media_status.content_id if self.media_status else None @property def media_content_type(self): """ Content type of current playing media. """ if self.media_status is None: ...
mdboom/freetypy
docstrings/tt_postscript.py
Python
bsd-2-clause
2,490
0
# -*- coding: utf-8 -*- # Copyright (c) 2015, Michael Droettboom All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, t...
R BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # The views and conclusions contained in the software...
__ import print_function, unicode_literals, absolute_import TT_Postscript__init__ = """ A TrueType PostScript table. """ TT_Postscript_format_type = """ Format of this table. """ TT_Postscript_italic_angle = """ Italic angle in degrees. """ TT_Postscript_underline_position = """ Underline position. """ TT_Postscr...
AdamWill/anaconda
pyanaconda/simpleconfig.py
Python
gpl-2.0
8,078
0.001609
# # simpleconifg.py - representation of a simple configuration file (sh-like) # # Copyright (C) 1999-2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your op...
d strings that were not replaced This will read all the lines in a file, looking for ones that start with keys and replacing the line with the associated string. The string should b
e a COMPLETE replacement for the line, not just a value. When add is True any keys that haven't been found will be appended to the end of the file along with the add_comment. """ # Helper to return the line or the first matching key's string def _replace(l): r = [s for k,s in keys if l.star...
reminisce/mxnet
example/ssd/quantization.py
Python
apache-2.0
8,206
0.004996
# 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...
/qssd_vgg16_reduced_300') param_name = '%s-%04d.params' % ('./model/qssd_vgg16_reduced_300', epoch) save_symbol(sym_name, qsym, logger) else: logger.info('Creating ImageRecordIter for reading calibration dataset') eval_iter = DetRecordIter(os.path.join(os.getcwd(), 'data', 'val.rec')...
id) qsym, qarg_params, aux_params = quantize_model(sym=sym, arg_params=arg_params, aux_params=aux_params, ctx=ctx, excluded_sym_names=excluded_sym_names, calib_mode=calib_mode, calib_data=eval_iter, ...
dimagi/commcare-hq
corehq/apps/export/management/commands/delete_exports.py
Python
bsd-3-clause
3,683
0.002715
from django.core.management.base import BaseCommand from dimagi.utils.couch.database import iter_bulk_delete from corehq.apps.export.models import ExportInstance class Command(BaseCommand): help = "Delete exports in a domain" def add_arguments(self, parser): parser.add_argument( 'domai...
ain, **options): db = ExportInstance.get_db() exports = db.view( 'export_instances_by_domain/view', startkey=[do
main], endkey=[domain, {}], include_docs=False, reduce=False, ).all() if not exports: print("No exports to delete here, exiting.") return if options['days_inactive'] > 0: import datetime inactive_since = datetim...
PythonSanSebastian/epcon
conference/models.py
Python
bsd-2-clause
49,377
0.005167
# -*- coding: UTF-8 -*- import datetime import os import os.path import subprocess from collections import defaultdict from django.conf import settings as dsettings from django.core import exceptions from django.core.cache import cache from django.db import connection from django.db import models from django.db import...
key = 'usage' if asc else '-usage'
return self.annotate_with_usage().order_by(key) class ConferenceTag(TagBase): objects = ConferenceTagManager() category = models.CharField(max_length=50, default='', blank=True) def save(self, **kw): if not self.pk: frame = inspect.currentframe() stack_trace = tra...
samuelcolvin/pydantic
docs/examples/exporting_models_ujson.py
Python
mit
308
0
from dat
etime import datetime import ujson from pydantic import BaseModel class
User(BaseModel): id: int name = 'John Doe' signup_ts: datetime = None class Config: json_loads = ujson.loads user = User.parse_raw('{"id": 123,"signup_ts":1234567890,"name":"John Doe"}') print(user)
brianspeir/Vanilla
vendor/bootstrap-vz/base/__init__.py
Python
bsd-3-clause
296
0.013514
__all__ = ['Phase', 'Task', 'main'] from phase
import Phase from task import Task from main import main def validate_manifest(data, validator, error): import os.path schema_path = os.path.normpath(os.path.join(os.path.dirname(__file__), 'manifest-
schema.json')) validator(data, schema_path)
skeenp/Roam
src/roam/errors.py
Python
gpl-2.0
854
0.003513
""" Module to handle sending error reports. """ import roam import roam.config import roam.utils errorreporting = False try: from raven import Client errorreporting = True except ImportError: errorreporting = False roam.utils.warning("Error reporting disabled due to import error") def can_send(): ...
ror_reporting", False) def send_exception(exinfo):
if can_send() and errorreporting: client = Client( dsn='http://681cb73fc39247d0bfa03437a9b53b61:[email protected]/17', release=roam.__version__ ) roam.utils.info("Sending error report.") client.captureException(exinfo)
linglung/ytdl
youtube_dl/extractor/senateisvp.py
Python
unlicense
6,273
0.001594
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, unsmuggle_url, ) from ..compat import ( compat_parse_qs, compat_urlparse, ) class SenateISVPIE(InfoExtractor): _COMM_MAP = [ ['ag', '76440', 'http://ag...
if entry[0] == committee: return entry[1:] def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {}) qs = compat_parse_qs(re.match(self._VALID_URL, ur
l).group('qs')) if not qs.get('filename') or not qs.get('type') or not qs.get('comm'): raise ExtractorError('Invalid URL', expected=True) video_id = re.sub(r'.mp4$', '', qs['filename'][0]) webpage = self._download_webpage(url, video_id) if smuggled_data.get('force_title'):...
beiko-lab/gengis
bin/Lib/site-packages/wx-2.8-msw-unicode/wx/build/build_options.py
Python
gpl-3.0
160
0.06875
UNICODE=1 UNDEF_N
DEBUG=1 INSTALL_MULTIVERSION=1 FLAVOUR="" EP_ADD_OPTS=1 EP_FULL_VER=0 WX_CONFIG="None" WXPORT="msw" MONOLITHIC=0
FINAL=0 HYBRID=1
hrayr-artunyan/shuup
shuup_tests/core/test_order_price_display.py
Python
agpl-3.0
3,010
0.001661
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import decimal import pytest from shuup.core.templatetags....
strip("\u20ac")) taxless_total += decimal.Decimal(money(line.taxless_price).strip("\u20ac")) assert decimal.Decimal(money(order.taxful_total_price).strip("\u20ac")) == taxful_total assert decimal.Decimal(money(order.taxless_total_price).strip("\u20ac")) == taxless_total def _get_order(shop, supplier):...
der = create_empty_order(shop=shop) order.full_clean() order.save() for product_data in _get_product_data(): quantity = product_data.pop("quantity") tax_rate = product_data.pop("tax_rate") product = create_product( sku=product_data.pop("sku"), shop=shop, ...
getting-things-gnome/gtg
tests/core/test_search_filter.py
Python
gpl-3.0
9,498
0
# ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2014 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Gene...
'search', '@
a']), p)) def test_simple_tag_or(self): task = FakeTask(tags=['@a', '@b']) self.assertTrue(search_filter( task, {"q": [('or', True, [("tag", True, "@a"), ("tag", True, "@b")])]})) self.assertTrue(search_filter( task, {"q": ...
chrislit/abydos
abydos/distance/_tarantula.py
Python
gpl-3.0
4,524
0
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
ptional, Sequence, Set, Union from ._token_distance import _TokenDistance from ..tokenizer import _Tokenizer __all__ = ['Tarantula'] class Tarantula(_TokenDistance): r"""Tarantula similarity. For two sets X and Y and a population N, Ta
rantula similarity :cite:`Jones:2005` is .. math:: sim_{Tarantula}(X, Y) = \frac{\frac{|X \cap Y|}{|X \cap Y| + |X \setminus Y|}} {\frac{|X \cap Y|}{|X \cap Y| + |X \setminus Y|} + \frac{|Y \setminus X|} {|Y \setminus X| + |(N \setminus X) \setmi...
plotly/plotly.py
packages/python/plotly/plotly/validators/box/marker/_symbol.py
Python
mit
14,526
0.000069
import _plotly_utils.basevalidators class SymbolValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="symbol", parent_name="box.marker", **kwargs): super(SymbolValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
213, "213", "pentagon-dot", 313, "313", "pentagon-open-dot", 14, "14",
"hexagon", 114, "114", "hexagon-open", 214, "214", "hexagon-dot", 314, "314", "hexagon-open-dot", 15, ...
moto-timo/robotframework
src/robot/output/xmllogger.py
Python
apache-2.0
5,678
0.000176
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
.assign) def end_keyword(self, kw): self._write_status(kw) self._writer.end('kw') def start_test(self, test): attrs = {'id': test.id, 'name': test.name} if test.timeout: attrs['timeout'] = unic(test.timeout) self._writer.start('test', attrs) def end_tes...
, test.tags) self._write_status(test, {'critical': 'yes' if test.critical else 'no'}) self._writer.end('test') def start_suite(self, suite): attrs = {'id': suite.id, 'name': suite.name, 'source': suite.source} self._writer.start('suite', attrs) def end_suite(self, suite): ...
eayunstack/neutron
neutron/plugins/ml2/extensions/dns_integration.py
Python
apache-2.0
23,051
0.00026
# Copyright (c) 2016 IBM # 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 appli...
rd(plugin_context, request_da
ta, db_data, network, dns_name or '') return dns_data_db def _populate_previous_external_dns_data(self, dns_data_db): dns_data_db['previous_dns_name'] = ( dns_data_db['current_dns_name']) dns_data_db['previous_dns_domain'] = ( dns_data_db['current_dns_domain']) ...
OpenSpaceProgram/pyOSP
library/sensors/Raspistill.py
Python
mit
2,060
0.001942
# -*- coding: utf-8 -*- import sys import time from subprocess import call #add the project folder to pythpath sys.path.append('../../') from library.components.SensorModule import SensorModule as Sensor from library.components.MetaData import MetaData as MetaData class Raspistill(Sensor): def __init__(self): ...
) self.addMetaData(iso800MetaData) def getIso100(sel
f): filename = "photos/" + str(time.time()) + "-iso100.jpg" call(["raspistill", "--ISO", "100", "-o", filename]) return str(filename) def getIso200(self): filename = "photos/" + str(time.time()) + "-iso200.jpg" call(["raspistill", "--ISO", "200", "-o", filename]) ret...
felipevolpone/alabama_orm
tests/test_property.py
Python
mit
1,389
0
import unittest from mock import Person, Gender from models import BaseProperty class TestProperty(unittest.TestCase): def test_enum_property(self): model = Person() model.gender = Gender.male self.assertEquals(model.gender, Gender.male) with self.assertRaises(ValueError): ...
obj
1.name = "string" obj1.age = 1 self.assertEqual(obj1.name, "string") self.assertEqual(obj1.age, 1) obj2 = Person() obj2.name = "new" obj2.age = 2 self.assertEqual(obj2.name, "new") self.assertEqual(obj2.age, 2) self.assertEqual(obj1.name, "stri...
magvugr/AT
AppAdiccionTic/models.py
Python
gpl-3.0
1,704
0.033451
from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models # Create your models here. class Noticia(models.Model): Publicado = 'Publicado' Borrador = 'Borrador' Titulo = models.CharField(max_length=30) Subtitulo = models.CharField(max_length=50) Imagen = mode...
Estado = models.CharField(max_length=9,choices=CHOICES, default=Borrador) IncluirVideo = models.BooleanField() CodVideo = models.CharField(max_length=200) Tags = models.CharField(max_length=30) usuario = models.ForeignKey(User) def __str__(self): return self.Titulo + ' - ' + self.Subtitulo class Evento(model...
= models.FileField(blank=True, upload_to='media/fotos/noticias') SubtituloImag = models.CharField(max_length=30) Cuerpo = models.CharField(max_length=500) Timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) Actualizado = models.DateTimeField(auto_now_add = False, auto_now = True) Lugar = models...
makfire/gstudio
gnowsys-ndf/gnowsys_ndf/ndf/views/task.py
Python
agpl-3.0
37,929
0.019774
import datetime import json from django.http import HttpResponseRedirect from django.http import StreamingHttpResponse from django.http import HttpResponse from django.shortcuts import render_to_response #render uncomment when to use from django.template import RequestContext from django.core.urlresolvers import reve...
history = [] subtask = [] for each in at_list: attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name':
each}) attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type.$id": attributetype_key._id}) if attr: if attributetype_key.name == "Assignee": u_list = [] for each_id in attr.object_value: u = User.objects.get(id=each_id) if u...
gnowledge/ncert_nroer
gstudio/tests/url_shortener.py
Python
agpl-3.0
5,124
0.000585
# Copyright (c) 2011, 2012 Free Software Foundation # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later vers...
LAR PURPOSE. See the # GNU Affero General Pu
blic License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Test cases for Gstudio's url_shortener""" from __future__ import with_statement import warnings from django.test import TestCas...
bartoldeman/easybuild-easyblocks
easybuild/easyblocks/s/snphylo.py
Python
gpl-2.0
3,939
0.002793
## # Copyright 2009-2018 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
specified correctly); # use run_cmd_qa doesn not work because of buffering issues (questions are not coming through) adjust_permissions('setup.sh', stat.S_IXUSR, add=True) (out, _) = run_cmd('bash ./setup.sh', inp='\n' * 10, simple=False) success_msg = "SNPHYLO is successfully installe...
lf): """Install by copying files/directories.""" bindir = os.path.join(self.installdir, 'bin') binfiles = ['snphylo.sh', 'snphylo.cfg', 'snphylo.template'] try: mkdir(bindir, parents=True) for binfile in binfiles: shutil.copy2(os.path.join(self.bui...
RevansChen/online-judge
Codewars/8kyu/training-js-number-7-if-dot-else-and-ternary-operator/Python/solution1.py
Python
mit
153
0.006536
# Python - 2.7.6 def sale_hotdogs(n): if n < 5: return n * 100 elif (5 <=
n < 10): return n *
95 else: return n * 90
zedr/boxing-clock
src/main.py
Python
bsd-3-clause
209
0
try: from boxe_c
lock.apps.android_app import BoxingApp except ImportError: from boxe_clock.apps.generic_app import BoxingApp def main(): BoxingApp().run() if __name__ =
= "__main__": main()
ina-foss/ID-Fits
lib/datasets/landmarks_file.py
Python
lgpl-3.0
1,121
0.005352
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3.0 of the Lic
ense, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have re...
andmarkFile(filename, landmarks_number): f = open(filename) # Skip first 3 lines for i in range(3): f.readline() # Read landmarks position landmarks = np.empty((landmarks_number, 2), dtype=np.float) for i in range(landmarks_number): landmarks[i] = np.array([float(x) for x in f....
CCI-MOC/GUI-Backend
scripts/import_tags.py
Python
apache-2.0
2,440
0.00041
#!/usr/bin/env python import json import logging from optparse import OptionParser from service_old.models import Instance import django django.setup() def export_instance_tags(): instance_tags = [] instances = Instance.objects.all() added = 0 for i in instances: if i.instance_tags: ...
instance_tags = json.loads(instance_tags_json) added = 0 skipped = 0 for instance_tag in instance_tags: try: instance = Instance.objects.get( instance_id=instance_tag['instance']) instance.instance_tags = ','.join( [tag['name'] for tag in insta...
stance.DoesNotExist as dne: logging.warn( 'Could not import tags for instance <%s> - DB Record does not exist' % instance_tag['instance']) skipped = skipped + 1 total = added + skipped logging.info( '%s Records imported. %s Records added, %s Record...
Loisel/colorview2d
colorview2d/mods/Scale.py
Python
bsd-2-clause
455
0.002198
"""A mod to scale the data.""" from co
lorview2d import imod class Scale(imod.IMod): """ The mod class to scale the values in the 2d data array according to the value entered in the widget: args (float): The float that is multiplied with the data array. """ def __init__(self): imod.IMod.__init__(self) self.args = se...
args
lewfish/django-social-news
social_news/urls.py
Python
mit
1,105
0.00724
from django.conf.urls import patterns, include, url from django.core.urlresolvers import reverse from django.contrib.auth.decorators import
login_required from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm from . import views urlpatterns = patterns('', url(r'^$', views.all, name='all'), url(r'^submit/$', login_required(views.EntryCreateView.as_view()), name...
url(r'^vote/$', login_required(views.vote), name='vote'), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'social_news/login.html'}, name='login'), url(r'^logout/$', 'django.contrib.auth.v...
p1c2u/openapi-core
openapi_core/validation/request/shortcuts.py
Python
bsd-3-clause
1,401
0
"""OpenAPI core validation request shortcuts module""" fro
m functools import partial from openapi_core.validation.request.validators import RequestBodyValidator from openapi
_core.validation.request.validators import ( RequestParametersValidator, ) from openapi_core.validation.request.validators import RequestSecurityValidator from openapi_core.validation.request.validators import RequestValidator def validate_request(validator, request): result = validator.validate(request) ...
vincentchevrier/dataquick
dataquick/plugins/visualizations/ui/psd.py
Python
mit
1,775
0.002817
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Coding\Python\PythonPackageLinks\dataquick\plugins\visualizations\ui\psd.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes mad
e in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_PSD(object): def setupUi(self, PSD): PSD.setObjectName("PSD") PSD.resize(1000, 561) self.verticalLayout = QtWidgets.QVBoxLayout(PSD) self.verticalLayout.setContentsMargins(3, 3, 3, 3) self.vert...
ion(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.layoutWidget = QtWidgets.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_left = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_left.setContentsMargins(0...
sjzabel/snail
tests/test-vlq.py
Python
bsd-3-clause
271
0.00369
import unittest from unittest.mock import MagicMock import io from snail import vlq clas
s TestVlq(unittest.TestCase): def setup(self): pass def teardown(self): pass def test_re
ad(self): pass def test_write(self): pass
yungyuc/solvcon
examples/misc/elas3d/elastic.py
Python
bsd-3-clause
26,514
0.01041
# -*- coding: UTF-8 -*- # # Copyright (C) 2010-2011 Yung-Yu Chen <[email protected]>. # # 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 l...
# Solver
. ############################################################################### class ElasticSolver(CeseSolver): """ Basic elastic solver. @ivar cfldt: the time_increment for CFL calculation at boundcond. @itype cfldt: float @ivar cflmax: the maximum CFL number. @itype cflmax: float @iva...
tipsybear/ormbad
ormbad/version.py
Python
apache-2.0
1,161
0.000861
# or
mbad.version # Helper module for ORMBad version information # # Author: Benjamin Bengfort <[email protected]> # Created: Thu Aug 13 12:38:42 2015 -0400 # # Copyright (C) 2015 Tipsy Bear Studios # For license information, see LICENSE.txt # # ID: version.py [] [email protected] $ """ Helper module for ORMBad ...
# __version_info__ = { 'major': 0, 'minor': 1, 'micro': 0, 'releaselevel': 'final', 'serial': 0, } def get_version(short=False): """ Returns the version from the version info. """ assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = ["%(major)i.%(minor)...
ajhager/copycat
lib/pyglet/window/__init__.py
Python
gpl-2.0
65,226
0.000767
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistribu...
rived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICU
LAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOW...
gofore/aws-emr
src/streaming-programs/02-xml-parse-test_map.py
Python
mit
765
0.005229
#!/usr/bin/python import sys import xml.etree.ElementTree as ET # XML parsing test # See https://hadoop.apache.org/docs/current/api/org/apache/hadoop/mapreduce/lib/aggregate/package-tree.html def m
ain(argv): root = ET.parse(sys.stdin).getroot() period_start = root.attrib.get('periodstart') for road_link in root.iter('{http://FTT.arstraffic.com/schemas/IndividualTT/}link'): road_link_id = road_link.attrib.get('id') road_link_times = [int(car.attrib.get('t
t')) for car in road_link] number_of_cars = len(road_link_times) average_travel_time = sum(road_link_times)/number_of_cars print "{0}\t{1} {2}".format(road_link_id, average_travel_time, number_of_cars) if __name__ == "__main__": main(sys.argv)
appleseedhq/cortex
python/IECoreMaya/FileSequenceParameterUI.py
Python
bsd-3-clause
3,597
0.033083
#################################
######################################### # # Copyright (c) 2010, Image En
gine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the followi...
orchidinfosys/odoo
addons/payment/models/res_config.py
Python
gpl-3.0
1,197
0
# -*- coding: utf-8 -*- from openerp.osv import fields, osv class AccountPaymentConfig(osv.TransientModel): _inherit = 'account.config.settings' _columns = { 'module_payment_transfer': fields.boolean( 'Wire Transfer', help='-This installs the module payment_transfer.'), ...
), 'module_payment_buckaroo': fields.boolean(
'Buckaroo', help='-This installs the module payment_buckaroo.'), 'module_payment_authorize': fields.boolean( 'Authorize.Net', help='-This installs the module payment_authorize.'), 'module_payment_sips': fields.boolean( 'Sips', help='-T...
laudaa/bitcoin
test/functional/fundrawtransaction.py
Python
mit
32,075
0.009602
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the fundrawtransaction RPC.""" from test_framework.test_framework import BitcoinTestFramework fro...
][0]['scriptSig']['hex'], '') ################################ # simple test with two outputs # ################################ inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.6, self.nodes[1].getnewaddress() : 2.5 } rawtx = self.nodes[2].createrawtransac...
awtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ...
racker/python-raxcli
raxcli/concurrency/__init__.py
Python
apache-2.0
1,568
0
# Copyright 2013 Rackspace # # 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...
KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ 'get_pool', 'run_function', 'join_pool' ] import os import sys tr
y: import gevent gevent gevent_available = True except ImportError: gevent_available = False DEFAULT_BACKEND = 'noop' BACKEND = DEFAULT_BACKEND USE_GEVENT = os.getenv('RAXCLI_USE_GEVENT') if USE_GEVENT and gevent_available: BACKEND = 'gevent' module_name = 'raxcli.concurrency.backends.%s_backen...
magfest/ubersystem
uber/site_sections/schedule.py
Python
agpl-3.0
16,602
0.003253
import json import ics from collections import defaultdict from datetime import datetime, time, timedelta from time import mktime import cherrypy from pockets import listify from sqlalchemy.orm import joinedload from uber.config import c from uber.decorators import ajax, all_renderable, cached, csrf_protected, csv_fi...
# we cache this view because it takes a while to generate return get_schedule_data(session, message) @schedule_view @csv_file def time_ordered(self, out, session): for event in session.query(Event).order_by('start_time', 'duration', 'location').all(): out.wri
terow([event.timespan(30), event.name, event.location_label]) @schedule_view def xml(self, session): cherrypy.response.headers['Content-type'] = 'text/xml' schedule = defaultdict(list) for event in session.query(Event).order_by('start_time').all(): schedule[event.location_la...
cleberzavadniak/eolo-app-db
eolo_db/__main__.py
Python
gpl-2.0
934
0
#!env python import optparse import logging from . import wamp from . import db from . import rpcs logging.basicConfig(level=logging.INFO) # Options parsing: parser = optparse.OptionParser() parser.add_option('-W', '--router', help="URL to WAMP router", default='ws://localhost:10...
nnect to", default='eolo') # TODO: add options related to the database backend. (opts, args) = parser.parse_args() # The Collections Manager: db_manager = db.DatabaseManager() # The RPCs Manager: rpc_manager = rpcs.RPCManager(db_manager) # Starts a WAMP session: wamp_session = wamp.WAMP_Session( ...
pc_manager, 'database', # Client type 'eolo.db.info', # Info topic opts.realm # Realm name ) wamp_session.start(opts.router) # Starts the main loop: wamp_session.run_loop()
funbaker/astropy
astropy/utils/iers/iers.py
Python
bsd-3-clause
30,484
0.001083
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ The astropy.utils.iers package provides access to the tables provided by the International Earth Rotation and Reference Systems Service, in particular allowing interpolation of published UT1-UTC values for given times. These are used in `astropy.time`...
as u from ...table import Table, QTable from ...utils.data import get_pkg_data_filename, clear_download_cache from ... import utils from ...utils.exceptions import AstropyWarning __all__ = ['Conf', 'conf', 'IERS', 'IERS_B', 'IERS_A', 'IERS_Auto', 'FROM_IERS_B', 'FROM_IERS_A', 'FROM_IERS_A_PREDIC...
'TIME_BEFORE_IERS_RANGE', 'TIME_BEYOND_IERS_RANGE', 'IERS_A_FILE', 'IERS_A_URL', 'IERS_A_README', 'IERS_B_FILE', 'IERS_B_URL', 'IERS_B_README', 'IERSRangeError', 'IERSStaleWarning'] # IERS-A default file name, URL, and ReadMe with content description IERS_A_FILE = 'finals2000A.all'...
yujikato/DIRAC
src/DIRAC/TransformationSystem/Agent/MCExtensionAgent.py
Python
gpl-3.0
5,092
0.008445
""" Agent to extend the number of tasks given the Transformation definition The following options can be set for the MCExtensionAgent. .. literalinclude:: ../ConfigTemplate.cfg :start-after: ##BEGIN MCExtensionAgent :end-before: ##END :dedent: 2 :caption: MCExtensionAgent options """ from __future__ import ab...
# Determine the number of tasks to be created numberOfTasks = self._calculateTaskNumber(maxTasks, statusDict) if not numberOfTasks: gLogger.info("No tasks required for transformation %d" % transID) return S_OK() # Extend the transformation by the determined number of tasks res = self.transC...
MattyO/start-cms
reverse.py
Python
gpl-2.0
1,062
0.001883
import fnmatch import os im
port json import argparse import re parser = argparse.ArgumentParser() parser.add_argument("template_data") args = parser.parse_args() template_data = json.loads(args.template_data) folder = template_data['app_name'] template_data = json.loads(args.template_data) for (dirpath, dirnames, filenames) in os.walk('./' ...
for filename in filenames: if filename.endswith(".pyc"): continue new_file_contents = "" with open(dirpath + "/" + filename, 'r') as f: for line in f: line, times = re.subn(template_data['app_name'], '{{app_name}}', line) new_file_con...
Tsiems/mobile-sensing-apps
tornado_bare/mongodb_example.py
Python
mit
174
0.017241
#!/usr/bin/python from pymongo import MongoClient client = MongoClient() db=client.exampledatabase collect1 = db.queries for document in collect1.find(): print docu
ment
openprocurement/openprocurement.auctions.dgf
openprocurement/auctions/dgf/views/financial/bid_document.py
Python
apache-2.0
623
0.001605
# -*- coding: utf-8 -*- from openprocurement.auctions.core.utils import ( opres
ource, ) from openprocurement.auctions.dgf.views.other.bid_document import ( AuctionBidDocumentResource, ) @opresource(name='dgfFinancialAssets:Auction Bid Documents', collection_path='/auctions/{auction_id}/bids/{bid_id}/documents', path='/auctions/{auction_id}/bids/{bid_id}/documents/{do...
lass FinancialAuctionBidDocumentResource(AuctionBidDocumentResource): pass
Tjorriemorrie/pokeraide
tui/demos/demo.py
Python
gpl-2.0
495
0.00202
from urwid import MainLoop, ExitMainLoop, Text, Filler,
AttrMap PALETTE = [ ('banner', 'black', 'light gray'), ('streak', 'black', 'dark red'), ('bg', 'black', 'dark blue'), ] def exit_on_q(key): if key == 'Q': raise ExitMainLoop() txt = Text(('banner', u"Hello World"), align='center') map1 = AttrMap(txt, 'streak') fill = Filler(map1) map2 = A...
in__': loop.run()
tgalal/inception
inception/argparsers/makers/submakers/submaker_updatezip.py
Python
gpl-3.0
1,747
0.005724
from .submaker import Submaker from inception.tools.signapk import SignApk import shutil import os from inception.constants import InceptionConstants class UpdatezipSubmaker(Submaker): def make(self, updatePkgDir): keys_name = self.getValue("keys") signingKeys = self.getMaker().getConfig().getKeyCo...
'%s' from %s does not exist" % (signApkPath, signApkKey) assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey) s
ignApk = SignApk(javaPath, signApkPath) targetPath = updatePkgDir + "/../" + InceptionConstants.OUT_NAME_UPDATE signApk.sign(updateZipPath, targetPath, signingKeys[0], signingKeys[1]) updateZipPath = targetPath return updateZipPath
aglie/meerkat
setup.py
Python
mit
480
0.052083
from setuptools import setup setup( name = 'meerkat', packages = ['meerkat'], version = '0.3.7', description = 'A program for reciprocal space reconstruction', author = 'Arkadiy Simonov, Dmitry Logvinovich', author_email = 'aglietto@gmai
l.com', url = 'https://git
hub.com/aglie/meerkat.git', # download_url = keywords = ['crystallography', 'single crystal', 'reciprocal space reconstruction'], classifiers = [], install_requires = ['fabio','h5py','numpy'], )
fake-name/ReadableWebProxy
alembic/versions/2019-09-08_c225ea8fbf5e_add_hash_and_parent_hash_columns.py
Python
bsd-3-clause
4,843
0.006607
"""Add hash and parent hash columns Revision ID: c225ea8fbf5e Revises: ea8987f915b8 Create Date: 2019-09-08 16:33:03.743328 """ # revision identifiers, used by Alembic. revision = 'c225ea8fbf5e' down_revision = 'ea8987f915b8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa fro...
ash'], ['data_hash']) print("Dropping is_delta column on rss_parser_funcs") op.drop_column('rss_parser_funcs_version', 'is_delta') print("Adding to web_pages 1") op.add_column(
'web_pages_version', sa.Column('data_hash', postgresql.UUID(), nullable=True, unique=True)) print("Adding to web_pages 2") op.add_column('web_pages_version', sa.Column('parent_hash', postgresql.UUID(), nullable=True)) print("Adding to web_pages (foreign key)") op.create_foreign_key(None, 'web_pages_vers...
blueskycoco/rt-thread
bsp/stm32/stm32f767-fire-challenger/rtconfig.py
Python
gpl-2.0
4,079
0.0076
import os # toolchains options ARCH='arm' CPU='cortex-m7' CROSS_TOOL='gcc' # bsp lib config BSP_LIBRARY_TYPE = None if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute...
-config "board/linker_scripts/link.icf"' LFLAGS += ' --entry __iar_program_start' CXXFLAGS = CFLAGS EXEC_PATH = EXEC_PATH + '/arm/bin/' POST_ACTION = 'ielftool --bin $TARGET rtthread.bin' def dist_handle(BSP_ROOT, dist_dir): import sys cwd_path = os.getcwd() sys.path.append(os.path.join(o...
, 'tools')) from sdk_dist import dist_do_building dist_do_building(BSP_ROOT, dist_dir)
arsenovic/galgebra
test/test_lt.py
Python
bsd-3-clause
402
0.012438
import unittest from sympy impo
rt symbols from galgebra.ga import Ga class TestLt(unittest.TestCase): # reproduce gh-105 def test_lt_matrix(self): base = Ga('a b', g=[1,1], coords=symbols('x,y',real=True)) a,b = base.mv() A = base.lt([a+b,2*a-b]) assert str(A) == 'Lt(a) = a + b\nLt(b) = 2*a - b' asse...
.matrix()) == 'Matrix([[1, 2], [1, -1]])'
DinoV/PTVS
Python/Product/PyKinect/PyKinect/winspeech/recognition.py
Python
apache-2.0
8,335
0.005399
# PyKinect # Copyright(c) Microsoft Corporation # 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 # # THIS CODE IS PROVIDED ON ...
onResult(alt) for alt in alternates) else: self.alternates = () class _event(object): """class used for adding/removing/invoking a set of listener func
tions""" __slots__ = ['handlers'] def __init__(self): self.handlers = [] def __iadd__(self, other): self.handlers.append(other) return self def __isub__(self, other): self.handlers.remove(other) return self def fire(self, *args): ...
CrowdStrike/kafka-python
test/fixtures.py
Python
apache-2.0
8,620
0.001508
import logging import os import os.path import shutil import subprocess import tempfile from six.moves import urllib import uuid from six.moves.urllib.parse import urlparse # pylint: disable-msg=E0611 from test.service import ExternalService, SpawnedService from test.testutil import get_open_port class Fixture(objec...
id, zk_host, zk_port, zk_chroot, replicas=1, partitions=2): self.host = host self.port = port self.broker_id = broker_id
self.zk_host = zk_host self.zk_port = zk_port self.zk_chroot = zk_chroot self.replicas = replicas self.partitions = partitions self.tmp_dir = None self.child = None self.running = False def out(self, message): logging.info("*** Kafka [%s:%d...
USGSDenverPychron/pychron
pychron/entry/tasks/project/project_manager.py
Python
apache-2.0
4,367
0.000458
# =============================================================================== # Copyright 2016 ross # # 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/LICE...
# s
elf._add() # ============= EOF =============================================