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
nicozhang/pyspider
pyspider/scheduler/scheduler.py
Python
apache-2.0
46,109
0.001431
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-02-07 17:05:11 import itertools import json import logging import os import time from collections import deque from six import iteritems, itervalues...
.path.join(self.data_path, 'scheduler.1h')) self._cnt['1d'].load(os.path.join(self.data_path, 'scheduler.1d')) self._cnt['all'].load(os.path.join(self.data_path, 'scheduler.all')) self._last_dump_cnt = 0 def _update_project
s(self): '''Check project update''' now = time.time() if ( not self._force_update_project and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now ): return for project in self.projectdb.check_update(self._last_update_project)...
smathot/qnotero
libqnotero/qt/QtCore.py
Python
gpl-2.0
777
0.003861
#-*- coding:utf-8 -*- """ This file is part of OpenSesame. OpenSesame is free software: you can
redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenSesame is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warr...
he GNU General Public License along with OpenSesame. If not, see <http://www.gnu.org/licenses/>. """ from libqnotero import qt if qt.pyqt == 5: from PyQt5.QtCore import * else: from PyQt4.QtCore import *
mozilla/gameon
gameon/submissions/migrations/0005_auto__add_field_category_description.py
Python
bsd-3-clause
6,583
0.007899
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Category.description' db.add_column('submissions_category', 'description', ...
harField', [], {'max_length': '255', 'blank': 'True'}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max
_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'to_market': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'url': ('django.db.models.fields.URLField', [], {'max_leng...
vikramraman/algorithms
python/editdistance.py
Python
mit
928
0.017241
# Author: Vikram Raman # Date: 09-12-2015 import time # edit distance between two strings # e(i,j) = min (1 + e(i-1,j) | 1 + e(i,j-1) | diff(i,j) + e(i-1,j-1)) def editdistan
ce(s1, s2): m = 0 if s1 is None else len(s1) n = 0 if s2 is None else len(s2) if m == 0: return n elif n == 0: return m l = [[i for i in range(0,n+1)]] for i in range(1,m+1): l.append([i]) for i in range(1,m+1): for j in range(1,n+1): minimum =...
diff(s1,s2,i,j) + l[i-1][j-1]) l[i].append(minimum) return l[m][n] def diff (s1, s2, i, j): return s1[i-1] != s2[j-1] s1 = "exponential" s2 = "polynomial" print "s1=%s, s2=%s" % (s1,s2) start_time = time.clock() distance=editdistance(s1, s2) print "distance=%d" % (distance) print("--- %s ...
velikodniy/python-fotki
fotki/user.py
Python
lgpl-3.0
3,334
0.002105
#!/usr/bin/env python # coding:utf-8 # Copyright (c) 2011, Vadim Velikodniy <vadim-velikodniy@yandex.ru> # # This library is free so
ftware; 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 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WA...
eneral Public License for more details. import httplib, json import fotki.collection as collection from fotki.auth import DEFAULT_AUTH class UserException(Exception): """Класс-исключение для ошибок получения информации о пользователе.""" pass class UserNotFound(UserException): """Исключение 'Пользователь...
SKA-ScienceDataProcessor/algorithm-reference-library
deprecated_code/workflows/mpi/imaging-pipelines_serial.py
Python
apache-2.0
12,979
0.018106
# coding: utf-8 # # Pipeline processing using serial workflows. # # This notebook demonstrates the continuum imaging and ICAL pipelines. These are based on ARL functions wrapped up as SDP workflows using the serial class. # In[1]: #get_ipython().run_line_magic('matplotlib', 'inline') import os import sys sys.pa...
channel_bandwidth=[channel_bandwidth[f]], cellsize=cellsize, phasecentre=phasecentre,
polarisation_frame=PolarisationFrame("stokesI")) for f, freq in enumerate(frequency)] # In[ ]: start=time.time() print('About to start invert' ,flush=True) dirty_list = invert_list_serial_workflow(predicted_vislist, model_list, context='wstack', ...
seldon/django-flexi-auth
flexi_auth/tests/models.py
Python
agpl-3.0
4,238
0.014158
# Copyright (C) 2011 REES Marche <http://www.reesmarche.org> # # This file is part of ``django-flexi-auth``. # ``django-flexi-auth`` is free software: you can redistribute it and/or modify # it under the t
erms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # ``django-flexi-auth`` is distributed in the hope that it will be u
seful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with ``django-flexi-auth``. If not, see <http...
py-mina-deploy/py-mina
py_mina/state.py
Python
mit
845
0.008284
""" Deploy state manager """ from py_mina.utils import _AttributeDict ################################################################################ # Default state ################################################################################ state = _AttributeDict({ 'pre_deploy': None, 'deploy': No...
############################################################### # Set state ##############
################################################################## def set(key, value): if key in state.keys(): state[key] = value else: raise Exception('State "%s" is not defined' % key) # Alias to prevent conflict when importing "py_mina.config" and "py_mina.state" set_state = set
richardliaw/ray
rllib/__init__.py
Python
apache-2.0
2,272
0
import logging # Note: do not introduce unnecessary library dependencies here, e.g. gym. # This file is imported from the tune module in order to register RLlib agents. from ray.rllib.env.base_env import BaseEnv from ray.rllib.env.external_env import ExternalEnv from ray.rllib.env.multi_agent_env import MultiAgentEnv ...
ntrib" _default_config = with_common_config({}) def setup(self, config): raise NameError( "Please run `contrib/{}` instead.".format(name)) return _SeeContrib # also register the aliases minus contrib/ to give a good error message for key in ...
keys()): assert key.startswith("contrib/") alias = key.split("/", 1)[1] register_trainable(alias, _see_contrib(alias)) _setup_logger() _register_all() __all__ = [ "Policy", "TFPolicy", "TorchPolicy", "RolloutWorker", "SampleBatch", "BaseEnv", "MultiAgentEnv", "...
aarestad/gradschool-stuff
crypto/python/factor.py
Python
gpl-2.0
217
0.009217
import math def factor(n): d = 2 factors = [] while n > 1 and d < math.sqrt(n):
if n % d == 0: factors.append(d) n = n/d else:
d=d+1 return factors
yasoob/PythonRSSReader
venv/lib/python2.7/dist-packages/oauthlib/oauth2/rfc6749/clients/mobile_application.py
Python
mit
9,122
0.00285
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals """ oauthlib.oauth2.rfc6749 ~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of various logic needed for consuming and providing OAuth 2.0 RFC6749. """ from .base import Client from ..parameters import prepare_grant_uri from ..pa...
commonly URIs or various categories such as ``videos`` or ``documents``. :param state: RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value whe...
ection 10.12`_. :param kwargs: Extra arguments to include in the request URI. In addition to supplied parameters, OAuthLib will append the ``client_id`` that was provided in the constructor as well as the mandatory ``response_type`` argument, set to ``token``:: >>> from o...
kanboard/kanboard-cli
kanboard_cli/shell.py
Python
mit
3,401
0.000588
# The MIT License (MIT) # # Copyright (c) 2016 Frederic Guillot # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
self.is_super_user = client_manager.is_super_user() self.command_manager.add_command('app version', application.ShowVersion) self.command_manager.add_command('app timezone', application.ShowTimezone) self.command_manager.add_command('project show', project.ShowProject) self.command_m...
ommand('project list', project.ListProjects) self.command_manager.add_command('task create', task.CreateTask) self.command_manager.add_command('task list', task.ListTasks) def main(argv=sys.argv[1:]): return KanboardShell().run(argv) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
Clustaar/clustaar.authorize
tests/authorize/conditions/test_true_condition.py
Python
mit
231
0
import pytest from
clustaar.authorize.conditions import TrueCondition @pytest.fixture def condition(): return TrueCondition() class TestCall(object): def test_returns_true(s
elf, condition): assert condition({})
stargaser/astropy
astropy/io/ascii/__init__.py
Python
bsd-3-clause
1,565
0.000639
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ An ext
ensible ASCII table reader and writer. """ from .core import
(InconsistentTableError, ParameterError, NoType, StrType, NumType, FloatType, IntType, AllType, Column, BaseInputter, ContinuationLinesInputter, BaseHeader, BaseData, BaseOutputter, Table...
mperrin/misc_astro
idlastro_ports/tvbox.py
Python
bsd-3-clause
511
0.013699
import numpy as np import matplotlib.pyplot as pl def tvbox(box=(1,1), xcen=0, ycen=0, center=None,**kwargs): """ draw a circle on an image. radius xcen ycen center= tuple in (Y,X) order. """ if center is not None: xcen=center[1] ...
x = [xcen-box[0], xcen+box[0], xcen+box[0], xcen-box[0], xcen-box[0]] y = [ycen-box[1], ycen-box[1], ycen+box[1], ycen+box[1], ycen-box[1]] pl.plot(x,y, **kwargs)
jmanoel7/pluma-plugins-0
plugins/zencoding/plugin.py
Python
gpl-3.0
6,126
0.003591
# @file plugin.py # # Connect Zen Coding to Pluma. # # Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com) # # Original Author Franck Marcia (franck.marcia@gmail.com) # import pluma, gobject, gtk, os from zen_editor import ZenEditor zencoding_ui_str = """ <ui> <menubar name="MenuBar"> <menu name="EditMenu"...
None, '_Next edit point', '<Alt>Right', "Place the cursor at the next edit point", self.next_edit_point), ('ZenCodingRemoveAction', None, '_Remove tag', '<C
trl><Alt>R', "Remove a tag", self.remove_tag), ('ZenCodingSplitAction', None, 'Split or _join tag', '<Ctrl><Alt>J', "Toggle between single and double tag", self.split_join_tag), ('ZenCodingCommentAction', None, 'Toggle _comment', '...
JacekPierzchlewski/RxCS
examples/signals/gaussNoise2_ex1.py
Python
bsd-2-clause
1,832
0.002183
""" This script is an example of how to use the random gaussian noise generator (type 2) module. |br| In this example only one signal is generated. Both the minimum and the maximum frequency component in the signal is regulated. After the generation, spectrum fo the signal is analyzed with an Welch analysis and p...
1.0 | 20-JAN-2016 : * Version 1.0 released. |br| *License*: BSD 2-Clause """ import rxcs import scipy.signal as scsig import matplotlib.pyplot as plt def _gaussNoise2_ex1(): # Things on the table: gaussNoise =
rxcs.sig.gaussNoise2() # Gaussian noise generator # Configure the generator... gaussNoise.fR = 100e6 # Representation sampling frequency [100 MHz] gaussNoise.tS = 1 # Time [1 sec] gaussNoise.fMin = 100e3 # Minimum frequency component [100 kHz] gaussNoise.fMax = 200e3 # Maximum fre...
jotes/pontoon
docs/conf.py
Python
bsd-3-clause
9,297
0.006133
# -*- coding: utf-8 -*- # # Pontoon documentation build configuration file, created by # sphinx-quickstart on Thu Jun 4 21:51:51 2015. # # This file is execfile()d with the current directory set to its # cont
aining dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another direc...
sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (name...
dashwav/nano-chan
cogs/utils/__init__.py
Python
mit
129
0
from .db_utils import PostgresController from .enums import Action, Change
__all__ = ['PostgresController', 'Action', 'Cha
nge']
queria/my-tempest
tempest/api/compute/security_groups/test_security_group_rules_negative.py
Python
apache-2.0
7,051
0
# Copyright 2013 Huawei Technologies Co.,LTD. # 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 # # Unl...
def resource_setup(cls): super(SecurityGroupRulesNegativeTestJSON, cls).resource_setup() cls.client = cls.security_groups_client @test.attr(type=['negative', 'smoke']) @test.services('network') def test_create_security_group_rule_with_non_existent_id(self): # Negative test: Cre...
# with non existent Parent group id # Adding rules to the non existent Security Group id parent_group_id = not_existing_id() ip_protocol = 'tcp' from_port = 22 to_port = 22 self.assertRaises(exceptions.NotFound, self.client.create_security_g...
mcdevs/Burger
burger/toppings/topping.py
Python
mit
1,295
0.000772
#!/usr/bin/env python # -*- coding: utf8 -*- """ Copyright (c) 2011 Tyler Kenendy <tk@tkte.ch> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
UT WARRANTY OF ANY K
IND, 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...
mistio/libcloud
docs/examples/loadbalancer/elb/ex_list_balancer_policy_types.py
Python
apache-2.0
291
0
from libcloud.loadbalancer.types import Provider from libcloud.loadbalancer.providers import get_driver ACCESS_ID = 'yo
ur access id' SECRET_KEY = 'your secret key' cls = get_driver(Provider.ELB) driver = cls(key=ACCESS_ID, secret=SECRET_KEY) pri
nt(driver.ex_list_balancer_policy_types())
tchellomello/home-assistant
homeassistant/components/synology_dsm/camera.py
Python
apache-2.0
3,046
0.000657
"""Support for Synology DSM cameras.""" from typing import Dict from synology_dsm.api.surveillance_station import SynoSurveillanceStation from homeassistant.components.camera import SUPPORT_STREAM, Camera from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType ...
None, ENTITY_ENABLE: True, ENTIT
Y_UNIT: None, }, ) self._camera = camera @property def device_info(self) -> Dict[str, any]: """Return the device information.""" return { "identifiers": {(DOMAIN, self._api.information.serial, self._camera.id)}, "name": self.name, ...
noironetworks/neutron
neutron/services/auto_allocate/db.py
Python
apache-2.0
17,334
0.000404
# Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP # # 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/li...
return self._check_requirements(context, tenant_id) elif fields: raise n_exc.BadRequest(resource='auto_allocate', msg=_("Unrecognized field")) # Check for an existent topology network_id =
self._get_auto_allocated_network(context, tenant_id) if network_id: return self._response(network_id, tenant_id, fields=fields) # See if we indeed have an external network to connect to, otherwise # we will fail fast default_external_network = self._get_default_external_netwo...
mvaled/sentry
tests/sentry/api/endpoints/test_group_hashes.py
Python
bsd-3-clause
3,716
0.000807
from __future__ import absolute_import import copy from six.moves.urllib.parse import urlencode from sentry.models import GroupHash from sentry.testutils import APITestCase, SnubaTestCase from sentry.testutils.factories import DEFAULT_EVENT_DATA from sentry.testutils.helpers.datetime import iso_format, before_now fr...
data={ "event_id": "a" * 32, "message": "message",
"timestamp": two_min_ago, "stacktrace": copy.deepcopy(DEFAULT_EVENT_DATA["stacktrace"]), "fingerprint": ["group-1"], }, project_id=self.project.id, ) event2 = self.store_event( data={ "event_id": "b" * 32,...
jeansch/octopasty-og
octopasty/internal.py
Python
gpl-3.0
5,463
0.000366
# -*- coding: utf-8 -*- # Octopasty is an Asterisk AMI proxy # Copyright (C) 2011 Jean Schurger <jean@schurger.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, either version 3 of the Li...
) else: response = Error(parameters=dict(Message='Authentication failed')) p = dict(emiter='__internal__', locked=locked,
timestamp=time(), packet=response, dest=client.id) client.send(Packet(p)) tmp_debug("AUTH", "'%s' failed to login" % username) client.disconnect() def logoff_user(self, packet): client = self.clients.get(packet.emiter) response = Goodb...
t-wissmann/qutebrowser
tests/unit/misc/test_keyhints.py
Python
gpl-3.0
7,603
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2020 Ryan Roden-Corrent (rcorre) <ryan@rcorre.net> # # This file is part of qutebrowser. # # qutebrowser 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...
'<ctrl-a>': 'message-info cmd-ctrla', }} config_stub.val.bindings.default = {} config_stub.val.bindings.commands = bindings keyhint.update_keyhint('normal', '<') assert keyhint.text() == expected_text( ('&lt;', 'yellow', 'a', 'message-info cmd-&lt;a'), ('&lt;', 'yellow', 'b'...
lor_switch(keyhint, config_stub): """Ensure the keyhint suffix color can be updated at runtime.""" bindings = {'normal': {'aa': 'message-info cmd-aa'}} config_stub.val.colors.keyhint.suffix.fg = '#ABCDEF' config_stub.val.bindings.default = {} config_stub.val.bindings.commands = bindings keyhint....
troukny/NetGen
src/network_handler.py
Python
gpl-3.0
2,563
0.014046
#!/usr/bin/env python # -*- coding: utf-8 -*- """ NetGen is a tool for financial network analysis Copyright (C) 2013 Tarik Roukny (troukny@ulb.ac.be) 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, v...
weight = float(weight) except: weight = 0.0 self.G.add_edge(edge[self.ou
t_node_index], edge[self.in_node_index],{'weight':weight}) else: for edge in self.list_edges: self.G.add_edge(edge[self.out_node_index], edge[self.in_node_index]) # ------------------------------------------------------------- # # save_network () # ...
mapr/impala
tests/stress/test_ddl_stress.py
Python
apache-2.0
3,153
0.011418
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, 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 requir...
, 1), (2, 2), (3, 3), (4, 4), (4, 4)" % tbl_name) # Cache the data the unpartitioned table self.client.execute("alter table %s set cached in 'testPool'" % tbl_name) # Cache, uncache, then re-cache the data in the partitioned table. self.client.execute("alter table %s_part set cached in 'tes
tPool'" % tbl_name) self.client.execute("alter table %s_part set uncached" % tbl_name) self.client.execute("alter table %s_part set cached in 'testPool'" % tbl_name) # Drop the tables, this should remove the cache requests. self.client.execute("drop table %s" % tbl_name) self.client.execut...
boryas/eidetic
lib/forget.py
Python
mit
226
0.00885
import rethinkdb as r import db def _forget_project(name, conn): db.get_table().filter(r.row['name'] == name).delete().run
(conn) def forget_project(name): conn = db.get_conn() return _forge
t_project(name, conn)
chfw/pyexcel
tests/test_bug_fixes.py
Python
bsd-3-clause
15,003
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from datetim
e import datetime from textwrap impo
rt dedent import psutil import pyexcel as p from _compact import StringIO, OrderedDict from nose.tools import eq_ def test_bug_01(): """ if first row of csv is shorter than the rest of the rows, the csv will be truncated by first row. This is a bug "a,d,e,f" <- this will be 1 '1',2,3,4 <- 4 ...
staticaland/trips
trips/cli.py
Python
mit
302
0
# -*- coding: utf-8 -*- import click from trips import oslo @click.command() @click.argument('from_place') @click.argument('to_place') def main(from_place, to_place): proposals = oslo.proposals(from_place, to_place) oslo.pr
int_proposals(proposals) if __name__ == "__main__":
main()
georgetown-analytics/classroom-occupancy
SensorDataCollection/Sensors/Asynchronous/DoorSensor.py
Python
mit
2,071
0.021246
import spidev import RPi.GPIO as GPIO import time class DoorSensor: def __init__(self, pin = None, verbose = False, dblogger = None): self.results = () self.device = None self.pin = pin self.dblogger = dblogger self.verbose = verbose # assign default pin if none provided if self.pin == ...
ef logLastReading(self, dblogger): cursor = dblogger.cursor conn = dblogger.conn loc = dblogger.location tstamp = int(round(time.time
() * 1000)) cmd = "INSERT INTO Door (timestamp, location, door_status) VALUES (%s, %s, %s);" cursor.execute(cmd, (tstamp, loc, self.results[0])) conn.commit() def getLastReading(self): return self.results def cleanUp(self): GPIO.cleanup() if __name__ == '__main__': # initialize different se...
ssplatt/slack-zenoss
ZenPacks/community/Slack/interfaces.py
Python
gpl-2.0
960
0.001042
###################################################################### # # Copyright 2012 Zenoss, Inc. All Rights Reserved. # ###################################################################### from zope.interface import Interface try: from Products.Zuul.interfaces.actions import IActio
nContentInfo ex
cept ImportError: from Products.Zuul import IInfo as IActionContentInfo from Products.Zuul.interfaces import IFacade from Products.Zuul.form import schema from Products.Zuul.utils import ZuulMessageFactory as _t class ISlackActionContentInfo(IActionContentInfo): slackUrl = schema.TextLine( title=_t(u...
AustereCuriosity/astropy
astropy/table/tests/test_subclass.py
Python
bsd-3-clause
2,488
0
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # TEST_UNICODE_LITERALS from ... import table from .. import pprint class MyRow(table.Row): def __str__(self): return str(self.as_void()) class MyColumn(table.Column): pass class MyMaskedColumn(table.MaskedCo...
mes if name != 'params'] params = [key.lower() for key in sorted(self['params'])] return out + params def values(self): return [self[key] for key in self.keys()] class ParamsTable(table.Table): Row = ParamsRow def test_params_ta
ble(): t = ParamsTable(names=['a', 'b', 'params'], dtype=['i', 'f', 'O']) t.add_row((1, 2.0, {'x': 1.5, 'y': 2.5})) t.add_row((2, 3.0, {'z': 'hello', 'id': 123123})) assert t['params'][0] == {'x': 1.5, 'y': 2.5} assert t[0]['params'] == {'x': 1.5, 'y': 2.5} assert t[0]['y'] == 2.5 assert t[1...
DailyActie/Surrogate-Model
01-codes/tensorflow-master/tensorflow/python/framework/tensor_util_test.py
Python
mit
16,873
0.001008
# Copyright 2015 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...
.assertAllClose(np.array([10.0, 20.0, 30.0], dtype=np.float32), a) def testFloatTyped(self): t = tensor_util.make_tensor_proto([10.0, 20.0, 30.0], dtype=tf.float32) self.assertProtoEquals(""" dtype: DT_FLOAT tensor_shape { dim { size: 3 } } tensor_content: "\000\000 A\000\000\240A...
oat32, a.dtype) self.assertAllClose(np.array([10.0, 20.0, 30.0], dtype=np.float32), a) def testFloatTypeCoerce(self): t = tensor_util.make_tensor_proto([10, 20, 30], dtype=tf.float32) self.assertProtoEquals(""" dtype: DT_FLOAT tensor_shape { dim { size: 3 } } tensor_conten...
deedee1886-cmis/deedee1886-cmis-cs2
simpleprogram.py
Python
cc0-1.0
888
0.022523
first_name = raw_input("Typ
e your name here ") last_name = raw_input("Type your last name here ") print "Hello " + first_name +' '+last_name + " nice to meet you, welcome to the height conversion program" def info(): a = raw_input("type your height here: ") return a def height_in_inches(): heigh
t_in_inches = float(info()) * 0.39370 return height_in_inches def your_height_vs_average_height(): your_height_vs_average_height = float(height_in_inches()) - 69 return your_height_vs_average_height def main(): print "you are {} inches tall,{} is your height compared to the average height (69 inches)".format(st...
Southpaw-TACTIC/TACTIC
src/pyasm/application/maya/maya_builder_exec.py
Python
epl-1.0
2,188
0.00457
#!/usr/bin/python ########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way wit...
mp_dir(), ticket) info.set_tmpdir(tmpdir) info.set_user(Environment.get_user_name() ) info.set_ticket(ticket) info.set_up_maya(init=True) env = info.get_app_env() env.set_tmpdir(tmpdir) # create the file builder builder = info.get_builder() builder.execute(contents) ...
h = "%s/maya_render.ma" % env.get_tmpdir() info.get_app().save(filepath) from maya_introspect import MayaIntrospect introspect = MayaIntrospect() introspect.execute() session_xml = introspect.get_session_xml() # should reproduce glue!!! file = open("%s/session.xml" % env.get_tmpdir(), "w" ...
DanAurea/Trisdanvalwen
communication/ComAPI/packetLogin.py
Python
mit
1,024
0.037109
from struct import pack, unpack from time import time from communication.ComAPI.packet import Packet class PacketLogin(Packet): """Class for constructing binary data based on a common API between client / server.""" def __init__(self): super().__init__() self.packetID = 3 def encode(self, username, avatar...
r))) bContainer = bContainer.__add__(avatar.encode()) bContainer = bContainer.__add__(pack(">f", position[0]))
bContainer = bContainer.__add__(pack(">f", position[1])) bContainer = bContainer.__add__(pack(">f", position[2])) return bContainer
ixc/plata
examples/simple/views.py
Python
bsd-3-clause
1,810
0.001105
from django import forms from django.contrib import messages from django.core.exceptions import ValidationError from django.db.models import ObjectDoesNotExist from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.utils.translation import uge...
plata.shop.models import Order from simple.models import Product shop = Shop(Contact, Order, Discount) product_list = generic.ListView.as_view( queryset=Product.objects.filter(is_active=True), template_name='pro
duct/product_list.html', ) class OrderItemForm(forms.Form): quantity = forms.IntegerField(label=_('quantity'), initial=1, min_value=1, max_value=100) def product_detail(request, object_id): product = get_object_or_404(Product.objects.filter(is_active=True), pk=object_id) if request.method =...
tangowhisky37/RaspiPythonProjects
OpenCV/CaptureVideoStream/CaptureVideoStream_v0.21.py
Python
gpl-3.0
10,532
0.028959
#!/home/pi/.virtualenvs/cv2/bin/python from picamera.array import PiRGBArray from picamera import PiCamera import picamera from time import sleep import time import cv2 import numpy as np import sys import datetime import boto3 import subprocess import os import pyowm import commands import multiprocessing import thr...
******************************" for nomatch in temp2['UnmatchedFaces']: print "Faces either don't match or are a poor ma
tch" return #Main Code Section Starts Here face_cascade = cv2.CascadeClassifier('/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('/usr/local/share/OpenCV/haarcascades/haarcascade_eye.xml') #nose_cascade = cv2.CascadeClassifier('/home/pi/opencv-3.0.0/dat...
wateraccounting/wa
Collect/ETmonitor/Es_monthly.py
Python
apache-2.0
817
0.017136
# -*- coding: utf-8 -*- """ Created on Wed Jan 03 09:36:48 2018 @author: tih """ import os import sys from DataAccess import DownloadData def ma
in(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1): """ This function downloads monthly ETmonitor data Keyword arguments: Dir -- 'C:/file/to/path/' Startdate -- 'yyyy-mm-dd' Enddate -- 'yyyy-mm-dd' latlim -- [ymin, ymax] (values must be between -60 and 70) ...
rtdate, Enddate) Type = "es" # Download data DownloadData(Dir, Startdate, Enddate, latlim, lonlim, Type, Waitbar) if __name__ == '__main__': main(sys.argv)
sonymoon/algorithm
src/main/python/geeksforgeeks/tree/max-path-sum.py
Python
apache-2.0
707
0.010463
# -*- coding: utf-8 -*- from Node import Node res = float("-inf") # 只有顶层root节点才可能即经过左边 又经过右边 def maxPathSum(root): if not root: return 0 max_l = maxPathSum(root.left) max_r = maxPathSum(root.right) max_single = max(max(max_l, max_r) + root.data, root.data) max_top = max(max_single, ma...
de(2) root.right = Node(10); root.left.left = Node(20); root.left.right = Node(1); root.right.right = Node(-25); root.right.right.left = Node(3); root.righ
t.right.right = Node(4); maxPathSum(root) print res
FedoraScientific/salome-smesh
doc/salome/examples/quality_controls_ex20.py
Python
lgpl-2.1
708
0.018362
# Aspect Ratio 3D import SMESH_mechanic_tetra import SMESH smesh = SMESH_mechanic_tetra.smesh mesh = SMESH_mechanic_tetra.mesh salome = SMESH_mechanic_tetra.salome # Criterion : ASPECT RATIO 3D > 4.5 ar_margin = 4.5 aFilter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_AspectRatio3D, SMESH.FT_MoreThan, ar_margin) a...
print anIds[i], j = j + 1 pass print "" # create
a group aGroup = mesh.CreateEmptyGroup(SMESH.VOLUME, "Aspect Ratio 3D > " + `ar_margin`) aGroup.Add(anIds) salome.sg.updateObjBrowser(1)
vileopratama/vitech
src/addons/l10n_bo/__openerp__.py
Python
mit
656
0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Cubic ERP - Teradata SAC. (https://cubicerp.
com). { "name": "Bolivia - Accounting", "version": "2.0", "description": """ Bolivian accounting chart and tax localization. Plan contable boliviano e impuestos de acuerdo a disposiciones vigentes """,
"author": "Cubic ERP", "website": "https://cubicERP.com", 'category': 'Localization', "depends": ["account"], "data": [ "l10n_bo_chart.xml", "account_tax.xml", "account_chart_template.yml", ], "installable": True, }
PoornimaNayak/autotest-client-tests
linux-tools/perl_Carp_Clan/perl_Carp_Clan.py
Python
gpl-2.0
1,270
0.004724
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error class perl_Carp_Clan(test.test): """ Autotest module for testing basic functionality of perl_Carp_Clan @author Kumuda G <kumuda.govind@in.ibm.com> ##...
ure counter for the test. """ self.nfail = 0 loggin
g.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./perl-Carp-Clan.sh'], cwd="%s/perl_Carp_Clan" %(test_path)) ret...
erramuzpe/C-PAC
CPAC/GUI/interface/windows/dataconfig_window.py
Python
bsd-3-clause
16,681
0.020562
import wx from ..utils.generic_class import GenericClass from ..utils.constants import control, dtype import os import yaml import pkg_resources as p import sys ID_RUN_EXT = 11 ID_RUN_MEXT = 12 class DataConfig(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, title="CP...
hbox.Add( run_ext, 1, flag=wx.LEFT|wx.ALIGN_LEFT, border=10) buffer = wx.StaticTex
t(btnPanel, label = "\t\t\t\t") hbox.Add(buffer) cancel = wx.Button(btnPanel, wx.ID_CANCEL, "Cancel",(220,10), wx.DefaultSize, 0 ) self.Bind(wx.EVT_BUTTON, self.cancel, id=wx.ID_CANCEL) hbox.Add( cancel, 0, flag=wx.LEFT|wx.BOTTOM, border=5) load = wx.Button(btnPane...
thumbor/remotecv
tests/test_image_processor.py
Python
mit
1,812
0.000552
from unittest import TestCase from preggy import expect from remotecv.image_processor import ImageProcessor from tests import read_fixture class ImageProcessorTest(TestCase): def test_when_detector_unavailable(self): image_processor = ImageProcessor() with expect.error_to_happen(AttributeError):...
ect("feature", read_fixture("one_face.jpg")) expect(detect).Not.to_be_empty() def test_should_be_empty_when_invalid_image(self): image_processor = ImageProcessor() detect = image_processor.detect("all", b"asdas") expect(detect).to_be_empty() def te
st_should_ignore_gif(self): image_processor = ImageProcessor() detect = image_processor.detect("all", b"asdas") expect(detect).to_be_empty()
AdamISZ/CoinSwapCS
coinswap/csjson.py
Python
gpl-3.0
12,462
0.004574
import os import binascii import json from txjsonrpc.web.jsonrpc import Proxy from txjsonrpc.web import jsonrpc from twisted.web import server from twisted.internet import reactor try: from OpenSSL import SSL from twisted.internet import ssl except: pass from .base import (get_current_blockheight, CoinSwap...
off if total avail < max #is required for privacy (otherwise we leak our wallet balance in #this costless query). Note that the wallet can be funded while #the server is running. if available_funds < maximum_amount: status["busy"] = True status["maximum_amount"] =...
rce_chain"] = source_chain status["destination_chain"] = destination_chain status["cscs_version"] = cs_single().CSCS_VERSION status["fee_policy"] = self.fee_policy.get_policy() status["locktimes"] = {"lock_server": {"min": serverlockmin, ...
ecrespo/pyurldownload_file
pyurldownload_file.py
Python
gpl-3.0
906
0.027594
#!/usr/bin/python3 import requests import bs4 import sys url = input('Enter URL -> ') pattern = input('Enter search pattern-> ') html = requests.get(url) dir_download = "./download/" if html.text.find("400 Bad Request") != -1: print ("Bad Request") sys.exit() soup = bs4.BeautifulSoup(html.text) tags = soup(...
_file, "wb") as f: f.write(r.content) except ConnectionError: print("Can't
download file: {0}".format(file)) except HTTPError: print("Can't download file: {0}".format(file)) f.close()
Haikson/virtenviro
virtenviro/registration/urls_new.py
Python
apache-2.0
396
0.005051
# ~*~ coding: utf-8 ~*~ f
rom django.conf.urls import * import virtenviro.registration.views import django.contrib.auth.views urlpatterns = [ url(r'^signup/$', virtenviro.registration.views.signup), url(r'^login/$', django.contrib.auth.views.login, {"template_name": "virtenviro/accounts/login.html"}), url(r'^logout/$', django.contr...
n_login, name='logout'), ]
airodactyl/qutebrowser
qutebrowser/browser/webkit/webkittab.py
Python
gpl-3.0
30,341
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
found, text, flags, caller): """Call the given callback if it's non-None. Delays the call via a QTimer so the website is re-rendered in between. Args: callback: What to call found: If the text was found text: The text searched for flags: The flag...
xt = 'found' if found else "didn't find" # Removing FindWrapsAroundDocument to get the same logging as with # QtWebEngine debug_flags = debug.qflags_key( QWebPage, flags & ~QWebPage.FindWrapsAroundDocument, klass=QWebPage.FindFlag) if debug_flags != '0x0000': ...
abawchen/leetcode
solutions/062_unique_paths.py
Python
mit
837
0.002389
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? ...
if m == 0 or n == 0: return 0 paths = [[1 for x in range(n)] for x in range(m)] for i in range(1, m): for j in range(1, n): paths[i][j] = paths[i-
1][j] + paths[i][j-1] return paths[-1][-1]
tuxfux-hlp-notes/python-batches
archieves/batch-62/oop/movie.py
Python
gpl-3.0
538
0.031599
#!/usr/bin/python # inbuild - Except
ion - python exception - parent clas # InvalidAgeException - Child class class InvalidAgeException(Exception): def __init__(self,age): self.age = age def validate_age(age): if age > 18: return "welcome to the movie!!!" else: raise InvalidAgeException(age)
if __name__ == '__main__': age = input("please enter your age:") try: validate_age(age) except InvalidAgeException as e: print "Buddy!! Go home and sleep you are still {}".format(e.age) else: print validate_age(age)
SimplyAutomationized/python-snap7
example/read_multi.py
Python
mit
2,021
0.000495
""" Example ussage of the read_multi_vars function This was tested against a S7-319 CPU """ import ctypes import struct import snap7 from snap7.common import check_error from snap7.snap7types import S7DataItem, S7AreaDB, S7WLByte client = snap7.client.Client() client.connect('10.100.5.2', 0, 2) data_items = (S7Da...
ms: # create the buffer buffer
= ctypes.create_string_buffer(di.Amount) # cast the pointer to the buffer to the required type pBuffer = ctypes.cast(ctypes.pointer(buffer), ctypes.POINTER(ctypes.c_uint8)) di.pData = pBuffer result, data_items = client.read_multi_vars(data_items) for di in data_items: chec...
zacherytapp/wedding
weddingapp/apps/gallery/admin.py
Python
bsd-3-clause
269
0.022305
fro
m django.contrib import admin from .models import Gallery class GalleryAdmin(admin.ModelAdmin): list_display = ('title', 'gallery_image', 'alt_text', 'display_order', 'visibility') search_fields = ['title', 'alt_text'] admin.site.register(Gallery, GalleryAdmi
n)
rvs/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/lib/dbstate.py
Python
apache-2.0
3,081
0.009737
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 ...
ting, 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 limitations under the License. """ import os import tinctest from mpp.li
b.PSQL import PSQL from mpp.lib.gpdbverify import GpdbVerify from mpp.lib.config import GPDBConfig from mpp.models import MPPTestCase class DbStateClass(MPPTestCase): def __init__(self,methodName,config=None): if config is not None: self.config = config else: self.config =...
lgp171188/xpens
xpens/app/migrations/0005_make_description_optional_provide_default_value.py
Python
agpl-3.0
606
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0004_add_default_ordering_of_categories_by_name'), ] operations = [ migrations.AlterField(
model_name='category', name='description', field=models.TextField(default='', blank=True),
), migrations.AlterField( model_name='expense', name='description', field=models.TextField(default='', blank=True), ), ]
giraldeau/python-augeas
setup.py
Python
lgpl-2.1
420
0.045238
#!/usr/bin/env python """ setup.py file for augeas """ import os prefix = os.environ.get("prefix", "/usr") from distutils.core import setup setup (name = 'python-augeas', version = '0.3.0', autho
r = "Harald Hoyer", author_email = "augeas-devel@redhat.com", descri
ption = """Python bindings for Augeas""", py_modules = [ "augeas" ], url = "http://augeas.net/", )
google/iree
build_tools/kokoro/gcp_ubuntu/cmake/linux/riscv64/tests/lit.cfg.py
Python
apache-2.0
756
0
import os import sys import lit.formats import lit.llvm # Configuration file for the 'lit' test runner. lit.llvm.initialize(lit_config, config) config.name = "RISC-V tests" config.test_format = lit.formats.ShTest(True) config.suffixes = [".run"] config.environment["BUILD_RISCV_DIR"] = os.ge
tenv("BUILD_RISCV_DIR") config.environment["TEST_CMD"] = ( "%s -cpu rv64,x-v=true,x-k=true,vlen=256,elen=64,vext_spec=v1.0" " -L %s/sysroot " % (os.getenv("QEMU_RV64_BIN"), os.getenv("RISCV_TOOLCHAIN_ROOT"))) config.environment["TEST_MODULE_CMD"] = ( "%s %s/iree/tools/iree-run-module --driver=dylib" %...
ronment["TEST_CMD"], os.getenv("BUILD_RISCV_DIR"))) config.test_exec_root = os.getenv("BUILD_RISCV_DIR") + \ "/tests"
rduivenvoorde/QGIS
tests/src/python/test_python_repr.py
Python
gpl-2.0
15,282
0.003807
# -*- coding: utf-8 -*- """QGIS Unit tests for core additions From build dir, run: ctest -R PyPythonRepr -V .. note:: 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,...
ve, QgsCurvePolygon, QgsEllipse, QgsLineString, QgsMultiCurve, QgsRectangle, QgsExpression, QgsField, QgsError, QgsMimeDataUtils, QgsVector, QgsVect
or3D, QgsVectorLayer, QgsReferencedPointXY, QgsReferencedRectangle, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsClassificationRange, QgsBookmark, QgsLayoutMeasurement, QgsLayoutPoint, QgsLayoutSize, QgsUnitTypes, QgsConditionalStyle, QgsTa...
Starch/paperwork
src/paperwork/deps.py
Python
gpl-3.0
7,285
0.000549
#!/usr/bin/env python3 import locale import os import sys try: # suppress warnings from GI import gi gi.require_version('Gtk', '3.0') gi.require_version('Poppler', '0.18') gi.require_version('PangoCairo', '1.0') except: pass try: from gi.repository import GLib from gi.repository impor...
'ubuntu': ('tesseract-ocr-%s' % lang['tesseract']), }, ) ) return missing def find_missing_dict(lang): if os.name == "nt": return [] import enchant missing = [] try: enchant.request_dict(lang['aspell']) except: missin...
% lang['aspell']), 'fedora': ('aspell-%s' % lang['aspell']), 'gentoo': ('aspell-%s' % lang['aspell']), 'linuxmint': ('aspell-%s' % lang['aspell']), 'ubuntu': ('aspell-%s' % lang['aspell']), } ) ) retu...
Phlos/LASIF_scripts
lasif_code/ad_src_tf_phase_misfit.py
Python
gpl-3.0
13,183
0.00129
#!/usr/bin/env python # -*- coding: utf-8 -*- """ An implementation of the time frequency phase misfit and adjoint source after Fichtner et al. (2008). :copyright: Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013 :license: GNU General Public License, Version 3 (http://www.gnu.org/copyleft/gpl.html)...
pressed # exponentially) weight *= (1.0 - np.exp(-(nu_t * max_period) ** 2)) # lowpass filter (periods shorter than min_period are suppressed # exponentially) nu_t_large = np.zeros(nu_t.shape) nu_t_small = np.zeros(nu_t.shape) thres = (nu_t <= 1.0 / min_period) nu_t_large[np.invert(thre...
= weight.max() # computation of phase difference, make quality checks and misfit --------- # Compute the phase difference. # DP = np.imag(np.log(m + tf_cc / (2 * m + np.abs(tf_cc)))) DP = np.angle(tf_cc) # Attempt to detect phase jumps by taking the derivatives in time and # frequency directi...
non-official-SD/base
src/tools/ceguidemo/menumanager.py
Python
gpl-3.0
375
0.045333
#!/usr/bin/env python # -*- coding: utf-8 -*- """Menu manager. A dictionary of menu instan
ce() functions (see MenuFactory) """ class MenuManager: menus = { } def register(menuName, menuFactory): MenuManager.menus[menuName] = menuFactory register = stati
cmethod(register) def get(menuName): return MenuManager.menus[menuName]() get = staticmethod(get)
mizhi/tictic
xmpp.py
Python
gpl-2.0
3,475
0.010072
# Copyright (c) - 2013 Mitchell Peabody. # See COPYRIGHT.txt and LICENSE.txt in the root of this project. from functools import wraps import inspect import logging from google.appengine.api import xmpp, users from google.appengine.ext.webapp import xmpp_handlers from model import User, Variable, Value from nl import...
/<client>. I think. This may be wrong, but that's what it appears like in GoogleTalk. :param xmpp_sender: The sender of the message. :returns: email of the sender """ email = sender.split("/") return email[0] def describe(description, params = ""): def _describe(func): setattr(func...
description)) return func return _describe class XmppHandler(xmpp_handlers.CommandHandler): @describe("Disremembers the user.") def forget_command(self, message = None): email = extract_email(message.sender) try: sender = users.User(email) exce...
mairin/anaconda
pyanaconda/ntp.py
Python
gpl-2.0
6,933
0.001731
# # Copyright (C) 2012-2013 Red Hat, Inc. # # This copyrighted material i
s 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 option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Genera...
joke2k/faker
faker/providers/color/color.py
Python
mit
10,362
0.000676
"""Internal module for human-friendly color generation. .. important:: End users of this library should not use anything in this module. Code adapted from: - https://github.com/davidmerfield/randomColor (CC0) - https://github.com/kevinwuhoo/randomcolor-py (MIT License) Additional reference from: - https://en.wi...
nge"] = [(b_min, b_max)] def generate( self, hue: Optional[HueType] = None,
luminosity: Optional[str] = None, color_format: str = "hex", ) -> str: """Generate a color. Whenever :meth:`color() <faker.providers.color.Provider.color>` is called, the arguments used are simply passed into this method, and this method handles the rest. """...
cineuse/CNCGToolKit
apps/pw_multiScriptEditor/widgets/numBarWidget.py
Python
mit
3,802
0.00263
from PySide.QtCore import * from PySide.QtGui import * import managers class lineNumberBarClass(QWidget): def __init__(self, edit, parent=None): QWidget.__init__(self, parent) self.edit = edit self.highest_line = 0 self.setMinimumWidth(30) self.edit.installEventFilter(self) ...
ontext == 'hou': fontSize = self.edit.fs font = QFont('monospace', fontSize*0.7) offset = (font_metrics.ascent() + font_metrics.descent())/2 else: fontSize = self.edit.font().pointSize()
font = painter.font() font.setPixelSize(fontSize) offset = font_metrics.ascent() + font_metrics.descent() color = painter.pen().color() painter.setFont(font) align = Qt.AlignRight while block.isValid(): line_count += 1 # The top le...
datagutten/comics
comics/comics/axecop.py
Python
agpl-3.0
766
0
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_d
ata import ComicDataBase class ComicData(ComicDataBase): name = 'Axe Cop' language = 'en'
url = 'http://www.axecop.com/' start_date = '2010-01-02' rights = 'Ethan Nicolle' class Crawler(CrawlerBase): history_capable_days = 60 schedule = 'Tu' time_zone = 'US/Pacific' headers = {'User-Agent': 'Mozilla/4.0'} def crawl(self, pub_date): feed = self.parse_feed('http://a...
astrofrog/ginga
ginga/LayerImage.py
Python
bsd-3-clause
7,562
0.003835
# # LayerImage.py -- Abstraction of an generic layered image. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import numpy import time import Bunch import BaseImage ...
yers and alpha/rgb compositing. """ def __init__(self): self._layer = [] self.cnt = 0 self.compose_types = ('alpha', 'rgb') self.compose = 'alpha' def _insertLayer(self, idx, image, alpha=None, name=None): if alpha == None: alpha = 1.0 if nam...
(self.cnt) self.cnt += 1 bnch = Bunch.Bunch(image=image, alpha=alpha, name=name) self._layer.insert(idx, bnch) def insertLayer(self, idx, image, alpha=None, name=None, compose=True): self._insertLayer(idx, image, alpha=alpha, name=name) if compose: ...
vandorjw/notes
vandorjw/vandorjw/urls.py
Python
mit
1,049
0.00286
from django.conf.urls import patterns, include, url from django.contrib import admin from .sitemap import BlogSitemap from .views import RobotPageView, HumanPageView, GooglePageView admin.autodiscover() sitemaps = { 'blog': BlogSitemap, } urlpatterns = patterns('', url( regex=r"^robots\.txt$", ...
GooglePageView.as_view(), name="google_webmasters", ), url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sit
emaps': sitemaps}), url(r'^admin/', include(admin.site.urls)), url(r'^browserid/', include('django_browserid.urls')), url(r"^contact/$", include('contact.urls', namespace='contact', app_name='contact')), url(r'^tinymce/', include('tinymce.urls')), url(r"^", include('blog.urls', namespace='blog', app...
davidwboswell/documentation_autoresponse
lib/bedrock_util.py
Python
mpl-2.0
995
0.001005
# This Source Code Form is subject to the terms of the Mozilla Public # License,
v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.conf import settings from django.http import Htt
pResponseRedirect import l10n_utils def secure_required(view_func): """Decorator makes sure URL is accessed over https.""" def _wrapped_view_func(request, *args, **kwargs): if not request.is_secure(): if not getattr(settings, 'DEBUG', True): request_url = request.build_abs...
blzr/enigma2
lib/python/Screens/PVRState.py
Python
gpl-2.0
224
0.017857
from Screen import Screen from Components.Label import Label class PVRState(Screen): def __init__(self, session): Screen.__init__(self, session) self["state"] = Label(text="") class Ti
meshiftState(PVRS
tate): pass
thoas/django-fairepart
fairepart/settings.py
Python
mit
354
0.002825
from django.conf import setting
s BACKENDS = getattr(settings, 'FAIREPART_BACKENDS', ( 'fairepart.backends.facebook.FacebookBackend', 'fairepart.backends.google.GoogleOAuth2Backend', )) RELATION_LIST_PAGINATE_BY = getattr(settings, 'FAIREPART_RELATION_LIST_PAGINATE_BY', 5) GOOGLE_APP_NAME = getattr(settings,
'FAIREPART_GOOGLE_APP_NAME', '')
mperignon/component_creator
topoflow_creator/topoflow/met_base.py
Python
gpl-2.0
109,509
0.01031
## Does "land_surface_air__latent_heat_flux" make sense? (2/5/13) # Copyright (c) 2001-2014, Scott D. Peckham # # Sep 2014. Fixed sign error in update_bulk_richardson_number(). # Ability to compute separate P_snow and P_rain. # Aug 2014. New CSDMS Standard Names and clean up. # Nov 2013. Con...
) # --------------------- # set_constants() # initialize() # update() # finalize() # ---------------------------- # set_computed_input_vars() # initialize_computed_vars() # ---------------------------- # update_P_integral() # update_P_max() # updat...
) # update_P_snow() # (9/14/14, new method) # ------------------------------------ # update_bulk_richardson_number() # update_bulk_aero_conductance() # update_sensible_heat_flux() # update_saturation_vapor_pressure() # update_vapor_pressure() # update_dew_point() ...
brain-tec/partner-contact
partner_external_map/__init__.py
Python
agpl-3.0
90
0
# -*- coding: utf-8 -*- from . import models
from .hooks import set_def
ault_map_settings
reubano/ckanutils
ckanutils.py
Python
mit
29,704
0.000135
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ ckanutils ~~~~~~~~~ Provides methods for interacting with a CKAN instance Examples: literal blocks:: python example_google.py Attributes: CKAN_KEYS (List[str]): available CKAN keyword arguments. """ from __future__ import ( absolute_import...
ools as it from os import environ, path as p from datetime import datetime as dt from operator import itemgetter from pprint import pprint from ckanapi import NotFound, NotAuthorize
d, ValidationError from tabutils import process as pr, io, fntools as ft, convert as cv __version__ = '0.14.9' __title__ = 'ckanutils' __author__ = 'Reuben Cummings' __description__ = 'Miscellaneous CKAN utility library' __email__ = 'reubano@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2015 Reuben Cummin...
mola/jalali-calendar
src/holiday.py
Python
gpl-2.0
1,532
0.106397
#!/usr/bin/env python ### # # Co
pyright (C) 2007 Mola Pahnadayan # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2
of the License, or # (at your option) any later version. # # This program is distributed in 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. # # ...
PyLadiesCZ/pyladies.cz
original/v1/s007-cards/klondike/test_popis_karty.py
Python
mit
1,114
0.000907
import pytest import klondike def test_popis_rubem_nahoru(): karta = 13, 'Pi', False assert klondike.popis_karty(karta) == '[???]' def test_popis_srdcova_kralovna(): karta = 12, 'Sr', True assert klondike.popis_karty(karta) in ['[Q ♥]', '[Q S]'] def test_otoc_kralovnu(): karta = 12, 'Sr', True...
nota, znak): karta = hodnota, 'Sr', True assert klondike.popis_karty(karta)
in ['[' + znak + ' ♥]', '[' + znak + ' S]']
pyblub/pyload
pyload/utils/parse.py
Python
agpl-3.0
4,211
0
# -*- coding: utf-8 -*- # @author: vuolter from __future__ import absolute_import, unicode_literals import os import re from future import standard_library from pyload.utils import convert, purge, web from pyload.utils.convert import to_str from pyload.utils.layer.legacy import hashlib from pyload.utils.time import...
it=None): # returns integer bytes DEFAULT_INPUTUNIT = 'byte' m = _RE_SIZE.match(to_str(text)) if m is None: return None if unit is None: unit = m.group('U') or DEFAULT_INPUTUNIT size = float(m.group('S').replace(',', '.')) unit = unit[0].lower()
return int(convert.size(size, unit, 'byte')) _TIMEWORDS = ('this', 'a', 'an', 'next') _TIMEMAP = { 'day': 60 ** 2 * 12, 'hr': 60 ** 2, 'hour': 60 ** 2, 'min': 60, 'sec': 1} _RE_TIME = re.compile(r'(\d+|[a-zA-Z-]+)\s*(day|hr|hour|min|sec)|(\d+)') def seconds(text): def to_int(obj): try: ...
alexjh/whatson
whats_on_to_simpledb.py
Python
gpl-2.0
9,735
0.009245
#!/usr/bin/python """Scrapes websvc and adds them to SimpleDB""" from __future__ import print_function import boto import time import datetime import re import pytz import sys import urllib import collections import yaml from musicbrainz2.webservice import Query, TrackFilter, WebServiceError, \ ...
nt(domain.name, item.name, item) try: last_song_time = int(item.name, 16) break except ValueError: invalid_item = domain.get_item(item.name) print("Deleting", item.name) domain.delete_item( invalid_item ) # print("Last song: ", int(item...
else: last_song_time = 0 return last_song_time def get_timestamps( source, timezone ): timestamps = collections.OrderedDict() song_times = re.findall('<option value=\"(.*?)\">(.*?)<\/option>', source) if ( len(song_times) == 0 ): return timestamp...
PyLearner/tp-qemu
qemu/tests/qmp_basic_rhel6.py
Python
gpl-2.0
14,327
0
import logging from autotest.client.shared import error def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depend heavily on QMP'...
"]["class"], classname)) check_key_is_dict(resp["error"], "data") if datadict and resp["error"]["data"] != datadict: raise error.TestFail("got data dict '%s' expected '%s'" % (resp["error"]["data"], datadict)) def test_version(version): """ ...
u": { "major": json-int, "minor": json-int, "micro": json-int } "package": json-string } """ check_key_is_dict(version, "qemu") check_key_is_str(version, "package") def test_greeting(greeting): check_key_is_dict(greeting, "QMP") check_key_is_dict(greeting["QMP"], "...
AccentDesign/wagtailstreamforms
wagtailstreamforms/models/abstract.py
Python
mit
318
0
from django.db impor
t models class AbstractFormSetting(models.Model): form = models.OneToOneField( "wagtailstreamforms.Form", on_delete=models.CASCADE, related_name="advanced_settings", ) class Meta: abstract = True def __str__(self):
return self.form.title
ptisserand/portage
pym/_emerge/search.py
Python
gpl-2.0
13,055
0.035619
# Copyright 1999-2014 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 from __future__ import unicode_literals import re import portage from portage import os from portage.dbapi.porttree import _parse_uri_map from portage.dbapi.IndexedPortdb import IndexedPortdb from portage.dbapi....
f func: value = func(*args, **kwargs) if value: return value return None def _getFetchMap(self, *args, **kwargs): for db in self._dbs: func = getattr(db, "getFetchMap", None) if func: value = func(*args, **kwargs) if value: return value return {} def _visible(self, db, cpv, met...
tdb pkg_type = "ebuild" if installed: pkg_type = "installed" elif built: pkg_type = "binary" return Package(type_name=pkg_type, root_config=self.root_config, cpv=cpv, built=built, installed=installed, metadata=metadata).visible def _first_cp(self, cp): for db in self._dbs: if hasattr(db, ...
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/python/mxnet/module/module.py
Python
apache-2.0
37,421
0.003233
# 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...
'data')` for a typical model used in image classification. label_
names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Defaul...
bl4ckdu5t/registron
tests/import/relimp/relimp1.py
Python
mit
795
0.005031
#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this softwa...
-------------------------
---------------- from __future__ import absolute_import name = 'relimp.relimp1' from . import relimp2 as upper from . relimp import relimp2 as lower assert upper.name == 'relimp.relimp2' assert lower.name == 'relimp.relimp.relimp2' if upper.__name__ == lower.__name__: raise SystemExit("Imported the same modul...
depp/sglib
script/d3build/msvc/base.py
Python
bsd-2-clause
1,042
0
# Copyright 2014 Dietrich Epp. # This file is part of SGLib. SGLib is licensed under the terms of the # 2-clause BSD license. For more information, see LICENSE.txt. BASE_CONFIG = { 'Config.PlatformToolset': 'v120', 'Config.CharacterSet': 'Unicode', 'ClCompile.WarningLevel': 'Level3', 'ClCompile.SDLCh...
ebugLibraries': True, 'VC.LinkIncremental': True, 'ClCompile.Optimization': 'Disabled', 'ClCompile.PreprocessorDefinitions': ['WIN32', '_DEBUG', '_WINDOWS'], } RELEASE_CONFIG = { 'Config.WholeProgramOptimization': True, 'Config.UseDebugLibraries': False, 'VC.LinkIncremental': False, 'ClComp...
initions': ['WIN32', 'NDEBUG', '_WINDOWS'], 'Link.GenerateDebugInformation': True, 'Link.EnableCOMDATFolding': True, 'Link.OptimizeReferences': True, }
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractNotoriousOnlineBlogspotCom.py
Python
bsd-3-clause
569
0.033392
def extractNotoriousOnlineBlogspotCom(item): ''' Parser for 'notorious-online.blogs
pot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type ...
=postfix, tl_type=tl_type) return False
whatisjasongoldstein/beagle
beagle/__init__.py
Python
mit
52
0
from .app import App fr
om .decorators
import action
sven-hm/pythonocc-core
src/addons/Display/WebGl/threejs_renderer.py
Python
lgpl-3.0
12,135
0.003049
##Copyright 2011-2014 Thomas Paviot (tpaviot@gmail.com) ## ##This file is part of pythonOCC. ## ##pythonOCC 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 of the License, or ##(at your...
var mouseXOnMouseDown = 0; var mouseY = 0; var mouseYOnMouseDown = 0; var moveForward = false; var moveBackward = false; var moveLeft = false; var moveRight = false; var moveUp = false; var moveDow
n = false; var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); camera = new THREE.Perspe...
hoevenvd/weewx_poller
bin/weewx/almanac.py
Python
gpl-3.0
17,450
0.009685
# # Copyright (c) 2009, 2011, 2012 Tom Keffer <tkeffer@gmail.com> # # See the file LICENSE.txt for your full rights. # # $Revision: 1046 $ # $Author: tkeffer $ # $Date: 2013-02-21 06:38:26 -0800 (Thu, 21 Feb 2013) $ # """Almanac data This module can optionally use PyEphem, which offers high quality astr...
If the module 'ephem' is used, them many other attributes are available. Here are a few examples: sun.rise: Time upper limb of sun will rise above the
horizon today in unix epoch time sun.transit: Time of transit today (sun over meridian) in unix epoch time sun.previous_sunrise: Time of last sunrise in unix epoch time sun.az: Azimuth (in degrees) of sun sun.alt: Altitude (in degrees) of sun mars.rise: Time when upper limb of m...
rogeriofalcone/treeio
sales/migrations/0003_treeiocurrency.py
Python
mit
30,418
0.007594
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license # encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models from treeio.finance.models import Currency from treeio.sales.models import SaleOrder,...
[], {'blank': 'True', 'related_name': "'child_set'", 'null': 'True', 'to': "orm['core.Group']"}) }, 'core.object': { 'Meta': {'object_name': 'Object'}, 'comments': ('django.db.models.fields.r
elated.ManyToManyField', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['core.Comment']"}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'objects_created'", 'null': 'True', 'to': "orm['core.User']"}),...
artem-smotrakov/httpooh
config.py
Python
gpl-3.0
285
0.003509
#!/usr/bin/python # contains configuration, parameters can be acces
sed as attributes class Config:
# init from argparse.ArgumentParser def __init__(self, parser): self.args = vars(parser.parse_args()) def __getattr__(self, name): return self.args[name]
vlttnv/scrimfinder2
scrim2/views/home.py
Python
gpl-2.0
2,491
0.00562
from flask import Blueprint, render_template, json, g, current_app, redirect, url_for, session from datetime import datetime as dt from scrim2.extensions import oid, db, lm from scrim2.models import User from sqlalchemy.orm.exc import NoResultFound from flask.ext.login import login_user, logout_user, current_user impor...
_.28v0002.29 """ api = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?' params = { 'key': current_app.config['STEAM_API_KEY'], 'steamids': steam_id, 'format': json } user_info = requests.get(url=api, params=params) user_in
fo_json = user_info.json() return user_info_json['response']['players'][0] or {}
caioserra/apiAdwords
examples/adspygoogle/dfa/v1_19/get_user_roles.py
Python
apache-2.0
2,451
0.008568
#!/usr/bin/python # # Copyright 2012 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 b...
'..', '..', '..', '..')) # Import appropriate classes fro
m the client library. from adspygoogle import DfaClient def main(client): # Initialize appropriate service. user_role_service = client.GetUserRoleService( 'https://advertisersapitest.doubleclick.net', 'v1.19') # Set user role search criteria. user_role_search_criteria = { 'pageSize': '10' } ...
cherepaha/PyDLV
demos/plot_compare_dlv_three_blocks.py
Python
gpl-3.0
2,266
0.01015
import pandas as pd from matplotlib import cm import matplotlib.pyplot as plt from pydlv import dl_model_3, data_reader, data_analyser, dl_generator, dl_plotter, trajectory_plotter ''' This script demonstrates how, using coefficients from the csv file generated previously, plot a 3d surface of decision landscapes fitt...
dlp.plot_surface(x, y, dl, color=colors[i], alpha=0.8) dlp.add_legend(colors, labels) plt.savefig('figures/blocks_%i_dlv.pdf' % (subj_id)) def plot_trajectories(data, subj_id, blocks, colors, labels): tp = trajectory_plotter.TrajectoryP
lotter() for i, block_no in enumerate(blocks): block_trajectories = data[(data.subj_id==subj_id) & (data.block_no==block_no)] tp.plot_mean_trajectories(block_trajectories, colors[i], labels[i]) block_info = block_trajectories.groupby('trial_no').first().groupby('high_chosen') \ ...
timkpaine/lantern
lantern/plotting/plot_bokeh.py
Python
apache-2.0
5,812
0.001721
import copy import pandas as pd from bokeh.plotting import figure, show, output_notebook from bokeh.models import Legend, Span # from bokeh.models import HoverTool from ..utils import in_ipynb from .plotobj import BasePlot from .plotutils import get_color _INITED = False class BokehPlot(BasePlot): def __init__(s...
continue # don't scatter against self x = data.columns[0] y = data.columns[i] c = get_color(i, col, color) fig = self.figure.scatter(x=data[x], y=data[y], legend='%s vs %s' % (x, y), ...
fstagni/DIRAC
FrameworkSystem/scripts/dirac-status-component.py
Python
gpl-3.0
1,235
0.008097
#!/usr/bin/env python """ Status of DIRAC components using runsvstat utility """ # from __future__ import print_function from DIRAC.Core.Base import Script Script.disableCS() Script.setUsageMessage('\n'.join([__doc__.split('\n')[1], 'Usage:', ' %s [...
vice|agent: Name of the particular component (default *: all)'])) Script.parseCommandLine() args = Script.getPositionalArgs() from DIRAC.FrameworkSystem.Client.ComponentInstaller import gComponentInstaller __RCSID__ = "$Id$" if len(args) > 2: Script.showHelp() exit(-1) system
= '*' component = '*' if len(args) > 0: system = args[0] if system != '*': if len(args) > 1: component = args[1] # gComponentInstaller.exitOnError = True # result = gComponentInstaller.getStartupComponentStatus([system, component]) if not result['OK']: print('ERROR:', result['Message']) exit(-1) gComponen...
tfroehlich82/saleor
saleor/product/migrations/0021_add_hstore_extension.py
Python
bsd-3-clause
312
0
from __future__ import unicode_literals from django.db import migrations from django.contrib.postgres.operations import H
StoreExtension class Migration(migrations.Migration): dependencies = [ ('product', '0020_attribute_data_to_clas
s'), ] operations = [ HStoreExtension(), ]
tyagow/AdvancingTheBlog
src/comments/forms.py
Python
mit
304
0.016447
from django i
mport forms class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.CharField(widget=forms.HiddenInput) parent_id = forms.IntegerField(w
idget=forms.HiddenInput, required=False) content = forms.CharField(label='',widget=forms.Textarea)