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
bruckhaus/challenges
python_challenges/project_euler/p007_ten_thousand_first_prime.py
Python
mit
873
0.001145
__author__ = 'tilmannbruckhaus' from collections import defaultdict class TenThousandFirstPrime: # 10001st prime # Problem 7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? LIMIT = 1000000 TARGET = 10...
t.prime_dict[j] = False if __name__ == '__m
ain__': print "The 10,001st prime is", TenThousandFirstPrime.find()
xjlin0/cs246
w2015/hw2/q4_clustering_kMeans_spark.py
Python
mit
2,787
0.011123
# Under the PySpark shell, type: # execfile('q4_clustering_kMeans_spark.py') #from pyspark import SparkContext, SparkConf # conf = SparkConf() # conf.setMaster("local") # conf.setAppName("Recommendation System") # conf.set("spark.executor.memory", "16g") #sc = SparkContext(conf=conf) #################################...
a.txt" data = sc.textFile(fileName, 8) #partition goes here parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')])).cache() # Build the models with different seeders: rando
m or fariest spots c1_clusters = KMeans.train(parsedData, 10, maxIterations=20, runs=1, initializationMode="random") c2_clusters = KMeans.train(parsedData, 10, maxIterations=20, runs=1, initializationMode='k-means||') #c1_initials=sc.textFile('c1.txt').map(lambda line: array([float(x) for x in line.split(' ')])) #c1_...
knipknap/exscript
Exscript/util/url.py
Python
mit
7,356
0.001767
# # Copyright (C) 2010-2017 Samuel Abels # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy,...
s = None def __str__(self): """ Like :class:`to_string()`. :rtype: str :return: A URL. """ url = ''
if self.protocol is not None: url += self.protocol + '://' if self.username is not None or \ self.password1 is not None or \ self.password2 is not None: if self.username is not None: url += quote(self.username, '') if self.password1 is...
tjcsl/director
web3/apps/sites/migrations/0017_auto_20170707_1608.py
Python
mit
572
0.001748
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-07 16:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sites', '0016_remove_site_domain_old'), ] operations = [
migrations.AlterField( model_name='site', name='purpose', field=models.CharField(choices=[('legacy', 'Legacy'), ('user', 'User'), ('project', 'Project'), ('activity', 'Activity'), ('other', 'Other')], max_length=16),
), ]
dendory/scripts
aws.py
Python
mit
22,042
0.032937
#!/usr/bin/python3 # # Simple AWS automation script - Patrick Lambert - http://dendory.net # Prerequisites: `pip3 install boto3` and `aws configure` # import os import sys import json import time cfgfile = os.path.join(os.path.expanduser("~"), ".aws.templates") # # Internal functions # def fail(msg): if os.name != "n...
'w') f.write(json.dumps(templates)) f.close() return True except: a, b, c = sys.exc_info() fail("Could not save templates file: " + str(b)) return False def usage(): info("Usage: aws.py <command> [options]") print() info("Available commands:") print("list-vms [-v|instanc
e id|name] : List all VMs, or details on one VM") print("start-vm <instance id|name> : Start a VM") print("stop-vm <instance id|name> : Stop a VM") print("restart-vm <instance id|name> : Reboot a VM") print("delete-v...
tigerlinux/tigerlinux-extra-recipes
recipes/misc/python-learning/CORE/0002-Print-and-Import-and-some-operations/print-and-import.py
Python
gpl-3.0
1,618
0.038937
#!/usr/bin/python3 # # By Reynaldo R. Martinez P. # Sept 09 2016 # TigerLinux AT Gmail DOT Com # Sa sample with some operations including usage of # a library import and some operations # # # # Here, weproceed to import the "SYS" library import sys # Next, we print the "sys.platform" information. Th...
a MODULE print ( "This is a MODULE from the last division: 342 Module 20" ) print ( 342%20 ) print ("") # This is an exponential: print ( "This is an exponential: 2 ^ 200" ) print(2 ** 100) print ("") # Define two string variable and concatenate them in the print statement var1 = "The Life is " var2 = "Strange
....." print ( "We define two strings, and concatenate them in a single print:") print ( var1 + var2 ) print ("") # Define 3 strings and print them in the same line: var3 = "Kiki" var4 = "Rayita" var5 = "Negrito" print ( "My 3 cats are named:" ) print ( var3, var4, var5 ) print ( "" ) # Next, we define a string vari...
isudox/leetcode-solution
python-algorithm/leetcode/problem_94.py
Python
mit
1,229
0
"""94. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the in-order traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively?...
ans.append(root.val) root = root.right return ans def recursive_inorder_traversal(self, root: TreeNode) -> List[int]: """ recursive traversal, process left if needed, then val, at last right """ if not root: return [] ans = [] ...
val) ans += self.recursive_inorder_traversal(root.right) return ans
joshmoore/openmicroscopy
components/tools/OmeroWeb/omeroweb/webmobile/views.py
Python
gpl-2.0
20,846
0.012952
from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render_to_response from omeroweb.webgateway.views import getBlitzConnection, _session_logout from omeroweb.webgateway import views as webgateway_views import settings import logging impor...
annot change your group becuase the data is currently processing. You can force it by logging out and logging in again.' url = reverse("webindex")+ ("?error=%s" % error) if request.session.get('nav')['experimenter'] is not None: url += "&experimen
ter=%s" % request.session.get('nav')['experimenter'] request.session['version'] = conn.getServerVersion() return HttpResponseRedirect(url) def viewer(request, imageId): conn = getBlitzConnection (request, useragent="OMERO.webmobile") if conn is None or not conn.isConnected(): ...
Pseudonick47/sherlock
backend/api/data.py
Python
gpl-3.0
37,646
0.003294
# -*- coding=utf-8 -*- """ All entry points for API are defined here. Attributes: mod (Blueprint): Flask Blueprint object used to separate api from website code. """ from flask import Blueprint, request, send_from_directory from flask_restful import Api, Resource import os fr...
: 2, "locations": [...] }, {
"id": 17, "name": "It's Time to Party", "description": "Have a wonderful time with young and wicked people in Sydney's most sp
seleniumbase/SeleniumBase
examples/image_test.py
Python
mit
2,523
0
import os import pytest from seleniumbase import BaseCase class ImageTests(BaseCase): @pytest.mark.run(order=1) def test_pull_image_from_website(self): """ Pull an image from a website and save it as a PNG file. """ self.open("https://xkcd.com/1117/") selector = "#comic" file_n...
ile( selector, file_name, folder, overlay_text ) self.assert_true(os.path.exists("%s/%s" % (folder, fil
e_name))) print('\n"%s/%s" was saved!' % (folder, file_name)) @pytest.mark.run(order=4) def test_add_text_overlay_to_full_page(self): """ Add a text overlay to a full page. """ self.open("https://xkcd.com/1922/") self.remove_element("#bottom") selector = "body" f...
ramalho/eagle-py
tests/entries.py
Python
lgpl-2.1
572
0.001748
#!/usr/bin/env python2 from eagle import * def changed
(app, entry, value): print "app %s, entry %s, value %r" % (app.id, entry.id, value) App(title="Entries Test", center=(Entry(id="single"), Entry(id="multi", multiline=True), Entry(id="non-editable", label="non-editable", value="Value", editable=False), Entr...
alue="Value", editable=False, multiline=True), ), data_changed_callback=changed, ) run()
lavagetto/plumber
setup.py
Python
gpl-3.0
589
0.001698
#!/usr/bin/python from setuptools import setup, find_pa
ckages setup( name='plumber', version='0.0.1-alpha', description='simple, mundane script to build and publish containers to marathon/mesos', author='Giuseppe Lavagetto', author_email='[email protected]', url='https://github.com/lavagetto/plumber', install_requires=['argparse', 'Flask...
lumber-run = plumber.main:run', ], }, )
astooke/synkhronos
synkhronos/comm.py
Python
mit
13,018
0.000615
import zmq import numpy as np import theano import theano.gpuarray try: from pygpu import collectives as gpu_coll except ImportError as exc: gpu_coll = None from .reducers import reducers sync = None cpu = None gpu = None def connect_as_master(n_parallel, rank, master_rank, use_gpu, m...
air_sockets: if soc
ket is None: recv_arrs.append(np.asarray(arr)) else: recv_arrs.append(recv_nd_array(socket)) return combine_nd_arrays(recv_arrs, nd_up, dest) def all_gather(self, arr, nd_up=0, dest=None): recv_arr = self.gather(arr, nd_up, dest) self.broadcast(re...
anyweez/regis
face/offline/ParserTools/ParserTools.py
Python
gpl-2.0
1,892
0.005814
import os # ParserTools class class ParserTools(object): def __init__(self): self.qset = None self.template = None # Called before running any PT functions in a term definition. def term_focus(self, term): self.qset = term.qset self.template = term.template # C...
def load_datafile(self, filename): directory = '../resources
/full' fp = open('%s/%s' % (directory, filename)) lines = fp.readlines() fp.close() return lines # Stores a file for the user that's currently being parsed. def store_userfile(self, contents): directory = '../resources/user' fp = open('%s/%d.%d.txt' % (directo...
padmacho/pythontutorial
objects/id_demo.py
Python
apache-2.0
113
0
x = 10 print("id(x) is ", id(x)) y = 20 print("id(y) i
s ", id(y)) print("id(x) == id(y): ", id(x
) == id(y))
tseaver/gcloud-python
firestore/tests/unit/gapic/v1beta1/test_firestore_client_v1beta1.py
Python
apache-2.0
20,576
0
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
b(method, self) def unary_stream(self, method, request_serializer=None, res
ponse_deserializer=None): return MultiCallableStub(method, self) def stream_stream(self, method, request_serializer=None, response_deserializer=None): return MultiCallableStub(method, self) class CustomException(Exception): pas...
lancekrogers/music-network
cleff/custom_wrappers.py
Python
apache-2.0
1,287
0.006216
from django.contrib.auth.decorators import user_passes_test, login_required from profiles.models import Musician, NonMusician from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect # import login_required user_passes_test # these functions are made to be passed into user_passes_tes...
(pk=x.pk) except ObjectDoesNotExist: return redirect('profiles:
register_musician') except AttributeError: return redirect('profiles:register_musician') def non_musician_check(x): try: return NonMusician.objects.filter(pk=x.pk) except ObjectDoesNotExist: return redirect('main:denied') except AttributeError: return redirect('main:den...
esurharun/aircrack-ng-cell
scripts/airgraph-ng/airgraph-ng.py
Python
gpl-2.0
16,007
0.03892
#!/usr/bin/python __author__ = 'Ben "TheX1le" Smith' __email__ = '[email protected]' __website__= 'http://trac.aircrack-ng.org/browser/trunk/scripts/airgraph-ng/' __date__ = '03/02/09' __version__ = '' __file__ = 'airgraph-ng' __data
__ = 'This is the main airgraph-ng file' """ Welcome to airgraph written by TheX1le Special Thanks to Rel1k and Zero_Chaos two people whom with out i would not be who I am! More Thanks to Brandon x0ne Dixon who really cleaned up the code forced it into pydoc format and cleaned up the logic a bit Thanks Man! I would al...
d Remote Exploit Community for all their help and support! ######################################## # # Airgraph-ng.py --- Generate Graphs from airodump CSV Files # # Copyright (C) 2008 Ben Smith <[email protected]> # # This program and its support programs are free software; you can redistribute it and/or modify it #...
TheCherry/ark-server-manager
src/config.py
Python
gpl-2.0
22
0
global mods m
ods
= []
CCI-MOC/GUI-Backend
api/v2/serializers/details/image.py
Python
apache-2.0
1,518
0
from core.models import Application as Image, BootScript from rest_framework import serializers from api.v2.serializers.summaries import UserSummarySerializer from api.v2.serializers.fields import ( ImageVersionRelatedField, TagRelatedField) from api.v2.serializers.fields.base import UUIDHyperlinkedIdentityField ...
truth_value = super(SwapBooleanField, self).to_representation(value) swap_value = not truth_value return swap_value class ImageSerializer(serializers.HyperlinkedModelSerializer): created_by = UserSummarySerializer(read_only=True) tags = TagRelatedField(many=True) versions = ImageVersi...
is_public = SwapBooleanField(source='private') url = UUIDHyperlinkedIdentityField( view_name='api:v2:application-detail', ) class Meta: model = Image fields = ( 'id', 'url', 'uuid', 'name', # Adtl. Fields 'c...
graebnerc/Beyond_Equilibrium
tsm-src.py
Python
mit
83,029
0.005095
from __future__ import print_function import numpy import random import scipy.stats """ This is the source code for the paper entitled "Beyond Equilibrium: Revisiting Two-Sided Markets from an Agent-Based Modeling Perspective" published in the International Journal of Computational Economics and Econometrics. Authors: ...
# maximum boundary buyer entrance fee min_trans_cost_s = -1000 # min transaction cost for seller max_trans_cost_s = 1010 # max transaction cost for seller min_trans_cost_b = -1000 # min transaction cost for buyer max_trans_cost_b = 1010 # max transaction cost for buyer ema_factor = 0.01 # e...
liary global variables provider_id = 0 # provider id counter seller_id = 0 # 'seller' id counter buyer_id = 0 # 'buyer' id counter transaction_counter = 0 # counter variable for transactions in period t = -1 # time figure = -1 # figure objects # object list var...
epronk/pyfit2
engines.py
Python
gpl-2.0
3,171
0.005361
import traceback from util import * import importlib class DefaultLoader(object): def __init__(self): self.fixtures
= {} def load(self, name): org_name = name fixture = self.fixtures.get(name) if fixture: print 'already exists, return' return fixture print 'DefaultLoader.load' try: module = self.do_load(name) except ImportError, inst: ...
module, name) fixture = getattr(module, name)() self.fixtures[org_name] = fixture return fixture def do_load(self, name): return __import__(name) class StringLoader(DefaultLoader): def __init__(self, script): self.script = script def load(self, name): x = co...
tensorflow/ngraph-bridge
tools/log_parser.py
Python
apache-2.0
6,884
0.002905
#============================================================================== # Copyright 2019-2020 Intel Corporation # # 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...
aries (representing jsons) # The constraints in expected is <= parsed_vals. Parsed_vals should have all possible values that the parser can spit out. However expected_vals can be relaxed (even empty) and choose to only verify/match certain fields match = lambda current, expected: all( [expected[k] == cu...
k in expected]) for graph_id_1 in expected_vals: # The ordering is not important and could be different, hence search through all elements of parsed_vals matching_id = None for graph_id_2 in parsed_vals: if match(expected_vals[graph_id_1], parsed_vals[graph_id_2]): ...
easytaxibr/airflow
tests/core.py
Python
apache-2.0
93,982
0.001734
# -*- coding: utf-8 -*- # # 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 ...
ose() reset() class OperatorSubclass(BaseOperator): """ An operator to test template substitution """ template_fields = ['some_templated_field']
def __init__(self, some_templated_field, *args, **kwargs): super(OperatorSubclass, self).__init__(*args, **kwargs) self.some_templated_field = some_templated_field def execute(*args, **kwargs): pass class CoreTest(unittest.TestCase): # These defaults make the test faster to run d...
brainwane/zulip
zerver/views/zephyr.py
Python
apache-2.0
2,693
0.001857
import bas
e64 import logging import re import subprocess from typing import Optional import orjson from django.conf import settings from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.decorator import authenticated_json_view from zerver.lib.ccache import ma
ke_ccache from zerver.lib.pysa import mark_sanitized from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_error, json_success from zerver.lib.users import get_api_key from zerver.models import UserProfile # Hack for mit.edu users whose Kerberos usernames don't match what they ...
t3dev/odoo
addons/stock/wizard/stock_warn_insufficient_qty.py
Python
gpl-3.0
1,401
0.002141
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file fo
r full copyright and licensing details. from odoo import api, fields, models from odoo.tools import float_compare class StockWarnInsufficientQty(models.AbstractModel): _name = 'stock.warn.insufficient.qty' _description = 'Warn Insufficient Quantity' product_id = fields.Many2one('product.product', 'Produ...
', '=', 'internal')]", required=True) quant_ids = fields.Many2many('stock.quant', compute='_compute_quant_ids') @api.one @api.depends('product_id') def _compute_quant_ids(self): self.quant_ids = self.env['stock.quant'].search([ ('product_id', '=', self.product_id.id), ('...
plotly/plotly.py
packages/python/plotly/plotly/validators/contourcarpet/line/_color.py
Python
mit
411
0.002433
import _plotly_utils
.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="color", parent_name="contourcarpet.line", **kwargs): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwar...
**kwargs )
recombinators/autoscaling
checker.py
Python
mit
2,410
0.000415
import os from sqs import (make_SQS_connection, get_queue, queue_size, ) from cloudwatch import (make_CW_connection, update_metric, ) from threading import Timer # Define AWS credentials AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] REGION = 'us-west-2'...
er(interval, full_queue_timer, args=[SQSconn, CWconn, queue_name, metric_name, interval] ).start() # Check queue sizes every 20 seconds def main(): full_queue_timer(SQSconn, CWconn,
FULL_COMPOSITE_QUEUE, FULL_COMPOSITE_METRIC, FULL_INTERVAL) preview_queue_timer(SQSconn, CWconn, PREVIEW_COMPOSITE_QUEUE, PREVIEW_COMPOSITE_METRIC, PREVIEW_INT...
scottnm/ProjectEuler
python/Problem1-Multiples_of_3_&_5.py
Python
apache-2.0
82
0.085366
sum=0 fo
r x in range(0,1
000): if(x%3==0 or x%5==0): sum+=x print(sum)
barmalei/primus
lib/primus/fileartifact.py
Python
lgpl-3.0
6,594
0.014407
# # Copyright 2009 Andrei <[email protected]> # # 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 opti...
if not os.path.exists(realpath): raise IOError("Path '%s' link has to refer does not exist." % self.path) os.chdir(Artifact.home_dir()) if os.path.exists(self.name): os.unlink(self.name) os.symlink(realpath, self.name)
def what_it_does(self): return "Create symlink: %s" % self.name class AcquiredDirectory(FileArtifact): def __init__ (self, name, dependencies=[]): FileArtifact.__init__(self, name, dependencies) path = self.fullpath() if os.path.exists(path) and (not os.path.isdir(path)): ...
classgrade/classgrade
classgrade/gradapp/migrations/0028_auto_20170105_1435.py
Python
mit
486
0
# -*- coding: utf-8 -*- # Generated by D
jango 1.10.1 on 2017-01-05 14:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gradapp', '0027_auto_20161109_0925'), ] operations = [ migrations.AlterField( model_name='evalquestion'...
omments', field=models.TextField(help_text='Use Markdown', max_length=500), ), ]
ovresko/erpnext
erpnext/setup/doctype/setup_progress/setup_progress.py
Python
gpl-3.0
1,811
0.027057
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe,
json from frappe.model.document import Document class SetupProgress(Document): pass def get_setup_progress(): if not getattr(frappe.local, "setup_progress", None): frappe.local.setup_progress = frappe.get
_doc("Setup Progress", "Setup Progress") return frappe.local.setup_progress def get_action_completed_state(action_name): for d in get_setup_progress().actions: if d.action_name == action_name: return d.is_completed def update_action_completed_state(action_name): action_table_doc = [d for d in get_setup_progr...
decvalts/iris
lib/iris/experimental/concatenate.py
Python
gpl-3.0
1,615
0
# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any l...
utomatic concatenation of multiple cubes over one or more existing dimensions. .. warning:: This
functionality has now been moved to :meth:`iris.cube.CubeList.concatenate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa def concatenate(cubes): """ Concatenate the provided cubes over common existing dimensions. ...
django-bft/django-bft
bft/utils/json_utils.py
Python
gpl-3.0
765
0.035294
from django.conf import settings from django.http import HttpResponseServerError, HttpResponse from django.utils import simplejson class JsonResponse(HttpResponse): def __init__(self, data, status=200): HttpResponse.__init__(self, content=simplejson.dumps(data),
content_type='application/json; charset=UTF-8', status=status ) class AJAXExceptionResponse: def process_exception(self, request, exception): if settings.DEBUG: if request.is_ajax(): import sys, traceback (exc_type, exc_info, tb) = sys.exc_info()
response = "%s\n" % exc_type.__name__ response += "%s\n\n" % exc_info response += "TRACEBACK:\n" for tb in traceback.format_tb(tb): response += "%s\n" % tb return HttpResponseServerError(response)
abrosen/numerical-analysis
numhw3.py
Python
lgpl-3.0
910
0.023077
# Andrew Rosen # performs Romberg Integration # Usage python numhw3.py from math import * de
f extrapolate(f,a,b, depth): R = [] for i i
n range(0, depth): R.append([None]*(depth)) R[0][0] = ((b-a)*.5)*(f(a)+ f(b)) for n in range(1, depth): h_n = (b-a)/(2.0**(n)) points = [0] for k in range(1,int(2**(n-1)) +1): point = f(a + (2*k -1)*h_n) points.append(point) R[n][0] = .5*R[n-1][0]...
plotly/plotly.py
packages/python/plotly/plotly/validators/densitymapbox/colorbar/_ticktext.py
Python
mit
436
0.002294
import _plotly_utils.b
asevalidators class TicktextValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name="ticktext", parent_name="densitymapbox.colorbar", **kwargs ): super(TicktextValidator, se
lf).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), **kwargs )
FenixFeather/ksp-music-hack
music_hack.py
Python
gpl-3.0
12,698
0.003229
#!/usr/bin/env python from __future__ import division import krpc import vlc import time import random import yaml import os import socket import math import logging import sys from collections import deque import argparse class Player(object): def __init__(self, path, preload=True): self.instance = vlc.In...
nged: self
.player.stop() if not self.player.is_playing(): self.play_next_track(self.current_scene) def play_flight_music(self): self.player.stop() while True: self.current_scene, changed = self.get_current_scene() if self.current_scene != "Fl...
DeveloperJose/Vision-Rat-Brain
feature_matching_v1/scripts_batch_processing/batch_warp.py
Python
mit
2,630
0.009132
# -*- coding: utf-8 -*- import numpy as np import csv import feature import config def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int...
iterations (Int)
prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) ""...
toumorokoshi/transmute-core
transmute_core/tests/contenttype_serializers/test_default_serializer_set.py
Python
mit
1,393
0.000718
import pytest from transmute_core import NoSeriali
zerFound, SerializationException def test_default_serializer_json(serializer_set): frm, expected_
to = {"foo": "bar"}, b'{"foo": "bar"}' serializer = serializer_set["application/json"] assert serializer.dump(frm) == expected_to assert serializer.load(expected_to) == frm def test_default_serializer_yaml(serializer_set): frm, expected_to = {"foo": "bar"}, b"foo: bar\n" serializer = serializer_se...
brextonpham/python-Ultron
python-vlc-master/generator/__init__.py
Python
mit
20
0
# Generator packag
e
petrhosek/rubber
rubber/converters/latex.py
Python
gpl-2.0
42,452
0.035028
# This file is part of Rubber and thus covered by the GPL # (c) Emmanuel Beffara, 2002--2006 """ LaTeX document building system for Rubber. This module contains all the code in Rubber that actually does the job of building a LaTeX document from start to finish. """ import os, os.path, sys, imp import re import string...
ass performs all the extraction of information from the log file. For efficiency, the instances contain the whole file as a list of strings so that it can be read several times with no disk access. """ #-- Initialization {{{2 def __init__ (self): self.lines = None def read (self, name): """ Read the speci...
d by the right compiler. Returns true if the log file is invalid or does not exist. """ self.lines = None try: file = open(name) except IOError: return 2 line = file.readline() if not line: file.close() return 1 if not re_loghead.match(line): file.close() return 1 self.lines = file...
caneruguz/osf.io
scripts/utils.py
Python
apache-2.0
1,318
0.000759
# -*- coding: utf-8 -*- import os import logging import datetime import sys from django.utils import timezone from website import settings def format_now(): return timezone.now().isoformat() def add_file_logger(logger, script_name, suffix=None): _, name = os.path.split(script_name) name = name.rstrip...
(self, bar_len=50): self.bar_len = bar_len def start(self, total, prefix): self.total = total self.count = 0 self.prefix = prefix def increment(self, inc=1): self.count += inc filled_len = int(round(self.bar_len * self.count / float(self.total))) percent...
) sys.stdout.flush() sys.stdout.write('{}[{}] {}{} ... {}\r'.format(self.prefix, bar, percents, '%', str(self.total))) def stop(self): # To preserve line, there is probably a better way to do this print('')
aisthesis/machinelearning
experiments/neural.py
Python
mit
5,497
0.002001
""" Copyright (c) 2014 Marshall Farrier license http://opensource.org/licenses/MIT @author: Marshall Farrier @contact: [email protected] @since: 2014-11-10 @summary: Neural network Resources: Great performance ideas: http://stackoverflow.com/questions/21106134/numpy-pure-functions-for-performance-caching """ ...
mpty((features.shape[0], wts0.shape[1] + 1)) hidden[:, 0] = 1.0 sigxw = sigmoid(features.dot(wts0)) hidden[:, 1:] = sigxw # get optimal wts1 given wts0 wts1 = np.linalg.pinv(hidden).dot(labels) predicted = hidden.dot(wts1) # backprop """ First version doesn't work. Sample output ...
nonlinear function using random features: error after iteration 1: 0.389115314723 error after iteration 2: 0.324511537066 error after iteration 3: 0.728566874908 error after iteration 4: 0.174713101869 error after iteration 5: 0.47208655752 error after iteration 6: 0.779610384956 ... er...
zhumingliang1209/Ardupilot
ardupilot/modules/waf/waflib/Build.py
Python
gpl-3.0
37,831
0.031852
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ Classes related to the build phase (build, clean, install, step, etc) The inheritance tree is the following: """ import os, sys, errno, re, shutil, stat try: import cPickle except ImportError: import pickle as cPickle from waflib import Ru...
py' """Suffix for the cache files""" INSTALL = 1337 """Positive value '->' install, see :py:attr:`waflib.Build.BuildContext.is_install`""" UNINSTALL = -1337 """Negative value '<-' uninstall, see :py:attr:`waflib.Build.BuildContext.is_install`""" SAVED_ATTRS = 'root node_deps raw_deps task_sigs'.split() """Build clas...
to save between the runs (root, node_deps, raw_deps, task_sigs)""" CFG_FILES = 'cfg_files' """Files from the build directory to hash before starting the build (``config.h`` written during the configuration)""" POST_AT_ONCE = 0 """Post mode: all task generators are posted before the build really starts""" POST_LAZY ...
miroag/mfs
tests/conftest.py
Python
mit
516
0.001938
import os import pytest @pyt
est.fixture(scope='session') def testdata(): """ Simple fixture to return reference data :return: """ class TestData(): def __init__(self): self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') def fn(self, fn): return os.path.join...
return f.read() return TestData()
iychoi/syndicate-core
ms/storage/storagetypes.py
Python
apache-2.0
25,103
0.032785
""" Copyright 2013 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicab...
ceededError = backend.RequestDeadlineExceededError APIRequestDeadlineExceededError = backend.APIRequestDeadlineExceededError URLRequestDeadlineExceededError = backend.URLRequestDeadlineExceededError TransactionFailedError = backend.TransactionFailedError def clock_gettime(): now = time.time() now_sec = int(now)...
= now.timetuple() now_sec = int(time.mktime( nowtt )) now_nsec = int(now.microsecond * 1e3) return (now_sec, now_nsec) ''' def get_time(): now_sec, now_nsec = clock_gettime() return float(now_sec) + float(now_nsec) / 1e9 class Object( Model ): # list of names of attributes of required attribu...
unicefuganda/edtrac
edtrac_project/rapidsms_edtrac/education/utils.py
Python
bsd-3-clause
12,792
0.00641
from dateutil.relativedelta import relativedelta from script.models import Script, ScriptProgress from rapidsms.models import Connection import datetime from rapidsms.models import Contact from rapidsms.contrib.locations.models import Location from poll.models impo
rt Poll from script.models im
port ScriptStep from django.db.models import Count from django.conf import settings from education.scheduling import schedule_at, at def is_holiday(date1, holidays = getattr(settings, 'SCHOOL_HOLIDAYS', [])): for date_start, date_end in holidays: if isinstance(date_end, str): if date1.date() =...
zavlab1/foobnix
foobnix/preferences/configs/other_conf.py
Python
gpl-3.0
9,256
0.002161
#-*- coding: utf-8 -*- ''' Created on 23 дек. 2010 @author: ivan ''' import logging from gi.repository import Gtk from foobnix.fc.fc import FC from foobnix.preferences.configs import CONFIG_OTHER from foobnix.util.antiscreensaver import antiscreensaver from foobnix.preferences.config_plugin import ConfigPlugin from...
yle (Menu Bar)")) self.new_style = Gtk.RadioButton.new_with_label_from_widget(self.old_style, _("New Style (
Button)")) pbox.pack_start(label, False, False, 0) pbox.pack_start(self.new_style, False, True, 0) pbox.pack_start(self.old_style, False, False, 0) o_r_box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5) o_r_box.show() o_r_label = Gtk.Label.new(_("Order-Repeat Switcher St...
Azure/azure-sdk-for-python
sdk/formrecognizer/azure-ai-formrecognizer/tests/test_dac_analyze_layout.py
Python
mit
7,732
0.004656
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # --
---------------------------------- im
port pytest import functools from devtools_testutils import recorded_by_proxy from azure.ai.formrecognizer._generated.v2022_01_30_preview.models import AnalyzeResultOperation from azure.ai.formrecognizer import DocumentAnalysisClient from azure.ai.formrecognizer import AnalyzeResult from preparers import FormRecognizer...
koery/win-sublime
Data/Packages/Package Control/package_control/downloaders/caching_downloader.py
Python
mit
5,367
0.001491
import sys import re import json import hashlib from ..console_write import console_write class CachingDownloader(object): """ A base downloader that will use a caching backend to cache HTTP requests and make conditional requests. """ def add_conditional_headers(self, url, headers): """ ...
:param status: The numeric response status of the request :param headers: A dict of reponse headers, with keys being lowercase :param content: The response content :return: The response content """ debug = self.settings.g
et('debug', False) cache = self.settings.get('cache') if not cache: if debug: console_write(u"Skipping cache since there is no cache object", True) return content if method.lower() != 'get': if debug: console_write(u"Skipping ...
ashleywaite/django-more
django_more/hashing.py
Python
bsd-3-clause
3,651
0
from base64 import b64encode, b16encode, b64decod
e, b16decode from math import ceil __all__ = [ "b64max", "b64len", "b64from16", "b64from256", "b16len", "b16max", "b16from64", "b16from256", "HashString", ] # Base 64 helpers for working in strings # b64 encodes 6 bits per character, in 3 byte raw increments, four bytes b64 def b6...
""" Maximum number of raw bits that can be stored in a b64 of length x """ # Four byte increments only, discard extra length return (char_length // 4) * (3 * 8) def b64len(bit_length): """ Minimum b64 length required to hold x raw bits """ # Three raw bytes {bl / (8*3)} is four b64 bytes return c...
majorcs/fail2ban
fail2ban/tests/fail2banregextestcase.py
Python
gpl-2.0
6,546
0.019554
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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;...
try: from systemd import journal except ImportError: journal = None from ..client import fail2banregex from ..client.fail2banregex import Fail2banRegex, get_opt_parser, output from .utils import LogCaptureTestCase, logSys fail2banregex.logSys = logSys def _test_output(*args): logSys.info(args[0]) fail2banregex....
F_FILES_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__),"..", "..", "config")) TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files") def _Fail2banRegex(*args): parser = get_opt_parser() (opts, args) = parser.parse_args(list(args)) return (opts, args, Fail2banRegex(opts)) class Fail2banR...
CompassionCH/compassion-modules
sponsorship_compassion/models/contracts_report.py
Python
agpl-3.0
10,144
0.00138
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # @author: Stephane Eicher <[email protected]> # # The licence is in the file __manifest__.py # ####################################################################...
lly managed or those who are " "paid (not the correspondent).", )
sr_nb_b2s_letter = fields.Integer('Number of letters to sponsor', compute='_compute_b2s_letter') sr_nb_s2b_letter = fields.Integer('Number of letters to beneficiary', compute='_compute_s2b_letter') sr_nb_boy = fields.Integer("Number...
dekom/threepress-bookworm-read-only
bookworm/django_evolution/__init__.py
Python
bsd-3-clause
1,410
0.001418
# The version of Django Evolution # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number,
Released) # VERSION = (0, 6, 6, 'alpha', 0, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: ve...
n += ' %s %s' % (VERSION[3], VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': version += '%s%s' % (VERSION[3...
ColumbiaCMB/kid_readout
kid_readout/analysis/timeseries/periodic.py
Python
bsd-2-clause
1,094
0.001828
""" This module contains functions to analyze periodic data. """ from __future__ import division, print_function import numpy as np def folded_shape(array, period_samples): if period_sam
ples == 0: raise ValueError("Cannot fold unmodulated data or with period=0") shape = list(array.shape) shape[-1] = -1 shape.append(period_samples) return tuple(shape) def fold(array, period_samples, reduce=None): reshaped = array.reshape(folded_shape(array, period_samples)) if reduce i...
def mask_left_right(size, skip): left_mask = (skip * size < np.arange(size)) & (np.arange(size) < size // 2) right_mask = size // 2 + skip * size < np.arange(size) return left_mask, right_mask def peak_to_peak(folded, skip=0.1): left_mask, right_mask = mask_left_right(size=folded.size, skip=skip) ...
paperreduction/fabric-bolt
fabric_bolt/core/urls.py
Python
mit
1,071
0.001867
from django.conf.urls import include, url from django.contrib import admin from django.conf import settings import socketio.sdjango from fabric_bolt.core import views socketio.sdjango.autodiscover() admin.autodiscover() urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(...
', include(socketio.sdjango.urls)), url(r'^users/', include('fabric_bolt.accounts.urls')), ] # Serve the static files from django if settings.DEBUG: urlpatterns += [ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'documen
t_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ]
liqd/a4-meinberlin
meinberlin/apps/newsletters/migrations/0001_initial.py
Python
agpl-3.0
1,979
0.005558
# -*- coding: utf-8 -*- from __future__ import unicode_literals import ckeditor_uploader.fields import django.utils.timezone from django.conf import settings from django.db import migrations from dj
ango.db import models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.A4_ORGANISATIONS_MODEL), ('a4projects', '0008_project_tile_image'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migration...
verbose_name='ID', auto_created=True)), ('created', models.DateTimeField(editable=False, default=django.utils.timezone.now)), ('modified', models.DateTimeField(null=True, editable=False, blank=True)), ('sender', models.EmailField(max_length=254, blank=True, verbose_name='...
wecatch/app-turbo
demos/models/blog/base.py
Python
apache-2.0
188
0
# -*- coding:utf-8 -*- from models.base impo
rt SqlBaseModel class Model(SqlBaseModel): def __init__(self): super(Model, self).__init_
_(db_name='blog') Base = Model().Base
baidubce/bce-sdk-python
sample/vcr/vcr_sample_conf.py
Python
apache-2.0
675
0.002963
# !/usr/bin/env python # coding=utf-8 """ Configuration for vcr samples. """ import logging from baidubce.bce_client_configuration import BceClientConfiguration fro
m baidubce.auth.bce_credentials import BceCredentials HOST = 'http://vcr.bj.baidubce.com' AK = 'Fill AK here' SK = 'Fill SK here' logger = logging.getLogger('baidubce.services.vcr.vcrclient') fh = logging.FileHandler('sample.log') fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(l...
BceClientConfiguration(credentials=BceCredentials(AK, SK), endpoint=HOST)
asedunov/intellij-community
python/testData/inspections/ChainedComparison5.py
Python
apache-2.0
164
0.060976
mapsize = 35 def test(x,
y): if <weak_warning descr="Simplify chained comparison">
0 <= x < <caret>mapsize and y >= 0 and y < mapsize</weak_warning>: return 1
broonie89/loadify-1
lib/ohdevtools/commands/update-nuget.py
Python
mit
2,276
0.005712
from xml.etree.cElementTree import parse, Element, ElementTree, dump from os import walk from os.path import join from optparse import OptionParser description = "Update the master package.config from individual project ones." command_group = "Developer tools" # Snippet used from the ElementTree documentation. # Tidy...
Element.get('version') packages[pkgId, pkgVersion] = packageElement print print "Writing projectdata/packages.config:" rootElement.extend([value for (key,value) in sorted(packages.items())]) indent(rootElement) tree = ElementTree(rootElement) dump(tree) tree.write('proj
ectdata/packages.config') if __name__ == "__main__": main()
chirilo/mozillians
vendor-local/lib/python/tablib/packages/odf3/thumbnail.py
Python
bsd-3-clause
31,736
0.000095
#!/usr/bin/python # -*- coding: utf-8 -*- # This contains a 128x128 px thumbnail in PNG format # Taken from http://www.zwahlendesign.ch/en/node/20 # openoffice_icons/openoffice_icons_linux/openoffice11.png # License: Freeware import base64 iconstr = """\ iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAAG0OVFdAAAABGdBTUEAANbY1E9Y...
R4F 5WVQsgZNEILYoCYrKOmD5EGBAqveQLEOzKPgFIArqROaFgbJv//yl+E2MKmrK0sByw0BhqOnTjK0 tbQymJub/dm6ecvXUydPlgGVnoZ6/gt6sxkggHAFuZStrfb0f/oz/ER/n2GY1x4PLpSAfQWG+Ph4 lGQHimVQIQZqtIBiGDSHAAKgGAU1YEAxDcpCIE+CYhjUgIHI8eCt23EtDQItGP/4DTRI9h/o+X8M j+9fY7AxVgWaxcmw/8g
Rhq72dgYfbx+GbVu3MWzbtiULmudB81NfsfUZAAIIX5oDNdviDCLm969s tGJQVVVFSaIgj4Nmd0GFGSjGQYEBKshAMcrLCym9YV1gSlqUIK0/gb3+Lz//M4DWp3798R
iamdankaufman/beets
beets/autotag/__init__.py
Python
mit
9,819
0
# This file is part of beets. # Copyright 2013, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
n this way. start_collapsing = False for marker in MULTIDISC_MARKERS: marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I) match = marker_pat.match(os.pat
h.basename(root)) # Is this directory the root of a nested multi-disc album? if dirs and not items: # Check whether all subdirectories have the same prefix. start_collapsing = True subdir_pat = None for subdir in dirs: ...
HybridF5/jacket
jacket/api/compute/openstack/compute/deferred_delete.py
Python
apache-2.0
3,026
0.00033
# Copyright 2011 OpenStack Foundation # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the s
pecific language governing permissions and limitations # under the License. """The deferred instance delete extension.""" import webob from jacket.api.compute.openstack import common from jacket.api.compute.openstack import extensions from jacket.api.compute.openstack import wsgi from jacket.compute import cloud ...
Lyleo/OmniMarkupPreviewer
OmniMarkupLib/Renderers/libs/python3/docutils/examples.py
Python
mit
3,913
0.000511
# $Id$ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ This module contains practical examples of Docutils client code. Importing this module from client code is not recommended; its contents are subject to change in future Docutils releases. Instead, i...
th=None, destination_path=None, input_encoding='unicode', settings_overrides=None): """ Return the document tree and publisher, for exploring Docutils internals. Parameters: see `html_parts()`. """ if settings_overrides: overrides = settings_overrides.copy() else: ...
.publish_programmatically( source_class=io.StringInput, source=input_string, source_path=source_path, destination_class=io.NullOutput, destination=None, destination_path=destination_path, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', ...
kelsoncm/django_brfied
django_brfied/management/commands/importar_uf_municipio.py
Python
mit
1,647
0.00365
from django.core.management.base import BaseCommand from django_brfied.models import UnidadeFederativa, Municipio from ...migrations import UNIDADE_FEDERATIVA_ROWS, MUNICIPIO_ROWS class Command(BaseCommand): help = "Importa as UFs e os Municípios para a base" # requires_system_checks = False # def __init...
print('UF importadas\n') print('Importando municípios') i =
1 q = len(MUNICIPIO_ROWS) for m in MUNICIPIO_ROWS: if i%500 == 0: print('\tImportados %3.2f%%' % ((i / q) * 100)) Municipio.objects.update_or_create(codigo=m[0], defaults={'nome': m[1], 'uf_id': m[2]}) i += 1 print('Municípios importados')
wheeler-microfluidics/zmq-plugin
zmq_plugin/_version.py
Python
lgpl-2.1
18,459
0
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also su...
th.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirn...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/neutronclient/tests/functional/test_clientlib.py
Python
mit
3,224
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 # d...
= discover.Discover(session=ks_session, auth_url=creds['auth_url']) # At the moment, we use keystone v2 AP
I v2_auth_url = ks_discover.url_for('2.0') ks_session.auth = v2_auth.Password( v2_auth_url, username=creds['username'], password=creds['password'], tenant_name=creds['tenant_name']) return v2_client.Client(session=ks_session) class LibraryTestCas...
PostCenter/botlang
tests/storage/test_storage_extensions.py
Python
mit
3,005
0.000333
import unittest from botlang import BotlangSystem from botlang.extensions.storage import StorageApi class DummyStore(StorageApi): def __init__(self): self.backend = {} def put(self, key, value, expiration=None): self.backend[key] = value def get(self, key): return self.backend....
caldb-get "test1")) (list "test2" (localdb-get "test2")) (list "got1" got1) (list "got2" got2) ) ) """) self.assertEqual(results['test1'], 444)
self.assertEqual(results['test2'], None) self.assertEqual(results['got1'], ':3') self.assertEqual(results['got2'], ':3') def test_global_storage(self): db = DummyStore() runtime = BotlangSystem.bot_instance().setup_global_storage(db) results = runtime.eval(""" ...
drivendata/countable-care-3rd-place
src/generate_feature9.py
Python
mit
2,602
0.001922
#!/usr/bin/env python from scipy import sparse from sklearn.datasets import dump_svmlight_file from sklearn.preprocessing import LabelEncoder import argparse import logging import numpy as np import os import pandas as pd from kaggler.util import encode_categorical_features, normalize_numerical_feature logging.bas...
zero_based=False)
dump_svmlight_file(df.values[n_trn:], np.zeros((n_tst,)), test_feature_file, zero_based=False) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--train-file', required=True, dest='train') parser.add_argument('--label-file', required=True, dest='...
JQIamo/artiq
artiq/test/lit/local_access/parallel.py
Python
lgpl-3.0
121
0
# RUN: %python -m artiq
.compiler.testbench.signature %s >%t with interleave: delay(1.0) t0 = no
w_mu() print(t0)
elewis33/doorstop
doorstop/core/vcs/veracity.py
Python
lgpl-3.0
959
0
"""Plug-in module to store requirements in a Veracity repository.""" from doorstop import common from doorstop.core.vcs.base import BaseWorkingCopy log = common.logger(__name__) class WorkingCopy(BaseWorkingCopy): """Veracity working copy.""" DIRECTORY = '.sgdrawer' IGNORES = ('.sgignores', '.vvignore...
'pull') self.call('vv', 'update') def edit(self, path): log.info("`vv` adds all changes") def add(self, path): self.call('vv', 'add', path) def delete(self, path):
self.call('vv', 'remove', path) def commit(self, message=None): message = message or input("Commit message: ") # pylint: disable=W0141 self.call('vv', 'commit', '--message', message) self.call('vv', 'push')
resmo/ansible
lib/ansible/modules/cloud/google/gcp_spanner_instance_info.py
Python
gpl-3.0
5,026
0.004377
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
project and between 4 and 30 characters in length. returned: success type: str nodeCount: description: - The number of nodes allocated to this instance.
returned: success type: int labels: description: - 'An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' returned: success type: dict ''' ######################################################################...
WilmerLab/HTSOHM-dev
analysis/figure_ml_vs_vf.py
Python
mit
2,118
0.010387
#!/usr/bin/env python3 import click import matplotlib import matplotlib.pyplot as plt from matplotlib import rc import numpy as np import pandas as pd prop1range = [0.0, 1.0] # VF prop2range = [0.0, 800.0] # ML num_ch4_a3 = 2.69015E-05 # from methane-comparison.xlsx fsl = fs = 8 rc('font',**{'family':'sans-serif','...
))/num_bins, minor=True) ax.set_yticks(prop2range[1] * np.array(range(0,num_bins + 1))/num_bins, minor=True) ax.tick_params(axis='x', which='major', labelsize=fs) ax.tick_params(axis='y', which='major', labelsize=fs) ax.grid(which='major', axis='both', linestyle='-', color='0.9', zorder=0) sc = a...
cmap=cm, vmin=-0.5, vmax=4.5) ax.set_xlabel('Void Fraction', fontsize=fsl) ax.set_ylabel('Methane Loading [V/V]', fontsize=fsl) # cb = fig.colorbar(sc, ax=ax) # cb.ax.tick_params(labelsize=fs) output_path = "figure.png" fig.savefig(output_path, dpi=1200, bbox_inches='tight') ...
Meriipu/quodlibet
gdist/__init__.py
Python
gpl-2.0
7,826
0
# Copyright 2007 Joe Wreschnig # 2012-2016 Christoph Reiter # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, ...
d to GTK+ and GObje
ct Python programs and libraries. Parameters (to distutils.core.setup): po_directory -- directory where .po files are contained po_package -- package name for translation files shortcuts -- list of .desktop files to build/install dbus_services -- list of .service files to build/install ...
blueyed/coveragepy
tests/farm/html/src/main.py
Python
apache-2.0
257
0
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # Fo
r details: https://github.com/nedbat/coveragepy/blob/mast
er/NOTICE.txt import m1 import m2 import m3 a = 5 b = 6 assert m1.m1a == 1 assert m2.m2a == 1 assert m3.m3a == 1
wdcxc/blog
admin/views/base.py
Python
mit
789
0.014157
import imp
ortlib from django.conf import settings from django.views import View class BaseView(View): """后台管理基类""" def __init__(self): self.context = {} self.context["path"] = {} def dispatch(self,request,*args,**kwargs): _path = request.path_info.split("/")[1:] self.context["path"][...
elf.context["path"]["action"] = _path[-1] imp_module_path = self.context["path"]["app"]+".views."+self.context["path"]["module"] imp_module = importlib.import_module(imp_module_path) imp_cls = getattr(imp_module,self.context["path"]["module"].capitalize()) return getattr(imp_cls,self.co...
nharraud/invenio
invenio/legacy/webstyle/templates.py
Python
gpl-2.0
27,002
0.004555
# This file is part of Invenio. # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, # 2013, 2014, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either versio...
CFG_SITE_URL from invenio_base.i18n import gettext_set_language, language_list_long from invenio.utils.url import make_canonical_urlargd, create_html_link from invenio.utils.date import convert_datecvs_to_datestruct from invenio_formatter import format_record from invenio.utils.html import get_mathjax_header c
lass Template: def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """Bootstrap friendly-Create navigation trail box body Parameters: - 'ln' *string* - The language to display - 'title' *string* - page title;...
KirarinSnow/Google-Code-Jam
Round 3 2008/D1.py
Python
gpl-3.0
2,492
0.006019
#!/usr/bin/python # # Problem: Endless Knight # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out # Comments: OK for large, but may time out on small. from itertools import * MOD = 10007 # Precompute factorial table mod MOD fact = [1] * MOD for i in xrange(1, MOD): fact[i]...
0 # normalize rock coordinates h, w = h-1-(h+w-2)/3, w-1-(h+w-2)/3 for i in range(r): row, col = rocks[
i] if (row+col-2)%3 != 0: rocks[i] = None else: rocks[i] = [row-1-(row+col-2)/3, col-1-(row+col-2)/3] if rocks[i][0] < 0 or rocks[i][0] > h: rocks[i] = None elif rocks[i][1] < 0 or rocks[i][1] > w: rocks[i] = None ...
treytabner/quickly
quickly/shell.py
Python
gpl-3.0
2,887
0
""" Quickly, quickly deploy and manage cloud servers Copyright (C) 2014 Trey Tabner <[email protected]> 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 opti...
resources.require('quickly')[0].version parser = argparse.ArgumentParser( version=version, description="Quickly deploy and manage cloud servers") parser.add_argument( "-n", "--no-action", dest='action', action='store_false', help="Perform no actions other than listing details") subp...
eploy and configure one or more servers in parallel") deploy_parser.add_argument( 'plan', help="File containing deployment plan in YAML format") manage_parser = subparsers.add_parser( 'manage', help="Manage one or more servers by executing commands") manage_parser.add_argument( 'pla...
KanoComputing/kano-feedback
kano_feedback/return_codes.py
Python
gpl-2.0
550
0
# return_codes.py # # Copyr
ight (
C) 2018 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Return codes of binaries used throughout this project. class RC(object): """Return codes of binaries used throughout this project. See ``source`` for more details.""" SUCCESS = 0 INCORRECT_ARGS = 1 NO_I...
plotly/python-api
packages/python/plotly/plotly/validators/scattermapbox/_hoverlabel.py
Python
mit
2,062
0.000485
import _plotly_utils.basevalidators class HoverlabelValidator(_plotly_utils
.basevalidators.CompoundValidator): def __init__(self, plotly_name="hoverlabel", parent_name="scattermapbox", **kwargs): super(HoverlabelValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Hoverlabel"),...
over label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for align . bgcolor Sets the background color of the hover labels ...
globocom/vault
identity/models.py
Python
apache-2.0
408
0
# -*- coding: utf-8 -*- from django.db import mode
ls class Project(models.Model): id = models.AutoField(primary_key=True) project =
models.CharField(max_length=255) user = models.CharField(max_length=255) password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'project' unique_together = (('project'),)
tszym/ansible
lib/ansible/modules/cloud/univention/udm_dns_zone.py
Python
gpl-3.0
7,158
0.00964
#!/usr/bin/python # -*- coding: UTF-8 -*- # Copyright (c) 2016, Adfinis SyGroup AG # Tobias Rueetschi <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ...
j.remove() changed = True except Exception as e: module.fail_json( msg='Removing dns zone {} failed: {}'.format(zone, e) ) module.exit_json( changed=changed, diff=diff, zon
e=zone ) if __name__ == '__main__': main()
ztop/psutil
psutil/_pslinux.py
Python
bsd-3-clause
40,128
0.0001
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Linux platform implementation.""" from __future__ import division import base64 import errno import os import re import socket ...
_CLASS_BE", "IOPRIO_CLASS_IDLE", # connection status constants "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1", "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT", "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", # other "phymem_buffers", "cached_phymem...
hasattr(cext, "linux_prlimit") # RLIMIT_* constants, not guaranteed to be present on all kernels if HAS_PRLIMIT: for name in dir(cext): if name.startswith('RLIM'): __extra__all__.append(name) # Number of clock ticks per second CLOCK_TICKS = os.sysconf("SC_CLK_TCK") PAGESIZE = os.sysconf("SC_PA...
oss/rutgers-repository-utils
setup.py
Python
gpl-2.0
858
0.039627
#!/usr/bin/env python """ Setup script for Rutgers Repository Utils. """ import distutils import sys from distutils.core import setup setup(name = 'rutgers-repository-utils', version = '1.3', de
scription = 'Python scripts for repository management', author = 'Open System Solutions', author_email = '[email protected]', url = 'https://github.com/oss/rutgers-repository-utils', license = 'GPLv2+', platforms = ['linux'], lo...
directories and do dependency checking.""", packages = ['repoutils'], package_dir = {'repoutils' : 'lib'})
FiveEye/ml-notebook
dlp/ch3_3_boston_housing.py
Python
mit
1,900
0.007368
import numpy as np import keras as ks import matplotlib.pyplot as plt from keras.datasets import boston_housing from keras import models from keras import layers from keras.utils.np_utils import to_categorical (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() mean = train_data.mean(...
num_val_samples : (i+1) * num_val_samples] val_targets = train_targets[i * num_val_samples : (i+1) * num
_val_samples] partial_train_data = np.concatenate([train_data[: i * num_val_samples], train_data[(i+1) * num_val_samples:]], axis=0) partial_train_targets = np.concatenate([train_targets[: i * num_val_samples], train_targets[(i+1) * num_val_samples:]], axis=0) model = build_model() history = model...
l-vincent-l/APITaxi
APITaxi/commands/warm_up_redis.py
Python
agpl-3.0
1,795
0.002786
from . import manager def warm_up_redis_func(app=None, db=None, user_model=None, redis_store=None): not_available = set() available = set() cur = db.session.connection().connection.cursor() cur.execute(""" SELECT taxi.id AS taxi_id, vd.status, vd.added_by FROM taxi LEFT OUTER JOIN vehicle ON veh...
if redis_store.type(app.config['REDIS_NOT_AVAILABLE']) != 'zset': redis_store.delete(app.config['REDIS_NOT_AVAILABLE'])
else: cursor, keys = redis_store.zscan(app.config['REDIS_NOT_AVAILABLE'], 0) keys = set([k[0] for k in keys]) while cursor != 0: to_remove.extend(keys.intersection(available)) not_available.difference_update(keys) cursor, keys = redis_store.zscan(app.config['...
wmizzi/tn2capstone
ServerScript/recievestore.py
Python
bsd-2-clause
1,705
0.017009
# created by Angus Clark 9/2/17 updated 27/2/17 # ToDo impliment traceroute function into this # Perhaps get rid of unnecessary itemediate temp file import socket import os import json import my_traceroute s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '130.56.253.43' #print host port = 5201 # Change ...
0])].update({'node':result[1], 'rtt':result[2]}) last_addr = result[1] id = info["UserInfo"]["user id"] timestamp = info["UserInfo"]["timestamp"] os.system('mkdir /home/ubuntu/data/'+id) path = "/home/ubuntu/data/" + id + "/" filename = timestamp + '.json' ...
savefile = open(path + filename, 'w+') savefile.write(json.dumps(info)) savefile.close()
matcatc/Test_Parser
src/TestParser/View/Tkinter/__init__.py
Python
gpl-3.0
714
0.002801
''' @date Aug 28, 2010 @author: Matthew A. Todd This file is part of Test Parser by Ma
tthew A. Todd Test Parser 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. Test Parser is distributed in the hope that it will be useful, bu...
E. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Test Parser. If not, see <http://www.gnu.org/licenses/>. '''
kvesteri/validators
tests/test_between.py
Python
mit
863
0
# -*- coding: utf-8 -*- import pytest import validators @pytest.mark.parametrize(('
value', 'min', 'max'), [ (12, 11, 13), (12, None, 14), (12, 11, None), (12, 12, 12) ]) def test_returns_true_on_valid_range(value, min, max): assert validators.between(value, min=min, max=max) @pytest.mark.parametrize(('value', 'min', 'max'), [ (12, 13, 12), (12, None, None), ]) def test_r...
valid_args(value, min, max): with pytest.raises(AssertionError): assert validators.between(value, min=min, max=max) @pytest.mark.parametrize(('value', 'min', 'max'), [ (12, 13, 14), (12, None, 11), (12, 13, None) ]) def test_returns_failed_validation_on_invalid_range(value, min, max): resu...
dlab-berkeley/collaboratool-archive
bsd2/vagrant-ansible/ansible/lib/ansible/playbook/play.py
Python
apache-2.0
27,767
0.005258
# (c) 2012-2013, 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...
e_name path = utils.path_dwim(self.basedir, os.path.joi
n('roles', orig_path)) if not os.path.isdir(path) and not orig_path.startswith(".") and not orig_path.startswith("/"): path2 = utils.path_dwim(self.basedir, orig_path) if not os.path.isdir(path2): raise errors.AnsibleError("cannot find role in %s or %s" % (path, path2)) ...
Thielak/program-y
src/programy/parser/template/maps/predecessor.py
Python
mit
1,445
0.00692
""" Copyright (c) 2016 Keith Sterling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,...
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import logging from programy.parser.template.maps.map import TemplateMap class PredecessorMap(TemplateMap): NAME ...
alue): int_value = int(value) str_value = str(int_value - 1) return str_value
xlcteam/scoreBoard
scorebrd/migrations/0009_auto__del_field_group_results.py
Python
bsd-3-clause
7,683
0.00807
# -*- 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): # Deleting field 'Group.results' db.delete_column('scorebrd_group', 'results_id') # Adding M2M tabl...
ls.fields.IntegerField', [], {'default': '0'}),
'goal_diff': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'goal_shot': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'loses': ('django.db.models.fields.IntegerFie...
hoelsner/product-database
django_project/views.py
Python
mit
7,479
0.002139
import logging import redis from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import PasswordChangeView from django.http import H...
.state.lower() == TaskState.PROCESSING: response = {
"state": "processing", "status_message": task.info.get("status_message", "") } elif task.state == TaskState.SUCCESS: response = { "state": "success", "status_message": task.info.get("status_message"...
neurobin/test
test1.py
Python
mit
876
0.001142
#!/usr/bin/env python """@package letsacme ################ letsacme ################### This script automates the process of getting a signed TLS/SSL certificate from Let's Encrypt using the ACME protocol.
It will need to be r
un on your server and have access to your private account key. It gets both the certificate and the chain (CABUNDLE) and prints them on stdout unless specified otherwise. """ import argparse # argument parser import subprocess # Popen import json # json.loads import os # os.path import sys ...
jawilson/home-assistant
homeassistant/components/edl21/sensor.py
Python
apache-2.0
11,383
0.000264
"""Support for EDL21 Smart Meters.""" from __future__ import annotations from datetime import timedelta import logging from sml import SmlGetListResponse from sml.asyncio import SmlProtocol import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const imp...
not in self._OBIS_BLACKLIST: _LOGGER.warning( "Unhandled sensor %s detected. Please report at " 'https://github.com/home-assistant/core/issues?q=is%%3Aissue+label%%3A"integration%%3A+edl21"+', obis, ) ...
ync def add_entities(self, new_entities) -> None: """Migrate old unique IDs, then add entities to hass.""" registry = await async_get_registry(self._hass) for entity in new_entities: old_entity_id = registry.async_get_entity_id( "sensor", DOMAIN, entity.old_unique_id...
sahlinet/fastapp
fastapp/migrations/0011_thread_updated.py
Python
mit
451
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('fastapp', '0010_auto_20150910_2010'), ] operations = [ migrations.AddField( model_name='thread', nam...
ated', field=models.DateTimeField(auto_now=True, null=True), p
reserve_default=True, ), ]
renanalencar/congrefor
congrefor/wsgi.py
Python
mit
296
0.013514
import os os.environ.setdefault("DJANGO_SE
TTINGS_MODULE", "congrefor.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() #from django.core.wsgi import get_wsgi_application #from dj_static import Cling #application = C
ling(get_wsgi_application())
pasko-evg/Python-2014
Lecture03/lecture_03.py
Python
unlicense
321
0
# coding=utf-8 # Лекция http://uneex.ru/LecturesCMC/PythonIntro2014/03_DataTypes import decimal import random # print decimal.Decimal(1.1) + decima
l.Decimal(1.1) # print decimal.Decimal
("1.1") + decimal.Decimal("1.1") # print dir(random) a = [] for j in range(0, 10): a.append(random.randrange(100)) print a