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 |
|---|---|---|---|---|---|---|---|---|
JQIamo/artiq | artiq/frontend/artiq_flash.py | Python | lgpl-3.0 | 5,247 | 0 | #!/usr/bin/env python3
# Copyright (C) 2015 Robert Jordens <[email protected]>
import argparse
import os
import subprocess
import tempfile
import shutil
from artiq import __artiq_dir__ as artiq_dir
from artiq.frontend.bit2bin import bit2bin
def scripts_path():
p = ["share", "openocd", "scripts"]
if os.name ... | fault)s")
return parser
def main():
| parser = get_argparser()
opts = parser.parse_args()
config = {
"kc705": {
"chip": "xc7k325t",
"start": "xc7_program xc7.tap",
"gateware": 0x000000,
"bios": 0xaf0000,
"runtime": 0xb00000,
"storage": 0xb80000,
},
}[opts.... |
CarnegieHall/metadata-matching | idMatching_flyers.py | Python | mit | 4,920 | 0.004675 | # !/usr/local/bin/python3.4.2
# ----Copyright (c) 2016 Carnegie Hall | The MIT License (MIT)----
# ----For the full license terms, please visit https://github.com/CarnegieHall/quality-control/blob/master/LICENSE----
# run script with 5 arguments:
# argument 0 is the script name
# argument 1 is the path to the Isilon HD... | ou want to save your unmatched performance IDs to
# argument 5 is the harddrive ID/volume that will be added to the output filename (E.g. ABH_20150901)
import csv
import glob
import itertools
import json
import os
from os.path import isfile, join, split
import sys
filePath_1 = str(sys.argv[1])
filePath_2 = str(sys.ar... | {}
##matchedList = []
unmatchedIDs = []
#Set a variable to equal the harddrive volume number, which is extracted from the file path
volume = sys.argv[len(sys.argv)-1]
#Extract filenames from the full file path and build dictionary
for full_filePath in glob.glob(os.path.join(filePath_1, '*.tif')):
file_name = os.... |
sideshownick/Snaking_Networks | MyPython/gen2.py | Python | gpl-2.0 | 4,649 | 0.068187 | #!python
#from Numeric import *
from numpy import *
from scipy import *
from scipy import zeros
from scipy.linalg import *
from scipy import sparse
import os
#import time
#from pylab import save
from random import random
#global size
#global ratioC
def generate(size,ratioC):
N=2*size**2 #=size*(size+1) + size*(size-... |
matC.append([(size+1)*(size-1)+1, cy*(size-1)+(cx-1)])
else:
#os.system('echo "%d %d 1" >> matrixR.mat'%((size-1)*(size)+2,cy*(size-1)+1))
matR.append([(size+1)*(size-1)+1, cy*(size-1)+(cx-1)])
#boundary 2
cx=size-1
if random() < ratioC:
#os.system('echo "%d %d 1" >> matr... | atC.append([(size+1)*(size-1)+2, cy*(size-1)+1])
else:
#os.system('echo "%d %d 1" >> matrixR.mat'%((size-1)*(size)+1,(cy+1)*(size-1)))
matR.append([(size+1)*(size-1)+2, cy*(size-1)+1])
size1=2*size-1
size2=size+size+1
size1a=2*size-3
size2a=size+size-1
size0=size+1
spread=0.0
N=(size+1... |
drincruz/slidedecker | config.py | Python | mit | 838 | 0.004773 | # Statement for enabling the development environment
DEBUG = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are wor | king with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db')
DATABASE_CONNECT_OPTIONS = {}
# Application threads. A common general assumption is
# using 2 per available processor cores - to handle
# incoming requests using one and performing background
# operations usin... | Request Forgery (CSRF)*
CSRF_ENABLED = True
# Use a secure, unique and absolutely secret key for
# signing the data.
CSRF_SESSION_KEY = "secret"
# Secret key for signing cookies
SECRET_KEY = "secret"
# Version Info
VERSION = '0.3.7'
|
tombstone/models | research/neural_gpu/wmt_utils.py | Python | apache-2.0 | 16,455 | 0.008508 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | 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.
# ==============================================================================
"""Utilities for downloadin... | re
import tarfile
from six.moves import urllib
import tensorflow as tf
# Special vocabulary symbols - we always put them at the start.
_PAD = b"_PAD"
_GO = b"_GO"
_EOS = b"_EOS"
_UNK = b"_CHAR_UNK"
_SPACE = b"_SPACE"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK, _SPACE]
PAD_ID = 0
GO_ID = 1
EOS_ID = 2
UNK_ID = 3
SPACE_ID =... |
jordanemedlock/psychtruths | temboo/core/Library/Amazon/Marketplace/Orders/__init__.py | Python | apache-2.0 | 1,089 | 0.00551 | from temboo.Library.Amazon.Marketplace.Orders.GetOrder import GetOrder, GetOrderInputSet, GetOrderResultSet, GetOrderChoreographyExecution
from temboo.Library.Amazon.Marketplace.Orders.GetServiceStatus import GetServiceStatus, GetServiceStatusInputSet, GetServiceStatusResultSet, GetServiceStatusChoreographyExecution
fr... | mail import ListOrdersWithBuyerEmail, ListOrdersWithBuyerEmailInputSet, ListOrdersWithBuyerEmailResultSet, ListOrdersWithBuyerEmailChoreographyExecution
from temboo.Library.Amazon.Ma | rketplace.Orders.ListOrdersWithSellerOrderId import ListOrdersWithSellerOrderId, ListOrdersWithSellerOrderIdInputSet, ListOrdersWithSellerOrderIdResultSet, ListOrdersWithSellerOrderIdChoreographyExecution
|
jtoppins/beaker | IntegrationTests/src/bkr/inttest/client/test_job_delete.py | Python | gpl-2.0 | 5,026 | 0.002786 |
# 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.
import os
from unittest2 import SkipTest
from turbogears.database impo... | ser2 = data_setup.create_user()
group.add_member(user)
group.add_member(user2)
self.job.group = group
self.j | ob.owner = user2
client_config = create_client_config(username=user.user_name,
password='password')
out = run_client(['bkr', 'job-delete', self.job.t_id],
config=client_config)
self.assert_(out.startswith('Jobs deleted:'), out)
self.assert_(self.job.t_id in ou... |
zlorb/mitmproxy | test/mitmproxy/tools/console/test_commander.py | Python | mit | 2,995 | 0 |
from mitmproxy.tools.console.commander import commander
from mitmproxy.test import taddons
class TestListCompleter:
def test_cycle(self):
tests = [
[
"",
["a", "b", "c"],
["a", "b", "c", "a"]
],
[
"xxx",
... | le() == expected
class TestCommandBuffer:
def test | _backspace(self):
tests = [
[("", 0), ("", 0)],
[("1", 0), ("1", 0)],
[("1", 1), ("", 0)],
[("123", 3), ("12", 2)],
[("123", 2), ("13", 1)],
[("123", 0), ("123", 0)],
]
with taddons.context() as tctx:
for start, ... |
Aracthor/cpp-maker | scripts/definitions.py | Python | mit | 3,275 | 0.00458 | #!/usr/bin/python3
## definitions.py for cpp-maker in /home/aracthor/programs/projects/cpp-maker
##
## Made by Aracthor
##
## Started on Mon Sep 7 10:09:33 2015 Aracthor
## Last Update Wed Sep 9 10:33:00 2015 Aracthor
##
def boolean_input(name, default):
question = name + " ? "
if (default == True):
... | if self.valid:
self.name = string_input("Name: ")
self.getter = boolean_input("Getter", True)
self.calcReturnType()
def calcReturnType(self):
self.return_type = self.pure_type
object_type = self.pure_type
const = (object_type[: | 5] == "const")
if const:
object_type = object_type[6:]
object_pure_type = object_type.replace("&", "").replace("*", "")
pointer_or_ref = object_type != object_pure_type
if object_pure_type not in NATIVE_TYPES:
self.include = object_pure_type.replace("::", "/")
... |
Endika/hr | hr_experience/models/hr_academic.py | Python | agpl-3.0 | 1,388 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modi... | long with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields
class hr_academic(models.Model):
_name = 'hr.academic'
_inherit = 'hr.curriculum'
diploma | = fields.Char(string='Diploma', translate=True)
study_field = fields.Char(string='Field of study', translate=True,)
activities = fields.Text(string='Activities and associations',
translate=True)
|
Justasic/StackSmash | StackSmash/apps/blog/admin.py | Python | bsd-2-clause | 509 | 0 | from django.contrib import admin
from StackSmash.apps.blog.models import Post, Comment
class PostAdmin(admin.ModelAdmin):
list_display | = ['title']
list_filter = ['listed', 'pub_date']
search_fields = ['title', 'content']
date_heirachy = 'pub_date'
save_on_top = True
p | repopulated_fields = {"slug": ("title",)}
class CommentAdmin(admin.ModelAdmin):
display_fields = ["post", "author", "created"]
admin.site.register(Post, PostAdmin)
admin.site.register(Comment, CommentAdmin)
|
jdzero/foundation | foundation/backend/views/__init__.py | Python | mit | 46 | 0 | f | rom .base import *
from .controller import *
| |
billychasen/billots | billots/src/model/crypto.py | Python | mit | 1,409 | 0.002129 | # Copyright (c) 2017-present, Billy Chasen.
# See LICENSE for details.
# Created by Billy Chasen on 8/17/17.
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA512
from Crypto.Signature import PKCS1_v1_5
from billots.src.utils.utils import Utils
class Crypto:
def __init__(self, key_size = 4096):
... | A.generate(self.key_size)
return {"public": keys.publickey().exportKey(),
"private": keys.exportKey()}
@staticmethod
def hash(val):
"""
Hash the value with SHA512
"""
h = SHA512.new()
h.update(Utils.safe_enc(val))
return h.hexdigest()
... | vate key
"""
key = RSA.importKey(private_key)
hashed = SHA512.new(Utils.safe_enc(data))
signer = PKCS1_v1_5.new(key)
return signer.sign(hashed)
@staticmethod
def verify_signed(public_key, signature, data):
"""
Verify a signature
"""
key =... |
loopingz/nuxeo-drive | nuxeo-drive-client/nxdrive/tests/test_shared_folders.py | Python | lgpl-2.1 | 3,409 | 0.00088 | from nxdrive.tests.common_unit_test import UnitTestCase
from nxdrive.client import RemoteDocumentClient
from nxdrive.client import LocalClient
class TestSharedFolders(UnitTestCase):
def test_move_sync_root_child_to_user_workspace(self):
"""See https://jira.nuxeo.com/browse/NXP-14870"""
admin_rem... | _folder_2)
# Make sure personal workspace is created for user1
remote_user1.make_file_in_user_workspace('File in user workspace',
| filename='UWFile.txt')
# As user1 register personal workspace as a sync root
remote_user1.register_as_root(user1_workspace_path)
# As user1 create a parent folder in user1's personal workspace
remote_user1.make_folder(user1_workspace_path, 'Parent')
# As ... |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/examples/model_selection/plot_train_error_vs_test_error.py | Python | mit | 2,578 | 0.001164 | """
=========================
Train error vs Test error
=========================
Illustration of how the performance of an estimator on unseen data (test data)
is not the same as the performance on training data. As the regularization
increases the performance on train decreases while the performance on test
is optim... | subplot(2, 1, 1)
plt.semilogx(alphas, train_errors, label='Train')
plt.semilogx(alphas, test_errors, label='Test')
plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k',
linewidth=3, label='Optimum on test')
plt.legend(loc='lower left')
plt.ylim([0, 1.2])
plt.xlabel('Regularization parameter'... | imated coef_ vs true coef
plt.subplot(2, 1, 2)
plt.plot(coef, label='True coef')
plt.plot(coef_, label='Estimated coef')
plt.legend()
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26)
plt.show()
|
mlecours/fake-switches | fake_switches/brocade/command_processor/config_vlan.py | Python | apache-2.0 | 3,733 | 0.003482 | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | args):
actual_ve = next(
(p for p in self.switch_configuration.ports if isinstance(p, VlanPort) and p.vlan_id == self.vlan.number),
False)
if not actual_ve:
name = " ".join(args)
self.switch_configuration.add_port(self.switch_configuration.new("VlanPort", ... | lan.number,
name))
else:
self.write_line("Error: VLAN: %s already has router-interface %s" % (
self.vlan.number, split_port_name(actual_ve.name)[1]))
def do_no_router_interface(self, *_):
self.... |
SSSD/sssd | src/tests/multihost/alltests/test_krb5.py | Python | gpl-3.0 | 6,587 | 0 | """ Automation of Krb5 tests
:subsystemteam: sst_idm_sssd
:upstream: yes
"""
from __future__ import print_function
import pytest
from sssd.testlib.common.utils import sssdTools
from sssd.testlib.common.expect import pexpect_ssh
from sssd.testlib.common.exceptions import SSHLoginException
@pytest.mark.usefixtures('se... | 72513
:id: 74a60320-e48b-11eb-ba19-845cf3eff344
:requirement: IDM-SSSD-REQ : LDAP Provider
:steps:
1. Start SSSD with any configuration
2. Call 'getent passwd username@domain'
3. Check the entry is present in data and timestamp cache
4. Now stop SSSD and r... | s:
1. Should succeed
2. Should succeed
3. Should succeed
4. Should succeed
5. Should succeed
6. Should succeed
7. Should succeed
"""
multihost.client[0].service_sssd('restart')
cmd = multihost.client[0].run_command('getent pas... |
mitdbg/modeldb | client/verta/verta/endpoint/autoscaling/__init__.py | Python | mit | 239 | 0 | # -*- coding: utf-8 -*-
"""Autoscaling configuration for endpoints."""
from verta | ._internal_utils import documentation
from ._autoscaling import Autoscaling
documentation.reassign_module(
[Autoscaling | ],
module_name=__name__,
)
|
hnakamur/ansible | lib/ansible/plugins/lookup/__init__.py | Python | gpl-3.0 | 1,681 | 0.001785 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# 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) an... | results.append(self._flatten([x,y]))
return results
def _flatten_hash_to_list(self, terms):
ret = []
for ke | y in terms:
ret.append({'key': key, 'value': terms[key]})
return ret
|
KamLii/Databaes | Crate/forms.py | Python | mit | 302 | 0.003311 | from django import forms
from Crate.models import Discussion
class ReportForm(forms.Form):
| report = forms.CharField(label="Enter your report", max_length=500, widget=forms.Textarea)
class DiscussionForm(forms.ModelForm):
| class Meta:
model = Discussion
fields = ['comment']
|
magreiner/orchestration-tools | template_testing.py | Python | apache-2.0 | 859 | 0 | #!/bin/python3
# Testscript for template generation and deploying
from cloud_provider.amazon import Amazon
from template.template import CloudFormationTemplate
from pprint import pprint
if __name__ == "__main__":
# Amazon Settings
region = "eu-west-1"
stack_name = 'TestStack'
# Template settings
... | .json'
# Create template
cfn_template = CloudFormationTemplate()
cfn_template.load_json_source(template_json_source_file)
cfn_template.save_template_file(template_file)
# ppr | int(cfn_template.source)
# Connect to Amazon CloudFormation
aws = Amazon(region)
# Deploy CloudFormation Template
aws.deploy_stack(stack_name, template_file=template_file)
# Delete Stack if error occured
# aws.delete_stack(stack_name)
|
NESCent/Chimp-Recs-FieldObservations | ObservationParsing/src/obsparser/app.py | Python | cc0-1.0 | 4,869 | 0.010885 | '''
Created on Feb 8, 2011
@author: vgapeyev
'''
import csv, re
__nonspace_whitespace = re.compile(r"[\t\n\r\f\v]")
__long_whitespace = re.compile(r"[ ]{2,}")
def normalize_whitespace(str):
str = re.sub(__nonspace_whitespace, " ", str)
str = re.sub(__long_whitespace, " ", str)
return str
def empty_line(... | |_|=)=?\s*(?P<animal>[a-zA-Z]+)\s*(-|_)?\s*(?P<num>\d+\w*)"
pat = re.compile(pat_spec)
match = re.search(pat, line)
if match and at_beginning(match, line):
equip = "N"
animal = match.group("animal").upper()
num = match.group("num")
rest = line[match.end():]
| return ((equip, animal, num), rest.lstrip())
else:
return (("", "", ""), line)
def parse_line(line):
(time, line) = pick_time(line)
(recnum, line) = pick_recnum(line)
text = normalize_whitespace(line.strip())
return (time, recnum[0], recnum[1], recnum[2], text)
def parse_one_file(src_fil... |
bitmazk/django-unshorten | manage.py | Python | mit | 259 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "unshorten.tests.setti | ngs")
from djang | o.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
wittrup/crap | python/keyboard.py | Python | mit | 3,048 | 0.006234 | import ctypes
from ctypes import wintypes
import time
user32 = ctypes.WinDLL('user32', use_last_error=True)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_SCANCODE = 0x0008
MAPVK_VK_TO_VSC = 0
# msdn... | LPINPUT, # pInputs
ctypes.c_int) # cbSize
# Functions
def PressKey(hexKeyCode):
x = INPUT(type=INPUT_KEYBOARD,
ki=KEYBDINPUT(wVk=hexKeyCode))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
x = INPUT(type=INPUT... | ki=KEYBDINPUT(wVk=hexKeyCode,
dwFlags=KEYEVENTF_KEYUP))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def AltTab():
"""Press Alt+Tab and hold Alt key for 2 seconds
in order to see the overlay.
"""
PressKey(VK_MENU) # Alt
PressKey(VK_TAB) # Tab
Re... |
popazerty/EG-2 | lib/python/Components/Converter/ConditionalShowHide.py | Python | gpl-2.0 | 1,460 | 0.037671 | from enigma import eTimer
from Converter import Converter
class ConditionalShowHide(Converter, object):
def __init__(self, argstr):
Converter.__init__(self, argstr)
args = argstr.split(',')
self.invert = "Invert" in args
self.blink = "Blink" in args
if self.blink:
self.blinktime = len(args) == 2 and args... | ef blinkFunc(self):
if self.blinking:
for x in self.downstream_elements:
x.visible = not x.visible
def startBlinking(self):
self.blinking = True
self.timer.start(self.blinktime)
def stopBlinking(self):
self.blinking = False
for x in self.downstream_elements:
| if x.visible:
x.hide()
self.timer.stop()
def calcVisibility(self):
b = self.source.boolean
if b is None:
return True
b ^= self.invert
return b
def changed(self, what):
vis = self.calcVisibility()
if self.blink:
if vis:
self.startBlinking()
else:
self.stopBlinking()
else:
fo... |
ee08b397/LeetCode-4 | 070 Text Justification.py | Python | mit | 3,264 | 0.007353 | """
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left
and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces
' ' when necessary so that each line has exactly ... |
Extra spaces between words should be distributed as evenly as possible. If the number of spaces o | n a line do not divide
evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification... |
luo2chun1lei2/AgileEditor | ve/src/ViewDialogPreferences.py | Python | gpl-2.0 | 3,229 | 0.011375 | #-*- coding:utf-8 -*-
###########################################################
# 项目各种选项的对话框。
import os, string, logging
import ConfigParser
from gi.repository import Gtk, Gdk, GtkSource
from VeUtils import *
from ModelProject import ModelProject
from VeEventPipe import VeEventPipe
##############################... | #if styleScheme is not None:
# self.styleScheme = styleScheme # 不能丢弃
#src_buffer.set_style_scheme(self.styleScheme)
model = Gtk.ListStore(str)
found_index = -1
for i in range(len(styles)):
model.append([styles[i]])
if styles[i] == self.setting['s... | el(model)
cell_render = Gtk.CellRendererText.new()
cmb.pack_start(cell_render, True)
cmb.add_attribute(cell_render, "text", 0)
cmb.set_active(found_index)
cmb.connect("changed", self.on_style_changed)
return cmb
def on_style_changed(self, combob... |
usrlocalben/pydux | test/test_apply_middleware.py | Python | mit | 1,791 | 0.002233 | from __future__ import absolute_import
import unittest
import mock
from pydux import create_store, apply_middleware
from .helpers.reducers import reducers
from .helpers.action_creators import add_todo, add_todo_if_empty
from .helpers.middleware import thunk
class TestApplyMiddleware(unittest.TestCase):
def test... | return lambda next: lambda action: next(action)
return apply
spy = mock.MagicMock()
store = apply_middleware(test(spy), thunk)(cre | ate_store)(reducers['todos'])
store['dispatch'](add_todo('Use Redux'))
store['dispatch'](add_todo('Flux FTW!'))
self.assertEqual(spy.call_count, 1)
args, kwargs = spy.call_args
self.assertEqual(sorted(list(args[0].keys())),
sorted(['get_state', 'dispatc... |
adrianratnapala/elm0 | n0run.py | Python | isc | 10,558 | 0.022163 | #!/usr/bin/python3
"""
n0run.py -- a unit test runner.
n0run runs 0unit based tests programs and then does wierd things far beyond
the power of 0unit. We use n0run when we want to make sure that things fail
when and "how" they are supposed to, even if the "how" means the error
propagates all the way to the ... | howok
if not isinstance(b, bytes) :
raise Exception('regex must be bytes.')
return n, compile(b), f
return list(map(compile_one, sources))
match_passe | d = compile_matchers([ ('passed', b'^passed: (?P<n>test\S*)'), ])
match_failed = compile_matchers([ ('FAILED', b'^FAILED: [^:]+:[0-9]+:(?P<n>test\S*)') ])
match_allpassed = compile_matchers([ (None, b'^All [0-9]+ tests passed$')])
def scan_output(po, matchers = match_passed ) :
out = {}
err = []
... |
moradin/renderdoc | util/test/tests/Vulkan/VK_SPIRV_13_Shaders.py | Python | mit | 3,571 | 0.006161 | import renderdoc as rd
import rdtest
class VK_SPIRV_13_Shaders(rdtest.TestCase):
demos_test_name = 'VK_SPIRV_13_Shaders'
def check_capture(self):
action = self.find_action("Draw")
self.check(action is not None)
self.controller.SetFrameEvent(action.eventId, False)
pipe: rd.P... | ctly")
if (refl.inputSignature[1].varName != 'col' or refl.inputSignature[1].compCount != 4):
raise rdtest.TestFailureException( | "Vertex shader input 'col' not reflected correctly")
if (refl.inputSignature[2].varName != 'uv' or refl.inputSignature[2].compCount != 2):
raise rdtest.TestFailureException("Vertex shader input 'uv' not reflected correctly")
if (refl.outputSignature[0].varName != 'opos' or refl.outputSignat... |
duedil-ltd/pyfilesystem | fs/__init__.py | Python | bsd-3-clause | 1,781 | 0.005053 | """
fs: a filesystem abstraction.
This module provides an abstract base class 'FS' that defines a consistent
interface to different kinds of filesystem, along with a range of concrete
implementations of this interface such as:
OSFS: access the local filesystem, through the 'os' module
TempFS: a ... | ntifiers in the fs namespace
import os
SEEK_CUR = os.SEEK_CUR
SEEK_END = os.SEEK_END
SEEK_SET = os.SEEK_SET
# Allow clean use of logging throughout the lib
import logging | as _logging
class _NullHandler(_logging.Handler):
def emit(self,record):
pass
_logging.getLogger("fs").addHandler(_NullHandler())
def getLogger(name):
"""Get a logger object for use within the pyfilesystem library."""
assert name.startswith("fs.")
return _logging.getLogger(name)
|
sunlightlabs/upwardly | src/movingup/utils/douglaspeucker.py | Python | bsd-3-clause | 2,902 | 0.006547 | # pure-Python Douglas-Peucker line simplification/generalization
#
# this code was written by Schuyler Erle <[email protected]> and is
# made available in the public domain.
#
# the code was ported from a freely-licensed example at
# http://www.3dsoftware.com/Cartography/Programming/PolyLineReduction/
#
# the orig... | oints (pts, tolerance):
anch | or = 0
floater = len(pts) - 1
stack = []
keep = set()
stack.append((anchor, floater))
while stack:
anchor, floater = stack.pop()
# initialize line segment
if pts[floater] != pts[anchor]:
anchorX = float(pts[floater][0] - pts[anchor][0])
... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/SGIS/texture_color_mask.py | Python | lgpl-3.0 | 714 | 0.026611 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw. | GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENS | ION_NAME = 'GL_SGIS_texture_color_mask'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GL,'GL_SGIS_texture_color_mask',error_checker=_errors._error_checker)
GL_TEXTURE_COLOR_WRITEMASK_SGIS=_C('GL_TEXTURE_COLOR_WRITEMASK_SGIS',0x81EF)
@_f
@_p.types(None,_cs.GLboolean,_cs.GLboolean,_cs.GLboolean,_... |
danielnyga/dnutils | src/dnutils/logs.py | Python | mit | 18,264 | 0.002245 | import json
import logging
import os
import re
import sys
import tempfile
import atexit
import warnings
import colored
import datetime
from .tools import ifnone
from .debug import _caller
from .threads import RLock, interrupted, Lock
from .tools import jsonify
import portalocker
FLock = portalocker.Lock
DEBUG = ... | Handler.__init__(self, filename, mode=mode, encoding=encoding, delay=delay)
self.timeformatstr = '%Y-%m-%d %H:%M:%S'
def emit(self, record):
try:
msg = self.format(record)
stream = self.stream
stream.write(msg)
stream.write(self.terminator)
... | .format(datetime.datetime.fromtimestamp(record.created).strftime(self.timeformatstr),
record.levelname,
' '.join(' '.join(map(str, record.msg)).split('\n')))
StreamHandler = logging.StreamHandler
_expose_basedir = '.exposure'
_exposures = Non... |
hal0x2328/neo-python | neo/Network/nodeweight.py | Python | mit | 2,320 | 0.002586 | from datetime import datetime
class NodeWeight:
SPEED_RECORD_COUNT = 3
SPEED_INIT_VALUE = 100 * 1024 ^ 2 # Start with a big speed of 100 MB/s
REQUEST_TIME_RECORD_COUNT = 3
def __init__(self, nodeid):
self.id: int = nodeid
self.speed = [self.SPEED_INIT_VALUE] * self.SPEED_RECORD_COUN... | me.utcnow().timestamp() * 1000 # milliseconds
self.request_time = [now] * self.REQUEST_TIME_RECORD_COUNT
def append_new_speed(self, speed) -> None:
# remove oldest
self.speed.pop(-1)
# add new
self.speed.insert(0, speed)
def append_new_request_time(self) -> None:
... | illiseconds
self.request_time.insert(0, now)
def _avg_speed(self) -> float:
return sum(self.speed) / self.SPEED_RECORD_COUNT
def _avg_request_time(self) -> float:
avg_request_time = 0
now = datetime.utcnow().timestamp() * 1000 # milliseconds
for t in self.request_time... |
pokey/smartAutocomplete | pythonServer/iterateRuns.py | Python | mit | 3,283 | 0.005483 | #!/usr/bin/python
from execrunner import o, selo, selmo, cmdList, f
import subprocess, argparse
# Dataset prefix
dp = '/u/nlp/data/smart-autocomplete/datasets/'
constants = {
'python': '/u/nlp/packages/python-2.7.4/bin/python2.7',
'statePath': '/u/nlp/data/smart-autocomplete/state'
}
def main():
parser = \
... | ngularity-chess', 'py')),
selo('features', -2,
# KN
['scope', 'ngram'],
# Ngrams
['simple', 'prev', 'prevTwo', 'prevThree'],
# Basic features
['simple', 'path', 'filetype', 'prev', 'prevTw... | # Individual features
['simple'],
['path'],
['filetype'],
['prev'],
['prevTwo'],
['prevThree'],
['prevPrev'],
['prevForm'],
['lineStart'],
... |
jaantoots/bridgeview | render/render.py | Python | gpl-3.0 | 18,995 | 0.000211 | """Provides methods for rendering the labelled model."""
import json
import os
import hashlib
import glob
import numpy as np
import bpy # pylint: disable=import-error
from . import helpers
class Render():
"""Configure and render the scene.
Parameters are read from conf_file. During testing and setup one
... | for camera views
if self.opts.get('spheres') is None:
sphere = helpers.BoundingSphere()
self.opts['spheres'] = {}
self.opts['spheres']['default'] = sphere.find(self.objects)
# Convert camera lines if provided
if self.opts.get('lines') is not None:
| self.opts['lines'] = {name: {point: np.array(coords)
for point, coords in line.items()}
for name, line in self.opts['lines'].items()}
# Initialise things
self.sun = self.new_sun()
self.camera = self.new_camera()
... |
pfalcon/ScratchABit | plugins/cpu/arm_32_arm_capstone.py | Python | gpl-3.0 | 891 | 0.001122 | # ScratchABit - interactive disassembler
#
# Copyright (c) 2018 Paul Sokolovsky
#
# 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... | S_ARCH_ARM, capstone.CS_MODE_ARM)
def PROCESSOR_ENTRY():
| return _any_capstone.Processor("arm_32", dis)
|
atrsoftgmbh/atrshmlog | python/src/tests/t_clock_id.py | Python | apache-2.0 | 594 | 0.006734 | #!/usr/bin/python3
#
# $Id:$
#
# We test a bit of the atrshmlog here.
#
# This is for the first starter, so only the basic things.
import sys
import atrshmlog
r = atrshmlog.attach()
id = atrshmlog.get_clock_id()
print('clock id : ' + s | tr(id) + ' : ')
oldid = atrshmlog.set_clock_id(2)
print('clock id : ' + str(oldid) + ' : ')
id = atrshmlog.get_clock_id()
print('clock | id : ' + str(id) + ' : ')
oldid = atrshmlog.set_clock_id(1)
print('clock id : ' + str(oldid) + ' : ')
id = atrshmlog.get_clock_id()
print('clock id : ' + str(id) + ' : ')
print (' ')
exit(0);
# end of test
|
mhbu50/frappe | frappe/model/document.py | Python | mit | 43,429 | 0.028 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
import frappe
import time
from frappe import _, msgprint, is_whitelisted
from frappe.utils import flt, cstr, now, get_datetime_str, file_lock, date_diff
from frappe.model.base_document import BaseDocument, get_controller... | cs = {}
self.flags = frappe._dict()
if args and args[0] and isinstance(args[0], str):
# first arugment is doctype
if len(args)==1:
# single
self.doctype = self.name = args[0]
else:
self.doctype = args[0]
if isinstance(args[1], dict):
# filter
self.name = frappe.db.get_value(args[... | args[1], "name")
if self.name is None:
frappe.throw(_("{0} {1} not found").format(_(args[0]), args[1]),
frappe.DoesNotExistError)
else:
self.name = args[1]
if 'for_update' in kwargs:
self.flags.for_update = kwargs.get('for_update')
self.load_from_db()
return
if args and a... |
kakunbsc/enigma2 | lib/python/Screens/InfoBar.py | Python | gpl-2.0 | 9,340 | 0.029229 | from Tools.Profile import profile
# workaround for required config entry dependencies.
from Screens.MovieSelection import MovieSelection
from Screen import Screen
profile("LOAD:enigma")
from enigma import iPlayableService
profile("LOAD:InfoBarGenerics")
from Screens.InfoBarGenerics import InfoBarShowHide, \
InfoBa... | oBarJobman, \
InfoBarPlugins, InfoBarServiceErrorPopupSupport:
x.__init__(self)
self.helpList.append((self["actions"], "InfobarActions", [(" | showMovies", _("view recordings..."))]))
self.helpList.append((self["actions"], "InfobarActions", [("showRadio", _("hear radio..."))]))
self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
{
iPlayableService.evUpdatedEventInfo: self.__eventInfoChanged
})
self.current_begin_time=0
assert... |
skarra/PRS | libs/sqlalchemy/util/deprecations.py | Python | agpl-3.0 | 7,169 | 0.000139 | # util/deprecations.py
# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Helpers related to deprecation of functions, methods, classes, other
functio... | warning. A sensible default
is used if not provided.
:param add_deprecation_to_docstring:
Default True. If False, the wrapped function's __doc__ is left
as-is. If True, the 'message' is prepended to the docs if
provided, or sensible default if message is omitted.
"""
if add_de... | "Call to deprecated function %(func)s"
def decorate(fn):
return _decorate_with_warning(
fn,
exc.SADeprecationWarning,
message % dict(func=fn.__name__),
header,
)
return decorate
def deprecated_params(**specs):
"""Decorates a function to wa... |
nens/threedi-qgis-plugin | tests/test_spatialalchemy.py | Python | gpl-3.0 | 2,234 | 0.000448 | from geoalchemy2.types import Geometry
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from ThreeDiToolbox.utils.threedi_database import ThreediDatabase
import logging
import os.path
import tempfile
import unittest
log... | name__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
def __repr__(self):
return "<User(name='%s')>" % (self.name)
class GeoTable(Base):
__tablename__ = "geotable"
id = Column(Integer, primary_key=True)
name = Column(String)
geom = Column(
Geometry(... | yWithSpatialite(unittest.TestCase):
def setUp(self):
self.tmp_directory = tempfile.mkdtemp()
self.file_path = os.path.join(self.tmp_directory, "testdb.sqlite")
db = ThreediDatabase(
{"db_file": self.file_path, "db_path": self.file_path}, echo=True
)
db.create_db(... |
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Screens/FactoryReset.py | Python | gpl-2.0 | 1,747 | 0.017745 | from Screens.MessageBox import MessageBox
from boxbranding import getMachineBrand, getMachineName
from Screens.ParentalControlSetup import ProtectedScreen
from Components.config import config
from Tools.BoundFunction import boundFunction
from Screens.InputBox import PinInput
class FactoryReset(MessageBox, ProtectedScr... | List=[x.value for x in config.ParentalControl.servicepin], triesEntry=config.ParentalControl.retries.servicepin, title=_("Please enter the correct pin code"), windowTitle=_("Enter pin code")))
def isProtected(self):
return config.ParentalCont | rol.setuppinactive.value and (not config.ParentalControl.config_sections.main_menu.value or hasattr(self.session, 'infobar') and self.session.infobar is None) and config.ParentalControl.config_sections.manufacturer_reset.value
def pinEntered(self, result):
if result is None:
self.closeProtectedScreen()
elif no... |
Etxea/gestioneide | gestioneide/migrations/0003_auto_20160228_1748.py | Python | gpl-3.0 | 768 | 0.001302 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-28 16:48
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('gestioneide', '0002_auto_20160223_1743'),
]
operations = [
migrations.AddField(
model_name='alumno',
name='fecha_nacimiento',
field=models.DateField(blank=True, default=datetime.date.today),
),
migrations.AlterField(
model_name='c... | s'), (4, 'Jueves'), (5, 'Viernes')], decimal_places=0, max_digits=1),
),
]
|
dvl/imagefy-web | imagefy/core/views.py | Python | mit | 380 | 0.002632 | from allauth.socialaccount.providers.facebook.v | iews import FacebookOAuth2Adapter
from allauth.socialaccount.providers.shopify.views import ShopifyOAuth2Adapter
from rest_auth.registration.views import SocialLoginV | iew
class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
class ShopifyLogin(SocialLoginView):
adapter_class = ShopifyOAuth2Adapter
|
jr-garcia/Engendro3D | Demos/_base/_model_paths.py | Python | mit | 305 | 0.003279 | import os
| maindir = os.path.join(os.path.dirname(__file__), os.pardir,"models")
duckMODEL = os.path.join(maindir, "duck", "duck.3DS")
dwarfMODEL = os.path.join(maindir, 'dwarf', "dwarf.x")
tubeMODEL = os.path.join(maindir, 'cil', 'cil.x')
triangleMODEL = os.path.join(maindir, | 'triangle', 'triangle.x')
|
furthz/colegio | src/register/forms.py | Python | mit | 14,437 | 0.007206 | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from dal import autocomplete
from django import forms
from django.forms import ModelForm
from profiles.models import Profile
from register.models import Alumno, Apoderado, Personal, Promotor, Director, Cajero, Tesorero, Proveedor, Colegi... | iones_distritos,
widget=forms.Select(attrs={'tabindex': '12', 'class': 'form-control'}))
self.fields['provincia'].initial = direc.provincia
self.fields['distrito'].initial = direc.distrito
self.fields['direccion' | ].initial = direc.calle
self.fields['referencia'].initial = direc.referencia
except:
self.fields['provincia'] = forms.ChoiceField(choices=self.ChoiceProvincia, initial='-1',
widget=forms.Select(
... |
kcsry/wurst | wurst/api/utils.py | Python | mit | 646 | 0.003096 | from rest_framework import serializers
def serializer_factory(model, serializer_class=serializers.ModelSerializer, attrs=None, meta=None):
"""
Generate a simple serializer for the given model class.
:param model: | Model class
:param serializer_class: Serializer base class
:param attrs: Serializer class attrs
:param meta: Serializer Meta class attrs
:return: a Serializer class
"""
attrs = attrs or {}
meta = meta or {}
meta.setdefault("model", model)
attrs.setdefa | ult("Meta", type(str("Meta"), (object,), meta))
return type(str("%sSerializer" % model.__name__), (serializer_class,), attrs)
|
olafhauk/mne-python | mne/preprocessing/nirs/_tddr.py | Python | bsd-3-clause | 4,673 | 0 | # Authors: Robert Luke <[email protected]>
# Frank Fishburn
#
# License: BSD (3-clause)
import numpy as np
from ... import pick_types
from ...io import BaseRaw
from ...utils import _validate_type
from ...io.pick import _picks_to_idx
def temporal_derivative_distribution_repair(raw):
"""Apply temporal... | o data
:footcite:`FishburnEtAl2019`. This approach removes baseline shift
and spike artifacts without the need for any user-supplied parameters.
Parameters
----------
raw : instance of Raw
The raw data.
%(verbose)s
Returns
-------
raw : instance of Raw
Data with TD... | ngth is an issue).
References
----------
.. footbibliography::
"""
raw = raw.copy().load_data()
_validate_type(raw, BaseRaw, 'raw')
if not len(pick_types(raw.info, fnirs='fnirs_od')):
raise RuntimeError('TDDR should be run on optical density data.')
picks = _picks_to_idx(raw.i... |
fedora-infra/pkgdb2 | pkgdb2/api/packages.py | Python | gpl-2.0 | 53,012 | 0.000094 | # -*- coding: utf-8 -*-
#
# Copyright © 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed... | output['error'] = 'Inva | lid input submitted'
if form.errors:
detail = []
for error in form.errors:
detail.append('%s: %s' % (error,
'; '.join(form.errors[error])))
output['error_detail'] = detail
httpcode = 500
jsonout = flask.jsonify(output... |
ros-infrastructure/ros_buildfarm | scripts/devel/build_and_test.py | Python | apache-2.0 | 6,218 | 0.000161 | #!/usr/bin/env python3
# Copyright 2014, 2016 Open Source Robotics Foundation, 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
#
# Unl... | NG=0',
| '-DCATKIN_TEST_RESULTS_DIR=%s' % test_results_dir]
additional_args = args.build_tool_args or []
if args.build_tool == 'colcon':
additional_args += ['--test-result-base', test_results_dir]
env = dict(os.environ)
env.setdefault('MAKEFLAGS', '-... |
armab/st2 | st2common/st2common/models/utils/action_alias_utils.py | Python | apache-2.0 | 4,206 | 0.001189 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | rs_match = r'(?:^|\s+)(\S+)=("(.*?)"|\'(.*?)\'|({.*?})|(\S+))'
extra = re.match(r'.*?((' + pairs_mat | ch + r'\s*)*)$',
self._param_stream, re.DOTALL)
if extra:
kv_pairs = re.findall(pairs_match,
extra.group(1), re.DOTALL)
self._param_stream = self._param_stream.replace(extra.group(1), '')
self._param_stream = " %s " % sel... |
powerpak/pph2_and_rank | pph2_and_rank.py | Python | mit | 11,921 | 0.007557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""\
pph2_and_rank.py
Submits a list of genes with SNPs to PolyPhen2 and orders them by
a score measuring the overall deleteriousness of the mutations,
normalized for protein length.
LICENSE
Written by Ted Pak for the Roth Laboratory (http://llama.mshri.on.ca).
Releas... | ulSoup(doc)
sid_input = soup | .find('input', {'name': 'sid'})
if sid_input is None:
print doc
raise RemoteException("GGI returned a weird page without a SID.")
sid = sid_input['value']
return sid
def poll_for_polyphen2_results(sid):
""" Polls PolyPhen2's GGI web interface for updates on the progress of the job.
... |
yippeecw/sfa | sfa/server/xmlrpcapi.py | Python | mit | 6,069 | 0.008898 | #
# SFA XML-RPC and SOAP interfaces
#
import string
import xmlrpclib
# SOAP support is optional
try:
import SOAPpy
from SOAPpy.Parser import parseSOAPRPC
from SOAPpy.Types import faultType
from SOAPpy.NS import NS
from SOAPpy.SOAP | Builder import buildSOAP
except ImportError:
SOAPpy = None
####################
#from sfa.util.faults import SfaNotImplemented, SfaAPIError, SfaInvalidAPIMethod, SfaFault
from sfa.util.faults import SfaInvalidAPIMethod, SfaAPIError, SfaFault
from sfa.util.sfalogging import logger
####################
# See "2.2 C... | = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
def xmlrpclib_escape(s, replace = string.replace):
"""
xmlrpclib does not handle invalid 7-bit control characters. This
function augments xmlrpclib.esca... |
PyPila/auth-client | authclient/decorators.py | Python | gpl-3.0 | 1,544 | 0 | import logging
from functools import wraps
from requests.exceptions import HTTPError
from django.utils.decorators import available_attrs
from django.conf import settings
from authclient import _get_user_session_key, SESSION_KEY
from authclient.client import auth_client
logger = logging.getLogger('authclient')
def ... | def _wrapped(request, *args, **kwargs):
return view_func(request, *args, **kwargs)
_wrapped.app_auth_exempt = True
return _wrapped
if function:
return decorator(function)
return decorator
def refresh_jwt(view_func):
"""
Decorator that adds headers to a response so ... | vailable_attrs(view_func))
def _wrapped_view_func(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
try:
resource_token = _get_user_session_key(request)
except KeyError:
pass
else:
try:
resource_token = auth_... |
sgaynetdinov/py-vkontakte | tests/test_user_career.py | Python | mit | 1,213 | 0 | import pytest
from vk.users import UserCareer
def test_user_career(factory):
career_json = factory('user_career.json')['career'][0]
career = UserCareer.from_json(None, career_json)
assert isinstance(career, UserCareer)
assert career.group == 22822305
assert career.company is None
assert care... |
career = UserCareer.from_json(None, career_json)
assert 'group_id' not in career_json
assert career.group is None
assert career.company == 'Telegram'
assert career.id == hash(career.company)
def test_wit | hout_city_id(factory):
career_json = factory('user_career.json')['career'][0]
del career_json['city_id']
career_json['city_name'] = 'Moscow'
career = UserCareer.from_json(None, career_json)
assert 'city_id' not in career_json
assert career.city is None
assert career.city_name == 'Moscow'
|
Bogadon/Battletech | ai.py | Python | gpl-2.0 | 18,339 | 0.006816 | # AI Classes
'''
Initiative: Either I win or I lose, if I win I go second, so I know my
opponents moves already- otherwise I have to try and predict them
Move Phase: Number of possible moves per unit depends on speeds and
world mechanics. It can easily be 100+ per unit. If we lost the
initiative then we need... | memory
class AI_Player(Player):
def __init__(self, name, mechs, disposition): #, World, MAX_TURN_CALCS):
super(AI_Player, self).__init__(name, mechs)
unique_id = 0
self.unique_ids = {}
for unit in self.units_live:
unit.unique_id = unique_id
self.unique_ids[un... | n = disposition
self.all_disps = [ 'reckless', 'aggressive', 'neutral', 'defensive',
'cowardly' ]
self.World = None
self.infer_opponent = 'neutral'
self.memory = []
self._all_turn_movements = []
self.my_turn = None
# Per Instance
... |
ClusterHQ/libcloud | libcloud/dns/drivers/zerigo.py | Python | apache-2.0 | 18,252 | 0.000055 | # 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 use ... | path = API_ROOT + 'hosts/%s.xml' % (record_id)
data = self.connection.request(path).object
record = self._to_record(elem=data, zone=zone)
return record
def create_zone(self, domain, type='master', ttl=None, extra=None):
"""
Create a new zone.
Provider API docs:
... | te
@inherits: :class:`DNSDriver.create_zone`
"""
path = API_ROOT + 'zones.xml'
zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl,
extra=extra)
data = self.connection.request(action=path,
... |
hectormartinez/rougexstem | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/corpus/reader/ycoe.py | Python | apache-2.0 | 11,296 | 0.00239 | # -*- coding: iso-8859-1 -*-
# Natural Language Toolkit: York-Toronto-Helsinki Parsed Corpus of Old English Prose (YCOE)
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Selina Dennis <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
"""
Corpus reader for ... | , format='parsed'):
if format == 'parsed': return self.parsed_sents(items)
if format == 'raw': return self.raw(items)
if format == 'tokenized': return self.words(items)
if format == 'tagged': return self.tagged_words(items)
if format == 'chunked': raise ValueError('no longer supp... | d_sents(items)
@deprecated("Use .words() instead.")
def tokenized(self, items=None):
return self.words(items)
@deprecated("Use .tagged_words() instead.")
def tagged(self, items=None):
return self.tagged_words(items)
@deprecated("Operation no longer supported.")
def chunked(self, ... |
jacobamey/Learning-Python | HF-Programming/HFP-CH1/GuessingGame.py | Python | gpl-2.0 | 342 | 0 | from rando | m import randint
secret = randint(1, 10)
print("Welcome!")
guess = 0
while guess != secret:
g = input("Guess the number: ")
guess = int(g)
if guess == secret:
print("You win!")
else:
if guess > secret:
print("Too High")
else:
print(" | Too low")
print("Game over!")
|
etkirsch/legends-of-erukar | erukar/content/inventory/materials/raw/AnimalHide.py | Python | agpl-3.0 | 204 | 0.004902 | from erukar.system.engine import MaterialGood
class | AnimalHide(MaterialGood):
BaseName = "Animal Hide"
BriefDescription = "an animal's hide"
BasePricePerSingle = 13
Weight | PerSingle = 0.9
|
buchuki/django-registration-paypal | paypal_registration/urls.py | Python | bsd-3-clause | 1,950 | 0.000513 | """
URLconf for registration and activation, using the paypal_registration backend
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.default.urls')),
"""
from ... | ls.defaults import *
from django.views.generic.simple import direct_to_template
try:
from django.views.decorators.csrf import csrf_exempt
except ImportError:
from django.contrib.csrf.middleware import csr | f_exempt
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
url(r'^activate/complete/$',
direct_to_template,
{'template': 'registration/activation_complete.html'},
name='registration_activation_complete'),
url(r'^activate/(?P<activati... |
Lyleo/OmniMarkupPreviewer | OmniMarkupLib/Renderers/libs/python3/genshi/builder.py | Python | mit | 11,729 | 0.002558 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consist... | You should
rarely (if ever) need to directly import and use any of the other classes in
this module.
E | lements can be created using the `tag` object using attribute access. For
example:
>>> doc = tag.p('Some text and ', tag.a('a link', href='http://example.org/'), '.')
>>> doc
<Element "p">
This produces an `Element` instance which can be further modified to add child
nodes and attributes. This is done by "calling" th... |
maruqu/flask-jsonapi | tests/test_filters_schema.py | Python | bsd-3-clause | 8,296 | 0.001205 | import uuid
import marshmallow_jsonapi
import pytest
from marshmallow_jsonapi import fields
import flask_jsonapi
from flask_jsonapi import filters_schema
class TestFiltersSchemaCreation:
def test_simple(self):
class ExampleFiltersSchema(filters_schema.FilterSchema):
title = filters_schema.Li... | a(filters_schema.FilterSchema):
title = filters_schema.FilterField()
class ExampleFiltersSchemaDerived(ExampleFiltersSchema):
content = filters_schema.FilterField()
assert ExampleFiltersSchemaDerived.base_filters == {
| 'title': filters_schema.FilterField(),
'content': filters_schema.FilterField(),
}
def test_creation_using_schema(self):
class ExampleSchema(marshmallow_jsonapi.Schema):
id = fields.UUID(required=True)
body = fields.Str()
is_active = fields.... |
blossomica/airmozilla | airmozilla/manage/views/channels.py | Python | bsd-3-clause | 2,361 | 0 | from django.contrib import messages
from django.shortcuts import render, redirect
from django.db import transaction
from airmozilla.main.models import Channel
from airmozilla.manage import forms
from .decorators import (
staff_required,
permission_required,
cancel_redirect
)
@staff_required
@permission_... | return render(request,
'manage/channel_new.html',
{'form': form,
'use_ace': use_ace})
@staff_required
@permission_required('main.change_channel')
@cancel_redirect('manage:channels')
@transaction.atomic
def channel_edit(request, id):
channel = Channel.obje... | instance=channel)
if form.is_valid():
channel = form.save()
if channel.parent and not form.cleaned_data['parent']:
channel.parent = None
channel.save()
messages.info(request, 'Channel "%s" saved.' % channel.name)
return redirect('ma... |
sminteractive/ndb-gae-admin | demo.py | Python | apache-2.0 | 193 | 0 | import sma | dmin as admin
# Setup the app
# app (instance of AdminApplication) inherits of webapp2.WSGIApplication
app = | admin.app
app.routes_prefix = '/admin'
app.discover_admins('demo_admin')
|
DevangS/CoralNet | lib/forms.py | Python | bsd-2-clause | 2,225 | 0.001798 | from django import forms
from images.models import Image
class ContactForm(forms.Form):
"""
Allows a user to send a general email to the site admins.
"""
email = forms.EmailField(
label='Your email address',
help_text="Enter your email address so we can reply to you.",
)
subjec... | t__(*args, **kwargs)
if user.is_authenticated():
del self.fields['email']
def clean_comma_separated_image_ids_field(value, source):
"""
Clean a char field that contains some image ids separated by commas.
e.g. "5,6,8,9" |
This would preferably go in a custom Field class's clean() method,
but I don't know how to define a custom Field's clean() method that
takes a custom parameter (in this case, the source). -Stephen
"""
# Turn the comma-separated string of ids into a proper list.
id_str_list = value.split(',')
... |
gatieme/EnergyEfficient | script/plot/perflogplot.py | Python | gpl-3.0 | 8,694 | 0.024284 | #!/usr/bin/python
# encoding=utf-8
#!coding:utf-8
import re
import sys
import argparse
import commands
import os
import subprocess
import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import openpyxl
class PerfPlotData :
plotName = "none name"
logfile = "none path"
... | ]
if (name == "NULL") :
break
resultfile = args.directory + "/" + name + "/perf/" + args.bench + "/" \
+ args.min_group + "-" + args.max_group + "-" + args.step_group + "-" +args.loop + ".log"
print "\n=========================================="
print "resu... | + int(args.step_group)) > int(args.max_group)) : # 同一个循环多次
iszero = False
else :
iszero = True
(xData, yData) = ReadPlotData(resultfile, 1000, iszero)
print "+++++++", len(xData), len(yData), "+++++++"
print xData
print yData
print "============... |
ivanalejandro0/bitmask_client | src/leap/bitmask/services/mail/emailfirewall.py | Python | gpl-3.0 | 3,225 | 0 | # -*- coding: utf-8 -*-
# emailfirewall.py
# Copyright (C) 2014 LEAP
#
# 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.
#... |
from leap.bitmask.util import first, force_eval
from leap.bitmask.util.privilege_policies import LinuxPolicyChecker
from leap.common.check import leap_assert
def get_email_firewall():
"""
Return the email firewall handler for the current platform.
"""
# disable email firewall on a docker container so... | ot (IS_LINUX):
error_msg = "Email firewall not implemented for this platform."
raise NotImplementedError(error_msg)
firewall = None
if IS_LINUX:
firewall = LinuxEmailFirewall
leap_assert(firewall is not None)
return firewall()
class EmailFirewall(object):
"""
Abstrac... |
campadrenalin/python-libcps | dbcps/sinks/redis.py | Python | lgpl-3.0 | 1,395 | 0.004301 | '''
This file is part of the Python CPS library.
The Python CPS library is f | ree software: you can redistribute it
and/or modify it under the terms of the GNU Lesser Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
the Python CPS library is distributed in the hope that it will be
useful, but WITHOUT ANY WARR... | ranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser Public License for more details.
You should have received a copy of the GNU Lesser Public License
along with the Python CPS library. If not, see
<http://www.gnu.org/licenses/>.
'''
redislib = __import__("redis", {})
from dbcps.sinks.c... |
pmghalvorsen/gramps_branch | gramps/cli/user.py | Python | gpl-2.0 | 6,799 | 0.005442 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2010 Brian G. Matherly
#
# 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 optio... | ----------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen import user
#------------------------------------------------------------------------
#
# Private Constants
#
#-----------------------------------------------------------... |
#
#-------------------------------------------------------------------------
class User(user.User):
"""
This class provides a means to interact with the user via CLI.
It implements the interface in :class:`.gen.user.User`
"""
def __init__(self, callback=None, error=None, auto_accept=False, quiet=Fa... |
eoogbe/api-client-staging | generated/python/gapic-google-cloud-dlp-v2beta1/setup.py | Python | bsd-3-clause | 1,575 | 0 | """A setup module for the GAPIC DLP API library.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
import sys
install_requires = [
'google-gax>=0.15.7, <0.16dev',
'oauth2client>=2.0.0, <4.0dev',
'proto-googl... | 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
],
description='GAPIC library for the DLP API',
... | ),
install_requires=install_requires,
license='Apache-2.0',
packages=find_packages(),
namespace_packages=[
'google', 'google.cloud', 'google.cloud.gapic',
'google.cloud.gapic.privacy', 'google.cloud.gapic.privacy.dlp'
],
url='https://github.com/googleapis/googleapis')
|
jiasir/pycs | vulpo/auth.py | Python | mit | 35,320 | 0.00051 | # Copyright 2010 Google Inc.
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011, Eucalyptus Systems, 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 re... | headers, None,
self._provider)
vulpo.log.debug('StringToSign:\n%s' % string_to_sign)
| b64_hmac = self.sign_string(string_to_sign)
auth_hdr = self._provider.auth_header
auth = ("%s %s:%s" % (auth_hdr, self._provider.access_key, b64_hmac))
vulpo.log.debug('Signature:\n%s' % auth)
headers['Authorization'] = auth
class HmacAuthV2Handler(AuthHandler, HmacKeys):
"""
... |
ChristineLaMuse/mozillians | vendor-local/lib/python/djcelery/backends/database.py | Python | bsd-3-clause | 1,952 | 0 | from __future__ import absolute_import
from celery import current_app
from celery.backends.base import BaseDictBackend
from celery.utils.timeutils import maybe_timedelta
from ..models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backend.
Using Django models to store ... | lt, status, traceback=None):
"""Store return value and status of an executed task."""
self.TaskModel._default_manager.store_result(task_id, result, status,
traceback=trac | eback)
return result
def _save_taskset(self, taskset_id, result):
"""Store the result of an executed taskset."""
self.TaskSetModel._default_manager.store_result(taskset_id, result)
return result
def _get_task_meta_for(self, task_id):
"""Get task metadata for a task by i... |
sbesson/zeroc-ice | rb/test/Ice/retry/run.py | Python | gpl-2.0 | 807 | 0.008674 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise RuntimeError("can't find toplevel directory!")
sys.path.append(os.path.join(path[0], "scripts"))
import TestUtil
TestUtil.clientServe... | |
horance-liu/tensorflow | tensorflow/contrib/layers/python/layers/layers.py | Python | apache-2.0 | 130,351 | 0.003744 | # -*- coding: utf-8 -*-
# Copyright 2016 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
#
# Un... | s)
return utils.collect_named_outputs(outputs_collections, sc, outputs)
@add_arg_scope
def avg_pool3d(inputs,
| kernel_size,
stride=2,
padding='VALID',
data_format=DATA_FORMAT_NDHWC,
outputs_collections=None,
scope=None):
"""Adds a 3D average pooling op.
It is assumed that the pooling is done per image but not in batch or channels.
Args... |
zetaops/zengine | zengine/tornado_server/server.py | Python | gpl-3.0 | 5,363 | 0.001865 | # -*- coding: utf-8 -*-
"""
tornado websocket proxy for WF worker daemons
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json
import os, sys
import traceback
from uuid import uuid4
from tornado import websocket, we... | ature logout bug (empty login form).
# # FIXME: find a better way to handle HTTP and SOCKET connections for same sess_id.
| # return
self.write(output)
self.finish()
self.flush()
URL_CONFS = [
(r'/ws', SocketHandler),
(r'/(\w+)', HttpHandler),
]
app = web.Application(URL_CONFS, debug=DEBUG, autoreload=False)
def runserver(host=None, port=None):
"""
Run Tornado server
"""
host =... |
jordanemedlock/psychtruths | temboo/core/Library/Google/Drive/Comments/Insert.py | Python | apache-2.0 | 5,038 | 0.005161 | # -*- coding: utf-8 -*-
###############################################################################
#
# Insert
# Creates a new comment on the given file.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file... | e value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.)
"""
super(InsertInputSet, self)._set_input('ClientSecret', value)
def set_Fields(self, value):
"""
Set the value of the Fiel... | he response.)
"""
super(InsertInputSet, self)._set_input('Fields', value)
def set_FileID(self, value):
"""
Set the value of the FileID input for this Choreo. ((required, string) The ID of the file.)
"""
super(InsertInputSet, self)._set_input('FileID', value)
def s... |
portableant/open-context-py | opencontext_py/apps/ocitems/versions/models.py | Python | gpl-3.0 | 845 | 0 | import hashlib
from django | .db | import IntegrityError
from django.db import models
# A version is a way of caching item data so changes can be
# undone
class Version(models.Model):
change_uuid = models.CharField(max_length=50, db_index=True)
uuid = models.CharField(max_length=50, db_index=True)
item_type = models.CharField(max_length=... |
paolo-losi/stormed-amqp | stormed/method/connection.py | Python | mit | 2,532 | 0.011058 | from stormed.util import add_method, AmqpError, logger
from stormed.serialization import table2str
from stormed.heartbeat import HeartbeatMonitor
from stormed.frame import status
from stormed.method.codegen import id2class
from stormed.method.constant import id2constant
from stormed.method.codegen.connection import *
... | __(self, reply_code, reply_text, method):
self.reply_code = reply_code
self.reply_text = reply_text
self.method = method
@add_method(Close)
def handle(self, conn):
try:
mod = id2class[self | .class_id]
method = getattr(mod, 'id2method')[self.method_id]
except:
method = None
conn.reset()
error_code = id2constant.get(self.reply_code, '')
logger.warn('Connection Hard Error. code=%r. %s', error_code,
self.reply_text)
if c... |
unixorn/haze | haze/commands/awsmetadata.py | Python | apache-2.0 | 1,176 | 0.006803 | #!/usr/bin/env python
# Copyright 2015 Joe Block <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance | with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or im... | s under the License.
#
# I have often found it convenient to be able to read what AWS metadata
# for an instance inside bash scripts on the instance.
import argparse
from haze.ec2 import getMetadataKey
# Bash helpers
def awsReadMetadataKey():
"""Print key from a running instance's metadata"""
parser = argparse.Ar... |
pyocd/pyOCD | pyocd/utility/progress.py | Python | apache-2.0 | 4,303 | 0.003486 | # pyOCD debugger
# Copyright (c) 2017-2019 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# 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... | awn onscreen as progress is updated to give the
impression of animation.
"""
## These width constants can't be changed yet without changing the code below to match.
WIDTH = 50
def _update(self, progress):
self._file.write('\r')
i = int(progress * self.WIDTH)
self._file.writ... | 100)))
self._file.flush()
def _finish(self):
self._file.write("\n")
class ProgressReportNoTTY(ProgressReport):
"""@brief Progress report subclass for non-TTY output.
A simpler progress bar is used than for the TTY version. Only the difference between
the previous and current progress... |
LynxyssCZ/Flexget | flexget/plugins/sites/limetorrents.py | Python | mit | 4,028 | 0.002979 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.requests import RequestExc | eption
from flexget.utils.soup import get_soup
from flexget.utils.search import torrent_availability, clean_symbols
from flexget.utils.tools import parse_filesize
log = logging.getLogger('limetorrents')
class Limetorrents(object):
"""
Limetorrents search plugin.
"""
schema = {
'oneOf': [
... | y': {'type': 'string', 'enum': ['all', 'anime', 'applications', 'games', 'movies', 'music',
'tv', 'other'], 'default': 'all'},
'order_by': {'type': 'string', 'enum': ['date', 'seeds'], 'default': 'date'}
},
'... |
karimbahgat/TinyPath | setup.py | Python | mit | 816 | 0.035539 | try: from setuptools import setup
except: from distutils.core import setup
setup( lon | g_description=open("README.rst").read(),
name="""tinypath""",
license="""MIT""",
author="""Karim Bahgat""",
author_e | mail="""[email protected]""",
py_modules=['tinypath'],
url="""http://github.com/karimbahgat/tinypath""",
version="""0.1.1""",
keywords="""paths files folders organizing""",
classifiers=['License :: OSI Approved', 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Intended Audience :: ... |
bbqbailey/geeksHome | geeksHomeApp/load_Sensors.py | Python | gpl-2.0 | 728 | 0.021978 | __author__ = 'superben'
#Zone, SensorName, SensorLocation, SensorType, SensorState, Header, Pin, GPIO, Direction
Sensors={}
print("Opening file sensors.txt")
f=open('sensors.txt','r')
firstTime=True
for line in f:
#print(line)
lineSplit=line.split(',')
#print("Split: " + str(lineSplit))
... | :
Sensors['Fields'] = lineStripped
firstTime=False
else:
zone=lineStripped[0]
sensorName=lineStripped[1]
Sensors[zone + '- | ' + sensorName] = lineStripped
print(Sensors)
for x in Sensors:
if (x != 'Fields'):
print(x, Sensors[x])
|
pombredanne/django-constance | constance/__init__.py | Python | bsd-3-clause | 268 | 0.003731 | from django.utils.functional import Lazy | Object
__version__ = '1.2.1'
default_app_config = 'constance.apps.ConstanceConfig'
class LazyConfi | g(LazyObject):
def _setup(self):
from .base import Config
self._wrapped = Config()
config = LazyConfig()
|
cheneydc/qnupload | src/qnupload/qnupload.py | Python | mit | 4,668 | 0.000214 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This modle will help you put your local file to
QiNiu cloud storage, I use it to share files and
pictures in my blog.
"""
import argparse
# Compatible for Py2 and Py3
try:
import ConfigParser
except ImportError:
import configparser
import os
import qiniu.config
impo... | # Get the full file list from the command line
fileList = []
for item in args.file:
if os.path.isdir(item):
fileList.extend([item+'/'+f for f in os.listdir(item)])
elif os.path.isfile(item):
fileList.append(item)
uploadAuth = getAuth(access_key, secret_key)
buc... | for filePath in fileList:
if checkFile(bucket, filePath, bucketName):
uploadFile(bucketName, filePath, uploadAuth, domain, full_name)
if __name__ == '__main__':
main()
|
daxtens/planyourpicnic | tools/import_furniture.py | Python | gpl-3.0 | 1,520 | 0.010526 | # Import Public Furniture listing into local database from CSV
import sys
sys.path.append('..')
from settings import *
import psycopg2
import psycopg2.extensions
import csv
class Point(object):
def __init__(self, dataString):
#clip out parenthesis, and split over comma
data = dataString[1:-1].split... | sycopg2.extensions.AsIs("'(%s, %s)'" % (psycopg2.extensions.adapt(point.longitude), psycopg2.extensions.adapt(point.latitude)))
psycopg2.extensions.register_adapter(Point, adapt_point)
db_conn = psycopg2.connect(host=DB_HOST, database=DB_ | DATABASE,
user=DB_USER, password=DB_PASSWORD, port=DB_PORT)
db_cur = db_conn.cursor()
with open("../data/Public_Furniture_in_the_ACT.csv") as csvfile:
reader = csv.reader(csvfile)
#skip column labels line
reader.next()
for entry in reader:
db_cur.execute("INSERT IN... |
asedunov/intellij-community | python/testData/intentions/typeAssertion4_after.py | Python | apache-2.0 | 70 | 0.042857 | def foo3(x, y):
assert isinstance(y, object)
i = x | + y
return i
| |
jrajahalme/envoy | docs/conf.py | Python | apache-2.0 | 9,203 | 0.005216 | # -*- coding: utf-8 -*-
#
# envoy documentation build configuration file, created by
# sphinx-quickstart on Sat May 28 10:51:27 2016.
#
# 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
# autogenerated file.
#
# All... | tterns also effect to | html_static_path and html_extra_path
exclude_patterns = [
'_build',
'_venv',
'Thumbs.db',
'.DS_Store',
'api-v2/api/v2/endpoint/load_report.proto.rst',
'api-v2/service/discovery/v2/hds.proto.rst',
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role... |
saurabh6790/erpnext | erpnext/accounts/report/gross_profit/gross_profit.py | Python | gpl-3.0 | 14,572 | 0.024774 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, scrub
from erpnext.stock.utils import get_incoming_rate
from erpnext.controllers.queries import get_match_cond
from ... | y", "base_rate", "buying_rate", "base_amount", "buying_amount",
"gross_profit", "gross_profit_percent"],
"customer_group": ["customer_group", "qty", "base_rate", "buying_rate", "base_amount", "buying_amount",
"gross_profit", "gross_profit_percent"],
"sales_person": ["sales_person", "allocated_amount", "qty", ... | "base_amount", "buying_amount", "gross_profit", "gross_profit_percent"],
"territory": ["territory", "base_amount", "buying_amount", "gross_profit", "gross_profit_percent"]
})
columns = get_columns(group_wise_columns, filters)
for src in gross_profit_data.grouped_data:
row = []
for col in group_wise_columns.... |
Sorsly/subtle | google-cloud-sdk/platform/ext-runtime/go/test/runtime_test.py | Python | mit | 4,874 | 0.000616 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | configs(appinfo=config,
deploy=True))
if __name__ == '__main__':
unittest. | main()
|
M4rtinK/modrana | core/fix.py | Python | gpl-3.0 | 2,174 | 0.00368 | # -*- coding: utf-8 -*-
# A fix encapsulating class, based on the AGTL Fix class
from datetime import datetime
class Fix():
BEARING_HOLD_EPD = 90 # arbitrary, yet non-random value
last_bearing = 0
# tracking the minimum difference between a received fix time and
# our current internal time.
min_ti... | mode=0,
error=0,
error_bearing=0,
horizontal_accuracy=None,
vertical_accuracy=None, # in meters
speed_accuracy=None, # in meters/sec
climb_accuracy=None, # in meters/sec
bearing_accuracy=None, # in... | time_accuracy=None, # in seconds
gps_time=None,
timestamp=None):
self.position = position
# debug - Brno
# self.position = 49.2, 16.616667
self.altitude = altitude
self.bearing = bearing
self.speed = speed
self.climb = climb... |
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/nltk/draw/dispersion.py | Python | gpl-2.0 | 1,744 | 0.005161 | # Natural Language Toolkit: Dispersion Plots
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <[email protected]>
# URL: <http://nltk.org/>
# For license inf | ormation, see LICENSE.TXT
"""
A utility for displaying lexical dispersion.
"""
def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"):
"""
Generate a lexical dispersion plot.
:param text: The source text
:type text: list(str) or enum(str)
:param words: The target wor... | import pylab
except ImportError:
raise ValueError('The plot function requires matplotlib to be installed.'
'See http://matplotlib.org/')
text = list(text)
words.reverse()
if ignore_case:
words_to_comp = list(map(str.lower, words))
text_to_comp = list(map(s... |
ZucchiniZe/nightcrawler | nightcrawler/urls.py | Python | mit | 992 | 0 | """nightcrawler URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en | /1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Includ... | to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'', include('listing.urls', namespace='listing')),
url(r'', include('extras.urls', namespace='extras')),
url(r'^accounts/', include('allauth.urls')),
... |
Yarichi/Proyecto-DASI | Malmo/Python_Examples/animation_test.py | Python | gpl-2.0 | 8,932 | 0.005374 | # ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# 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 Softw... | x2="20" y2="1" z2="20" | type="obsidian"/>
</DrawingDecorator>
</AnimationDecorator>
<AnimationDecorator>
<Parametric seed="random">
<x>15*sin(t/20.0)</x>
<y>227-(t/120.0)</y>
<z>15*cos(t/20.0)</z>
</Parametric... |
JonathonReinhart/pykvm | pykvm/kvmstructs.py | Python | mit | 9,642 | 0.002593 | # pykvm
# https://github.com/JonathonReinhart/pykvm
# (C) 2015 Jonathon Reinhart
import ctypes
from ctypes import Structure, Union, c_uint8, c_uint16, c_uint32, c_uint64
class kvm_regs(Structure):
_fields_ = [
('rax', c_uint64),
('rbx', c_uint64),
('rcx', c_uint64),... | ' RSI: 0x{:016X}'.format(self.rsi),
' RDI: 0x{:016X}'.format(self.rdi),
| ' RSP: 0x{:016X}'.format(self.rsp),
' RBP: 0x{:016X}'.format(self.rbp),
' R8: 0x{:016X}'.format(self.r8),
' R9: 0x{:016X}'.format(self.r9),
' R10: 0x{:016X}'.format(self.r10),
' R11: 0x{:016X}'.format(self.r11),
' ... |
mark-in/securedrop-app-code | tests/functional/source_navigation_steps.py | Python | agpl-3.0 | 2,626 | 0.000762 | import tempfile
class SourceNavigationSteps():
def _source_visits_source_homepage(self):
self.driver.get(self.source_location)
self.assertEqual("SecureDrop | Protecting Journalists and Sources",
self.driver.title)
def _source_chooses_to_submit_documents(self):
... | 'logout').click()
notification = self.driver.find_element_by_css_selector('p.no | tification')
self.assertIn('Thank you for logging out.', notification.text)
|
ronkitay/Rons-Tutorials | Python/BasicTutorials/command_line_arguments.py | Python | mit | 1,520 | 0.003947 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import io
def get_file_length(file_to_check):
return get_file_length_with_os_stats(file_to_check)
# return get_file_length_with_seek_and_tell(file_to_check)
def get_file_length_with_seek_and_tell(file_to_check):
fi | le_to_check.seek(0, io.SEEK_END)
file_size = file_to_check.tell()
file_to_check.seek(0, io.SEEK_SET)
return file_size
def get_file_length_with_os_stats(file_to_check):
return os.stat(file_to_check.name).st_size
def validate_is_file(file_name):
if os.path.isdir( | file_name):
print ("Path {} is a directory, expected a file!".format(file_name))
exit(2)
if __name__ == '__main__':
if len(sys.argv) != 3:
print ("Expected <source path> <targer path> but got {} arguments instead.".format(len(sys.argv) - 1))
exit(1)
print (sys.platform)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.