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 |
|---|---|---|---|---|---|---|---|---|
gr33ndata/19898 | nineteen898/twapi.py | Python | mit | 3,510 | 0.004843 | import os
import json
import yaml
import base64
import requests
class TWAPI:
def __init__(self, config_file='../config.yml'):
#print os.getcwd()
self.config_file = config_file
self.key = ''
self.secret = ''
self.bearer = ''
self.load_conf()
#self.show_c... | token=token, max_posts=count)
else:
print r.status_code
def get_users(self, users='', count=10):
url = 'https://api.twitter.com/oauth2/token'
payload = {
'grant_type': 'client_credentials | '
}
headers = {
'Authorization': 'Basic ' + self.bearer,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
r = requests.post(url, data=payload, headers=headers)
if r.status_code == 200:
token = r.json()["access_token"]
... |
fiete201/qutebrowser | scripts/asciidoc2html.py | Python | gpl-3.0 | 11,655 | 0.000343 | #!/usr/bin/env python3
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <[email protected]>
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pub... | details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Generate the html documentation based on the asciidoc files."""
from typing import List, Optional
import re
import os
import sys
import subprocess
import shutil
imp... | rt pathlib
REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
DOC_DIR = REPO_ROOT / 'qutebrowser' / 'html' / 'doc'
sys.path.insert(0, str(REPO_ROOT))
from scripts import utils
class AsciiDoc:
"""Abstraction of an asciidoc subprocess."""
FILES = ['faq', 'changelog', 'contributing', 'quickstart', 'use... |
DramaFever/sst | src/sst/selftests/by_xpath.py | Python | apache-2.0 | 989 | 0 | import sst
import sst.actions
# xpath locator tests
#
# see: http://seleniumhq.org/docs/appendix_locating_techniques.html
sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')
sst.actions.get_element_by_xpath("//p[contains(@class, 'unique_class')]")
sst.actions.get_element_by_... | ents_by_xpath('//p')
sst.actions.get_elements_by_xpath("//p[contains(@class, 'some_class')]")
sst.actions.fails(
sst.actions.get_element_by_xpath, '//doesnotexist')
sst.actions.fails(
sst.actions.get_element_by_xpath, "//a[contains(@id, 'doesnotexist')]")
assert len(sst.actions.get_elements_by_xpath(
'//d... | s.get_elements_by_xpath(
"//p[contains(@class, 'some_class')]"
)) == 2
|
mahirrudin/easy-octopress | windows/ez_setup.py | Python | mit | 11,369 | 0.002199 | #!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, ... | dst = None
try:
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(target, "wb")
dst.write(data)
finally:
| if src:
src.close()
if dst:
dst.close()
download_file_insecure.viable = lambda: True
def get_best_downloader():
downloaders = [
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
]
for dl in downloaders... |
mattilyra/gensim | gensim/test/test_corpora_dictionary.py | Python | lgpl-2.1 | 12,494 | 0.000963 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Unit tests for the `corpora.Dictionary` class.
"""
from collections import Mapping
import logging
import unittest
import codecs
import os
import os.path
import scipy
import gensim
from gens... | uman) should exist
expected = {'human': 0}
| self.assertEqual(d.token2id, expected)
# three docs
texts = [['human'], ['human'], ['human']]
d = Dictionary(texts)
expected = {0: 3}
self.assertEqual(d.dfs, expected)
# only one token (human) should exist
expected = {'human': 0}
self.assertEqual(... |
FRC900/2016VisionCode | preseason_edge_detection/edge_detection.py | Python | mit | 1,892 | 0.048626 | # edge detection and colorspaces, includes laplacian and sobel filters that are tuned to the pink whiffle ball
import cv2
import numpy as np
def nothing(x):
pass
cap = cv2.VideoCapture(0)
cv2.namedWindow('frame1')
kernel = np.ones((5,5),np.uint8)
# create trackbars for color change, tuned to pink whiffle ball
#... |
# define range of color in HSV
lower = np.array([hLo,sLo,vLo])
upper = np.array([hUp,sUp,vUp])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower, upper)
# Bitwise-AND mask and original ima | ge
res = cv2.bitwise_and(frame,frame, mask= mask)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
laplacian = cv2.Laplacian(closing,cv2.CV_64F)
sobelx = cv2.Sobel(closing,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(closing,cv2.CV_64F,0,1,ksize=... |
837468220/python-for-android | python3-alpha/python3-src/Lib/test/test_codecs.py | Python | apache-2.0 | 64,172 | 0.00173 | from test import support
import unittest
import codecs
import locale
import sys, _testcapi, io
class Queue(object):
"""
queue: write bytes at one end, read bytes from the other end
"""
def __init__(self, buffer):
self._buffer = buffer
def write(self, chars):
self._buffer += chars
... | n
# of input to the reader | byte by byte. Read everything available from
# the StreamReader and check that the results equal the appropriate
# entries from partialresults.
q = Queue(b"")
r = codecs.getreader(self.encoding)(q)
result = ""
for (c, partialresult) in zip(input.encode(self.encoding), pa... |
yotomyoto/benzene-vanilla | tournament/summary.py | Python | lgpl-3.0 | 9,376 | 0.005546 | #!/usr/bin/python -u
#----------------------------------------------------------------------------
# Summarizes a twogtp tournament.
#
# TODO: - Simplify stuff. The table idea seems bad, in retrospect.
# - Do we really care about which openings are won/lost?
import os, sys, getopt, re, string
from statistics imp... | progs = []
p1Timeouts = 0.0
p2Timeouts = 0.0
while line != "":
if line[0] != "#":
array = string.split(line, "\t")
fullopening = array[2]
black = array[3]
white = array[4]
bres = array[5]
wres = array[6]
... | array[7]
timeBlack = float(array[8])
timeWhite = float(array[9])
if longOpening:
opening = string.strip(fullopening)
else:
moves = string.split(string.strip(fullopening), ' ')
opening = moves[0]
considerGame = ... |
PhonologicalCorpusTools/PolyglotDB | polyglotdb/corpus/lexical.py | Python | mit | 2,263 | 0.003093 | from ..io.importer import lexicon_data_to_csvs, import_lexicon_csvs
from ..io.enrichment.lexical import enrich_lexicon_from_csv, parse_file
from .spoken import SpokenContext
class LexicalContext(SpokenContext):
"""
Class that contains methods for dealing specifically with words
"""
def enrich_lexicon(... | _csvs(self, lexicon_data, case_sensitive=case_sensitive)
import_lexicon_csvs(self, type_data, case_sensitive=case_sensitive)
self.hierarchy.add_type_properties(self, self.word_name, type_data.items())
self.encode_hierarchy()
def enrich_lexicon_from_csv(self, path, case_sensitive=False):
... | boolean
Defaults to false
"""
enrich_lexicon_from_csv(self, path, case_sensitive)
def reset_lexicon_csv(self, path):
"""
Remove properties that were encoded via a CSV file
Parameters
----------
path : str
CSV file to get property nam... |
mythmon/edwin | edwin/bundles.py | Python | mpl-2.0 | 584 | 0 | class BundleConfiguration(object):
def PIPELINE_CSS(self):
return {
'client': {
| 'source_filenames': [
'font-awesome/css/font-awesome.css',
'css/client.less',
],
'output_filename': 'css/client.css',
},
}
def PIPELINE_JS(self):
return {
'client': {
'source_filenam... | .browserify.js',
],
'output_filename': 'js/client.js',
},
}
|
mhbu50/erpnext | erpnext/accounts/doctype/accounts_settings/accounts_settings.py | Python | gpl-3.0 | 2,701 | 0.01666 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.custom.doctype.property_setter.property_setter import make_property_setter
from frappe.model.... | type, "payment_schedule", "print_hide", 0 if show_in_print else 1, "Check", validate_fields_for_doctype=False)
def toggle_discount_accounting_fields(self):
enabl | e_discount_accounting = cint(self.enable_discount_accounting)
for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
if enable_discount_accounting:
make_property... |
dbrattli/RxPY | examples/autocomplete/autocomplete.py | Python | apache-2.0 | 2,765 | 0.005787 | """
RxPY example running a Tornado server doing search queries against Wikipedia to
populate the autocomplete dropdown in the web UI. Start using
`python autocomplete.py` and navigate your web browser to http://localhost:8080
Uses the RxPY IOLoopScheduler (works on both Python 2.7 and 3.4)
"""
import os
from tornad... | url = 'http://en.wikipedia.org/w/api.php'
params = {
"action": 'opensearch',
"search | ": term,
"format": 'json'
}
# Must set a user agent for non-browser requests to Wikipedia
user_agent = "RxPY/1.0 (https://github.com/dbrattli/RxPY; [email protected]) Tornado/4.0.1"
url = url_concat(url, params)
http_client = AsyncHTTPClient()
return http_client.fetch(url, method... |
gimli-org/gimli | pygimli/frameworks/methodManager.py | Python | apache-2.0 | 29,010 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Method Manager
Provide the end user interface for method (geophysical) dependent
modelling and inversion as well as data and model visualization.
"""
import numpy as np
import pygimli as pg
from pygimli.utils import prettyFloat as pf
def fit(funct, data, err=None, ... | fop=None, fw=None, data=None, **kwargs):
"""Constructor."""
self._fop = fop
self._fw = fw
# we hold our own copy of the data
self._verbose = kwargs.pop('verbose', False)
self._debug = kwargs.pop('debug', False)
| self.data = None
if data is not None:
if isinstance(data, str):
self.load(data)
else:
self.data = data
# The inversion framework
self._initInversionFramework(verbose=self._verbose,
debug=self._d... |
benatkin/tuneage | urls.py | Python | mit | 511 | 0.001957 | from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
import os
admin.autodiscover()
urlpatterns = patterns('',
('^$', 'django.views.generic.simple.redirect_to', {'url': '/admin/'}),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin... | l(
r'^med | ia/(.*)$',
'django.views.static.serve',
kwargs={'document_root': os.path.join(settings.PROJECT_PATH, 'media')}
),
)
|
berdario/RangeHTTPServer | RangeHTTPServer.py | Python | apache-2.0 | 4,567 | 0.000876 | #!/usr/bin/python
'''
Use this in the same way as Python's http.server / SimpleHTTPServer:
python -m RangeHTTPServer [port]
The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports
'Range:' headers to load portions of files. This is helpful for doing local web
development with genomi... | s RangeRequestHandler(SimpleHTTPRequestHandler):
"""Adds support for HTTP 'Range' requests to SimpleHTTPRequestHandler
The approach is to:
- Override send_head to look for 'Range' and respond appropriately.
- Override copyfile to only | transmit a range when requested.
"""
def send_head(self):
if 'Range' not in self.headers:
self.range = None
return SimpleHTTPRequestHandler.send_head(self)
try:
self.range = parse_byte_range(self.headers['Range'])
except ValueError as e:
s... |
MicroPyramid/Django-CRM | teams/models.py | Python | mit | 1,068 | 0 | import arrow
from django.db import models
from common.models import Org, Profile
from django.utils.translation import ugettext_lazy as _
class Te | ams(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
users = models.ManyToManyField(Profile, related_name="user_teams")
created_on = models.DateTimeField(_("Cr | eated on"), auto_now_add=True)
created_by = models.ForeignKey(
Profile,
related_name="teams_created",
blank=True,
null=True,
on_delete=models.SET_NULL,
)
org = models.ForeignKey(
Org, on_delete=models.SET_NULL, null=True, blank=True
)
class Meta:
... |
444thLiao/VarappX | varapp/migrations/0001_initial.py | Python | gpl-3.0 | 10,400 | 0.002788 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-11 12:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GeneDet... | )),
('gerp_element_pval', models.FloatField(blank=True, null=True)),
('gene_symbol', models.TextField(blank=True, db_column='gene')),
('transcript', models.TextField(blank=True)),
('exon', models.TextField(blank=True)),
| ('is_exonic', models.NullBooleanField()),
('is_coding', models.NullBooleanField()),
('is_lof', models.NullBooleanField()),
('codon_change', models.TextField(blank=True)),
('aa_change', models.TextField(blank=True)),
('impact', mo... |
Valloric/ycmd | update_api_docs.py | Python | gpl-3.0 | 1,822 | 0.036224 | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import platform
import sys
import subprocess
DIR_OF_THIS_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_DOCS = os.path.... | enapi.yml' )
subprocess.call( [ bootprint, 'openapi', api, DIR_OF_DO | CS ] )
if __name__ == '__main__':
GenerateApiDocs()
|
RGD2/swapforth | esp8266/esptool2.py | Python | bsd-3-clause | 30,932 | 0.004364 | #!/usr/bin/env python
#
# ESP8266 ROM Bootloader Utility
# https://github.com/themadinventor/esptool
#
# Copyright (C) 2014 Fredrik Ahlberg
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; eith... | size, blocks, blocksize, offset))[1] != "\0\ | 0":
ra |
sstoma/CellProfiler | cellprofiler/modules/trackobjects.py | Python | gpl-2.0 | 137,657 | 0.005688 | from cellprofiler.gui.help import USING_METADATA_HELP_REF, USING_METADATA_GROUPING_HELP_REF, LOADING_IMAGE_SEQ_HELP_REF
TM_OVERLAP = 'Overlap'
TM_DISTANCE = 'Distance'
TM_MEASUREMENTS = 'Measurements'
TM_LAP = "LAP"
TM_ALL = [TM_OVERLAP, TM_DISTANCE, TM_MEASUREMENTS,TM_LAP]
LT_NONE = 0
LT_PHASE_1 = 1
LT_SPLIT = 2
LT_... | circumstances:
<ul>
<li>At the beginning o | f a trajectory, when there is no data to determine the model as
yet.</li>
<li>At the beginning of a closed gap, since a model was not actually applied to make
the link in the first phase.</li>
</ul></li>
</ul>
</li>
<li><i>LinkingDistance:</i>The difference between the propagated position of an
object and the object ... |
katchengli/tech-interview-prep | interview_cake/ic24.py | Python | apache-2.0 | 777 | 0.005148 | class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def reverseLinkedList(head):
originalPointer = head
newHead = None
secondNew = None
while originalPointer != None:
newHead = originalPointer
originalPointer = originalPointer.nex... | de(3)
node4 = LinkedListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = None
newHead = reverseLinkedList(node1)
while newHead != None:
print(newHead.value)
newHead = new | Head.next
print(reverseLinkedList(None))
print(reverseLinkedList(LinkedListNode(6)).value)
|
mxOBS/deb-pkg_trusty_chromium-browser | v8/tools/push-to-trunk/bump_up_version.py | Python | bsd-3-clause | 7,906 | 0.006957 | #!/usr/bin/env python
# Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for auto-increasing the version on bleeding_edge.
The script can be run regularly by a cron job. It will increase the bui... | yToVersion("lkgr_")
print "LKGR version: %s" % self["lkgr_version"]
# Ensure a clean version branch.
self.GitCheckout("master")
self.DeleteBranch(VERSION_BRANCH)
class LKGRVersionUpToDateBailout(Step):
MESSAGE = "Stop script if the lkgr has a renewed version."
def RunStep(self):
# If a versi... | iles(self["lkgr"]):
print "Stop because the lkgr is a version change itself."
return True
# Don't bump up the version if it got updated already after the lkgr.
if SortingKey(self["lkgr_version"]) < SortingKey(self["latest_version"]):
print("Stop because the latest version already changed sinc... |
openatv/enigma2 | lib/python/timer.py | Python | gpl-2.0 | 10,631 | 0.027091 | from bisect import insort
from time import time, localtime, mktime
from enigma import eTimer, eActionMap
import datetime
class TimerEntry:
StateWaiting = 0
StatePrepared = 1
StateRunning = 2
StateEnded = 3
StateFailed = 4
def __init__(self, begin, end):
self.begin = begin
self.prepare_time = 20
self.end ... | esetRepeated()
#begindate = localtime(self.begin)
#newdate = datetime.datetime(begindate.tm_year, begindate.tm_mon, begindate.t | m_mday 0, 0, 0);
self.repeatedbegindate = begin
self.backoff = 0
self.disabled = False
self.failed = False
def resetState(self):
self.state = self.StateWaiting
self.cancelled = False
self.first_try_prepare = 0
self.findRunningEvent = True
self.findNextEvent = False
self.timeChanged()
def resetR... |
tynn/numpy | numpy/core/numeric.py | Python | bsd-3-clause | 87,411 | 0.000114 | from __future__ import division, absolute_import, print_function
try:
# Accessing collections abstract classes from collections
# has been deprecated since Python 3.3
import collections.abc as collections_abc
except ImportError:
import collections as collections_abc
import itertools
import operator
imp... | broadcast', 'dtype',
'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where',
'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
'result_type', 'asarray', 'asanyarray', 'ascontiguousarray',
| 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'require',
'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
'isclose', 'load', ... |
VipulSarin/citenet | scopus_module/insert_papers.py | Python | gpl-3.0 | 2,317 | 0.022874 | from py2neo import authenticate, Graph, Node, Relationship
from scopus.scopus_api import ScopusAbstract
from paper_abstract import *
import pdb
import argparse
import json
import os
import sys
reload (sys)
sys.setdefaultencoding('UTF-8')
def init_arg_parser():
parser = argparse.ArgumentParser()
parser.add_arg... | er,count)
(filen | ame,server,port) = init_arg_parser()
filename=filename.replace("\n","")
authenticate(server+":"+port, "neo4j", "3800")
graph = Graph()
with open(filename) as f:
paper_ids = f.readlines()
paper_ids = [x.strip('\n') for x in paper_ids]
completed = 0
data={}
data['total']=len(paper_ids)
data['completed']=completed
ou... |
ossanna16/django-rest-framework | tests/test_schemas.py | Python | bsd-2-clause | 28,125 | 0.002133 | import unittest
import pytest
from django.conf.urls import include, url
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase, override_settings
from rest_framework import filters, pagination, permissions, serializers
from rest_framework.compat import cor... | tFields)
def custom_action_with_list_fields(self, request, pk):
"""
A custom action using both list field and list serializer in the serializer.
"""
return super(ExampleSerializer, self).retrieve(self, request)
| @list_route()
def custom_list_action(self, request):
return super(ExampleViewSet, self).list(self, request)
@list_route(methods=['post', 'get'], serializer_class=EmptySerializer)
def custom_list_action_multiple_methods(self, request):
return super(ExampleViewSet, self).list(self, request)
... |
rspavel/spack | lib/spack/spack/modules/common.py | Python | lgpl-2.1 | 30,792 | 0 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Here we consolidate the logic for creating an abstract description
of the information that module systems need.
This i... | ance(value, dict):
update_dictionary_extending_lists(target[key], update[key])
else:
target[k | ey] = update[key]
def dependencies(spec, request='all'):
"""Returns the list of dependent specs for a given spec, according to the
request passed as parameter.
Args:
spec: spec to be analyzed
request: either 'none', 'direct' or 'all'
Returns:
list of dependencies
The... |
chemelnucfin/tensorflow | tensorflow/python/keras/layers/lstm_v2_test.py | Python | apache-2.0 | 37,712 | 0.002864 | # Copyright 2018 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... | nh', 'sigmoid', 0, True, True),
('not_use_bias', 'tanh', 'sigmoid', 0, False, False),
)
def test_could_use_defun_backend(self, activation, recurrent_activation,
recurrent_dropout, unroll, use_bias):
layer = rnn.LSTM(
1,
activation=activation,
recu... | =unroll,
use_bias=use_bias)
self.assertFalse(layer.could_use_cudnn)
def test_static_shape_inference_LSTM(self):
# Github issue: 15165
timesteps = 3
embedding_dim = 4
units = 2
model = keras.models.Sequential()
inputs = keras.layers.Dense(
embedding_dim, input_shape=(times... |
mozilla/elasticutils | elasticutils/tests/test_mlt.py | Python | bsd-3-clause | 3,116 | 0 | from nose.tools import eq_
from elasticutils import MLT
from elasticutils.tests import ESTestCase
|
class MoreLikeThisTest(ESTestCase):
data = [
{'id': 1, 'foo': 'bar', 'tag': 'awesome'},
{'id': 2, 'foo': 'bar', 't | ag': 'boring'},
{'id': 3, 'foo': 'bar', 'tag': 'awesome'},
{'id': 4, 'foo': 'bar', 'tag': 'boring'},
{'id': 5, 'foo': 'bar', 'tag': 'elite'},
{'id': 6, 'foo': 'notbar', 'tag': 'gross'},
{'id': 7, 'foo': 'notbar', 'tag': 'awesome'},
]
def test_bad_mlt(self):
"""Te... |
gperciva/artifastring | research/mode-detect/plot-harmonics.py | Python | gpl-3.0 | 3,185 | 0.009733 | #!/usr/bin/env python
import os.path
import sys
import glob
import numpy
import pylab
import expected_frequencies
import defs
import stft
import partials
try:
dirname = sys.argv[1]
except:
print "Need dirname, and optional maximum frequency"
try:
min_freq = float(sys.argv[2])
max_freq = float(sys.a... | ame(wav_filename)
filenames.sort()
Bs = numpy.loadtxt(os.path.join(base_filename, 'Bs.txt'))
SAMPLE_RATE, base_freq, B, limit, below, abo | ve = Bs
limit = int(limit)
num_harms = None
for i, filename in enumerate(filenames):
seconds = i*HOPSIZE / float(SAMPLE_RATE)
if seconds > MAX_SECONDS:
print "Reached time cutoff of %.1f" % MAX_SECONDS
return
print i, filename
fft = numpy.loadtxt(filen... |
rexzhang/rpress | rpress/views/rpadmin/settings.py | Python | gpl-3.0 | 1,428 | 0.002101 | #!/usr/bin/env python
# coding=utf-8
import flask
from flask import flash
from flask_login import login_required
from rpress.models import SiteSetting
from rpress.database import db
from rpress.runtimes.rpadmin.template import render_template, navbar
from rpress.runtimes.current_session import get_current_site, get_... | _setting is None:
site_set | ting = SiteSetting(
site_id=site.id,
key=key,
value=None,
)
form = SettingsForm(obj=site_setting)
if form.validate_on_submit():
form.populate_obj(site_setting)
db.session.add(site_setting)
db.session.commit()
flash("settings updated... |
repodono/repodono.jobs | src/repodono/jobs/sanic.py | Python | gpl-2.0 | 5,298 | 0 | # -*- coding: utf-8 -*-
"""
Sanic implementation
"""
from sanic import response
from sanic import Blueprint
from random import getrandbits
class JobServer(object):
"""
A basic job server that will setup a couple routes.
The target usage is to encapsulate and expose a service that takes
some input a... | 'Location': '/%s/%s' % (self.route_poll, job_id),
},
| status=201,
)
@blueprint.route(route_poll)
async def poll(request, job_id):
if job_id not in self.mapping:
return self._error(error_msg='no such job_id', status=404)
# XXX whenever the API for dealing with the actual Popen
# objects ... |
robocomp/learnbot | learnbot_dsl/functions/proprioceptive/base/near_to_target.py | Python | gpl-3.0 | 232 | 0.038793 | import ma | th as m
def near_to_target(lbot, targetX, targetY, nearDist = 50):
x, y, alpha = lbot.getPose()
distToTarget = m.sqrt(m.pow(x-targetX, 2) + m.pow(y-targetY, 2))
if distToTarget <= nearDist: |
return True
return False
|
armet/python-armet | armet/__init__.py | Python | mit | 363 | 0 | # -*- coding: utf-8 -*-
from __future__ im | port absolute_import, unicode_literals, division
from ._version import __version__, __version_info__ # noqa
from .decorators import route, resource, asynchronous
from .helpers import use
from .relationship import Relationship
__all__ = [
'route',
'resource',
'asynchronous',
| 'use',
'Relationship'
]
|
google/citest | citest/base/base_test_case.py | Python | apache-2.0 | 8,010 | 0.004494 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | execution.
self.__final_outcome_relation = None
self.__in_step = None
setattr(self, self.__method_name, self.__wrap_method)
super(BaseTestCase, self).__init__(methodName)
def __wrap_method(self):
# Wraps the calls to the actual test method so we have visibility.
#
# | When __call__ passes control to the base class, it will call this method
# after it has called setup. When we pass control back after this method,
# the base class will call teardown.
#
# Note this comment is not a string so that the TestRunner
# will not reflect on its comment.
self.__end_step... |
louyihua/edx-platform | lms/djangoapps/instructor_task/tests/test_models.py | Python | agpl-3.0 | 4,163 | 0.001922 | """
Tests for instructor_task/models.py.
"""
import copy
from cStringIO import StringIO
import time
import boto
from django.conf import settings
from django.test import SimpleTestCase, override_settings
from mock import patch
from common. | test.utils import MockS3Mixin
from instructor_task.models import ReportStore
fr | om instructor_task.tests.test_base import TestReportMixin
from opaque_keys.edx.locator import CourseLocator
class ReportStoreTestMixin(object):
"""
Mixin for report store tests.
"""
def setUp(self):
super(ReportStoreTestMixin, self).setUp()
self.course_id = CourseLocator(org="testx", c... |
PhilHarnish/forge | src/data/graph/multi/multi_walk.py | Python | mit | 1,190 | 0.008403 | import collections
from typing import Dict, Iterable, List, Union
from data import types
from data.graph import bloom_node, walk as walk_internal
Expression = bloom_node.BloomNode
Expressions = Union[List[Expression], Dict[str, Expression]]
WeightedWords = Union[List[types.WeightedWord], Dict[str, types.WeightedWord]... | _iter__(self) -> Iterable[ResultSet]:
if not self._expressions:
return
sources = [(k, walk_internal.walk(v)) for k, v in self._expressions.items()]
values = [(k, next(v, _EXHAUSTED)) for k, v in sources]
if not any(v is _EXHAUSTED for _, v in values):
yield ResultSet(dict(values))
def walk... | ons)
|
carlosb/scicomp | scicomp/rootfind/rootfindpack.py | Python | gpl-3.0 | 11,013 | 0 | """
Root finding methods
====================
Routines in this module:
bisection(f, a, b, eps=1e-5)
newton1(f, df, eps=1e-5)
newtonn(f, J, x0, eps=1e-5)
secant(f, x0, x1, eps=1e-5)
inv_cuadratic_interp(f, a, b, c, eps=1e-5)
lin_fracc_interp(f, a, b, c, eps=1e-5)
broyden(f, x0, B0, eps=1e-5)
"""
import numpy as np
'... | if(abs(x_old - x_new) <= eps):
break
except(ZeroDivisionError):
return np.nan
root = x_new
return root, iterations
def secant(f, x0, x1, eps=1e-5, display=False):
"""
Parameters
----------
f : f | unction
Function we want to find the root of.
x0 : float
First initial value "close" to the root of f.
x1: float
Second initial value "close" to the root of f.
eps : float
Tolerance.
Returns
-------
root : float
Root of f.
iterations : int
Num... |
artyomboyko/log-analysis | log_reader.py | Python | mit | 2,330 | 0.002575 | import time
import asyncio
from aiokafka import AIOKafkaProducer
from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC
class LogStreamer:
def __init__(self,
KAFKA_SERVERS,
KAFKA_TOPIC,
loop,
savepoint_file,
log_fi... | p_s | ervers=KAFKA_SERVERS)
self.savepoint_file = savepoint_file
self.log_file = log_file
async def produce(self, finite=False):
last = self.savepoint_file.read()
if last:
self.log_file.seek(int(last))
skip_first_empty = True
while True:
line = sel... |
JoaquimPatriarca/senpy-for-gis | gasp/frompsql.py | Python | gpl-3.0 | 3,280 | 0.014024 | """
PostgreSQL Database data to Python Object/Array
"""
from gasp.pgsql import connection
def sql_query(conParam, query, encoding=None):
"""
Retrive data from a SQL query
"""
conn = connection(conParam)
if encoding:
conn.set_client_encoding(encoding)
cursor = conn.cursor()
... | _columns_name
from gasp import goToList
cols = get_columns_name(pgCon, pgTable) if not cols else \
goToList(cols)
data = sql_query(
pgCon,
'SELECT {cols_} FROM {table}'.format(
cols_=', '.join(cols),
table=pgTable
)
)
... | t sanitizeColsName:
from gasp.pgsql import pgsql_special_words
for i in range(len(cols)):
if cols[i][1:-1] in pgsql_special_words():
cols[i] = cols[i][1:-1]
return [
{cols[i] : row[i] for i in range(len(cols))} for row in data
]
def sql_query_with_inner... |
SedFoam/sedfoam | tutorials/Py/plot_tuto1DBedLoadTurb.py | Python | gpl-2.0 | 3,062 | 0.010124 | import subprocess
import sys
import numpy as np
import fluidfoam
import matplotlib.pyplot as plt
plt.ion()
############### Plot properties #####################
import matplotlib.ticker as mticker
from matplotlib.ticker import StrMethodFormatter, NullFormatter
from matplotlib import rc
#rc('font',**{'family':'sans-ser... | ##
# Load DEM data
######################
zDEM, phiDEM, vxPDEM, vxFDEM, TDEM = np.loadtxt('DATA/BedloadTurbDEM.txt', unpack=True)
######################
#Read SedFoam results
######################
sol = '../1DBedLoadTurb/'
try:
proc = subprocess.Popen(
["foamListTimes", "-latestTime", "-case", sol],
... | oc.stdout.read() #to obtain the output of function foamListTimes from the subprocess
timeStep = output.decode().rstrip().split('\n')[0] #Some management on the output to obtain a number
#Read the data
X, Y, Z = fluidfoam.readmesh(sol)
z = Y
phi = fluidfoam.readscalar(sol, timeStep, 'alpha_a')
vxPart = fluidfoam.readve... |
adammaikai/OmicsPipe2.0 | omics_pipe/modules/RNAseq_QC.py | Python | mit | 1,409 | 0.036196 | #!/usr/bin/env python
from omics_pipe.parameters.default_parameters import default_parameters
from omics_pipe.utils import *
p = Bunch(default_parameters)
def RNAseq_QC(sample, RNAseq_QC_flag):
'''Runs picard rnaseqmetrics and insertsize estimation
input:
.bam
output:
pdf plot
... | R_VERSION:
'''
spawn_job(jobname = 'RNAseq_QC', SAMPLE = sample, LOG_PATH = p.OMICSPIPE["LOG_PATH"], RESULTS_EMAIL = p.OMICSPIPE["EMAIL"], SCHEDULER = p.OMICSPIPE["SCHEDULER"], walltime = p.RNASEQQC["WALLTIME"], queue = p.OMICSPIPE["QUEUE"], nodes = p.RNASEQQC["NODES"], ppn = p.RNASEQQC["CPU"], mem... | .RNASEQQC["REFFLAT"], p.RNASEQQC["TEMP_DIR"], sample, p.RNASEQQC["PICARD_VERSION"], p.RNASEQQC["R_VERSION"]])
job_status(jobname = 'RNAseq_QC', resultspath = p.RNASEQQC["RESULTS"], SAMPLE = sample, outputfilename = sample + "/insertSizeHist.pdf", FLAG_PATH = p.OMICSPIPE["FLAG_PATH"])
return
if __name__ == '__ma... |
claudep/pootle | pootle/apps/pootle_app/migrations/0015_add_tp_path_idx.py | Python | gpl-3.0 | 470 | 0.002128 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 20 | 16-11-04 16:36
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pootle_app', '0014_set_directory_tp_path'),
]
operations = [
migrations.AlterIndexTogether(
name='directory',
index_t... | )]),
),
]
|
janezhango/BigDataMachineLearning | py/testdir_single_jvm/test_exec2_enums_rand_cut.py | Python | apache-2.0 | 11,650 | 0.006867 | import unittest, random, sys, time, re, getpass
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util
import h2o_print as h2p, h2o_gbm
# details:
# we want to seed a random dictionary for our enums
# string.ascii_uppercase string.printable string.lette... | column
# essentially sampling with replacement
rowData = []
for iCol in range(inCount):
# FIX! | we should add some random NA?
ri = random.choice(colEnumList[iCol])
rowData.append(ri)
# output columns. always 0-10e6 with 2 digits of fp precision
for oCol in range(outCount):
ri = "%.2f" % random.uniform(0, 10e6)
rowData.append(ri)
# use the n... |
aequitas/home-assistant | homeassistant/components/sensibo/climate.py | Python | apache-2.0 | 12,247 | 0 | """Support for Sensibo wifi-enabled home thermostats."""
import asyncio
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.climate import ClimateDevice, PLATFORM_SCHEMA
from homeassistant.components.climate.const import (
DOMAIN, SUPPORT_TARGET_TEMPERATURE, ... | """Return the list of supported features."""
return self._supported_features
def _do_update(self, data):
self._name = data['room']['name']
self._measurements = data['measurements']
self._ac_states = data['acState']
self._available = data['connectionStatus']['isAlive']
... | apabilities = \
capabilities['modes'][self._ac_states['mode']]
temperature_unit_key = data.get('temperatureUnit') or \
self._ac_states.get('temperatureUnit')
if temperature_unit_key:
self._temperature_unit = TEMP_CELSIUS if \
temperature_unit_key == 'C... |
Sophist-UK/sophist-picard-plugins | sort_multivalue_tags.py | Python | gpl-2.0 | 1,718 | 0.00291 | # -*- coding: utf-8 -*-
# This is the Sort Multivalue Tags plugin for MusicBrainz Picard.
# Copyright (C) 2013 Sophist
#
# 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 th... | N_API_VERSIONS = ["0.15.0", "0.15.1", "0.16.0", "1.0.0", "1.1.0", "1.2.0", "1.3.0"]
from picard.metadata import register_track_metadata_processor
# Exclude the following tags because the sort order is | related to other tags or has a meaning like primary artist
_sort_multivalue_tags_exclude = [
'artists', '~artists_sort', 'musicbrainz_artistid',
'albumartist', '~albumartists_sort', 'musicbrainz_albumartistid',
'work', 'musicbrainz_workid',
'label', 'catalognumber',
'country', 'date',
'releasety... |
danche354/Sequence-Labeling | ner/evaluate-senna-hash-pos-chunk-128-64.py | Python | mit | 1,788 | 0.008949 | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length =... | .ner_pos_length |
chunk_length = conf.ner_chunk_length
IOB = conf.ner_IOB_decode
test_data = load_data.load_ner(dataset='eng.testb')
best_epoch = sys.argv[1]
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.tx... |
JSBCCA/pythoncode | early_projects/practice_loop.py | Python | mit | 191 | 0 | def int_list():
howmany = int(input("How many inputs? "))
nums = []
f | or i in range(howmany):
x = int(input("Inp | ut: "))
nums.append(x)
print(nums)
int_list()
|
hassanabidpk/djangoproject.com | docs/tests.py | Python | bsd-3-clause | 2,750 | 0.004364 | import os
from pathlib import Path
from django.contrib.sites.models import Site
from django.core.urlresolvers import set_urlconf
from django.template import Context, Template
from django.test import TestCase
from .utils import get_doc_path
class SearchFormTestCase(TestCase):
fixtures = ['doc_test_fixtures']
... | \"nf\">"
"band_listing</span><span class=\"p\">(</span><span class=\"n\">request</span><span "
"class=\"p\">):</span>\n <span class=\"sd\">"""A view of all bands"
"."""</span>\n <span class=\"n\">bands</span> <span class=\"o\">="
| "</span> <span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">"
"Band</span><span class=\"o\">.</span><span class=\"n\">objects</span><span "
"class=\"o\">.</span><span class=\"n\">all</span><span class=\"p\">()</span>\n "
"<span class=\"k\">return</span> <sp... |
stonebig/winpython | winpython/_vendor/qtpy/tests/test_qtxmlpatterns.py | Python | mit | 1,117 | 0.000895 | import pytest
from qtpy import PYSIDE2, PYSIDE6, PYQT6
@pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0")
def test_qtxmlpatterns():
"""Test the qtpy.QtXmlPatterns namespace"""
from qtpy import QtXmlPatterns
assert QtXmlPatterns.QAbstractMessageHandler is not None
assert QtXmlPa... | QtXmlPatterns.QXmlSchema is not None
assert QtXmlPatterns.QXmlSchemaValidator is not None
assert QtXmlPatterns.QXmlSe | rializer is not None
|
xmaruto/mcord | xos/synchronizers/base/syncstep.py | Python | apache-2.0 | 10,897 | 0.012389 | import os
import base64
from datetime import datetime
from xos.config import Config
from xos.logger import Logger, logging
from synchronizers.base.steps import *
from django.db.models import F, Q
from core.models import *
from django.db import reset_queries
from synchronizers.base.ansible import *
from generate.depende... | rror_map = args.get('error_map')
try:
self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
except:
self.soft_deadline = 5 # 5 seconds
return
def fetch_pending(self, deletion=False):
# This is the most common implementation of fetch_pending
... | # Steps should override it if they have their own logic
# for figuring out what objects are outstanding.
main_objs = self.observes
if (type(main_objs) is not list):
main_objs=[main_objs]
objs = []
for main_obj in main_objs:
if (not deletion):
lobjs = main_obj.objects.filter(Q(enacted__lt... |
jodaiber/semantic_compound_splitting | visualization_and_test/evaluate_candidates_indiv.py | Python | apache-2.0 | 4,883 | 0.006349 | __author__ = 'rwechsler'
import cPickle as pickle
import itertools
import random
from annoy import AnnoyIndex
import multiprocessing as mp
import sys
import argparse
import time
import datetime
import numpy as np
def timestamp():
return datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
d... | = mp.Pool(processes=arguments.n_processes)
params = candidate_generator(candidates, arguments.rank_threshold, arguments.sample_set_size, annoy_tree_file, vector_dims, lock)
results = pool.map(mp_wrapper_evaluate_set, params)
| print timestamp(), "pickling"
pickle.dump(results, open(arguments.result_output_file, "wb"))
print timestamp(), "done"
|
kjs73/pele | examples/gui/bljsystem.py | Python | gpl-3.0 | 2,178 | 0.003673 | """
start a gui for a binary lennard jones cluster.
All that is really needed to start a gui is define a system and call run_gui
system = BLJCluster(natoms, ntypeA)
run_gui(system)
"""
import sys
from PyQt4 import QtGui
from pele.systems import BLJCluster
from pele.gui import run_gui
from _blj_dialog impo... | t_sigAB.text())
self.epsAB = float(self.ui.lineEdit_epsAB.text())
self.sigBB = float(self.ui.lineEdit_sigBB.text())
self.epsBB = float(self.ui.lineEdit_epsBB.text())
| self.sigAA = 1.
self.epsAA = 1.
def on_buttonBox_accepted(self):
self.get_input()
self.close()
def on_buttonBox_rejected(self):
self.close()
if __name__ == "__main__":
# create a pop up window to get the number of atoms
app = QtGui.QApplication(sys.argv)
dialog... |
charlesll/RamPy | rampy/tests/test_mlregressor.py | Python | gpl-2.0 | 1,520 | 0.017763 | import unittest
import numpy as np
np.random.seed(42)
import scipy
from scipy.stats import norm
import rampy as rp
class TestML(unittest.TestCase):
def test_mlregressor(self):
x = np.arange(0,600,1.0)
nb_samples = 100 # number of samples in our dataset
# true partial spectra
S... | C_new_))).T
noise_new = np.random.randn(len(x))*1e-4
Obs_new = np.dot(C_new_true,S_true) + noise_new
model = rp.mlregressor(Obs,C_true[:,0].reshape(-1,1))
for i in ["KernelRidge", "SVM", "LinearRegression", "NeuralNet", "BaggingNeuralNet"]:
# we do not test on Lasso and El... | .user_kernel = 'poly'
model.fit()
C_new_predicted = model.predict(Obs_new)
# testing if refit works
model.refit()
if __name__ == '__main__':
unittest.main()
|
sobomax/virtualbox_64bit_edd | src/VBox/ValidationKit/tests/additions/tdAddBasic1.py | Python | gpl-2.0 | 11,512 | 0.016157 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: tdAddBasic1.py $
"""
VirtualBox Validation Kit - Additions Basics #1.
"""
__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free sof... | UN.INF');
if oSession is not None:
self.addTask(oSession);
# Do the testing.
reporter.testStart('Install');
fRc, oTxsSession = self.testInstallAdditions(oSession, oTxsSession, oTestVm);
reporter.testDone();
fSkip = not fRc;
rep... | testDone(fSkip);
reporter.testStart('Guest Control');
if not fSkip:
(fRc2, oTxsSession) = self.aoSubTstDrvs[0].testIt(oTestVm, oSession, oTxsSession);
fRc = fRc2 and fRc;
reporter.testDone(fSkip);
## @todo Save an restore test.
... |
leilihh/novaha | nova/cmd/all.py | Python | apache-2.0 | 3,403 | 0.000294 | # Copyright 2011 OpenStack Foundation
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... | uncher.launch_service(service.Service.create(binary=binary,
topic=topic,
| manager=manager))
except (Exception, SystemExit):
LOG.exception(_('Failed to load %s'), binary)
launcher.wait()
|
lisprolog/python | to_encrypt.py | Python | bsd-3-clause | 1,378 | 0.006531 | '''
This mission is the part of the set. Another | one - Caesar cipher decriptor.
Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar cipher where each letter of inpu | t text is replaced by another that stands at a fixed distance. For example ("a b c", 3) == "d e f"
example
Input: A secret message as a string (lowercase letters only and white spaces)
Output: The same string, but encrypted
Precondition:
0 < len(text) < 50
-26 < delta < 26
'''
def to_encrypt(text, delta):
alph... |
dennybaa/st2 | st2actions/st2actions/runners/python_action_wrapper.py | Python | apache-2.0 | 6,375 | 0.002039 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | pack
self._file_path = file_path
self._parameters = parameters or {}
self._parent_args = parent_args or []
self._class_name = None
self._logger = logging.getLogger('PythonActionWrapper')
try:
config.parse_args(args=self._parent_args)
except Exception... | nce()
output = action.run(**self._parameters)
# Print output to stdout so the parent can capture it
sys.stdout.write(ACTION_OUTPUT_RESULT_DELIMITER)
print_output = None
try:
print_output = json.dumps(output)
except:
print_output = str(output)
... |
google-code/billreminder | src/lib/dbus_actions.py | Python | mit | 5,266 | 0.001899 | # -*- coding: utf-8 -*-
__all__ = ['Actions']
import dbus
import dbus.service
import os
from subprocess import Popen
import dal
import bill
from lib import common, scheduler
from lib.utils import force_string
from lib.utils import Message
from db.billstable import BillsTable
class Actions(object):
def __init__... | (force_string(kwargs))
return self._correct_type(record)
except dbus.DBusException:
if self.__init__():
return self.edit_bill(kwargs)
def delete_bill(self, key):
""" Delete a record in the database """
try:
return self.dbus_interf | ace.delete_bill(key)
except dbus.DBusException:
if self.__init__():
return self.delete_bill(kwargs)
def get_categories(self, kwargs):
""" Returns one or more records that meet the criteria passed """
try:
ret = []
if isinstance(kwargs, bas... |
grupoanfi/orderbook-data-analysis | ODA/test/test_mini_market.py | Python | gpl-3.0 | 11,740 | 0.001533 | __author__ = 'Math'
import unittest
from ODA.market_cols import OrderKeys, ExecutionResponse
from utils import Generear_ordenes_limit
import random
import pandas as pd
from ODA.market import Market, Request
req_ask1 = {
OrderKeys.size: 1000,
OrderKeys.direction: -1,
OrderKeys.price: 1600,
OrderKeys.id... | res = []
self.my_ordens.agregar_ordenes_bid(n_orders)
for order in self.my_ordens.list_ordenes_bid:
l_res.append(self.my_mini_market.execut | e_request(Request(**order)).msg)
self.assertSetEqual(set(l_res), {ExecutionResponse.OK})
l = []
for index in range(n_orders):
for order in self.my_mini_market.orders_queue[1]:
if order.id_order == index:
l.append(index)
self.assertEqual... |
suryakencana/niimanga | niimanga/sites/__init__.py | Python | lgpl-3.0 | 2,259 | 0.001771 | """
# Copyright (c) 05 2015 | surya
# 18/05/15 [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 option) any later ve... | pass
def get_html(self, url, method='GET', **kwargs):
resp = request(method, url, **kwargs)
if resp.status_code != 200:
raise HtmlError({'msg': 'external_request_fail', 'url': url})
return resp.content
def fetch_manga_seed_page(self, url, **kwargs):
return se... | e(self, url, **kwargs):
return self.get_html(url, **kwargs)
def fetch_page_image(self, url, **kwargs):
return self.get_html(url, **kwargs)
def search_by_author(self, author):
"""
Return list of chapter dicts whose keys are:
name
url
site
... |
vied12/superdesk | server/apps/validators/validators.py | Python | agpl-3.0 | 645 | 0 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
| # AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
class ValidatorsResource(superdesk.Resource):
schema = {
'_id': {'type': 'string', 'required': True},
'schema': {
'type': 'dict',
'require... | vice):
pass
|
freedesktop-unofficial-mirror/gstreamer-sdk__cerbero | test/test_cerbero_packages_linux.py | Python | lgpl-2.1 | 7,324 | 0.000683 | # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; eit... | s(self):
self.packager._empty_packages = []
expected = (['gstreamer-test1'],
['gstreamer-test3'],
['gstreamer-test-bindings'])
self.store.get_package('gstreamer-test1').has_runtime_package = True
self.store.get_package('gstreamer-test3').has_runtim... | PackageType.RUNTIME, '')
self.assertEquals(expected, requires)
# test devel packages
requires = self.packager.get_meta_requires(PackageType.DEVEL, '-dev')
self.assertEquals(([], [], []), requires)
# test empty packages
self.store.get_package('gstreamer-test1').has_devel... |
petertrotman/adventurelookup | server/adventures/models/edition.py | Python | mit | 317 | 0 | "" | "
Model for the edition.
"""
# pylint: disable=too-few-public-methods
from django.db import models
from .mixins import TimestampMixin, DescriptionNotesMixin
class Edition(models.Model, TimestampMixin, DescriptionNotesMixin):
"""
Model for the edition.
"""
name = models.CharField(max_length= | 128)
|
aparo/elasticsearch-cookbook-third-edition | chapter_16/mapping_management.py | Python | bsd-2-clause | 1,158 | 0.008636 | import elasticsearch
es = elasticsearch.Elasticsearch()
index_name = "my_index"
type_name = "my_type"
if es.indices.exists(index_na | me):
es.indices.delete(index_name)
es.indices.create(index_name)
es.cluster.health(wait_for_status="yellow")
es.indices.put_mapping(index=index_name, doc_type=type_name, body={type_name:{"properties": {
"uuid": {"type": "keyword", "store": "true"},
"title": {"type": "text", "store": "true", "term_ve | ctor": "with_positions_offsets"},
"parsedtext": { "type": "text", "store": "true", "term_vector": "with_positions_offsets"},
"nested": {"type": "nested", "properties": {"num": {"type": "integer", "store": "true"},
"name": {"type": "keyword", "store": "true"},
... |
grbd/GBD.Build.BlackJack | blackjack/cmake/vars/CMakeBehavior.py | Python | apache-2.0 | 2,553 | 0.001176 | from .types.CMakeVariable import CMakeVariable
from .types.VariableCollection import VariableCollection
class CMakeBehavior(VariableCollection):
"""CMake Behavior related variables"""
BUILD_SHARED_LIBS = ()
CMAKE_ABSOLUTE_DESTINATION_FILES = ()
CMAKE_APPBUNDLE_PATH = ()
CMAKE_AUTOMOC_RELAXED_MODE... | OJECT_" + projname + "_INCLUDE", projname)
@staticmethod
def CMAKE_POLICY_DEFAULT_CMP_NNNN(polnum: str):
return CMakeVariable("CMAKE_POLICY_DEFAULT_CMP" + polnum, polnum)
@staticmethod
def CMAKE_POLICY_WARNING_CMP_NNNN(polnum: str):
return CMakeVariable("CMAKE_POLICY_WARNING_CMP" + pol... | kagename: str):
return CMakeVariable("CMAKE_DISABLE_FIND_PACKAGE_" + packagename, packagename)
|
bdh1011/wau | venv/lib/python2.7/site-packages/twisted/test/test_log.py | Python | mit | 36,409 | 0.00195 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.log}.
"""
from __future__ import division, absolute_import, print_function
from twisted.python.compat import _PY3, NativeStringIO as StringIO
import os
import sys
import time
import logging
import warnings
import ... | C{None}.
"""
eventDict = dict(message=(), isError= | 0)
text = log.textFromEventDict(eventDict)
self.assertIdentical(text, None)
def test_whySpecified(self):
"""
The C{"why"} value, when specified, is first part of message.
"""
try:
raise RuntimeError()
except:
eventDict = dict(
... |
tswsl1989/powerline-shell | segments/newline.py | Python | mit | 103 | 0 | def add_newline_segment(powerlin | e):
powe | rline.append("\n", Color.RESET, Color.RESET, separator='')
|
HelioGuilherme66/robotframework-selenium2library | src/Selenium2Library/utils/events/event.py | Python | apache-2.0 | 140 | 0 | from builtins import object
import abc
class Event( | object) | :
@abc.abstractmethod
def trigger(self, *args, **kwargs):
pass
|
to-bee/members_python | web/authentication/admin.py | Python | lgpl-3.0 | 821 | 0.002436 | import django
from django.contrib import admin
from authentication.models import LoginUser, Group
@admin.register(LoginUser)
class AdminLoginUser(admin.ModelAdmin):
list_disp | lay = ('username', 'email', 'get_orgs')
search_fields = [
'username', 'email'
]
def get_orgs(self, obj):
return obj.orgs_str
get_orgs.short_description = 'Organization'
def get_form(self, request, obj=None, **kwargs):
# self.fields = []
# self.readonly_fields = []... | end('user_permissions')
return super(AdminLoginUser, self).get_form(request, obj, **kwargs)
admin.site.register(Group)
admin.site.unregister(django.contrib.auth.models.Group) |
Mariaanisimova/pythonintask | INBa/2015/Shemenev_A_V/task_100_30.py | Python | apache-2.0 | 3,036 | 0.064657 | #Задача №10, Вариант 30
#Напишите программу "Генератор персонажей" для игры.Пользователю должно быть предоставлено 30 пунктов,
#которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудр | ость и Ловкость.
#Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но и возвращать их туда из характеристик,
#которым он | решил присвоить другие значения.
#Шеменев А.В
#28.04.2016
print ("""
Добро пожаловать в "Генератор персонажей".
Вы можете распределить 30 очков между 4 характеристиками:
Сила, Здоровье, Мудрость и Ловкость. Вы можете как и брать из общего
числа пункотв, так и возвращать. Распределяйте характеристики с ... |
superdesk/Live-Blog | plugins/superdesk-person/__plugin__/superdesk_person/gui.py | Python | agpl-3.0 | 429 | 0.004662 | '''
Created on Feb 2, 2012
@package ally core reques | t
@copyright 2011 Sourcefabric o.p.s.
@license http://www.gnu.org/licenses/gpl-3.0.txt
@author: Gabriel Nistor
Contains the GUI configuration setup for the node presenter plugin.
'''
from ..gui_core.gui_co | re import publishGui, publish
# --------------------------------------------------------------------
@publish
def publishJS():
publishGui('superdesk/person')
|
devilry/devilry-django | devilry/devilry_admin/views/common/bulkimport_users_common.py | Python | bsd-3-clause | 5,904 | 0.001863 | import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_l... | xurl()
def import_users_from_emails(self, e | mails):
raise NotImplementedError()
def import_users_from_usernames(self, usernames):
raise NotImplementedError()
def form_valid(self, form):
if settings.CRADMIN_LEGACY_USE_EMAIL_AUTH_BACKEND:
self.import_users_from_emails(emails=form.cleaned_users_set)
else:
... |
jandebleser/django-wiki | src/wiki/views/article.py | Python | gpl-3.0 | 34,566 | 0.000521 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import difflib
import logging |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import Q
| from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.views.generic.base import RedirectView, TemplateView, View
from django.views.generic.edit import FormView
f... |
abarisain/mopidy | mopidy/utils/encoding.py | Python | apache-2.0 | 217 | 0 | from __future__ import unicode_literals
import locale
def locale_decode(bytestr):
try:
return unicode(bytestr)
except Uni | codeError:
return str(bytestr).decode(locale.getpreferreden | coding())
|
keenerd/wtf | wikipedia.py | Python | bsd-3-clause | 2,140 | 0.009841 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# https | ://en.wikipedia.org/w/index.php?title=List_of_computing_and_IT_abbreviations&action=edit
import re, urllib2
from collections import defaultdict
from BeautifulSoup import BeautifulSoup
pull = lambda url: urllib2.urlopen(urllib2.Request(url))
wikip = lambda article: pull('https://en.wikipedia.org/w/index | .php?title=%s&action=edit' % article)
# todo: List_of_file_formats
def stock():
ad = defaultdict(list)
for line in open('acronyms'):
if '\t' not in line:
continue
line = line.strip()
a,d = line.split('\t')
ad[a].append(d)
for line in open('acronyms.comp'):
... |
andrewsosa/hackfsu_com | api/api/models/__init__.py | Python | apache-2.0 | 1,488 | 0 | """
The Django User class is used to handle users and authentication.
https://docs.djangoproject.com/en/1.10/ref/contrib/auth/
User groups:
| superadmin - Can access django admin page
admin - Can access regular admin pages
hacker - Hacker pages
mentor - Mentor pages
judge - Judge pages
user (implied when logged in) - User pages
"""
from .hackathon import Hackathon
from .hackathon_countdown import HackathonCount | down
from .hackathon_map import HackathonMap
from .hackathon_sponsor import HackathonSponsor
from .hackathon_update import HackathonUpdate
from .attendee_status import AttendeeStatus
from .schedule_item import ScheduleItem
from .school import School
from .anon_stat import AnonStat
from .scan_event import ScanEvent
from... |
Dallinger/Dallinger | demos/dlgr/demos/bartlett1932/models.py | Python | mit | 758 | 0 | from dallinger.nodes import Source
import random
class WarOfTheGhostsSource(Source):
"""A Source that reads in a random story from a file and transmit | s it."""
__mapper_args__ = {"polymorphic_identity": "war_of_the_ghosts_source"}
def _contents(self):
"""Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents().
"""
| stories = [
"ghosts.md",
"cricket.md",
"moochi.md",
"outwit.md",
"raid.md",
"species.md",
"tennis.md",
"vagabond.md",
]
story = random.choice(stories)
with open("static/stimuli/{}".format(story)... |
tmct/adventOfCode2016 | problems/1/Position.py | Python | mit | 514 | 0.001946 | from Di | rection import Direction
class Position:
def __init__(self, direction=Direction.north):
self.x_coord = 0
self.y_coord = 0
self.direction = direction
def turn(self, turn):
self.direction = self.direction.turn(turn)
def walk_forward(self, steps):
self.x_coord += ste... | ord |
ledeprogram/algorithms | class1/homework/born_mathias_1_1.py | Python | gpl-3.0 | 276 | 0.07971 | def my_mean(list):
length = count_length(list)
sum = 0
for i in list:
sum = sum + i
return sum / length
def count_length(list):
count = 0
for i in list:
if i == '':
break
else:
count += | 1
return count
numbers = [1,2,3,4,5,6,7,8,9]
print( | my_mean(numbers))
|
dlutxx/memo | python/advanced.py | Python | mit | 1,657 | 0.001811 | #-*- coding: utf8 -*-
'''
Examples of advanced Python features:
- metaclass
- descriptor
- generator/forloop
'''
from __future__ import print_function
import sys
if sys.version_info > (3, ): # Python 3
exec('''
def exec_in(code, glob, loc=None):
if isinstance(code, str):
code = compile(code, '<... | print("AnimalMeta.__call__")
return super(AnimalMeta, self).__call__(*args, **kwargs)
class Cat(with_meta(AnimalM | eta)):
name = 'cat'
def __init__(self):
print('Meow')
kit = Cat()
|
teknogods/eaEmu | eaEmu/gamespy/auth.py | Python | gpl-3.0 | 944 | 0.023305 | from __future__ import absolute_import
import struct
import logging
from twisted.internet.protocol import Protocol, ServerFactory
from .. import util
class GamespyAuth(Protocol):
def connectionMade(self):
self.log = util.getLogger('gamespy.auth', self)
def dataReceived(self, data):
hdrFmt = '!4s4... | ansport. | loseConnection()
class GamespyAuthFactory(ServerFactory):
protocol = GamespyAuth
|
d3adc0d3/simple-db-app | query_result_window.py | Python | mit | 1,046 | 0.027184 | from PyQt4.QtGui import *
class QueryResultWindow:
def __init__(self):
self.__create_window_widget()
self.__create_ui()
def __create_window_widget(self):
self.__qt_widget_object = QWidget()
self.__qt_widget_object.resize(800, 600)
self.__qt_widget_object.setWindowTitle('Результат запроса')
def __create_... | self.__qt_widget_object.setLayout(layout)
layout.addWidget(query_result_table)
self.__query_result_table = query_result_table
def show(self):
self.__qt_widget_object.show()
def set_column_names(self | , columns):
self.__query_result_table.setColumnCount(len(columns))
self.__query_result_table.setHorizontalHeaderLabels(columns)
def set_data(self, data):
self.__query_result_table.setRowCount(len(data))
for i, row in enumerate(data):
for j in range(0, len(row)):
item_value = row[j]
item_text = str... |
aviarypl/mozilla-l10n-addons-server | src/olympia/addons/management/commands/approve_addons.py | Python | bsd-3-clause | 3,058 | 0 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
import olympia.core.logger
from olympia import amo
from olympia.addons.models import Addon
from olympia.amo.utils import chunked
from olympia.reviewers.utils import ReviewHelper
log = olympia.core.logger.getLogger('z.addons')
... | helper = ReviewHelper(request=None, addon=addon,
version=file_.version)
# Provide the file to review/sign to the helper.
helper.set_data({'addon_files': [file_],
'comments': u'bulk approval'})
if review_type == 'full':
# Alre... | helper.handler.process_public()
log.info(u'File %s (addon %s) approved', file_.pk, addon.pk)
else:
log.info(u'File %s (addon %s) not approved: '
u'addon status: %s, file status: %s',
file_.pk, addon.pk, addon.status, file_.status)
def g... |
leovoel/glc.py | examples/gradient.py | Python | mit | 412 | 0.004854 | from | example_util import get_filename
from glc import Gif
from glc.color import Color, hsva
with Gif(get_filename(__file__)) as a:
a.set_bg_color(Color("black")).set_duration(2).set_size(300, 300)
l = a.render_list
res = 250
c = [hsva((i / res) * 360, 1, 1) for i in range(res)]
l.gradient_pie(x=a.w * ... | =a.h * 0.5, rotation=[0, 90], rx=a.w * 0.5, ry=a.h * 0.5, colors=c)
a.save()
|
TamiaLab/carnetdumaker | apps/bugtracker/forms.py | Python | agpl-3.0 | 4,597 | 0.002393 | """
Forms for the bug tracker app.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from apps.txtrender.forms import MarkupCharField
from apps.contentreport.forms import ContentReportCreationForm
from apps.tools.http_utils import get_client_ip_address
from .models import (IssueTic... | IssueTicketSubscription.objects.subsc | ribe_to_issue(author, new_obj.issue)
else:
IssueTicketSubscription.objects.unsubscribe_from_issue(author, new_obj.issue)
# Notify subscribers
notify_of_new_comment(issue, new_obj, request, author)
# Return the newly created object
return new_obj
class IssueComment... |
DougFirErickson/neon | examples/fast_rcnn_alexnet.py | Python | apache-2.0 | 7,314 | 0.002461 | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana 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
#
# ... | Alexnet from Neon model zoo to the local
url = 'https://s3-us-west-1.amazonaws.com/nervana-modelzoo/alexnet/'
filename = 'alexnet.p'
size = 488808400
workdir, filepath = Dataset._valid_path_append(path, '', filename)
if not os.path.exists(filepath):
Dataset.fetch_ | dataset(url, filename, filepath, size)
print 'De-serializing the pre-trained Alexnet using ImageNet I1K ...'
pdict = load_obj(filepath)
param_layers = [l for l in model.layers.layers[0].layers[0].layers]
param_dict_list = pdict['model']['config']['layers']
for layer, ps in zip(param_layers, param_... |
prabeesh/Spark-Kestrel | python/pyspark/worker.py | Python | bsd-3-clause | 2,473 | 0.001617 | """
Worker that receives input from Piped RDD.
"""
import os
import sys
import time
import traceback
from base64 import standard_b64decode
# CloudPickler needs to be imported so that depicklers are registered using the
# copy_reg module.
from pyspark.accumulators import _accumulatorRegistry
from pyspark.broadcast impor... | ith_length, w | rite_int, \
read_long, write_long, read_int, dump_pickle, load_pickle, read_from_pickle_file
def load_obj(infile):
return load_pickle(standard_b64decode(infile.readline().strip()))
def report_times(outfile, boot, init, finish):
write_int(-3, outfile)
write_long(1000 * boot, outfile)
write_long(1... |
c10k/docgen | cpp_doc_generator.py | Python | mit | 28,176 | 0.002271 | #! /usr/bin/env python3
import argparse
from os.path import basename, splitext, isdir, abspath, join
from os import getcwd
class comments:
def __init__(self, comment_lines):
self.comment_lines = []
temp_buffer = str()
for each_line in comment_lines:
each_line = each_line.stri... | elif each_line.startswith("access"):
if properties['access'] is None:
parsed_access = each_line.split(' ')
if len(parsed_access) == 2:
properties['access'] = parsed_access[1]
... | "Invalid comment.. access val not specified with @access tag", line_tag)
else:
raise Exception(
"Invalid comment.. @access tag found again in a single comment", line_tag)
elif each_line.start... |
radez/packstack | packstack/plugins/puppet_950.py | Python | apache-2.0 | 9,838 | 0.003354 | """
Installs and configures puppet
"""
import sys
import logging
import os
import platform
import time
from packstack.installer import utils
from packstack.installer import basedefs, output_messages
from packstack.installer.exceptions import ScriptRuntimeError
from packstack.modules.common import filtered_hosts
from ... | (tar_opts, os_modules, hostname,
os.path.join(host_dir, 'modules')))
server.execute()
def waitforpuppet(currently_running):
global controller
log_len = 0
twirl = ["-","\\","|","/"]
while currently_running:
for hostname, finished_lo... | if len(log_file) > log_len:
log_len = len(log_file)
if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
twirl = twirl[-1:] + twirl[:-1]
sys.stdout.write(("\rTesting if puppet apply is finished : %s" % log_file).ljust(40 + log_len))
... |
WisZhou/websocket_messager | utils.py | Python | mit | 904 | 0.001106 | #!/usr/bin/env python
# coding: utf-8
import logging
import config
def get_common_logger(name='common', logfile=None):
'''
args: name (str): logger name
logfile (str): log file, use stream handler (stdout) as default.
return:
logger | obj
'''
my_logger = logging.getLogger(name)
my_logger.setLevel(config.LOG_LEVEL)
if logfile:
handler = logging.FileHandler(logfile)
else:
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)... | my_logger.addHandler(handler)
# Stop logger propagate, forbiden duplicate log.
my_logger.propagate = False
return my_logger
COMMON_LOGGER = get_common_logger('common logger')
if __name__ == '__main__':
COMMON_LOGGER.debug('test')
|
willprice/python-omxplayer-wrapper | tests/unit/test_dbus_connection.py | Python | lgpl-3.0 | 3,009 | 0.000665 | import unittest
from parameterized import parameterized
from mock import patch, Mock
from dbus import DBusException
from omxplayer.dbus_connection import DBusConnection, DBusConnectionError
@patch('dbus.bus.BusConnection')
class DBusConnectionTests(unittest.TestCase):
def setUp(self):
self.proxy = Mock(... | uid=EXAMPLE'],
['unix:abstract=/tmp/dbus-EXAMPLE2,guid=EXAMPLE2'],
])
def test_connects_to_omxplayer_bus(self, BusConnection, bus_address, *args):
self.create_example_dbus_connection(bus_address)
BusConnection.assert_called_once_with(bus_address)
def test_ | constructs_proxy_for_omxplayer(self, BusConnection, *args):
BusConnection.return_value = self.bus
self.create_example_dbus_connection()
self.bus.get_object.assert_called_once_with(
'org.mpris.MediaPlayer2.omxplayer',
'/org/mpris/MediaPlayer2',
introspect=Fals... |
elifesciences/lax | src/publisher/api_v2_views.py | Python | gpl-3.0 | 12,634 | 0.00182 | import json
import jsonschema
from django.core import exceptions as django_errors
from . import models, logic, fragment_logic, utils
from .utils import ensure, isint, toint, lmap
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts impo... | tion/vnd.elife.article-vor+json', {'version': 2})
parsed_mime, parsed_params = parse_header(mime.encode())
# ('*/*', 'version', None)
# ('application/json', 'version', None)
# ('application/vnd.elife.article-poa+json', 'version', 2)
version = parsed_params.pop("version", b"").dec... | version or None))
return lst
def negotiate(accepts_header_str, content_type_key):
"""parses the 'accept-type' header in the request and returns a content-type header and version.
returns `None` if a content-type can't be negotiated."""
# "application/vnd.elife.article-blah+json"
response_mime = _... |
cbrucks/Federated_Keystone | tests/test_backend_sql.py | Python | apache-2.0 | 11,834 | 0.000085 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | with an essex/folsom bug.
Non-indexed attributes were returned in an 'extra' attribute, instead
of on the entity itself; for consistency and backwards compatibility,
those attributes should be included twice.
This behavior is specific to the SQL driver.
"""
tenant_id =... | uid4().hex
arbitrary_value = uuid.uuid4().hex
tenant = {
'id': tenant_id,
'name': uuid.uuid4().hex,
'domain_id': DEFAULT_DOMAIN_ID,
arbitrary_key: arbitrary_value}
ref = self.identity_man.create_project({}, tenant_id, tenant)
self.assertEqu... |
aplanas/kmanga | kmanga/kmanga/settings.py | Python | gpl-3.0 | 4,546 | 0.00088 | """
Django settings for kmanga project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# ... | assword_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordVali | dator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, ... |
freedomtan/tensorflow | tensorflow/tools/ci_build/copy_binary.py | Python | apache-2.0 | 4,178 | 0.007899 | #!/usr/bin/python
# Copyright 2017 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 r... | se for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#
# Automatically copy TensorFlow binaries
#
# Usage:
# ./tensorflow/tools/ci_build/copy_binary.py --filename
# tf_nightly/tf_nightly_gpu-1.4... | ow for different python versions."""
# pylint: disable=superfluous-parens
import argparse
import os
import re
import shutil
import tempfile
import zipfile
TF_NIGHTLY_REGEX = (r"(.+)(tf_nightly.*)-(\d\.[\d]{1,2}"
r"\.\d.dev[\d]{0,8})-(.+)\.whl")
BINARY_STRING_TEMPLATE = "%s-%s-%s.whl"
def check_... |
dlux/sayHi_tempest_plugin | demo_tempest_plugin/config.py | Python | gpl-3.0 | 595 | 0 | '''
Tempest plugin configuration for say_hi packages
@author: luzC
'''
from oslo_config import cfg
from tempest import config
|
service_available_group = cfg.OptGroup(
name="service_available",
title="Available OpenStack Services"
)
ServiceAvailableGroup = [
cfg.BoolOpt("dluxSay", default=True,
help="Whether or not dluxsay is expected to be available")
]
say_hi_group = cfg. | OptGroup(
name="say_hi",
title="Say hi test variables"
)
SayHiGroup = [
cfg.StrOpt("my_custom_variable", default="custom value",
help="My custom variable.")
]
|
saeranv/UWG_Python | resources/quickstart.py | Python | gpl-3.0 | 587 | 0.003407 | import UWG
import os
# Gets path of current directory
CURR_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
# To run UWG provide the following inputs
epw_directory = os.path.join(CURR_DIRECTORY,"epw") # EPW file directory
epw_filename = "SGP_Singapore.486980_IWEC.epw" # EPW file name
uwg_param_directory =... | e name
# Initialize the UWG object
uwg = UWG.UWG(epw_directory, epw_filename, u | wg_param_directory, uwg_param_filename)
# Run the simulation
uwg.run()
|
ChinaMassClouds/copenstack-server | openstack/src/horizon-2014.2/openstack_dashboard/dashboards/admin/aggregates/forms.py | Python | gpl-2.0 | 2,999 | 0.000333 | # 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... | ta["name"] + "aggregate update")
message = _('Successfully updated aggregate: "%s."') \
% data['name']
messages.success(request, message)
except Exception:
exceptions.handle(request,
_('Unable to update the aggregate.'))
... |
try:
new_metadata = json.loads(self.data['metadata'])
metadata = dict(
(item['key'], str(item['value']))
for item in new_metadata
)
for key in old_metadata:
if key not in metadata:
metadata[key... |
janusnic/21v-python | unit_14/car8.py | Python | mit | 319 | 0.018809 | #!/usr/bin/python
# -*- coding: utf-8 | -*-
import sqlite3 as lite
import sys
uId = 4
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("SELECT Name, Price FROM Cars WHERE Id=:Id",
{"Id": uId}) |
con.commit()
row = cur.fetchone()
print row[0], row[1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.