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 |
|---|---|---|---|---|---|---|---|---|
sinotradition/sinoera | sinoera/ganzhi/guimao33.py | Python | apache-2.0 | 231 | 0.031111 | #!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@contact: sinotradition@gmail.com
@copyright: License according to the project li | cense.
'''
NAME='guimao33'
SPELL='guǐmǎo'
CN='癸卯'
SEQ='40'
if __name__=='__main__':
pass | |
lexotero/python-redsys | redsys/__init__.py | Python | mit | 68 | 0 | from .Com | merce import Commerc | e
from .Transaction import Transaction
|
frc1418/2015-robot | robot/common/distance_sensors.py | Python | apache-2.0 | 1,861 | 0.014508 | import wpilib
import math
class SharpIR2Y0A02:
'''
Sharp IR sensor GP2Y0A02YK0F
Long distance sensor: 20cm to 150cm
Output is in centimeters
Distance can be calculated using 62.28*x ^ -1.092
'''
def __init__(self,num):
self.distance = ... | t
return max(min(d, 145.0), 22.5)
def getVoltage(self):
return self.distance.getVoltage()
class SharpIRGP2Y0A41SK0F:
'''
| Sharp IR sensor GP2Y0A41SK0F
Short distance sensor: 4cm to 40cm
Output is in centimeters=
'''
#short Distance
def __init__(self,num):
self.distance = wpilib.AnalogInput(num)
def getDistance(self):
'''Returns distance in centimeters'''
... |
SymbiFlow/pycapnp | buildutils/detect.py | Python | bsd-2-clause | 4,766 | 0.000629 | """Detect zmq version"""
#
# Copyright (C) PyZMQ Developers
#
# This file is part of pyzmq, copied and adapted from h5py.
# h5py source used under the New BSD license
#
# h5py: <http://code.google.com/p/h5py/>
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, ... | t tempfile
from .misc import get_compiler, get_output_error
from .patch import patch_lib_paths
pjoin = os.path.join
#
# Utility functions (adapted from h5py: http://h5py.googlecode.com)
#
def test_compilation(cfile, com | piler=None, **compiler_attrs):
"""Test simple compilation with given settings"""
cc = get_compiler(compiler, **compiler_attrs)
efile, _ = os.path.splitext(cfile)
cpreargs = lpreargs = []
if sys.platform == 'darwin':
# use appropriate arch for compiler
if platform.architecture()[0] ... |
incredible-vision/show-and-tell | data_loader.py | Python | mit | 3,497 | 0.003432 | import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import os
import json
import pickle
import argparse
from PIL import Image
import numpy as np
from utils import Vocabulary
class CocoDataset(data.Dataset):
def __init__(self, root, anns, vocab, mode='train',transform=None):
... | b_path,
mode=mode,
transform=transform)
data_loader = torch.utils.data.DataLoader(dataset= | coco,
batch_size=opt.batch_size,
shuffle=shuffle,
num_workers=num_workers,
collate_fn=collate_fn)
return data_loader
if __name__ =... |
norayr/unisubs | apps/auth/migrations/0032_remove_thumb_options.py | Python | agpl-3.0 | 21,604 | 0.008193 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
'accountlinker.thirdpartyaccount': {
... | ateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
| 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
... |
johan--/Geotrek | geotrek/common/tests/test_parsers.py | Python | bsd-2-clause | 5,465 | 0.004762 | # -*- encoding: utf-8 -*-
import mock
import os
from shutil import rmtree
from tempfile import mkdtemp
from django.test import TestCase
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test.utils import override_settings
... | t = Attachment.objects.get()
self.assertEqual(attachment.content_object, organism)
self.assertEqual(attachment.attachment_file.name, 'paperclip/common_organism/{pk}/titi.png'.format(pk=organism.pk))
self.assertEqual(attachment.filetype, self.filetype)
@mock.patch('requests.get')
| def test_attachment_not_updated(self, mocked):
mocked.return_value.status_code = 200
mocked.return_value.content = ''
filename = os.path.join(os.path.dirname(__file__), 'data', 'organism.xls')
call_command('import', 'geotrek.common.tests.test_parsers.AttachmentParser', filename, verbos... |
bskari/sparkfun-avc | main.py | Python | mit | 13,115 | 0.001067 | """Main command module that starts the different threads."""
from ws4py.server.cherrypyserver import WebSocketPlugin
from ws4py.server.cherrypyserver import WebSocketTool
import argparse
import cherrypy
import datetime
import logging
import os
import serial
import signal
import subprocess
import sys
import threading
im... | NEUTRAL_US
)
)
time.sleep(0.1)
blaster.write(
'{pin}={steering}\n'.format(
pin=STEERING_GPIO_PIN,
steering=STEERING_NEUTRAL_US
)
)
time.sleep(0.1)
except IOError:
... | for thread in THREADS:
thread.kill()
thread.join()
# Some threads should still be active
expected = set(('MainThread', '_TimeoutMonitor'))
actives = set((thread.name for thread in threading.enumerate()))
if not (actives <= expected):
print('Trying to exit while {} threads are ... |
stefco/dotfiles | winscripts/plexmovie.py | Python | mit | 4,386 | 0.003648 | "Add a movie to Plex."
import sys
from pathlib import Path
from argparse import ArgumentParser
from tkinter import filedialog, messagebox, simpledialog, Tk, Frame, Label
from tkinter.ttk import Combobox, Button
class FeaturettePicker:
FEATURETTES = {
"Behind the Scenes": "behindthescenes",
"Delet... | initialvalue=fsrc.name[:-len(fsrc.suffix)], parent=tkr)
if name is None:
return
fext = simpledialog.askstring("Extension",
f"File extension for {fsrc.name}:",
... | ker.FEATURETTES[ftype]}{fext}"
files.append((fsrc, fdst))
msg = ("\n\nFeatures:\n\n"+"\n".join(f"{s} -> {d.name}" for (s, d) in files)+"\n\n") if files else ""
if not messagebox.askokcancel("Proceed?",
f"Ready to link {src.name} -> {out}. {msg}Procee... |
clu8/RainbowTable | crack.py | Python | mit | 2,202 | 0.024069 | #!/usr/bin/env python3
import rainbow
import hashlib
import string
import time
import random
"""SHA-256 hash function
Precondition: Input plaintext as string
Postcondition: Returns hash as string
"""
def sha256(plaintext):
return hashlib.sha256(bytes(plaintext, 'utf-8')).hexdigest()
"""Returns a reduction function... | erage time per hash (including failures): {2} secs.""" \
.format(numSuccess, numTests, (time.time() - start) / numTests))
table = rainbow.RainbowTable(sha256, reduce_lower(4 | ), gen_lower(4)) |
xe1gyq/GiekIs | examples/au.py | Python | apache-2.0 | 1,636 | 0.011002 | #!/usr/bin/env python3
# NOTE: this example requires PyAudio because it uses the Microphone class
import speech_recogniti | on as sr
# this is called from the background thread
def callback(recognizer, audio):
# received audio data, now we'll recognize it using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
| # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
# print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio))
r.recognize_google(audio, key="")
except sr.UnknownValueEr... |
BaluDontu/docker-volume-vsphere | esx_service/utils/auth.py | Python | apache-2.0 | 13,215 | 0.003405 | # Copyright 2016 VMware, 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... | ue
return vol_size_in_MB + total_storage_used <= usage_quota
else:
# no privileges
return True
def check_privileges_for_command(cmd, opts, tenant_uuid, datastore, privileges):
"""
Check whether the (tenant | _uuid, datastore) has the privileges to run
the given command.
"""
result = None
cmd_need_mount_privilege = [CMD_ATTACH, CMD_DETACH]
if cmd in cmd_need_mount_privilege:
if not has_privilege(privileges, auth_data_const.COL_MOUNT_VOLUME):
result = "No mount privilege"
if ... |
google-code/abc2esac | abcesac/tests/music.py | Python | gpl-3.0 | 4,909 | 0.017315 | import unittest
from fractions import Fraction as F
from abcesac.music import *
class KeyTestCase(unittest.TestCase):
def test_get_notes(self):
got = Key('C').get_notes()
want = ['C','D','E','F','G','A','B']
self.assertEquals(got, want)
got = Key('D').get_notes()
want = [... | ength, F(3,8))
tuplet = Tuplet(7, 3)
tuplet.add_note(Note(name='C', length=F(1,16)))
tuplet.add_note(Note(name='C', length=F(1,16)))
tuplet.add_note(Note(name='C', length=F(1,16)))
tuplet.add_note(Note(name='C', length=F(1,16)))
tuplet.add_note(Note(name='C', l | ength=F(1,16)))
tuplet.add_note(Note(name='C', length=F(1,16)))
tuplet.add_note(Note(name='C', length=F(1,16)))
self.assertEquals(tuplet.length, F(3,16))
def test_modes(self):
got = Key('C').mode_scale('major')
want = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
self.assertEq... |
tjduigna/exa | exa/core/container.py | Python | apache-2.0 | 24,987 | 0.002441 | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2019, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
"""
Container
########################
The :class:`~exa.core.container.Container` class is the primary object for
data processing, analysis, and visualization. In brief, containers a... | column of the parent. Note that this relationship
| cdf = self[child]
cin = cdf.index.name
cols = [col for col in kwargs[parent] if cin == col or (cin == col[:-1] and col[-1].isdigit())]
index = kwargs[parent][cols].stack().astype(np.int64).values
kwargs[child] = cdf[cdf.index.isin(i... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/aio/operations/_service_endpoint_policy_definitions_operations.py | Python | mit | 24,059 | 0.005362 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | efinition_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_versio... | # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'),
'serviceEndpointPolicy... |
stencila/hub | worker/jobs/pull/http_test.py | Python | apache-2.0 | 1,623 | 0.000616 | from contextlib import ContextDecorator
from unittest import mock
import httpx
import pytest
from util.working_directory import working_directory
from .http import pull_http
class MockedHttpxStreamResponse(ContextDecorator):
"""
VCR does not like recording HTTPX stream requests so mock it.
"""
def... | lf, attr):
return getattr(self.respon | se, attr)
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, *args, **kwargs):
return self
@pytest.mark.vcr
@mock.patch("httpx.stream", MockedHttpxStreamResponse)
def test_extension_from_mimetype(tempdir):
with working_directory(tempdir.path):
files = pull_http(... |
jtraver/dev | python3/graphics/modulefinder1.py | Python | mit | 416 | 0 | #!/usr/bin/env python3
# https://docs.python.org/3/library/modulefinder.html
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script('graph1.py')
print('Loaded modules | :')
for name, mod in finder.modules.items():
print('%s: ' % name, end='')
print(','.join(list(mod.globalnames.keys())[:3]))
print('-'*5 | 0)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))
|
akretion/bank-statement-reconcile | __unported__/statement_voucher_killer/voucher.py | Python | agpl-3.0 | 6,659 | 0.00015 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com)
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera... |
if context is None:
context = {}
statement_id = context.get('statement_id', False)
if not statement_id:
return {'type': 'ir.actions.act_window_close'}
data = self.read(cr, uid, ids, context=context)[0]
line_ids = data['line_ids']
if not line_ids:
... | eturn {'type': 'ir.actions.act_window_close'}
line_obj = self.pool['account.move.line']
statement_obj = self.pool['account.bank.statement']
statement_line_obj = self.pool['account.bank.statement.line']
currency_obj = self.pool['res.currency']
line_date = time.strftime(DEFAULT_SER... |
zenieldanaku/DyDCreature_Editor | azoe/widgets/basewidget.py | Python | mit | 2,314 | 0 | from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... | 2)
draw.line(imagen, color_sombra, (w - 2, h - 2), (w - 2, 0), 2)
draw.lines(imagen, color_luz, 0, [(w - 2, 0), (0, 0), (0, h - 4)], 2)
return imagen
def reubicar_en_ventana(self, dx=0, dy=0):
self.rect.move_ip(dx, dy)
self.x += dx
self.y += dy
self... | repr__(self):
return self.nombre
def is_visible(self):
return self._visible
|
rochacbruno/dynaconf | example/django_pure/polls/views.py | Python | mit | 125 | 0 | from django.conf import settings
from django.http import HttpResponse
def index(requ | est):
return Htt | pResponse("Hello")
|
suutari/shoop | shuup_tests/browser/admin/test_refunds.py | Python | agpl-3.0 | 4,879 | 0.003689 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import decimal
import os
import time
import pytest
from django.cor... | "0.00"))))
assert len(browser.find_by_css("#id_ | form-0-line_number option")) == 12 # blank + arbitrary amount + num lines
click_element(browser, "#select2-id_form-0-line_number-container")
wait_until_appeared(browser, "input.select2-search__field")
browser.execute_script('$($(".select2-results__option")[1]).trigger({type: "mouseup"})') # select arbitrary... |
datapythonista/datapythonista.github.io | docs/cart_talk.py | Python | apache-2.0 | 5,718 | 0.003498 | """Source code used for the talk:
http://www.slideshare.net/MarcGarcia11/cart-not-only-classification-and-regression-trees
"""
# data
import pandas as pd
data = {'age': [38, 49, 27, 19, 54, 29, 19, 42, 34, 64,
19, 62, 27, 77, 55, 41, 56, 32, 59, 35],
'distance': [6169.98, 7598.87, 3276.07, 15... | se, | True, True, True, False, True, True, True, True, False]}
df = pd.DataFrame(data)
# base_plot
from bokeh.plotting import figure, show
def base_plot(df):
p = figure(title='Event attendance',
plot_width=900,
plot_height=400)
p.xaxis.axis_label = 'Distance'
p.yaxis.axis_label... |
nullishzero/Portage | pym/_emerge/JobStatusDisplay.py | Python | gpl-2.0 | 7,763 | 0.031302 | # Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
from __future__ import unicode_literals
import formatter
import io
import sys
import time
import portage
from portage import os
from portage import _encodings
from portage import _unicode_encode
from portage.ou... | exported, include it
# in the xterm title, just like emergelog() does.
# See bug #390699.
title_str = " ".join(plain_output.split())
hostname = os.environ.get("HOSTNAME")
if hostname is not None: |
title_str = "%s: %s" % (hostname, title_str)
xtermTitle(title_str)
|
lehmacdj/.dotfiles | bin/bitrate.py | Python | gpl-3.0 | 314 | 0 | #!/usr/bin/env python3
from mutagen.mp3 import MP3
import sys
if len(sys.argv) < 2:
print('error: didn\'t pass enough arguments')
print('us | age: ./bitrate.py < | file name>')
print('usage: find the bitrate of an mp3 file')
exit(1)
f = MP3(sys.argv[1])
print('bitrate: %s' % (f.info.bitrate / 1000))
|
joshsmith2/superlists | lists/migrations/0001_initial.py | Python | gpl-2.0 | 492 | 0.002033 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(seriali... | ary_key=True, auto_ | created=True, verbose_name='ID')),
],
options={
},
bases=(models.Model,),
),
]
|
scottsilverlabs/raspberrystem | rstem/projects/led_matrix_games/aspirin.py | Python | apache-2.0 | 9,366 | 0.009075 | from rstem import led_matrix, accel
import RPi.GPIO as GPIO
import random
import time
import sys
# notify of progress
print("P50")
sys.stdout.flush()
# set up led matrix
#led_matrix.init_grid(2,2)
led_matrix.init_matrices([(0,8),(8,8),(8,0),(0,0)])
# set up accelometer
accel.init(1)
# notify of progress
print("P60"... | to bounce back
if self.direction == Direction.LEFT and self.position[0] == 0:
self.direction = Direction.RIGHT
elif self.direction == Direction.RIGHT and self.p | osition[0] == led_matrix.width()-1:
self.direction = Direction.LEFT
elif self.direction == Direction.DOWN and self.position[1] == 0:
self.direction = Direction.UP
elif self.direction == Direction.UP and self.position[1] == led_matrix.height()-1:
self.direction = Direc... |
carlitos26/RESTful-Web-service | browser-version/app/modules.py | Python | gpl-3.0 | 1,874 | 0.012807 | import sqlite3 as sql
from flask.json import jsonify
from flask import current_app
def total_entries():
with sql.connect("names.db") as con:
cur = con.cursor()
| entries = cur.execute("SELECT count(*) FROM names").fetchone()
con.commit()
return '{}\n'.format('{}\n'.format(entries)[1:-3])
def select_entries_by_name(name):
with sql.connect("names.db") as con:
cur = con.cursor()
query = cur.execute("SELECT id, year, gender, count FROM names W... | |
airbnb/airflow | tests/dags/test_task_view_type_check.py | Python | apache-2.0 | 1,768 | 0 | #
# 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... | this file except in compliance
# with the License. You ma | y obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for... |
ooovector/qtlab_replacement | single_shot_readout.py | Python | gpl-3.0 | 8,239 | 0.028766 | from . import data_reduce
import numpy as np
from . import readout_classifier
class single_shot_readout:
"""
Single shot readout class
Args:
adc (Instrument): a device that measures a complex vector for each readout trigger (an ADC)
prepare_seqs (list of pulses.sequence): a dict of sequences of control pulses.... | ))/self.adc.get_clock(), 's')]
points['threshold'] = []
return points
def get_dtype(self):
dtypes = {}
scores = {score_name:float for score_name in readout_classifier.readout_classifier_scores}
dtypes.update(scores)
if self.measure_avg_samples:
avg_samples = {'avg_sample'+str(_class):self.adc.get_dty... | lf.adc.get_dtype()[self.adc_measurement_name] for _class in self.readout_classifier.class_list}
dtypes.update(avg_samples)
dtypes.update(features)
if self.measure_hists:
dtypes['hists'] = float
dtypes['proba_points'] = float
if self.measure_feature_w_threshold:
dtypes['feature'] = np.complex
dtype... |
jeffhammond/spaghetty | branches/old/python/archive/build_executables_basic.py | Python | bsd-2-clause | 11,373 | 0.006419 | #!/usr/bin/python
import fileinput
import string
import sys
import os
ar = 'ar'
fortran_compiler = 'ftn'
fortran_opt_flags = '-O3'
fortran_link_flags = '-O1'
c_compiler = 'cc'
c_opt_flags = '-O3'
src_dir = './src/'
obj_dir = './obj/'
exe_dir = './exe/'
lib_name = 'tce_sort_f77_basic.a'
count = '100'
rank = '30'... | '+A+B+C+D
print driver_name
source_name = driver_name+'_driver.F'
lst_name = driver_name+'_driver.lst'
source_file = open(source_name,'w')
source_fi | le.write(' PROGRAM ARRAYTEST\n')
source_file.write('#include "mpif.h"\n')
source_file.write(' REAL*8 before('+ranks[0]+','+ranks[0]+','+ranks[0]+','+ranks[0]+')\n')
source_file.write(' REAL*8 after_jeff('+sizechar+')\n')
source_file.write(' REAL*8 after_hirata('+sizechar+')\n... |
ahMarrone/solar_radiation_model | tests/performance_test.py | Python | mit | 1,278 | 0 | import unittest
from models import heliosat
import numpy as np
from netcdf import netcdf as nc
from datetime import datetime
import os
import glob
class TestPerformance(unittest.TestCase):
def setUp(self):
# os.system('rm -rf static.nc temporal_cache products')
os.system('rm -rf temporal_cache pr... | print "Scaling total time to %.2f hours." % estimated
print "Efficiency achieved: %.2 | f%%" % (3.5 / estimated * 100.)
if __name__ == '__main__':
unittest.run()
|
the-blue-alliance/the-blue-alliance | src/backend/common/sitevars/apistatus.py | Python | mit | 1,216 | 0 | import datetime
from typing import | Optional, TypedDict
from backend.common.sitevars.sitevar import Sitevar
class WebConfig(TypedDict):
travis_job: str
tbaClient_endpoints_sha: str
current_commit: str
deploy_time: str
endpoints_sha: str
commit_time: str
class AndroidConfig(TypedDict):
min_app_version: int
latest_app_... | p_version: int
latest_app_version: int
class ContentType(TypedDict):
current_season: int
max_season: int
web: Optional[WebConfig]
android: Optional[AndroidConfig]
ios: Optional[IOSConfig]
class ApiStatus(Sitevar[ContentType]):
@staticmethod
def key() -> str:
return "apistatus... |
jackfirth/pyramda | pyramda/relation/max_test.py | Python | mit | 127 | 0 | from .max import max
from pyramda.private.asserts import assert_equal
def max_test():
a | ssert_equal(ma | x([1, 3, 4, 2]), 4)
|
srmagura/potential | scripts/optimize_basis.py | Python | gpl-3.0 | 1,662 | 0.006619 | """
Script for selecting a good number of basis functions.
Too many or too few basis functions will introduce numerical error.
True solution must be known.
Run the program several times, varying the value of the -N option.
There may be a way to improve on this brute force method.
"""
# To allow __main__ in subdirecto... | y_print(t):
print('n_circle={} n_radius={} error={}'.format(*t))
def worker(t):
options['n_circle'] = t[0]
options['n_radius'] = t[1]
my_solver = ps.ps.PizzaSolver(options)
result = my_solver.run()
t = (t[0], t[1], result.error)
my_print(t)
return t
all_options = []
# Tweak the... | as needed
for n_circle in range(30, 100, 5):
for n_radius in range(17, n_circle, 4):
all_options.append((n_circle, n_radius))
with Pool(4) as p:
results = p.map(worker, all_options)
min_error = float('inf')
for t in results:
if t[2] < min_error:
min_error = t[2]
min_t = t
print(... |
ljwolf/spvcm | spvcm/svc/__init__.py | Python | mit | 23 | 0 | fro | m .model import SV | C
|
vipul-tm/DAG | dags-ttpl/sync.py | Python | bsd-3-clause | 19,607 | 0.033304 | import os
import socket
from airflow import DAG
from airflow.contrib.hooks import SSHHook
from airflow.operators import PythonOperator
from airflow.operators import BashOperator
from airflow.operators import BranchPythonOperator
from airflow.hooks.mysql_hook import MySqlHook
from airflow.hooks import RedisHook
from air... | e': device.get('warning') or device.get('dtype_ds_warning')}]})
else:
rules[name].update({"Severity2":["warning",{'name': str(name)+"_warning", 'operator': 'greater_than', 'value': ''}]})
if device_type not in ping_rule_dict:
if device.get('ping_pl_critical') and device.get('ping_pl_warning') and device.get('... | et('ping_rta_warning'):
ping_rule_dict[device_type] = {
'ping_pl_critical' : device.get('ping_pl_critical'),
'ping_pl_warning': device.get('ping_pl_warning') ,
'ping_rta_critical': device.get('ping_rta_critical'),
'ping_rta_warning': device.get('ping_rta_warning')
}
for device_type in ping... |
samabhi/pstHealth | venv/bin/createfontdatachunk.py | Python | mit | 600 | 0 | #!/Users/abhisheksamdaria/GitHub/pstHealth/venv/bin/python2.7
fro | m __future__ import print_function
import base64
import os
import sys
if __name__ == "__main__":
# create font data chunk for embedding
font = "Tests/images/courB08"
print(" f._load_pilfont_data(")
print(" # %s" % os.path.basename(font))
print(" BytesIO(base64.decodestring(b'''")... | ase64.decodestring(b'''")
base64.encode(open(font + ".pbm", "rb"), sys.stdout)
print("'''))))")
# End of file
|
e-Luminate/eluminate_web | eluminate_web/apps/events/migrations/0006_auto__add_field_event_photo.py | Python | gpl-3.0 | 7,343 | 0.007899 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.photo'
db.add_column('events_event', 'photo',
self.gf('django.db... | _name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30'... | "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default... |
hwangsyin/cbrc-devteam-blog | service/service.py | Python | apache-2.0 | 5,715 | 0.006211 | import settings
import mysql.connector
from domain.domain import Article
from domain.domain import Project
from domain.domain import User
from domain.domain import Tag
import service.database as db
# 文章管理
class ArticleService:
# 查询最近发表的文章
def query_most_published_article(self):
conn = d... | return None
_tag_id = None
try:
_tag_id = int(tag_id)
except ValueError:
return None
sql = "".join(["select a.id as id,a.author_id as author_id,u.name as author_name",
",a.title as title,a.create_time as create_time,a.publish_time as publish... | on a.author_id=u.id",
" where a.publish_time is not null and a.id in (select article_id from article_tag where tag_id=%(tag_id)s)"])
conn = db.get_connection()
cursor = conn.cursor()
cursor.execute(sql, {"tag_id": _tag_id})
articles = None
for (id, author_id, a... |
mpetyx/palmdrop | venv/lib/python2.7/site-packages/cms/tests/plugins.py | Python | apache-2.0 | 46,414 | 0.001982 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import datetime
from cms.api import create_page, publish_page, add_plugin
from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered
from cms.models import Page, Placeholder
from cms.models.pluginmodel import CMSPlugin, PluginModelBase
from cms... | ):
def _create_text_plugin_on_page(self, page):
plugin_data = | {
'plugin_type': "TextPlugin",
'language': settings.LANGUAGES[0][0],
'placeholder': page.placeholders.get(slot="body").pk,
}
response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data)
self.assertEquals(response.status_code, 200)
created_plugin_id = ... |
orbitfp7/nova | nova/tests/unit/scheduler/filters/test_numa_topology_filters.py | Python | apache-2.0 | 7,379 | 0.000678 | # 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
# d... | are.VirtNUMALimitTopology.from_json(
host.limits['numa_topology'])
self.assertEqual(limits_topology.cells[0].cpu_limit, 42)
self.assertEqual(limits_topology.cells[1].cpu_limit, 42)
self.assertEqual(limits_topology.cells[0].memory_limit, | 665)
self.assertEqual(limits_topology.cells[1].memory_limit, 665)
|
inclement/plyer | setup.py | Python | mit | 1,374 | 0 | #!/usr/bin/env python
from os.path import dirname, join
import plyer
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
curdir = dirname(__file__)
packages = [
'plyer',
'plyer.platforms',
'plyer.platforms.linux',
'plyer.platforms.android',
'plyer.platfo... | tatus :: 4 - Beta',
'Intended | Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programmin... |
tomato42/fsresck | fsresck/nbd/request.py | Python | gpl-2.0 | 3,965 | 0 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Description: File system resilience testing application
# Author: Hubert Kario <hubert@kario.pl>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Copyright (c) 2015 Hubert Kario. All rights reserved.
#
# This ... | gth)
return NBDRequest(req_type, handle, data_from, data_length, payload)
def send(self, request):
"""Send a single request through socket."""
data = struct.pack(self.request_fmt,
Magic.NBD_REQUEST_MAGIC,
request.req_type,
| request.handle,
request.data_from,
request.data_length)
if request.req_type == RequestType.NBD_CMD_WRITE:
data = data + request.data
self.sock.sendall(data)
|
metomi/rose | metomi/rosie/svn_pre_commit.py | Python | gpl-3.0 | 13,444 | 0.000149 | #!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Copyright (C) British Crown (Met Office) & Contributors.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of... | c:
err = InfoFileError(InfoFileError.NO_INFO, exc.stderr)
if err:
bad_changes.append(err)
txn_ | info_map[sid] = err
continue
# Suite must have an owner
txn_owner, txn_access_list = self._get_access_info(
txn_info_map[sid]
)
if not txn_owner:
bad_changes.append(
... |
redhat-imaging/imagefactory | imagefactory_plugins/Rackspace/__init__.py | Python | apache-2.0 | 668 | 0 | # encoding: utf-8
# Copyright 2012 Red Hat, Inc.
#
# Licensed under the Ap | ache 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 ... | tions under the License.
from .Rackspace import Rackspace as delegate_class
|
dpdani/tBB | tBB/async_stdio.py | Python | gpl-3.0 | 1,064 | 0.00094 | # From: https://gist.github.com/nathan-hoad/8966377
import os
import asyncio
import sys
from asyncio.streams import StreamWriter, FlowControlMixin
reader, writer = None, None
@asyncio. | coroutine
def stdio(loop=None):
if loop is None:
loop = asyncio.get_event_loop()
| reader = asyncio.StreamReader()
reader_protocol = asyncio.StreamReaderProtocol(reader)
writer_transport, writer_protocol = yield from loop.connect_write_pipe(FlowControlMixin, os.fdopen(0, 'wb'))
writer = StreamWriter(writer_transport, writer_protocol, None, loop)
yield from loop.connect_read_pipe... |
ingenieroariel/geonode | geonode/groups/forms.py | Python | gpl-3.0 | 5,314 | 0.000188 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | for ui in value.split(","):
ui = ui.strip()
try:
validate_email(ui)
try:
invitees.append(get_user_model().objects.get(email=ui))
except get_user_model().DoesNotExist:
invitees.append(ui)
except V... | errors.append(ui)
if errors:
message = (
"The following are not valid email addresses or "
"usernames: %s; no invitations sent" %
", ".join(errors))
raise forms.ValidationError(message)
return invitees
|
sim0629/irc | irc/server.py | Python | lgpl-2.1 | 17,734 | 0.002425 | # -*- coding: utf-8 -*-
"""
irc/server.py
Copyright © 2009 Ferry Boender
Copyright © 2012 Jason R. Coombs
This server has basic support for:
* Connecting
* Channels
* Nicknames
* Public/private messages
It is MISSING support for notably:
* Server linking
* Modes (user and channel)
* Proper error reporting
* Basic... | to user
return
if ni | ck in self.server.clients:
# Someone else is using the nick
raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick))
if not self.nick:
# New connection and nick is available; register and send welcome
# and MOTD.
self.nick = nick
sel... |
oyiadin/Songs-Distributor | utils.py | Python | mit | 1,548 | 0.00646 | import random
import time
import datetime
from consts import *
__all__ = ['gen_valid_id', 'gen_list_page', 'log']
def gen_valid_id(collection):
def gen_id():
| _id = ''
for i in range(4):
_id += random.choice('0123456789')
return _id
id = gen_id()
while collection.find_one({'id': id}):
id = gen_id()
return id
def gen_list_page(collection, status, page=1):
page = int(page)
left = (page - 1) * 15
right = le... | all.count() else 0
if page > max_page:
return PAGE_NOT_EXIST
elif page < 1:
return ARGS_INCORRECT
header = '===== {0}/{1} =====\n'.format(page, max_page)
selected = all[left:right]
return header + '\n'.join([
'{id} {title} ({comment})'.format(**i) for i in selected])
def ... |
corystreet/pyOdbcToTde | Static/TableauSDK-9100.15.0828.1711/tableausdk/Exceptions.py | Python | gpl-2.0 | 1,040 | 0.003846 | # - | ----------------------------------------------------------------------------
#
# This file is the copyrighted property of Tableau Software and is protected
# by registered patents and other applicable U.S. and international laws and
# regulations.
#
# Unlicensed use of the contents of this file is prohibited. Please re... | le for further details.
#
# -----------------------------------------------------------------------------
from ctypes import *
from . import Libs
class TableauException(Exception):
def __init__(self, errorCode, message):
Exception.__init__(self, message)
self.errorCode = errorCode
self.mes... |
gusDuarte/sugar | src/jarabe/model/speech.py | Python | gpl-2.0 | 7,214 | 0.000832 | # Copyright (C) 2011 One Laptop Per Child
#
# This program is f | ree software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT | ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Fra... |
LEMS/pylems | lems/api.py | Python | lgpl-3.0 | 328 | 0 | """
PyLEMS | API module.
:author: Gautham Ganapathy
:organization: LEMS (https://github.com/organizations/LEMS)
"""
from lems.model.fundamental import *
from lems.model.structure import *
from lems.model.dynamics import *
from lems.model.simulation import *
from lems.model.component import *
from lems.model.model import Mod | el
|
pmaconi/RedditGoggles | reddit-goggles.py | Python | mit | 11,792 | 0.037907 | import argparse, collections, configparser, json, math, mysql.connector as sql, praw, os, requests, sys, time
from datetime import datetime
from pprint import pprint
from mysql.connector import errorcode
from requests import HTTPError
from requests import ConnectionError
from fcntl import flock, LOCK_EX, LOCK_NB
# Pri... | nt) :
cursor = conn.cursor()
query = "REPLACE INTO comment (job_id, submission_id, comment_id, " \
"parent_id, author, body, created_utc, ups, downs) VALUES " \
"(%s, %s, %s, %s, %s, %s, %s, %s, %s) "
values = [
job_id,
submission_id,
comment.id,
comment.parent_id,
None if comment.author is None else... | tamp(comment.created_utc).strftime('%Y-%m-%d %H:%M:%S'),
comment.ups,
comment.downs
]
try :
cursor.execute(query, values)
conn.commit()
return True
except sql.Error as err :
verbose("")
verbose(">>>> Warning: Could not add Comment: " + str(err))
verbose(" Query: " + cursor.statement)
return F... |
psych0der/resumizr | resumizr/urls.py | Python | mit | 3,010 | 0.01495 | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r''... | trib.auth.views.password_reset_confirm',
{'post_reset_redirect' : '/users/password/done/'}),
url(r'^users/password/done/$', 'django.contrib.auth.views.password_reset_complete'),
url(r'^$', 'api.views.home',name='home'),
url(r'^signup/(?P<backend>[^/]+)/$', 'api.views.signup', name='signup'),
... | l(r'^email-sent/', 'api.views.validation_sent'),
url(r'^resumizr-login/(?P<backend>[^/]+)/$', 'api.views.username_login', name='username_login'),
url(r'^login/$','api.views.login', name='login'),
url(r'^logout/$','api.views.logout', name='logout'),
url(r'^app/$','api.views.app',name='app'),
ur... |
hradec/gaffer | python/GafferUI/Slider.py | Python | bsd-3-clause | 18,399 | 0.051796 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | s ) or index < 0 or in | dex >= len( self.__values ) :
raise IndexError
self.__selectedIndex = index
self._qtWidget().update()
signal = getattr( self, "_selectedIndexChangedSignal", None )
if signal is not None :
signal( self )
## May return None to indicate that no index is selected.
def getSelectedIndex( self ) :
retur... |
Fizzadar/pyinfra | tests/test_api/test_api.py | Python | mit | 2,193 | 0 | from unittest import TestCase
from paramiko import SSHException
from pyinfra.api import Config, State
from pyinfra.api.connect import connect_all
from pyinfra.api.exceptions import NoGroupError, NoHost | Error, PyinfraError
from ..paramiko_util import PatchSSHTestCase
from ..util import make_inventory
class TestInventoryApi(TestCase):
def test_inventory_creation(self):
inventory = make_inventory()
# Check length
assert len(inventory.hosts) == 2
# Get a host
host = invent... | oup data
assert inventory.get_group_data('test_group') == {
'group_data': 'hello world',
}
def test_tuple_host_group_inventory_creation(self):
inventory = make_inventory(
hosts=[
('somehost', {'some_data': 'hello'}),
],
tuple_g... |
rlrs/deep-rl | run_double.py | Python | mit | 1,928 | 0.001556 | """
Copyright 2016 Rasmus Larsen
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE.txt file for details.
"""
import sys
import time
from sacred import Experiment
from core.ALEEmulator import ALEEmulator
from dqn.Agent import Agent
from dqn.DoubleDQN import DoubleDQN
e... | / 1e6
batch_size = 32
train_start | = 5e3
train_frames = 5e6
test_freq = 5e4
test_frames = 5e3
update_freq = 4
@ex.command
def test(_config):
emu = ALEEmulator(_config)
_config['num_actions'] = emu.num_actions
net = DoubleDQN(_config)
net.load(_config['rom_name'])
agent = Agent(emu, net, _config)
agent.next(0) ... |
Hammer2900/SunflowerX | application/plugins/find_file_extensions/size.py | Python | gpl-3.0 | 2,732 | 0.00183 | import gtk
from plugin_base.find_extension import FindExtension
class SizeFindFiles(FindExtension):
"""Size extension for find files tool"""
def __init__(self, parent):
FindExtension.__init__(self, parent)
# create container
table = gtk.Table(2, 4, False)
table.set_border_wi... | changed)
| self._entry_min.connect('value-changed', self._min_value_changed)
self._entry_max.connect('activate', self._parent.find_files)
self._entry_min.connect('activate', lambda entry: self._entry_max.grab_focus())
# pack interface
table.attach(label, 0, 3, 0, 1, xoptions=gtk.FILL)
... |
naggie/dsblog | dsblog/environment.py | Python | mit | 1,659 | 0.010247 | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_d... | 'original_img_dir'])
config['database_file'] = join(config['output_dir'],config['database_f | ile'])
def makeDirs():
if not config:
raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
path = config[key]
if not isdir(path):
makedirs(path)
|
CLVsol/odoo_addons | clv_medicament_template/history/clv_medicament_template_history.py | Python | agpl-3.0 | 4,727 | 0.008462 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | lp="If unchecked, it will allow you to disable the history without removing it.",
default=True)
@api.one
def insert_clv_medicament_template_history(self, medicament_template_id, state, notes):
if self.active_history:
values = {
'medicamen... | tate': state,
'notes': notes,
}
self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values)
@api.multi
def write(self, values):
if (not 'state' in values) and (not 'date' in values):
notes = values.keys()
self.inse... |
bonno800/pynet | week9exercise9-a-b.py | Python | apache-2.0 | 275 | 0 | import mytest
pr | int '----This is func1----'
mytest.world.func1()
print '----This is func2----'
mytest.simple.func2()
print '----This is func3----'
mytest.whatever.func3()
print '----This is myobj using | MyClass----'
myobj = mytest.MyClass('nick', 'florida')
myobj.hello()
|
cirruspath/python-oauth2-middleware | pom/server/pomserver.py | Python | apache-2.0 | 7,922 | 0.012497 | # Copyright 2014 Cirruspath, 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 wri... | : 'offline'}
url = source.authorize_url + "?" + urllib.urlencode(payload)
responses[state] = { 'stage' : 'authorize',
'session' : session }
if 'redirect' in request.args:
responses[state]['redirect'] = request.args['redirect']
print "Using the %s | user redirect" % responses[state]['redirect']
return redirect(url)
#
# Fetch a new access token using a refresh token.
#
@app.route('/refresh', methods=['DELETE'])
def revoke_access_token():
refresh_token = request.args['refresh']
source = providers[request.args['source']]
payload = { 'token' : ... |
has2k1/plotnine | plotnine/tests/test_geom_ribbon_area.py | Python | gpl-2.0 | 2,328 | 0 | import numpy as np
import pandas as pd
from plotnine import (ggplot, aes, geom_area, geom_ribbon,
facet_wrap, scale_x_continuous, theme)
n = 4 # No. of ribbions in a vertical stack
m = 100 # Points
width = 2*np.pi # width of each ribbon
x = np.linspace(0, width, m)
df = pd.... | om_ribbon(aes('x+3*width', color='z'),
fill=None, size=2) +
geom_ribbon(aes('x+4*width', fill='factor(z)')) +
geom_ribbon(aes('x+5*width', size='z'),
color='black', fill=None) +
| scale_x_continuous(
breaks=[i*2*np.pi for i in range(7)],
labels=['0'] + [r'${}\pi$'.format(2*i) for i in range(1, 7)])
)
assert p + _theme == 'ribbon_aesthetics'
def test_area_aesthetics():
p = (ggplot(df, aes('x', 'ymax+2', group='factor(z)')) +
geom_area() ... |
anaran/olympia | lib/es/utils.py | Python | bsd-3-clause | 1,403 | 0 | import os
import amo.search
from .models import Reindexing
from django.core.management.base import CommandError
# shortcut functions
is_reindexing_amo = Reindexing.objects.is_reindexing_amo
flag_reindexing_amo = Reindexing.objects.flag_reindexing_amo
unflag_reindexing_amo = Reindexing.objects.unflag_reindexing_amo
g... | t_es().flush_bulk(forced=True)
def raise_if_reindex_in_progress(site):
"""Checks if the database indexation flag is on for the given site.
If it's on, and if no "FORCE_INDEXING" variable is present in the env,
raises a CommandError.
"""
already_reindexing = Reindexing.objects._is_reindexing(site)... | "variable in the environ to force it")
|
Cinemair/cinemair-server | cinemair/shows/migrations/0002_auto_20150712_2126.py | Python | mit | 430 | 0.002326 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('shows', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='show',
op | tions={'verbose_name_plural': 'shows', 'ordering': ['d | atetime', 'cinema', 'id'], 'verbose_name': 'show'},
),
]
|
alehaa/james | jamesci/status.py | Python | gpl-3.0 | 1,897 | 0.000527 | # This file is part of James CI.
#
# James CI 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.
#
# James CI is distributed in the hope t... | or FITNESS FOR
# | A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with James CI. If not, see <http://www.gnu.org/licenses/>.
#
#
# Copyright (C)
# 2017 Alexander Haase <ahaase@alexhaase.de>
#
import enum
@enum.u... |
nanditav/15712-TensorFlow | tensorflow/contrib/learn/python/learn/estimators/linear.py | Python | apache-2.0 | 31,382 | 0.004716 | # 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
#
# Unless required by applica... | oned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas,
min_slice_size=64 << 20)
with variable_scope.variable_scope(
parent_scope, values=features.values(), partitioner=partitioner) as scope:
if joint_weights:
logits, _, _ = (
layers.joint_weighted_sum_from_... | s=feature_columns,
num_outputs=head.logits_dimension,
weight_collections=[parent_scope],
scope=scope))
else:
logits, _, _ = (
layers.weighted_sum_from_feature_columns(
columns_to_tensors=features,
feature_columns=feature_columns,
... |
i3visio/osrframework | osrframework/wrappers/papaly.py | Python | agpl-3.0 | 3,867 | 0.004397 | ################################################################################
#
# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Softwa... | _author__ = "Felix Brezo, Yaiza Rubio <cont | acto@i3visio.com>"
__version__ = "2.0"
from osrframework.utils.platforms import Platform
class Papaly(Platform):
"""A <Platform> object for Papaly."""
def __init__(self):
self.platformName = "Papaly"
self.tags = ["social"]
########################
# Defining valid modes #
... |
silveregg/moto | moto/dynamodb/models.py | Python | apache-2.0 | 9,875 | 0.00081 | from __future__ import unicode_literals
from collections import defaultdict
import datetime
import json
from moto.compat import OrderedDict
from moto.core import BaseBackend
from moto.core.utils import unix_time
from .comparisons import get_comparison_func
class DynamoJsonEncoder(json.JSONEncoder):
def default(s... | don't have the attribute
continue
else:
# No attribute found and comparison is no NULL. This item fails
| passes_all_conditions = False
break
if passes_all_conditions:
results.append(result)
return results, scanned_count, last_page
def delete_item(self, hash_key, range_key):
try:
if range_key:
return self.i... |
jordanemedlock/psychtruths | temboo/core/Library/Genability/TariffData/GetTariff.py | Python | apache-2.0 | 4,018 | 0.004978 | # -*- coding: utf-8 -*-
###############################################################################
#
# GetTariff
# Returns an individual Tariff object with a given id.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may no... | """
Set the value of the AppKey input for this Choreo. ((required, string) The App Key provided by Genability.)
"""
super(GetTariffInputSet, self)._set_input('AppKey', value)
def set_MasterTariffID(self, value):
"""
Set the value of the MasterTariffID input for this Choreo... | super(GetTariffInputSet, self)._set_input('MasterTariffID', value)
def set_PopulateProperties(self, value):
"""
Set the value of the PopulateProperties input for this Choreo. ((optional, boolean) Set to "true" to populate the properties for the returned Tariffs.)
"""
super(GetTariff... |
esthermm/odoo-addons | procurement_service_project/models/sale_order.py | Python | agpl-3.0 | 1,663 | 0 | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def action_button_confirm(self):
procurement_obj = self.env... | lass SaleOrderLine(models.Model):
_ | inherit = 'sale.order.line'
service_project_task = fields.Many2one(
comodel_name='project.task', string='Generated task from procurement',
copy=False)
|
VigTech/Vigtech-Services | principal/views.py | Python | lgpl-3.0 | 45,303 | 0.014399 | # -*- encoding: utf-8 -*-
# from django.shortcuts import render, render_to_response, redirect, get_object_or_404, get_list_or_404, Http404
from django.core.cache import cache
from django.shortcuts import *
from django.views.generic import TemplateView, FormView
from django.http import HttpResponseRedirect, HttpResponse... | Arxiv
# import igraph
import traceback
import json
import django.utils
from Logica.ConexionBD.adminBD import AdminBD
from principal.parameters import *
from principal.permisos import *
# sys.setdefaultencoding is cancelled by site.py
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')... | yecto = None
##nombre_proyecto = None
class home(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
global proyectos_list
global model_proyecto
try:
existe_proyecto = False
proyectos_list = get_list_or_404(proyecto, idUsuario=self... |
cernops/keystone | keystone/tests/unit/common/test_manager.py | Python | apache-2.0 | 1,531 | 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | t_deprecated_feature')
def test_class_is_properly_deprecated(self, mock_reporter):
Driver = manager.create_legacy_drive | r(catalog.CatalogDriverV8)
# NOTE(dstanek): I want to subvert the requirement for this
# class to implement all of the abstract methods.
Driver.__abstractmethods__ = set()
impl = Driver()
details = {
'as_of': 'Liberty',
'what': 'keystone.catalog.core.Dri... |
mozilla/addons-server | src/olympia/users/tests/test_admin.py | Python | bsd-3-clause | 38,889 | 0.001363 | from django.conf import settings
from django.contrib import admin
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages.storage import default_storage as default_messages_storage
from django.db import connection
from django.test import RequestFactory
from django.test.utils import CaptureQuer... | n_ip').text() == '127.0.0.1 127.0.0.1 127.0.0.2'
# Sam | e for the others that match
assert doc('.field-restriction_history__ip_address').text() == '- 127.0.0.2 -'
assert (
doc('.field-restriction_history__last_login_ip').text() == '127.0.0.2 - -'
)
def test_search_for_multiple_ips(self):
user = user_factory(email='someone@moz... |
ir-lab/intprim | intprim/__init__.py | Python | mit | 231 | 0 | from intprim.bayesian_interaction_primitives import *
im | port intprim.basis
import intprim.constants
import intprim.examples
import intprim.filter
import intprim.filter.align
import intprim.filter.spatiotemporal
import intprim.util | |
Halfish/lstm-ctc-ocr | 1_generateImage.py | Python | apache-2.0 | 1,086 | 0.003683 | # coding: utf-8
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import sys
import os
# how many pictures to generate
num = 10
if len(sys.argv) > 1:
num = int(sys.argv[1])
def genline(text, font, filename):
'''
generate one line
'''
w, h = font.getsize(text... | w') as f:
f.write(text)
f.close()
if __nam | e__ == '__main__':
if not os.path.isdir('./lines/'):
os.mkdir('./lines/')
for i in range(num):
fontname = './fonts/simkai.ttf'
fontsize = 24
font = ImageFont.truetype(fontname, fontsize)
text = str(random.randint(1000000000, 9999999999))
text = text + str(random.r... |
chosenone75/Neural-Networks | tf/CNN-Sentence-Classification/train_CNN4Text.py | Python | gpl-3.0 | 10,181 | 0.021904 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 20 23:53:19 2017
@author: chosenone
Train CNN for Text Classification
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import ti... | ==============================================================
# train parameters
#==============================================================================
tf.flags.DEFINE_integer("batch_size",64,"Batch size (default size 64)")
tf.flags.DEFINE_integer("num_epochs",200,"Epoch sizes(default size 200)")
tf.flags.... | model interval(default 100)")
tf.flags.DEFINE_integer("checkpoint_interval",100,"Save Checkpoint Interval(default 100)")
tf.flags.DEFINE_integer("num_checkpoints",5,"number of checkpoints to save(default 5)")
#==============================================================================
# misc parameters
#=======... |
flyhung/CMSIS-DAP | tools/get_binary.py | Python | apache-2.0 | 1,166 | 0.002573 | """
CMSIS-DAP Interface Firmware
Copyright (c) 2009-2013 ARM Limited
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 la... | mport gen_binary, is_lpc, split_path
from os.path import join
if __name__ == '__main__':
options = get_options()
in_path = get_interface_path(options.interface, options.target, bootloade | r=False)
_, name, _ = split_path(in_path)
out_path = join(TMP_DIR, name + '.bin')
print '\nELF: %s' % in_path
gen_binary(in_path, out_path, is_lpc(options.interface))
print "\nBINARY: %s" % out_path
|
github/codeql | python/ql/test/library-tests/ControlFlow/except/test.py | Python | mit | 1,251 | 0.02558 | #Ensure there is an exceptional edge from the following case
def f2():
b, d = Base, Derived
try:
class MyNewClass(b, d):
pass
except:
e2
def f3():
sequence_of_four = a_global
try:
a, b, c = sequence_of_four
except:
e3
#Always treat locals as no... | _global
try:
a = seq
except:
ea
def fb():
a, b, c = a_global
try:
seq = a, b, c
except:
eb
#Ensure that a.b and c[d] can raise
def fc():
a, b = a_global
try:
return a[b]
except:
ec
def fd():
a = a_global
try:
return a.b
... | lse:
ef
|
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/ns/nspbr6_args.py | Python | apache-2.0 | 1,047 | 0.025788 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | o in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class nspbr6_args :
""" Provides addit... | lf) :
self._detail = False
@property
def detail(self) :
"""To get a detailed view.
"""
try :
return self._detail
except Exception as e:
raise e
@detail.setter
def detail(self, detail) :
"""To get a detailed view.
"""
try :
self._detail = detail
except Exception as e:
raise e
|
vodik/plumbum | tests/test_color.py | Python | mit | 2,444 | 0.020458 | import pytest
from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound
from plumbum.colorlib.names import color_html, FindNearest
class TestNearestColor:
def test_exact(self):
assert FindNearest(0,0,0).all_fast() == 0
for n,color in enumerate(color_html):
... | (fgcolor=Color.from_full('green | '))) == '\033[38;5;2m'
assert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m'
class TestNearestColor:
def test_allcolors(self):
myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255)
for r in myrange:
for g in myrange:
for b in myrange... |
sebastien/wwwclient | tests/site-google.py | Python | lgpl-3.0 | 902 | 0.012195 | #!/usr/bin/env python
# vim: tw=80 ts=4 sw=4 noet
from os.path import join, basename, dirname, abspath
import _import
from wwwclient import browse, scrape
HTML = scrape.HTML
s = browse.Session("http://www.google.com")
f = s.form().fill(q="python web scraping")
s.submit(f, action="btnG", method="GET")
tree = scrape | .HTML.tree(s.page())
nodes = tree. | cut(below=3)
nodes = nodes.filter(accept=lambda n:n.name.lower() in ("table","p"))
for node in nodes.children:
print HTML.text(node)
if node.name == "p":
link = node.find(withName="a")[0]
print "-->", link.attribute("href")
print HTML.links(link)
else:
print "---------"
# Google results are not properly clo... |
psi4/psi4 | tests/psi4numpy/cphf/input.py | Python | lgpl-3.0 | 2,679 | 0.005972 | #! Tests out the CG solver with CPHF Polarizabilities
import time
import numpy as np
import psi4
psi4.set_output_file("output.dat")
# Benzene
mol = psi4.geometry("""
0 1
O 0.000000000000 0.000000000000 -0.075791843589
H 0.000000000000 -0.866811828967 0.601435779270
H ... | func(ma | trices, active_mask):
ret = []
for act, mat in zip(active_mask, matrices):
if act:
p = mat.clone()
p.apply_denominator(precon)
ret.append(p)
else:
ret.append(False)
return ret
def wrap_Hx(matrices, active_mask):
x_vec = [mat for act, mat ... |
imperial-genomics-facility/data-management-python | igf_data/illumina/runparameters_xml.py | Python | apache-2.0 | 3,007 | 0.018291 | from bs4 import BeautifulSoup
class RunParameter_xml:
'''
A class for reading runparameters xml file from Illumina sequencing runs
:param xml_file: A runparameters xml file
'''
def __init__(self, xml_file):
self.xml_file = xml_file
self._read_xml()
def _read_xml(self):
'''
Internal funct... | if soup.workflowtype:
workflowtype = \
soup.workflowtype.contents[0]
return workflowtype
except Exception as e:
raise ValueError('Failed to get NovaSeq workflow type')
def get_novaseq_flowcell(self) | :
try:
soup = self._soup
flowcell_id = None
workflowtype = self.get_nova_workflow_type()
if workflowtype is None or \
workflowtype != 'NovaSeqXp':
raise ValueError(
'Missing NovaSeq workflow type: {0}'.\
format(workflowtype))
if soup.r... |
odoo-arg/odoo_l10n_ar | l10n_ar_reject_checks/models/account_own_check.py | Python | agpl-3.0 | 2,297 | 0.002612 | # -*- encod | ing: utf-8 -*-
##############################################################################
#
# 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
# ... | rogram 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
# ... |
Gknoblau/gladitude | twitter/twitter_tweepy.py | Python | mit | 3,076 | 0.002276 | import datetime
import tweepy
from geopy.geocoders import Nominatim
import json
from secret import *
import boto3
import re
import preprocessor as p
import time
p.set_options(p.OPT.URL, p.OPT | .EMOJI)
# Get the service resource.
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('fuck')
geolocator = Nominatim()
epoch = datetime.datetime.utcfromtimestamp(0)
with open('zip2fips.json') as data_file:
zip2fips = json.load(data_file)
def get_fips(coords):
location = ... | n.raw:
if 'country_code' in location.raw['address']:
if location.raw['address']['country_code'] == 'us':
if 'postcode' in location.raw['address']:
zipcode = location.raw['address']['postcode']
else:
print("postcode not in locati... |
grapesmoker/nba | game/Season.py | Python | gpl-2.0 | 12,250 | 0.002286 | from __future__ import division
__author__ = 'jerry'
from utils.settings import pbp, seasons
from Game import Game
class NoCollectionError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class SeasonDataError(Exception):
def __init__(self, msg... | _ast / team_mp) * mp * 5 - ast) / ((team_fgm / team_mp) * mp * 5 - fgm)) * (1 - (mp / (team_mp / 5))))
fg_part = fgm * (1 - 0.5 * ((pts - ftm | ) / (2 * fga)) * q_ast)
team_scoring_poss = team_fgm + (1 - (1 - (team_ftm / team_fta))**2) * team_fta * 0.4
team_play_pct = team_scoring_poss / (team_fga + team_fta * 0.4 + team_tov)
team_orb_weight = ((1 - team_orb_pct) * team_play_pct) / ((1 - team_orb_pct) * team_play_pct + team_orb_pct * (1... |
bobisme/hello | python/hello3.py | Python | mit | 50 | 0 | #! | /usr/bin/env python3
print('hel | lo hello hello')
|
pythonvietnam/pbc082015 | VuQuangThang/21082015_B2/bai4.py | Python | gpl-2.0 | 433 | 0.080831 | #def binh_phuong()
try:
a=int(raw_input("Nhap so n>=0 \n"))
while a<=0:
a=int(raw_input("Nhap lai so n>=0\n "))
print "%d" %(a)
b=pow(a,2)
c=int(raw_input("Doan so binh phuong cua ban\n"))
while c!=b:
if c<b:
| print"chua dung, cao len 1 chut\n"
c=input()
else:
print"qua rui giam xuong ti\n"
c=input()
print "Chinh xac ket qua la %d" % | (c)
except:
print "Ban nhap khong dung kieu Integer"
|
planBrk/domaincrawler | test/test_link_aggregator.py | Python | apache-2.0 | 3,054 | 0.007531 | import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class LinkAggregatorTest(unittest.Tes... | is time, we also specify a referrer page
filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url)
self.assertListEqual(expected_links,filtered_links)
self.assertSetEqual(set(expected_links),link_aggregator._links)
| # Second invocation should result in deduplication
filtered_links = link_aggregator.filter_update_links(valid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# None of the invalid links should pass
... |
JackMc/CourseScraper | web/main.py | Python | mit | 311 | 0 | from flask import Flask, request, session, g, redirect, url_for, \
abort, flash
import db
import routes
DATABASE = 'test.db'
DEBUG = True
SECRET_KEY = 'key'
USERNAME = 'ad | min'
P | ASSWORD = 'password'
app = Flask(__name__)
app.config.from_object(__name__)
if __name__ == '__main__':
app.run()
|
jenshnielsen/hemelb | Tools/hemeTools/parsers/snapshot/__init__.py | Python | lgpl-3.0 | 11,074 | 0.00587 | #
# Copyright (C) University College London, 2007-2012, all rights reserved.
#
# This file is part of HemeLB and is provided to you under the terms of
# the GNU LGPL. Please see LICENSE in the top level directory for full
# details.
#
import numpy as np
import xdrlib
import warnings
from .. import HemeLbMagicNumbe... | count': voxel_count}
@classmethod
def _load(cls, filename, header):
return np.loadtxt(filename,
skiprows=cls.nHeaderLines,
dtype=cls._readable_row).view(np.recarray)
pass
class XdrVoxelFormatOneSnapshot(object):
@classmethod
def ... | he header, slurp data, create XDR object
f = file(filename)
f.seek(cls._headerLengthBytes)
reader = xdrlib.Unpacker(f.read())
ans = np.recarray((header['voxel_count'],), dtype=cls._readable_row)
# Read all the voxels.
for i in xrange(header['voxel_count']):
a... |
popazerty/EG-2 | lib/python/Components/Task.py | Python | gpl-2.0 | 15,627 | 0.03398 | # A Job consists of many "Tasks".
# A task is the run of an external tool, with proper methods for failure handling
from Tools.CList import CList
class Job(object):
NOT_STARTED, IN_PROGRESS, FINISHED, FAILED = range(4)
def __init__(self, name):
self.tasks = [ ]
self.resident_tasks = [ ]
self.workspace = "/tmp... | borted:
not_met.append(AbortedPostcondition())
else:
for postcondition in self.postconditions:
if not postcondition.check(self):
not_met.append(postcondition)
self.cleanup(not_met)
self.callback(self, not_met)
def afterRun(self):
pass
def writeInput(sel | f, input):
self.container.write(input)
def getProgress(self):
return self.__progress
def setProgress(self, progress):
if progress > self.end:
progress = self.end
if progress < 0:
progress = 0
self.__progress = progress
if self.task_progress_changed:
self.task_progress_changed()
progress = pro... |
ntt-sic/heat | heat/tests/test_neutron_loadbalancer.py | Python | apache-2.0 | 34,298 | 0.000087 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | scheduler.TaskRunner(rsrc.create)()
error = self.assertRaises(exception.InvalidTemplateAttribute,
| rsrc.FnGetAtt, 'subnet_id')
self.assertEqual(
'The Referenced Attribute (monitor subnet_id) is incorrect.',
str(error))
self.m.VerifyAll()
def test_update(self):
rsrc = self.create_health_monitor()
neutronclient.Client.update_health_monitor... |
adrianholovaty/django | tests/regressiontests/csrf_tests/tests.py | Python | bsd-3-clause | 13,454 | 0.002155 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.context_processors import csrf
from django.http import HttpRequest, HttpResponse
from django.middleware.csrf import CsrfViewMiddleware, CSRF_KEY_LENGTH
from django.template import RequestContext, Template
from django.test import TestCase
from dj... | ).process_response(req, res | p)
csrf_cookie = resp2.cookies.get('myname', False)
self.assertNotEqual(csrf_cookie, False)
self.assertEqual(csrf_cookie['domain'], '.example.com')
self.assertEqual(csrf_cookie['secure'], True)
self.assertEqual(csrf_cookie['path'], '/test/')
self.assertTrue('Cookie' in re... |
sunrin92/LearnPython | 1-lpthw/ex32.py | Python | mit | 812 | 0.004926 | the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots',]
change = [1, 'pennies', 2, 'dimes', 3, 'quarters',]
#this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d" % number)
# same as above
for fruit in fruits:
print("A fruit of type: %s" % fr... | n go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print("I got %r " % i)
# we can alse build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0,6):
print("Adding %d to the list." % i)
... | % i)
|
gyimothilaszlo/interval-music-maker | AudioMerger.py | Python | mit | 1,005 | 0.034826 | from pydub import *
class AudioMerger:
voice_tags = ["one", "two", "three", "four", "five", "ten", "RUN", "relax", "completed"]
def __init__( | self, music):
self.music = music
self.additionalGain = 8
self.voices={}
for voice in self.voice_tags:
sound = AudioSegment.from_file('voices/' + voice + '.wav')
sound += self.additionalGain
self.voices[voice] = sound
def addCountdown(self, startTime, isRun = True):
for i in range(1, 6):
voice = ... | self.music = self.music.overlay(self.voices["ten"], position = (startTime - 10) * 1000)
voice = self.voices["RUN" if isRun else "relax"]
self.music = self.music.overlay(voice, position = startTime * 1000)
def addCompleted(self, startTimeSec):
self.music = self.music.overlay(self.voices["completed"], position ... |
pankajlal/prabandh | books/migrations/0004_auto_20160703_2143.py | Python | apache-2.0 | 384 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-03 16:13
from __future__ import unicod | e_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('books', '0003_book_owner'),
]
operations = [
migrations.RenameModel(
old_name='Book',
new_name='BookItem',
),
| ]
|
akash1808/tempest | tempest/api/compute/volumes/test_volumes_get.py | Python | apache-2.0 | 3,025 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "L | icense"); you may
# not use this file except i | n 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 AN... |
virtualelephant/openstack-heat-bde-plugin | plugin/BigDataExtensions.py | Python | apache-2.0 | 17,510 | 0.003198 | #!/usr/bin/python
#
# OpenStack Heat Plugin for interfacing with VMware Big Data Extensions
#
# Chris Mutchler - chris@virtualelephant.com
# http://www.VirtualElephant.com
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License... | NAME, CLUSTER_TYPE, NETWORK, CLUSTER_PASSWORD, CLUSTER_RP,
VIO_CONFIG, BDE_CONFIG, SECURITY_GROUP, SUBNET
) = (
'bde_endpoint', 'vcm_server', 'username', 'password',
'cluster_name', 'cluster_type', 'network', 'cluster_password', 'cluster_rp',
'vio_config', 'bde_config', 'security_gro... | a(
properties.Schema.STRING,
required=True,
default='bde.localdomain'
),
VCM_SERVER: properties.Schema(
properties.Schema.STRING,
required=True,
default='vcenter.localdomain'
),
USERNAME: properties.Schema(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.