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 |
|---|---|---|---|---|---|---|---|---|
nextgis/nextgisweb_compulink | nextgisweb_compulink/compulink_site/view.py | Python | gpl-2.0 | 32,980 | 0.003015 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
import os
from os import path, mkdir
from shutil import rmtree
import tempfile
from zipfile import ZipFile, ZIP_DEFLATED
import codecs
import geojson
from osge... | eInfo
from nextgisweb_compulink.compulink_reporting.utils import OverdueStatusCalculator
from ..compulink_admin.layers_struct_group import FOCL_LAYER_STRUCT, SIT_PLAN_LAYER_STRUCT, FOCL_REAL_LAYER_STRUCT,\
OBJECTS_LAYER_STRUCT, ACTUAL_FOCL_REAL_LAYER_STRUCT
from ..compulink_admin.model import SituationPlan, FoclStr... | OJECT_STATUS_BUILT, FoclStructScope, Region, District, ConstructObject
from ..compulink_admin.well_known_resource import DICTIONARY_GROUP_KEYNAME
from .. import compulink_admin
from ..compulink_admin.view import get_region_name, get_district_name, get_regions_from_resource, \
get_districts_from_resource, get_projec... |
MSusik/invenio | invenio/ext/fs/cloudfs/onedrivefs.py | Python | gpl-2.0 | 30,405 | 0.001348 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU Ge | neral Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio 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 PARTICUL... | more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
OneDrive file system
--------------------
Known issues:
* Flush and close, b... |
trosa/forca | gluon/storage.py | Python | gpl-2.0 | 5,865 | 0.002728 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowi... | ('lock_keys', None)\
and not key in self:
raise SyntaxError, 'setting key \'%s\' does not exist' % key
if key != 'lock_values' and self.get('lock_values', None):
raise Syn | taxError, 'setting value cannot be changed: %s' % key
self[key] = value
class Messages(Storage):
def __init__(self, T):
self['T'] = T
def __setattr__(self, key, value):
if key != 'lock_keys' and self.get('lock_keys', None)\
and not key in self:
raise SyntaxEr... |
thomersch/Mikrowelle-OS | util/search.py | Python | bsd-2-clause | 386 | 0.041451 | import json
import sys
if sys.version_info < (3, 0, 0) | :
from codecs import open
def build_index(posts, path):
index = []
for post in posts:
index.append({
"episode": post["episode"],
"date": post["date"],
"title": post[" | title"],
"subtitle": post["subtitle"],
"content": post["content"]
})
with open(path, "a+", encoding="utf-8") as f:
json.dump(index, f)
|
aronsky/home-assistant | homeassistant/components/cisco_ios/device_tracker.py | Python | apache-2.0 | 4,678 | 0.000641 | """Support for Cisco IOS Routers."""
import logging
import re
from pexpect import pxssh
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CO... | col Address | Age (min) | Hardware Addr | Type | Interface
lines_result = lines_result[2:]
for line in lines_result:
parts = line.split()
if len(parts) != 6:
continue
| # ['Internet', '10.10.11.1', '-', '0027.d32d.0123', 'ARPA',
# 'GigabitEthernet0']
age = parts[2]
hw_addr = parts[3]
if age != "-":
mac = _parse_cisco_mac_address(hw_addr)
age = int(age)
... |
praekelt/rapidpro | temba/middleware.py | Python | agpl-3.0 | 5,397 | 0.002223 | from __future__ import absolute_import, unicode_literals
import traceback
from django.db import transaction
from django.utils import timezone, translation
from temba.orgs.models import Org
from temba.contacts.models import Contact
from temba.settings import BRANDING, DEFAULT_BRAND, HOSTNAME
class ExceptionMiddlewar... | stats.Stats.sort_stats
for all so | rt options.
?count => The number of rows to display. Default is 100.
This is adapted from an example found here:
http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation.
"""
def can(self, request):
return settings.DEBUG and 'prof' in request.GET
def process_view... |
obi-two/Rebelion | data/scripts/templates/object/tangible/ship/crafted/chassis/shared_tieinterceptor_deed.py | Python | mit | 479 | 0.045929 | #### NOTICE: THIS FILE IS AUTOGE | NERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/chassis/shared_tieinterceptor_deed.iff"
result.attribute_template_id = 8
result.stfNa... | NS ####
return result |
praekelt/vumi-go | go/vumitools/contact/models.py | Python | bsd-3-clause | 16,310 | 0 | # -*- test-case-name: go.vumitools.tests.test_contact -*-
from uuid import uuid4
from datetime import datetime
from twisted.internet.defer import returnValue
from vumi.persist.model import Model, Manager
from vumi.persist.fields import (
Unicode, ManyToMany, ForeignKey, Timestamp, Dynamic)
from go.vumitools.acco... | f is_s | mart_group(self):
return self.query is not None
def __unicode__(self):
return self.name
class Contact(Model):
"""A contact"""
VERSION = 2
MIGRATOR = ContactMigrator
# key is UUID
user_account = ForeignKey(UserAccount)
name = Unicode(max_length=255, null=True)
surname... |
benoitbryon/django-confit | django_confit/schemas/raven/contrib/django/raven_compat.py | Python | bsd-3-clause | 713 | 0 | """Configuration schema(s) for Raven."""
import colander
class ConfigurationSchema(colander.Schema):
"""Configuration for Raven, the official Sentr | y client."""
RAVEN_CONFIG = colander.SchemaNode(
colander.Mapping(unknown='raise'),
missing=colander.required,
default=colander.null,
| children=[
colander.SchemaNode(
colander.String(),
name='dsn',
missing=colander.required,
default=colander.null,
)
]
)
SENTRY_CLIENT = colander.SchemaNode(
colander.String(),
missing=colander.drop,
... |
geometalab/djangocms-interactiveimage | admin.py | Python | mit | 1,767 | 0.001132 | from django.contrib import admin
from django.template.response import SimpleTemplateResponse
from django.utils.translation import ugettext_lazy as _
from .forms import InteractivePointForm
from .models import InteractivePoint
IS_POPUP_VAR = '_popup'
ACTION_VAR = '_action'
POINT_ID_VAR = '_point_id'
class Interactiv... | # Return empty perms dict thus hiding the model from admin index
return {}
def response_add(self, request, value, post_url_continue=None):
if IS_POPUP_VAR in request.POST:
return self.response_popup(request, value)
else:
| super().response_add(request, value, post_url_continue)
def response_change(self, request, value):
if IS_POPUP_VAR in request.POST:
return self.response_popup(request, value)
else:
super().response_change(request, value)
def response_delete(self, request, value):
... |
zhkzyth/a-super-fast-crawler | scheduler/spider_sched.py | Python | mit | 834 | 0.009592 | #!/usr/bin/env python
#encoding:utf-8
"""
spider-scheduler.py
"""
import datetime
import os
import sys
PROJECT_ROOT = os.path.dirname(os.pa | th.dirname(os.path.realpath(__file__)))+'/crawler/'
sys.path.insert(0, PROJECT_ROOT)
import scheduler
from crawler import application
#set our spider task here.
#TODO may crontab better?
spider_task = scheduler.Task("spider",
datetime.datetime.now(),
schedule... | ntilSuccess(application.main, num_tries=5))
#set up scheduler to distribute tasks
spider_scheduler = scheduler.Scheduler()
spider_id = spider_scheduler.schedule_task(spider_task)
spider_scheduler.start()
# Give it a timeout to halt any running tasks and stop gracefully
spider_scheduler.join()
|
Pierre-Sassoulas/django-survey | survey/tests/models/test_survey.py | Python | agpl-3.0 | 1,428 | 0 | from datetime import date
from django.core.validators import URLValidator
from django.utils.timezone import now
from survey.tests.models import BaseModelTest
class TestSurvey(BaseModelTest):
def test_unicode(self):
"""Unicode generation."""
self.assertIsNotNone(str(self.survey))
def test_qu... | date)
def test_expiration_date(self):
"""expirationdate must be datetime date instance or None"""
self.assertIsInstance(self.survey.expire_date, date)
def test_expiration_date_is_in_future(self):
"""by default the expiration should be a week in the future"""
| self.assertGreater(self.survey.expire_date, now())
def test_redirect_url(self):
self.assertIsNone(URLValidator()(self.survey.redirect_url))
|
lcpt/xc | verif/tests/materials/geom_section/test_quad_region_02.py | Python | gpl-3.0 | 1,612 | 0.029795 | # -*- coding: utf-8 -*-
# Home made test
import xc_base
import geom
import xc
from model import predefined_spaces
from materials import typical_materials
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.perez... | 3= ((G[1]-zGTeor)/zGTeor)
ratio4= ((Iy-iTeor)/iTeor)
ratio5= ((Iz-iTeor)/iTeor)
'''
print "area= ",area
print "G= ",G
print "Iy= ",Iy
print "Iz= ",Iz
print "iTeor= ",iTeor
print "Pyz= ",Pyz
print "ratio1= ",ratio1
print "ratio2= ",ratio2
print "ratio | 3= ",ratio3
print "ratio4= ",ratio4
print "ratio5= ",ratio5
'''
import os
from miscUtils import LogMessages as lmsg
fname= os.path.basename(__file__)
if (abs(ratio1)<1e-15) & (abs(ratio2)<1e-15) & (abs(ratio3)<1e-15) & (abs(ratio4)<1e-15) & (abs(ratio5)<1e-15) :
print "test ",fname,": ok."
else:
lmsg.error(fname+... |
pythonsingapore/pythonsingapore | website/webapps/django/myproject/user_data/admin.py | Python | mit | 243 | 0 | """Admin sit | es for the ``user_data`` app."""
from django.contrib import admin
from user_data import models
class UserProfileAdm | in(admin.ModelAdmin):
raw_id_fields = ('user', )
admin.site.register(models.UserProfile, UserProfileAdmin)
|
coreboot/chrome-ec | util/flash_jlink.py | Python | bsd-3-clause | 6,344 | 0.000315 | #!/usr/bin/env python3
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=logging-fstring-interpolation
"""Flashes firmware using Segger J-Link.
This script requires Segger hardware at... | 1
r
loadfile {FIRMWARE} { | FLASH_ADDRESS}
r
go
exit
"""
class BoardConfig:
"""Board configuration."""
def __init__(self, interface, device, flash_address):
self.interface = interface
self.device = device
self.flash_address = flash_address
SWD_INTERFACE = 'SWD'
STM32_DEFAULT_FLASH_ADDRESS = '0x8000000'
DRAGONCL... |
ProjectCloudly/cloudly | cloudly/context_processors.py | Python | mit | 2,445 | 0.01636 | # content processor functions
import datetime
from django.conf import settings
from django.contrib.auth.models import User
from userprofile.models import Profile
import pymongo
from pymongo import MongoClient
from pymongo import ASCENDING, DESCENDING
client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT)
... | new_notif['name'] = servers_names[notif['server_id']]
new_notif['service'] = notif['service']
try:
new_notif['date'] = notif['date']
except: new_notif['date'] = None
| server = mongo.servers.find_one({'uuid':notif['server_id'],})
if((datetime.datetime.now()-server['last_seen']).total_seconds()<20):
active_notifs[notifs_type].append(new_notif)
notifs_counter += 1
notifs_counter += offline_servers_count
return {
'notifs_c... |
CityGrid/arsenal | server/arsenalweb/views/api/reports/db.py | Python | apache-2.0 | 2,149 | 0.002792 | '''Arsenal API Db Reports.'''
# Copyright 2015 CityGrid Media, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | enderer='json')
def api_reports_db_read(request):
'''Process read requests for the /api | /reports/db route.'''
query = DBSession.execute("SHOW STATUS WHERE Variable_name IN ('wsrep_local_recv_que_avg', 'wsrep_connected', 'wsrep_cluster_conf_id', 'wsrep_cluster_state_uuid', 'wsrep_local_state_comment', 'wsrep_cluster_status', 'wsrep_cluster_size', 'wsrep_ready')")
db_status = {}
for row in que... |
TrustPlus/darkcoin-abe | contrib/ecdsa.py | Python | agpl-3.0 | 45,622 | 0.008943 | #!/usr/bin/env python
# Retrieved from http://ecdsa.org/ecdsa.py on 2011-10-17.
# Thanks to ThomasV.
# 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, o... | OR 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 this program. If not, see
# <http://www.gnu.org/licenses/agpl.html>.
import sys
import os
import warnings
import optparse
import re
from cg... | mon
import Abe.DataStore
import Abe.readconf
import operator
# bitcointools -- modified deserialize.py to return raw transaction
import Abe.deserialize
import Abe.util # Added functions.
import Abe.base58
from Abe.abe import *
AML_APPNAME = "Bitcoin ecdsa.org"
AML_TEMPLATE = """
<!DOCTYPE html PUBLIC "-//W3C//DTD ... |
mrinesi/PrediXmod | MetaXcan/calculate_variances.py | Python | mit | 2,191 | 0.004108 | #!/usr/bin/env python
import datetime
import gc
import gzip
import numpy as np
import os
import sys
DIR = '1000GP/1000GP_Phase3/'
SNP_LIST = set(x.strip() for x in open('SNP_LIST'))
class SNP:
def __init__(self, id, position, | hap):
self.id = id
| self.position = position
self.hap = hap
class Iterator:
def __init__(self, chrlegend):
self.chrlegend = chrlegend
self.chrhap = chrlegend.replace('legend', 'hap')
self.chrnumber = chrlegend.split('.')[0].split('chr')[1]
self.legend_file = gzip.open(os.path.join(DIR, self.c... |
peri-source/peri | peri/logger.py | Python | mit | 7,443 | 0.003359 | """
A simple but pretty logging interface for configurable logs across all packages.
To use, simply import the base log and (maybe) tack on a child context:
.. code-block:: python
from peri.logger import log
clog = log.getChild("<child name>") # optional
The possible options are:
clog.{info,debug,war... | s, **kwargs):
self.log.fatal(*args, **kwargs)
def getChild(self, name):
return self.log.getChild(name)
BWHandler = logging.StreamHandler
LogHandler = logging.handlers.RotatingFileHandler
try:
from peri.logger_colors import PygmentHandler
except ImportError as e:
PygmentHandler = BWHandler... | Handler
except ImportError as e:
LoggrHandler = BWHandler
types = {
'stringio': BWHandler,
'console-bw': BWHandler,
'console-color': PygmentHandler,
'rotating-log': LogHandler,
'loggr': LoggrHandler,
}
levels = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARN,
... |
jaeilepp/mne-python | mne/commands/mne_compute_proj_eog.py | Python | bsd-3-clause | 8,083 | 0.000124 | #!/usr/bin/env python
r"""Compute SSP/PCA projections for EOG artifacts.
You can do for example:
$ mne compute_proj_eog -i sample_audvis_raw.fif \
--l-freq 1 --h-freq 35 \
--rej-grad 3000 --rej-mag 4000 --rej-eeg 100
or
$ mne compute_proj_eog -i sample_audvis_raw.fif \
... | ber of jobs to run in parallel", default=1)
parser.add_op | tion("--rej-grad", dest="rej_grad", type="float",
help="Gradiometers rejection parameter in fT/cm (peak "
"to peak amplitude)", default=2000)
parser.add_option("--rej-mag", dest="rej_mag", type="float",
help="Magnetometers rejection parameter in fT (... |
project-hypr/hypr2 | tests/models/test_range_filter.py | Python | bsd-2-clause | 4,895 | 0 | # Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved.
#
# Licensed under the Simplified BSD License (the "License");
# you may not use this file except in compliance with the License.
import pytest
from hypr.helpers.mini_dsl import Range
@pytest.mark.populate(10)
class TestIntervalTypes:
models = 'S... | model):
"""Test an interval always false."""
assert model.get(id=(False, Range(0, 100))) == []
def test_true(self, model):
"" | "Test an interval always true."""
ref = sorted(model.get())
rv = sorted(model.get(id=Range(0, 100)))
assert rv == ref
def test_conjunction(self, model):
"""A ∧ B."""
ref = model.get(id=A_and_B)
rv = model.get(id=((True, A, 0), (True, B, 1)))
assert sorted(rv... |
weso/CWR-DataApi | cwr/parser/decoder/cwrjson.py | Python | mit | 570 | 0 | # -*- coding: utf-8 -*-
import json
from cwr.parser.decoder.common | import Decoder
from cwr.parser.decoder.dictionary import FileDictionaryDecoder
"""
Classes for decoding CWR classes from JSON dictionaries.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class JSONDecoder(Decoder):
def __init__(self):
| super(JSONDecoder, self).__init__()
self._dict_decoder = FileDictionaryDecoder()
def decode(self, data):
decoded = json.loads(data)
return self._dict_decoder.decode(decoded)
|
nihlaeth/dragonfly-grammars | dragonfly_grammars/context.py | Python | gpl-3.0 | 3,168 | 0.003472 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Context generators
Easily generate context instances.
"""
from aenea import AppContext, ProxyAppContext, ProxyPlatformContext
def linux():
"""
Context that matches only on linux.
Raises
------
None
Returns
-------
aenea.ProxyPlatformC... |
..doctest::
>>> terminal()
LogicOrContext(...)
"""
return AppContext('putty') | \
ProxyAppContext(cls='t | erminator')
def true_vim():
"""
Real vim context.
Complete vim as opposed to vi or apps with vim
key bindings.
Raises
------
None
Returns
-------
dragonfly.LogicAndContext
Examples
--------
..doctest::
>>> TODO
"""
return terminal() & cross_platf... |
ajdale/jstool | jstool.py | Python | mit | 5,509 | 0.003812 | #!/usr/bin/python
import os
import sys
import argparse
import requests
import subprocess
import shutil
class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbos... | help='output file')
parser.add_argument('-c, --compression', default=0, dest='compress', type=int, help='compression level of output file\n0: no compression\n1: strip whitespace\n2: simple\n3: advanced')
parser.add_argument('--compi | ler', default=None, dest='compiler_path', type=str, help='path to closure compiler jar file. If not specified, online closure API will be used instead')
parser.add_argument('--filter-console', default=False, dest='no_console', help='strips console calls', action='store_true')
args = parser.parse_args()
con... |
google-research/public-data-in-dpfl | utils/datasets/infinite_emnist_test.py | Python | apache-2.0 | 3,434 | 0.003786 | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | st.get_synthetic()
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 5)
self.assertEqual(raw_client_data.element_type_structure,
inf_client_data.element_type_structure | )
def test_pseudo_client_count(self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
self.assertLen(raw_client_data.client_ids, 1)
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 10)
self.assertLen(inf_client_data.client_ids, 10)
def test_first_pseudo_client_prese... |
pnwairfire/pyairfire | bin/statuslogging/log-status.py | Python | gpl-3.0 | 2,666 | 0.005626 | #!/usr/bin/env python
"""log-status.py | : Script to ....
Example calls:
> ./bin/statuslogging/log-status.py \
-e https://status-log.airfire.org/status-logs \
-k abc123 -s dsfjerw -p BlueSky -o Ok -f foo=bar -f baz=foo -v
"""
__author__ = "Joel Dubowy"
import datetime
import logging
import re
import sys
from afscripting import (
options ... | )
try:
from pyairfire import statuslogging
except:
import os
root_dir = os.path.abspath(os.path.join(sys.path[0], '../../'))
sys.path.insert(0, root_dir)
from pyairfire import statuslogging
# Note: though some argue that all required parameters should be specified as
# positional arguments, I pref... |
Opus1no2/Ifbyphone-API-Module | src/Ifbyphone/api/addons.py | Python | mit | 685 | 0.010219 | from base import IfbyphoneApiBase
class Addons(IfbyphoneApiBase):
def list(self):
"""List all purchased Addons for an account
"""
self. | options['action'] = 'addons.list'
return self.call(self.options)
def purchase(self, **kwargs):
"""Purchase an addon for an account
keyword arguments:
item_id -- ID number of desired addon
qty -- the quantity of the addon
send_receipt -- set... | e'
return self.call(self.options) |
hrmyd/pytc-gui | pytc_gui/main_window.py | Python | unlicense | 5,587 | 0.001611 | """
pytc GUI using PyQt5
"""
from pytc.global_fit import GlobalFit
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from .exp_setup import AddExperimentWindow
from .fit_update import AllExp, PlotBox
from .help_dialogs import VersionInfo, DocumentationURL
from matplotlib.backends.bac... | les (*.csv)")
plot_name = file_name.split(".")[0] + "_plot.pdf"
try:
data_file = open(file_name, "w")
data_file.write(self._fitter.fit_as_csv)
data_file.close()
plot_save = PdfPages(plot_name)
fig, ax = self._fitter.plot()
plot_sa... | )
def main():
"""
"""
version = pkg_resources.require("pytc-gui")[0].version
try:
app = QApplication(sys.argv)
app.setApplicationName("pytc")
app.setApplicationVersion(version)
pytc_run = Main()
sys.exit(app.exec_())
except KeyboardInterrupt:
sys.exi... |
govarguz/espressopp | testsuite/pickle_potential/pickle_potential.py | Python | gpl-3.0 | 1,526 | 0.028834 | #!/usr/bin/env python2
#
# Copyright (C) 2013-2017(H)
# Max Planck Institute for Polymer Research
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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,... | ibuted 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 General Public License
# along with this progra... | g/licenses/>.
#
# -*- coding: utf-8 -*-
import espressopp
system, integrator = espressopp.standard_system.LennardJones(0,(10,10,10))
system.storage.addParticles([[1,0,espressopp.Real3D(5,5,5)]],'id','type','pos')
system.storage.addParticles([[2,0,espressopp.Real3D(5,6,5)]],'id','type','pos')
system.storage.addPartic... |
furgerf/kaggle-projects | dstl/utils.py | Python | apache-2.0 | 2,976 | 0.008401 | import numpy as np
import shapely.affinity
import cv2
from collections import defaultdict
from shapely.geometry import MultiPolygon, Polygon
class Utils:
@staticmethod
def multi_polygon_to_pixel_mask(polygon, image_size):
mask = np.zeros(image_size, np.uint8)
int_coords = lambda x: np.array(x).round().asty... | # now messy stuff to associate parent and child contours
cnt_children = defaultdict(list)
child_cont | ours = set()
assert hierarchy.shape[0] == 1
# http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html
for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]):
if parent_idx != -1:
child_contours.add(idx)
cnt_children[parent_idx].append(approx_contours[idx])
# crea... |
kslundberg/pants | src/python/pants/base/build_configuration.py | Python | apache-2.0 | 8,384 | 0.008349 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import inspect
impor... | ctories.items():
self._register_target_macro_factory_alias(alias, target_macro_factory)
for alias, obj in aliases.objects.items():
| self._register_exposed_object(alias, obj)
for alias, context_aware_object_factory in aliases.context_aware_object_factories.items():
self._register_exposed_context_aware_object_factory(alias, context_aware_object_factory)
# TODO(John Sirois): Warn on alias override across all aliases since they shar... |
negar-rostamzadeh/rna | cooking.py | Python | mit | 9,787 | 0.000204 | import logging
import os
import time
import numpy as np
import theano.tensor as T
from theano import config
import theano
from blocks.algorithms import (GradientDescent, Adam, Momentum,
CompositeRule, StepClipping)
from blocks.extensions import FinishAfter, Printing, ProgressBar
from bloc... | momentum])
adam = Adam(learning_rate=lr_var)
step_rule = CompositeRule([clipping, adam])
training_algorithm = GradientDescent(
cost=model.cost | , parameters=all_params,
step_rule=step_rule)
monitored_variables = [
lr_var,
aggregation.mean(training_algorithm.total_gradient_norm)] + monitorings
for param in all_params:
name = param.tag.annotations[0].name + "." + param.name
to_monitor = training_algorithm.gradien... |
robertnishihara/ray | python/ray/dashboard/interface.py | Python | apache-2.0 | 4,036 | 0 | import aiohttp
from abc import ABC, abstractmethod
class BaseDashboardController(ABC):
"""Set of APIs to interact with a Dashboard class and routes.
Make sure you run start_collecting_metrics function before using
get_[stats]_info methods.
"""
@abstractmethod
def get_ray_config(self):
... | ling_status(self, req) -> aiohttp.web.Response:
raise NotImplementedError("Please implement this method.")
@abstractmethod
async def get_profiling_info(self, req) -> aiohttp.web.Response:
raise NotImplementedError("Please implement this method.")
@abstractmethod
async def kill_actor(se... | , req) -> aiohttp.web.Response:
raise NotImplementedError("Please implement this method.")
@abstractmethod
async def errors(self, req) -> aiohttp.web.Response:
raise NotImplementedError("Please implement this method.")
|
CrazyWearsPJs/minimalist_web_crawler | src/search.py | Python | mit | 314 | 0.047771 | def lucky_search( | index, ranks, keyword):
urls = index.get(keyword)
if urls and ranks:
return max(urls, key = lambda x: ranks[x])
else:
return None
def ordered_search(inde | x, ranks, keyword):
urls = index.get(keyword)
if urls and ranks:
return sorted(urls, key = lambda x: ranks[x])
else:
return None
|
solring/TWCompanyTree | parser/directorParser.py | Python | unlicense | 2,061 | 0.004852 | import json
import urllib
import urllib2
from pyquery import PyQuery as pq
types = ['sii', 'otc', 'rotc', 'pub']
companys = {}
def outputResult(outfile):
ofd = open(outfile, 'w')
c = 0
ofd.write("[")
for k, comp in companys.iteritems():
ofd.write(", \n") if c == 0
ofd.write("%s" % json.dumps(comp... | url = "http://mops.twse.com.tw/mops/web/ajax_t93sb06"
values = { 'encodeURIComponent': '1',
'step': '1',
'firstin': '1',
'off':'1',
'TYPEK':target }
req_data = urllib.urlencode(values)
req = urllib2.Request(url, req_data)
res = urllib... | raw_doc = res.read()
#print raw_doc
encoding = 'utf-8'
if res.headers.has_key('content-encoding'):
encoding = res.headers['content-encoding']
doc = pq(raw_doc.decode(encoding)) # get the DOM
print "encoding = %s" % doc.encoding
table = pq(doc('table').filter('.hasBorder')) # get the... |
galactics/space-api | beyond/propagators/j2.py | Python | gpl-3.0 | 1,215 | 0 | import numpy as np
from .base import AnalyticalPropagator
from ..constants import Earth
from ..dates import timedelta
class J2(AnalyticalPropagator):
"""Analytical propagator taking only the Earth-J2 effect into account"""
@property
def orbit(s | elf):
return self._orbit if hasattr(self, "_orbit") else None
@orbi | t.setter
def orbit(self, orbit):
self._orbit = orbit.copy(form="keplerian_mean")
def propagate(self, date):
if type(date) is timedelta: # pragma: no cover
date = self.orbit.date + date
delta_t = (date - self.orbit.date).total_seconds()
mu = Earth.mu
r = s... |
philrhinehart/waterlogged | logger/backup_data.py | Python | mit | 552 | 0.03442 | import csv
from logger.models import * |
import StringIO
def create_backup(fountain_name = ''):
# Load logs
if fountain_ | name:
logs = Fountain.objects.get(name=fountain_name).log_set.all()
else:
logs = Log.objects.all()
# Create file stream
f = StringIO.StringIO()
csvF = csv.writer( f, delimiter=',')
# Write CSV headers
csvF.writerow(['Fountain','Date','Time','Bottles', 'Rate', 'Deg F'])
for l in logs:
# Write l... |
teemulehtinen/a-plus | threshold/migrations/0001_initial.py | Python | gpl-3.0 | 2,684 | 0.004098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course', '0032_auto_20170215_0953'),
('exercise', '0025_auto_20170215_0953'),
]
operations = [
migrations.CreateMode... | options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Threshold',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('name', models.CharFiel... | nsumed by easier difficulty requirements.', default=False)),
('course_instance', models.ForeignKey(to='course.CourseInstance', related_name='thresholds', on_delete=models.CASCADE)),
('passed_categories', models.ManyToManyField(blank=True, to='course.LearningObjectCategory')),
... |
Pysellus/pysellus | spec/fixtures/multiple_files/file_1.py | Python | mit | 190 | 0.010526 | def file_1_function_a():
| pass
a_number = 7
a_string = 'bleh'
def file_1_function_b():
pass
file_1_function_a.is_setup_function = True
file_1_function_b. | is_setup_function = True
|
tboyce021/home-assistant | tests/components/smart_meter_texas/test_init.py | Python | apache-2.0 | 2,555 | 0.000783 | """Test the Smart Meter Texas module."""
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.smart_meter_texas.const import DOMAIN
from homeassistant.config_entries import (
ENTRY_STATE_LOADED,
ENTRY_STATE_NOT_LOADED,
ENTRY... | ATE_SETUP_RETRY
async def test_update_failure(hass, config_entry, aioclient_mock):
"""Test that the coordinator handles a bad respons | e."""
await setup_integration(hass, config_entry, aioclient_mock, bad_reading=True)
await async_setup_component(hass, HA_DOMAIN, {})
await hass.async_block_till_done()
with patch("smart_meter_texas.Meter.read_meter") as updater:
await hass.services.async_call(
HA_DOMAIN,
... |
martinb07/mysmarthome | logics/zeit.py | Python | gpl-3.0 | 4,137 | 0.011603 | #/logics/zeit.py
#!/usr/bin/env python
sh_now = sh.now()
debug = False
# Funktionen
def leap_year(year):
if (year % 400 == 0) or ((year % 4 == 0) and not (year % 100 == 0)):
return True
else:
return False
def days_of_month(month, year):
if month in [1, 3, 5, 7, 8, 10, 1... | )
# Sekunde/Stunde
sh.second.since.hour(sh.second.sin | ce.minute() + (60 * sh.minute.since.hour()))
sh.second.until.hour(sh.second.until.minute() + (60 * sh.minute.until.hour()))
# Sekunde/Tag
sh.second.since.midnight(sh.second.since.minute() + (3600 * sh.hour.since.midnight()))
sh.second.until.midnight(sh.second.until.minute() + (3600 * sh.hour.until.midnight()))
# Minu... |
kblomqvist/yasha | yasha/parsers.py | Python | mit | 3,274 | 0.001833 | """
The MIT License (MIT)
Copyright (c) 2015-2021 Kim Blomqvist
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, modify, ... | ()
def parse_xml(file):
import xmltodict
assert file.name.endswith('.xml')
variables = xmltodict.parse(file.read().decode(ENCODING))
return variables if variables else dict()
def parse_svd(file):
# TODO: To be moved into its own repo
| from .cmsis import SVDFile
svd = SVDFile(file)
svd.parse()
return {
"cpu": svd.cpu,
"device": svd.device,
"peripherals": svd.peripherals,
}
def parse_ini(file):
from configparser import ConfigParser
cfg = ConfigParser()
# yasha opens files in binary mode, configpa... |
babble/babble | include/jython/Lib/test/test_cmath_jy.py | Python | apache-2.0 | 3,591 | 0.005569 | #! /usr/bin/env python
""" Simple test script for cmathmodule.c
Roger E. Masse
"""
import cmath
import unittest
from test import test_support
from test.test_support import verbose
p = cmath.pi
e = cmath.e
if verbose:
print 'PI = ', abs(p)
print 'E = ', abs(e)
class CmathTestCase(unittest.TestCase):
d... | cmath.acosh(complex(3, 4)))
def test_asin(self):
self.assertAlmostEqual(complex(0.633984, 2.30551),
cmath.asin(complex(3, 4)))
def test_asinh(self):
self.assertAlmostEqual(complex(2.29991, 0.917617),
cmath.asinh(comple... | _atan(self):
self.assertAlmostEqual(complex(1.44831, 0.158997),
cmath.atan(complex(3, 4)))
def test_atanh(self):
self.assertAlmostEqual(complex(0.11750, 1.40992),
cmath.atanh(complex(3, 4)))
def test_cos(self):
self.assert... |
tombstone/models | official/vision/image_classification/optimizer_factory_test.py | Python | apache-2.0 | 4,279 | 0.002103 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | lf, optimizer_name, moving_average_decay, lookahead):
"""Smoke test to be sure no syntax errors."""
model = self.build_toy_model()
params = {
'learning_rate': 0.001,
'rho': 0.09,
'momentum': 0.,
'epsilon': 1e-07,
'moving_average_decay': moving_average_decay,
'... | ead,
}
optimizer = optimizer_factory.build_optimizer(
optimizer_name=optimizer_name,
base_learning_rate=params['learning_rate'],
params=params,
model=model)
self.assertTrue(issubclass(type(optimizer), tf.keras.optimizers.Optimizer))
def test_unknown_optimizer(self):
wi... |
grafana/grafana | scripts/build/ci-msi-build/msigenerator/generator/build.py | Python | agpl-3.0 | 14,202 | 0.00345 | #!/usr/bin/env python
#
# Creates .wxs files to be used to generate multiple MSI targets
#
# by default the script will check for dist and enterprise-dist, and parse
# the version as needed options are provided to give a build version that will
# download the zip, drop in to dist/enterprise-dist and do the same thing
#... | shutil.copy2(outfile, target_dir_name)
nssm_file = get_nssm('/tmp/cache', NSSM_VERSION)
if not os.path.isdir(target_dir_name + '/nssm'):
os.mkdir(target_dir_name + '/nssm')
extract_zip(nssm_file, target_dir_name + '/nssm')
print('H | ARVEST COMPLETE')
os.chdir(src_dir)
generate_firewall_wxs(env, PRODUCT_VERSION, '/tmp/scratch/grafana-firewall.wxs', target_dir_name)
generate_service_wxs(env, PRODUCT_VERSION, '/tmp/scratch/grafana-service.wxs', target_dir_name, NSSM_VERSION)
generate_product_wxs(env, config, features, '/tmp/scratch/pr... |
kmpf/uap | include/steps/gffread_extract_transcripts.py | Python | gpl-3.0 | 2,927 | 0 | from logging import getLogger
from abstract_step import AbstractStep
import os
logger = getLogger('uap_logger')
class GffreadExtractTranscripts(AbstractStep):
'''
extract transcripts from gtf
http://ccb.jhu.edu/software/stringtie/gff.shtml
write a fasta file with spliced exons for each GFF transcript... | connection['in/anno'][0])
rfiles.append(connection['in/anno'][0])
continue
stderr_file = "%s-gffread_extract_transcripts-log_stderr.txt" % (
| run_id)
log_stderr = run.add_output_file("log_stderr",
stderr_file, rfiles)
stdout_file = "%s-gffread_extract_transcripts-log_stdout.txt" % (
run_id)
log_stdout = run.add_output_file("log_stdout",
... |
Gamebasis/3DGamebasisServer | GameData/blender-2.71-windows64/2.71/scripts/freestyle/styles/blueprint_circles.py | Python | gpl-3.0 | 1,917 | 0.001043 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Filename : blueprint_circles.py
# Author : Emmanuel Turquin
# Date : 04/08/2005
# Purpose : Produces a blueprint using circular contour strokes
from freestyle.chainingiterator... | dBP1D,
TrueUP1D,
pyHigherLengthUP1D,
)
from freestyle.shaders import (
ConstantThicknessShader,
IncreasingColorShader,
TextureAssignerShader,
pyBluePrintCirclesShader,
pyPerlinNoise1DShader,
)
from freestyle.types import Operators
upred = AndUP1D(QuantitativeInvisibilityUP1D(0), Co... |
autosportlabs/RaceCapture-Pro_firmware | bin/rcp_log_linter.py | Python | gpl-3.0 | 3,639 | 0.001374 | #!/usr/bin/env python3
import optparse
class RcpLogValidator(object):
MAX_ERRORS = 25
MAX_INTERVAL_STEP_MS = 3000
MIN_INTERVAL_STEP_MS = 1
def __init__(self):
self.interval = 0
self.columns = 0
def _count_commas(self, line):
return line.count(',')
def _validate_colum... | Expected {}, " +
"found {}").format(line_no, self.columns, columns))
return False
def _validate_interval_time(sel | f, line, line_no):
try:
interval = int(line.split(',', 1)[0])
except ValueError:
interval = 0
# Deal with initialization.
if self.interval == 0:
self.interval = interval
return True
interval_min = self.interval + self.MIN_INTERVAL... |
levilucio/SyVOLT | tests/TestModules/HNacExampleRuleLHS.py | Python | mit | 12,702 | 0.007322 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import cPickle as pickle
from uuid import UUID
class HNacExampleRuleLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HNacExampleRuleLHS.
"""
# Flag thi... | e LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#====================================================================== | =========
return True
"""
self.vs[1]["MT_pre__name"] = """
#===============================================================================
# This code is executed when evaluating if a node shall be matched by this rule.
# You can access the value of the current node's attribute value by: attr_value.
# You can... |
AlphaCluster/NewsBlur | vendor/paypalapi/response.py | Python | mit | 4,173 | 0.000719 | # coding=utf-8
"""
PayPalResponse parsing and processing.
"""
import logging
from pprint import pformat
from vendor.paypalapi.compat import is_py3
if is_py3:
#noinspection PyUnresolvedReferences
from urllib.parse import parse_qs
else:
# Python 2.6 and up (but not 3.0) have urlparse.parse_qs, which is cop... | w = parse_qs(query_string)
self.config = config
logger.debug("PayPal NVP API Response:\n%s" % self.__str__())
def __str__(self):
"""
Returns a string represe | ntation of the PayPalResponse object, in
'pretty-print' format.
:rtype: str
:returns: A 'pretty' string representation of the response dict.
"""
return pformat(self.raw)
def __getattr__(self, key):
"""
Handles the retrieval of attributes that don't exist on ... |
izapolsk/integration_tests | cfme/tests/automate/custom_button/test_rest_custom_button.py | Python | gpl-2.0 | 7,392 | 0.001488 | import fauxfactory
import pytest
from cfme import test_requirements
from cfme.rest import gen_data
from cfme.tests.automate.custom_button import CLASS_MAP
from cfme.tests.automate.custom_button import OBJ_TYPE
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.rest import assert_response
f... | esource_attributes
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.tier(3),
test_requirements.custom_button,
pytest.mark.parametrize("obj_type", OBJ_TYPE, ids=[obj.capitalize() for obj in OBJ_TYPE],
scope="module"),
]
@pytest.fixture(scope="module")
def group_r... | [obj_type]["rest"]
response = gen_data.custom_button_sets(request, appliance, button_type)
assert_response(appliance)
return response[0]
@pytest.fixture(scope="module")
def buttons_rest(request, appliance, obj_type):
# create unassigned button (custom button)
button_type = CLASS_MAP[obj_type]["res... |
kuba1/qtcreator | share/qtcreator/debugger/creatortypes.py | Python | lgpl-2.1 | 5,087 | 0.005701 | ############################################################################
#
# Copyright (C) 2015 The Qt Company Ltd.
# Contact: http://www.qt.io/licensing
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the comm... | pany LGPL Exception
# version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
#
#############################################################################
from dumper import *
def dumpLiteral(d, value):
d.putSimpleCharArray(value["_chars"], value["_size"])
def qdump__Core__Id(d, value):
try:... | ainChildren(value)
def qdump__Debugger__Internal__GdbMi(d, value):
str = d.encodeByteArray(value["m_name"]) + "3a20" \
+ d.encodeByteArray(value["m_data"])
d.putValue(str, Hex2EncodedLatin1)
d.putPlainChildren(value)
def qdump__Debugger__Internal__DisassemblerLine(d, value):
d.putByteArrayValu... |
melphi/article-extractor | python/setup.py | Python | apache-2.0 | 416 | 0 | from os | import path
from setuptools import setup
CURRENT_PATH = path.dirname(path.abspath(__file__))
with open(CURRENT_PATH + '/requirements.txt', 'r') as file:
REQUIREMENTS = file.read().splitlines()
setup(
name='crawler',
version='0.0.1',
description='Crawler',
test_suite='tests',
packages=['app']... | REQUIREMENTS)
|
googleads/google-ads-python | google/ads/googleads/v9/enums/types/asset_set_asset_status.py | Python | apache-2.0 | 1,166 | 0.000858 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or | agreed to in writing, 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 proto # type: ignore
__protobu... | manifest={"AssetSetAssetStatusEnum",},
)
class AssetSetAssetStatusEnum(proto.Message):
r"""Container for enum describing possible statuses of an asset
set asset.
"""
class AssetSetAssetStatus(proto.Enum):
r"""The possible statuses of an asset set asset."""
UNSPECIFIED = 0
U... |
janverschelde/PHCpack | src/Python/PHCpy3/phcpy/factor.py | Python | gpl-3.0 | 33,771 | 0.003998 | """
Given a witness set representation of a pure dimensional solution set,
the functions in this module separate the generic points in the witness set
according to the irreducible components of the solution set.
"""
def standard_decomposition(deg):
"""
Returns the decomposition as a list of labels of witness p... | edded system *embsys* and its solutions *esols*.
If the embedded polynomial system is a Laurent system,
then islaurent must equal one, the default is zero | .
If *verbose* is False, then no output is written.
If *nbloops* equals zero, then the user is prompted to give
the maximum number of loops.
"""
from phcpy.phcpy2c3 import py2c_factor_set_standard_to_mute
from phcpy.phcpy2c3 import py2c_factor_set_standard_to_verbose
from phcpy.phcpy2c3 impo... |
zetaops/ulakbus | ulakbus/services/personel/hitap/hizmet_nufus_ekle.py | Python | gpl-3.0 | 1,674 | 0.001796 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
"""HITAP Nufus Ekle
Hitap'a personelin Nufus bilgilerinin eklenmesini yapar.
"""
from ulakbus.services.personel.hitap.hitap_service import ZatoHitapS... | d': 'soyad',
'tckn': 'tckn',
'aciklama': 'aciklama',
'yetkiSeviyesi': 'yetki_seviyesi',
'kurumaBaslamaTarihi': 'kuruma_baslama_tarihi',
'gorevTarihi6495': 'gorev_tarihi_6495',
'emekliSicil6495': 'emekli_sicil_6495'
},
'date_filter':... | muriyet_baslama_tarihi', 'kuruma_baslama_tarihi'],
'long_to_string': ['kayit_no'],
'required_fields': ['tckn', 'ad', 'soyad', 'dogumTarihi', 'cinsiyet', 'emekliSicilNo',
'memuriyetBaslamaTarihi', 'durum', 'kurumSicili', 'maluliyetKod',
'sebep', 'ye... |
sigvef/elma | elma/models.py | Python | mit | 27,072 | 0.000443 | from __future__ import annotations
import itertools
import random
import struct
from abc import ABCMeta
from math import cos, sin
from pathlib import Path
from typing import List, Optional, Union
from PIL import Image
import elma.packing
from elma.constants import VERSION_ELMA
from elma.render import LevelRenderer
fr... | ure.point and
self.picture_name == other_picture.picture_name and
self.texture_name == other_picture.texture_name and
self.mask_name == other_picture.mask_name and
self.distance == other_picture.distance and
self.clipping == other_picture.c... | grass (boolean): A boolean deciding whether or not the polygon is a
grass polygon.
"""
def __init__(self, points: List[Point], grass: bool = False) -> None:
self.points = points
self.grass = grass
def __repr__(self) -> str:
return 'Polygon(points: %s, grass: %s)' % (self... |
olof/svtplay-dl | lib/svtplay_dl/service/flowonline.py | Python | mit | 1,384 | 0.001445 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
from __future__ import absolute_import
import copy
import re
from urllib.parse import urlparse
from svtplay_dl.error import ServiceError
from svtplay_dl.fetcher.hls import hlsparse
from svtplay_dl.service import OpenGraphThumbMix... | )
if not match:
yield ServiceError("Cant find video file")
return
streams = hlsparse(self.config, self.http.request("get", match.gr | oup(1)), match.group(1), output=self.output)
for n in list(streams.keys()):
yield streams[n]
|
Fauxmoehawkeen/soundcloud-python-master | soundcloud/tests/test_resource.py | Python | bsd-2-clause | 1,217 | 0 | try:
import json
except ImportError:
import simplejs | on as json
from soundcloud.resource import wrapped_resource, ResourceList, Resource
from soundcloud.tests.utils import MockResponse
from nose.tools import eq_
def test_json_list():
"""Verify that a json list is wrapped in a ResourceList object."""
resources = wrapped_resource(MockResponse(json.dumps([{'foo'... | rces))
eq_('bar', resources[0].foo)
def test_json_object():
"""Verify that a json object is wrapped in a Resource object."""
resource = wrapped_resource(MockResponse(json.dumps({'foo': 'bar'})))
assert isinstance(resource, Resource)
eq_('bar', resource.foo)
def test_properties_copied():
"""C... |
neillc/zookeepr | zkpylons/controllers/invoice.py | Python | gpl-2.0 | 16,775 | 0.004054 | import datetime
import logging
import json
from pylons import request, response, session, tmpl_context as c
from zkpylons.lib.helpers import redirect_to
from pylons.controllers.util import Response, redirect
from pylons.decorators import validate, jsonify
from pylons.decorators.rest import dispatch_on
from formenco... | nique_key())):
# Raise a no_auth error
h.auth.no_role()
c.printable = True
c.invoice = Invoice.find_by_id(id, True)
c.payment_received = None
c.payment = None
if c.invoice.is_paid and c.invoice.total > 0:
c.payment_received = c.invoice.good_pa... | payment = c.payment_received.payment
return render('/invoice/view_printable.mako')
@authorize(h.auth.has_organiser_role)
def index(self):
c.can_edit = True
c.invoice_collection = Invoice.find_all()
return render('/invoice/list.mako')
@authorize(h.auth.has_organiser_role)
... |
ronhanson/python-tbx | fabfile/__init__.py | Python | mit | 1,018 | 0.003929 | import os
from fabric.decorators import task
from fabric.api import local, run, cd, env, prefix, hide
from fabric.colors import cyan, red, green, yellow
import app
import git
import virtualenv
@task
def init():
"""Execute init tasks for all components (virtualenv, pip)."""
print(yellow("# Setting up developme... | True))
virtualenv.init()
virtualenv.update()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment."))
@task
def update():
"""Update virtual env with requirements packages."""
virtualenv.update()
@task
def dev():
... | nt environment...\n", True))
virtualenv.init()
virtualenv.update()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment."))
@task
def clean():
"""Clean .pyc files"""
app.clean()
|
kbg/drms | drms/tests/_runner.py | Python | mit | 578 | 0 | from __future__ import absolute_import, division, print_function
import | os
# Package directory, i.e. the parent directory in respect to this file
pkg_dir = os.path.dirname(os.path.dirname(__file__))
try:
import pytest
except ImportError:
def run_tests(extra_args=None):
raise ImportError('pytest is needed to run tests')
else:
de | f run_tests(extra_args=None):
args = []
if extra_args is not None:
args += extra_args
args += [pkg_dir]
print('running: pytest ' + ' '.join(args))
return pytest.main(args)
|
noslenfa/tdjangorest | uw/lib/python2.7/site-packages/fabric/tasks.py | Python | apache-2.0 | 15,409 | 0.000649 | from __future__ import with_statement
from functools import wraps
import inspect
import sys
import textwrap
from fabric import state
from fabric.utils import abort, warn, error
from fabric.network import to_dict, normalize_to_string, disconnect_all
from fabric.context_managers import settings
from fabric.job_queue im... | atched_get_argspec
def get_task_details(task):
details = [
textwrap.dedent(task.__doc__)
if task.__doc__
else 'No docstring provided']
argspec = | inspect.getargspec(task)
default_args = [] if not argspec.defaults else argspec.defaults
num_default_args = len(default_args)
args_without_defaults = argspec.args[:len(argspec.args) - num_default_args]
args_with_defaults = argspec.args[-1 * num_default_args:]
details.append('Arguments: %s' % (
... |
apehua/pilas | pilas/actores/mano.py | Python | lgpl-3.0 | 1,790 | 0.001119 | # -*- encoding: utf-8 -*-
# Pilas engine - A video game framework.
#
# Copyright 2010 - Hugo Ruscitti
# License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# Website - http://www.pilas-engine.com.ar
from pilas.actores import Actor
import pilas
class CursorMano(Actor):
"""
Representa un cusor del rat... | elf.imagen = self.imagen_arrastrando
def cuando_suelta_el_mouse(self, evento):
if self.pu | lsado:
self.imagen = self.imagen_normal
self.pulsado = False
|
Hutspace/odekro | mzalendo/core/models.py | Python | agpl-3.0 | 25,729 | 0.007229 | from __future__ import division
import datetime
import re
import itertools
import random
from django.conf import settings
from django.core import exceptions
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.m... | et(self.model)
def loose_match_name(self, name):
"""Search for a loose match on a name. May not be too reliable"""
# import here to avoid creating an import loop
from haystack.query import SearchQuerySet
# Try matching all the bits
results = SearchQuerySet().filter... | for bit in re.split(r'\s+', name):
results = results.filter_and(content=bit)
# If we have exactly one result return that
if len(results) == 1:
return results[0].object
else:
return None
def get_next_featured(self, current_slug, want_pre... |
zzzzzzzlmy/MyLeetCode | 83. Remove Duplicates from Sorted List.py | Python | unlicense | 742 | 0.009434 | '''
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
'''
#Code is here
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# s... | def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
p = head
while p.next:
if p.v | al == p.next.val:
p.next = p.next.next
else:
p = p.next
return head
|
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/integration/cloud/providers/joyent.py | Python | apache-2.0 | 3,591 | 0.002228 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Nicole Thomas <nicole@saltstack.com>`
'''
# Import Python Libs
from __future__ import absolute_import
import os
import random
import string
# Import Salt Testing Libs
from salttesting.helpers import ensure_in_syspath, expensiveTest
ensure_in_syspath('../../../')
... | d instance name
'''
return 'CLOUD-TEST-' + ''.join(
random.choice(string.ascii_uppercase + string.digits)
for x in range(size)
)
# Create th | e cloud instance name to be used throughout the tests
INSTANCE_NAME = __random_name()
PROVIDER_NAME = 'joyent'
class JoyentTest(integration.ShellCase):
'''
Integration tests for the Joyent cloud provider in Salt-Cloud
'''
@expensiveTest
def setUp(self):
'''
Sets up the test requir... |
davjohnst/fundamentals | fundamentals/recursion/hanoi/tower.py | Python | apache-2.0 | 1,102 | 0.004537 | #!/usr/bin/env python
class Tower(object):
def __init__(self, n, tower_name):
if n < 0:
raise ValueError("n must be 0 or greater")
self.stack = [x + 1 for x in range(n)][::-1]
self.tower_name = tower_name
def size(self):
return len(self.stack)
def add(self... | {1} on top of a {2}".format(self.tower_name, value, prev)
self.stack.append(value)
return
raise ValueError("must stack smaller values over bigger values")
def pop(self):
if self.size() == 0:
rais | e ValueError("can't pop when tower has 0 elements")
popped = self.stack.pop()
print "[Tower {0}] popping {1}".format(self.tower_name, popped)
return popped
def to_string(self):
return str(self.stack)
if __name__ == "__main__":
t = Tower(3, "a")
t.pop()
t.pop()
t.... |
adamchainz/django_atomic_dispatch | setup.py | Python | bsd-3-clause | 1,291 | 0 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
' | django_atomic_dispatch',
]
requires = [
]
tests_require = [
'flake8',
'django-nose',
'rednose',
]
with open('README.rst') as readme_file:
readme = readme_file.read()
setup(
name='django-atomic-dispatch',
version='2.0.0',
description='Atomic transaction aware signals for Django 1.6+',
... |
url='https://github.com/adamchainz/django_atomic_dispatch',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'django_atomic_dispatch': 'django_atomic_dispatch'},
include_package_data=True,
tests_require=tests_require,
install_requires=requires,
license=open('LICENSE').rea... |
Shopify/shopify_python_api | shopify/base.py | Python | mit | 7,625 | 0.002885 | import pyactiveresource.connection
from pyactiveresource.activeresource import ActiveResource, ResourceMeta, formats
import shopify.yamlobjects
import shopify.mixins as mixins
import shopify
import threading
import sys
from six.moves import urllib
import six
from shopify.collection import PaginatedCollection
from pyac... | .headers
def set_headers(cls, value):
cls._threadlocal.headers = value
headers = property(get_headers, set_headers, | None, "The headers sent with HTTP requests")
def get_format(cls):
return getattr(cls._threadlocal, "format", ShopifyResource._format)
def set_format(cls, value):
cls._threadlocal.connection = None
ShopifyResource._format = cls._threadlocal.format = value
format = property(get_for... |
rflamary/POT | ot/optim.py | Python | mit | 12,806 | 0.004217 | # -*- coding: utf-8 -*-
"""
Optimization algorithms for OT
"""
# Author: Remi Flamary <remi.flamary@unice.fr>
# Titouan Vayer <titouan.vayer@irisa.fr>
#
# License: MIT License
import numpy as np
from scipy.optimize.linesearch import scalar_search_armijo
from .lp import emd
from .bregman import sinkhorn
# The... | Regularization parameter. Only used and necessary when armijo=False
Gc : ndarray (ns,nt)
Optimal map found by linearization in the FW algorithm. Only used and necessary when armijo=False
constC : ndarray (ns,nt)
Constant for the gromov cost. See [24]. Only used and necessary when armijo=Fal... | ional
Cost matrix between the features. Only used and necessary when armijo=False
Returns
-------
alpha : float
The optimal step size of the FW
fc : int
nb of function call. Useless here
f_val : float
The value of the cost for the next iteration
Referen... |
Donkyhotay/MoonPy | zope/tal/translationcontext.py | Python | gpl-3.0 | 1,523 | 0.000657 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
################################### | ###########################################
"""Translation context object for the TALInterpreter's I18N support.
The translation context provides a container for the information
needed to perform translation of a marked string from a page template.
$Id: translationcontext.py 26559 2004-07-15 21:22:32Z srichter $
"""
... |
junsooo/Fake_love | chatbot/model.py | Python | mit | 4,248 | 0.002384 | # -*- coding: utf-8 -*-
# 자세한 설명은 상위 폴더의 03 - Seq2Seq.py 등에서 찾으실 수 있습니다.
import tensorflow as tf
# Seq2Seq 기본 클래스
class Seq2Seq:
logits = None
outputs = None
cost = None
train_op = None
def __init__(self, vocab_size, n_hidden=128, n_layers=3):
self.learning_late = 0.001
self.vo... | f.outputs, self.targets)
accuracy = tf.reduce_mean(tf.cast(prediction_check, tf.float32))
return session.run([self.targets, self.outputs, accuracy],
feed_dict={self.enc_input: enc_input,
self.dec_input: dec_input,
... | return session.run(self.outputs,
feed_dict={self.enc_input: enc_input,
self.dec_input: dec_input})
def write_logs(self, session, writer, enc_input, dec_input, targets):
merged = tf.summary.merge_all()
summary = session.run(merged... |
masterkeywikz/seq2graph | src/theanets-0.6.1/theanets/main.py | Python | mit | 9,363 | 0.001175 | '''This module contains some glue code encapsulating a "main" process.
The code here is aimed at wrapping the most common tasks involved in creating
and, especially, training a neural network model.
'''
import climate
import datetime
import downhill
import os
import warnings
from . import graph
from . import trainer... | or str
A specification for obtaining a model. If a string is given, it is
assumed to name a file containing a pickled model; this file will be
loaded and used. If a network instance is provided, it will be used
as the model. If a callable (such as | a subclass) is provided, it
will be invoked using the provided keyword arguments to create a
network instance.
'''
def __init__(self, network, *args, **kwargs):
if isinstance(network, str) and os.path.isfile(network):
self.load(network)
elif isinstance(network, grap... |
claudep/pootle | pootle/apps/pootle_comment/migrations/0001_initial.py | Python | gpl-3.0 | 2,477 | 0.004845 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_... | (default=False, help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be | displayed instead.', verbose_name='is removed')),
('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)),
('site', models.ForeignKey(to='sites.Site', on_delete=models.CASCADE)... |
jntkym/rappers | getlyrics.py | Python | mit | 3,885 | 0.019017 | # -*- coding: utf-8 -*-
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEB... | _list
print("artist\ttitle\ttext")
for artist in artist_list[:args.n_artists]:
urls = getLyricUrlList(artist)
if verbose:
logger.info('{}: {} songs'.format(artist, len(urls))) |
for i, url in enumerate(urls, start=1):
if verbose:
if i%10 == 0: logger.info("Wrote " + str(i) + " songs")
lyric = getLyricText(url[1])
print("{artist}\t{title}\t{text}".format(
artist=artist,
title=url[0].encode("utf-8"),
text=lyric))
time.sleep(1.0) # Wai... |
larsks/cloud-init | cloudinit/tests/helpers.py | Python | gpl-3.0 | 17,816 | 0 | # This file is part of cloud-init. See LICENSE file for license information.
from __future__ import print_function
import functools
import httpretty
import logging
import os
import random
import shutil
import string
import sys
import tempfile
import time
import mock
import six
import unittest2
from unittest2.util im... | tever
# it previously had
def rebase_path(old_path, new_base):
if old_path.startswith(new_base):
# Already handle | d...
return old_path
# Retarget the base of that path
# to the new base instead of the
# old one...
path = os.path.join(new_base, old_path.lstrip("/"))
path = os.path.abspath(path)
return path
# Can work on anything that takes a path as arguments
def retarget_many_wrapper(new_base, am,... |
mcallaghan/tmv | BasicBrowser/import_hlda.py | Python | gpl-3.0 | 5,188 | 0.011951 | #!/usr/bin/env python3
import argparse, time
import numpy as np
import django
from django.utils import timezone
import datetime, os
import sys
import db6 as db
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BasicBrowser.settings")
django.setup()
from tmv_app.models import *
def read_state(filename, terms):
... | ssign", "r") as assign:
for line in assign:
(doc_id, score, path) = line.split(None, 2)
doc_id = int(doc_id)
doc = docs[doc_id]
try:
d = Doc.o | bjects.get(UT=doc)
except:
d = Doc(UT=doc)
d.save()
score = float(score)
path = [int(x) for x in path.split()]
level = -1
for topic_id in path:
level+=1
for topic in topics:
if... |
1065865483/0python_script | four/Webdriver/FindElement/By_idName.py | Python | mit | 343 | 0.003096 | fr | om selenium import webdriver
from time import sleep
driver=webdriver.Firefox()
driver.get("http://www.baidu.com/")
sleep(3)
# driver.find_element_by_id('kw').send_keys('Selenium我要自学网')
driv | er.find_element_by_name('wd').send_keys('Selenium我要自学网')
sleep(3)
driver.find_element_by_id('su').click()
sleep(3)
driver.quit()
|
AlohaWorld/TR | UHCF/common/movieAttr.py | Python | apache-2.0 | 2,436 | 0.001232 | #!/env/python
# -*- encoding: utf-8 -*-
"""
@version: 0.1
@author: wenzhiquan
@contact: wenzhiquanr@163.com
@site: http://github.wenzhiquan.com
@software: PyCharm
@file: movieAttr.py
@time: 16/3/6 11:19
@description: null
"""
from config import config
from lib import stdLib
class MovieAttr():
def __init__(self):... | File = r'result/hotMovie.list'
stdLib.dumpData(hotMovieList, outFile)
def goodMovie(self):
read = open(config.trainFile, 'r')
data = read.readlines()
read.close()
length = len(data)
goodMovieDict = dict()
| gradeCountDict = dict()
for i in data:
tmp = i[:-1].split(config.separator)
movieId = tmp[1]
grade = tmp[2]
goodMovieDict.setdefault(movieId, 0)
gradeCountDict.setdefault(movieId, 0)
goodMovieDict[movieId] += float(tmp[2])
... |
kapteyn-astro/kapteyn | doc/source/EXAMPLES/mu_minorticks.py | Python | bsd-3-clause | 1,126 | 0.023091 | from kapteyn import maputils
from matplotlib import pyplot as plt
fitsobj = maputils.FITSimage("m101.fits")
fig = plt.figure()
fig.subplots_adjust(left=0.18, bottom=0.10, right=0.90,
top=0.90, wspace=0.95, hspace=0.20)
for i in range(4):
f = fig.add_subplot(2,2,i+1)
mplim = fitsobj.Annotat... | e:
majorgrat = mplim.Graticule(skyout='galactic',
offsetx=True, unitsx='ARCMIN')
majorgrat.setp_gratline(color='b')
majorgrat.setp_tickmark(markersize=10)
majorgrat.setp_ticklabel(fontsize=6)
majorgrat.setp_plotaxis(plotaxis= | [0,1], fontsize=10)
minorgrat = mplim.Minortickmarks(majorgrat, 3, 5,
color="#aa44dd", markersize=3, markeredgewidth=2)
maputils.showall()
plt.show()
|
thelazier/dash | test/functional/feature_addressindex.py | Python | mit | 15,001 | 0.002866 | #!/usr/bin/env python3
# Copyright (c) 2014-2015 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 addressindex generation and fetching
#
import binascii
from test_framework.messages import COI... | ddresses": ["93bVhahvUKmQu8gu9g3QnPPa2cxFK98pMB", "yMNJePdcKvXtWWQnFYHNeJ5u8TF2v1dfK4"]})
assert_equal(len(multitxids), 6)
assert_equal(multitxids[0], txid0)
assert_equal(multitxids[1], txidb0)
assert_equal(multitxids[2], txid1)
assert_equal(multitxids[3], txidb1)
assert_... | 2)
# Check that balances are correct
balance0 = self.nodes[1].getaddressbalance("93bVhahvUKmQu8gu9g3QnPPa2cxFK98pMB")
assert_equal(balance0["balance"], 45 * 100000000)
# Check that outputs with the same address will only return one txid
self.log.info("Testing for txid uniquenes... |
asif-mahmud/Pyramid-Apps | imageupload/imageupload/views/home/security/__init__.py | Python | gpl-2.0 | 381 | 0 | from imageupload.security import BaseAuth
from pyramid.security | import (
DENY_ALL,
Deny,
Everyone,
Allow,
)
class HomeAuth(object):
@staticmethod
def home(request):
class HomePage(BaseAuth):
def __acl__(self):
| return [
(Allow, Everyone, 'view'),
]
return HomePage(request)
|
zbyrne/gameboy | pyboy/test_memory.py | Python | gpl-2.0 | 1,660 | 0 | from unittest import TestCase
from memory import RamController
from memory import MemoryController
class RamTests(TestCase):
def test_create_ram(self):
ram = RamController(500)
self.assertEqual(len(ram), 500)
def test_read_write(self):
ram = RamController(32)
ram[0] = 0xFF
... | c = mem._get_controller(15)
self.assertIs(c.controller, ram1)
c = mem._get_controller(31)
self.assertIs(c.controller, ram1)
c = mem._get_controller(32)
self.assertIs(c.controller, ram2)
c = mem._get_controller(95)
self.assertIs(c.controller, ram2)
with se... | ._get_controller(96)
def test_read_write_byte(self):
ram = RamController(32)
mem = MemoryController()
mem.register_controller(ram, 0)
mem.write_byte(0x5A, 0)
self.assertEqual(mem.read_byte(0), 0x5A)
def test_read_write_word(self):
ram = RamController(32)
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PyQt4/QtGui/__init__/QToolBar.py | Python | gpl-2.0 | 6,912 | 0.00897 | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from QWidget import QWidget
class QToolBar(QWidget):
"""
QToolBar(QString, QWidget parent=None)
QToolBar(QWidget parent=None)
""... | """ QToolBar.addSeparator() -> QAction """
return QAction
def addWidget(self, QWidget): # real signature unknown; restored from __doc__
""" QToolBar.addWidget | (QWidget) -> QAction """
return QAction
def allowedAreas(self): # real signature unknown; restored from __doc__
""" QToolBar.allowedAreas() -> Qt.ToolBarAreas """
pass
def allowedAreasChanged(self, *args, **kwargs): # real signature unknown
""" QToolBar.allowedAreasChanged[Qt.T... |
KanoComputing/kano-feedback | kano_feedback/FeedbackWindow.py | Python | gpl-2.0 | 15,986 | 0.00025 | #!/usr/bin/env python
# FeedbackWindow.py
#
# Copyright (C) 2014-2019 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# The main window to send feedback to Kano
from gi.repository import Gtk, Gdk, GdkPixbuf
from kano.gtk3.scrolled_window import ScrolledWindow
from kano.gtk3.top_b... | 0.35
)
screen = Gdk.Screen.get_default()
specific_provider = Gtk.CssProvider()
specific_provider.load_from_path(Media.media_dir() + 'css/style.css')
style_context = Gtk.StyleContext()
style_context.add_provider_for_screen(
screen, specific_provider, Gtk... | top_bar = TopBar(
title=_("Report a Problem"), # noqa: F821
window_width=self.WIDTH,
has_buttons=False
)
self._top_bar.set_close_callback(Gtk.main_quit)
self.set_decorated(True)
self.set_titlebar(self._top_bar)
self.entry = Gtk.Entry()
... |
sastryduri/agentless-system-crawler | tests/unit/test_plugins.py | Python | apache-2.0 | 69,027 | 0.000174 | import types
import unittest
from collections import namedtuple
import mock
from plugins.systems.config_container_crawler import ConfigContainerCrawler
from plugins.systems.config_host_crawler import ConfigHostCrawler
from plugins.systems.connection_container_crawler import ConnectionContainerCrawler
from plugins.syst... | do self.count = for some reason
mcount = 0
class MockedMemCgroupFile(mock.Mock):
def __init__(self):
pas | s
def readline(self):
return '2'
def __iter__(self):
return self
def next(self):
global mcount
mcount += 1
if mcount == 1:
return 'total_cache 100'
if mcount == 2:
return 'total_active_file 200'
else:
raise StopIt... |
nanounanue/pipeline-template | tests/pipeline_tests.py | Python | gpl-3.0 | 183 | 0.005464 | fro | m nose.tools import *
import dummy.pipelines.dummy
def setup():
print("SETUP")
def teardown():
print("TEARDOWN")
def test_basic():
print("Ejecutando test_basic | ")
|
catapult-project/catapult | tracing/tracing/value/histogram_serializer_unittest.py | Python | bsd-3-clause | 4,606 | 0.000651 | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from tracing.value import histogram
from tracing.value import histogram_serializer
from tracing.value.diagnostics import breakdown
from trac... | iagnostic], 'ggg')
self.assertIn('statisticsNames', diagnostics['GenericSet'])
_, stat_indexes = list(
diagnostics['GenericSet']['statisticsNames'].items())[0]
self.assertEqual(
['a | vg', 'count', 'max', 'min', 'std', 'sum'],
[serializer_objects[i] for i in stat_indexes]
)
self.assertIn('description', diagnostics['GenericSet'])
_, description_index = list(
diagnostics['GenericSet']['description'].items())[0]
self.assertEqual(serializer_objects[description_index], 'lo... |
jhumphry/ukraildata_etl | nrcif/schema/schemagen_tsi.py | Python | gpl-2.0 | 1,780 | 0 | # schemagen_tsi.py
# Copyright 2013 - 2016, James Humphry
# 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.
#
# Thi... | EMA = "tsi"
DDL.write('-- SQL DDL for data extracted from ATOC .TSI interchange \n'
'-- files in CSV format. Auto-generated by schemagen_tsi.py\n\n')
DDL.write("CREATE SCHEMA {0};\nSET search_path TO | {0},public;\n\n"
.format(SCHEMA))
DDL.write('''-- Only one table\n''')
DDL.write("CREATE TABLE tsi (\n")
first_field = False
for i in TSI.layout:
if not first_field:
first_field = True
else:
DDL.write(",\n")
fieldname = i.name.lower().repla... |
so-rose/openlut | main.py | Python | mit | 1,931 | 0.008804 | #!/usr/bin/env python3.5
'''
openlut: A package for managing and applying 1D and 3D LUTs.
Color Management: openlut deals with the raw RGB values, does its work, then puts out images with correct raw RGB values - a no-op.
Dependencies:
-numpy: Like, everything.
-wand: Saving/loading images.
-PyOpenGL - For image ... | NTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import sys
#~ from lib.files import Log #For Development
if __name__ == "__main__" :
if not sys.argv[1:]: prin | t('Use -t to test!'); exit()
if sys.argv[1] == '-t' :
import tests.suite
tests.suite.runTest('img_test', 'testpath')
|
Rhymmor/pharmac | src/solver-server/pkg/algorithms/identifiability/sensitivity.py | Python | mit | 1,544 | 0.003886 | import json
import numpy as np
from scipy.integrate import odeint
from ..utils import model_eval, NumpyEncoder
def sens_value(sol, par, delta_x, delta_y):
if sol != 0 and delta_x != 0:
return par / sol * (delta_y) / (2 * delta_x)
else:
return float('Inf')
def find_sensitivity(funcs, y0, t, par... |
return sens_list
def solve_sensitivity(model, ModelParser):
parser = ModelParser(model['model'])
points_count = model['options']['points']
t = np.linspace(0, model['options']['in | terval'], points_count)
params_dict = model['parameters']
delta = 0.00001 #TODO: remove hardcode
result = find_sensitivity(model_eval, model['initialValues'], t, params_dict, delta, parser)
return {'solution': result}
|
LLNL/spack | lib/spack/spack/test/cmd/license.py | Python | lgpl-2.1 | 3,129 | 0 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os.path
import re
from llnl.util.filesystem import | mkdirp, touch
import spack.cmd.license
import spack.paths
from spack.ma | in import SpackCommand
license = SpackCommand('license')
def test_list_files():
files = license('list-files').strip().split('\n')
assert all(f.startswith(spack.paths.prefix) for f in files)
assert os.path.join(spack.paths.bin_path, 'spack') in files
assert os.path.abspath(__file__) in files
def tes... |
chagaz/SamSpecCoEN | code/setupSampledLOSO_writeIndices.py | Python | mit | 5,303 | 0.004526 | # @Author
# Chloe-Agathe Azencott
# chloe-agathe.azencott@mines-paristech.fr
# April 2016
import argparse
import h5py
import numpy as np
import os
import sys
def main():
""" Create train/test indices for one repeat of a 10-fold sampled leave-one-study-out
experiment on the RFS data.
The indices will be... | ampled_loso/repeat%d' % (args.data_dir, args.repeat)
# Create outDir if it does not exist
if not os.path.isdir(outDir):
sys.stdout.write("Creating %s\n" % outDir)
try:
os.makedirs(outDir)
except OSError:
if not os.path.isdir(outDir):
raise
... | e loading it (so as not to use test data for normalization).
f = h5py.File("%s/ACES/experiments/data/U133A_combat.h5" % args.data_dir)
expressionData = np.array(f['U133A_combat_RFS']['ExpressionData'])
sampleLabels = np.array(f['U133A_combat_RFS']['PatientClassLabels'])
sampleAccess = np.array(f['U133A_... |
IRC-SPHERE/HyperStream | hyperstream/tools/aggregate_plate/2016-11-11_v1.0.0.py | Python | mit | 2,699 | 0.003705 | # The MIT License (MIT) # Copyright (c) 2014-2017 University of Bristol
#
# 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... | _execute(self, sources, alignment_stream, interval):
# Combine the data, apply the mapping and sort (inefficient!)
return sorted(itertools.chain(*(map(lambda x: self.mapper(source.stream_id.meta_data, x),
source.window(interval, force_cal | culation=True)) for source in sources)),
key=lambda x: x.timestamp)
def mapper(self, meta_data, instance):
"""
Pull out the meta data plate value and put it into the instance value
:param meta_data: the original meta data
:param instance: the original instance
... |
edisonlz/fruit | web_project/base/site-packages/django/contrib/admin/templatetags/admin_list.py | Python | apache-2.0 | 16,417 | 0.00402 | from __future__ import unicode_literals
import datetime
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.contrib.admin.util import (lookup_field, display_for_field,
display_for_value, label_for_field)
from django.contrib.admin.views.main import (ALL_VAR, EMPTY_CHANGELIST_... | = make_qs_param(ot, j)
o_list_primary.append(param)
| o_list_toggle.append(param)
o_list_remove.append(param)
if i not in ordering_field_columns:
o_list_primary.insert(0, make_qs_param(new_order_type, i))
yield {
"text": text,
"sortable": True,
"sorted": sorted,
"a... |
cloudspaces/eyeos-u1db | eyeos/extern/u1db/Protocol_v1Test.py | Python | agpl-3.0 | 13,318 | 0.003681 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'root'
import unittest
from mock import Mock
from Protocol_v1 import Protocol_v1
import json
import u1db
import os
class Protocol_v1Test (unittest.TestCase):
def setUp(self):
self.protocol = Protocol_v1(True)
def tearDown(self):
os.re... | """
method: protocol
when: called
with: typeSelectAndList
should: returnArray
"""
def test_protocol_called_typeSelectAndList_returnArray(self):
params = '{"type":"select","lista":[{"file_id":"124568","user_eyeos":"eyeos"}]}'
self.protocol.select = Mock()
self.protocol.... | .protocol.select.assert_called_once_with("124568","eyeos")
self.assertEquals('[]',result)
"""
method: protocol
when: called
with: typeUpdateAndList
should: updateCorrect
"""
def test_protocol_called_typeUpdateAndList_updateCorrect(self):
params = '{"type":"update","lista":[{... |
PyORBIT-Collaboration/py-orbit | py/orbit/py_linac/lattice_modifications/rf_models_modifications_lib.py | Python | mit | 21,812 | 0.032597 | #!/usr/bin/env python
#--------------------------------------------------------------
# The functions for the lattice modifications to replace the base
# RF gap nodes with
# 1. The Axis Fields nodes.
# The initial base RF gap nodes have zero length, and the length
# of new nodes is defined by the RF fields on... | msg = msg + "Type of gap no | de=" + rf_gap.getType()
msg = msg + os.linesep
orbitFinalize(msg)
#---- af_rf_gap_dict[rf_gap] = AxisFieldRF_Gap(rf_gap)
#---- rf_gap_ind_up_down_arr[[rf_gap,gap_ind,drift_down_ind,drift_up_ind],...]
(af_rf_gap_dict,rf_gap_ind_up_down_arr) = Make_AxisFieldRF_Gaps_and_Find_Neihbor_Nodes(rf_length_tolera... |
raphaeldussin/brushcutter | examples/dev/example_interp_to_roms.py | Python | gpl-3.0 | 3,077 | 0.015275 | # this example aims at showing ability of ESMF to regrid on ROMS grid
import os
import ESMF
from brushcutter import fill_msg_grid as fill
import matplotlib.pylab as plt
import numpy as np
# This call enables debug logging
ESMF.Manager(debug=True)
# Use example provided with ESMPy
srcdir = '/Users/raphael/tmp_install... | hael/STORAGE/ROMS/GRIDS/' # laptop
#romsdir = '/Volumes/P4/workdir/raphael/work_brushcutter/' # proteus
romsgrid = romsdir + 'CCS_7k_0-360_fred_grd.nc'
# Create | source grid
grid1 = ESMF.Grid(filename=srcgrid,
filetype=ESMF.FileFormat.GRIDSPEC)
# Create the roms grid
grid2 = ESMF.Grid(filename=romsgrid,
filetype=ESMF.FileFormat.GRIDSPEC,
coord_names=["lon_rho", "lat_rho"])
# Create a field on the centers of the grid
field1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.