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 |
|---|---|---|---|---|---|---|---|---|
xke/nash | app/__init__.py | Python | bsd-2-clause | 145 | 0.006897 | # __init__.py is a special Python file that allow | s a directory to become
# a Python package so it can be accessed using the 'import' statement.
| |
yunojuno/django-onfido | tests/conftest.py | Python | mit | 8,575 | 0.0007 | """Shared pytest fixtures and test data."""
import copy
import uuid
import pytest
from django.contrib.auth import get_user_model
from onfido.models import Applicant, Check, Event, Report
APPLICANT_ID = str(uuid.uuid4())
CHECK_ID = str(uuid.uuid4())
IDENTITY_REPORT_ID = str(uuid.uuid4())
DOCUMENT_REPORT_ID = str(uuid... | ear", "properties": {}},
"voting_register": {"result": "clear", "properties": {}},
},
},
"date_of_birth": {
"result": "clear",
"breakdown": {
"credit_agencies": {"result": | "clear", "properties": {}},
"voting_register": {"result": "clear", "properties": {}},
},
},
"mortality": {"result": "clear"},
},
"check_id": CHECK_ID,
"documents": [],
}
TEST_REPORT_DOCUMENT = {
"created_at": "2019-10-03T14:05:48Z",
"documents": [{"id": D... |
xycfree/py_spider | baidu/__init__.py | Python | gpl-3.0 | 154 | 0.006494 | #!/usr/bin/env python
# -*- codi | ng: utf-8 -*-
# @Date : 2016/11/23 16:15
# @Aut | hor : xycfree
# @Link : http://example.org
# @Version : $
import os |
sayan801/indivo_server | indivo/tests/data/reports/allergy.py | Python | gpl-3.0 | 2,324 | 0.003442 | from base import report_content_to_test_docs
_TEST_ALLERGIES_INVALID = [
# an allergy with the wrong schema, should trigger a validation error
"""
<Models xmlns='http://indivo.org/vocab/xml/documents#'>
<Model name="Allergy">
<Field name="allergic_reaction_title">Anaphylaxis</Field>
<Field name="alle... | >
<Field name="category_identifier">416098002</Field>
<Field name="drug_class_allergen_title">Sulfonamide Antibacterial</Field>
<Field name="drug_class_allergen_system">http://purl.bioontology.org/ontology/NDFRT/</Fiel | d>
<Field name="drug_class_allergen_identifier">N0000175503</Field>
<Field name="severity_title">Severe</Field>
<Field name="severity_system">http://purl.bioontology.org/ontology/SNOMEDCT/</Field>
<Field name="severity_identifier">24484000</Field>
</Model>
</Models>
""",
]
TEST_ALLERGIES_INVALID = re... |
graphql-python/graphql-core | tests/test_star_wars_introspection.py | Python | mit | 11,566 | 0.000865 | from typing import Any
from graphql import graphql_sync
from .star_wars_schema import star_wars_schema
def query_star_wars(source: str) -> Any:
result = graphql_sync(star_wars_schema, source)
assert result.errors is None
return result.data
def describe_star_wars_introspection_tests():
def describe... | "name": None,
"kind": "LIST",
"ofType": {"name": "Character", "kind": "INTERFACE"},
},
},
{
"name": "appearsIn",
... | d": "ENUM"},
},
},
{
"name": "secretBackstory",
"type": {
"name": "String",
"kind": "SCALAR",
... |
sigmapi-gammaiota/sigmapi-web | sigmapiweb/apps/PartyListV2/migrations/0012_auto_20181022_0058.py | Python | mit | 444 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-1 | 0-22 00:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("PartyListV2", "0011_auto_20181021_2203"),
]
operations = [
migrations.RenameField(
model_name="restrictedguest",
old_name... | new_name="added_by",
),
]
|
ict-felix/stack | vt_manager_kvm/src/python/vt_manager_kvm/communication/utils/ZabbixHelper.py | Python | apache-2.0 | 2,427 | 0.030902 | # -*- coding: utf-8 -*-
'''
Created on 2015/04/17
@author: 2015 AIST
'''
import time
from django.conf import settings
from zbxsend import Metric, send_to_zabbix
import logging
import json
from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
class ZabbixHelper():
logg... | = logging.getLogger("ZabbixHelper")
@staticmethod
def sendAgentStatus(server, available):
if available == True:
status = 1 # UP
else:
status = 2 # DOWN
timestamp = int(time.time())
driver = HandlerConfigurator.get_vt_am_driver()
server_urn = driver.generate_component_id(server)
itemname = settings... | urn
@staticmethod
def sendVMDiscovery(server, vms):
timestamp = int(time.time())
discoveryList = []
for vm in vms:
discovery = {"{#USERVM.NAME}": vm.name}
discoveryList.append(discovery)
tmpobj = {"data": discoveryList}
discoveryStr = json.dumps(tmpobj)
metric = Metric(server.name, settings.ZBX_ITE... |
Byron/bcore | src/python/bsemantic/tests/test_generators.py | Python | lgpl-3.0 | 4,860 | 0.004527 | #-*-coding:utf-8-*-
"""
@package bsemantic.tests.test_generators
@brief tests for bsemantic.generators
@author Sebastian Thiel
@copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html)
"""
from __future__ import unicode_literals
from butility.future import str
__all__ = []
# W0614 unused ... | == 1, "Should have only one node"
assert node_list[0] is string_tree.root_node(), "the only contained string node should be the root"
| # assert concatenation with different separators works. Note that we work on node-references here
new_sep = '#'
assert new_sep not in node_list.to_string()
node_list.extend(node_list)
# this affects one and the same root, the first node in a list will not contribute its parent separa... |
banebg/embedded | webdimovanjeitemp/blog/django_thermometer/settings.py | Python | gpl-3.0 | 58 | 0 | BASE_PATH = '/sys/bus/w1/devices/' |
TAIL_PATH = "w1_sla | ve"
|
auspbro/CodeSnippets | Python/LPTHW/ex26.py | Python | gpl-3.0 | 2,393 | 0.004597 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ryan'
import ex25
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Print... | ormula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (jelly_beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point)
sentenc... |
words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print sorted_words
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
|
johnkerl/sack | uniqc_m.py | Python | bsd-2-clause | 1,891 | 0.002644 | #!/usr/bin/python -Wall
# ================================================================
# Given a list, returns a list of pairs of elements and repetition counts.
# Example (with commas elided for legibility):
#
# Input: [ 1 1 1 2 2 3 3 3 3 5 5 1 1 ]
# Output: [ [3 1] [2 2] [4 3] [2 5] [2 1] ]
#
# I.e. there i... | rv.append([head, count])
head = list[nexti]
count = 1
curri += 1
nexti += 1
return rv
# ---------------------------------------------------------- | ------
# Test cases:
#def test1(list):
# #print list
# #print uniqc(list)
# #print
#
# # Pipe the output to, say, expand -20.
# print list, "\t", uniqc(list)
#
#def test_uniqc():
# test1([])
# test1([8])
# test1([8, 8])
# test1([8, 9])
# test1([9, 8])
# test1([9, 9])
# test1([8, 8, 8])
# test... |
gentledevil/ansible | lib/ansible/plugins/shell/sh.py | Python | gpl-3.0 | 6,399 | 0.002813 | # (c) 2014, Chris Church <chris@ninemoreminutes.com>
#
# 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 lat... | CULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ | import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import pipes
import ansible.constants as C
import time
import random
_USER_HOME_PATH_RE = re.compile(r'^~[_.A-Za-z0-9][-_.A-Za-z0-9]*$')
class ShellModule(object):
# How to end lines in a python script one-liner
_SH... |
RoboJackets/robocup-software | launch/config_server.launch.py | Python | apache-2.0 | 388 | 0 | import launch
from launch import LaunchDescription
import launch_ros.actions
def generate_launch_description():
return LaunchDescription(
[
| launch_ros.actions.Node(
package="rj_robocup",
executable="config_server",
output="screen",
| on_exit=launch.actions.Shutdown(),
)
]
)
|
befeltingu/UdacityFinalProject4 | conference.py | Python | apache-2.0 | 33,399 | 0.006467 | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import ... | if field.name == 'date':
setattr(sf, field.name, str(getattr(session, field.name)))
else:
setattr(sf, field.name, getattr(session, field.name))
sf.check_initialized()
return sf
def _createSessionObject(self, request):
"""... | object, returning SessionForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRe... |
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/enkf/obs_data.py | Python | gpl-3.0 | 2,908 | 0.016162 | from types import NoneType
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB
from ert.util import Matrix
class ObsData(BaseCClass):
def __init__(self):
c_pointer = ObsData.cNamespace().alloc()
super(ObsData, self).__init__(c_pointer)
def __len__(self):
""" @rty... | er = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("obs_data", ObsData)
ObsData.cNamespace().alloc = cwrapper.prototype("c_void_p obs_data_alloc()")
ObsData.cNamespace().free = cwrapper.prototype("void obs_data_fre | e(obs_data)")
ObsData.cNamespace().active_size = cwrapper.prototype("int obs_data_get_active_size(obs_data)")
ObsData.cNamespace().add_block = cwrapper.prototype("obs_block_ref obs_data_add_block(obs_data , char* , int , matrix , bool)")
ObsData.cNamespace().allocdObs = cwrapper.prototype("matrix_obj obs_data_allo... |
shantilabs/django-smarturlfield | tests/test_modelfield.py | Python | mit | 1,155 | 0.001732 | from django import forms
from example.models import OneUrlModel, ManyUrlsModel
def test_one_url(db):
class F(forms.ModelForm):
class Meta:
model = OneUrlModel
fields = '__all__'
form = F({'url': 'ya.RU'})
instance = form.save()
assert instance.url == 'http://ya.ru'
... | ):
class F(forms.ModelForm):
class Meta:
model = ManyUrlsModel
fields = '__all__'
form = F({'urls': 'ya.RU, xx.com '
'httP://zzz.ff'})
assert form.is_valid()
instance = form.save()
asse | rt instance.urls == [
'http://xx.com',
'http://ya.ru',
'http://zzz.ff',
]
form = F(instance=instance)
assert bool(form.errors) == False
def test_model(db):
instance = ManyUrlsModel.objects.create(
urls=['http://ya.ru', 'http://xx.com'],
)
assert ManyUrlsModel.... |
saleswise/talon | talon/signature/learning/featurespace.py | Python | apache-2.0 | 2,878 | 0 | # -*- coding: utf-8 -*-
""" The module provides functions for conversion of a message body/body lines
into classifiers features space.
The body and the message sender string are converted into unicode before
applying features to them.
"""
from talon.signature.constants import SIGNATURE_MAX_LINES
from talon.signature... | s, fallback to zeros
return ([[f(line) for f | in features] for line in last_lines] or
[[0 for f in features]])
def build_pattern(body, features):
'''Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain featur... |
freevo/freevo1 | src/helpers/__init__.py | Python | gpl-2.0 | 34 | 0 | """
| Helper and server modules
"""
| |
unioslo/cerebrum | Cerebrum/rest/api/__init__.py | Python | gpl-2.0 | 2,970 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2018 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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... |
})
from Cerebrum.rest.api import v1
app.register_blueprint(v1.blueprint, url_prefix='/v1')
@app.before_request
def register_request_s | tart():
g.request_start = time.time()
db.init_app(app)
proxy_auth.init_app(app, db)
auth.init_app(app, db)
@app.after_request
def log_request_data(response):
req_time = time.time() - g.request_start
req_time_millis = int(round(req_time * 1000))
ip_log = list(reques... |
cecilulysess/MinerLite | main.py | Python | gpl-3.0 | 1,792 | 0.016183 | #!/usr/bin/python
# MinerLite - A client side miner controller.
# This will launch cgmin | er with a few delay seconds and
# retrieve the local data and post it into somewhere!
#
# Author: Yanxiang Wu
# Release Under GPL 3
# Used code from cgminer python API example
import socket
import json
import sys
import subprocess
import time
import os
path = "/home/ltcminer/mining/cgminer/cgminer"
log_file = "/ho... | 6)
done = False
while not done:
more = socket.recv(4096)
if not more:
done = True
else:
buffer = buffer+more
if buffer:
return buffer
def retrieve_cgminer_info(command, parameter):
... |
philkroos/tinkervision | src/test/colormatch/pick_color.py | Python | gpl-2.0 | 2,616 | 0.003058 | import cv2
import numpy as np
import sys
from time import sleep
class Hue:
h = 0
s = 0
v = 0
class HueAverage:
def __init__(self, wname, wwidth, wheight, avgSize):
self.avgSize = avgSize
self.x = self.y = 0
self.at = Hue();
self.avg = Hue();
self.cli | cked = False
self.width = wwidth
self.height = wheight
def mouseHandler(self, event, x, y, flag, param):
if self.hsv == None:
return
if (event == cv2.EVENT_LBUTTONDOWN):
self.x = x
self.y = y
xmin = int(max(0, x - self.avgSize))
... | n(self.width, x + self.avgSize))
ymin = int(max(0, y - self.avgSize))
ymax = int(min(self.height, y + self.avgSize))
self.at.h = self.hsv[y, x][0]
self.at.s = self.hsv[y, x][1]
self.at.v = self.hsv[y, x][2]
h = s = v = 0
for x in range(... |
yowmamasita/social-listener-exam | ferris/core/controller.py | Python | mit | 13,807 | 0.002825 | import webapp2
import re
import weakref
from webapp2 import cached_property
from webapp2_extras import sessions
from google.appengine.api import users
from ferris.core.ndb import encode_key, decode_key
from ferris.core.uri import Uri
from ferris.core import inflector, auth, events, views, request_parsers, response_hand... | outing, reusable components, request data parsering, and
view rendering.
"""
_controllers = []
class __metaclass__(type):
def __new__(meta, name, bases, dict):
global _temporary_route_storage
cls = type.__new__(meta, name, bases, dict)
| if name != 'Controller':
# Add to the controller registry
if not cls in Controller._controllers:
Controller._controllers.append(cls)
# Make sure the metaclass as a proper inheritence chain
if not issubclass(cls.Meta, Controller.M... |
yassineS/COSMOS-2.0 | cosmos/web/views.py | Python | gpl-3.0 | 8,041 | 0.00398 | import itertools as it
from operator import attrgetter
from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request
from sqlalchemy import desc
from .. import Execution, Stage, Task, TaskStatus
from ..job.JobManager import JobManager
from . import filters
from ..graph.draw import dra... | name, task_ | id=task.id))
# @bprint.route('/execution/<ex_name>/<stage_name>/task/')
# def task(ex_name, stage_name):
# # resource_usage = [(category, field, getattr(task, field), profile_help[field]) for category, fields in
# # task.profile_fields for field in fields]
# assert req... |
scionrep/scioncc | src/ion/process/bootstrap/datastore_loader.py | Python | bsd-2-clause | 2,396 | 0.004591 | #!/usr/bin/env python
"""Process that loads the datastore"""
__author__ = 'Michael Meisinger, Thomas Lennan'
"""
Possible Features
- load objects into different datastores
- load from a directory of YML files in ion-definitions
- load from a ZIP of YMLs
- load an additional directory (not under GIT control)
- change... | s_name()).lower()
log.info("DatastoreLoader: {op=%s, datastore=%s, path=%s, prefix=%s}" % (op, datastore, path, prefix))
self.da = datastore_admin.DatastoreAdmin()
if op:
if op == "load":
self.da.load_datastore(path, datastore, ignore_errors=False)
elif ... | esources import ResourceRegistryHelper
rrh = ResourceRegistryHelper()
rrh.dump_resources_as_xlsx(path)
elif op == "blame":
# TODO make generic
self.da.get_blame_objects()
elif op == "clear":
self.da.clear_datastore(d... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/remote/models/if_vlan_remote.py | Python | apache-2.0 | 4,719 | 0.003179 | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class IfVlanRemote(RemoteModel):
"""
VLANs that an interface is in along with the STP state of the interface. Also includes SVIs (VlanInterfaceInd = 1) and peer interfaces attached to access ports (VlanExtensionIn... | d was collected or calculated.
| ``attribute type:`` datetime
| ``InterfaceID:`` The internal NetMRI identifier of the interface participating in the VLAN.
| ``attribute type:`` number
| ``StpPortDesignatedBridge:`` The Spanning Tree Protocol designated bridge address of this interface for this VL... | nning Tree Protocol state of this interface for this VLAN.
| ``attribute type:`` string
| ``VlanExtensionInd:`` A flag indicating if this record represents an interface attached to an access port rather than on a participating bridge.
| ``attribute type:`` bool
| ``VlanID:`` The internal NetMRI id... |
fffy2366/image-processing | nudetest.py | Python | mit | 7,025 | 0.005275 | #!bin/evn python
# encoding:utf-8
from __future__ import print_function
import os
import sys
from nude import Nude
# from tests.python.nude import Nude
import time
import cv2
import cv2.cv as cv
from PIL import Image
ROOT = os.path.dirname(os.path.abspath(__file__))
# IMAGE_DIR = "/Users/fengxuting/Downloads/photo/p... | ale %s" % (scale))
if(scale<50):
# delete(faces,index,axis=0)
pass
else:
faces_new.append(face)
else:
faces_new = faces
return faces_new
# 裁剪人脸以下的图片
def cropImg(self,file,faces):
ori... | iImg)
ipl_image = Image.open(oriImg)
# print(ipl_image.height)
if (len(faces) < 1):
print("no face")
return faces
(x, y, w, h) = faces[0]
yy = int(y + 1.5*h)
hh = h * 6
(width,height) = ipl_image.size
if (hh > height - y):
... |
leobarros/use_cabeca_python | nester/setup.py | Python | apache-2.0 | 341 | 0.061765 | from distutils.core import setup
setup(
| name = 'nicknester',
version = '1.3.0',
py_modules = ['nester'],
author = 'htýthon',
author_email = 'hfpython@headfirstlabs.com',
url = 'http://www.headfirstlabs.com',
description = 'A simple printer of nested | list',
)
|
FabienPean/sofa | applications/plugins/SofaPython/python/SofaPython/console.py | Python | lgpl-2.1 | 5,349 | 0.014208 | """a readline console module (unix only).
maxime.tournier@brain.riken.jp
the module starts a subprocess for the readline console and
communicates through pipes (prompt/cmd).
the console is polled through a timer, which depends on PySide.
"""
from select import select
import os
import sys
import signal
if __name_... | except OSError:
pass
else:
import subprocess
import code
import atexit
_cleanup = None
def _register( c ):
global _cleanup
if _cleanup: _cleanup()
_cleanup = c
class Console(code.InteractiveConsole):
def __init__(self,... | is provided through 'locals' (usually: locals() or globals())
'timeout' (in milliseconds) sets how often is the console polled.
"""
code.InteractiveConsole.__init__(self, locals)
if timeout >= 0:
def callback():
self.pol... |
google-research/google-research | ptopk_patch_selection/ntsnet.py | Python | apache-2.0 | 20,236 | 0.008747 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | ags.DEFINE_config_file(
"config", None, "Training configuration.", lock_config=True)
flags.DEFINE_string("workdir", None, "Work unit directory.")
NUM_CLASSES = 200
ANCHORS_SETTINGS = (
dict(
layer="p3",
stride=32,
size=48,
scale=[2**(1. / 3.), 2**(2. / 3.)],
aspect_ratio... | stride=64,
size=96,
scale=[2**(1. / 3.), 2**(2. / 3.)],
aspect_ratio=[0.667, 1, 1.5]), # Anchors 6-11
dict(
layer="p5",
stride=128,
size=192,
scale=[1, 2**(1. / 3.), 2**(2. / 3.)],
aspect_ratio=[0.667, 1, 1.5]), # Anchors 12-20
)
class Commun... |
TingPing/plugins | XChat/define.py | Python | mit | 1,320 | 0.039394 | import urllib
import ast
import xchat
__module_name__ = | "Define"
__module_author__ = "TingPing"
__module_version__ = "2"
__module_description__ = "Show word definitions"
# based on google dictionary script by Sridarshan Shetty - http://srid | arshan.co.cc
def define(word, word_eol, userdata):
if len(word) >= 2:
_word = xchat.strip(word[1])
_number = 1
if len(word) >= 3:
_number = int(xchat.strip(word[2]))
else:
xchat.prnt('Define Usage: /define word [number]')
xchat.prnt(' number being alternate definition')
return xchat.EAT_ALL
url="ht... |
luzheqi1987/nova-annotation | nova/network/security_group/neutron_driver.py | Python | apache-2.0 | 23,777 | 0 | # Copyright 2013 Nicira, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | LOG.exception(_("Neutron Error updating security group %s"),
name)
if e.status_code == 401:
# TODO(arosen) Cannot raise generic response from neutron here
| # as this error code could be related to bad input or over
# quota
raise exc.HTTPBadRequest()
raise exc_info[0], exc_info[1], exc_info[2]
return self._convert_to_nova_security_group_format(security_group)
def _convert_to_nova_security_group_format(self, security... |
emgreen33/easy_bake | oven.py | Python | mit | 583 | 0.013722 | import RPi.GPIO as gpio
from datetime import datetime
import time
import controller
gpio.setmode(gpio.BOARD)
# switch_pins = [10, 40, 38]
switch = 10
gpio.setup(switch, gpio.OUT, initial=False)
# gpio.setup(switch_pins, gpio.OUT, initial=False)
def switch_on(): |
gpio.output(switch, True)
print "Oven switched ON at " + str(datetime.now())
def switch_off():
gpio.output(switch, False)
print "Oven switched OFF at " + s | tr(datetime.now())
def status():
return gpio.input(switch)
switch_on()
print status()
time.sleep(3)
switch_off()
print status()
# gpio.cleanup()
|
robertodr/kleisli | setup.py | Python | lgpl-2.1 | 2,121 | 0.002357 | #!/usr/bin/env python
# This file is autogenerated by Autocmake
# Copyright (c) 2015 by Radovan Bast and Jonas Juselius
# See https://github.com/scisoft/autocmake/
import os
import sys
sys.path.append('cmake/lib')
from config import configure
import docopt
options = """
Usage:
./setup.py [options] [<builddir>]
... | command based on options and arguments.
"""
command = []
command.append('CXX=%s' % arguments['--cxx'])
command.append('cmake')
command.append('-DEXTRA_CXXFLAGS="%s"' % arguments['--extra-cxx-flags'])
command.append('-DENABLE_CODE_COVERAGE=%s' % arguments['--coverage'])
command.append('-DCMA... | TYPE=%s' % arguments['--type'])
command.append('-G "%s"' % arguments['--generator'])
if(arguments['--cmake-options']):
command.append('%s' % arguments['--cmake-options'])
return ' '.join(command)
try:
arguments = docopt.docopt(options, argv=None)
except docopt.DocoptExit:
sys.stderr.write... |
esetomo/mio | script/pymio/mmd/pmd/pmd_model.py | Python | gpl-3.0 | 28,845 | 0.009256 | import copy
import math
from pymio.material.material_list import MaterialList
from pymio.material.phong_material import PhongMaterial
from pymio.material.textured_phong_material import TexturedPhongMaterial
from pymio.material.by_polygon_material_mapping import ByPolygonMaterialMapping
from pymio.geometry.ind... | g(self):
mapping = IndexedTextureMapping()
for vertex in self.vertices:
mapping.append_tex_coord(Uv(vertex.tex_coord.u, 1.0 - vertex.tex_coord.v))
for i in xrange(self.triangle_ | count):
v0 = self.triangle_vertex_indices[3*i]
v1 = self.triangle_vertex_indices[3*i+1]
v2 = self.triangle_vertex_indices[3*i+2]
mapping.append_new_polgon()
mapping.append_tex_coord_index_to_last_polygon(v2)
mapping.append_tex_coord_index_to_... |
y-zeng/grpc | tools/run_tests/run_tests.py | Python | bsd-3-clause | 49,895 | 0.009941 | #!/usr/bin/env python2.7
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this lis... | }
def platform_string():
return jobset.platform_string()
_DEFAULT_TIMEOUT_SECONDS = 5 * 60
# SimpleConfig: just compile with CONFIG=config, and run the binary to test
class Config(object):
def __init__(self, config, environ=None, timeout_multiplier=1, tool_prefix=[]):
if environ is None:
environ = ... | ltiplier
def job_spec(self, cmdline, timeout_seconds=_DEFAULT_TIMEOUT_SECONDS,
shortname=None, environ={}, cpu_cost=1.0, flaky=False):
"""Construct a jobset.JobSpec for a test under this config
Args:
cmdline: a list of strings specifying the command line the test
... |
the-gigi/conman | conman/conman_etcd.py | Python | mit | 3,240 | 0 | """A configuration management class built on top of etcd
See: http://python-etcd.readthedocs.org/
It provides a read-only access and just exposes a nested dict
"""
import functools
import time
import etcd3
from conman.conman_base import ConManBase
def thrice(delay=0.5):
"""This decorator tries failed operation... | password=None,
grpc_options=None,
on_change=lambda e: None):
ConManBase.__init__(self)
self.on_change = on_change
self.client = etcd3.client(
host=host,
port=port,
ca_cert=ca_cert,
cert_key=cert_key... | user=user,
password=password,
grpc_options=grpc_options,
)
def _add_key_recursively(self, etcd_result):
ok = False
target = self._conf
for x in etcd_result:
ok = True
value = x[0].decode()
key = x[1].key.decode()
... |
dayatz/taiga-back | taiga/projects/userstories/api.py | Python | agpl-3.0 | 18,791 | 0.002289 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | "to this user story."))
if obj.status and obj.status.project != obj.project:
raise exc.PermissionDenied(_("You don't have permissions to set this status "
"to this user story."))
"""
| Updating some attributes of the userstory can affect the ordering in the backlog, kanban or taskboard
These three methods generate a key for the user story and can be used to be compared before and after
saving
If there is any difference it means an extra ordering update must be done
"""
def _back... |
id2669099/turbo-waffle | task_07_02.py | Python | mit | 249 | 0 | import ra | ndom
from string import digits, ascii_letters, punctuation
def password_generator(length):
while True:
values = list(digits + ascii_letters + punctuation)
yield ''.join([random.choice(values) for i in range(length)] | )
|
cdapio/cdap-ambari-service | src/main/resources/common-services/CDAP/6.0.0/package/scripts/master.py | Python | apache-2.0 | 4,572 | 0.00175 | # coding=utf8
# Copyright © 2015-2017 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | gure(self, env):
print('Configure the CDAP Master')
import params
env.set_params(params)
helpers.cdap_config('master')
def upgrade(self, env):
self.run_class(
env,
classname='io.cdap.cdap.data.tools.UpgradeTool',
label='CDAP Upgrade Tool',... | ='upgrade force'
)
def upgrade_hbase(self, env):
self.run_class(
env,
classname='io.cdap.cdap.data.tools.UpgradeTool',
label='CDAP HBase Coprocessor Upgrade Tool',
arguments='upgrade_hbase force'
)
def postupgrade(self, env):
self... |
JudaismBot/JudaismBot | scrapers/mechonMamre.py | Python | mit | 2,147 | 0.014905 | from bs4 import BeautifulSoup as Soup
import json
import re
import requests
from common import *
from nltk.corpus import words
entries = []
WEBSITE = 'http://www.mechon-mamre.org/jewfaq/glossary.htm'
SITE_TITLE = "Mechon Mamre"
source_object = {"site":WEBSITE, "title":SITE_TITLE}
def main():
parseMechonMamre()
... | efinition" in entry:
entry["definition"]["text"] += " "+line.strip()
else:
entry["definition"] = {"text":line.strip(),"source":source_object}
def parseTerm(entry, term):
if(term.startswith("Kohein")):
pass
else:
| matches = re.findall("([a-zA-Z-'\d][a-zA-Z- '\d]+)(?: \(([^;\)]*)(;[^;\)]*)*\))?(;|$)",term)
return matches[0][0]
if __name__ == '__main__':
main() |
atiqueahmedziad/addons-server | src/olympia/amo/middleware.py | Python | bsd-3-clause | 12,302 | 0 | import contextlib
import re
import socket
import urllib
import uuid
from django.conf import settings
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.db import transactio... | L, but it has to be
ascii to go in a Location header. iri_to_uri seems like a good compromise.
"""
qs = request.META.get('QUERY_STRING', '')
try:
request.META['QUERY_STRING'] = iri_to_uri(qs)
yield
finally:
request.META['QUERY_STRING'] = qs
class CommonMiddleware(common.Co... | ware, self).process_request(request)
class NonAtomicRequestsForSafeHttpMethodsMiddleware(MiddlewareMixin):
"""
Middleware to make the view non-atomic if the HTTP method used is safe,
in order to avoid opening and closing a useless transaction.
"""
def process_view(self, request, view_func, view_ar... |
kbussell/django-auditlog | src/auditlog/filters.py | Python | mit | 1,023 | 0.000978 | from django.contrib.admin | import SimpleListFilter
from django.contrib.contenttypes.models import ContentType
from django.db.models import Value
from django.db.models.functions import Concat
from auditlog.registry import auditlog
class ResourceTypeFilter(SimpleListFilter):
title = 'Resource Type'
parameter_name = 'resource_type'
... | tracked_model_names = [
'{}.{}'.format(m._meta.app_label, m._meta.model_name)
for m in auditlog.list()
]
model_name_concat = Concat('app_label', Value('.'), 'model')
content_types = ContentType.objects.annotate(
model_name=model_name_concat,
).filter(... |
scheib/chromium | third_party/blink/web_tests/external/wpt/fetch/api/resources/redirect.h2.py | Python | bsd-3-clause | 505 | 0.005941 | from wptserve.utils import isomorphic_decode, isomorphic_encode
def handle_headers(frame, request, response):
status = 302
if b'redirect_status' in request.GET:
status = int(request.GET[b'redirect_status'])
response.status = status
if b'locat | ion' in request.GET:
url = isomorphic_decode(request.GET[b'location'])
| response.headers[b'Location'] = isomorphic_encode(url)
response.headers.update([('Content-Type', 'text/plain')])
response.write_status_headers()
|
jamesbdunlop/defaultShotgunLibrary | server/tk_sgsrv.py | Python | apache-2.0 | 420 | 0.002381 | import config_constants as configCONST
from shotgun_api3 import Shotgun
base_url = configCONST.SHOTGUN_URL
script_name = configCONST.SHOTGUN_TOOLKIT_NAME
api_key = configCONST.SHOTGUN_TOOLKIT_API_KEY
SHOTGUN_SERVER = Shotgun(b | ase_url=base_url,
script_name=script_name,
api_key=api_key,
ensure_ascii=True,
connect=True) | |
digitalocean/netbox | netbox/ipam/migrations/0030_3569_vlan_fields.py | Python | apache-2.0 | 760 | 0 | from django.db import migrations, models
VLAN_STATUS_CHOICES = (
(1, 'active'),
(2, 'reserved'),
(3, 'deprecated'),
)
def vlan_status_to_slug(apps, schema_editor):
VLAN = apps.get_model('ipam', 'VLAN')
for id, slug in VLAN_STAT | US_CHOICES:
VLAN.objects.filter(status=str(id)).update(status=slug)
class Migration(migrations.Migration):
atomic = False
dependencies = [
('ipam', '0029_3569_ipaddress_fields'),
]
operations = [
# VLAN.status
migrations.AlterField(
model_name='vlan',
... | migrations.RunPython(
code=vlan_status_to_slug
),
]
|
tsaylor/remember-forever | remember_forever/urls.py | Python | mit | 1,038 | 0.003854 | from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView
# Uncomment the next two lines to enable the admin:
from django.contrib import | admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'core.views.home', name='home'),
url(r'^morsel/create/$', 'core.views.create_morsel', name='morsel_create'),
url(r'^morsel/(?P<pk>\d+)/$', 'core.views.morsel_detail', | name='morsel_detail'),
url(r'^morsel/(?P<pk>\d+)/delete/$', 'core.views.morsel_delete', name='morsel_delete'),
url(r'^accounts/login/', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/', 'django.contrib.auth.views.logout', {'next_page': '/'}, name="logout"),
url(r'^accounts/', i... |
chpatrick/hubsan | test.py | Python | gpl-3.0 | 530 | 0.013208 | from hubsan import *
import logging
import math
logging.basicConfig(level = logging.INFO)
hubsan = Hubsan()
hubsan.init()
hubsan.bind()
hubsan.safety()
print "bind complete"
session_id = hubsan.session_id
channel = hubsan.channel
print "channel: %d" % channel
print "session_id: %s" % format_packet(session_id)
pri... | t()
hubsan2.bind(session_id = session_id, channel = channel)
print "resumed"
while True:
hubsan2.control(0.05, 0, 0, | 0)
|
abad623/verbalucce | verbalucce/nltk/misc/wordfinder.py | Python | apache-2.0 | 4,113 | 0.013372 | # Natural Language Toolkit: Word Finder
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
# Simplified from PHP version by Robert Klein <brathna@gmail.com>
# http://fswordfinder.sourceforge.net/
from __futur... | grid[i][j] == '':
grid[i][j] = random.choice(alph)
return grid, used
def word_finder():
from nltk.corpus import words
wordlist = words.words()
random.shuffle(wordlist)
wordlist = wordlist[:200]
wordlist = [w for w in wordlist if 3 <= len(w) | <= 12]
grid, used = wordfinder(wordlist)
print("Word Finder\n")
for i in range(len(grid)):
for j in range(len(grid[i])):
print(grid[i][j], end=' ')
print()
print()
for i in range(len(used)):
print("%d:" % (i+1), used[i])
if __name__ == '__main__':
word_find... |
klahnakoski/ActiveData | vendor/mo_threads/queues.py | Python | mpl-2.0 | 18,763 | 0.001705 |
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
# THIS THREADING MODULE IS PERMEATED BY THE p... | if not self.lock.wait(till=self.closed | till):
if self.closed:
break
return None
(DEBUG or not self.silent) and Log.note(self.name + " queue closed")
return THREAD_STOP
def pop_all(self):
"""
NON-BLOCKING POP ALL ... | elf.queue.clear()
return output
def pop_one(self):
"""
NON-BLOCKING POP IN QUEUE, IF ANY
"""
with self.lock:
if self.closed:
return THREAD_STOP
elif not self.queue:
return None
else:
v =self... |
hatchetation/freeipa | ipalib/plugins/baseldap.py | Python | gpl-3.0 | 76,643 | 0.002623 | # Authors:
# Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2009 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 versio... | else:
if value.lower() == entry_attrs[attr].lower():
break
return entry_attrs
def validate_externalhost(ugettext, hostname):
try:
validate_hostname(hostname, check_fqdn=False, allow_underscore=True)
except ValueError, e:
return unicode(e)
... | tr('externalhost*', validate_externalhost,
label=_('External host'),
flags=['no_option'],
)
def add_external_pre_callback(membertype, ldap, dn, keys, options):
"""
Pre callback to validate external me |
ihh/dart | python/XGram/Tests/GeneratorCodonsTest.py | Python | gpl-2.0 | 6,123 | 0.019108 | import unittest
import string
from pprint import pprint
import XGram, XGram.Parser, XGram.Exceptions
from XGram.Generator.Prebuilt import Codons
from XGram.Model import Annotation
import Bio.Data.CodonTable
class GeneratorCodonsTest(unittest.TestCase):
"""
A test class for testing a grammar
"""
def s... | self.buildAndCheckModel( "codons-four", codon_frequencies = codon_frequencies )
def testModelCodonsFour(self):
"""test codons-four model
"""
self.buildAndCheckModel( "codons-four" )
codons = Bio.Data.CodonTable.standard_dna_table.forward_table
... | for codon in Bio.Data.CodonTable.standard_dna_table.forward_table:
codon_frequencies[codon] = float(n)/f
n += 1
self.buildAndCheckModel( "codons-four", codon_frequencies = codon_frequencies )
def buildAndCheckModel(self, codon_model, **kwargs... |
mjn19172/Savu | savu/test/test_utils.py | Python | apache-2.0 | 4,791 | 0 | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | output.append(pu.get_projection_data(datum, temp_file,
plugin.name, mpi,
plugin.get_output_shape(
datum)))
elif isinstance(datum,... | plugin.get_output_shape(
datum)))
return output
|
CHEN-JIANGHANG/qcspgen | qcspgen/aggregator.py | Python | mit | 2,819 | 0.001064 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from qcspgen_exception import QCSPGenException
import functools
def _verify_type( | func):
"""
decorator to verify item type supplied for the wrapped function
:param func: decorated function
:return: wrapper
"""
@functools.wraps(func)
def wrapper(self, *item):
if not isinstance(item[-1], self.item_type):
raise QCSPGenException("- typeError: item is not ... | ike base class to store items in the same type, example:
::
a = Aggregator(str)
a.append("hello")
a.append("world")
print a.aggregator, a.item_type
:param item_kind: the item type for aggregator's elements
"""
def __init__(self, item_kind):
super(Aggregator, sel... |
Auquan/auquan-toolbox-python | auquanToolbox/resultviewer.py | Python | mit | 13,093 | 0.003208 | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("TkAgg") # important to call this right after
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib import style
i... | ort %')
position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.)
plt.gcf().canvas.draw()
def update_plot():
# Callback Function for plot button
try: |
d1 = pd.to_datetime(box_value2.get())
d2 = pd.to_datetime(box_value3.get())
if d1 >= daily_pnl.index[0] and d2 <= daily_pnl.index[-1]:
plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, box_value.get(), box_value2.get(), box_value3.g... |
serendi-app/serendi-server | docs/conf.py | Python | agpl-3.0 | 9,191 | 0.006093 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Serendi documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 14 10:26:42 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor direc | tives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs ... |
highco-groupe/odoo | addons/share/wizard/share_wizard.py | Python | agpl-3.0 | 50,906 | 0.006149 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | id, ids, context=context):
if this.result_line_ids:
ctx = dict(context, share_url_template_hash_arguments=['action'])
user = this.result_line_ids[0]
data = dict(dbname=cr.dbname, login=user.login, passw | ord=user.password, action=this.action_id.id)
result[this.id] = this.share_url_template(context=ctx) % data
return result
_columns = {
'action_id': fields.many2one('ir.actions.act_window', 'Action to share', required=True,
help="The action that opens the screen conta... |
jgontrum/jgsnippets | jgsnippets/elasticsearch/__init__.py | Python | mit | 46 | 0.021739 | from jgsnippets.elastics | earch.c | rud import Crud |
goldsborough/algs4 | stacks-queues/python/queue.py | Python | mit | 205 | 0.034146 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*-
class Queue:
def __init__(self):
self.queue = []
def e | nqueue(self, item):
self.queue.append(item)
def dequeue(self, item):
return self.queue.pop(0) |
aldenjenkins/foobargamingwebsite | djangobb_forum/forms.py | Python | bsd-3-clause | 22,552 | 0.004257 | # coding: utf-8
from __future__ import unicode_literals
import os.path
from datetime import timedelta
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from djangobb_foru... | (label=_('Attachment'), required=False)
subscribe = forms.BooleanField(label=_('Subscribe'), help_text=_("Subscribe this topic."), required=False)
class Meta:
model = Post
fields = ['body']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.topi... | ntest', None)
super(AddPostForm, self).__init__(*args, **kwargs)
if self.topic:
self.fields['name'].widget = forms.HiddenInput()
self.fields['name'].required = False
if self.contest:
self.fields['body'].widget = forms.Textarea(attrs={'class':'markup derpfla... |
amwelch/a10sdk-python | a10sdk/core/ip/ip_nat_alg.py | Python | apache-2.0 | 802 | 0.011222 | from a10sdk.common.A10BaseClass import A10BaseClass
class Alg(A10BaseClass):
"""Class Description::
Change NAT ALG Settings.
Class alg supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param DeviceProxy: The device proxy ... | for keys, value in kwargs.items():
setattr(self,keys, | value)
|
picklepete/pyicloud | tests/test_account.py | Python | mit | 4,486 | 0.002006 | """Account service tests."""
from unittest import TestCase
from . import PyiCloudServiceMock
from .const import AUTHENTICATED_USER, VALID_PASSWORD
class AccountServ | iceTest(TestCase):
"""Account service tests."""
s | ervice = None
def setUp(self):
"""Set up tests."""
self.service = PyiCloudServiceMock(AUTHENTICATED_USER, VALID_PASSWORD).account
def test_repr(self):
"""Tests representation."""
# fmt: off
assert repr(self.service) == "<AccountService: {devices: 2, family: 3, storage: ... |
agarciamontoro/TFG | Software/Stuff/test_ray.py | Python | gpl-2.0 | 3,739 | 0.000802 | import os
i | mport numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mp | l_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz'])
sz = extents[:, 1] - extents[:, 0]
centers = np.mean(extents, axis=1)
maxsize = max(abs(sz))
r = maxsize/2
for ctr, dim in zip(centers, 'xyz'):
getattr(ax... |
jleclanche/pywow | wdbc/main.py | Python | cc0-1.0 | 10,011 | 0.032864 | from cStringIO import StringIO
from struct import pack, unpack, error as StructError
from .log import log
from .structures import fields
class DBFile(object):
"""
Base class for WDB and DBC files
"""
@classmethod
def open(cls, file, build, structure, environment):
if isinstance(file, basestring):
file = op... | ._addresses = {}
self._values = {}
self.file = file
self.build = build
self.environment = environment
def __repr__(self):
return "%s(file=%r, build=%r)" % (self.__class__.__name__, self.file, self.build)
def __contains__(self, id):
return id in self._addresses
def __getitem__(self, item):
if isinsta... | self._values:
self._parse_row(item)
return self._values[item]
def __setitem__(self, item, value):
if not isinstance(item, int):
raise TypeError("DBFile indices must be integers, not %s" % (type(item)))
if isinstance(value, DBRow):
self._values[item] = value
self._addresses[item] = -1
else:
#... |
jjdmol/LOFAR | SAS/OTDB_Services/getParset.py | Python | gpl-3.0 | 2,018 | 0.002973 | #!/usr/bin/env python
#coding: iso-8859-15
#
# Copyright (C) 2015
# ASTRON (Netherlands Institute for Radio Astronomy)
# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the term... | software suite is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A | PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
#
# $Id$
"""
"""
from lofar.messaging.RPC import RPC
from lofar.sas.otdb.config import D... |
magne-max/zipline-ja | tests/data/test_us_equity_pricing.py | Python | apache-2.0 | 12,525 | 0 | #
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | each asset's
lifetime.
"""
columns = ['high', 'volume']
for as | set in self.assets:
self._check_read_results(
colum |
rowhit/h2o-2 | py/testdir_single_jvm/notest_exec2_poppush2_fail.py | Python | apache-2.0 | 2,065 | 0.008717 | import unittest, random, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_browse as h2b, h2o_exec as h2e, h2o_import as h2i
initList = [
('crunk', "crunk=function(x){x+98};"),
('r.hex', 'r.hex=i.hex'),
]
# maybe can't have unused functions
phrases = [
"crunk=function(x){x+98};",
# "c... | ){x+98};r.hex[,3]=4;"]
f | or resultKey, execExpr in initList:
h2e.exec_expr(h2o.nodes[0], execExpr, resultKey=resultKey, timeoutSecs=4)
for execExpr in exprList:
h2e.exec_expr(h2o.nodes[0], execExpr, resultKey=None, timeoutSecs=4)
if __name__ == '__main__':
h2o.unit_main()
|
jlazic/GlogSMS | sms/management/commands/check_failed_messages.py | Python | mit | 1,774 | 0.003946 | # -*- coding: utf-8 -*-
__author__ = 'josip@lazic.info'
from django.core.management.base import BaseCommand, CommandError
from sms.models import Message, StatusLog
from datetime import datetime, timedelta
from django.core.mail import mail_admins
from django.conf import settings
from sms.tasks import queue_message
cl... | try:
failed_messages = Message.objects.filter(status='sent', updated__lte=datetime.now() - timedelta(hours=1))
for message in failed_messages:
message.status = 'queued'
s = StatusLog(status='requeueing', error='Poruka nije poslana unutar sat v | remena',
log='Requeueing message due to inactivity in last hour',
phone_number='1234', message=message)
s.save()
message.save()
if settings.SMS_AMQP_ENABLED:
# Send message to AMQP queue again... |
dgaston/ddbio-ngsflow | ddb_ngsflow/pipeline.py | Python | mit | 1,788 | 0.002237 | """
.. module:: pipeline
:platform: Unix, OSX
:synopsis: A wrapper module for executing commands and logging their output.
.. moduleauthor:: Daniel Gaston <daniel.gaston@dal.ca>
"""
import sys
import subprocess as sub
def run_and_log_command(command, logfile):
"""This function uses the python subprocess... | ses: RuntimeError
"""
with open(logfile, "wb") as err:
sys.stdout.write("Executing {} and writing to logfile {}\n".format(command, logfile))
err.write("Command: {}\n".format(command))
p = sub.Popen(command, stdout=sub.PIPE, stderr=err, shell=True)
output = p.comm | unicate()
code = p.returncode
if code:
raise RuntimeError("An error occurred when executing the commandline: {}. "
"Please check the logfile {} for details\n".format(command, logfile))
def spawn_batch_jobs(job):
"""
This is simply a placeholder root j... |
pattisdr/osf.io | scripts/analytics/migrate_analytics.py | Python | apache-2.0 | 20,106 | 0.004377 | # A script to migrate old keen analytics to a new collection, generate in-between points for choppy
# data, or a little of both
import os
import csv
import copy
import pytz
import logging
import argparse
import datetime
from dateutil.parser import parse
from keen.client import KeenClient
from website.settings import ... | ject_id')
read_key = keen_settings['priva | te'].get('read_key')
master_key = keen_settings['private'].get('master_key')
write_key = keen_settings['private'].get('write_key')
if keen_project and read_key and master_key:
client = KeenClient(
project_id=keen_project,
read_key=read_key,
master_key=master_key,
... |
hrantzsch/signature-verification | tools/svm.py | Python | gpl-3.0 | 1,068 | 0.000936 | from sklearn import svm
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier
import pickle
import sys
import numpy as np
def load_data(path):
data = pickle.load(open(path, 'rb'))
keys = sorted(list(data.keys()))
X = []
y = []
for k in keys:
for x in data[k]:
X... | return np.array(X, np.float32), np.array(y, np.int32)
if __name__ == '__main__':
X, y = load_data(sys.argv[1])
Xt, yt = load_data(sys.argv[2])
# === train ===
clf = OneVsOneClassifier(svm.LinearSVC(verbose=1,
max_iter=10000,
... | # clf = pickle.load(open('svm.pkl', 'rb'))
# === test ===
prediction = clf.predict(Xt)
correct = prediction == yt
print("\n========")
print("Accuracy: {}".format(sum(correct) / len(correct)))
|
gvb/odoo | addons/sale/sale.py | Python | agpl-3.0 | 71,046 | 0.005588 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | sale_claus | e = ', sale_order AS sale '
no_invoiced = True
cursor.execute('SELECT rel.order_id ' \
'FROM sale_order_invoice_rel AS rel, account_invoice AS inv '+ sale_clause + \
'WHERE rel.invoice_id = inv.id ' + clause)
res = cursor.fetchall()
if no_invoice... |
Clarify/clarify_python | tests/__init__.py | Python | mit | 2,307 | 0.008236 | import sys
import os
import re
if sys.version_info[0] < 3:
from io import open
host = 'https://api.clarify.io'
def load_body(filename):
text = None
with open(os.path.join('.', 'tests', 'data', filename), encoding="utf-8") as f:
text = f.read()
return text if text else '{}'
def register_ur... | lication/json')
httpretty.register_uri('GET', re.compile(host + '/v1/bundles/(\w+)\?embed=(.*)$'),
body=load_body('bundle_embedded.json'), status=200,
content_type='application/json', match_querystring=True)
httpretty.register_uri('GET', re.compile(host + ... | tent_type='application/json', match_querystring=True)
httpretty.register_uri('GET', re.compile(host + '/v1/bundles/(\w+)/tracks$'),
body=load_body('tracks.json'), status=200,
content_type='application/json')
httpretty.register_uri('GET', re.compile(host + ... |
ganga-devs/ganga | ganga/GangaCore/Core/GangaThread/MTRunner/Data.py | Python | gpl-3.0 | 1,817 | 0.001101 | #!/usr/bin/env python
from queue import Queue
import threading
class DuplicateDataItemError(Exception):
"""
Class raised when adding the same item in the Data object.
"""
def __init__(self, message):
self.message = message
class Data(object):
"""
Class to define user dataset colle... | with infinity number
of slots, it should never throw "Queue.Full" exception.
'''
self.lock.acquire()
try:
if item not in self.collection:
self.collection.append(item)
self.queue.put(item)
else:
raise DuplicateData... | self.lock.release()
def getNextItem(self):
'''
try to get the next item in the queue after waiting in max. 1 sec.
if nothing available, the exception "Queue.Empty" will be thrown.
'''
theItem = None
self.lock.acquire()
try:
theItem = self.que... |
wbinventor/openmc | tests/regression_tests/uwuw/test.py | Python | mit | 1,025 | 0.002927 | import openmc
import openmc.capi
from openmc.stats import Box
from openmc.material import Materials
import pytest
from tests.testing_harness import PyAPITestHarness
pytestmark = pytest.mark.skipif(
not openmc.capi._dagmc_enabled(),
reason="DAGMC CAD geometry is not enabled.")
class UWUWTest(PyAPITestHarness)... | llies = [tally]
model.tallies.export_to_xml()
def test_uwuw() | :
harness = UWUWTest('statepoint.5.h5')
harness.main()
|
ramineni/myironic | ironic/tests/drivers/test_agent_client.py | Python | apache-2.0 | 4,574 | 0.001312 | # Copyright 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | get:
res = mock.Mock()
res.json.return_value = {'commands': []}
mock_get.return_value = res
self.assertEqual([], self.client.get_commands_status(self.node))
@mock.patch('uuid.uuid4', mock.MagicMock(return_value='uuid'))
def test_prepare_image(self):
self.... | prepare_image(self.node,
image_info,
wait=False)
self.client._command.assert_called_once_with(node=self.node,
method='standby.prepare_image',
params=params,
... |
MyNameIsMeerkat/skyline | src/webapp/webapp.py | Python | mit | 2,673 | 0.001871 | import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import setti... | PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html | '), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
... |
burzillibus/RobHome | venv/lib/python2.7/site-packages/gevent/fileobject.py | Python | mit | 7,896 | 0.003293 | """
Wrappers to make file-like objects cooperative.
.. class:: FileObject
The main entry point to the file-like gevent-compatible behaviour. It will be defined
to be the best available implementation.
There are two main implementations of ``FileObject``. On all systems,
there is :class:`FileObjectThread` which... | mode is None:
assert bufsize == -1, "If you use the default mode, you can't choose a bufsize"
fobj = os.fdopen(fobj)
else:
fobj = os.fdopen(fobj, mode, bufsize)
self.__io_holder = [fobj] # signal for _wrap_method
super(FileObjectThread, self).... | def _do_close(self, fobj, closefd):
self.__io_holder[0] = None # for _wrap_method
try:
with self.lock:
self.threadpool.apply(fobj.flush)
finally:
if closefd:
# Note that we're not taking the lock; older code
# did fobj.close... |
glizek/openacademy-project | openacademy/model/openacademy_course.py | Python | apache-2.0 | 1,587 | 0 | '''
This module is to create model of Course
'''
from openerp import api, fields, models, _
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved
description =... | Sessions")
| _sql_constraints = [
('name_description_check',
'CHECK(name != description)',
_("The title of the course should not be the description")),
('name_unique',
'UNIQUE(name)',
_("The course title must be unique")),
]
@api.one # api.one send defaults params: c... |
lem9/weblate | weblate/trans/data.py | Python | gpl-3.0 | 1,577 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Data files helpers."""
import os
from django.conf import settin... | r(path):
"""Ensure directory exists and is writable by us"""
if not os.path.exists(path):
os.makedirs(path)
else:
if not os.access(path, os.W_OK):
raise OSError(
'DATA_DIR {0} is not writable!'.format(path)
)
def check_data_writable():
"""Check w... |
pescobar/easybuild-easyblocks | easybuild/easyblocks/generic/conda.py | Python | gpl-2.0 | 4,661 | 0.003218 | ##
# Copyright 2009-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | f extra_options(extra_vars=None):
"""Extra easyconfig parameters specific to Conda easyblock."""
extra_vars = Binary.extra_options(extra_vars)
extra_vars.update({
'channels': [None, "List of conda channels to pass to 'conda | install'", CUSTOM],
'environment_file': [None, "Conda environment.yml file to use with 'conda env create'", CUSTOM],
'remote_environment': [None, "Remote conda environment to use with 'conda env create'", CUSTOM],
'requirements': [None, "Requirements specification to pass to 'conda i... |
openmotics/gateway | testing/unittests/api_tests/serializers/sensor_test.py | Python | agpl-3.0 | 4,097 | 0.000488 | # Copyright (C) 2020 OpenMotics BV
#
# 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 distribu... | room=10)
assert expected_dto == dto
self.assertEqual(expected_dto, dto)
self.assertEqual(['external_id', 'id', 'name', 'physical_quantity', 'room', 'source', 'unit'], sorted(dto.loaded_fields))
# Empty room
dto = SensorSerializer.deserialize({'id': 5,
... | name='bar'), dto)
self.assertEqual(['id', 'name', 'room'], sorted(dto.loaded_fields))
# No room
dto = SensorSerializer.deserialize({'id': 5,
'name': 'bar'})
self.assertEqual(SensorDTO(id=5, name='bar'), dto)
self.assertEqual(['id', 'nam... |
ajrichards/htsint | htsint/__init__.py | Python | bsd-3-clause | 693 | 0.012987 | import sys,os
## basic files
#sys.path.append(os.path.realpath(__file__))
#print(os.path.realpath(__file__))
#print(os.path.pardir | (os.path.realpath(__file__)))
#print(os.path.split(os.path.abspath(__file__))[:-1])
from .version import __version__
from .basedir import __basedir__
## database functions and classes
from .Configure import Configure
from .RunSubprocess import run_subprocess, RunSubprocess
from .GeneOntology import GeneOntology
from ... | ort GeneDistances
from .AssembleDistances import AssembleDistances
from .TaxaSummary import TaxaSummary
from .GeneSetCollection import GeneSetCollection
from .GeneSet import GeneSet
|
bjolivot/ansible | lib/ansible/modules/cloud/azure/azure_rm_virtualmachine.py | Python | gpl-3.0 | 60,368 | 0.004092 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# 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 Soft... | d to false.
default: null
required: false
ssh_password_enabled:
description:
- When th | e os_type is Linux, setting ssh_password_enabled to false will disable SSH password authentication
and require use of SSH keys.
default: true
required: false
ssh_public_keys:
description:
- "For os_type Linux provide a list of SSH keys. Each item in the list should ... |
BlueDragonX/whatcouch | whatcouch/test/testplugins/testauthenticatorplugin.py | Python | bsd-3-clause | 1,977 | 0.002023 | # Copyright (c) 2010, Ryan Bourgeois <bluedragonx@gmail.com>
# All rights reserved.
#
# This software is licensed under a modified BSD license as defined | in the
# provided license file at the root of this project. You may modify and/or
# distribute in accordance with those terms.
#
# This software is provided "as is" and any express or implied warranties,
# including, but not limited to, the implied warranties of merchantability and
# fitness for a particular purpose a... | @staticmethod
def setup_class():
Config.username = 'admin'
Config.password = 'password'
Config.user = User.create(Config.username, Config.password)
Config.user.save()
Config.plugin = AuthenticatorPlugin(Config.t11)
@staticmethod
def teardown_class():
Conf... |
iulian787/spack | var/spack/repos/builtin/packages/sfcgal/package.py | Python | lgpl-2.1 | 1,183 | 0.001691 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Sfcgal(CMakePackage):
"""
SFCGAL is a C++ wrapper library | around CGAL with the aim of supporting
ISO 19107:2013 and OGC Simple Features Access 1.2 for 3D operations. SFCGAL
provides standard compliant geometry types and operations, that can be
accessed from its C or C++ APIs.
"""
homepage = "http://www.sfcgal.org/"
url = "https://githu | b.com/Oslandia/SFCGAL/archive/v1.3.7.tar.gz"
version('1.3.7', sha256='30ea1af26cb2f572c628aae08dd1953d80a69d15e1cac225390904d91fce031b')
# Ref: http://oslandia.github.io/SFCGAL/installation.html
depends_on('cgal@4.3: +core')
depends_on('boost@1.54.0:')
depends_on('mpfr@2.2.1:')
depends_on('gmp... |
marcionreis/djangoecommerce | core/tests/test_views.py | Python | cc0-1.0 | 1,619 | 0.00248 | # coding=utf-8
from django.test import TestCase, C | lient
from django.core.urlresolvers import reverse
from django.core import mail
class IndexViewTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = reverse('index')
def tearDown(self):
pass
def test_status_code(self):
response = self.client.get(self.url... | et(self.url)
self.assertTemplateUsed(response, 'index.html')
class ContactViewTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = reverse('contact')
def test_view_ok(self):
response = self.client.get(self.url)
self.assertEquals(response.status_code,... |
karservice/kobra | kobra/tests/test_sesam.py | Python | mit | 4,475 | 0.000447 | # -*- coding: utf-8 -*-
from datetime import timedelta
from unittest import mock
from uuid import UUID
from django.test import TestCase
from sesam import SesamStudent, StudentNotFound
from .. import factories
from ..models import Student
def sesam_response_factory(student):
# Factory function useful together wi... | self.assertEqual(changed_student.union, new_union)
def test_get_with_local_no_sesam(self):
# With local entry.
student = factories.StudentFactory()
with mock.patch('sesam.SesamStudentServiceClient.get_student',
side_effect=StudentNotFound):
with mo... | = Student.objects.get(pk=student.pk,
use_sesam=True)
self.assertEqual(student.pk, fetched_student.pk)
self.assertEqual(student.last_updated, fetched_student.last_updated)
def test_get_updates_mifare_id(self):
# With existing local entry.... |
jessrosenfield/pants | src/python/pants/backend/python/tasks/checkstyle/common.py | Python | apache-2.0 | 9,330 | 0.010289 | # coding=utf-8
# Copyright 2015 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 ast
import co... | p, indent in self.iter_logical_lines(self._blob))
def __iter__(self):
return iter(self.lines)
def __getitem__(self, line_number):
return self.lines[self.line_range(line_number)]
def __str__(self):
return 'PythonFile({filename})'.format(filename=self.filename)
@classmethod
def parse(cls, filena... |
@classmethod
def from_statement(cls, statement):
"""A helper to construct a PythonFile from a triple-quoted string, for testing.
:param statement: Python file contents
:return: Instance of PythonFile
"""
return cls('\n'.join(textwrap.dedent(statement).split('\n')[1:]))
@classmethod
def ite... |
pcolmant/repanier | repanier/views/producer_invoice_class.py | Python | gpl-3.0 | 4,583 | 0.000873 | import django
from django.http import Http404
from django.views.generic import DetailView
from repanier.const import DECIMAL_ZERO
from repanier.models.bankaccount import BankAccount
from repanier.models.invoice import ProducerInvoice
from repanier.models.offeritem import OfferItemReadOnly
from repanier.models.producer... | bjects.filter(
producer_invoice=producer_invoice
).order_by("operation_date")
| context["bank_account_set"] = bank_account_set
offer_item_set = (
OfferItemReadOnly.objects.filter(
permanence_id=producer_invoice.permanence_id,
producer_id=producer_invoice.producer_id,
)
.exclude(quantity_invoiced=... |
google/trax | trax/tf_numpy/examples/mnist/train_test.py | Python | apache-2.0 | 1,761 | 0.004543 | # coding=utf-8
# Copyright 2022 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ain(
batch_size=1,
learning_rate=0.1,
num_training_iters=10,
validation_steps=5)
train.t | rain(
batch_size=2,
learning_rate=0.1,
num_training_iters=5,
validation_steps=2)
train.train(
batch_size=10,
learning_rate=0.1,
num_training_iters=1,
validation_steps=1)
def fake_mnist_data():
def gen_examples(num_examples):
... |
rain87/pc-health | smart_attributes.py | Python | mit | 3,144 | 0.000636 | names = {
1: 'Read Error Rate',
2: 'Throughput Performance',
3: 'Spin-Up Time',
4: 'Start/Stop Count',
5: 'Reallocated Sectors Count',
6: 'Read Channel Margin',
7: 'Seek Error Rate',
8: 'Seek Time Performance',
9: 'Power-On Hours',
10: 'Spin Retry Count',
11: 'Recalibration R... | unt | (Fujitsu)',
194: 'Temperature Celsius',
195: 'Hardware ECC Recovered',
196: 'Reallocation Event Count',
197: 'Current Pending Sector Count',
198: 'Uncorrectable Sector Count',
199: 'UltraDMA CRC Error Count',
200: 'Multi-Zone Error Rate',
201: 'Soft Read Error Rate or TA Counter Detecte... |
Unode/ete | ete3/tools/ete_build_lib/ordereddict.py | Python | gpl-3.0 | 10,439 | 0.001437 | from __future__ import absolute_import
import six
# #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of th... | f E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
'''
... | ven)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
# Make progressively weaker assumptions about "other"
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
... |
priestc/MultiExplorer | multiexplorer/multiexplorer/migrations/0007_auto_20170211_0802.py | Python | mit | 967 | 0.002068 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-11 08:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezo | ne
class Migration(migrations.Migration):
dependencies = [
('multiexplorer', '0006_pullhistory'),
| ]
operations = [
migrations.CreateModel(
name='PushHistory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('last_pushed', models.DateTimeField(default=django.utils.timezone.now)),
... |
DGA-MI-SSI/YaCo | tests/tests/test_enums.py | Python | gpl-3.0 | 9,673 | 0.001654 | # Copyright (C) 2017 The YaCo 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 3 of the License, or
# (at your option) any later version.
#
# This program is ... | "])
b.run(
self.check_types(),
self.script("idaapi.set_enum_member_name(idaapi.get_enum_member_by_name('field_a'), 'field_b')"),
self.save_types(),
)
b.check_git(modi | fied=["enum"], added=["enum_member"], deleted=["enum_member"])
a.run(
self.check_types(),
self.script("idaapi.set_enum_name(idaapi.get_enum('name_a'), 'name_b')"),
self.save_types(),
)
a.check_git(modified=["enum"])
b.run(
self.check_types(... |
htlcnn/pyrevitscripts | HTL.tab/Test.panel/Test.pushbutton/keyman/keyman/keys/models.py | Python | mit | 300 | 0.006667 | from django.db import models
from django.core.urlresolvers import reverse
class Sof | tware(models.Model):
name = models.CharField(max_length=200)
def __unicode_ | _(self):
return self.name
def get_absolute_url(self):
return reverse('software_edit', kwargs={'pk': self.pk})
|
dennyb87/pycity | week5/card_validation_test.py | Python | gpl-3.0 | 1,101 | 0.002725 | import unittest
from card_validation import (
numberToMatrix,
getOddDigits,
getEvenDigits,
sumOfDoubleOddPlace,
sumOfEvenPlace,
getDigit,
isValid
)
class CardValidationTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(CardValidationTest, self).__init__(*args, ... | ss__, list)
def test_getEvenDigits(self):
self.assertEqual(self.evens.__class__, list)
def test_sumOfDoubleOddPlace(self):
self.assertEqual(sumOfDoubleOddPlace(self.o | dds), 29)
def test_getDigit(self):
self.assertEqual(getDigit(9), 9)
def test_isValid(self):
self.assertEqual(isValid(self.card_number), True)
if __name__ == "__main__":
unittest.main()
|
WillGuan105/django | tests/gis_tests/relatedapp/tests.py | Python | bsd-3-clause | 15,582 | 0.002246 | from __future__ import unicode_literals
from django.contrib.gis.db.models import F, Collect, Count, Extent, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
from django.db import connection
from django.test import TestCase, skipUnlessDBF... | self.assertAlmostEqual(ref.x, pnt.x, tol)
self.assertAlmostEqual(ref.y, pnt.y, tol)
self.assertEqual(ref.srid, pnt.srid)
# Each city transformed to the SRID of their state plane coordinate system.
tr | ansformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
)
for name, srid, wkt in transformed:
... |
fnp/wolnelektury | src/infopages/migrations/0001_initial.py | Python | agpl-3.0 | 4,109 | 0.008033 | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
... | 0, null=True, ver | bose_name='Title', blank=True)),
('title_ru', models.CharField(max_length=120, null=True, verbose_name='Title', blank=True)),
('title_uk', models.CharField(max_length=120, null=True, verbose_name='Title', blank=True)),
('left_column', models.TextField(verbose_name='left c... |
Guidobelix/pyload | module/plugins/accounts/OpenloadCo.py | Python | gpl-3.0 | 413 | 0.014528 | # -*- coding: utf-8 -*-
from module.plugins.internal.XFSAccount import XFSAccount
class OpenloadCo(XFSAccount):
__name__ = "OpenloadCo"
__type__ = "account"
__version__ = "0.02"
__status__ = "testing"
__description__ = """Openload.co account plugin"""
__license__ = "GPLv3"
__a... | Purcaro", "vuolter@gmail.com")]
PLUGIN_DOMAIN = "openload.co"
| |
gem/oq-engine | openquake/hazardlib/gsim/morikawa_fujiwara_2013.py | Python | agpl-3.0 | 14,534 | 0.003509 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2021 GEM Foundation
#
# OpenQuake 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... | 350 0.000083 0.000066 -0.2486 0.4243
0.13 -0.0321 -0.005786 -0.005757 -0.006331 7.4788 7.5645 7.9644 0.015607 -0.072886 15.0 -0.395130 2000.0 350 0.000082 0.000066 -0.2494 0.4229
0.15 -0.0321 -0.005564 -0.005579 -0.006078 7.4630 7.5471 7.9360 0.014118 -0.061401 15.0 -0.461774 2000.0 350 0.000... | 9 2000.0 350 0.000081 0.000066 -0.2516 0.4162
0.2 -0.0321 -0.005151 -0.005027 -0.005476 7.4307 7.4788 7.8719 0.011273 -0.043392 15.0 -0.633661 2000.0 350 0.000080 0.000065 -0.2528 0.4152
0.22 -0.0322 -0.005000 -0.004827 -0.005204 7.4139 7.4461 7.8311 0.010380 -0.035431 15.0 -0.665914 2000.0 3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.