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 |
|---|---|---|---|---|---|---|---|---|
mvanveen/cargo | cargo/image.py | Python | mit | 1,022 | 0.019569 | from cargo.base import CargoBase, lowercase, make_id_dict
class Image(CargoBase):
"""Python wrapper class encapsulating the metadata for a Docker Image"""
def __init__(self, *args, **kw):
super(Image, self).__init__(*args, **kw)
@property
def config(self, *args , **kw):
image = make_id_dict(self._do... | (self._config.get('id'))
if image:
self._config = lowercase(image)
return self._config
@property
def image(self):
return self.config.get('image')
@property
def size(self):
return self.config.get('size')
@property
def vsize(self):
return self.config.get('virtualsize')
@propert... | ('id')
@property
def repository(self):
return self.config.get('repository')
@property
def tag(self):
return self.config.get('tag')
def __repr__(self):
if self.repository:
return '<Image [%s:%s]>' % (self.repository, self.image_id[:12])
return '<Image [%s]>' % (self.image_id[:12],)
|
jnez71/lqRRT | demos/lqrrt_ros/behaviors/car.py | Python | mit | 3,231 | 0.005262 | """
Constructs a planner that is good for being kinda like a car-boat thing!
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from params import *
import lqrrt
################################################# DYNAMICS
magic_rudder = 6000
def dynamics(x, u, dt):
"""
Returns... | a seed state, goal state, and buffer.
"""
return [(min([seed[0], goal[0]]) - buff[0], max([seed[0], goal[0]]) + buff[1]),
(min([seed[1], goal[1]]) - buff[2], max([seed[1], goal[1 | ]]) + buff[3]),
(-np.pi, np.pi),
(0.9*velmax_pos[0], velmax_pos[0]),
(-abs(velmax_neg[1]), velmax_pos[1]),
(-abs(velmax_neg[2]), velmax_pos[2])]
################################################# MAIN ATTRIBUTES
constraints = lqrrt.Constraints(nstates=nstates, ncontrols=... |
nive/nive | nive/utils/dataPool2/tests/performance_test.py | Python | gpl-3.0 | 12,761 | 0.014262 |
import copy
from nive.utils.dataPool2.mysql.tests import test_MySql
try:
from nive.utils.dataPool2.mysql.mySqlPool import *
except:
pass
from . import test_db
from nive.utils.dataPool2.sqlite.sqlite3Pool import *
mode = "mysql"
printed = [""]
def print_(*kw):
if type(kw)!=type(""):
v = ""
... | pool = getPool()
print_( "Create entries (nodb) and check exists: ")
t = time.time()
for i in range(0,n):
e=pool._GetPoolEnt | ry(i, version=None, datatbl="data1", preload="skip", virtual=True)
e.Exists()
t2 = time.time()
pool.Close()
print_( n, " checks in ", t2-t, "secs. ", (t2-t)/n, " per check")
print_()
def createentries2(n):
pool = getPool()
print_( "Create entries (nodata): ")
t = time.time()
f... |
ashang/calibre | src/odf/opendocument.py | Python | gpl-3.0 | 26,274 | 0.004948 | # -*- coding: utf-8 -*-
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency
#
# This library 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 2.1 of the License, or (at you... | nd self._styles_ooo_fix.has_key(styleref):
element.setAttrNS(TEXTNS,u'style-name', self._styles_ooo_fix[styleref])
def __register_stylename(self, elemen | t):
''' Register a style. But there are three style dictionaries:
office:styles, office:automatic-styles and office:master-styles
Chapter 14
'''
name = element.getAttrNS(STYLENS, u'name')
if name is None:
return
if element.parentNode.qname in (... |
andresailer/DIRAC | DataManagementSystem/Client/FTS3Client.py | Python | gpl-3.0 | 3,920 | 0.008673 | import json
from DIRAC.Core.Base.Client import Client
from DIRAC import S_OK, S_ERROR
from DIRAC.DataManagementSystem.private.FTS3Utilities import FTS3JSONDecoder
class FTS3Client(Client):
""" Client code to the FTS3 service
"""
def __init__(self, url=None, **kwargs):
""" Constructor function.
"""
... | :
operations = json.loads(operationsJSON, cls=FTS3JSONDecoder)
return S_OK(operations)
except Exception as e:
return S_ERROR(0, "Exception when decoding the non finis | hed operations json %s" % e)
def getOperationsFromRMSOpID(self, rmsOpID, **kwargs):
""" Get the FTS3Operations matching a given RMS Operation
:param rmsOpID: id of the operation in the RMS
:return: list of FTS3Operation objects
"""
res = self._getRPC(**kwargs).getOperationsFromRMSOpID(rm... |
aronsky/home-assistant | homeassistant/components/cloud/google_config.py | Python | apache-2.0 | 8,528 | 0.000938 | """Google config for Cloud."""
import asyncio
from http import HTTPStatus
import logging
from hass_nabucasa import Cloud, cloud_api
from hass_nabucasa.google_report_state import ErrorResponse
from homeassistant.components.google_assistant.const import DOMAIN as GOOGLE_DOMAIN
from homeassistant.components.google_assis... | istry as er, start
from homeassistant.setup import async_setup_component
from .const import (
CONF_ENTITY_CONFIG,
DEFAULT_DISABLE_2FA,
PREF_DISABLE_2FA,
PREF_SHOULD_EXPOSE,
)
from .prefs import CloudPreferences
_LOGGER = logging.getLogger(__name__)
class CloudGoogleConfig(AbstractConfig):
"""HA ... | ation for Google Assistant."""
def __init__(
self, hass, config, cloud_user: str, prefs: CloudPreferences, cloud: Cloud
):
"""Initialize the Google config."""
super().__init__(hass)
self._config = config
self._user = cloud_user
self._prefs = prefs
self._c... |
googleinterns/betel | betel/app_page_scraper.py | Python | apache-2.0 | 5,385 | 0.001486 | import pathlib
import urllib.error
import urllib.request
import logging
import bs4
import parmap
import pandas as pd
from betel import utils
from betel import info_files_helpers
from betel import betel_errors
class PlayAppPageScraper:
"""A class for scraping the icons and categories from Google Play Store
app... | APP_CATEGORY_ITEMPROP)
if category is None:
raise betel_errors.PlayScrapingError("Category itemprop not found in html.")
return category.get_text()
def store_app_info(self, app_id: str) -> None:
"""Adds an app to the data set by retrieving all the info
needed and appendi... | ategory is in the
_category_filter list.
:param app_id: the id of the app.
"""
search_data_frame = utils.get_app_search_data_frame(app_id)
part_of_data_set = (
info_files_helpers.part_of_data_set(self._info_file, search_data_frame)
)
try:
... |
switchonproject/sip-html5-protocol-tool | protocoltool/migrations/0024_auto_20161212_1645.py | Python | lgpl-3.0 | 399 | 0 | # -*- coding: utf-8 -*-
f | rom __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('protocoltool', '0023_auto_20161208_1723'),
]
operations = [
migrations.RenameField(
model_name='basicdataset',
old_name='chec... | e='hidden',
),
]
|
RemiFr82/ck_addons | ck_equipment/models/eqpt_paddler.py | Python | gpl-3.0 | 551 | 0.005445 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
from ./eqpt_equipment import EQPT_TYPES
class Paddler(models.Model):
_name = 'eqpt.paddler'
_description = "Paddler Cycle Equipment"
_description = "Cycle paddler equipment"
eqpt_type = fields.Selection(selection=EQPT_TYPES, string="")
... | string="Cycle")
member_id = fields.M | any2one(comodel_name='adm.asso.member', string="Member")
|
zhuww/planetclient | gti.py | Python | apache-2.0 | 6,453 | 0.017666 | #!/homes/janeway/zhuww/bin/py
import numpy
import pyfits
from pylab import *
#from Pgplot import *
#from ppgplot import *
#import ppgplot
from numpy import *
class Cursor:
badtimestart=[]
badtimeend=[]
lines = []
def __init__(self, ax):
self.ax = ax
#self.lx = ax.axhline(color='k') #... | a(x )
#self.txt.set_text( 'x=%1.2f, y=%1.2f'%(x,y) )
#print 'x=%1.2f, y=%1.2f'%(x,y)
draw()
hdulist=pyfits.open('histo.fits')
tabdata=hdulist[1].data
cols=hdulist[1].columns
#names=cols.names
#print names
counts=array(tabdata.field('COUNTS'))
time=array(tabdata.field('TIME'))
#starttime=time... | event', cursor.mouse_move)
connect('button_press_event', cursor.click)
duration = max(time) - min(time)
ax.set_xlim((min(time)-0.1*duration, max(time)+0.1*duration))
show()
#while not ppgplot.pgband(0)[2]=="X":
#print "click on the daigram twice to define a bad time interval:"
#badtimestart.append(ppgplot.pgban... |
Mathew/psychoanalysis | psychoanalysis/apps/pa/migrations/0002_auto__del_participant.py | Python | mit | 7,476 | 0.007089 | # -*- 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 model 'Participant'
db.delete_table(u'pa_participant')
# Removing M2M table for field us... | cipant'
db.create_table(u'pa_participant_user', (
('id', models.AutoField(verbose_name='ID', primary_key | =True, auto_created=True)),
('participant', models.ForeignKey(orm[u'pa.participant'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_participant_user', ['participant_id', 'user_id'])
# Removing M2M table for field user on ... |
CommonAccord/Cmacc-Org | Doc/G/NW-NDA/99/WiP/Schedule/String.py | Python | mit | 2,950 | 0.008136 | import re
thisDict = {
"path": "thisDict",
"2": "2",
"3": "3",
"5": "5",
"7": "7",
"2 x 2": "{2} x {2}",
"3 x 2": "{3} x {2}",
"4": "{2 x 2}",
"6": "{3 x 2}",
"8": "{2 x 2} x {2}",
"16": "{2 x 2} x {2 x 2}",
"96": "{16} x {6}",
"thisModel.Root": "thisModel.Root: {96}... | new_path = find_value(dictionary, search[i][1:-1])
value = value.replace(search[i], new_val, 1)
path += new_path
return value, path
value, path = find_value(thisDict, "megaModel.Root")
print("Value: ", value)
print("Path:\n", path | )
#Called inside find_value when there is no such key in the given dictionary input
#Find the key from other dictionaries, keep log of which path; return
# def fetch_value(dictionary, key): |
christiangalsterer/httpbeat | vendor/github.com/elastic/beats/packetbeat/tests/system/test_0029_http_gap.py | Python | apache-2.0 | 659 | 0 | from packetbeat import BaseTest
"""
Tests for HTTP messages with gaps (packet loss) in them.
"""
class Test(BaseTest):
def test_gap_in_large_f | ile(self):
"""
Should recover well from losing a packet in a large
file download.
"""
self.render_config_template(
http_ports=[8000],
)
self.run_packetbeat(pcap="gap_in_stream.pcap")
objs = self.read_output()
assert len(objs) = | = 1
o = objs[0]
assert o["status"] == "OK"
print(o["notes"])
assert len(o["notes"]) == 1
assert o["notes"][0] == "Packet loss while capturing the response"
|
davidvilla/python-doublex | doublex/safeunicode.py | Python | gpl-3.0 | 333 | 0 | # -*- coding: utf-8 -*-
import sys
def __if_nu | mber_get_string(number):
converted_str = number
if isinstance(number, (int, float)):
converted_str = str(number)
return converted_str
def get_string(strOrUnicode, encoding='utf-8'):
strOrUnicode = __if_number_get_string(strOrUnicode)
| return strOrUnicode
|
murrayrm/python-control | control/frdata.py | Python | bsd-3-clause | 26,326 | 0.000076 | # Copyright (c) 2010 by California Institute of Technology
# Copyright (c) 2012 by Delft University of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source... | EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Author: M.M. (Rene) van Paassen (using xferfcn.py as basis)
# Date: 02 Oct 12
from __future__ import division
"""
Frequency response data representation and functions.
This module contains the FRD class and also functions that operate on
FRD data.
"""
# Exte... | ones, \
real, imag, absolute, eye, linalg, where, dot, sort
from scipy.interpolate import splprep, splev
from .lti import LTI, _process_frequency_response
from . import config
__all__ = ['FrequencyResponseData', 'FRD', 'frd']
class FrequencyResponseData(LTI):
"""FrequencyResponseData(d, w[, smooth])
A ... |
iulian787/spack | var/spack/repos/builtin/packages/xmessage/package.py | Python | lgpl-2.1 | 845 | 0.001183 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xmessage(AutotoolsPackage, XorgPackage):
"""xmessage displays a message or query in a wind... | or can select one of several buttons
to answer a question. xmessage can also exit after a specified time."""
homepage = "http://cgit.freedesktop.org/xorg/app/xmessage"
xorg_mirror_path = "app/xmessage-1.0.4.tar.gz"
version('1.0.4', sha256='883099c3952c8cace5bd11d3df | 2e9ca143fc07375997435d5ff4f2d50353acca')
depends_on('libxaw')
depends_on('libxt')
depends_on('pkgconfig', type='build')
depends_on('util-macros', type='build')
|
richgieg/RichEmu86 | main.py | Python | mit | 98 | 0 | import system
# Crea | te the computer system and power it up.
sys = system.System()
sys.power_on | ()
|
daien/daco | distances_rkhs.py | Python | mit | 24,666 | 0.000568 | """
Pairwise distance functions between time series in a RKHS
=========================================================
They all have the following prototype:
function(K, T1, T2, **kwargs)
"""
import numpy as np
from scipy.linalg import solve, eigvals, inv
from scipy.signal import correlate2d
# mean-eleme... | distance_hsac_truncated(K, T1, T2, tau=1):
""" Compute the squared HS distance between the autocovariance operators of
two time series
|| \\scov^{(y)}_{\\tau} - \\scov^{(x)}_{\\tau} ||_{HS}^2 =
1/T**2 ( Tr(K_1 x K_1^\\tau) + Tr(K_2 x K_2^\\tau) - 2 Tr(K_{1,2} x K_{2,1}^\\tau ) )
Parameter | s
----------
K: (T1+T2) x (T1+T2) array,
between frames kernel matrix
T1: int,
duration of time series 1
T2: int,
duration of time series 2
tau: int, optional, default: -1
lag, ie time shift used in the auto-covariance computation
Returns
-------
dhsa... |
nikitakurylev/TuxemonX | tuxemon/core/states/combat/combat.py | Python | gpl-3.0 | 27,084 | 0.001625 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tuxemon
# Copyright (C) 2014, William Edwards <shadowapex@gmail.com>,
# Benjamin Bean <superman2k5@gmail.com>
#
# This file is part of Tuxemon.
#
# Tuxemon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | mport namedtuple, defaultdict
from functools import partial
from itertools import chain
from operator import attrgetter
import pygame
from core import tools, state
from core.components.locale import translator
from core.components.pyganim import PygAnimation
from core.components.sprite import Sprite
from core.compone... | ents.ui.draw import GraphicBox
from core.components.ui.text import TextArea
from .combat_animations import CombatAnimations
trans = translator.translate
# Create a logger for optional handling of debug messages.
logger = logging.getLogger(__name__)
logger.debug("%s successfully imported" % __name__)
EnqueuedAction =... |
skosukhin/spack | var/spack/repos/builtin/packages/liblbxutil/package.py | Python | lgpl-2.1 | 2,028 | 0.000986 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
####################################### | #######################################
from spack import *
class Liblbxutil(AutotoolsPackage):
"""liblbxutil - Low Bandwith X extension (LBX) utility routines."""
homepage = "http://cgit.freedesktop.org/xorg/lib/liblbxutil"
url = "https://www.x.org/archive/individual/lib/liblbxutil-1.1.0.tar.gz"
... |
PyBossa/pybossa-locust | mainandprojects.py | Python | agpl-3.0 | 600 | 0.011667 | from loc | ust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def login(self):
# do a login here
# self.client.post("/login", {"username":"ellen_key", "password":"ed... | et("/app/category/featured/")
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait=5000
max_wait=9000 |
mylokin/redisext | redisext/backend/rmredis.py | Python | mit | 326 | 0 | from __future__ import absolute_import
import redisext.backend.abc
import rm.rmredis
class Client(redisext.backend.abc.IClient):
def __init__(self, database=None, role=None):
| self._redis = rm.rmredis.RmRedis.get_instance(database, role)
class C | onnection(redisext.backend.abc.IConnection):
CLIENT = Client
|
s40523116/2016fallcp_hw | w4.py | Python | agpl-3.0 | 66 | 0.045455 | m | ystring="40523116"
mystring=mystring +" test"
print(mystrin | g)
|
neversun/sailfish-hackernews | src/main.py | Python | mit | 3,028 | 0.000661 | import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+ite... | es):
for r in responses:
pyotherside.send('new-item', r)
resetDownloader()
currentlyDownloading(False)
de | f resetDownloader():
global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
|
WMD-group/SMACT | smact/__init__.py | Python | mit | 14,679 | 0.011309 | """
Semiconducting Materials from Analogy and Chemical Theory
A collection of fast screening tools from elemental data
"""
# get correct path for datafiles when called from another directory
from builtins import filter
from builtins import map
from builtins import range
from builtins import object
from os ... | (self,symbol,oxidation,coordination=4, radii_source="shannon"):
Element.__init__(self,symbol)
self.oxidation = oxidation
self.coordination = coordination
# Get shannon radius for the oxidation state and coordination.
self.shannon_radius = None;
if radii_sour... | bol);
elif radii_source == "extended":
shannon_data = data_loader.lookup_element_shannon_radius_data_extendedML(symbol)
else:
print("Data source not recognised. Please select 'shannon' or 'extended'. ")
if shannon_data:
for dataset in shan... |
Cadasta/cadasta-platform | deployment/scripts/ami.py | Python | agpl-3.0 | 1,182 | 0.001692 | #!/usr/bin/env python
import sys
from os.path import normpath, join, dirname, abspath
machine_file = normpath(join(dirname(abspath(__file__)),
'../files/machine-images.csv'))
def read_machine_file():
amis = {}
with open(machine_file) as fp:
for l in fp:
type... | ):
return read_machine_file().get(type + ':' + region)
def set_ami(type, region, ami):
amis = read_machine_file()
amis[type + ':' + region] = ami
write_machine_ | file(amis)
def main(argv):
if len(argv) == 3:
print(get_ami(argv[1], argv[2]))
elif len(argv) == 4:
set_ami(argv[1], argv[2], argv[3])
else:
print("""
Usage:
Get AMI ami.py <type> <region>
Save AMI ami.py <type> <region> <ami>
""")
sys.exit(1)
if __name__ == "__mai... |
rg3/youtube-dl | youtube_dl/extractor/stv.py | Python | unlicense | 3,447 | 0.002031 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
compat_str,
float_or_none,
int_or_none,
smuggle_url,
str_or_none,
try_get,
)
class STVPlayerIE(InfoExtractor):
IE_NAME = 'stv:player'
_VALID_URL = r'https?://play... | ': 'this resource is unavailable outside of the UK',
}, {
# episodes
'url': 'https://player.stv.tv/episode/4125/jennifer-saunders-memory-lane',
'only_matching': True,
}]
BRIGHTCO | VE_URL_TEMPLATE = 'http://players.brightcove.net/1486976045/default_default/index.html?videoId=%s'
_PTYPE_MAP = {
'episode': 'episodes',
'video': 'shortform',
}
def _real_extract(self, url):
ptype, video_id = re.match(self._VALID_URL, url).groups()
webpage = self._download_... |
sharestack/sharestack-api | sharestackapi/techs/test_models.py | Python | mit | 8,113 | 0 | import random
from django.test import TestCase
from .models import TechType, Tech, Component
# shared data across the tests
types = [
{
"name": "framework",
"description": "to do web stuff"
},
{
"name": "database",
"description": "to store stuff"
},
{
"nam... | .all()), len(types))
def test_retrieval(self):
for i in types:
t = TechType(**i)
t.save()
t2 = TechType.objects.get(id=t.id)
self.assertEqual(t, t2)
def test_filter(self):
for i in types:
t = TechType(**i)
t.save()
... | ["name"])[0]
self.assertEqual(t.description, tech_type["description"])
def test_str(self):
for i in types:
t = TechType(**i)
self.assertEqual(str(t), i["name"])
class TechTests(TestCase):
def test_save(self):
for i in techs:
t = Tech(**i)
... |
mne-tools/mne-tools.github.io | 0.20/_downloads/e414d894f3f4079b3e5897dd9c691af7/plot_morph_surface_stc.py | Python | bsd-3-clause | 5,938 | 0 | """
.. _ex-morph-surface:
=============================
Morph surface source estimate
=============================
This example demonstrates how to morph an individual subject's
:class:`mne.SourceEstimate` to a common reference space. We achieve this using
:class:`mne.SourceMorph`. Pre-computed data will be morphed ... | ndTemplates) [1]_. This
transform will be used to morph the surface vertices of the subject towards the
reference vertices. Here we will use 'fsaverage' as a | reference space (see
https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage).
The transformation will be applied to the surface source estimate. A plot
depicting the successful morph will be created for the spherical and inflated
surface representation of ``'fsaverage'``, overlaid with the morphed surface
source estimate... |
bacher09/Gentoolkit | pym/gentoolkit/equery/check.py | Python | gpl-2.0 | 7,056 | 0.029337 | # Copyright(c) 2009, Gentoo Foundation
#
# Licensed under the GNU General Public License, v2
#
# $Header: $
"""Checks timestamps and MD5 sums for files owned by a given installed package"""
from __future__ import print_function
__docformat__ = 'epytext'
# =======
# Imports
# =======
import os
import sys
from funct... | return obj_errs
# =========
# Functions
# =========
def print_help(with_description=True):
"""Print description, usage and a detailed help message.
@type with_description: bool
@param with_description: if true, print module's __doc__ string
"""
if with_description:
print(__doc__.strip())
print()
# Depre... | 12/2008
depwarning = (
"Default action for this module has changed in Gentoolkit 0.3.",
"Use globbing to simulate the old behavior (see man equery).",
"Use '*' to check all installed packages.",
"Use 'foo-bar/*' to filter by category."
)
for line in depwarning:
sys.stderr.write(pp.warn(line))
print()
pr... |
adaussy/eclipse-monkey-revival | plugins/python/org.eclipse.eclipsemonkey.lang.python/Lib/test/test_module.py | Python | epl-1.0 | 1,896 | 0.004747 | # Test the module type
from test.test_support import verify, vereq, verbose, TestFailed
from types import ModuleType as module
# An uninitialized module has no __dict__ or __name__, and __doc__ is None
foo = module.__new__(module)
verify(foo.__dict__ is None)
try:
s = foo.__name__
except AttributeError:
pass
... | __, "foo")
vereq(foo.__doc__, u"foodoc\u1234")
vereq(foo.__dict__, {"__name__": " | foo", "__package__": None, "__doc__": u"foodoc\u1234"})
# Reinitialization should not replace the __dict__
foo.bar = 42
d = foo.__dict__
foo.__init__("foo", "foodoc")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, "foodoc")
vereq(foo.bar, 42)
vereq(foo.__dict__, {"__name__": "foo", "__package__": None, "__doc__": "food... |
qedsoftware/commcare-hq | corehq/apps/cloudcare/views.py | Python | bsd-3-clause | 29,447 | 0.002241 | import HTMLParser
import json
from xml.etree import ElementTree
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import get_object_or_404
fr... | ath.split('/')
app_id = split[1] if len(split) >= 2 else None
if len(split) >= 5 and split[4] == "parent":
parent_id = split[5]
case_id = split[7] if len(split) >= 7 else None
else:
parent_id = None
| case_id = split[5] if len(split) >= 6 else None
app = None
if app_id:
if app_id in [a['_id'] for a in apps]:
app = look_up_app_json(domain, app_id)
else:
messages.info(request, _("That app is |
mscuthbert/abjad | abjad/tools/rhythmtreetools/test/test_rhythmtreetools_RhythmTreeNode_duration.py | Python | gpl-3.0 | 1,469 | 0.000681 | # -*- encoding: utf-8 -*-
from abjad.tools.durationtools import Duration
from abjad.tools.rhythmtreetools import RhythmTreeContainer, RhythmTreeLeaf
def test_rhythmtreetools_RhythmTreeNode_duration_01():
tree = RhythmTreeContainer(preprolated_duration=1, children=[
RhythmTreeLeaf(preprolated_duration=1),... | tree[1].append(tree.pop | ())
assert tree.duration == Duration(1)
assert tree[0].duration == Duration(1, 3)
assert tree[1].duration == Duration(2, 3)
assert tree[1][0].duration == Duration(2, 7)
assert tree[1][1].duration == Duration(4, 21)
assert tree[1][2].duration == Duration(4, 21)
tree.preprolated_duration = 1... |
dannybrowne86/django-timepiece | timepiece/tests/factories.py | Python | mit | 6,805 | 0.000882 | import datetime
from dateutil.relativedelta import relativedelta
from decimal import Decimal
import factory
from factory.fuzzy import FuzzyDate, FuzzyInteger
import random
from django.contrib.auth import models as auth
from django.contrib.auth.hashers import make_password
from timepiece.contracts import models as con... | ry.DjangoModelFactory):
FACTORY_FOR = crm.ProjectRelationship
user = factory.SubFactory('timepiece.tests.factories.User')
project = factory.SubFactory('timepiece.tests.factories.Project')
class UserProfile(factory.DjangoModelFactory):
FACTORY_FOR = crm.UserProfile
user = factory.SubFactory('time... | ambda n: 'a{0}'.format(n))
name = factory.Sequence(lambda n: 'activity{0}'.format(n))
class BillableActivityFactory(Activity):
billable = True
class NonbillableActivityFactory(Activity):
billable = False
class ActivityGroup(factory.DjangoModelFactory):
FACTORY_FOR = entries.ActivityGroup
name... |
cpennington/edx-platform | cms/djangoapps/contentstore/api/tests/base.py | Python | agpl-3.0 | 2,906 | 0.001376 | """
Base test case for the course API views.
"""
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from lms.djangoapps.courseware.tests.factories import StaffFactory
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPL... | # The name of the view to use in reverse() call in self.get_url()
@classmethod
def setUpClass(cls):
super(BaseCourseViewTest, cls).setUpClass | ()
cls.course = CourseFactory.create(display_name='test course', run="Testing_course")
cls.course_key = cls.course.id
cls.password = 'test'
cls.student = UserFactory(username='dummy', password=cls.password)
cls.staff = StaffFactory(course_key=cls.course.id, password=cls.passwor... |
osgcc/ryzom | nel/tools/build_gamedata/processes/rbank/2_build.py | Python | agpl-3.0 | 11,551 | 0.013159 | #!/usr/bin/python
#
# \file 2_build.py
# \brief Build rbank
# \date 2009-03-10-22-43-GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Build rbank
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This program is free soft... | for dir in IgLookupDirectories:
files = findFiles(log, ExportBuildDirectory + "/" + dir, "", ".ig" | )
for file in files:
cf.write("\t\"" + os.path.basename(file)[0:-len(".ig")] + "\", \n")
cf.write("};\n")
cf.write("\n")
cf.write("Output = \"" + ExportBuildDirectory + "/" + RbankBboxBuildDirectory + "/temp.bbox\";\n")
cf.write("\n")
cf.close()
subprocess.call([ BuildIgBoxes ])
os.remove("build_ig_boxes.cf... |
mbohlool/client-python | kubernetes/client/models/v1alpha1_role_list.py | Python | apache-2.0 | 6,307 | 0.001586 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"" | "
from pprint import pformat
from six import iteritems
import re
class V1alpha1RoleList(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | ""
swagger_types = {
'api_version': 'str',
'items': 'list[V1alpha1Role]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__... |
python-hyper/priority | src/priority/__init__.py | Python | mit | 346 | 0 | # -*- coding: utf-8 -*-
" | ""
priority: HTTP/2 priority implementation for Python
"""
from .priority import ( # noqa
Stream,
PriorityTree,
DeadlockError,
PriorityLoop,
PriorityError,
DuplicateStreamError,
MissingStreamError,
TooManyStreamsError,
BadWeightError,
PseudoStreamError,
)
__ve | rsion__ = "2.0.0"
|
hammerlab/mhctools | mhctools/netmhc_cons.py | Python | apache-2.0 | 1,609 | 0.000622 | # Copyright (c) 2014-2017. Mount Sinai School of Medicine
#
# 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 applicabl... | alleles=alleles,
parse_output_fn=parse_netmhccons_stdout,
# netMHCcons does not have a supported allele flag
supported_alleles_flag=None,
length_flag="-length",
input_file_flag="-f",
allele_flag="-a",
peptide_mode_flags=["-inp... | default_peptide_lengths=default_peptide_lengths,
group_peptides_by_length=True)
|
isanwong/cctools | weaver/src/examples/batch.py | Python | gpl-2.0 | 410 | 0.004878 | uname = ParseFunction('uname -a > {OUT}')
for group in ('disc', 'ccl', 'gh'):
batch_options = 'requirements = MachineGroup == "{0}"'.format(group)
uname(outputs='uname.{0}'.format(group), environment={'BATCH_OPTIONS': batch_options})
#for group in ('disc', 'ccl', 'gh'):
# with Options(ba | tch='requirements = MachineGroup == "{0}"'.format(group)):
# uname(outputs='uname.{0}'.form | at(group))
|
FederatedAI/FATE | examples/pipeline/upload/pipeline-upload-extend-sid.py | Python | apache-2.0 | 2,416 | 0.003311 | #
# Copyright 2019 The FATE 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 appli... | kend.pipeline import PipeLine
from pipeline.utils.tools import load_job_config
def main(config="../../config.yaml", namespace=""):
# obtain config
if isinstance(config, str):
config = load_job_config(config)
| parties = config.parties
guest = parties.guest[0]
data_base = config.data_base_dir
# partition for data storage
partition = 4
# table name and namespace, used in FATE job configuration
dense_data = {"name": "breast_hetero_guest", "namespace": f"experiment{namespace}"}
tag_data = {"name": "... |
plotly/plotly.py | packages/python/plotly/plotly/validators/surface/hoverlabel/font/_color.py | Python | mit | 470 | 0.002128 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="surface.hoverlabel.font", **kwargs
):
super(C | olorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.po | p("edit_type", "none"),
**kwargs
)
|
vascotenner/holoviews | holoviews/core/util.py | Python | bsd-3-clause | 31,475 | 0.004829 | import os, sys, warnings, operator
import numbers
import itertools
import string, fnmatch
import unicodedata
from collections import defaultdict
import numpy as np
import param
try:
from cyordereddict import OrderedDict
except:
from collections import OrderedDict
try:
import pandas as pd # noqa (optional... | self_or_cls.aliases.update({v:k for k,v in kwargs.items()})
@param.parameterized.bothmethod
def remove_aliases(self_or_cls, aliases):
"""
Remove a list of aliases.
"""
for k,v in self_or_cls.aliases.items():
if v in aliases:
self_or_cls.aliases.p... | eg', 'json', 'latex',
'latex', 'pdf', 'png', 'svg', 'markdown']
disabled_ = (self_or_cls.disable_leading_underscore
if disable_leading_underscore is None
else disable_leading_underscore)
if disabled_ and name.startswith('_'):
retur... |
0ED/UnitX | doc/conf.py | Python | mit | 6,844 | 0.005552 | # -*- coding: utf-8 -*-
#
# UnitX documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 17 05:31:20 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | al links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ----------------... | t file, name, description, authors, manual section).
man_pages = [
(master_doc, 'unitx', u'UnitX Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree... |
tejesh95/Zubio.in | zubio/allauth/socialaccount/providers/flickr/tests.py | Python | mit | 1,692 | 0 | # -*- coding: utf-8 -*-
from allauth.socialaccount.tests import create_oauth_tests
from allauth.tests import MockedResponse
from allauth.socialaccount.providers import registry
from .provider import FlickrProvider
class FlickrTests(create_oauth_tests(registry.by_id(FlickrProvider.id))):
def get_mocked_response(s... | taken": {"_content": null}, "views": {"_content": "28"}, "firstdate": {"_content": null}}, "iconserver": "0", "description": {"_content": ""}, "mobileurl": {"_content": "http://m.flickr.com/photostream.gne?id=6294613"}, "profileurl": {"_content": "http://www.flickr.com/people/12345678@N00/"}, "mbox_sha1sum": {"_content... | ocation": {"_content": ""}, "id": "12345678@N00", "realname": {"_content": "raymond penners"}, "iconfarm": 0}, "stat": "ok"}
""")] # noqa
def test_login(self):
account = super(FlickrTests, self).test_login()
f_account = account.get_provider_account()
self.assertEqual(account.user.first_nam... |
softak/webfaction_demo | vendor-local/lib/python/kombu/serialization.py | Python | bsd-3-clause | 11,002 | 0.000273 | """
kombu.serialization
===================
Serialization utilities.
:copyright: (c) 2009 - 2011 by Ask Solem
:license: BSD, see LICENSE for more details.
"""
import codecs
import sys
import pickle as pypickle
try:
import cPickle as cpickle
except ImportError:
cpickle = None # noqa
from kombu.utils.encodi... | thod.
For example, `json` (default), `pickle`, `yaml`, `msgpack`,
or any custom methods registered using :meth:`register`.
:raises SerializerNotInstalled: If the serialization method
requested is not available.
"""
try | :
(self._default_content_type, self._default_content_encoding,
self._default_encode) = self._encoders[name]
except KeyError:
raise SerializerNotInstalled(
"No encoder installed for %s" % name)
def encode(self, data, serializer=None):
if serialize... |
ekivemark/BlueButtonDev | appmgmt/utils.py | Python | apache-2.0 | 1,004 | 0.002988 | # -*- coding: utf-8 -*-
"""
BlueButtonDev.appmgmt
FILE: utils
Created: 12/2/15 8:09 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
from django.contrib import message | s
from .models import DEVELOPER_ROLE_CHOICES
from django.conf import settings
def Choice_Display(role):
"""
Receive a string of the current role
Lookup in DEVELOPER_ROLE_CHOICES
Return the String
:param role:
:return:
"""
result = dict(DEVELOPER_ROLE_CHOICES).get(role)
if role == ... | essages when using Class Based Views.
"""
def delete(self, request, *args, **kwargs):
messages.success(self.request, self.success_message)
return super(MessageMixin, self).delete(request, *args, **kwargs)
def form_valid(self, form):
messages.success(self.request, self.success_messag... |
DeeDee22/nelliepi | src/ch/fluxkompensator/nelliepi/IPAddressFinder.py | Python | gpl-2.0 | 283 | 0.021201 | '''
Created on Jun 15, 2014
@author: geraldin | e
'''
import socket
import fcntl
impor | t struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[20:24]) |
cliffano/swaggy-jenkins | clients/python-blueplanet/generated/app/openapi_server/models/github_repositorypermissions.py | Python | mit | 3,754 | 0.002397 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from app.openapi_server.models.base_model_ import Model
from openapi_server import util
class GithubRepositorypermissions(Model):
"""NOTE: This class is auto gene... | admin: bool=None, push: bool=None, pull: bool=None, _class: str=None): # noqa: E501
"""GithubRepositorypermissions - a model defined in Swagger
:param admin: The admin of this GithubRepositorypermissions. # noqa: E501
:type admin: bool
:param push: The push of this GithubRepositoryper... | :param pull: The pull of this GithubRepositorypermissions. # noqa: E501
:type pull: bool
:param _class: The _class of this GithubRepositorypermissions. # noqa: E501
:type _class: str
"""
self.swagger_types = {
'admin': bool,
'push': bool,
'pu... |
USTB-LETTers/judger | exceptions.py | Python | mit | 256 | 0 | # -*- coding: utf-8 -*-
class CrazyBoxError(Exce | ption):
"""
The base class for custom exceptions raised by crazybox.
"""
pass
class DockerError(Exception):
"""
An error occurred with the un | derlying docker system.
"""
pass
|
cfc603/django-twilio-sms-models | tests/test_models.py | Python | bsd-3-clause | 25,815 | 0 | import datetime
from django.test import override_settings, TestCase
from django_twilio.models import Caller
from mock import Mock, patch, PropertyMock
from model_mommy import mommy
from twilio.rest.exceptions import TwilioRestException
from .mommy_recipes import caller_recipe, message_recipe, phone_number_recipe
fro... | y.make(ApiVersion)
self.assertEqual(
'{}'.format(api_version.date), api_version.__str__()
)
def test_get_or_create_created_false(self):
api_version = mommy.make(ApiVersion)
self.assertEqual(
api_version, ApiVersion.get_or_create(api_version.date)
)
... | .get_or_create(date)
self.assertEqual(date, api_version.date)
self.assertEqual(1, ApiVersion.objects.all().count())
class CurrencyModelTest(CommonTestCase):
def test_unicode(self):
self.string_test('Currency', 'abc', **{'code': 'abc'})
def test_get_or_create_created_false(self):
... |
netoaraujjo/hal | clustering/agglomerative_clustering.py | Python | mit | 1,946 | 0.023124 | #-*- coding: utf-8 -*-
import numpy as np
from sklearn.cluster import AgglomerativeClustering as sk_AgglomerativeClustering
from sklearn.externals.joblib import Memory
from .clustering import Clustering
class AgglomerativeClustering(Clustering):
"""docstring for AgglomerativeClustering."""
def __init__(self, d... | ,
affinity = self.affinity,
memory = self.memory,
connectivity = self.connectivity,
compute_full_tree = self.compute_full_tree,
| linkage = self.linkage,
pooling_func = self.pooling_func).fit(self.data)
self.clusters = super().make_clusters(self.data, self.model.labels_)
@property
def labels_(self):
"""Retorna os labels dos elementos do dataset."""
... |
toladata/TolaTables | silo/migrations/0029_auto_20170915_0810.py | Python | gpl-2.0 | 1,233 | 0.003244 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-15 15:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('silo', '0028_auto_20170913_0206'),
]
operations = ... | user',
name='workflowlevel1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1'),
),
migrations.AlterField(
model_name='workflowlevel2',
name='activity_id',
field=models.Integer... | name='workflowlevel1',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1'),
),
]
|
damonmcminn/rosalind | boilerplate.py | Python | gpl-2.0 | 183 | 0 | from os | import path
rosalind_id = path.basename(__file__).split | ('.').pop(0)
dataset = "../datasets/rosalind_{}.txt".format(rosalind_id)
data = open(dataset, 'r').read().splitlines()
|
shawnadelic/shuup | shuup/xtheme/plugins/category_links.py | Python | agpl-3.0 | 2,994 | 0.001002 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.utils.translation import ugettext_lazy ... | for request customer.
"""
selected_categories = self.config.get("categories", [])
show_all_categories = self.config.get("show_all_categories", True)
request = context.get("request")
categories = Category.objects.all_visible(
customer=getattr(request, "customer"),
... | )
if not show_all_categories:
categories = categories.filter(id__in=selected_categories)
return {
"title": self.get_translated_value("title"),
"categories": categories,
}
|
jpetto/olympia | src/olympia/amo/views.py | Python | bsd-3-clause | 5,726 | 0 | import json
import os
import re
from django import http
from django.conf import settings
from django.db.transaction import non_atomic_requests
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache... | tatsd.clients import statsd
from olympia import amo, api
from olympia.amo.utils import log_cef
from . import monitors
log = commonware.log.getLogger('z.amo')
monit | or_log = commonware.log.getLogger('z.monitor')
jp_log = commonware.log.getLogger('z.jp.repack')
flash_re = re.compile(r'^(Win|(PPC|Intel) Mac OS X|Linux.+i\d86)|SunOs',
re.IGNORECASE)
quicktime_re = re.compile(
r'^(application/(sdp|x-(mpeg|rtsp|sdp))|audio/(3gpp(2)?|AMR|aiff|basic|'
r'mi... |
MaxTyutyunnikov/lino | lino/utils/config.py | Python | gpl-3.0 | 11,277 | 0.018003 | # -*- coding: UTF-8 -*-
## Copyright 2009-2013 Luc Saffre
## This file is part of the Lino project.
## Lino 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 y... | iles(loader,pattern,group=''):
"""
Naming conventions for :xfile:`*.dtl` files are:
- the first detail is called appname.Model.dtl
- If there are more Details, then they are called
appname.Model.2.dtl, appname.Model.3.dtl etc.
The `sort()` below must remove the filename exte... | = find_config_files(pattern,group).items()
def fcmp(a,b):
return cmp(a[0][:-4],b[0][:-4])
files.sort(fcmp)
prefix = group.replace("/",os.sep)
for filename,cd in files:
filename = join(prefix,filename)
ffn = join(cd.name,filename)
logger.debug("Loading %s...",ffn)... |
hrroon/literoticapi | test/author_test.py | Python | gpl-3.0 | 290 | 0.006897 | import unittest
from literoticapi.author import *
class testStory(unittest.Tes | tCase):
def setUp(self):
self.a | uthor = Author(868670)
def testGetSeriesAndNonSeries(self):
assert len(self.author.get_stories()) >= 132
if __name__ == "__main__":
unittest.main()
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/testfixtures/tests/test_wrap.py | Python | agpl-3.0 | 5,995 | 0.012677 | # Copyright (c) 2008 Simplistix Ltd
# See license.txt for license details.
from mock import Mock
from testfixtures import wrap,compare
from unittest import TestCase,TestSuite,makeSuite
class TestWrap(TestCase):
def test_wrapping(self):
m = Mock()
@wrap(m.before,m.after)
def test_functio... | m.before1,m.after1)
def test_function(r1,r2):
m.test_function(r1,r2)
return 'something'
compare(m.method_calls,[])
compare(test_function(),'something')
compare(m.method_calls,[
('before1', (), {}),
('before2', (), {}),
('test_f... | }),
])
def test_multiple_wrappers_only_want_first_return(self):
m = Mock()
m.before1.return_value=1
@wrap(m.before2,m.after2)
@wrap(m.before1,m.after1)
def test_function(r1):
m.test_function(r1)
return 'something'
compar... |
arizvisa/syringe | lib/ia32/_optable.py | Python | bsd-2-clause | 2,339 | 0 | OperandLookupTable = b''.join([
b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00'
b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00'
b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00'
b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00'
... | 0\x00\x00\x00\x00\xbd\x00\xc1'
b'\x84\x84\x88\x88\x88\x88\x88\x88\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd'
b'\x84\x84\x84\x84\x84\x00\x84\x00\x84\x84\x88\x84\x84\x84\x84\x84'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd\xbd'
... | c1\xc1\xc1\xc1\x88\x88\x88\x00\x84\x84\x00\x00\x84\x84\x88\x88'
b'\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d\x7d'
b'\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81\x81'
b'\x00\x00\x00\xbd\xc1\xbd\x00\x00\x00\x00\x00\xbd\xc1\xbd\x84\xbd'
b'\x81\xbd\xba\xbd\xba\xba\x81\x82\x... |
BD777/WindPythonToy | comm/network.py | Python | apache-2.0 | 7,827 | 0.004999 | # -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup, UnicodeDammit
import time
import os
import re
import log
import tools
class Get(object):
# timeout, retry_interval -> seconds
def __init__(self, url='', timeout=5, retry=5, retry_interval=2, proxies={}, headers={}, download_file=None, sav... | os:]
pos = fn.rfind('.')
if pos >= len(fn) or pos == -1:
pass
else:
if suf == '':
suf = fn[pos:]
try:
fn = fn[:pos]
except Exception as e:
pass
filename = fn
dammit = UnicodeDammit(fi... | 重名的文件,并做处理
i = 0
while True:
if i == 0:
if not os.path.exists( os.path.join(self.savepath, filename+suf) ):
break
else:
if not os.path.exists( os.path.join(self.savepath, filename+("(%d)"%i)+suf ) ):
filename... |
nirmeshk/oh-mainline | vendor/packages/django-debug-toolbar/debug_toolbar/panels/profiling.py | Python | agpl-3.0 | 4,968 | 0.000201 | from __future__ import absolute_import, division, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from debug_toolbar.panels import Panel
from debug_toolbar import settings as dt_settings
import cProfile
from pstats import Stats
from colorsys impor... | Panel that displays profiling information.
"""
title = _("Profiling")
template = 'debug_toolbar/panels/profiling.html'
def process_view( | self, request, view_func, view_args, view_kwargs):
self.profiler = cProfile.Profile()
args = (request,) + view_args
return self.profiler.runcall(view_func, *args, **view_kwargs)
def add_node(self, func_list, func, max_depth, cum_time=0.1):
func_list.append(func)
func.has_sub... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/pip/_internal/models/scheme.py | Python | apache-2.0 | 770 | 0 | """
For types associated with installation schemes.
For a general overview of available schemes and their context, see
https://docs.python.org/3/install/index.html#alternate-installation.
"""
SCHEME_KEYS = ['platlib', 'purelib', 'headers', 'scripts', 'data']
class Scheme:
"""A Scheme holds paths which are used... | platli | b, # type: str
purelib, # type: str
headers, # type: str
scripts, # type: str
data, # type: str
):
self.platlib = platlib
self.purelib = purelib
self.headers = headers
self.scripts = scripts
self.data = data
|
luckyleap/NLP_Projects | MSChallenge Ngrams/MSChallengeNGrams.py | Python | mit | 908 | 0.030837 | # David Tsui 2.9.2016
# Human Languages and Technologies
# Dr. Rebecca Hwa
from Ngrams import *
#TRAIN
train_file = open("tokenized_train.txt","r")
train_str = train_file.read();
tri = Trigram(1)
print "Begin training vocabul | ary----------------------"
tri.trainVocabulary(train_str)
#tri.printVocabulary()
#Takes in questions for development
dev_file = open("Holmes.lm_format.questions.txt")
output_file = open("holmes_output.txt","w+")
print "Begin calculating perplexity------- | ---------------"
for i, line in enumerate(dev_file):
#Clean text by removing all quotations
line = line[:-1]
exclude = set(string.punctuation)
s = ''.join(ch for ch in line if ch not in exclude)
s = s.lower()
#Lambda factors
lu = .3
lb = .3
lt = .4
print "Question %d complete" %(i)
perplexity = tri.getPerWor... |
lino-framework/lino | lino/modlib/system/models.py | Python | bsd-2-clause | 4,683 | 0.002776 | # -*- coding: UTF-8 -*-
# Copyright 2009-2019 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
from django.conf import settings
from django.utils.encoding import force_str
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.apps... | %r" % k)
setattr(self, k, v)
self.full_clean()
self.save()
def save(self, *args, **kw):
# print("20180502 save() {}".format(dd.obj2str(self, True)))
super(SiteConfig, self).save(*args, **kw)
settings.SITE.clear_s | ite_config()
def my_handler(sender, **kw):
# print("20180502 {} my_handler calls clear_site_config()".format(
# settings.SITE))
settings.SITE.clear_site_config()
#~ kw.update(sender=sender)
# dd.database_connected.send(sender)
#~ dd.database_connected.send(sender,**kw)
from django.test.si... |
FEniCS/ufl | demo/ExplicitConvection.py | Python | lgpl-3.0 | 332 | 0 | #
# Author: Martin Sandve Alnes |
# Date: 2008-10-03
#
from ufl import (Coe | fficient, TestFunction, TrialFunction, VectorElement, dot,
dx, grad, triangle)
element = VectorElement("Lagrange", triangle, 1)
u = TrialFunction(element)
v = TestFunction(element)
w = Coefficient(element)
a = dot(dot(w, grad(u)), v) * dx
|
hhucn/netsec-uebungssystem | netsecus/korrekturserver.py | Python | mit | 4,455 | 0.000673 | from __future__ import unicode_literals
import logging
import os
import tornado.ioloop
import tornado.web
from .webhandler.DownloadHandler import DownloadHandler
from .webhandler.OverviewHandler import OverviewHandler
from .webhandler.GradingPreviewMailsHandler import GradingPreviewMailsHandler
from .webhandler.Grad... | port SubmissionsListAllHandler
from .webhandler.SubmissionsListCurrentHandler import SubmissionsListCurrentHandler
from .webhandler.SubmissionsListUnfinishedHandler import SubmissionsListUnfinishedHandler
from .webhandler.SubmissionStudentSheetHandler import SubmissionStudentSheetHandler
from .webhandler.TaskCreateHand... | er.TaskEditHandler import TaskEditHandler
from .webhandler.UpdateDatabaseHandler import UpdateDatabaseHandler
from .webhandler.contact import (
ContactCraftHandler,
ContactSendHandler,
ContactAllCraftHandler,
ContactAllSendHandler,
)
from .webhandler.merge import (
MergeSelectHandler,
MergePrevi... |
mgolub2/Breadcrumb | ESP8266/chain_simulator.py | Python | gpl-3.0 | 4,013 | 0.005981 | #!/usr/local/bin/python3.5
"""
Author: Maximilian Golub
Simulate the chain parsing and replying to a http request to test
the ESP8266
"""
import serial
import socket
import re
import traceback
import sys
import subprocess
import time
PORT = '/dev/cu.usbserial-FTZ29WSV' #OSX
#PORT = 'COM3' # If on windows
BAUD = 1152... | GET/POST whatever request from the Wifi device attached to the
ESP8266. Looks for the Host header, trys to get the host+port with regex.
:param data:
:param serial_socket:
:return:
"""
try:
host_match = re.search('Host: (\S+)\\r\\n', data)
if host_match:
| host = host_match.group(1)
#print(host)
try:
host, port = host.split()
except ValueError:
port = 80
if host == "192.168.1.1:8080": # Special case to test basic functionality level.
with open('hackaday.txt', 'r') as d:
... |
siggame/webserver | webserver/codemanagement/management/commands/update_repos.py | Python | bsd-3-clause | 4,248 | 0.000235 | from django.core.management.base import BaseCommand
from webserver.codemanagement.models import TeamClient
import os
import re
import tempfile
import subprocess
class Command(BaseCommand):
help = 'Attempts to update all repositories by pulling from bases'
def handle(self, *args, **options):
# A lis... |
stderr=subprocess.PIPE)
out, err = pull.communicate()
if pull.returncode != 0:
errors.append(
("Failed to pull into {0}'s repo".format(client.team.name),
repo_directory,
out + err)... | )
continue
####################
# Push
####################
self.stdout.write("\tPushing...\n")
push = subprocess.Popen(["git", "push"],
cwd=repo_directory,
stdout=subp... |
vgrem/Office365-REST-Python-Client | office365/sharepoint/files/checkedOutFileCollection.py | Python | mit | 350 | 0.002857 | from office365.sharepoint.base_entity_collection import BaseEntityCollection
from office365.sharepoint.files.checkedOu | tFile import | CheckedOutFile
class CheckedOutFileCollection(BaseEntityCollection):
def __init__(self, context, resource_path=None):
super(CheckedOutFileCollection, self).__init__(context, CheckedOutFile, resource_path)
|
who-emro/meerkat_abacus | meerkat_abacus/util/data_types.py | Python | mit | 555 | 0.009009 | import csv
from meerkat_abacus.config import config
def data_types(param_config=config):
with open(param_config.config_directory + param_config.country_config["types_file"],
"r", encoding='utf-8',
errors="replac | e") as f:
DATA_TYPES_DICT = [_dict for _dict in csv.DictReader(f)]
return DATA_TYPES_DICT
def data_types_for_form_name(form_name, param_config=config):
return [data_type for data_ | type in data_types(param_config=param_config) if form_name == data_type['form']]
DATA_TYPES_DICT = data_types() |
mashedkeyboard/Headlights | handlers.py | Python | gpl-3.0 | 429 | 0.016317 | import logging
from time import strftime
def closed():
logging.info('Headli | ghts process stopped')
def criterr(errortext):
logging.critical('A fatal error occured :: ' + errortext)
exit()
def err(errortext):
logging.error('An error occured :: ' + errortext)
def warn(errortext):
logging.warning(errortext)
def inf(errortext):
logging.info(errortext)
def debug(errortext):... | logging.debug(errortext) |
chapman-cpsc-230/hw1-grazi102 | sin2_plus_cos2.py | Python | mit | 1,198 | 0.004174 |
"""
File: <Sin2_plus_cos2>
Copyright (c) 2016 <Lauren Graziani>
License: MIT
<debugging a program>
"""
"""
# a
from math import sin, cos #need to import pi from math
x = pi/4
1_val = math.sin^2(x) + math.cos^2(x) #can't start a variable with a number, powers are written by **
print 1_VAL
"""
# a debugged
from m... | .t should be v0*2, change comma to period and periods to *
print s
"""
# b debugged
v0 = 3
t = 1
a = 2 ** 2
s = v0*t + 0.5*a*t**2
print s
#c
"""
a = 3,3 b = 5,3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2ab + b2
eq2_sum = a2 - (2ab + b2
eq1_pow = (a+b)**2
eq2_pow = (a-b)**2
print 'First equation: %g = %g', % (eq1_sum, eq1_po... | 1_pow = (a+b)**2
eq2_pow = (a-b)**2
print "First equation: %g = %g" % (eq1_sum, eq1_pow)
print "Second equation: %h = %h" % (eq2_pow, eq2_pow)
"""
|
caot/intellij-community | python/testData/inspections/PyPropertyDefinitionInspection25/src/prop_test.py | Python | apache-2.0 | 1,700 | 0.042941 | class A(object):
def __init__(self, bar):
self._x = 1 ; self._bar = bar
def __getX(self):
return self._x
def __setX(self, x):
self._x = x
def __delX(self):
pass
x1 = property(__getX, __setX, __delX, "doc of x1")
x2 = property(__setX) # should return
x3 = property(__getX, __getX) # shou... | 5
self._x = x
@boo.deleter
def boo2(self): # ignored in 2,5
pass
@property
def moo(self): # should return
pass
@moo.setter
def foo(self, x):
return 1 # ignored in 2.5
@foo.deleter
def foo(self):
return self._x # ignored in 2.5
@qoo.setter # unknown qoo is reported in ref ... | n
def qoo(self, v):
self._x = v
@property
def bar(self):
return None
class Ghostbusters(object):
def __call__(self):
return "Who do you call?"
gb = Ghostbusters()
class B(object):
x = property(gb) # pass
y = property(Ghostbusters()) # pass
z = property(Ghostbusters) # pass
class Eternal(o... |
tornadoalert/kmcoffice | venue/migrations/0006_eventcalander.py | Python | gpl-3.0 | 725 | 0.002759 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-25 12:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('venue', '0005_auto_20170916_0701'),
]
operations = [
migrations.CreateModel... | 'name', models.CharField(default='Default Event' | , max_length=200)),
('calander_id', models.TextField()),
('active', models.BooleanField(default=True)),
],
),
]
|
mikeireland/pyghost | pyghost/extract.py | Python | mit | 20,005 | 0.024144 | """Given (x,wave,matrices, slit_profile), extract the flux from each order. For
readability, we keep this separate from the simulator.... but the simulator is
required in order to run this.
To run, create a simulated fits file (e.g. "test_blue.fits") using ghostsim then:
blue_high = pyghost.extract.Extractor('blue',... | the configuration | . For GHOST, it can be "red" or "blue".
The extraction is defined by 3 key parameters: an "x_map", which is equivalent to
2dFDR's tramlines and contains a physical x-coordinate for every y (dispersion direction)
coordinate and order, and a "w_map", which is the wavelength corresponding to every y
(... |
crustymonkey/r53-dyndns | libr53dyndns/errors.py | Python | gpl-2.0 | 133 | 0.015038 |
class IPParseError( | Exception):
pass
class ZoneNotFoundError(Exception):
pass
class InvalidInputErro | r(Exception):
pass
|
linkhub-sdk/popbill.cashbill.example.py | getChargeInfo.py | Python | mit | 1,259 | 0.001747 | # -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import CashbillService, PopbillException
cashbillService = CashbillService | (testValue.LinkID, testValue.SecretKey)
cashbillService.IsTest = testValue.IsTest
cashbillService.IPRestrictOnOff = testValue.IPRestrictOnOff
cashbillService.UseStaticIP = testValue.UseStaticIP
cashbillService.UseLocalTimeYN = testValue.UseLocalTimeYN
'''
연동회원의 현금영수증 API 서비스 과금정보를 확인합니다.
- https://docs.popbill.com/cas... |
response = cashbillService.getChargeInfo(CorpNum, UserID)
print(" unitCost (발행단가) : %s" % response.unitCost)
print(" chargeMethod (과금유형) : %s" % response.chargeMethod)
print(" rateSystem (과금제도) : %s" % response.rateSystem)
except PopbillException as PE:
print("Exception Occur : [%d] %s" % (PE.cod... |
ray-project/ray | python/ray/util/sgd/torch/examples/tune_example.py | Python | apache-2.0 | 5,267 | 0.00019 | # fmt: off
"""
This file holds code for a Distributed Pytorch + Tune page in the docs.
FIXME: We switched our code formatter from YAPF to Black. Check if we can enable code
formatting on this module and update the paragraph below. See issue #21318.
It ignores yapf because yapf doesn't allow comments right after code ... | "--num-workers",
"-n",
type=int,
default=1,
help="Sets number of workers for training.")
parser.add_argument(
"--use-gpu",
action="store_true",
default=False,
help="Enables GPU training")
parser.add_argument(
"--lr-reduce-o | n-plateau",
action="store_true",
default=False,
help="If enabled, use a ReduceLROnPlateau scheduler. If not set, "
"no scheduler is used."
)
args, _ = parser.parse_known_args()
if args.smoke_test:
ray.init(num_cpus=3)
elif args.server_address:
ray.i... |
mlperf/training_results_v0.7 | Google/benchmarks/resnet/implementations/resnet-cloud-TF2.0-tpu-v3-32/tf2_common/utils/mlp_log/test_mlp_log.py | Python | apache-2.0 | 739 | 0.00406 | """Test MLPerf logging.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import | json
import sys
import pytest
from tensorflow_models.mlperf.models.rough.mlp_log import mlp_log
class TestMLPerf | Log(object):
"""Test mlperf log."""
def test_format(self):
msg = mlp_log.mlperf_format('foo_key', {'whiz': 'bang'})
parts = msg.split()
assert parts[0] == ':::MLL'
assert float(parts[1]) > 10
assert parts[2] == 'foo_key:'
j = json.loads(' '.join(parts[3:]))
assert j['value'] == {'whiz':... |
ricotabor/opendrop | opendrop/app/keyboard.py | Python | gpl-2.0 | 1,940 | 0 | # Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com)
# OpenDrop is released under the GNU GPL License. You are free to
# modify and distribute the code, but always under the same license
# (i.e. you cannot make commercial derivatives).
#
# If you use this software in your research, please cite the foll... | ournal of
# Open Source Software
#
# These citations help us not only to understand who is using and
# developing OpenDrop, and for what purpose, but also to justify
# continued development of this code and other open source resources.
#
# OpenDrop is distributed WITHOUT ANY WARRANTY; without even the
# implied warrant... | eceived a copy of the GNU General Public License along
# with this software. If not, see <https://www.gnu.org/licenses/>.
from enum import IntEnum
from gi.repository import Gdk
class Key(IntEnum):
UNKNOWN = -1
Up = Gdk.KEY_Up
Right = Gdk.KEY_Right
Down = Gdk.KEY_Down
Left = Gdk.KEY_Left
... |
qubs/data-centre | climate_data/migrations/0020_annotation.py | Python | apache-2.0 | 1,145 | 0.003493 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-13 03:20
from __future__ import unicode_literals
import django.contrib.postgres.fields.ranges
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('climate_data',... | ('time_range', django.contrib.postgres.fields.ranges.DateTimeRangeField()),
('comment', models.TextField()),
| ('sensor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='climate_data.Sensor')),
('station', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='climate_data.Station')),
],
),
]
|
chenke91/ckPermission | settings.py | Python | mit | 313 | 0.003195 | #coding:utf-8
bind = 'unix:/var/run/ | gunicorn.sock'
workers = 4
# you should change this
user = 'root'
# maybe you like error
loglevel = 'debug'
errorlog = ' | -'
logfile = '/var/log/gunicorn/debug.log'
timeout = 300
secure_scheme_headers = {
'X-SCHEME': 'https',
}
x_forwarded_for_header = 'X-FORWARDED-FOR'
|
ikn/o | game/engine/entity.py | Python | gpl-3.0 | 884 | 0.003394 | """Entities: things that exist in the world."""
from .gfx import GraphicsGroup
from .util import ir
class Entity (object):
"""A thing that exists in the world.
Entity()
Currently, an entity is just a container of graphics.
"""
def __init__ (self):
#: The :class:`World <engine.game.World>` this en... | roup>`
#: containing the entity's graphics, with ``x=0``, ``y=0``.
self.graphics = GraphicsGroup()
def added (self):
"""Called whenever the entity is added to a world.
This is called after | :attr:`world` has been changed to the new world.
"""
pass
def update (self):
"""Called every frame to makes any necessary changes."""
pass
|
supistar/Botnyan | plugins/drive.py | Python | mit | 603 | 0 | # -*- encoding:utf8 -*-
from model.parser import Parser
from model.googledr | ive import GoogleDrive
from plugins.base.responsebase import IResponseBase
class Drive(IResponseBase):
def hear_ | regex(self, **kwargs):
lists = Parser().get_keyword_list(expand=True)
print("Lists : %r" % lists)
return "^({0})$".format("|".join(lists))
def response(self, **kwargs):
drive_kwargs = {
'document_id': Parser().get_document_id(kwargs.get('text')),
'export_type... |
antoinecarme/pyaf | tests/artificial/transf_Logit/trend_MovingMedian/cycle_0/ar_/test_artificial_32_Logit_MovingMedian_0__100.py | Python | bsd-3-clause | 263 | 0.087452 | import pyaf.Bench.TS_datase | ts as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedia | n", cycle_length = 0, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 0); |
dumoulinj/ers | ers_backend/ers_backend/celery.py | Python | mit | 607 | 0.001647 | from __future__ import absolute_import
import os
from celery import Celery
# set the default | Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ers_backend.settings')
from django.conf import settings
app = Celery('dataset_manager', backend="redis://localhost")
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.co... | {0!r}'.format(self.request))
|
FrostLuma/Mousey | mousey/bot/context.py | Python | mit | 2,070 | 0 | # -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 - 2018 FrostLuma
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, c... | license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT W... | ENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 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.
"""
from mousey import commands
from mousey.utils import haste, Time... |
caseywstark/colab | colab/apps/object_feeds/templatetags/object_feeds_tags.py | Python | mit | 2,666 | 0.007127 | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
### Show an update instance ###
@register.inclusion_tag("feeds/update.html", takes_context=True)
def show_update(context, update):
feed_object = update.feed.feed_object
... | subscription_url = reverse('feeds_subscription', kwargs={'feed_id': feed.id})
if user.is_authenticated():
subscription = feed.is_user_follo | wing(user)
else:
subscription = None
return {'subscription_url': subscription_url, 'subscription': subscription,
'extra_text': extra_text, 'feed': feed,
'STATIC_URL': settings.STATIC_URL}
|
mrchristine/spark-examples-dbc | src/main/python/ml/max_abs_scaler_example.py | Python | apache-2.0 | 1,515 | 0.00066 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | ransform | (dataFrame)
scaledData.show()
# $example off$
spark.stop()
|
eteamin/spell_checker_web_api | scwapi/__init__.py | Python | gpl-3.0 | 49 | 0 | # -*- codin | g: utf-8 -*-
"""The scwapi package | """
|
bengosney/rhgd3 | gardens/migrations/0024_auto_20180215_2316.py | Python | gpl-3.0 | 759 | 0.001318 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-02-15 23:16
from __future__ import unicode_literals
from django.db import migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('gardens', '0023_auto_20180215_2314'),
]
operations = [
... | model_name='maintenancephoto',
name='main',
),
migrations.AddField(
model_name='maintenancephoto',
name='large',
field=image_cropping.fields.ImageRatioField('image', '600x400', adapt_rotation=False, allow_fullsize=False, free_crop=False, help_text=Non... | |
wxiang7/airflow | airflow/operators/__init__.py | Python | apache-2.0 | 2,497 | 0.0004 | # Imports operators dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils.helpers import import_module_attrs as _import_module_attrs
# These need to be integrated first as other operators depend on them
_import_module_attrs(globals(), {
'check_operator': [
... | '],
'hive_stats_operator': ['HiveStatsCollectionOperator'],
's3_to_hive_operator': ['S3ToHiveTransfer'],
'hive_to_mysql': ['HiveToMySqlTransfer'],
'presto_to_mysql': ['PrestoToMySqlTransfer'],
's3_file_transform_operator': ['S3FileTransformOperator'],
'http_operator': ['SimpleHttpOperator'],
... | rator': ['MsSqlOperator'],
'mssql_to_hive': ['MsSqlToHiveTransfer'],
'slack_operator': ['SlackAPIOperator', 'SlackAPIPostOperator'],
'generic_transfer': ['GenericTransfer'],
'oracle_operator': ['OracleOperator']
}
_import_module_attrs(globals(), _operators)
from airflow.models import BaseOperator
def... |
fangdingjun/dnsproxy | third-part/ldns-1.6.17/contrib/python/examples/python3/ldns-newpkt.py | Python | gpl-3.0 | 476 | 0.014706 | #!/usr/bin/python
import ldns
pkt = ldns.ldns_pkt.new_query_frm_str("www.google.com",ldns.LDNS_RR_TYPE_ANY, ldns.LDNS_RR_CLASS_IN, ldns.LDNS_QR | ldns. | LDNS_AA)
rra = ldns.ldns_rr.new_frm_str("www.google. | com. IN A 192.168.1.1",300)
rrb = ldns.ldns_rr.new_frm_str("www.google.com. IN TXT Some\ Description",300)
list = ldns.ldns_rr_list()
if (rra): list.push_rr(rra)
if (rrb): list.push_rr(rrb)
pkt.push_rr_list(ldns.LDNS_SECTION_ANSWER, list)
print("Packet:")
print(pkt)
|
zcoinofficial/zcoin | src/bls-signatures/python-impl/aggregation_info.py | Python | mit | 6,831 | 0 | from util import hash256, hash_pks
from copy import deepcopy
class AggregationInfo:
"""
AggregationInfo represents information of how a tree of aggregate
signatures was created. Different tress will result in different
signatures, due to exponentiations required for security.
An AggregationInfo i... | onInfo(new_tree, message_hashes, public_keys)
@staticmethod
def secure_merge_infos(colliding_infos):
"""
Infos are merged together with combination of exponents
"""
# Groups are sorted by message then pk then exponent
# Each info object (and all | of it's exponents) will be
# exponentiated by one of the Ts
colliding_infos.sort()
sorted_keys = []
for info in colliding_infos:
for key, value in info.tree.items():
sorted_keys.append(key)
sorted_keys.sort()
sorted_pks = [public_key for (mess... |
citrix-openstack-build/python-keystoneclient | keystoneclient/middleware/auth_token.py | Python | apache-2.0 | 50,380 | 0.000099 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-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 r... | ame, tenant, etc
Refer to: http://keystone.openstack.org/middlewarearchitecture.html
HEADERS
-------
* Headers starting with HTTP\_ is a standard http header
* Headers starting with HTTP_X is an extended http header
Coming in from initial | call from client or customer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
HTTP_X_AUTH_TOKEN
The client token being passed in.
HTTP_X_STORAGE_TOKEN
The client token being passed in (legacy Rackspace use) to support
swift/cloud files
Used for communication between components
^^^^^^^^^^^^^^^^^^^^^^^... |
jklaiho/django-class-fixtures | class_fixtures/tests/tests_dumpdata.py | Python | bsd-3-clause | 11,960 | 0.008027 | import re
from django.core.management import call_command
from django.test import TestCase
from class_fixtures.tests.models import (Band, Musician,
Membership, Roadie, Competency, JobPosting, ComprehensiveModel)
from class_fixtures.utils import string_stdout
class DumpDataTests(TestCase):
def test_encoding_de... | e().split('\n')
self.assertEqual(lines[11], """tests_band_fixture.add(1, **{'name': u"The Apostrophe's Apostles"})""")
self.assertEqual(lines[12], """tests_musician_fixture.add(1, **{'name': u'Ivan "The Terrible" Terrible'})""")
# Raw string to represent what's actually printed out, ... | self.assertEqual(lines[13], r"""tests_musician_fixture.add(2, **{'name': u'\\, aka the artist formerly known as Backslash'})""")
self.assertEqual(lines[14], """tests_membership_fixture.add(1, **{'band': 1, 'date_joined': datetime.date(2000, 12, 5), 'instrument': u'Bass', 'musician': 1})""")
... |
saketkc/ribo-seq-snakemake | configs/Oct_10_2016_HuR_Human_rna.py | Python | bsd-3-clause | 2,343 | 0.012804 |
## Absolute location where all raw files are
RAWDATA_DIR = '/home/cmb-06/as/skchoudh/dna/Oct_10_2016_HuR_Human_Mouse_Liver/rna-seq/Penalva_L_08182016/human'
## Output directory
OUT_DIR = '/staging/as/skchoudh/Oct_10_2016_HuR_Human_Mouse_Liver/RNA-Seq_human'
## Absolute location to 're-ribo/scripts' directory
SRC_... | Path to bed file with start codon coordinates
START_CODON_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.start_codon.bed'
## Path to bed file with stop codon coordinates
STOP_CODON_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.stop_codon.bed'
## Pa... | s.cds.bed'
# We don't have these so just use CDs bed to get the pipeline running
UTR5_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.UTR5.bed'
UTR3_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.UTR3.bed'
## Name of python2 environment
## The followin... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/unittest/suite.py | Python | unlicense | 10,084 | 0.00119 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: suite.py
"""TestSuite"""
import sys
from . import case
from . import util
__unittest = True
def _call_if_exists(parent, attr):
func = getattr(pa... | currentClass._classSetupFailed = True
className = util.strclass(currentClass)
errorName | = 'setUpClass (%s)' % className
self._addClassOrModuleLevelException(result, e, errorName)
finally:
_call_if_exists(result, '_restoreStdout')
return
def _get_previous_module(self, result):
previousModule = None
previousClass ... |
beiko-lab/gengis | bin/Lib/site-packages/scipy/linalg/cblas.py | Python | gpl-3.0 | 362 | 0.002762 | """
This module is deprecated -- use scipy.linalg.blas instead
"""
from __future__ import division, print_func | tion, absolute_import
try:
from ._cblas import *
except ImportError:
empty_module = True
import numpy as _np |
@_np.deprecate(old_name="scipy.linalg.cblas", new_name="scipy.linalg.blas")
def _deprecate():
pass
_deprecate()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.