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 |
|---|---|---|---|---|---|---|---|---|
digitalocean/netbox | netbox/users/migrations/0004_standardize_description.py | Python | apache-2.0 | 400 | 0 | # Generated by Django 3.0.3 on 2020-03-13 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_token_permissions'),
]
operations = [
migrations.AlterField(
model_name='token',
name='description',
... | rField(blank=True, max_length=200),
| ),
]
|
takkaneko/netengtools | fwiloprov.py | Python | mit | 6,508 | 0.006454 | #!/usr/bin/env python3
# fwiloprov.py
import re
import getpass
import pexpect
from pexpect import EOF
from pexpect import TIMEOUT
from pexpect import ExceptionPexpect
from locationcode import Loccode
from networksid import NWdevice
from ipaddress import ip_address
from ipaddress import ip_network
from ipa... | R: ILO VLAN MUST BE BETWEEN 900 AND 949.\n')
except AtrributeError:
print('ERROR: AttributeError.\n')
# 2. DEPTHCODE:
iloDepth = getDepth('firewall','9901',[])
# 3. ILO SUBNET:
if mfwloc.site == 'iad':
ilonet = ip_network('10.176.0.0/16')
else:
ilonet... | fw_interface = input('Enter the firewall interface for the iLO segment (e.g, eth1, s1p1, gi0/4, etc.): ').strip()
if fw_interface in devicePorts(mfw):
break
else:
print('ERROR: INVALID INTERFACE\n')
except AttributeError:
print('ERROR... |
tymofij/adofex | transifex/releases/migrations/0001_initial.py | Python | gpl-3.0 | 323 | 0.009288 |
fro | m south.db import db
from django.db import models
from transifex.releases.models import *
class Migration:
def forwards(self, orm):
"Write your forwards migration here"
def backwards(self, orm):
"Write your backwards migration here"
models = {
}
complete_apps = [' | releases']
|
openatx/uiautomator2 | examples/runyaml/run.py | Python | mit | 3,918 | 0.002061 | #!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = | "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screenshot"
EXIST = "assert_exist"
W | AIT = "wait"
def split_step(text: str):
__alias = {
"点击": CLICK,
"上滑": SWIPE_UP,
"右滑": SWIPE_RIGHT,
"左滑": SWIPE_LEFT,
"下滑": SWIPE_DOWN,
"截图": SCREENSHOT,
"存在": EXIST,
"等待": WAIT,
}
for keyword in __alias.keys():
if text.startswith(ke... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/clothing/shared_clothing_dress_formal_26.py | Python | mit | 462 | 0.047619 | # | ### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/clothing/shared_clothing_dress_formal_26.iff"
result.attrib... | |
krisss2121/bpmn-python | bpmn_python/graph/classes/events/intermediate_catch_event_type.py | Python | gpl-3.0 | 478 | 0 | # coding=utf-8
"""
Class used for representing tIntermediateCatchEvent of BPMN 2.0 graph
"""
import graph.classes.events.catch_event_type as catch_event
class IntermediateCatchEvent(catch_event.CatchEvent):
"""
Class used for representing tIntermedia | teCatchEvent of BPMN 2.0 graph
"""
def __init__(self):
"""
Default constructor, initializes | object fields with new instances.
"""
super(IntermediateCatchEvent, self).__init__()
|
hfp/tensorflow-xsmm | tensorflow/contrib/optimizer_v2/rmsprop_test.py | Python | apache-2.0 | 19,033 | 0.010561 | # Copyright 2015 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... | )
variables.global_variables_initializer().run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval())
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.a | ssertAllCloseAccordingToType(
[[0., 1.]], var0.eval(), atol=0.01)
@parameterized.parameters([dtypes.float32, dtypes.float64])
def testMinimizeSparseResourceVariableCentered(self, dtype):
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x... |
hall1467/wikidata_usage_tracking | python_analysis_scripts/longitudinal_misalignment/calculate_intermediate_sums.py | Python | mit | 2,652 | 0.006033 | """
Post processing (subset of columns) to calculate intermediate sum edit counts
and other variables. Date sorted.
Usage:
calculate_intermediate_sums (-h|--help)
calculate_intermediate_sums <input> <output>
[--debug]
[--verbose]
Options:
-h... | <input> Path to file to process.
<output> Wh | ere revisions results
will be written
--debug Print debug logging to stderr
--verbose Print dots and stuff to stderr
"""
import docopt
import sys
import logging
import operator
from collections import defaultdict
import mysqltsv
logger = logging.getLogger(__name__)
def main(argv=No... |
sandialabs/BioCompoundML | bcml/Parser/build_training.py | Python | bsd-3-clause | 6,250 | 0.00048 | """
This process takes in the training dataset and outputs
a data structure that includes the name of the molecule,
the predictor, and the CAS number
Attributes:
input_file (str): This is the training file that
is read by the output
Instance (class): This is a private class which
structures each instanc... | orestClassifier requires no missing data,\
features being imputed by mean')
X = self.train
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(X)
| self.train = imp.transform(X)
rf = RandomForestClassifier(n_jobs=-1, oob_score=True, max_depth=5)
feat_selector = boruta_py.BorutaPy(rf, n_estimators='auto',
verbose=verbose, seed=seed)
feat_selector.fit(self.train, self.predictors)
self.feature... |
UdK-VPT/Open_eQuarter | mole3/stat_corr/window_wall_west_ratio_MFH_by_building_age_correlation.py | Python | gpl-2.0 | 570 | 0.036842 | # OeQ autogenerated correlation for 'Window/Wall Ratio West in Correlation to | the Building Age'
import math
import numpy as np
from . import oeqCorrelation as oeq
def window_wall_west_ratio_MFH_by_building_age_correlation(*xin):
# OeQ autogenerated correlation for 'Window to Wall Ratio in Western Direction'
A_WIN_W_BY_AW= oeq.correlation(
const= -37846.911859,
a= 7 | 7.3456608212,
b= -0.0592490161432,
c= 2.01631207341e-05,
d= -2.57207834473e-09,
mode= "lin")
return dict(A_WIN_W_BY_AW=A_WIN_W_BY_AW.lookup(*xin))
|
samuel/kokki | kokki/cookbooks/nginx/libraries/sites.py | Python | bsd-3-clause | 535 | 0.013084 |
from os.path import exists
from k | okki import Environment, Execute
def site(name, enable=True):
env = Environment.get_instance()
if enable:
cmd = 'nxensite'
else:
cmd = 'nxdissite'
def _not_if():
e = exists("%s/sites-enabled/%s" % (env.config.nginx.dir, name))
return e if enable else not e
Execute... | otifies = [("reload", env.resources["Service"]["nginx"])],
not_if = _not_if)
|
govarguz/espressopp | src/esutil/RNG.py | Python | gpl-3.0 | 1,767 | 0.006791 | # Copyright (C) 2012,2013,2019
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redis | tribute it and/or modify
# it under the terms of the GNU G | eneral Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ESPResSo++ 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 PARTI... |
Zlash65/erpnext | erpnext/accounts/report/profitability_analysis/profitability_analysis.py | Python | gpl-3.0 | 5,970 | 0.031658 | # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, getdate, formatdate, cstr
from erpnext.accounts.report.financial_statements import filter_accou... | )))
total_row = calculate_values(accounts, gl_entries_by_account, filters)
accumulate_values_into_parents(accounts, accounts_by_name)
data = prepare_data(accounts, filters, total_row, parent_children_map, based_on)
data = filter_out_zero_value_rows(data, parent_children_map,
show_zero_values=filters.get("show_z... | return data
def calculate_values(accounts, gl_entries_by_account, filters):
init = {
"income": 0.0,
"expense": 0.0,
"gross_profit_loss": 0.0
}
total_row = {
"cost_center": None,
"account_name": "'" + _("Total") + "'",
"warn_if_negative": True,
"income": 0.0,
"expense": 0.0,
"gross_profit_loss": 0... |
adregner/HAppy | happy/shell.py | Python | mit | 1,151 | 0.013901 | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def parse_args(argv):
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
... | dd_option('-l', '--level', dest='log_level', default='warn',
help = "Set logging level (debug, info, warn, error) Default: warn")
parser.add_option('-c', '--config', dest='config', default='/etc/happy.conf' | ,
help = "Path to HAppy configuration file. Default: /etc/happy.conf")
options, args = parser.parse_args()
options.subcommand = subcommand
return options
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)(... |
andresriancho/dotcloud-cli | dotcloud/ui/colors.py | Python | mit | 2,257 | 0 | """
dotcloud.ui.colors - Pythonic wrapper around colorama
Usage:
colors = Colors()
# Format string inlining
print '{c.green}->{c.reset} Hello world!'.format(c=colors)
# Call
print colors.blue('Hello world!')
# Wrapper
with colors.red:
print 'Hello world'
"""
import sys
import c... | me """
if color is None:
return None
if not hasattr(colorama.Fore, color.upper()):
raise KeyError('Unknown color "{0}"'.format(color))
return getattr(colorama.Fore, color.upper())
def __enter__(self):
if self.color is not None:
| sys.stdout.write(self.color)
def __exit__(self, type, value, traceback):
if self.color is not None:
sys.stdout.write(colorama.Style.RESET_ALL)
def __str__(self):
if self.color is None:
return ''
return self.color
def __call__(self, text):
... |
nathanielvarona/airflow | airflow/contrib/operators/qubole_operator.py | Python | apache-2.0 | 1,158 | 0.001727 | #
# 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... | ions
# under the License.
"""This module is deprecated. Please use :mod:`airflow.providers.qubole.operators.qubole`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.qubole.operators.qubole import QuboleOperator # noqa
warnings.warn(
"This module is deprecated. Please use `airf | low.providers.qubole.operators.qubole`.",
DeprecationWarning,
stacklevel=2,
)
|
pencilcheck/pttbbs-py | src/pttbbs/screenlets.py | Python | mit | 33,791 | 0.004458 | # -*- encoding: UTF-8 -*-
import struct
from time import localtime
import itertools
import codecs
import gevent
from copy import copy
from copy import deepcopy
import screen
from screen import ForegroundColors, BackgroundColors
from screen import Align
from utility import Dimension
from string import lowercase
retu... | rols[self.focusIndex] if self.focusIndex != None else None
def setFocusedControl(self, control):
for i, item in enumerate(self.controls):
item.focused = False
if item == control:
self.focusIndex = i
item.focused = True
return
def ... | for item in self.controls:
item.update(data)
return self.handleData(data)
def draw(self, force=False):
self.buffer = ""
for item in self.controls:
if item.redrawn and not item.visible:
self.buffer += screen.fillBlank(item.dimension)
... |
OSUmageed/1DSweptCUDA | ResultPlots/ConferencePaper/Parsed/plotit.py | Python | mit | 4,498 | 0.028902 | import numpy as np
import os
import sys
import os.path as op
import matplotlib as mpl
import mpl.pyplot as plt
import palettable.colorbrewer as pal
from datetime import datetime
from cycler import cycler
#plt.rc('axes', prop_cycle=cycler('color', pal.qualitative.Dark2_8.mpl_colors)+
# cycler('marker',['D','o','v','... | end(ho, loc='up | per left', fontsize='medium')
ax1.set_ylabel(ylbl)
ax1.set_xlabel(xlbl)
ax1.set_xlim([heat[0,0],heat[-1,0]])
ho.pop(3)
ho.pop(0)
ax2.semilogx(heat[:,0],heat[:,4], heat[:,0], heat[:,5])
ax2.hold(True)
ax2.semilogx(heat[:,0],heat[:,9], heat[:,0], heat[:,10])
ax2.legend(ho, loc='upper right', fontsize='medium')
ax1.grid... |
nathanhi/deepserve | deepserve/fileupload/views.py | Python | mit | 231 | 0 | # -*- coding: utf-8 -*-
from rest_framework import viewsets
from . import serializers, models
class FileViewSet(viewsets.ModelViewSe | t):
queryset = models.File.objects.all()
serialize | r_class = serializers.FileSerializer
|
UK992/servo | tests/wpt/web-platform-tests/webdriver/tests/support/authentication.py | Python | mpl-2.0 | 800 | 0 | import urllib
def basic_authentication(username=None, password=None, protocol="http"):
from .fixtures | import server_config, url
build_url = url(server_config())
query = {}
| return build_url("/webdriver/tests/support/authentication.py",
query=urllib.urlencode(query),
protocol=protocol)
def main(request, response):
user = request.auth.username
password = request.auth.password
if user == "user" and password == "password":
retur... |
dims/cinder | cinder/image/glance.py | Python | apache-2.0 | 23,309 | 0 | # Copyright 2010 OpenStack Foundation
# Copyright 2013 NTT corp.
# 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/LIC... | """Instantiate a new glanceclient.Client object."""
if version is None:
version = CONF.glance_api_version
params = {}
if use_ssl:
scheme = 'https'
# https specific params
params['insecure'] = CONF.glance_api_insecure
params['ssl_com | pression'] = CONF.glance_api_ssl_compression
params['cacert'] = CONF.glance_ca_certificates_file
else:
scheme = 'http'
if CONF.auth_strategy == 'keystone':
params['token'] = context.auth_token
if CONF.glance_request_timeout is not None:
params['timeout'] = CONF.glance_request... |
AGMMGA/EM_scripts | EM_scripts/tests/mrc2mrc_tests.py | Python | gpl-2.0 | 8,856 | 0.004855 | import sys
import multiprocessing
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from scripts_EM import mrc2mrc as m
# class test_files_operations(unittest.TestCase):
#
# def setUp(self):
# self.files = ['1.mrc', '2.mrc', '3.mrc']
# self.tempdir = te... | with patch('sys.argv', testargs.split()):
# with self .assertRaises(SystemExit):
# a = m.image | Converter()
# a.get_mrc_files()
#
# def test_normal_operation(self):
# testargs = 'foo.py -i {}'.format(self.tempdir)
# with patch('sys.argv', testargs.split()):
# with patch('subprocess.Popen') as mock_popen:
# #mocking subprocess.communicate to avoi... |
point97/hapifis | server/apps/survey/migrations/0036_auto__add_questionreport__del_field_question_filterBy__del_field_quest.py | Python | gpl-3.0 | 7,859 | 0.007126 | # -*- 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 model 'QuestionReport'
db.create_table(u'survey_questionreport', (
(u'question_ptr', se... | s.rela | ted.ForeignKey', [], {'to': u"orm['survey.Survey']"}),
'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 5, 12, 0, 0)'}),
'uuid': ('django.db.models.fields.CharField', [], {'default': "'a9c61729-3f02-4bcc-84d1-c76a9c59a771'", 'max_length': '36', 'primary_ke... |
masfaraud/volmdlr | tests/core.py | Python | gpl-3.0 | 1,065 | 0.002817 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Testing core module functions
"""
import math
import numpy as npy
import volmdlr as vm
v2D_1 = vm.Vector2D(3*npy.random.random(2)-1.5)
| v2D_2 = vm.Vector2D(3*npy.random.random(2)-1.5)
p2D_1 = vm.Point2D(3*npy.random.random(2)-1.5)
p2D_2 = vm.Point2D(3*npy.random.random(2)-1.5)
v3D_1 = vm.Vector3D(3*npy.random.random(3)-1.5)
v3D_2 = vm.Vector3D(3*npy.random.random(3)-1.5)
p3D_1 = vm.Point3D(3*npy.random.random(3)-1.5)
p3D_2 = vm.Point3D(3*npy.random... | v2D_1_normalized.Norm(), 1, abs_tol=1e-9)
assert math.isclose(v2D_1_normalized.Dot(v2D_1),v2D_1.Norm(), abs_tol=1e-9)
# Testing normal vector
normal_v2D_1 = v2D_1.NormalVector()
assert math.isclose(normal_v2D_1.Dot(v2D_1), 0, abs_tol=1e-9)
normal_unit_v2D_1 = v2D_1.NormalVector(unit=True)
assert math.isclose(normal_u... |
GaretJax/csat | csat/acquisition/migrations/0013_auto__add_field_acquisitionsessionconfig_dark_thumbnail.py | Python | mit | 3,962 | 0.008329 | # -*- 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 'AcquisitionSessionConfig.dark_thumbnail'
db.add_column(u'acquisition_acquisitionsessionconfi... | ject_name': 'AcquisitionSessionConfig'},
'completed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'dark_thumbnail': ('django.db.models.fields.Boo... | elds.TextField', [], {'blank': 'True'}),
'graph': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'ma... |
GabrielNicolasAvellaneda/dd-agent | tests/checks/mock/test_cassandra.py | Python | bsd-3-clause | 5,234 | 0.004776 | # stdlib
import logging
import unittest
# project
from dogstream.cassandra import parse_cassandra
logger = logging.getLogger(__name__)
class TestCassandraDogstream(unittest.TestCase):
def testStart(self):
events = parse_cassandra(logger, " INFO [main] 2012-12-11 21:46:26,995 StorageService.java (line 6... | .java (line 268) Saved KeyCache (5 items) in 3 ms")
self.assertTrue(events is None)
def testWarn(self):
events = parse_cassandra(logger, " WARN [MemoryMeter:1] 2012-12-03 20:07:47,158 Memtable.java (line 197) setting live ratio to minimum of 1.0 instead of 0.9416553595658074")
self.assertTr... | a (line 135) Exception in thread Thread[CompactionExecutor:518,1,RMI Runtime]
java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:7... |
okfde/ris-web | scripts/remove_thumbs.py | Python | bsd-3-clause | 2,543 | 0.005899 | # encoding: utf-8
"""
Copyright (c) 2012 - 2015, Marian Steinbach, Ernesto Ruge
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,... | in(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../city")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
des | cription='Generate Fulltext for given City Conf File')
parser.add_argument(dest='city', help=("e.g. bochum"))
options = parser.parse_args()
city = options.city
cityconfig = __import__(city)
connection = MongoClient(config.DB_HOST, config.DB_PORT)
db = connection[config.DB_NAME]
query = {'thu... |
tux-00/ansible | lib/ansible/module_utils/facts/hardware/freebsd.py | Python | gpl-3.0 | 6,910 | 0.001881 | # This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that ... | ufacturer'
)
for (k, v) in DMI_DICT.items():
| if dmi_bin is not None:
(rc, out, err) = self.module.run_command('%s -s %s' % (dmi_bin, v))
if rc == 0:
# Strip out commented lines (specific dmidecode output)
# FIXME: why add the fact and then test if it is json?
d... |
convexengineering/gplibrary | gpkitmodels/GP/aircraft/wing/gustloading.py | Python | mit | 2,004 | 0.001497 | " spar loading for gust case "
import os
from numpy import pi, hstack, array
from ad.admath import cos
import pandas as pd
from gpkit import parse_variables
from gpfit.fit_constraintset import FitCS
from .sparloading import SparLoading
#pylint: disable=invalid-name, no-member, arguments-differ, exec-used
#pylint: disa... | ust 10 [m/s] gust velocity
Ww [lbf] wing weight
v [m/s] vehicle speed
cl [-] wing lift coefficient
Variables of length wing.N
--------------------------
agust [-] | gust angle of attack
cosminus1 self.return_cosm1 [-] 1 minus cosine factor
LaTex Strings
-------------
vgust V_{\\mathrm{gust}}
Ww W_{\\mathrm{w}}
cl c_l
agust \\alpha_{\\mathrm{gust}}
cosminus1 (cos(x... |
hakkeroid/lcconcept | src/layeredconfig/sources/jsonfile.py | Python | bsd-3-clause | 457 | 0 | # -*- coding: utf-8 -*-
import json
from layeredconfig import so | urce
class JsonFile(source.Source):
"""Source for json files"""
def __init__(self, source, **kwargs):
super(JsonFile, self).__init__(**kwargs)
self._source = source
def _read(self):
with open(self._source) as fh:
return json.load(fh)
def _write(self, | data):
with open(self._source, 'w') as fh:
json.dump(data, fh)
|
okwow123/djangol2 | example/env/bin/gifmaker.py | Python | mit | 689 | 0 | #!/home/ilovejsp/project/ad3/django-allauth/example/env/bin/python
#
# The Python Imaging Library
# $Id$
#
# convert sequence format to GIF animation
#
# history:
# 97 | -01-03 fl created
#
# Copyright (c) Secret Labs AB 1997. All rights reserved.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import Image
if __name__ == "__main__":
import sys
if len(sys.argv) < ... | GIF animations")
print("Usage: gifmaker infile outfile")
sys.exit(1)
im = Image.open(sys.argv[1])
im.save(sys.argv[2], save_all=True)
|
kadhikari/navitia | source/jormungandr/jormungandr/georef.py | Python | agpl-3.0 | 5,482 | 0.001642 | # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public t... | his program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from navitiacommon import r | equest_pb2, response_pb2, type_pb2
import logging
from jormungandr import utils
class Kraken(object):
def __init__(self, instance):
self.instance = instance
def place(self, place):
req = request_pb2.Request()
req.requested_api = type_pb2.place_uri
req.place_uri.uri = place
... |
mdpiper/topoflow | topoflow/utils/midpoints.py | Python | mit | 10,558 | 0.014302 |
## Copyright (c) 2001-2009, Scott D. Peckham
## November 2009 (converted from IDL)
#-----------------------------------------------------------------------
# Notes: Use the random midpoint displacement method to create
# a fractal surface/landscape (due to Mandelbrot).
# This can be used as initial s... | = 1
DONE[0,nx - 1] = 1
DONE[ny - 1,0] = 1
DONE[ny - 1,nx - 1] = 1
#----------------------------------------------
EDGE = zeros([ny, nx], dtype='UInt8') |
EDGE[:,0] = 1
EDGE[:,nx - 1] = 1
EDGE[0,:] = 1
EDGE[ny - 1,:] = 1
#------------------------------
# Initialize grid of z-values
#------------------------------
numpy.random.seed(seed)
v = random.normal(loc=0.0, scale=1.0, size=(2, 2))
z = zeros([ny, nx], dtype='Fl... |
vmware/nsxramlclient | tests/clusterprep.py | Python | mit | 2,874 | 0.007658 | # coding=utf-8
#
# Copyright © 2015 VMware, Inc. All Rights Reserved.
#
# 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, co... | 20:
response = session.read('taskFrameworkJobs', uri_parameters={'jobId': job_id})
| session.view_response(response)
status = response['body']['jobInstances']['jobInstance']['status']
if status == completion_status:
return True
else:
time.sleep(30)
status_poll_count += 1
raise Exception('Timeout waiting for Job to complete')
def ma... |
yast/yast-python-bindings | examples/RichText2.py | Python | gpl-2.0 | 673 | 0.011887 | # encoding: utf-8
# Example for a RichText widget
from yast import import_module
import_module('UI')
from yast import *
class RichText2Client:
def main(self):
UI.OpenDialog(
| Opt("defaultsize"),
VBox(
RichText(
Opt("plainText"),
"This is a RichText in plainText mode.\n" +
"No HTML \t\ttags\tare\tsupported\ | there, tabs\tand\tline\tbreaks\n" +
"are output literally \n" +
"as are HTML tags like <b> or <i> or &product;."
),
PushButton(Opt("default"), "&OK")
)
)
UI.UserInput()
UI.CloseDialog()
RichText2Client().main()
|
abesto/fig | tests/unit/cli_test.py | Python | apache-2.0 | 4,148 | 0.000482 | from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import os
import tempfile
import shutil
from .. import unittest
import mock
from compose.cli import main
from compose.cli.main import TopLevelCommand
from compose.cli.errors import ComposeFileNotFound
from six import StringI... | project_dir = tempfile.mkdtemp()
try:
make_files(project_dir, filenames)
command = TopLevelCommand()
command.base_dir = project_dir
return os.path.basename(command.get_config_path())
finally:
shutil.rmtree(project_dir)
def make_files(dirname, filenames):
for fname i... | n(os.path.join(dirname, fname), 'w') as f:
f.write('')
|
Makeystreet/makeystreet | woot/apps/catalog/migrations/0137_auto__add_upfile.py | Python | apache-2.0 | 70,587 | 0.007749 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UpFile'
db.create_table(u'catalog_upfile', (
... | '50'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'catalog.articletag': {
'Meta': {'obj | ect_name': 'ArticleTag'},
'added_time': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'likes_count': ('django.d... |
liumengjun/django-static-precompiler | static_precompiler/compilers/babel.py | Python | mit | 2,171 | 0.001382 | import os
import warnings
from static_precompiler import exceptions, utils
from . import base
__all__ = (
"Babel",
)
class Babel(base.BaseCompiler):
name = "babel"
input_extension = "es6"
output_extension = "js"
def __init__(self, executable="babel", sourcemap_enabled=False, modules=None, plu... | return_code, out, errors = utils.run_command(args)
if return_code:
raise exceptions.StaticCompilationError(errors)
if self.is_sourcemap_enabled:
utils.fix_sourcemap(full_output_path + ".map", source_path, full_output_path)
return self.get_output_path(source_path)
d... | rce)
if return_code:
raise exceptions.StaticCompilationError(errors)
return out
|
Guake/guake | guake/globals.py | Python | gpl-2.0 | 3,863 | 0.001812 | # -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 progra... | pyt | est report",
r"^\s.*\:\:[a-zA-Z0-9\_]+\s",
r"^\s*(.*\:\:[a-zA-Z0-9\_]+)\s",
),
(
"line starts by 'ERROR in Filename:line' pattern (GCC/make). File path should exists.",
r"\s.\S[^\s\s].[a-zA-Z0-9\/\_\-\.\ ]+\.?[a-zA-Z0-9]+\:[0-9]+",
r"\s.\S[^\s\s].(.*)\:([0-9]+)",
),
... |
aabed/mhn | server/mhn/common/templatetags.py | Python | lgpl-2.1 | 65 | 0 | def format_date(dt):
ret | urn dt.strftime('%Y-%m-%d %H:%M:%S' | )
|
FND/gabbi | gabbi/simple_wsgi.py | Python | apache-2.0 | 3,301 | 0 | #
# Copyright 2014, 20 | 15 Red Hat. All Rights Reserved.
#
# Author: Chris Dent <chdent@redhat.com>
#
# 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 requ... | aw 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.
"""
SimpleWsgi provides a WSGI callab... |
gkonstantyno/construct | construct/protocols/layer2/arp.py | Python | mit | 2,137 | 0.04773 | """
Ethernet (TCP/IP protocol stack)
"""
from binascii import unhexlify
from construct import *
from construct.protocols.layer3.ipv4 import IpAddressAdapter
from ethernet import MacAddressAdapter
def HwAddress(name):
return IfThenElse(name, lambda ctx: ctx.hardware_type == "ETHERNET",
MacAddressAdapter(... | NNEL = 18,
IEEE1394 = 24,
HIPARP = 28,
ISO7816_3 = 29,
ARPSEC = 30,
IPSEC_TUNNEL = 31,
INFINIBAND = 32,
),
Enum(UBInt16("protocol_type"),
IP = 0x0800,
),
UBInt8("hwaddr_length"),
UBInt8("protoaddr_length"),
Enum(UBInt16("opcode"),
R... | REPLY = 2,
REQUEST_REVERSE = 3,
REPLY_REVERSE = 4,
DRARP_REQUEST = 5,
DRARP_REPLY = 6,
DRARP_ERROR = 7,
InARP_REQUEST = 8,
InARP_REPLY = 9,
ARP_NAK = 10
),
HwAddress("source_hwaddr"),
ProtoAddress("source_protoaddr"),
HwAddress("d... |
tboyce021/home-assistant | homeassistant/components/rfxtrx/__init__.py | Python | apache-2.0 | 16,421 | 0.00067 | """Support for RFXtrx devices."""
import asyncio
import binascii
from collections import OrderedDict
import copy
import logging
import RFXtrx as rfxtrxmod
import async_timeout
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA
fro... | ID] = device_id
|
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=data,
)
)
return True
async def async_setup_entry(hass, entry: config_entries.ConfigEntry):
"""Set up the RFXtrx component.""... |
cyclus/cyc3d | data_to_json.py | Python | bsd-3-clause | 912 | 0.006579 | #!/usr/bin/env python
import os
import json
from argparse import ArgumentParser
from datetime import datetime
import time
import numpy as np
from tools import diff_last, cost_val, load_kind
def year_to_ms(y):
"""converts years to milliseconds."""
x = datetime(y, 1, 1)
x = time.mktime(x.timetuple()) * 10... | nt(x)
def main():
parser = ArgumentParser()
parser.add_argu | ment('filename')
parser.add_argument('-k', dest="kind", help="waste or cost or newcost", default="waste")
ns = parser.parse_args()
data = load_kind(ns.filename, ns.kind)
dates = map(year_to_ms, data['year'])
j = [{"key": k, "values": zip(dates, np.asarray(data[k], 'i8'))} \
for k in data.dt... |
patrickod/fixture | fixture/test/test_loadable/test_django/util.py | Python | lgpl-2.1 | 579 | 0.008636 | """This is mostly a copy of methods and internal classes from loadable"""
from django.db.models.loading import get_models
from fixture.loadable.loadable import DeferredStoredObject
def assert_empty(mod):
for model in get_models(mod):
assert model.objec | ts.count() == 0
def resolve_stored_object(column_val):
if type(column_val)==DeferredStoredObject:
return column_val.get_stored_object_from_loader(self)
else:
return column_val
def get_column_vals(row):
for c in row.columns():
yield (c, resolve_store | d_object(getattr(row, c))) |
Oinweb/py-fly | api/management/commands/evaluate_quiz.py | Python | bsd-2-clause | 3,663 | 0.001092 | import os
import sys
import json
from datetime import datetime
from django.db import connection, transaction
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from fly_project import constants
from api.mo... | n_submission.f is not question_answer.f_is_correct:
is_right = False
if is_right:
question_submission.mark = 1
| else:
question_submission.mark = 0
question_submission.save()
# Step 4: Iterate through all the submitted Questions and perform a
# total mark tally of the Quiz and then mark the Quiz either a success
# or a failure.
total_m... |
google-research/language | language/bert_extraction/steal_bert_qa/utils/filter_queries_victim_agreement.py | Python | apache-2.0 | 5,977 | 0.009035 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | Filer the dataset based on the filtering scheme.
if FLAGS.scheme == "random":
random.shuffle(qa_f1)
qa_f1 = {x[0]: x[2] for x in qa_f1[:FLAGS.train_set_size]}
elif FLAGS.scheme == "top_f1":
qa_f1 = {x[0]: x[2] for x in qa_f1[:FLAGS.train_set_size]}
elif FLAGS.scheme == "bottom_f1":
qa_f1 = {x[0]:... | eturn
output_data_orig = {"data": [], "version": FLAGS.version}
# A total of len(preds_data) + 1 datasets are constructed, each with all
# all possible answers for the filtered questions.
# First, make a dataset with the original pool_dataset's answers.
# Run through the pool dataset and add all those que... |
martomo/SublimeTextXdebug | xdebug/helper/helper.py | Python | mit | 1,497 | 0.000668 | """
Helper module for Python version 3.0 and above
- Ordered dictionaries
- Encoding/decoding urls
- Unicode/Bytes (for sending/receiving data from/to socket, base64)
- Exception handling (except Exception as e)
"""
import base64
from urllib.parse import unquote, quote
from collections import OrderedDict
def modulen... | se64 byte string, decode to convert to UTF8 string
return base64.b64encode(data.encode('ascii')).decode('utf8')
def unicode_chr(code):
return chr(code)
def unicode_string(string):
# Python 3.* uses unicode by default
return string
def is_digit(string):
# Check if string is digit
return isi... | isinstance(value, int)
|
MaxMorgenstern/EmeraldAI | EmeraldAI/Logic/ROS/Serial/SerialFinder.py | Python | apache-2.0 | 888 | 0.005631 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
import itertools
class SerialFin | der():
_command = """ls -al /sys/class/tty/ttyUSB* | grep -o "/sys/class/tty/ttyUSB.*"| sed 's/ -> .*//'"""
_replace = "/sys/class/tty"
_replaceWith = "/dev"
def Find(self):
proc = subprocess.Popen([self._command], stdout=subprocess.PIPE, shell=True)
(out, _) = proc.communicate()
... |
def __split(self, data):
lines = []
for _, group in itertools.groupby(data, self.__groupSeparator):
line = ''.join(str(e) for e in group)
line = line.strip()
if (len(line) > 1):
lines.append(line.replace(self._replace, self._replaceWith))
... |
VirusTotal/misp-modules | misp_modules/modules/expansion/sophoslabs_intelix.py | Python | agpl-3.0 | 6,396 | 0.004378 | import json
import requests
import base64
from . import check_input_attribute, checking_error, standard_error_message
from pymisp import MISPEvent, MISPObject
from urllib.parse import quote
moduleinfo = {'version': '1.0',
'author': 'Ben Verschaeren',
'description': 'SOPHOSLabs Intelix Integ... | n attribute else attribute['value1']
| getattr(client, mapping[attribute['type']])(attribute_value)
return client.get_result()
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
RafaelPAndrade/LEIC-A-IST | RC/Proj/CS.py | Python | mit | 16,058 | 0.002678 | #!/usr/bin/env python3
import socket, sys, getopt, os
from signal import signal, pause, SIGINT, SIGTERM, SIG_IGN
from pickle import load, dump
from multiprocessing import Process
from multiprocessing.managers import SyncManager
from lib.server import tcp_server, udp_server, udp_client
from lib.utils import (read_byte... | p_client. | start()
def authenticate_user(valid_users, conn):
""" Authenticates user, returns (user,pass) (AUT/AUR) """
username = read_bytes_until(conn, " ")
password = read_bytes_until(conn, "\n")
print("-> AUT {} {}".format(username, password))
res = (False, False)
status = "NOK"
if username no... |
uber/tchannel-python | tests/tornado/test_peer.py | Python | mit | 12,004 | 0.000083 | # encoding=utf8
# Copyright (c) 2016 Uber Technologies, Inc.
#
# 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, mod... | ection.outgoing.call_count == 2
@pytest.mark.gen_test
def test_peer_connection_network_failure():
# Network errors in connecting to a peer must be retried with a different
# peer.
healthy = TChannel('healthy-server')
healthy.listen()
unhe | althy = TChannel('unhealthy-server')
unhealthy.listen()
# register the endpoint on the healthy host only to ensure that the
# request wasn't made to the unhealthy one.
@healthy.raw.register('hello')
def endpoint(request):
return 'world'
known_peers = [healthy.hostport, unhealthy.hostpo... |
ncbray/pystream | sandbox/learning/__init__.py | Python | apache-2.0 | 578 | 0.00173 | # Copyright 2011 Nicholas Bray
#
# Licensed under the Apache Licens | e, 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.
|
bearpaw/pytorch-pose | pose/models/__init__.py | Python | gpl-3.0 | 80 | 0 | from .hou | rglass import *
from .hourglass_gn import *
from .pose_resnet impo | rt *
|
VROOM-Project/vroom-scripts | benchmarks/compare_to_BKS.py | Python | bsd-2-clause | 5,946 | 0.000841 | # -*- coding: utf-8 -*-
import json
import numpy as np
import sys
# Compare a set of computed solutions to best known solutions on the
# same problems.
# See src/vrptw_to_json.py, src/pdptw_to_json.py and
# src/hvrp_to_json.py.
CUSTOM_PRECISION = 1000
BENCH_DOUBLE_PRECISION = 100
CUSTOM_PRECISION_CLASSES = [
"sol... | ",".join(
[
"Instance",
"Jobs",
"Vehicles",
"tightness",
"Best known cost",
"Assigned jobs",
"Used vehicles",
"Solution cost",
"Unassigned jobs",
... | assigned = []
unassigned = []
tightnesses = []
gaps = []
computing_times = []
assigned_jobs = 0
total_files = len(files)
job_ok_files = 0
optimal_sols = 0
for f in files:
instance = f[0 : f.rfind("_sol.json")]
instance = instance[instance.rfind("/") + 1 :]
... |
czpython/django-cms | cms/test_utils/project/pluginapp/plugins/revdesc/models.py | Python | bsd-3-clause | 1,417 | 0.003529 | # -*- coding: utf-8 -*-
from django.db import models
from cms.models import CMSPlugin
# sorry for the cryptic names. But we were hitting max lengths on Django 1.6
# and 1.7 with the too long names otherwise.
class UnalteredPM(CMSPlu | gin):
title = models.CharField(max_length=50)
search_fields = ['title']
class NoRelNmePM(CMSPlugin):
cmsplugin_ptr = models.OneToOneField(CMSPlugin, related_name='+', parent_link=True)
title = models.CharField(max_length=50)
search_fields = ['title']
class NoRelQNmePM(CMSPlugin):
cmsplugin_p... |
class CustomRelQNmePM(CMSPlugin):
cmsplugin_ptr = models.OneToOneField(CMSPlugin, related_query_name='reldesc_custom_relqn', parent_link=True)
title = models.CharField(max_length=50)
search_fields = ['title']
class CustomRelNmePM(CMSPlugin):
cmsplugin_ptr = models.OneToOneField(CMSPlugin, related_n... |
cxxgtxy/tensorflow | tensorflow/python/lib/core/bfloat16_test.py | Python | apache-2.0 | 17,140 | 0.004959 | # Copyright 2015 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... | self.assertEqual(v > w, bfloat16(v) > bfloat16(w))
def testGreaterEqual(self):
for v in FLO | AT_VALUES:
for w in FLOAT_VALUES:
self.assertEqual(v >= w, bfloat16(v) >= bfloat16(w))
def |
batpad/osmcha-django | osmchadjango/changeset/migrations/0002_auto_20150804_0119.py | Python | gpl-3.0 | 448 | 0.002232 | # -* | - coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('changeset', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='changeset',
name='reaso... | easons'),
),
]
|
28ideas/quant-econ | quantecon/robustlq.py | Python | bsd-3-clause | 8,434 | 0.002846 | """
Filename: robustlq.py
Authors: Chase Coleman, Spencer Lyon, Thomas Sargent, John Stachurski
Solves robust LQ control problems.
"""
from __future__ import division # Remove for Python 3.sx
import numpy as np
from lqcontrol import LQ
from quadsums import var_quadratic_sum
from numpy import dot, log, sqrt, identit... | F : array_like
A self.k x self.n array
Retu | rns
=======
K : array_like, dtype = float
P : array_like, dtype = float
"""
Q2 = self.beta * self.theta
R2 = - self.R - dot(F.T, dot(self.Q, F))
A2 = self.A - dot(self.B, F)
B2 = self.C
lq = LQ(Q2, R2, A2, B2, beta=self.beta)
P, neg_K, d =... |
xiandiancloud/edxplaltfom-xusong | lms/djangoapps/instructor/views/legacy.py | Python | agpl-3.0 | 82,769 | 0.003383 | """
Instructor Views
"""
## NOTE: This is the code for the legacy instructor dashboard
## We are no longer supporting this file or accepting changes into it.
from contextlib import contextmanager
import csv
import json
import logging
import os
import re
import requests
from collections import defaultdict, OrderedDict... | unique_student_identifier = strip_if_string(unique_student_identifier)
msg = ""
try:
if "@" in unique_student_identifier:
student = User.objects.get(email=unique_student_identifier)
| else:
student = User.objects.get(username=unique_student_identifier)
msg += _("Found a single student. ")
except User.DoesNotExist:
student = None
msg += "<font color='red'>{text}</font>".format(
text=_("Couldn't find student with that emai... |
jorsea/vertical-ngo | logistic_order_requisition_donation/__openerp__.py | Python | agpl-3.0 | 1,324 | 0 | # -*- coding: utf-8 -*-
#
#
# Copyright 2014 Camptocamp SA
# Au | thor: Yannick Vaucher
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distri... | ICULAR 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/>.
#
#
{"name": "Link 'Logistics Order - Donation' and 'Logistics Requisition'",
"su... |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tools/cocos2d-console/plugins/framework/framework_update.py | Python | mit | 934 | 0.001071 |
import cocos
from MultiLanguage import MultiLanguage
fro | m package.helper import ProjectHelper
class FrameworkUpdate(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "update-framework"
@staticmethod
def brief_des | cription():
return MultiLanguage.get_string('FRAMEWORK_UPDATE_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.bri... |
mclois/iteexe | nevow/appserver.py | Python | gpl-2.0 | 13,064 | 0.002526 | # -*- test-case-name: nevow.test.test_appserver -*-
# Copyright (c) 2004 Divmod.
# See LICENSE for details.
"""A web application server built using twisted.web
"""
import cgi
from copy import copy
from urllib import unquote
from types import StringType
import warnings
from twisted.web import server
from twisted.web... | th the new sessions
return server.Request.getSession(self, sessionInterface)
def URLPath(self):
return url.URL.fromContext(self)
def rememberRootURL(self, url=None):
"""
Remember the currently-processed part of the URL for later
recalling.
"""
if url is ... | return server.Request.rememberRootURL(self)
else:
self.appRootURL = url
def sessionFactory(ctx):
"""Given a RequestContext instance with a Request as .tag, return a session
"""
return ctx.tag.getSession()
requestFactory = lambda ctx: ctx.tag
class NevowSite(server.Site):
... |
BjoernSch/WLANThermo_v2 | software/usr/sbin/wlt_2_nextion.py | Python | gpl-3.0 | 53,246 | 0.006524 | #!/usr/bin/python
# coding=utf-8
# Copyright (c) 2015, 2016 Björn Schrader
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | x00'):
message['type'] = 'inv_instr'
message['iserr'] = True
message['errmsg'] = 'Invalid instruction'
is_return = True
elif (message['raw'][0] == '\x01'):
message['type'] = 'ok'
message['errmsg'] = 'Successful execution of instruction'
... | '\x03'):
message['type'] = 'inv_pageid'
message['iserr'] = True
message['errmsg'] = 'Page ID invalid'
is_return = True
elif (message['raw'][0] == '\x04'):
message['type'] = 'inv_pictid'
message['iserr'] = True
message['errmsg']... |
reddymeghraj/showroom | erpnext/buying/doctype/item_info/test_item_info.py | Python | agpl-3.0 | 300 | 0.01 | # | -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Item Info')
class TestItemInfo( | unittest.TestCase):
pass
|
GPContributors/PyGP | pygp/loadfile.py | Python | lgpl-3.0 | 19,068 | 0.007971 | import zipfile
import os
import array
import collections
from struct import unpack
from ctypes import c_ubyte
import pygp.utils as utils
import pygp.constants as constants
import pygp.crypto as crypto
class Loadfile(object):
'''
This class builds a LoadFile object from a disk-based file.
and provides bas... | s["Staticfield"]
if "Export" in self.components.keys():
rawCodeAsString += self.components["Export"]
if "ConstantPool" in self.components.keys():
rawCodeAsString += self.components["ConstantPool"]
if "RefLocation" in self.components.keys():
rawCodeAsString ... | rawCodeAsString += self.components["Descriptor"]
return rawCodeAsString
def get_code_size(self):
''' returns the code size of the package '''
size = int(len(self.get_raw_code())/2)
return size
def get_estimate_size(self):
''' returns the estimate size of... |
ericmjl/reassortment-simulation-and-reconstruction | sequence.py | Python | mit | 1,435 | 0.036934 | """
Author: Eric J. Ma
Affiliation: Massachusetts Institute of Technology
"""
from random import choice
from generate_id import generate_id
class Sequence(object):
"""
The Sequence object is the lowest level object in the pathogen simulator.
It provides a container for storing seed sequences for the pathogens pre... | uper(Sequence, self).__init__()
self.sequence = None
if sequence == None:
self.sequence = self.generate_sequence(length)
else:
self.sequence = sequence
if id == None:
self.id = generate_id()
else:
self.id = id
def __repr__(self):
return self.id
def generate_sequence(self, length):
"""... | quence to that sequence.
"""
sequence = ''
for i in range(length):
letter = choice(['A', 'T', 'G', 'C'])
sequence += letter
return sequence |
sunilsm7/django_resto | profiles/migrations/0003_remove_profile_following.py | Python | mit | 398 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-21 06:05
from __future__ import unicode_literals
from djan | go.db import migrations
cl | ass Migration(migrations.Migration):
dependencies = [
('profiles', '0002_auto_20170721_1129'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='following',
),
]
|
jawilson/home-assistant | homeassistant/components/roomba/roomba.py | Python | apache-2.0 | 3,241 | 0 | """Class for Roomba devices."""
import logging
from homeassistant.components.vacuum import SUPPORT_FAN_SPEED
from .irobot_base import SUPPORT_IROBOT, IRobotVacuum
_LOGGER = logging.getLogger(__name__)
ATTR_BIN_FULL = "bin_full"
ATTR_BIN_PRESENT = "bin_present"
FAN_SPEED_AUTOMATIC = "Automatic"
FAN_SPEED_ECO = "Eco... | fan_speed
@property
def fan_speed_list | (self):
"""Get the list of available fan speed steps of the vacuum cleaner."""
return FAN_SPEEDS
async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
if fan_speed.capitalize() in FAN_SPEEDS:
fan_speed = fan_speed.capitalize()
_LOGGER.deb... |
rwightman/pytorch-image-models | timm/models/densenet.py | Python | apache-2.0 | 15,611 | 0.003139 | """Pytorch Densenet implementation w/ tweaks
This file is a copy of https://github.com/pytorch/vision 'densenet.py' (BSD-3-Clause) with
fixed kwargs passthrough and addition of dynamic global avg/max pool.
"""
import re
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as n... | stem_only=True):
self.num_classes = num_classes
self.drop_rate = drop_rate
super(DenseNet, self).__init__()
# Stem
deep_stem = 'deep' in stem_type # 3x3 deep stem
num_init_features = growth_rate * 2
if aa_layer is None:
st | em_pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
else:
stem_pool = nn.Sequential(*[
nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
aa_layer(channels=num_init_features, stride=2)])
if deep_stem:
stem_chs_1 = stem_chs_2 = growth_rate
... |
axmachado/simplepos | simplepos/codegen/boolean.py | Python | gpl-3.0 | 15,374 | 0.00013 | # -*- coding: utf-8 -*-
"""
Copyright © 2017 - Alexandre Machado <axmachado@gmail.com>
This file is part of Simple POS Compiler.
Simnple POS Compiler 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 Found... | sult, '1')]
elseBlock = [Assignment(typedefs.INT, exprResult, '0')]
ifStm = IfStatement(self.codeBlock)
ifStm.selfGenerated(conditional, ifBlock, elseBlock)
self.codeBlock.addStatements(ifStm)
return "$ | (%s)" % exprResult
def procLogicalExpression(self, value):
"processes a logical expression"
exprResult = self.codeBlock.currentScope().autoInt()
logExpr = LogicalExpr(value.left, value.operator, value.right)
logExpr.preConditionalCode(self.codeBlock, exprResult)
return "$(%s... |
lukas-hetzenecker/home-assistant | tests/components/dexcom/test_config_flow.py | Python | apache-2.0 | 4,420 | 0 | """Test the Dexcom config flow."""
from unittest.mock import patch
from pydexcom import AccountError, SessionError
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.dexcom.const import DOMAIN, MG_DL, MMOL_L
from homeassistant.const import CONF_UNIT_OF_MEASUREMENT, CONF_USERNAME
... | result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONFIG,
)
assert | result2["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_unknown_error(hass):
"""Test we handle unknown error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
... |
eltoncarr/tubular | tubular/tests/test_utils.py | Python | agpl-3.0 | 3,467 | 0.001154 | """
Tests of the utility code.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from copy import copy
import boto
from boto.ec2.autoscale.launchconfig import LaunchConfiguration
from boto.ec2.autoscale.group import AutoScalingGroup
from boto.ec2.autoscale import Tag
import six
def c... | propagate_at_launch=True
) for k, v in six.iteritems(tags)
]
if elbs is None:
elbs = []
# Create asgs
conn = boto.ec2.autoscale.connect_to_region('us-east-1')
config = LaunchConfiguration(
name='{}_lc'.format(asg_name),
image_id=ami_id,
instance_type='t2... | reate_launch_configuration(config)
group = AutoScalingGroup(
name=asg_name,
availability_zones=['us-east-1c', 'us-east-1b'],
default_cooldown=60,
desired_capacity=2,
load_balancers=elbs,
health_check_period=100,
health_check_type="EC2",
max_size=2,
... |
robin900/sqlalchemy | test/orm/test_deferred.py | Python | mit | 30,663 | 0.003131 | import sqlalchemy as sa
from sqlalchemy import testing, util
from sqlalchemy.orm import mapper, deferred, defer, undefer, Load, \
load_only, undefer_group, create_session, synonym, relationship, Session,\
joinedload, defaultload, aliased, contains_eager, with_polymorphic
from sqlalchemy.testing import eq_, Asse... | mapper(Order, orders, properties=dict(
description=deferred(orders.c.description, group='primary'),
opened=deferred(orders.c.isopen, group='primary')))
sess = create_session()
o = Order()
sess.add(o)
o.id = 7
| def go():
o.description = "some description"
self.sql_count_(0, go)
def test_unsaved_group_2(self):
orders, Order = self.tables.orders, self.classes.Order
mapper(Order, orders, properties=dict(
description=deferred(orders.c.description, group='primary'),
... |
MTG/pycompmusic | test/essentia/rhythmTest.py | Python | agpl-3.0 | 306 | 0.006536 | #!/usr | /bin/env python
import rhythm
re = rhythm.RhythmExtract()
# fname = '/media/Data/Data/CompMusicD | B/Carnatic/audio/Aneesh_Vidyashankar/Pure_Expressions/7_Jagadoddharana.mp3'
fname = '/media/Code/UPFWork/PhD/Data/CMCMDa/mp3/adi/10014_1313_Bhagyadalakshmi.mp3'
results = re.run(fname)
print("All done")
|
anaran/kuma | kuma/wiki/managers.py | Python | mpl-2.0 | 8,955 | 0.000335 | from datetime import date, datetime, timedelta
from django.core import serializers
from django.db import models
import bleach
from constance import config
from .constants import (ALLOWED_TAGS, ALLOWED_ATTRIBUTES, ALLOWED_STYLES,
TEMPLATE_TITLE_PREFIX)
from .content import parse as parse_conte... |
def get_by_stale_rendering(self):
| """Find documents whose renderings have gone stale"""
return (self.exclude(render_expires__isnull=True)
.filter(render_expires__lte=datetime.now()))
def allows_add_by(self, user, slug):
"""
Determine whether the user can create a document with the given
slu... |
mattrobenolt/django-sudo | sudo/__init__.py | Python | bsd-3-clause | 246 | 0 | """
sudo
~~~~
:copyright: (c) 2020 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
try:
| VERSION = __import__("pkg_resources").get_di | stribution("sudo").version
except Exception: # pragma: no cover
VERSION = "unknown"
|
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/audit/auditmessages.py | Python | apache-2.0 | 6,791 | 0.035488 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | er the License.
#
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.c | itrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class auditmessages(base_resource) :
""" Configuration for audit message resource. """
def __init__(self... |
jgillis/casadi | documentation/examples/solvers/exacthessian.py | Python | lgpl-3.0 | 2,328 | 0.020189 | #
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved.
#
# CasADi is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Pub... | sian with the help of the Rosenbrock function
x=SX("x")
y=SX("y")
obj = (1-x)**2+100*(y-x**2)**2
#! We choose to add a single constraint
constr = x**2+y**2
f=SXFunction([vertcat([x,y])],[obj])
g=SXFunction([vertcat([x,y])],[constr])
solver = IpoptSolver(f,g)
#! We need the hessian of the lagrangian.
#! A pro... | calar factor
lambd=SX("lambd") # Multipier of the problem, shape m x 1.
xy = vertcat([x,y])
h=SXFunction([xy,lambd,sigma],[sigma*hessian(obj,xy)+lambd*hessian(constr,xy)])
#! We solve the problem with an exact hessian
solver = IpoptSolver(f,g,h)
solver.init()
solver.input("lbx").set([-10]*2)
solver.input("ubx").... |
mansenfranzen/notebooks | Confidence Interval Simulation Bokeh/model.py | Python | mit | 2,316 | 0.003886 | """This module contains the data handler."""
import numpy as np
import tssim
from bokeh.models import ColumnDataSource
def create_source( | series):
return ColumnDataSource(data=dict(x=series.index.values, y=series.values))
def dummy1():
ts = tssim.TimeSeries(start="2017-04-04", freq="D", periods=1100)
ts. | add("Noise", lambda x: x * 0 + np.random.normal(0, 0.25, size=x.shape[0]))
ts.add("Log", lambda x: np.log(x))
ts.add("Increase", lambda x: x * 0.01, condition=lambda x: x < 1)
return ts.generate().values
def dummy2():
ts = tssim.TimeSeries(start="2017-04-04", freq="D", periods=1100)
ts.add("Noise",... |
pkdevbox/trac | trac/web/session.py | Python | bsd-3-clause | 22,324 | 0.000134 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2014 Edgewall Software
# Copyright (C) 2004 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2004-2006 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2006 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2008 Matt Good <matt@matt-good.net>
# All rights reserved.
#... | :
dict.__setitem__(self, key, unicode(value))
def set(self, key, value, default=None):
"""Set a variable in the session, or remove it if it's equal to the
default value.
"""
value = unicode(val | ue)
if default is not None:
default = unicode(default)
if value == default:
self.pop(key, None)
return
dict.__setitem__(self, key, value)
def get_session(self, sid, authenticated=False):
self.env.log.debug("Retrieving session for ID %r... |
eddiejessup/pizza | src/dump.py | Python | gpl-2.0 | 39,268 | 0.001248 | import sys
import commands
import re
import glob
import types
from os import popen
from math import * # any function could be used by set()
import numpy as np
oldnumeric = False
try:
from DEFAULTS import PIZZA_GUNZIP
except:
PIZZA_GUNZIP = "gunzip"
class dump:
def __init__(self, *list):
... | ])
item = f.readline()
| if len(self.names) == 0:
self.scale_original = -1
xflag = yflag = zflag = -1
words = item.split()[2:]
if len(words):
for i in range(len(words)):
if words[i] == "x" or words[i] == "xu":
... |
obi-two/Rebelion | data/scripts/templates/object/tangible/ship/crafted/reactor/shared_base_reactor_subcomponent_mk5.py | Python | mit | 499 | 0.044088 | #### NOTICE: THIS FILE IS AUTOGENERATED
# | ### 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/reactor/shared_b | ase_reactor_subcomponent_mk5.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_reactor_subcomponent_mk5")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
TheWardoctor/Wardoctors-repo | script.module.uncoded/lib/resources/lib/sources/de/horrorkino.py | Python | apache-2.0 | 3,418 | 0.005851 | # -*- coding: utf-8 -*-
"""
Covenant Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This prog... | r = dom_parser.parse_dom(r, 'iframe', req='src')
r = [i.attrs['src'] for i in r]
for i in r:
valid, host = source_utils.is_host_valid(i, hostDict)
| if not valid: continue
sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': i, 'direct': False, 'debridonly': False, 'checkquality': True})
return sources
except:
return sources
def resolve(self, url):
return url
def ... |
tuxta/gameframe | GameFrame/EntryTextObject.py | Python | gpl-3.0 | 4,969 | 0 | import pygame
from GameFrame import TextObject, Globals, Level
class EntryTextObject(TextObject):
def __init__(self, room: Level, x: int, y: int, max_len=4):
TextObject.__init__(self, room, x, y, '')
self.max_len = max_len
self.handle_key_events = True
self.accepting_input = True
... | self.text += '1'
key_recognised = True
elif key[pygame.K_2]:
self.text += '2'
key_recognised = True
elif key[pygame.K_3]:
self.text += '3'
key_recognised = True
elif key[pygame.K_4]:
... | key_recognised = True
elif key[pygame.K_6]:
self.text += '6'
key_recognised = True
elif key[pygame.K_7]:
self.text += '7'
key_recognised = True
elif key[pygame.K_8]:
self.text += '8'
k... |
ryokbys/nap | pmd/force_params/QEq_params/extract_QEq_params.py | Python | mit | 3,310 | 0.02145 | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... | """
nstates = (0,2,8,18,32,50)
if atomic_number > 86:
raise ValueError('Atomic number greater than 86 is not available.')
elif atomic_number <= sum_array(nstates,1):
n = 1
elif atomic_number <= sum_array(nstates,2):
n = 2
elif atomic_number <= sum_array(nsta | tes,3):
n = 3
elif atomic_number <= sum_array(nstates,4):
n = 4
elif atomic_number <= sum_array(nstates,5):
n = 5
else:
raise ValueError('Atomic number is something wrong: ',atomic_number)
freedom = (0,2,6,10,14,18,22)
nval = atomic_number - sum_array(nstates,n-1)
... |
velorientc/git_test7 | tests/qt_repomanager_test.py | Python | gpl-2.0 | 2,859 | 0.001749 | import mock, unittest
from mercurial import ui
from tortoisehg.hgqt import thgrepo
def mockrepo(ui, path):
m = mock.MagicMock(ui=ui, root=path)
m.unfiltered = lambda: m
return m
LOCAL_SIGNALS = ['repositoryOpened', 'repositoryClosed']
MAPPED_SIGNALS = ['configChanged', 'repositoryChanged', 'repositoryDest... | elf.repoman.repositoryOpened.connect(
lambda: self.assertTrue(self.repoman.repoAgent('/a' | )))
self.repoman.openRepoAgent('/a')
self.repositoryOpened.assert_called_once_with('/a')
self.repositoryOpened.reset_mock()
# emitted only if repository is actually instantiated (i.e. not cached)
self.repoman.openRepoAgent('/a')
self.assertFalse(self.repositoryOpened.call... |
doktorinjh/WeatherPane | WU_Bridge_GitHub.py | Python | apache-2.0 | 4,290 | 0.007925 | import urllib2
import json
#Get json data from Weather Underground by using IP address
f = urllib2.urlopen('http://api.wunderground.com/api/***KEY***/conditions/forecast/hourly/q/autoip.json')
json_string = f.read()
parsed_json = json.loads(json_string)
#Current Location and Observation Time
location = parse... | recast']['simpleforecast']['forecastday'][1]['low']['fahrenheit']
tomorrow_weather = parsed_json['forecast']['simpleforecast']['forecastday'][1]['conditions']
to | morrow_precip = parsed_json['forecast']['simpleforecast']['forecastday'][1]['pop']
tomorrow_snow = parsed_json['forecast']['simpleforecast']['forecastday'][1]['snow_allday']['in']
#Write output to python text file
#f = open( 'C:\Users\User\Desktop\WU_Test.txt', 'w' ) #For testing purposes
f = open( '/WU_Variabl... |
StellarCN/py-stellar-base | stellar_sdk/xdr/operation_body.py | Python | apache-2.0 | 23,177 | 0.00164 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .allow_trust_op import AllowTrustOp
from .begin_sponsoring_future_reserves_op import BeginSponsoringFutureReservesOp
from .bump_sequ... | "
XDR Source Code::
union switch (OperationType type)
{
ca | se CREATE_ACCOUNT:
CreateAccountOp createAccountOp;
case PAYMENT:
PaymentOp paymentOp;
case PATH_PAYMENT_STRICT_RECEIVE:
PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp;
case MANAGE_SELL_OFFER:
ManageSellOfferOp ma... |
Aroliant/iBeon | python/ibeon.py | Python | mit | 901 | 0.057714 | import re
class ibeon:
def remSpaces(data):
return data.re | place(" ", "")
def remNumbers(data):
return ''.join([x for x in data if not x.isdigit()])
def remSymbols(data):
return re.sub('[^\w]', '', data)
def onlyNumbers(data) | :
return re.sub('[^0-9]', '', data)
def onlyAlpabets(data):
return re.sub('[^A-Za-z]', '', data)
def countSpaces(data):
return data.count(' ')
def countNumbers(data):
return len(re.sub('[^0-9]', '', data))
def countAlpabets(data):
return len(re.sub('[^A-Za-z]', '', d... |
Foxnox/robotique-delpeyroux-monseigne | src/direct_kinematics.py | Python | mit | 1,409 | 0.034776 | from math import *
from Vertex import *
#Length of the three subparts of the robot leg
L1 = 51.0
L2 = 63.7
L3 = 93.0
Alpha = 20.69 #Mecanic constraint on Theta 2
Beta = 5.06 #Mecanic constraint on Theta 3
# Check if the given float match with radian (between 2PI and -2PI)
def radValidation (radian):
return (radian... | = alpha
theta3 = 90-(alpha+beta+theta3)
#print "Angles : " + str(theta1) + " ; " + str(theta2) + " ; " + str(theta3)
theta1=radians(theta1)
theta2=-radians(theta2)
theta3=-radians(theta3)
#Storing all the sinus and cosinus into variable in order to simpl | ify and run the calculation only once
c_1 = cos(theta1)
c_2 = cos(theta2)
c_2_3 = cos(theta2 + theta3)
s_1 = sin(theta1)
s_2 = sin(theta2)
s_2_3 = sin(theta2 + theta3)
#calculation of the projections and the differences due to the robot setting
projection = l1 + (l2 * c_2) + (l3 * c_2_3)
#Calculation of the ... |
openstack/tempest | tempest/api/volume/admin/test_group_snapshots.py | Python | apache-2.0 | 12,992 | 0 | # Copyright 2017 FiberHome Telecommunication Technologies CO.,LTD
# Copyright (C) 2017 Dell Inc. or its subsidiaries.
# 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 Lice... | is in the list
of all group snapshots
8. Delete group snapshot "group_snapshot1"
"""
# Create volume type
volume_type = self.create_volume_type()
# Create group type
group_type = self.create_group_type()
# Create group
grp = self.create_group... | volume_types=[volume_type['id']])
# Create volume
vol = self.create_volume(volume_type=volume_type['id'],
group_id=grp['id'])
# Create group snapshot
group_snapshot_name = data_utils.rand_name('group_snapshot')
group... |
project-callisto/callisto-core | callisto_core/notification/migrations/0005_rename_to_emailnotification.py | Python | agpl-3.0 | 408 | 0 | # -*- codi | ng: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-24 15:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("notification", "0004_delete_old_email_notification")]
operations = [
migrations.RenameModel(
o... | n", new_name="EmailNotification"
)
]
|
SiLab-Bonn/pyBAR | pybar/testing/tools/create_fixture.py | Python | bsd-3-clause | 1,622 | 0.003699 | ''' Script to reduce data files to create unit test fixtures.
'''
import tables as tb
def create_fixture(file_in, file_out, n_readouts, nodes):
with tb.open_file(file_in, 'r') as in_file:
with tb.open_file(file_out, 'w') as out_file:
in_file.copy_node('/configuration', out_file.root, recursiv... | inal_data\LFCMOS_1_14Ne | q\lfcmos_3_efficiency\117_lfcmos_3_ext_trigger_scan.h5',
file_out='small.h5',
n_readouts=100,
nodes=['raw_data', 'meta_data'])
|
DenisCarriere/mapillary | mapillary/geotag.py | Python | mit | 6,563 | 0.001067 | #!/usr/bin/python
# coding: utf8
from upload import create_file_list
import exifread
import math
import pexif
import re
import datetime
import time
from bs4 import BeautifulSoup
from geojson import FeatureCollection, Feature, LineString, Point
import json
def utc_to_localtime(utc_time):
utc_offset_timedelta = da... | lng
dPhi = math.log(
math.tan(end_lat / 2.0 + math.pi / 4.0) /
math | .tan(start_lat / 2.0 + math.pi / 4.0)
)
if abs(dLng) > math.pi:
if dLng > 0.0:
dLng = -(2.0 * math.pi - dLng)
else:
dLng = (2.0 * math.pi + dLng)
y = math.sin(dLng)*math.cos(end_lat)
x = math.cos(start_lat) * math.sin(end_lat) - math.sin(start_lat) *\
mat... |
gtaylor/dott | src/game/parents/base_objects/base.py | Python | bsd-3-clause | 25,944 | 0.001156 | """
Contains base level parents that aren't to be used directly.
"""
from twisted.internet.defer import inlineCallbacks, returnValue
from fuzzywuzzy.process import QRatio
from fuzzywuzzy import utils as fuzz_utils
from src.daemons.server.ansi import ANSI_HILITE, ANSI_NORMAL
from src.daemons.server.objects.exceptions ... | turn self._generic_id_to_baseobject_property_getter('zone_id')
def set_zone(self, obj_or_id):
"""
Sets this object's z | one.
:param obj_or_id: The object or object ID to set as the
object's zone master.
:type obj_or_id: A ``BaseObject`` sub-class or an ``int``.
"""
self._generic_baseobject_to_id_property_setter('zone_id', obj_or_id)
zone = property(get_zone, set_zone)
#noinspection... |
samurailens/sop | app/samplePythonScript/webapp.py | Python | gpl-2.0 | 609 | 0.026273 | from gi.repository import Gtk
from gi.repository import WebKit
class BrowserView:
def __init__(self):
window = Gtk.Window()
window.connect('delete-event',Gtk.main_quit)
self.view = WebKit.WebView()
#self.view.load_uri('http://example.net')
#https://www.raspberrypi.or... | ontent in /var/www/index.html
self.view.load_uri('http://192.168.1.6')
window.add(self.view)
window.fullscreen()
window.show_all()
|
if __name__ == "__main__":
BrowserView()
Gtk.main() |
jgrizou/robot_2WD | python/robotControl/Motors.py | Python | gpl-2.0 | 3,698 | 0.001082 | import threading
import time
MOVEXCOUNT = 20
GETCOUNT = 21
COUNT = 22
RESETCOUNT = 23
RESETEDCOUNT = 24
SETPOSCONTROLSTATUS = 25
SETACCELERATION = 26
SETDECELERATION = 27
SETMAXSPEED = 28
SETSPEED = 40
GETSPEED = 41
SPEED = 42
SETPID = 43
SETPIDLIMIT = 44
class Motors(threading.Thread):
def __init__(self, cmdMes... | e()
inTime = True
while not self.resetedCount and inTime:
time.sleep(1e-6)
if time.time() - startTime > self.timeout:
inTime = False
if not inTime:
return [None, None]
tmp = self.resetedCount
self.resetedCount = []
retur... | KP, KI, KD):
self.KP = float(KP)
self.KI = float(KI)
self.KD = float(KD)
self.cMes.send(SETPID, self.KP, self.KI, self.KD)
def setPIDLimit(self, limit):
self.PIDLimit = float(limit)
self.cMes.send(SETPIDLIMIT, self.PIDLimit)
def setAcceleration(self, acc):
... |
nkouevda/slack-rtm-bot | slack_rtm_bot/handlers/reaction.py | Python | mit | 976 | 0.009221 | import itertools
from .base import MessageHandler
from .. import settings
class ReactionHandler(MessageHandler):
TR | IGGER_ANCHOR = ''
TRIGGER_PREFIX = ''
TRIGGERS = sorted(
settings.EMOJI_REACTIONS.keys() + settings.MESSAGE_REACTIONS.keys())
HELP = 'add emoji and message reaction | s'
def handle_message(self, event, triggers, query):
for trigger in triggers:
trigger = trigger.lower()
for reaction in self._get_reactions(settings.EMOJI_REACTIONS, trigger):
self.client.api_call(
'reactions.add',
name=reaction,
channel=event['channel'],
... |
matteius/parkle-api | accounts/models.py | Python | gpl-3.0 | 422 | 0.00237 | from django.db import models
# Create your | models here.
class ParklePlayer(models.Model):
""" Consider this our User model for a Registered Parkle Player.
"""
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(unique=True)
player_key = models.CharField(max_length=32, u | nique=True) # max length of uuid.hex
secret_key = models.CharField(max_length=32, unique=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.