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 |
|---|---|---|---|---|---|---|---|---|
jtsommers/dijkd | p1.py | Python | gpl-2.0 | 3,077 | 0.039649 | from p1_support import load_level, show_level
from math import sqrt
from heapq import heappush, heappop
import operator
VERBOSE = False
def debug(*args):
if (VERBOSE):
print ''.join([str(arg) for arg in args])
def dijkstras_shortest_path(src, dst, graph, adj):
dist = {}
prev = {}
dist[src] = 0
prev[src] = Non... | ns
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] level_file src_waypoint dst_waypoint")
parser.add_option("-v", "--verbose", dest="verbose", help="use verbose logging", action=" | store_true", default=False)
(options, args) = parser.parse_args()
# Make sure the appropriate number of arguments was supplied
if (len(args) != 3):
print "Unexpected argument count."
parser.print_help()
else:
VERBOSE = options.verbose
filename, src_waypoint, dst_waypoint = args
test_route(filename, src_w... |
Resmin/Resmin | resmin/utils/models.py | Python | gpl-3.0 | 1,570 | 0 | import hashlib
from sorl.thumbnail import get_thumbnail
from django.db import models
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from resmin.libs.baseconv import base62
class BaseModel(models... | e, crop='center').url
def serialize(self):
return {'cPk': self.p | k,
'cTp': ContentType.objects.get_for_model(self).pk,
'thumbnail_url': self.thumbnail_url}
class Meta:
abstract = True
|
edx/ecommerce-scripts | transifex/pull.py | Python | agpl-3.0 | 4,324 | 0.002544 | #!/usr/bin/env python3
"""
This script can be used to automatically pull translations from Transifex,
commit, push, and merge them to their respective repos.
To use, export an environment variable `GITHUB_ACCESS_TOKEN`. The token requires
GitHub's "repo" scope.
Run the script from the root of this repo.
python t... | pilemessages
"""
import os
import shutil
from argparse import ArgumentParser
from utils import DEFAULT_MERGE_METHOD, MERGE_METHODS, logger, repo_context
# The name of the branch to use.
BRANCH_NAME = 'transifex-bot-update-translations'
# The commit message to use.
MESSAGE = 'chore(i18n): update translations'
# En... | = ''
os.environ['SKIP_NPM_INSTALL'] = 'True'
os.environ['LANG'] = 'C.UTF-8'
# Configuration repo to fetch lms/studio settings
CONFIGURATION_REPO_URL = 'https://github.com/edx/configuration.git'
def pull(clone_url, repo_owner, merge_method=DEFAULT_MERGE_METHOD, skip_compilemessages=False,
skip_check_changes... |
antoinecarme/pyaf | tests/artificial/transf_Integration/trend_MovingAverage/cycle_12/ar_/test_artificial_32_Integration_MovingAverage_12__100.py | Python | bsd-3-clause | 271 | 0.084871 | import pyaf.Benc | h.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "Int | egration", sigma = 0.0, exog_count = 100, ar_order = 0); |
attakei/openshift-ansible | playbooks/aws/openshift-cluster/library/ec2_ami_find.py | Python | apache-2.0 | 9,777 | 0.007262 | #!/usr/bin/env python2
#pylint: skip-file
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | required: false
sort_end:
description:
- Which result to end with (when sorting).
- Corresponds to Python slice notation.
default: null
require | d: false
state:
description:
- AMI state to match.
default: 'available'
required: false
virtualization_type:
description:
- Virtualization type to match (e.g. hvm).
default: null
required: false
no_result_action:
description:
- What to do when no results are found.
... |
dennisfrancis/PacketManipulator | umit/pm/gui/core/__init__.py | Python | gpl-2.0 | 971 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008 Adriano Monteiro Marques
#
# Author | : Francesco Piccinno <[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 version.
#
# This program is distrib... | nty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ... |
Bassintag551/spark-python-sdk | sparkpy/Message.py | Python | mit | 513 | 0 | #
# Message for spark-python-sdk
# Started on 19/04/2017 by Antoine
#
class Message:
def __init__(self):
self.id = None
self.roomId = None |
self.toPersonId = None
self.toPersonEmail = None
self.personId = None
self.personEmail = None
self.text = None
self.file = None
self.roomType = None
self.created = None
self.files = None
self.markdown = N | one
self.html = None
self.mentionedPeople = None
|
roadmapper/ansible | lib/ansible/plugins/terminal/dellos6.py | Python | gpl-3.0 | 3,474 | 0.002015 | #
# (c) 2016 Red Hat Inc.
#
# (c) 2017 Dell EMC.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | s')
def on_be | come(self, passwd=None):
if self._get_prompt().endswith(b'#'):
return
cmd = {u'command': u'enable'}
if passwd:
cmd[u'prompt'] = to_text(r"[\r\n]?password:$", errors='surrogate_or_strict')
cmd[u'answer'] = passwd
try:
self._exec_cli_command... |
nmc-probe/emulab-nome | robots/vmcd/camera_data/test_lin_blend3.py | Python | agpl-3.0 | 7,084 | 0.009034 | #!/usr/local/bin/python
#
# Copyright (c) 2005 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public Licens... | e blob coordinates are p | assed through the error
# correction blend, producing a world coordinate offset which is
# added to the and new world coordinates in the data frame line,
# which is then output. Everything else streams straight through.
import sys
import getopt
import string
import re
import geom
import bl... |
akrherz/iem | scripts/iemre/precip_ingest.py | Python | mit | 3,827 | 0 | """Ingest Stage IV Hourly Files.
1. Copies to hourly stage IV netCDF files
2. Copies hourly stage IV netCDF to hourly IEMRE
"""
import os
import datetime
import sys
import numpy as np
from scipy.interpolate import NearestNDInterpolator
import pygrib
from pyiem import iemre
from pyiem.util import utc, ncopen, ... | e(
"/mesonet/ARCHIVE/data/%Y/%m/%d/stage4/ST4.%Y%m%d%H.01h.grib"
)
if not os.path.isfile(fn):
LOG.info("stage4_ingest: missing file %s", fn)
return 0
gribs = pygrib.open(fn)
grb = gribs[1]
val = grb.values
# values over 10 inches are bad
val = np.where(val > 250.0, 0,... | copen(ncfn, "a", timeout=300) as nc:
p01m = nc.variables["p01m"]
# account for legacy grid prior to 2002
if val.shape == (880, 1160):
p01m[tidx, 1:, :] = val[:, 39:]
else:
p01m[tidx, :, :] = val
nc.variables["p01m_status"][tidx] = 1
LOG.debug(
... |
elPistolero/DeepFried2 | DeepFried2/datasets/cifar100.py | Python | mit | 1,879 | 0.001597 | from DeepFried2.zoo.download import download as _download
import numpy as _np
from tarfile import open as _taropen
try: # Py2 compatibility
import cPickle as _pickle
except ImportError:
import pickle as _pickle
def data():
fname = _download('http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz')
... | with f.extractfile('cifar-100-python/meta') as m:
m = _pickle.load(m, encoding='latin1')
try:
from sklearn.preprocessing import LabelEncoder
le_c = LabelEncoder()
le_c.classes_ = _np.array(m['coarse_label_names'])
le_f = LabelEncoder()
| le_f.classes_ = _np.array(m['fine_label_names'])
except ImportError:
le_c = _np.array(m['coarse_label_names'])
le_f = _np.array(m['fine_label_names'])
return (Xtr, ytr_c, ytr_f), (Xva, yva_c, yva_f), (Xte, yte_c, yte_f), (le_c, le_f)
|
openqt/algorithms | leetcode/python/lc069-sqrtx.py | Python | gpl-3.0 | 925 | 0.008649 | # coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated an | d only
the integer part of the result is returned.
**Example 1:**
**Input:** 4
**Output:** 2
**Example 2:**
**Input:** 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
... | type x: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
|
jcu-eresearch/TDH-dc24-ingester-platform | dc24_ingester_platform/service/repodb.py | Python | bsd-3-clause | 13,401 | 0.007537 | """
Created on Oct 5, 2012
@author: nigel
"""
from dc24_ingester_platform.utils import format_timestamp, parse_timestamp
from dc24_ingester_platform.service import BaseRepositoryService
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DECIMAL, Boolean, ForeignKey,... | ker(bind=self.engine)()
try:
objs = s.query(DataEntryMetadata).filter(DataEntryMetadata.data_entry == data_entry.id)
count = objs.count()
return SearchResults([self._create_data_entry_metadata(obj) for obj in objs.offset(offset).limit(limit).all()], \
... | offset, limit, count)
finally:
s.close()
def _create_dataset_metadata(self, session, obj):
"""Internal method for creating the DataEntry domain object from a database
observation
"""
schema = ConcreteSchema(self.service.get_schema_tre... |
qianqians/Screw | 3rdparty/duktape/tools/configure.py | Python | lgpl-2.1 | 41,654 | 0.005714 | #!/usr/bin/env python2
#
# Prepare a duk_config.h and combined/separate sources for compilation,
# given user supplied config options, built-in metadata, Unicode tables, etc.
#
# This is intended to be the main tool application build scripts would use
# before their build step, so convenient, versions, Python compa... | with open(value, 'rb') as f:
force_options_yaml.append(f.read())
def add_force_option_define(option, opt, value, parser):
tmp = value.split('=')
if len(tmp) == 1:
doc = { tmp[0]: True }
elif len(tmp) == 2:
doc = { tmp[0]: | tmp[1] }
else:
raise Exception('invalid option value: %r' % value)
force_options_yaml.append(yaml.safe_dump(doc))
def add_force_option_undefine(option, opt, value, parser):
tmp = value.split('=')
if len(tmp) == 1:
doc = { tmp[0]: False }
else:
... |
lampslave/sorl-thumbnail | tests/settings/default.py | Python | bsd-3-clause | 1,335 | 0 | from os.path import join as pjoin, abspath, dirname, pardir
import django
SECRET_KEY = 'SECRET'
PROJ_ROOT = abspath(pjoin(dirname(__file__), pardir))
DATA_ROOT = pjoin(PROJ_ROOT, 'data')
THUMBNAIL_PREFIX = 'test/cache/'
THUMBNAIL_DEBUG = True
THUMBNAIL_LOG_HANDLER = {
'class': 'sorl.thumbnail.log.ThumbnailLogHand... | MPLATE_CONTEXT_PROCESSORS = (
'django.core.context_proc | essors.request',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware... |
chasedog/EpisodeDiscussions | stats.py | Python | apache-2.0 | 4,633 | 0.005612 | from db import DB
from itertools import groupby
import operator
from datetime import datetime, timedelta
import classifiers, re
class Season:
def __init__(self, number, isRewatch):
self.number = number
self.episodes = []
self.is_rewatch = isRewatch
def addEpisode(self, episode):
... | matches = re.findall(classifiers.ff, titleLowered)
count = len(matches)
if count == 0:
item["season"] = -1
item["episode"] = - | 1
elif count == 1:
season = matches[0][2].strip()
episode = matches[0][4].strip()
seasonAndEpisode = str(season) + episode
if len(season) >= 1 and len(episode) >= 1:
print("A", matches[0])
item["season"] = int(season)
... |
cpcloud/numba | numba/tests/doc_examples/test_structref_usage.py | Python | bsd-2-clause | 4,851 | 0 | # "magictoken" is used for markers as beginning and ending of example text.
import unittest
# magictoken.ex_structref_type_definition.begin
import numpy as np
from numba import njit
from numba.core import types
from numba.experimental import structref
from numba.tests.support import skip_unless_scipy
# Define a S... | rn the field in jit-code.
# The definition of MyStruct_get_name is shown later.
return MyStruct_get_name(self)
@property
def vector(self):
# The definition of MyStruct_get_vector is shown later.
return MyStruct_get_vector(self)
@njit
def | MyStruct_get_name(self):
# In jit-code, the StructRef's attribute is exposed via
# structref.register
return self.name
@njit
def MyStruct_get_vector(self):
return self.vector
# This associates the proxy with MyStructType for the given set of
# fields. Notice how we are not contraining the type of e... |
vedujoshi/tempest | tempest/api/identity/admin/v3/test_domains_negative.py | Python | apache-2.0 | 2,964 | 0 | # Copyright 2015 Red Hat 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 ... | s.rand_name('domain-dup')
domain = self.domains_client.create_domain(name=domain_name)['domain']
domain_id = domain['id']
self.addCleanup(self. | delete_domain, domain_id)
# Domain name should be unique
self.assertRaises(
lib_exc.Conflict, self.domains_client.create_domain,
name=domain_name)
|
ByrdOfAFeather/AlphaTrion | Community/migrations/0021_auto_20170817_2233.py | Python | mit | 775 | 0.00129 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-18 02:33
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = | [
('Community', '0020_auto_20170816_1400'),
]
operations = [
migrations.AlterField(
model_name='communitygameratings',
name='game_rating',
field=models.PositiveIntegerField(choices=[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8... | tetime.date(2017, 8, 17)),
),
]
|
colloquium/rhevm-api | python/host-nics-test.py | Python | lgpl-2.1 | 1,769 | 0.013002 | #!/usr/bin/env python
# Copyright (C) 2010 Red Hat, Inc.
#
# This 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 your option) any later version.
#
# This so... | *
opts = parseOptions()
(host, cluster, network) = (None, None, None)
if len(opts['oargs']) >= 3:
(host, cluster, network) = opts['oarg | s'][0:3]
links = http.HEAD_for_links(opts)
for fmt in [xmlfmt]:
t = TestUtils(opts, fmt)
print "=== ", fmt.MEDIA_TYPE, " ==="
if host is None:
continue
h = t.find(links['hosts'], host)
c = t.find(links['clusters'], cluster)
nic = fmt.HostNIC()
nic.name = 'bond0'
nic.network = fmt.Net... |
GT-IDEaS/SkillsWorkshop2017 | Week01/Problem04/cruiz_04.py | Python | bsd-3-clause | 242 | 0.024793 | #!/usr/bin/env python
number = 0
for a in range(999,99,-1):
for b in range(999,99,-1):
pal=a*b
if (str(pal) == str(pal)[::-1]) | :
if (pal > number):
number = pal
break
print(number | )
|
delink/SA-kvstore_migrator | bin/splunkkvstore.py | Python | apache-2.0 | 6,834 | 0.036874 | #####
# splunkkvstore.py - Class for manipulating kvstore collections in Splunk
#####
import sys
import requests
import json
import logging
logging.getLogger(__name__)
class splunkkvstore(object):
# On instaniation, only collect the details. Do not do anything until login is called.
def __init__(self,url,*args):
... | tions/config".format(owner_scope,app_scope)
payload = { 'name': coll_name }
create_coll_request = self.api("POST",api_endpoint,payload | )
results = create_coll_request.json()
return results
def delete_collection(self,owner_scope,app_scope,coll_name):
if not owner_scope:
owner_scope = "-"
if not app_scope:
app_scope = "-"
# http://docs.splunk.com/Documentation/Splunk/latest/RESTREF/RESTkvstore
api_endpoint = "/servicesNS/{}/{}/sto... |
census-instrumentation/opencensus-python | contrib/opencensus-ext-azure/opencensus/ext/azure/common/transport.py | Python | apache-2.0 | 10,424 | 0 | # Copyright 2019, OpenCensus Authors
#
# 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 w... | exception = self.options.minimum_retry_interval
except Exception as ex:
logger.warning(
'Error when sending request %s. Dropping telemetry.', ex)
if self._check_stats_collection():
with _requests_lock:
_re | quests_map['exception'] = _requests_map.get('exception', 0) + 1 # noqa: E501
# Extraneous error (non-retryable)
exception = -1
finally:
end_time = time.time()
if self._check_stats_collection():
with _requests_lock:
duration = _... |
spulec/moto | moto/sdb/__init__.py | Python | apache-2.0 | 179 | 0 | """sdb module initialization; sets value for base decorator."""
from .models import sdb | _back | ends
from ..core.models import base_decorator
mock_sdb = base_decorator(sdb_backends)
|
xyvab/graphTheory | test.py | Python | gpl-3.0 | 561 | 0.024955 | #import sys
#sys.path.append("/home/vxv/Workspace/graphTheory/graph")
#print (sys.path)
from graph.graph import | Graph_Adj, Graph_Mat
if __name__ == "__main__":
g = { "a" : ["d"],
"b" : ["c"],
"c" : ["b", "c", "d", "e"],
"d" : ["a", "c"],
"e" : ["c"],
"f" : []
}
graph = Graph_Adj(g)
print("Vertices of graph:")
print(graph.edges())
if __name__ == '__m... | = [ [1, 0, 1],
[0, 0, 1],
[1, 1, 1]]
graph = Graph_Mat(g)
print(graph.vertices()) |
FuegoFro/KeepTalkingBot | src/modules/whos_on_first.py | Python | mit | 3,598 | 0.002779 | import os
import time
from tesserocr import PSM, PyTessBaseAPI
import cv2
from constants import MODULE_CLASSIFIER_DIR, MODULE_SPECIFIC_DIR
from cv_helpers import apply_offset_to_locations, get_classifier_directories, inflate_classifier, ls, \
ls_debug
from modules import ModuleSolver, Type
from modules.whos_on_fi... | lick_delay
NUM_TIMES_TO_SOLVE = 3
WHOS_ON_FIRST_BUTTON_CLASSIFIER_DIR = os.path.join(MODULE_SPECIFIC_DIR, "whos_on_first", "buttons")
def test():
tesseract = _get_tesseract()
classifier = inflate_classifier(WHOS_ON_FIRST_BUTTON_CLASSIFIER_DIR)
| vocab_path, unlabelled_dir, labelled_dir, features_dir, svm_data_dir = \
get_classifier_directories(MODULE_CLASSIFIER_DIR)
i = 0
# for path in ["/Users/danny/Dropbox (Personal)/Projects/KeepTalkingBot/module_specific_data/whos_on_first/in_game_6.png"]:
# for path in ls(os.path.join(labelled_dir, ... |
ityaptin/encounter | encounter/models/npc.py | Python | mit | 924 | 0.002165 | __author__ = 'it'
import re
from encounter.models import base
"""Contains a models for NPCs and monsters."""
ABILITY_TE | MPLATE = re.compile(r"([a-zA-Z]{3}) (\d+)")
SAVE_TEMPLATE = re.compile(r"([a-zA-Z]{3,4}) ([+-]\d+)")
def read_ability_scores(abilities_raw="Str 0, Dex 0, Con 0, "
"Int 0, Wis 0, Cha 0"):
abilities = ABILITY_TEMPLATE.findall(abilities_raw)
return dict((abili | ty[0], int(ability[1])) for ability in abilities)
def read_saves(saves_raw='Fort +4, Ref +5, Will +2'):
saves = SAVE_TEMPLATE.findall(saves_raw)
return dict((save[0], int(save[1])) for save in saves)
class NPC(base.BaseModel):
__name__ = "NPC"
def __repr__(self):
return ("{clazz}:"
... |
eclee25/flu-SDI-exploratory-age | scripts/create_fluseverity_figs/Supp_fall_summer_baselinebars.py | Python | mit | 1,857 | 0.012386 | #!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 8/25/14
###Function: barplot comparing number of "any diagnosis" visits during the 7 week fall baseline (wks 40-6) and 7 week summer baseline (wks 33-39)
###Import data:
###Command Line: python Supp... | all = ax.bar(xloc, fallBL, bw, color='green', align='center')
summer = ax.bar(xloc+bw, summerBL, bw, color='orange', align='center')
ax.legend([fall[0], summer[0]], ('Fall BL', 'Summer BL'), loc='upper left')
ax.set_xticks(xloc+bw/2)
ax.set_xticklabels(sl, fontsize=fssml)
ax.set_ylabel('Any Diagnosis Visits', fontsize=... | p/fall_summer_baselinebars.png', transparent=False, bbox_inches='tight', pad_inches=0)
plt.close()
# plt.show()
|
sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/pandas/core/format.py | Python | mit | 88,798 | 0.000631 | # -*- coding: utf-8 -*-
from __future__ import print_function
# pylint: disable=W0141
import sys
from pandas.core.base import PandasObject
from pandas.core.common import adjoin, notnull
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas import compat
from pandas.compat import(StringIO, lzip, r... | by set_option), 'right' out
of the box.
index_na | mes : bool, optional
Prints the names of the indexes, default True
force_unicode : bool, default False
Always return a unicode result. Deprecated in v0.10.0 as string
formatting is now rendered to unicode by default.
Returns
-------
formatted : string (or unicode, depending on d... |
smmribeiro/intellij-community | python/testData/refactoring/introduceVariable/argumentToUnnamedParameter.py | Python | apache-2.0 | 90 | 0.011111 | from typing import NewType
SomeType = NewType("SomeType", bytes)
SomeType(b"va<caret | >lue") | |
hlzz/dotfiles | graphics/VTK-7.0.0/Filters/General/Testing/Python/WarpVectorImage.py | Python | bsd-3-clause | 1,372 | 0.000729 | #!/usr/bin/env python
import vtk
from vtk.test import T | esting
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create pipeline
#
reader = vtk.vtkDataSetReader()
reader.SetFileName(VTK_DATA_ROOT + "/Data/RectGrid2.vtk")
rea | der.Update()
warper = vtk.vtkWarpVector()
warper.SetInputConnection(reader.GetOutputPort())
warper.SetScaleFactor(0.2)
extract = vtk.vtkExtractGrid()
extract.SetInputConnection(warper.GetOutputPort())
extract.SetVOI(0, 100, 0, 100, 7, 15)
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(extract.G... |
jpmunic/udest | watson_examples/conversation_v1.py | Python | mit | 771 | 0.003891 | import json
from watson_developer_cloud import ConversationV1
conversation = ConversationV1(
username='c4129348-b14c-4d2d-80ca-25b1acc59ca7',
password='dHfhKbO2pXH4',
versio | n='2016-09-20')
# replace with your own workspace_id
workspace_id = 'b42ee794-c019-4a0d-acd2-9e4d1d016767'
response = conversation.message(workspace_id=workspace_id, message_input={'text': 'What\'s the weather like?'})
print(json.dumps(response, indent=2))
# When you send multiple requests for the same conversation,... | ssage_input={'text': 'turn the wipers on'},
# context=response['context'])
# print(json.dumps(response, indent=2))
|
ceumicrodata/adatmesterseg | code/class11.py | Python | cc0-1.0 | 1,190 | 0.001681 | import | pandas
s = pandas.Series([1, 2, 3])
print s
data = {'part': ['fidesz', 'jobbik'], 'szavazat': [60, 40]}
frame = pandas.DataFrame(data)
print frame
df = pandas.read_csv('../data/result_part.csv')
print df.head()
print df[:100 | ]
print df['part']
print df['szavazat']
df['uj'] = 'NaN'
print df.tail()
new = df[df['megye'] == 1][df['telepules'] == 1][df['szavazokor'] == 1]
print df[df.megye == 1][df.telepules == 1][df.szavazokor == 1]
print new
print df.describe()
print df.drop_duplicates()
print df['part'].unique()
print df.groupby('part... |
sharhalakis/vdns | src/vdns/zone0.py | Python | gpl-3.0 | 14,983 | 0.014683 | #!/usr/bin/env python
# coding=UTF-8
#
import copy
import time
import socket
import logging
import vdns.common
class Zone0:
"""
Base class for producing zone files
"""
def __init__(self, dt):
self.dt=dt
def fmttd(self, td):
"""
Format a timedelta value to something that's... | ='CNAME'
data=rec['hostname0']
if rec['hostname0'].count('.')>=2:
needsdot=True
elif rr=='txt':
rrname='TXT'
data='"%s"' % (rec['txt'],)
elif rr=='dnssec':
rrname='DNSKEY'
if rec['ksk']:
flags=257
... | rec['hostname']=rec['domain']
data='%s 3 %s %s' % (flags, rec['algorithm'], rec['key_pub'])
elif rr=='sshfp':
rrname='SSHFP'
data='%(keytype)d %(hashtype)d %(fingerprint)s' % rec
elif rr=='dkim':
rrname='TXT'
hostname='%(selector)s._domai... |
antismap/MICshooter | sources/lib/eztext.py | Python | mit | 11,212 | 0.0198 | # input lib
from pygame.locals import *
import pygame, string
class ConfigError(KeyError): pass
class Config:
""" A utility for configuration """
def __init__(self, options, *look_for):
assertions = []
for key in look_for:
if key[0] in options.keys(): exec('self.'+key[0]... | K_3 and '3' in self.restricted: self.value += '3'
elif event.key == K_4 and '4' in self.restricted: self.value | += '4'
elif event.key == K_5 and '5' in self.restricted: self.value += '5'
elif event.key == K_6 and '6' in self.restricted: self.value += '6'
elif event.key == K_7 and '7' in self.restricted: self.value += '7'
elif event.key == K_8 and... |
scikit-optimize/scikit-optimize | skopt/sampler/base.py | Python | bsd-3-clause | 689 | 0 |
from collections import defaultdict
class InitialPointGenerator(object):
def generate(self, dimensions, n_samples, random_state=None):
raise NotImplemented
def set_params(self, **params):
"""
Set the parameters of this initial point generator.
Parameters
----------
... | t
Generator parameters.
Returns
-------
self : object
Generator instance.
"""
if not params:
# Simple optimization to gain speed (inspect is slow)
return self
for key, value in params.items():
| setattr(self, key, value)
return self
|
B3AU/waveTree | sklearn/linear_model/omp.py | Python | bsd-3-clause | 31,732 | 0.000126 | """Orthogonal matching pursuit algorithms
"""
# Author: Vlad Niculae
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import linalg
from scipy.linalg.lapack import get_lapack_funcs
from .base import LinearModel, _pre_fit
from ..base import RegressorMixin
from ..utils import array2d, as_float_... | [:n_active, :n_active], Xy[:n_active], lower=True,
overwrite_b=False)
if return_path:
coefs[:n_active, n_active - 1] = gamma
| beta = np.dot(Gram[:, :n_active], gamma)
alpha = Xy - beta
if tol is not None:
tol_curr += delta
delta = np.inner(gamma, beta[:n_active])
tol_curr -= delta
if tol |
reyoung/Paddle | python/paddle/fluid/tests/test_if_else_op.py | Python | apache-2.0 | 8,444 | 0.000237 | # Copyright (c) 2018 PaddlePaddle 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 app... | for data in train_reader():
x_data = np.array([x[0] for x in data]).astype("float32")
y_data = np.array([x[1] for x in data]).astype("int64")
| y_data = y_data.reshape((y_data.shape[0], 1))
outs = exe.run(prog,
feed={'x': x_data,
'y': y_data},
fetch_list=[avg_loss])
print(outs[0])
if outs[0] < 1.0:
... |
shiquanwang/numba | numba/codegen/coerce.py | Python | bsd-2-clause | 8,887 | 0.0018 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm
from numba import *
from numba import nodes
from numba.typesystem import is_obj, promote_to_native
from numba.codegen.codeutils import llvm_alloca, if_badval
from numba.codegen import debug
class ObjectCoercer(object... | lator.error_label))
def _create_llvm_string(self, str):
return self.translator.visit(nod | es.ConstNode(str, c_string_type))
def lstr(self, types, fmt=None):
"Get an llvm format string for the given types"
typestrs = []
result_types = []
for type in types:
if is_obj(type):
type = object_
elif type.is_int:
type = prom... |
tartavull/google-cloud-python | trace/tests/__init__.py | Python | apache-2.0 | 575 | 0 | # Copyright 2017 Google Inc.
#
# Licensed under the | Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distrib... |
# limitations under the License.
|
typemytype/RoboFontExamples | fontGroups/changeGroupSingleQuote.py | Python | mit | 514 | 0.005837 |
for f in AllFonts():
hasEdits = False
for name, members in f.gro | ups.items():
groupHasEdits = False
new = []
for m in members:
if m[-1] == "'":
groupHasEdits = True
hasEdits = True
new.append(m[:-1])
else:
new.append(m)
f.groups[name]=new
if hasEdits:
... | lName |
tsdmgz/ansible | lib/ansible/module_utils/facts/hardware/darwin.py | Python | gpl-3.0 | 3,527 | 0.001985 | # This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that ... | if rc == 0:
mac_facts['model'] = out.splitlines()[-1].split()[1]
mac_facts['osversion'] = self.sysctl['kern.osversion']
| mac_facts['osrevision'] = self.sysctl['kern.osrevision']
return mac_facts
def get_cpu_facts(self):
cpu_facts = {}
if 'machdep.cpu.brand_string' in self.sysctl: # Intel
cpu_facts['processor'] = self.sysctl['machdep.cpu.brand_string']
cpu_facts['processor_core... |
palmer-dabbelt/riscv-qemu | scripts/tracetool/backend/ust.py | Python | gpl-2.0 | 804 | 0.006234 | #!/usr/bin/env | python
# -*- coding: utf-8 -*-
"""
LTTng User Space Tracing backend.
"""
__author__ = "Lluís Vilanova | <[email protected]>"
__copyright__ = "Copyright 2012-2016, Lluís Vilanova <[email protected]>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "[email protected]"
from tracetool import out
PUBLIC = True
def generate_h_begi... |
vandenheuvel/tribler | Tribler/community/allchannel/__init__.py | Python | lgpl-3.0 | 125 | 0.008 | """
The allchannel communi | ty is used to collect votes for cha | nnels and thereby discover which channels are most popular.
"""
|
tiredtyrant/CloudBot | plugins/chan_track.py | Python | gpl-3.0 | 23,414 | 0.000043 | """
Track channel ops for permissions checks
Requires:
server_info.py
"""
import gc
import json
import logging
import weakref
from collections import Mapping, Iterable, namedtuple
from contextlib import suppress
from numbers import Number
from operator import attrgetter
from irclib.parser import Prefix
import cloudb... | tus):
"""
:type status: plugins.core.server_info.Status
"""
if status not in self.status:
logger.warn | ing(
"[%s|chantrack] Attempted to remove status not set "
"on member: %s %s",
self.conn.name, self, status
)
else:
self.status.remove(status)
def sort_status(self):
"""
Ensure the sta... |
leppa/home-assistant | tests/helpers/test_state.py | Python | apache-2.0 | 7,019 | 0.001282 | """Test state helpers."""
import asyncio
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant.components.sun import STATE_ABOVE_HORIZON, STATE_BELOW_HORIZON
from homeassistant.const import (
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_CLOSED,
STATE_HOME,
STA... | set_result(None)
with patch(
("homeassistant.components.climate.reproduce_state.async_reproduce_states")
) as climate_fun:
climate_fun.return_value = asyncio.Future()
climate_fun.return_value.set_result(None)
state_media_player = ha.State("media_player.t... | st", "bad")
state_climate = ha.State("climate.test", "bad")
context = "dummy_context"
yield from state.async_reproduce_state(
hass,
[state_media_player, state_climate],
blocking=True,
context=context,
)
... |
codekoala/clip2zeus | clip2zeus/main.py | Python | mit | 581 | 0.006885 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Monitors the system clipboard for text that contains URLs for conversion
using 2ze.us
"""
from clip2zeus.common import *
def mai | n():
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-p', '--port', dest='port', default=DEFAULT_PORT, help='The port for the daemon to listen on')
options, args = parser.parse_args()
params = dict(
port=options.port,
)
clip2zeus = Clip2ZeusApp.for_pla... |
if __name__ == '__main__':
main()
|
ouyangshi/ahpucourses | config.py | Python | gpl-3.0 | 1,337 | 0 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICA | TIONS = False
MAIL_SERVER = 'smtp.qq.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get('MAIL_USERNAME') or ''
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') or ''
AHPUCOURSES_MAIL_SUBJECT_PREFIX = '[Ahpucourse]'
AHPUCOURSES_MAIL_SENDER = 'Ahpucourses Admin <admin@examp... | AHPUCOURSES_ADMIN = '[email protected]'
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class TestingConfig(Config):
... |
zvezdan/pip | src/pip/_vendor/distlib/database.py | Python | mit | 50,056 | 0.000479 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2017 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
"""PEP 376 implementation."""
from __future__ import unicode_literals
import base64
import codecs
import contextlib
import hashlib
import logging
import os
import posixpath
import sys
import z... | if gen_dist:
self._cache.generated = True
if gen_egg:
self._cache_egg.generated = True
@classmethod
def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. ... | the one
separating the name from the version number.
:parameter name: is converted to a standard distribution name by replacing
any runs of non- alphanumeric characters with a single
``'-'``.
:type name: string
:parameter version: is con... |
atvKumar/open-tamil | transliterate/azhagi.py | Python | mit | 30,836 | 0.042643 | ## -*- coding: utf-8 -*-
# (C) 2013 Muthiah Annamalai
#
# Implementation of Azhagi rules - தமிழ் எழுத்துக்கள்
# Ref: B. Viswanathan, http://www.mazhalaigal.com/tamil/learn/keys.php
#
class Transliteration:
table = {}
# not implemented - many-to-one table
# Azhagi has a many-to-one mapping - using a Tamil... | le["nje"]=u"ஞெ"
table["Gne"]=u"ஞெ"
table["GnE"]=u"ஞே"
table["gnE"]=u"ஞே"
table["gnae"]=u"ஞே"
table["njE"]=u"ஞே"
table["njae"]=u"ஞே"
table["Gnae"]=u"ஞே"
table["gnai"]=u"ஞை"
table["njai"]=u"ஞை"
table["Gnai"]=u"ஞை"
table["gno"]=u"ஞொ"
table["njo"]=u"ஞொ"
table["Gno"]=u"ஞ... | ோ"
table["gnoa"]=u"ஞோ"
table["gnoe"]=u"ஞோ"
table["njO"]=u"ஞோ"
table["njoa"]=u"ஞோ"
table["njoe"]=u"ஞோ"
table["Gnoa"]=u"ஞோ"
table["Gnou"]=u"ஞௌ"
table["Gnau"]=u"ஞௌ"
table["gnow"]=u"ஞௌ"
table["gnou"]=u"ஞௌ"
table["gnau"]=u"ஞௌ"
table["njow"]=u"ஞௌ"
table["njou"]... |
joshua-cogliati-inl/raven | tests/framework/PostProcessors/Validation/DSS/lorentzAttractor_timeScale_I.py | Python | apache-2.0 | 2,032 | 0.023622 | # Copyright 2017 Battelle Energy Alliance, 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 required by applicable law or agreed t... | ry of input file names, file location, and other parameters
RAVEN run.
@ In, inputFiles, list, data objects required for external model initialization.
@ Out, None
"""
self.sigma = 10.0
self.rho = 28.0
self.beta = 8.0/3.0
return
def run(self,Input):
"""
Constructor
@ In, Input,... | maxTime = 0.5
tStep = 0.005
self.sigma = 10.0
self.rho = 28.0
self.beta = 8.0/3.0
numberTimeSteps = int(maxTime/tStep)
self.x1 = np.zeros(numberTimeSteps)
self.y1 = np.zeros(numberTimeSteps)
self.z1 = np.zeros(numberTimeSteps)
self.time1 = np.zeros(numberTimeSteps)
self.x0 = Input['... |
richm/designate | designate/backend/impl_nsd4slave.py | Python | apache-2.0 | 4,900 | 0 | # Copyright (C) 2013 eNovance SAS <[email protected]>
#
# Author: Artom Lifshitz <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.... | sock = eventlet.wrap_ssl(eventlet.connect((host, port)),
keyfile=self._keyfile,
certfile=self._certfile)
stream = sock.makefile()
stream.write('%s %s\n' % (self.NSDCT_VERSION, command))
stream.flush()
| result = stream.read()
stream.close()
sock.close()
return result.rstrip()
def update_recordset(self, context, domain, recordset):
pass
def delete_recordset(self, context, domain, recordset):
pass
def create_record(self, context, domain, recordset, record):
... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/mpls/lsps/static_lsps/__init__.py | Python | apache-2.0 | 13,426 | 0.001266 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | stance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
a... | break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = ... |
meigrafd/Sample-Code | serial_input.py | Python | mit | 1,579 | 0.010766 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import serial
import time
import sys
#-------------------------------------------------------------------
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 38400
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.par | ity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None # | block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for wri... |
rizac/gfzreport | gfzreport/sphinxbuild/core/extensions/setup.py | Python | gpl-3.0 | 9,566 | 0.003868 | '''
Simple sphinx extension which sets up the necessary translators (html, latex) and other stuff
It is also a collection of trial and errors mostly commented and left here as a reminder in order
Created on Apr 4, 2016
@author: riccardo
'''
import re
import sys
import os
from os import path
from gfzreport.sphinxbuild.... | ef decorate_title(string, underline_symbol, overline_symbol=None):
"""
Decorates a string title as in rst format
:param string: the string represetning the title
:param underline_symbol: A 1-character string, representing the decorator character for
underline
:param overl... | g the decorator character for
overline
:Examples:
decorate_string("sea", "=") returns:
sea
===
decorate_string("abc", "=", "-") returns:
---
sea
===
"""
lens = len(string)
string = "{0}\n{1}".format(string, lens * underline_symb... |
mattbernst/polyhartree | support/ansible/modules/core/cloud/rackspace/rax_cdb_database.py | Python | gpl-3.0 | 4,837 | 0.000413 | #!/usr/bin/python -tt
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distrib... |
short_description: 'create / delete a database in the Cloud Databases'
description:
- create / delete a database in the Cloud Databases.
version_added: "1.8"
options:
cdb_id:
description:
- The databases server UUID
default: null
name:
description:
- Name to give to the database
defau... | description:
- Set of symbols and encodings
default: 'utf8'
collate:
description:
- Set of rules for comparing characters in a character set
default: 'utf8_general_ci'
state:
description:
- Indicate desired state of the resource
choices: ['present', 'absent']
default: pr... |
fangxinmiao/projects | Architeture/Backend/Framework/WebBenchmarker/frameworks/Python/django/helloworld/manage.py | Python | gpl-3.0 | 630 | 0 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'helloworld.settings')
try:
fro | m django.core.management import execute_from_command_line
| except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if _... |
lariodiniz/OramaBankTest | OramaBank/pynetbanking/tests/test_views.py | Python | gpl-2.0 | 2,719 | 0.002575 | # coding: utf-8
#--------------//////////----------------------
#Projeto Criado por: Lário Diniz
#Contatos: [email protected]
#data: 29/09/2015
#--------------//////////----------------------
from django.test import TestCase
from django.test import Client
from ..models import User, Cliente_Model
class lo... | obj.password)
self.resp = self.client.get('/clint/%s' %cliente.slug,secure=True )
print self.resp
def test_get(self):
'Verifica o staus code 200 da pagina /clint/'
self.assertEqual(200, self.resp.status_code)
def test_template(self):
'Verifica o Template Usado'
... | pass
"""
|
DrXyzzy/smc | src/smc_pyutil/smc_pyutil/smc_close.py | Python | agpl-3.0 | 2,160 | 0.003704 | #!/usr/bin/python
MAX_FILES = 100
import json, os, sys
home = os.environ['HOME']
if 'TMUX' in os.environ:
prefix = '\x1bPtmux;\x1b'
postfix = '\x1b\\'
else:
prefix = ''
postfix = ''
def process(paths):
v = []
if len(paths) > MAX_FILES:
sys.stderr.write(
"You may close a... | pwd instead of getcwd or os.path.abspath since we want this to
# work when used inside a directory that is a symlink! I could find
# no analogue of pwd directly in Python (getcwd is not it!).
path = os.path.join(os.popen('pwd').read().strip(), path)
# determine name relativ... | directory?
if os.path.isdir(path):
v.append({'directory': name})
else:
v.append({'file': name})
if v:
mesg = {'event': 'close', 'paths': v}
print(prefix + '\x1b]49;%s\x07' % json.dumps(
mesg, separators=(',', ':')) + postfix)
def main():
if... |
idea4bsd/idea4bsd | python/testData/formatter/spaceAfterTrailingCommaIfNoSpaceAfterCommaButWithinBracesOrBrackets.py | Python | apache-2.0 | 126 | 0.031746 | s1 = {1, 2, 3 | ,}
s2 = {1, }
d1 = {'foo': 1, 'bar': 2, 'baz': 3,}
d2 = {'foo': 1,}
d3 = {}
l1 = [1, 2 | , 3,]
l2 = [1, ]
l3 = []
|
rackerlabs/quark | quark/api/extensions/ip_addresses.py | Python | apache-2.0 | 6,441 | 0 | # Copyright (c) 2013 Rackspace Hosting Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | nd(e)
def create(self, request, **kwargs):
raise webob.exc.HTTPNotImplemented()
def show(self, ip_address_id, request, id):
context = request.context
# TODO(jlh): need to ensure ip_address_id is used to filter port
try:
return {"ip_addresses_port": |
self._plugin.get_port_for_ip_address(context,
ip_address_id, id)}
except n_exc.NotFound as e:
raise webob.exc.HTTPNotFound(e)
def update(self, ip_address_id, request, id, body=None):
body = self._deserialize(r... |
antoinecarme/pyaf | tests/artificial/transf_Quantization/trend_MovingAverage/cycle_5/ar_12/test_artificial_32_Quantization_MovingAverage_5_12_100.py | Python | bsd-3-clause | 272 | 0.084559 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset a | s art
art.process_d | ataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 12); |
Canas/kaftools | kaftools/filters.py | Python | mit | 7,408 | 0.00216 | # -*- coding: utf-8 -*-
"""
kaftools.filters
~~~~~~~~~~~~~~~~~~~~~~~~
This module provides adaptive kernel filtering classes.
Currently supports:
- Kernel Least Mean Squeares (KLMS)
- Exogenous Kernel Least Mean Squares (KLMS-X)
- Kernel Recursive Least Squares (KRLS)
Not all filters support all features. Be sure to ... | = None
self.coefficients = None
self.similarity = None
self.kernel = None
self.error = None
self.learning_rate = None
self.delay = None
self.coefficient_history = None
self.error_history = None
self.param_history = None
self._estimate = np... | AttributeError("Filter has not been applied yet.")
else:
return self._estimate
class KlmsFilter(Filter):
"""Original SISO KLMS filter with optional delayed input. """
def fit(self, kernel=GaussianKernel(sigma=1.0), learning_rate=1.0, delay=1,
kernel_learning_rate=None, sparsif... |
xiangke/pycopia | mibs/pycopia/mibs/HP_SN_POS_GROUP_MIB_OID.py | Python | lgpl-2.1 | 2,839 | 0.02043 | # python
# This file is generated by a program (mib2py).
import HP_SN_POS_GROUP_MIB
OIDMAP = {
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1': HP_SN_POS_GROUP_MIB.snPO | SInfo,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.1': HP_SN_POS_GROUP_MIB.snPOSInfoPortNum,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.2': HP_SN_POS_GROUP_MIB.snPOSIfIndex,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.3': HP_SN_POS_GROUP_MIB.snPOSDescr,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.4': HP_SN_POS_GROUP_MIB.snPOSName,
'1.3.6... | d,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.6': HP_SN_POS_GROUP_MIB.snPOSInfoAdminStatus,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.7': HP_SN_POS_GROUP_MIB.snPOSInfoLinkStatus,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.8': HP_SN_POS_GROUP_MIB.snPOSInfoClock,
'1.3.6.1.4.1.11.2.3.7.11.12.2.14.1.1.1.9': HP_SN_POS_GROUP_MIB.snPOSI... |
stratosphereips/Manati | manati/api_manager/migrations/0003_remove_externalmodule_acronym.py | Python | agpl-3.0 | 1,302 | 0.006144 | #
# Copyright (c) 2017 Stratosphere Laboratory.
#
# This file is part of ManaTI Project
# (see <https://stratosphereips.org>). It was created by 'Raul B. Netto <[email protected]>'
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License ... | .gnu.org/licenses/>
# for copying permission.
#
# -*- coding: utf-8 -* | -
# Generated by Django 1.9.7 on 2016-11-09 20:49
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api_manager', '0002_externalmodule_status'),
]
operations = [
migrations.RemoveField(
model_na... |
mjames-upc/python-awips | dynamicserialize/dstypes/com/raytheon/uf/common/dataaccess/response/GetGridLatLonResponse.py | Python | bsd-3-clause | 858 | 0.001166 | ##
##
# File auto-generated against equivalent DynamicSerialize Java class
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# Oct 10, 2016 5916 bsteffen Generated
class GetGrid... | lf.nx
def set | Nx(self, nx):
self.nx = nx
def getNy(self):
return self.ny
def setNy(self, ny):
self.ny = ny
|
akiokio/centralfitestoque | src/.pycharm_helpers/python_stubs/-1807332816/_sre.py | Python | bsd-2-clause | 453 | 0.013245 | # e | ncoding: utf-8
# module _sre
# from (built-in)
# by generator 1.130
# no doc
# no imports
# Variables with simple values
CODESIZE = 4
copyright = ' SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB '
MAGIC = 20031017
# functions
def compile(*args, **kwargs): # real signature unknown
pass
def getcode | size(*args, **kwargs): # real signature unknown
pass
def getlower(*args, **kwargs): # real signature unknown
pass
# no classes
|
tiaanwillemse/pythonNotifier | notifier.py | Python | mit | 2,262 | 0.007958 | import utils
class Notifier(object):
def __init__(self, key='', type='slack'):
self.key = key
self.type = type
self.parameters = {
'icon' : ':space_invader:',
'username': 'Notifier Bot',
'channel' : 'general'
}
if self.key:
if... |
self.message(object)
def warning(self, object):
if self.type == 'slack':
if isinstance(object, str):
object = {'text': object}
object.update({'color' : 'warning'})
self.message(object)
def danger(self, object):
if s... | 'text': object}
object.update({'color' : 'danger'})
self.message(object) |
Etharr/plugin.video.youtube | resources/lib/youtube_plugin/kodion/impl/mock/mock_context_ui.py | Python | gpl-2.0 | 1,400 | 0.000714 | __author__ = 'bromix'
from ..abstract_context_ui import AbstractContextUI
from ...logging import *
from .mock_progress_dialog import MockProgressDialog
class MockContextUI(AbstractContextUI):
def __init__(self):
AbstractContextUI.__init__(self)
self._view_mode = None
def set_view_mode(self, ... | def show_notification(self, message, header='', image_uri='', time_milliseconds=5000):
log('=======NOTIFICATION=======')
log('Message : %s' % message)
log('header : %s' % header)
log('image_uri: %s' % image_uri)
log('Time : %d' % time_milliseconds)
log('==========... | log("called 'open_settings'")
def refresh_container(self):
log("called 'refresh_container'")
|
apache/incubator-superset | superset/migrations/versions/f9847149153d_add_certifications_columns_to_slice.py | Python | apache-2.0 | 1,499 | 0.000667 | # 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 f | ile
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses | /LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under... |
AdamWill/blivet | tests/formats_test/methods_test.py | Python | lgpl-2.1 | 16,986 | 0.003356 | import unittest
from unittest.mock import patch, sentinel, PropertyMock
from blivet.errors import DeviceFormatError
from blivet.formats import DeviceFormat
from blivet.formats.luks import LUKS
from blivet.formats.lvmpv import LVMPhysicalVolume
from blivet.formats.mdraid import MDRaidMember
from blivet.formats.swap imp... | # fmt cannot exist
self.format.exists = True
with patch.object(self.format, "_create"):
self.set_os_path_exists(True)
self.assertRaisesRegex(DeviceFormatError, "format already exists", self.format.create)
self.assertFalse(self.format._create.called) # pylint: dis... | must be accessible
with patch.object(self.format, "_create"):
# device must be accessible
self.set_os_path_exists(False)
self.assertRaisesRegex(DeviceFormatError, "invalid device specification", self.format.create)
self.assertFalse(self.format._create.called) # p... |
schleichdi2/OPENNFR-6.1-CORE | opennfr-openembedded-core/meta/lib/oeqa/selftest/bbtests.py | Python | gpl-2.0 | 14,655 | 0.007711 | import os
import re
import oeqa.utils.ftools as ftools
from oeqa.selftest.base import oeSelfTest
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars
from oeqa.uti | ls.decorators import testcase
class BitbakeTests(oeSelfTest):
def getline(self, res, line):
for l in res.output.split('\n'):
if line in l:
return l
@testcase(789)
def test_run_bitbake_from_dir_1(self):
os.chdir(os.path.jo | in(self.builddir, 'conf'))
self.assertEqual(bitbake('-e').status, 0, msg = "bitbake couldn't run from \"conf\" dir")
@testcase(790)
def test_run_bitbake_from_dir_2(self):
my_env = os.environ.copy()
my_env['BBPATH'] = my_env['BUILDDIR']
os.chdir(os.path.dirname(os.environ['BUILDD... |
bo858585/AbstractBooking | Booking/booking/migrations/0018_auto_20150310_1533.py | Python | mit | 1,427 | 0.000701 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('booking', '0017_auto_20150309_1910'),
]
operations = [
migrations.AlterField(
model_name='booking',
... | 0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u0438\u044f \u0437\u0430\u043a\u0430\u0437\u0447\u0438\u043a\u043e\u043c'), (b'running', '\u0412\u0437\u044f\u0442 \u043d\u0430 \u0438\u0441\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435'), (b'completed', '\u0417\u0430\u0432\u0435\u0440\u0448\u0435\u043d')]),
... | ld(auto_now_add=True, db_index=True),
preserve_default=True,
),
]
|
bcbnz/python-rebuild | src/rebuild/widgets/results/__init__.py | Python | gpl-3.0 | 196 | 0 | from .base_result import BaseResult
| from .sub import Sub
from .split import Split
from .match import Match
from .search import Search
from .find_all import FindAll
from .find_iter import FindIter | |
aspose-cells/Aspose.Cells-for-Cloud | Examples/Python/Examples/GetAutoshapeFromWorksheet.py | Python | mit | 1,342 | 0.009687 | import asposecellscloud
from asposecellscloud.CellsApi import CellsApi
from asposecellscloud.CellsApi import ApiException
from asposecellscloud.CellsApi import AutoShapesResponse
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify ... | d file to aspose cloud storage
storageApi.PutCreate(Path=filen | ame, file=data_folder + filename)
try:
#invoke Aspose.Cells Cloud SDK API to get autoshape from a worksheet
response = cellsApi.GetWorksheetAutoshape(name=filename, sheetName=sheetName, autoshapeNumber=autoshapeNumber)
if response.Status == "OK":
autoShape = response.AutoShape
print autoSh... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/pip/_internal/resolution/base.py | Python | apache-2.0 | 563 | 0.001776 | from typing import Callable, List
from pip._internal.req.req_install import InstallRequirement
from pip._internal.req.req_set import RequirementSet
InstallRequirementProvider = Callable[[str, InstallRequirement], InstallRequirement]
class BaseResolver:
def resolve(self, root_reqs, check_supported_wheels):
... | edError()
def get_installation_order(self, req_set):
# type: (RequirementSet) -> List[Instal | lRequirement]
raise NotImplementedError()
|
lbryio/lbry | torba/torba/client/words/english.py | Python | mit | 19,271 | 0.106274 | words = [
'abandon',
'ability',
'able',
'about',
'above',
'absent',
'absorb',
'abstract',
'absurd',
'abuse',
'access',
'accident',
'account',
'accuse',
'achieve',
'acid',
'acoustic',
'acquire',
'across',
'act',
'action',
'actor',
'actress',
'actual',
'adapt',
'add',
'addict',
'address',
'adjust',
'admit',
'adult',
'adv... | ct',
'auction',
'audit',
'august',
'aunt',
'author',
'auto',
'autumn',
'average',
'avocado',
'avoid',
'awake',
'aware',
'away',
'awesome',
'awful',
' | awkward',
'axis',
'baby',
'bachelor',
'bacon',
'badge',
'bag',
'balance',
'balcony',
'ball',
'bamboo',
'banana',
'banner',
'bar',
'barely',
'bargain',
'barrel',
'base',
'basic',
'basket',
'battle',
'beach',
'bean',
'beauty',
'because',
'become',
'beef',
'before',
'begin',
'behave',
'behind',
'believe',
'below',
'belt',... |
Golker/wttd | eventex/subscriptions/tests/test_view_detail.py | Python | mit | 1,288 | 0.000776 | from django.test import TestCase
from eventex.subscriptions.models import Subscription
from django.shortcuts import resolve_url as r
class SubscriptionDetailGet(TestCase):
def setUp(self):
self.obj = Subscription.objects.create(
name='Luca Bezerra', cpf='12345678901',
email='lucabe... | )
self.response = self.client.get(r('subscriptions:detail', self.obj.pk))
def test_get(self):
self.assertEqual(200, self.response.status_code)
def test_template(self):
self.assertTemplateUsed(self.response,
'subscriptions/subscription_detail.html')
... | = self.response.context['subscription']
self.assertIsInstance(subscription, Subscription)
def test_html(self):
contents = (self.obj.name, self.obj.cpf, self.obj.email, self.obj.phone)
with self.subTest():
for expected in contents:
self.assertContains(self.respon... |
jiadaizhao/LeetCode | 1501-1600/1579-Remove Max Number of Edges to Keep Graph Fully Traversable/1579-Remove Max Number of Edges to Keep Graph Fully Traversable.py | Python | mit | 1,211 | 0.004955 | class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n + 1))
def findParent(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
def union(u, v):
... | pu = findParent(u)
pv = findParent(v)
if pu != pv:
parent[pv] = pu
return 1
else:
return 0
e1 = e2 = result = 0
for t, u, v in edges:
if t == 3:
if union(u, v):
... | e2 += 1
else:
result += 1
parentOrig = parent[:]
for t, u, v in edges:
if t == 1:
if union(u, v):
e1 += 1
else:
result += 1
parent = pa... |
uglyboxer/Blackjack | blackjack/packages/card.py | Python | unlicense | 1,787 | 0.001119 | class Card:
""" Class of a single card in a traditional deck of 52 cards.
Cards are 2 - 10 and have a value matching their integer name.
or the are a 'face' card (Jack, Queen, King) and valued at 10.
Ace cards are valued at 1 or 1 | 1 depending on the state of the rest of the
hand.
Parameters
----------
input_card : tuple
A 3-value tuple composed of:
card_name : string
The name of the card from the traditional set of playing cards.
suit : string
One of ('H', 'D', 'C', 'S') represen... | original location in the shoe at "construction" time
Attributes
----------
card_name : string
The "rank" of given card instance
suit : string
The "suit"
orig_loc : int
The integer representing the location in the original shoe, before any
shuffling
value : int
... |
rnestler/LibrePCB | tests/funq/libraryeditor/test_copy_package_category.py | Python | gpl-3.0 | 2,109 | 0.003319 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test copying a package category in the library editor
"""
def test(library_editor, helpers):
"""
Copy package category with "New Library Element" wizard
"""
le = library_editor
# Open "New Library Element" wizard
le.action('libraryEditorActio... | = category_tree.model().items( | ).items[0]
category_tree.select_item(category)
le.widget('libraryEditorNewElementWizardNextButton').click()
# Check metadata
widget_properties = {
('NameEdit', 'text'): 'C-SMT',
('DescriptionEdit', 'plainText'): '',
('KeywordsEdit', 'text'): '',
('VersionEdit', 'text'): ... |
smulikHakipod/USB-Emulation | hid.py | Python | bsd-2-clause | 4,982 | 0.005821 | import random
import datetime
from USBIP import BaseStucture, USBDevice, InterfaceDescriptor, DeviceConfigurations, EndPoint, USBContainer
# Emulating USB mouse
# HID Configuration
class HIDClass(BaseStucture):
_fields_ = [
('bLength', 'B', 9),
('bDescriptorType', 'B', 0x21), # HID
('bcd... | 0x09, 0x38, # | Usage (Wheel)
0x15, 0x81, # Logical Minimum (-0x7f)
0x25, 0x7f, # Logical Maximum (0x7f)
0x75, 0x08, # Report Size (8)
0x95, 0x03, # Report Count (3)
0x81, 0x06, # Input (Data, Variable, Relative)
0xc0, ... |
GccX11/machine-learning | hmm.py | Python | mit | 3,184 | 0.047739 | #author Matt Jacobsen
'''
This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM).
Implement a Baum-Welch algorithm (like EM?) to learn parameters
Implement a Viterbi algorithm to learn structure.
Implement a forward-backward algorithm (like BP) to do inference over the ... | beta = [[1.0]*len(O) for i in range(self.numstates)]
#r | ecursion
for t in range(len(O)-2, -1, -1):
for i in range(self.numstates-1, -1, -1):
sum_i = 0.0
for j in range(self.numstates-1, -1, -1):
sum_i += a[i][j] * beta[i][t+1]
beta[i][t] = sum_i * b[i][bmap[O[t]]]
#normalize alpha to avoid underflow
for t in range(0, len(O)-1):
for n in range... |
mohittahiliani/tcp-eval-suite-ns3 | src/flow-monitor/examples/wifi-olsr-flowmon.py | Python | gpl-2.0 | 7,439 | 0.008469 | # -*- Mode: Python; -*-
# Copyright (c) 2009 INESC Porto
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
#... | e number of nodes (total number of nodes will be this number squared)")
cmd.Results = None
cmd.AddValue("Results", "Write XML results to file")
cmd.Plot = None
cmd.AddValue("Plot", "Plot the results using the matplotlib python module")
cmd.Parse(argv)
wifi = ns.wifi.WifiHelper.Default()
... | ns.wifi.NqosWifiMacHelper.Default()
wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
wifiPhy.SetChannel(wifiChannel.Create())
ssid = ns.wifi.Ssid("wifi-default")
wifi.SetRemoteStationManager("ns3::ArfWifiManager")
wifiMac.SetType ("ns3::AdhocWi... |
cpcloud/ibis | ibis/backends/clickhouse/client.py | Python | apache-2.0 | 5,153 | 0.000194 | import re
from typing import Any
import numpy as np
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
base_typename_re = re.compile(r"(\w+)")
_clickhouse_dtypes = {
'Null': dt.Null,
... | m = base_typename_re.match(typename)
self.base_typename = m.groups()[0]
if self.base_typename not in _clickhouse_dtypes:
raise com.UnsupportedBackendType(typename)
self.typename = self.base_typename
self.nullable = nullable
if self.base_typename == 'Array':
... | lf.typename})'
else:
return self.typename
def __repr__(self):
return f'<Clickhouse {str(self)}>'
@classmethod
def parse(cls, spec):
# TODO(kszucs): spare parsing, depends on clickhouse-driver#22
if spec.startswith('Nullable'):
return cls(spec[9:-1], ... |
jtsmith1287/gurpscg | main.py | Python | apache-2.0 | 5,971 | 0.011221 | import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().re... | n += 1 # go to the next column
complete_html += "</table>" # close the table
self.f | ields["spell_checkboxes"] = complete_html
def configureCatBoxes(self):
psionic_powers = ["Antipsi", "Esp", "Psychic Healing",
"Psychokinesis", "Teleportation", "Telepathy"]
power_cats = []
checkbox_html = '<input type="checkbox" name="cat_type" value="%s"> %s'
column = 0
c... |
nemonik/Intellect | intellect/examples/testing/Test.py | Python | bsd-3-clause | 2,750 | 0.002182 | """
Copyright (c) 2011, The MITRE Corporation.
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 code must retain the above copyright
notice, this list of conditions and the... | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN... | Test module
Initial Version: Feb 23, 2011
@author: Michael Joseph Walsh
"""
def helloworld():
"""
Returns "hello world" annd prints "returning 'hello world'" to the
sys.stdout
"""
print "returning 'hello world'"
return "hello world"
def greaterThanTen(n):
"""
Returns True if 'n' ... |
dc3-plaso/dfvfs | tests/vfs/lvm_file_system.py | Python | apache-2.0 | 6,113 | 0.007852 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for a file system implementation using pyvslvm."""
import unittest
from dfvfs.path import lvm_path_spec
from dfvfs.path import os_path_spec
from dfvfs.path import qcow_path_spec
from dfvfs.resolver import context
from dfvfs.vfs import lvm_file_system
from tests impo... | 2'])
class LVMFileSystemTest(shared_test_lib.BaseTestCase):
"""The unit test for the LVM file system object."""
def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._resolver_context = context.Context()
test_file = self._GetTestFilePath([u'lvmtest.qcow2'])
path_spec = os... | =path_spec)
self._lvm_path_spec = lvm_path_spec.LVMPathSpec(
location=u'/', parent=self._qcow_path_spec)
# qcowmount test_data/lvmtest.qcow2 fuse/
# vslvminfo fuse/qcow1
#
# Linux Logical Volume Manager (LVM) information:
# Volume Group (VG):
# Name: vg_test
# Identi... |
andrewyang96/GutenbergsHorse | mostpopular.py | Python | mit | 7,833 | 0.002043 | MOSTPOPULAR = [
1342, # Pride and Prejudice
11, # Alice's Adventures in Wonderland
76, # Adventures of Huckleberry Finn
74, # The Adventures of Tom Sawyer
1952, # The Yellow Wallpaper
4300, # Ulysses
27827, # The Kama Sutra of Vatsyayana
174, # The Picture of Dorian... | f Frederick Douglass, an American Slave
120, # Treasure Island
768, # Wuthering Heights
10609, # English Literature
42, # The Strange Case of Dr. Jekyll and Mr. H | yde
2852, # The Hound of the Baskervilles
27, # Far from the Madding Crowd
#4233, # Novo dicionario da lingua portuguesa
236, # The Jungle Book
2600, # War and Peace
2554, # Crime and Punishment
219, # Heart of Darkness
1497, # The Republic
100, # The Complete Wo... |
qutip/qutip | qutip/tests/test_random.py | Python | bsd-3-clause | 5,522 | 0.000543 | import numpy as np
from qutip import (
rand_ket, rand_dm, rand_herm, rand_unitary, rand_ket_haar, rand_dm_hs,
rand_super, rand_unitary_haar, rand_dm_ginibre, rand_super_bcsz, qeye,
rand_stochastic,
)
import pytest
@pytest.mark.repeat(5)
@pytest.mark.parametrize('func', [rand_unitary, rand_unitary_haar])
d... | j.isherm
@pytest.mark.repeat(5)
def test_rand_dm_ginibre_rank():
"""
Random Qobjs: Ginibre-random density ops have correct rank.
"""
random_qobj = rand_dm_ginibre(5, rank=3)
rank = sum([abs(E) >= 1e-10 for E in random_qobj.eigenenergies()])
assert rank == 3
@pytest.mark.repeat(5)
@pytest.mar... | metrize('kind', ["left", "right"])
def test_rand_stochastic(kind):
"""
Random Qobjs: Test random stochastic
"""
random_qobj = rand_stochastic(5, kind=kind)
axis = {"left":0, "right":1}[kind]
np.testing.assert_allclose(np.sum(random_qobj.full(), axis=axis), 1,
atol=... |
ricotabor/opendrop | opendrop/vendor/harvesters/__init__.py | Python | gpl-2.0 | 22 | 0 | __ve | rsion__ = '1.2.8' | |
heddle317/moto | tests/test_awslambda/test_lambda.py | Python | apache-2.0 | 14,853 | 0.000404 | from __future__ import unicode_literals
import base64
import botocore.client
import boto3
import hashlib
import io
import json
import zipfile
import sure # noqa
from freezegun import freeze_time
from moto import mock_lambda, mock_s3, mock_ec2, settings
def _process_lamda(pfunc):
zip_output = io.BytesIO()
z... | ""
def lambda_handler(event, context):
volume_id = event.get('volume_id')
print('get volume deta | ils for %s' % volume_id)
import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2', endpoint_url="http://{base_url}")
vol = ec2.Volume(volume_id)
print('Volume - %s state=%s, size=%s' % (volume_id, vol.state, vol.size))
return event
""".format(base_url="localhost:5000" if settings.TEST_SERVE... |
nttcom/eclcli | eclcli/compute/v2/host.py | Python | apache-2.0 | 2,150 | 0 | # Copyright 2013 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 required by applicable law or agree... | og_name)
parser.add_argument(
"--zone",
metavar="<zone>",
help="Only return hosts in the availability zone.")
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
columns = (
"Host Name",
... | operties(
s, columns,
) for s in data))
class ShowHost(command.Lister):
"""Show host command"""
def get_parser(self, prog_name):
parser = super(ShowHost, self).get_parser(prog_name)
parser.add_argument(
"host",
metavar="<host>",
... |
PritishC/nereid | trytond_nereid/tests/test_country.py | Python | gpl-3.0 | 6,084 | 0 | # -*- coding: utf-8 -*-
"""
Test Country
:copyright: (c) 2014 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
import json
import unittest
from decimal import Decimal
import trytond.tests.test_tryton
from trytond.tests.test_tryton import POOL, USER, DB_NAM... | country1, country2, = self.Country.create([{
'name': 'India',
'code': 'IN'
}, {
'name': 'Australia',
'code': 'AU',
}])
# Create subdivision | only for country1
self.Subdivision.create([{
'country': country1.id,
'code': 'IN-OR',
'name': 'Orissa',
'type': 'state',
}])
with app.test_client() as c:
rv = c.get('/countries/%d/subdivisions' % countr... |
imp/transitions | tests/test_reuse.py | Python | mit | 7,652 | 0.001568 | try:
from builtins import object
except ImportError:
pass
from transitions import MachineError
from transitions.extensions import HierarchicalMachine as Machine
from transitions.extensions import NestedState
from .utils import Stuff
from unittest import TestCase
try:
from unittest.mock import MagicMock
e... | (self):
pass
def test_blueprint_simple(self):
states = ['A', 'B', 'C', 'D']
# Define with list of dictionaries
transitions = [
{'trigger': 'walk', 'source': 'A', 'dest': 'B'},
{'trigger': 'run', 'source': 'B', 'dest': 'C'},
| {'trigger': 'sprint', 'source': 'C', 'dest': 'D'}
]
m = Machine(states=states, transitions=transitions, before_state_change='before_state_change',
after_state_change='after_state_change', initial='A')
self.assertEqual(len(m.blueprints['states']), 4)
self.assertEq... |
google/tink | python/tink/_keyset_reader_test.py | Python | apache-2.0 | 4,878 | 0.005535 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | er('not json')
with self.assertRaises(core.TinkError):
reader.read()
def test_read_encrypted(self):
# encryptedKeyset is a base64-encoding of 'some ciphertext wi | th keyset'
json_encrypted_keyset = """
{
"encryptedKeyset": "c29tZSBjaXBoZXJ0ZXh0IHdpdGgga2V5c2V0",
"keysetInfo": {
"primaryKeyId": 42,
"keyInfo": [
{
"typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
"out... |
kayhayen/Nuitka | nuitka/nodes/TryNodes.py | Python | apache-2.0 | 17,486 | 0.000972 | # Copyright 2021, Kay Hayen, mailto:[email protected]
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | ef=except_handler.source_ref,
)
except_handler = None
# If tried may raise, even empty exception handler has a meaning to
# ignore that exception.
if tried_may_raise:
collection_exception_handling = TraceCollectionBranch(
parent=colle... | re, this is a problem, we just
# found an inconsistency that is a bug.
if not exception_collections:
for statement in tried.subnode_statements:
if statement.mayRaiseException(BaseException):
raise NuitkaOptimizationError(
... |
SINGROUP/pycp2k | pycp2k/classes/_hf4.py | Python | lgpl-3.0 | 1,138 | 0.002636 | from pycp2k.inputsection import InputSection
from ._hf_info4 import _hf_info4
from ._periodic5 import _periodic5
from ._screening5 import _screening5
from ._interaction_potential5 import _interaction_potential5
from ._load_balance4 import _load_balance4
from ._memory5 import _memory5
class _hf4(InputSection):
def... | self.INTERACTION_POTENTIAL = _interaction_potential5()
self.LOAD_BALANCE = _load_balance4()
self.MEMORY = _memory5()
self._name = "HF"
self._keywords = {'Treat_lsd_in_core': 'TREAT_LSD_IN_CORE', 'Pw_hfx_blocksize': 'PW_HFX_BLOCKSIZE', 'Fraction': 'FRACTION', 'Pw_hfx': 'PW_HFX'}
... | E': 'LOAD_BALANCE', 'PERIODIC': 'PERIODIC', 'MEMORY': 'MEMORY', 'INTERACTION_POTENTIAL': 'INTERACTION_POTENTIAL', 'HF_INFO': 'HF_INFO'}
|
lubosz/gst-plugins-vr | valgrind_helpers/valgrind-make-fix-list.py | Python | lgpl-2.1 | 628 | 0.004777 | #!/usr/bin/env python
import os, sys
usage = "usage | : %s [infile [outfile]]" % os.path.basename(sys.argv[0])
if len(sys.argv) < 1:
print (usage)
else:
stext = "<insert_a_suppression_name_here>"
rtext = "memcheck problem #"
input = sys.stdin
output = sys.stdout
hit = 0
if len(sys.argv) > 1:
input = open(sys.argv[1])
if len(sys.arg... | hit = hit + 1
output.write(s.replace(stext, "memcheck problem #%d" % hit))
else:
output.write(s)
|
ctrlaltdel/neutrinator | vendor/openstack/identity/version.py | Python | gpl-3.0 | 1,236 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | pes = resource.Body('media-types')
status = resource.Body('status')
updated = resource.Body('updated')
@classmethod
def list(cls, session, paginated=False, base_path=None, **params):
if base_path is None:
base_path = cls.base_path
resp = session. | get(base_path,
params=params)
resp = resp.json()
for data in resp[cls.resources_key]['values']:
yield cls.existing(**data)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.