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
bioinformed/pysam
benchmark/python_flagstat.py
Python
mit
622
0.003215
"""compute number of reads/alignments from BAM file =================================================== This is a benchmarking utility script with limited functionality. Compute simple flag stats on a BAM
-file using the pysam python interface. """ import sys import pysam assert len(sys.argv) == 2, "USAGE: {} filename.bam".format(sys.argv[0]) is_paired = 0 is_proper = 0 for read in pysam.AlignmentFile(sys.argv[1], "rb"): is_paired += read.is_paired is_proper += read.is_proper_pair print ("there are alignmen...
s_proper)
plotly/python-api
packages/python/plotly/plotly/graph_objs/scatterternary/hoverlabel/_font.py
Python
mit
11,245
0.0008
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Font(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scatterternary.hoverlabel" _path_str = "scatterternary.hoverlabel.font" _valid_props = {"color...
urn self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val # family # ------ @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if ...
multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are in...
levilucio/SyVOLT
tests/combine_test.py
Python
mit
20,391
0.01025
''' Created on 2013-01-22 @author: levi ''' import unittest import time from path_condition_generator import PathConditionGenerator from t_core.matcher import Matcher from t_core.rewriter import Rewriter from t_core.iterator import Iterator from t_core.messages import Packet from t_core.tc_python.frule import FRul...
kS2S_run4LHS from police_station_transformation.run4.backward_matchers.HSF2SFBackF2F_run4LHS import HSF2SFBackF2F_run4LHS from police_station_transfo
rmation.run4.backward_matchers.HMM2MMBackM2M1_run4LHS import HMM2MMBackM2M1_run4LHS from police_station_transformation.run4.backward_matchers.HMM2MMBackM2M2_run4LHS import HMM2MMBackM2M2_run4LHS from police_station_transformation.run4.backward_matchers.HFF2FFBackF2F1_run4LHS import HFF2FFBackF2F1_run4LHS from police_st...
srijanss/rhub
webapp/tests.py
Python
mit
28,803
0.020067
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.urls import reverse from django.test import TestCase from django.utils import timezone import copy from django.contrib.auth.models import User, Group from .models import Restaurant, Type, Cuisine, Food, Booking from .views ...
, 'description': 'test', 'state': 'test', 'city': 'test', 'street': 'test', 'longitude': 0.000111, 'latitude': 0.000111, 'telephone': '1234567890', 'website': 'http://test.com' } class RestaurantModelTests(TestCase): def test_restaurant_object_creation(self): """ Restaurant object crea...
restaurant = create_restaurant("Test Restaurant") self.assertIs(isinstance(restaurant, Restaurant), True) self.assertEqual(restaurant.__str__(), restaurant.name) class TypeModelTests(TestCase): def test_type_object_creation(self): """ Type object created must return true for isinstance() and __str__() m...
andyvand/cygsystem-config-cluster
src/Apache.py
Python
gpl-2.0
327
0.006116
import string from TagObject import TagObject from BaseResource import BaseResource import gettext _ = gettext.gettext TAG_NAME = "apache" RESOURCE_TYPE = _("Apa
che Server") class Apache(BaseResource): def __init__(self): BaseResource.__init__(self) self.TAG_NAME = TAG_
NAME self.resource_type = RESOURCE_TYPE
luken/SpockBot
spockbot/plugins/helpers/interact.py
Python
mit
9,523
0
""" Interact with the world: - swing the arm, sneak, sprint, jump with a horse, leave the bed - look around - dig/place/use blocks - use the held (active) item - use/attack entities - steer vehicles - edit and sign books By default, the client sends swing and look packets like the vanilla client. This can be disabled ...
requires = ('ClientInfo', 'Inventory', 'Net', 'Channels') def __init__(self, ploader, settings): super(InteractPlugin, self).__init__(ploader, settings) ploader.provides('Interact', self) self.sneaking = False self.sprinting = False self.dig_p
os_dict = {'x': 0, 'y': 0, 'z': 0} self.auto_swing = True # move arm when clicking self.auto_look = True # look at clicked things def swing_arm(self): self.net.push_packet('PLAY>Animation', {}) def _entity_action(self, action, jump_boost=100): entity_id = self.clientinfo.eid...
aitgon/wopmars
wopmars/tests/resource/model/FooBaseH.py
Python
mit
472
0
""" Example of module documentation which can be multiple-lined """ from sqlalchemy import Column, Integer, String from wopmars.Base import Base class FooBaseH(Base): """ Documentation for the class """ __tablename__ = "FooBaseH" id = Column(Integer, primary_key=True, auto
increment=True) name = Column(String(255)) state = Column(Strin
g) __mapper_args__ = { 'polymorphic_on': state, 'polymorphic_identity': "1" }
makelove/OpenCV-Python-Tutorial
官方samples/contours.py
Python
mit
2,455
0.019145
#!/usr/bin/env python ''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' # Python 2/3 compatibility from __future__ import print_funct...
e(levels): vis = np.zeros((h, w, 3), np.uint8) levels = levels - 3 cv2.drawContours( vis,
contours, (-1, 2)[levels <= 0], (128,255,255), 3, cv2.LINE_AA, hierarchy, abs(levels) ) cv2.imshow('contours', vis) update(3) cv2.createTrackbar( "levels+3", "contours", 3, 7, update ) cv2.imshow('image', img) cv2.waitKey() cv2.destroyAllWindows()
zzeleznick/zDjango
venv/lib/python2.7/site-packages/django/utils/timezone.py
Python
mit
9,180
0.002288
""" Timezone-related classes and functions. This module uses pytz when it's available and fallbacks when it isn't. """ from datetime import datetime, timedelta, tzinfo from threading import local import sys import time as _time try: import pytz except ImportError: pytz = None from django.conf import setting...
ekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0 class LocalTimezone(ReferenceLocalTimezone): """ Slightly improved local time implementation focusing on correctness. It still crashes on dates before 1970 or after 2038, but at least the ...
except (OverflowError, ValueError) as exc: exc_type = type(exc) exc_value = exc_type( "Unsupported value: %r. You should install pytz." % dt) exc_value.__cause__ = exc six.reraise(exc_type, exc_value, sys.exc_info()[2]) utc = pytz.utc if pytz else...
simvisage/oricreate
oricreate/fu/fu_poteng_bending.py
Python
gpl-3.0
1,193
0.000838
#------------------------------------------------------------------------- # # Copyright (c) 2009, IMB, RWTH Aachen. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in simvisage/LICENSE.txt and may be redistributed only # under the conditions described...
pt import \ IFu from .fu import \ Fu @provides(IFu) class FuPotEngBending(Fu): '''Optimization criteria based on minimum Bending energy of gravity. This plug-in class lets the crease pattern operators evaluate the integral over the spatial domain in an instantaneous configura
tion ''' def get_f(self, t=0): '''Get the bending energy of gravity. ''' return self.forming_task.formed_object.V def get_f_du(self, t=0): '''Get the derivatives with respect to individual displacements. ''' return self.forming_task.formed_object.V_du
arunhotra/tensorflow
tensorflow/python/summary/impl/directory_watcher.py
Python
apache-2.0
4,586
0.00785
"""Contains the implementation for the DirectoryWatcher class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.platform import gfile from tensorflow.python.platform import logging class DirectoryWatcher(object): """A ...
he new one. The sequence of events might look something # like this: # # 1. Event #1 written to file #1. # 2. We check for events and yield event #1 from file #
1 # 3. We check for events and see that there are no more events in file #1. # 4. Event #2 is written to file #1. # 5. Event #3 is written to file #2. # 6. We check for a new file and see that file #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the...
olt/mapproxy
mapproxy/test/system/test_wms_srs_extent.py
Python
apache-2.0
6,717
0.006253
# This file is part of the MapProxy project. # Copyright (C) 2014 Omniscale <http://omniscale.de> # # 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...
=50'}, {'body': img.read(), 'headers': {'content-type': 'image/png'
}}) with mock_httpd(('localhost', 42423), [expected_req]): resp = self.app.get('http://localhost/service?SERVICE=WMS&REQUEST=GetMap' '&LAYERS=direct&STYLES=' '&WIDTH=100&HEIGHT=100&FORMAT=image/png' '&BBOX=-100,3500000,100,3500100&SRS=EPSG:25832' ...
chenyyx/scikit-learn-doc-zh
examples/zh/applications/plot_tomography_l1_reconstruction.py
Python
gpl-3.0
5,478
0.001278
""" ====================================================================== Compressive sensing: tomography reconstruction with L1 prior (Lasso) ====================================================================== This example shows the reconstruction of an image from a set of parallel projections, acquired along dif...
x, than the projection operator used here. The reconstruction with L1 penalization gives a result with zero error (all pixels are successfully labeled with 0 or 1), even if noise was added to the projections. In comparison, an L2 penalization (:class:`sklearn.linear_model.Ridge`) produces a large number of labeling er...
ontrary to the L1 penalization. Note in particular the circular artifact separating the pixels in the corners, that have contributed to fewer projections than the central disk. """ print(__doc__) # Author: Emmanuelle Gouillart <emmanuelle.gouillart@nsup.org> # License: BSD 3 clause import numpy as np from scipy impo...
RANUX/django-payway
payway/merchants/http.py
Python
bsd-2-clause
1,585
0.001893
# -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices(...
self.POST = self.__request() def __set_GET(self, *args, **kwargs): self.GET = self.__request() def __request(self): return { 'url': self.merchant.result_url, 'data': { 'uid': self.order.uid, 'is_paid': self.order.is_paid, ...
on, } } class MerchantHttpClient(HttpClient): @classmethod def notify(cls, merchant, order): result = '' try: request = MerchantHttpRequest(merchant, order) response = cls.execute(request) result = response.text except ConnectionE...
tysonholub/twilio-python
twilio/rest/serverless/v1/service/environment/deployment.py
Python
mit
15,554
0.003665
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base...
st.serverless.v1.service.environment.deployment.DeploymentPage """ response = self._version.domain.twilio.request( 'GET', target_url, ) return DeploymentPage(self._version, response, self._solution) def create(self, build_sid): """ Create a n...
:param unicode build_sid: The SID of the build for the deployment :returns: Newly created DeploymentInstance :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance """ data = values.of({'BuildSid': build_sid, }) payload = self._version.creat...
google/pyctr
core/qual_names.py
Python
apache-2.0
8,100
0.01
# 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, s...
ge(0, len(self
.qn) - 1): if self.has_subscript(): delimiter = '_sub_' else: delimiter = '_' ssf_string += ssfs[i] + delimiter return ssf_string + ssfs[-1] def ast(self): """Determine gast.Node type of current object.""" # The caller must adjust the context appropriately. if self.h...
eviljeff/olympia
src/olympia/amo/tests/test_decorators.py
Python
bsd-3-clause
5,649
0
from datetime import datetime, timedelta from django import http from django.contrib.auth.models import AnonymousUser from django.core.exceptions import PermissionDenied from django.test import RequestFactory from django.utils.encoding import force_text from unittest import mock import pytest from olympia import amo...
func(request): return {'x': 1} response = decorators.json_view(func, status_code=202)(mock.Mock()) assert response.status_code == 202 def test_json_view_res
ponse_status(): response = decorators.json_response({'msg': 'error'}, status_code=202) assert force_text(response.content) == '{"msg": "error"}' assert response['Content-Type'] == 'application/json' assert response.status_code == 202 class TestLoginRequired(TestCase): def setUp(self): sup...
Omenia/RFHistory
ServerApp/apps.py
Python
mit
134
0
from __future__ import
unicode_literals from django.ap
ps import AppConfig class RfhistoryConfig(AppConfig): name = 'RFHistory'
rlworkgroup/metaworld
metaworld/policies/sawyer_coffee_button_v1_policy.py
Python
mit
1,025
0.000976
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeeButtonV1Policy(Policy): @staticmethod
@assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'mug_pos': o
bs[3:6], 'unused_info': obs[6:], } def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({ 'delta_pos': np.arange(3), 'grab_effort': 3 }) action['delta_pos'] = move(o_d['hand_pos'], to_xyz=self._desired_pos(o_d), p=10.) ...
guolivar/totus-niwa
service/thirdparty/featureserver/tests/geoalchemy_model.py
Python
gpl-3.0
605
0.004959
from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base from geoalchemy import GeometryColumn, LineString, Geometry
DDL engine = create_engine('postgres://michel@localhost/featureserver', echo=False) session = sessionmaker(bind=engine)() metadata = MetaData(engine) Base = declarative_base(metadata=metadata) class Road(Base): __tablename__ = 'fs_alchemy_road' id = Column(Integer, primary_key=True) name = Column(Unicode,...
Column(LineString(2)) GeometryDDL(Road.__table__)
neslihanturan/artge
artge/wsgi.py
Python
gpl-3.0
387
0
""" WSGI config for artge project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see htt
ps://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os fro
m django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "artge.settings") application = get_wsgi_application()
gobstones/PyGobstones-Lang
tests/basictests/basictests_test.py
Python
gpl-3.0
132
0.015152
from FileBundleTestCase imp
ort FileBundleTestCase import unittest class BasicTests(unittest.Te
stCase, FileBundleTestCase): pass
erdc-cm/numexpr
numexpr/expressions.py
Python
mit
14,057
0.006189
__all__ = ['E'] import operator import sys import threading import numpy # Declare a double type that does not exist in Python space double = numpy.double # The default kind for undeclared variables default_kind = 'double' type_to_kind = {bool: 'bool', int: 'int', long: 'long', float: 'float', doub...
eans when ``False`` and ``True`` are already # supported. if isinstance(x, (bool, numpy.bool_)): return bool # ``long`` is not explicitly needed since ``int`` automatically # returns longs when needed (since Python 2.3). # The duality of float and double in Python avoids that we have to list...
`` too. for converter in int, float, complex: try: y = converter(x) except StandardError, err: continue if x == y: # Constants needing more than 32 bits are always # considered ``long``, *regardless of the platform*, so we # can cle...
Ziemin/telepathy-gabble
tests/twisted/jingle/call-hold-audio.py
Python
lgpl-2.1
28,484
0.015974
""" Test the Hold API. """ import dbus from dbus.exceptions import DBusException from functools import partial from servicetest import call_async, EventPattern, assertEquals, assertLength from jingletest2 import test_all_dialects from gabbletest import sync_stream from call_helper import CallTest, run_call_test import...
_REQUESTED), chan.Hold.GetHoldState()) def connect(self): assertEquals((cs.HS_HELD, cs.HSR_REQUESTED), self.chan.Hold.GetHoldState()) assertEquals((cs.HS_HELD, cs.HSR_REQUES
TED), self.chan.Hold.GetHoldState()) CallTest.connect(self, expect_after_si=self.hold_event) def accept_outgoing(self): # We are on hold, no states to complete here self.check_channel_state(cs.CALL_STATE_PENDING_INITIATOR) self.chan.Accept(dbus_interface=cs.CHANNEL_...
yossarianirving/pyvatebin
pyvatebin/__init__.py
Python
mit
27
0
fr
om .pyvatebin import app
Julian24816/lHelper
assign_group_name.py
Python
gpl-3.0
786
0.002545
# coding=utf-8 """ Lets the user assign groups to all cards, which have no group yet. """ import data cards = [data.database_manager.get_card(card_id) for card_id, in data.database_manager.get_connection().execute( "SELECT card_id FROM card WHERE card_id NOT IN (SELECT card_id FROM card_group_membership)").fetch...
] for card in cards: if card not in new_cards: new_cards.append(card) print(len(new_cards)) cards = new_cards group_name = "adeo-11" for card_id, translations in cards: for translation in translations: print(translation) group = input("group_name? {} > ".format(group_name)).strip(" ") i...
_manager.add_card_to_group(card_id, group_name)
blcook223/bencook.info
blog/models.py
Python
isc
1,100
0.001818
from markdown import markdown from django.db import models from django.core.urlresolvers import reverse class Tag(models.Model): """ A subject-matter tag for blog posts """ slug = models.CharField(max_length=200, unique=True) name = models.SlugField(max_length=200, unique=True) def __str__(s...
lug = models.SlugField(max_length=50, unique=True) body = models.TextField() date = models.DateField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.title def get_absolute_url(self): return reverse('post', args=(self.slug,)) def teaser(self...
return ' '.join([self.body[:100], '...']) def body_html( self ): return markdown(self.body) class Meta: ordering = ('title', 'date', 'body')
jonobacon/ubuntu-accomplishments-viewer
accomplishments_viewer_lib/Builder.py
Python
gpl-3.0
11,454
0.00096
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2012 Jono Bacon <jono@ubuntu.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foun...
ionary # *_dict dictionary # *name string # ele_* element in a ElementTree # pylint: disable=R0904 # the many public methods is a feature of Gtk.Builder class Builder(Gtk.Builder): ''' extra features connects glade defined handler to default_handler if necessary auto connects widget to handler with matchi...
n_* not made ''' def __init__(self): Gtk.Builder.__init__(self) self.widgets = {} self.glade_handler_dict = {} self.connections = [] self._reverse_widget_dict = {} # pylint: disable=R0201 # this is a method so that a subclass of Builder can redefine it def default_h...
andrewcbennett/iris
lib/iris/tests/test_cdm.py
Python
gpl-3.0
49,510
0.004161
# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any l...
eError): self.cube.add_dim_coord(scalar_dim_coord, []) with self.assertRaises(ValueError): self.cube.add_dim_coord(scalar_dim_coord, ()) cub
e = self.cube.copy() cube.add_aux_coord(scalar_dim_coord) cube.add_aux_coord(scalar_aux_coord) self.assertEqual(set(cube.aux_coords), {scalar_dim_coord, scalar_aux_coord}) # Various options for dims cube = self.cube.copy() cube.add_aux_coord(scalar_dim_coord, [])...
Exploit-install/Veil-Pillage
modules/enumeration/host/etw_results.py
Python
gpl-3.0
3,006
0.006986
""" Parses the results found for the ETW started on a machine, downloads the results and stops the ETW. All credit to pauldotcom- http://pauldotcom.com/2012/07/post-exploitation-recon-with-e.html Module built by @harmj0y """ import settings from lib import command_methods from lib import helpers from lib im...
ds '"+username+":"+password+"' on : " + target + "\n" else: # save the file off to the appropriate location saveFile = helpers.saveModuleFile(self, target, moduleFile, parseResult) self.output += "[*] ETW results for "+flag+" using creds '"+username+":"+passwo...
target + " stored at "+saveFile+"\n"
ParrotPrediction/pyalcs
lcs/agents/xcs/__init__.py
Python
mit
207
0
from .Condition import Condition from .Configuration import Configuration from .Classifier import Classifier from .ClassifiersList import ClassifiersList
from .XCS import XCS from .Geneti
cAlgorithm import *
openstack/tempest-lib
tempest_lib/api_schema/response/compute/v2_1/services.py
Python
apache-2.0
2,380
0
# Copyright 2014 NEC Corporation. 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 ...
'id': {'type': ['integer', 'string'], 'pattern': '^[a-zA-Z!]*@[0-9]+$'}, 'zone': {'type': 'string'}, 'host': {'type': 'string'}, 'state': {'type': 'string'}, 'binary': {'ty...
string', 'null']}, 'disabled_reason': {'type': ['string', 'null']} }, 'additionalProperties': False, 'required': ['id', 'zone', 'host', 'state', 'binary', 'status', 'updated_at', 'disabled_reason'] ...
codekoala/treedo
treedo/gui.py
Python
bsd-3-clause
12,628
0.003405
import wx import wx.calendar from wx.lib.masked import TimeCtrl from wx.lib.agw import hypertreelist as HTL from datetime import datetime, time from lib import Task, DATA, PRIORITIES, DEFAULT_PRIORITY from decorators import requires_selection ID_ADD_TASK = 1000 ID_ADD_SUBTASK = 1010 ID_COLLAPSE = 1020 ID_EXPAND = 103...
izer.Add((20, 20), 0, 0, 0) sizer.Add(self.chkIsComplete, 0, 0, 0) sizer.Add(self.lblDateDue, 0, wx.ALIGN_RIGHT, 0) sizer.Add(self.chkIsDue, 0, 0, 0) sizer.Add((20, 20), 0, 0, 0) sizer.Add(self.calDueDate, 0, 0, 0) sizer.Add((20, 20), 0, 0, 0) sizer.Add(self.txtTi...
mainSizer.AddF(self.CreateStdDialogButtonSizer(wx.OK|wx.CANCEL), wx.SizerFlags(0).Expand().Border(wx.BOTTOM|wx.RIGHT, 5)) self.SetSizer(mainSizer) mainSizer.Fit(self) self.Layout() self.Centre() size = (290, 450) self.SetMinSize(size) ...
maxikov/tatmon
trash/setup.py
Python
gpl-3.0
83
0.012048
from distutils.core import setup impor
t py2ex
e setup(console=['newsputnik.py'])
ioam/param
setup.py
Python
bsd-3-clause
2,203
0.005447
import os from setuptools import setup ########## autover ########## def get_setup_version(reponame): """Use autover to get up to date version.""" # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param.version import Version return Ver...
:: 5 - Production/Stable", "Programming Language :: Python :: 2", "Programmi
ng Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Operating System :: OS Independent", "Intended Audience :: Science/Research", ...
dpetzold/django-angular
djng/styling/bootstrap3/field_mixins.py
Python
mit
1,771
0.001129
# -*- coding: utf-8 -*- from django.forms import fields from django.forms import widgets from djng.forms import field_mixins from . import widgets as bs3widgets class BooleanFieldMixin(field_mixins.BooleanFieldMixin): def get_converted_widget(self): assert(isinstance(self, fields.BooleanField)) if...
) if isinstance(self.widget, widgets.RadioSelect): self.widget_css_classes = None if not isinstance(self.widget, bs3widgets.RadioSelect): new_widget = bs3widgets.RadioSelect() new_widget.__dict__ = self.widget.__dict__ return new_widget c...
eChoiceField)) if isinstance(self.widget, widgets.CheckboxSelectMultiple): self.widget_css_classes = None if not isinstance(self.widget, bs3widgets.CheckboxSelectMultiple): new_widget = bs3widgets.CheckboxSelectMultiple() new_widget.__dict__ = self.widget....
YannickB/odoo-hosting
__unfinished__/clouder_template_taiga/template.py
Python
agpl-3.0
3,298
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron # Copyright 2015, TODAY Clouder SASU # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License with Attribution # ...
f.execute(['rm', '-rf', './*.tar.gz'], path='/var/www',
username='www-data') class ClouderBase(models.Model): """ Add methods to manage the shinken specificities. """ _inherit = 'clouder.base' @api.multi def deploy_build(self): """ Configure nginx. """ res = super(ClouderBase, self).deploy_build() if self.a...
vpstudios/Codecademy-Exercise-Answers
Language Skills/Python/Unit 5/1-Python Lists and Dictionaries/Lists/3-New Neibors.py
Python
mit
329
0.00304
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] # Last night our zoo's sloth brutally attacked #the poor tiger and ate it whole. # The ferocious
sloth has been replaced by a friendly hyena. zoo_animals[2] = "hyena" # What shall fill the void left by our dear departed tiger? # Your code here! zoo_animals[3] = 'teta'
mmb90/dftintegrate
dftintegrate/fourier/vaspdata.py
Python
mit
3,878
0
""" Classes:: VASPData -- A collection of functions that wrap bash code to extract data from VASP output into managable .dat (.txt) files. """ import numpy as np from subprocess import call, check_output from ast import literal_eval class VASPData(object): """ A collection of functions that wrap bash c...
ns:: extract_symops_trans -- Get symm
etry operations and translations from OUTCAR -> symops_trans.dat. extract_kpts_eigenvals -- Get k-points, weights, and eigenvalues from EIGENVAL -> kpts_eigenvals.dat. extract_kmax -- Get kmax from KPOINTS -> kmax.dat (details about what kmax is are given in readdata.py). """ ...
gartung/dxr
dxr/app.py
Python
mit
20,359
0.001326
from cStringIO import StringIO from datetime import datetime from functools import partial from itertools import chain, imap, izip from logging import StreamHandler import os from os import chdir from os.path import join, basename, split, dirname, relpath from sys import stderr from time import time from mimetypes impo...
config): """Return the rendered template for search.html.
""" frozen = frozen_config(tree) # Try a normal search: template_vars = { 'filters': filter_menu_items( plugins_named(frozen['enabled_plugins'])), 'generated_date': frozen['generated_date'], 'google_analytics_key': config.google_analytics_key, ...
audiolion/django-behaviors
tests/views.py
Python
mit
635
0
from django.views.generic.edit import CreateView, UpdateView from .models import AuthoredMock, EditoredMock from .forms import AuthoredModelFormMock, EditoredModelFormMock class FormKwargsR
equestMixin(object): def get_form_kwargs(self): kwargs = super(EditoredMockUpdateView, self).get_form_kwargs(self) kwargs['request'] = self.request return kwargs class AuthoredM
ockCreateView(FormKwargsRequestMixin, CreateView): model = AuthoredMock form = AuthoredModelFormMock class EditoredMockUpdateView(FormKwargsRequestMixin, UpdateView): model = EditoredMock form = EditoredModelFormMock
ltiao/networkx
networkx/algorithms/matching.py
Python
bsd-3-clause
32,997
0.001879
""" ******** Matching ******** """ # Copyright (C) 2004-2015 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. # Copyright (C) 2011 by # Nicholas Mancuso <nick.mancuso@gmail.com> # All rights reserved. # ...
) # If b is a sub-blossom, # blossomparent[b] is its immediate parent (sub-)blossom. # If b is a top-level blossom, blossomparent[b] is None. blossomparent = dict(zip(gnodes, repeat(None))) # If b is a (sub-)blossom, # blossombase[b] is its base VERTEX (i.e. recursive sub-blossom). blossom...
a T-blossom), # bestedge[w] = (v, w) is the least-slack edge from an S-vertex, # or None if there is no such edge. # If b is a (possibly trivial) top-level S-blossom, # bestedge[b] = (v, w) is the least-slack edge to a different S-blossom # (v inside b), or None if there is no such edge. # This ...
wufangjie/leetcode
727. Minimum Window Subsequence.py
Python
gpl-3.0
1,035
0.001932
from collections import defaultdict class Solution(object): def minWindow(self, S, T): """ :type S: str :type T: str :rtype: str """ pre = defaultdict(list) for i, c in enumerate(T, -1): pre[c].append(i) for val in pre.values(): ...
== T[-1] and start_index[-2] is not None and i - start_index[-2] < hi
- lo): lo, hi = start_index[-2], i if lo < 0: return '' else: return S[lo:hi+1] # print(Solution().minWindow("abcdebdde", "bde")) # print(Solution().minWindow("nkzcnhczmccqouqadqtmjjzltgdzthm", "bt")) print(Solution().minWindow("cnhczmccqouqadqtmjjzl", "mm"))
yanheven/console
openstack_dashboard/dashboards/project/volumes/volumes/tests.py
Python
apache-2.0
48,594
0.001173
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
glance.image_list_detailed(IsA(http.HttpRequest), filter
s={'is_public': True, 'status': 'active'}) \ .AndReturn([self.images.list(), False]) api.glance.image_list_detailed(IsA(http.HttpRequest), filters={'property-owner_id': self.tenant.id, ...
eugene7646/autopsy
test/script/regression.py
Python
apache-2.0
93,572
0.00451
#!/usr/bin/python # -*- coding: utf_8 -*- # Autopsy Forensic Browser # # Copyright 2013 Basis Technology Corp. # # 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/l...
details.") sys.exit(1) # exit
if a single-user case and the local .db file was not created if not file_exists(test_data.get_db_path(DBType.OUTPUT)) and not test_data.isMultiUser: Errors.print_error("Autopsy did not ru
rew4332/tensorflow
tensorflow/contrib/learn/python/learn/learn_io/graph_io_test.py
Python
apache-2.0
14,145
0.006999
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
me_queue" % name file_names_name = "%s/input" % file_name_queue_name example_queue_name = "%s/random_shuffle_queue" % name op_nodes = test_util.assert_ops_in_graph({ file_names_name: "Const",
file_name_queue_name: "FIFOQueue", "%s/read/TFRecordReader" % name: "TFRecordReader", example_queue_name: "RandomShuffleQueue", name: "QueueDequeueMany" }, g) self.assertEqual( set(_FILE_NAMES), set(sess.run(["%s:0" % file_names_name])[0])) self.asser...
qingtech/weibome
manage.py
Python
gpl-2.0
250
0
#!/usr/bin/env python import os import s
ys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weibome.settings") from django.core.management import execute_from_command_line execute_from_command_line(sy
s.argv)
KiChjang/servo
tests/wpt/web-platform-tests/tools/third_party/aioquic/tests/test_h3.py
Python
mpl-2.0
45,118
0.000997
import binascii from unittest import TestCase from aioquic.buffer import encode_uint_var from aioquic.h3.connection import ( H3_ALPN, ErrorCode, FrameType, FrameUnexpected, H3Connection, StreamType, encode_frame, ) from aioquic.h3.events import DataReceived, HeadersReceived, PushPromiseRece
ived from aioquic.h3.exceptions import NoAvailablePushIDError from aioquic.quic.configuration import QuicConfiguration from aioquic.quic.events import StreamDataReceived from aioquic.quic.logger import QuicLogger from .test_connection import client_and_server, transfer def h3_client_and_server(): return client_a...
) def h3_transfer(quic_sender, h3_receiver): quic_receiver = h3_receiver._quic if hasattr(quic_sender, "stream_queue"): quic_receiver._events.extend(quic_sender.stream_queue) quic_sender.stream_queue.clear() else: transfer(quic_sender, quic_receiver) # process QUIC events ...
fwenzel/django-sha2
test/django13/tests/test_bcrypt.py
Python
bsd-3-clause
6,294
0
# -*- coding:utf-8 -*- from django import test from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.management import call_command from mock import patch from nose.tools import eq_ class BcryptTests(test.TestCase): def setUp(se...
suffix = '$2011-01-01' raw_hashes = { 'john': '02CfJWdVwLK80jlRe/Xx1u8sTHAR0JUmKV9YB4BS.Os4LK6nsoLie', 'jane': '.ipDt6gRL3CPkVH7FEyR6.8YXeQFXAMyiX3mXpDh4YDBonrdofrcG', 'jude': '6Ol.vgIFxMQw0LBhCLtv7OkV.oyJjen2GVMoiNcLnbsljSfYUkQqe', } u = User.objects.get(...
ix, raw_hashes['john'], suffix) u.password = django14_style_password assert u.check_password('123456') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jane") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jan...
petervago/instrument-control
Python_client/test_tcp.py
Python
gpl-3.0
5,163
0.025567
##################################### # Example how to control Agilent Function egenrator over GPIB # Author, Peter Vago, NI Systems Engineer, 2016 # # PyVISA 1.8 version is used. # For migrating from older version (<1.5) read this: https://media.readthedocs.org/pdf/pyvisa/master/pyvisa.pdf # ########################...
elif args[1]=='scpi-short': if len(args)<3: ind=0 for i in examples: print("%d: %s"%(ind,i)) ind+=1 return 0, "Usage: python test_tcp.py scpi-short <num>" else: index=int(args[2]) command=examples[index] ...
ENS": if len(args)<4: return 2, "-" else: parameter=args[3] # e.g. -10 elif cmd[0:5]=="*IDN?": cmd="*IDN?" parameter="" else: return 2 , cmd[0:4] command=cmd+" "+parameter elif args[1]=='file': ...
WillemJan/Narralyzer
narralyzer/config.py
Python
gpl-3.0
7,418
0.001213
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- ''' narralyzer.config ~~~~~~~~~~~~~~~~~ Handle misc config variables. :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem-Jan Faber. :license: GPLv3, see licence.txt for more details. ''' from os import path, listdir from ConfigParser import Con...
st)): return None # Parse the 'models', into lang_en_stanford_port: 9991 fashion. if isins
tance(result, dict): if variable.endswith('stanford_path'): requested_language = variable.replace('_stanford_path', '') requested_language = requested_language.replace('lang_', '') for language_3166 in result: if language_3166 == requested_...
qtile/qtile
libqtile/backend/wayland/__init__.py
Python
mit
135
0
# Shorten the import for this becaus
e it will be used in configs from libqtile.backend.wayland.inputs import InputConfig
# noqa: F401
divtxt/binder
bindertest/test_table.py
Python
mit
9,815
0.002038
import unittest from datetime import date from binder.col import * from binder.table import Table, SqlCondition, SqlSort, AND, OR from bindertest.tabledefs import Foo, Bar class TableTest(unittest.TestCase): def test_init_2_AutoIdCols(self): # Table can have only 1 AutoIdCol try: T...
ntCol("x"), AutoIdCol("id2")) except AssertionError, e: self.assertEquals("Table 'xyz' has more than one AutoIdCol", str(e)) else: self.fail() def test_init_duplicate_col_name(self): try: Table("xyz", AutoIdCol("id1"), IntCol("x"), UnicodeCol("x", 20)) ...
): expected = ["foo_id", "i1", "s1", "d1"] actual = [col.col_name for col in Foo.cols] self.assertEquals(expected, actual) expected = ["bi", "bs", "bd", "bdt1", "bb"] actual = [col.col_name for col in Bar.cols] self.assertEquals(expected, actual) def test_auto_id_col...
AtonLerin/pymel
maya/utils.py
Python
bsd-3-clause
9,716
0.003396
""" General utility functions that are not specific to Maya Commands or the OpenMaya API. Note: By default, handlers are installed for the root logger. This can be overriden with env var MAYA_DEFAULT_LOGGER_NAME. Env vars MAYA_GUI_LOGGER_FORMAT and MAYA_SHELL_LOGGER_FORMAT can be used to override the default format...
calling this function will cause "myPackage" to be imported, in order to determine myPackage.__path__ (though in most circumstances, it will already have
been). Parameters ---------- modName : str The name of the overriden module that you wish to execute callingFileFunc : function A function that is defined in the file that calls this function; this is provided solely as a means to identify the FILE that calls this functi...
nirvn/QGIS
tests/src/python/test_qgslayoutview.py
Python
gpl-2.0
27,525
0.00436
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsLayoutView. .. note:: 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. """ __a...
tem_spy = QSignalSpy(view.itemFocused) view.selectAll() self.assertTrue(item1.isSelected()) self.assertTrue(item2.isSelected()) self.assertFalse(item3.isSelected()) # locked self.assertEqual(len(focused_item_spy), 1) item3.setSelected(True) # locked item selection shou...
ertFalse(item3.isSelected()) # locked def testDeselectAll(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) l.addItem(item1) item2 = QgsLayoutItemPicture(l) l.addItem(item2) item3 = QgsLayoutItemPicture(l) ...
andersk/zulip
zerver/migrations/0302_case_insensitive_stream_name_index.py
Python
apache-2.0
706
0.004249
from django.db import migrations class Migration(migrations.Migration): dependencies = [
("zerver", "0301_fix_unread_messages_in_deactivated_streams"), ] operations = [ # We do Stream lookups case-insensitively with respect to the name, but we were missing # the appropriate (realm_id, upper(name::text)) unique index to enforce uniqueness # on database level. ...
upper(name::text)); """ ), migrations.AlterUniqueTogether( name="stream", unique_together=set(), ), ]
mzdaniel/oh-mainline
vendor/packages/kombu/kombu/tests/test_compat.py
Python
agpl-3.0
10,185
0.000295
from kombu.tests.utils import unittest from kombu import BrokerConnection, Exchange from kombu import compat from kombu.tests.mocks import Transport, Channel class test_misc(unittest.TestCase): def test_iterconsume(self): class Connection(object): drained = 0 def drain_events(...
try_to_queue("foo", **dict(defs))) class test_Publisher(unittest.TestCase): def setUp(self): self.connection = BrokerConnection(transport=Transport) def test_constructor(self): pub = comp
at.Publisher(self.connection, exchange="test_Publisher_constructor", routing_key="rkey") self.assertIsInstance(pub.backend, Channel) self.assertEqual(pub.exchange.name, "test_Publisher_constructor") self.assertTrue(pub.exchange.durabl...
dati91/servo
python/servo/packages.py
Python
mpl-2.0
343
0
# This Source Code F
orm is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.7.2", "llvm": "6.0.0", "moztools": "0.0.1-5", "ninja": "1.7.1",
"openssl": "1.1.0e-vs2015", }
BitWriters/Zenith_project
zango/lib/python3.5/site-packages/pip/operations/freeze.py
Python
mit
5,194
0
from __future__ import absolute_import import logging import re import pip from pip.req import InstallRequirement from pip.req.req_file import COMMENT_RE from pip.utils import get_installed_distributions from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.p...
line = line[len('--editable'):]
.strip().lstrip('=') line_req = InstallRequirement.from_editable( line, default_vcs=default_vcs, isolated=isolated, wheel_cache=wheel_cache, ) ...
micolous/python-slackrealtime
src/slackrealtime/event.py
Python
gpl-3.0
5,496
0.025837
""" slackrealtime/event.py - Event handling for Slack RTM. Copyright 2014-2020 Michael Farrell <http://micolous.id.au> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the L...
): pass class TeamJoin(BaseEvent): pass EVENT_HANDLERS = { u'hello': Hello, u'message': Message, u'channel_archive': Channe
lArchive, u'channel_created': ChannelCreated, u'channel_deleted': ChannelDeleted, u'channel_history_changed': ChannelHistoryChanged, u'channel_joined': ChannelJoined, u'channel_left': ChannelLeft, u'channel_marked': ChannelMarked, u'channel_rename': ChannelRename, u'channel_unarchive': ChannelUnarchive, u'im_...
dims/neutron
neutron/db/extradhcpopt_db.py
Python
apache-2.0
6,854
0
# Copyright (c) 2013 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
for dopt in extra_dhcp_opts: if self._is_valid_opt_value(dopt['opt_name'], dopt['opt_value']): ip_version = dopt.get('ip_version', 4) db = ExtraDhcpOpt( port_id=port['id'], ...
opt_value=dopt['opt_value'], ip_version=ip_version) context.session.add(db) return self._extend_port_extra_dhcp_opts_dict(context, port) def _extend_port_extra_dhcp_opts_dict(self, context, port): port[edo_ext.EXTRADHCPOPTS] = self._get_port_ext...
mbauskar/Das_Erpnext
erpnext/stock/report/bom_search/bom_search.py
Python
agpl-3.0
1,068
0.034644
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and Contributors and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json def execute(filters=None): data = [] parents = { "Sales BOM Item": "Sales BOM", "BOM Explosion Item": "BOM", "BOM ...
]).append(d.item_code) for parent, items in all_boms.iteritems(): valid = True for key, ite
m in filters.iteritems(): if key != "search_sub_assemblies": if item and item not in items: valid = False if valid: data.append((parent, parents[doctype])) return [{ "fieldname": "parent", "label": "BOM", "width": 200, "fieldtype": "Dynamic Link", "options": "doctype" }, { "fieldn...
oblalex/django-workflow
src/workflow/templatetags/__init__.py
Python
mit
49
0
"""
Temp
late tags for reversion application. """
alexsilva/proxyme
proxyme/settings.py
Python
mit
2,487
0.000402
""" Django settings for proxyme project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and t
heir values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BAS
E_DIR, ...) import os import tempfile BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#z$gq7gm...
lbryio/lbry
lbry/lbry/wallet/server/session.py
Python
mit
16,685
0.003776
import math import unicodedata as uda from binascii import unhexlify, hexlify from torba.rpc.jsonrpc import RPCError from torba.server.hash import hash_to_hex_str from torba.server.session import ElectrumX from torba.server import util from lbry.schema.result import Outputs from lbry.schema.url import URL from lbry.w...
im_id = self.db.get_claim_id_from_outpoint(unhexlify(tx_hash)[::-1], nout) claim_id = hexlify(raw_claim_id[::-1]).decode() claim = await self.claimtrie_getclaimbyid(claim_id) result.update(claim) return result async def claimtrie_getnthclaimforname(self, name, n): ...
s']) > n >= 0: # TODO: revist this after lbrycrd_#209 to see if we can sort by claim_sequence at this point result['claims'].sort(key=lambda c: (int(c['height']), int(c['nout']))) result['claims'][n]['claim_sequence'] = n return result['claims'][n] async def claimtri...
Djaler/ZloyBot
utils.py
Python
mit
2,934
0.001961
import functools import typing import inspect import itertools import supycache from telegram import Bot, User @supycache.supycache(cache_key='admin_ids_{1}', max_age=10 * 60) def get_admin_ids(bot: Bot, chat_id): return [admin.user.id for admin in bot.get_chat_administrators(chat_id)] def is_user_group_admin(...
functools.wraps(func) def inner(instance, bot, update): module, d
ata = parse_callback_data(update.callback_query.data) if module == current_module: return func(instance, bot, update) return lambda: True # помечает update с CallbackQuery обработанным, если ни один из хендлеров не подошел return inner def grouper(iterable, n): """ Позволяет ...
fps/teq
example.py
Python
lgpl-3.0
2,171
0.012897
# Let's import the teq module. Make sure the dynamic linker is setup to find libteq.so. Also # make sure that python finds teq.so (the python module). # import teq # Let's import the little python library that makes some things a little easier from pyteq import * # Create a teq object. This creates the jack client, ...
# Wait
for the user to press Enter... try: i = input("Press Enter to continue...") except: pass t.deactivate()
ohmu/kafka-python
test/test_protocol.py
Python
apache-2.0
12,430
0.001287
#pylint: skip-file import io import struct import pytest from kafka.protocol.api import RequestHeader from kafka.protocol.commit import GroupCoordinatorRequest from kafka.protocol.fetch import FetchRequest, FetchResponse from kafka.protocol.message import Message, MessageSet, PartialMessage from kafka.protocol.metada...
assert returned_offset2 == 1 message2 = Message(b'v2', key=b'k2') message2.encode() assert decoded_message2 == message2 def test_encode_message_header(): expect = b''.join([ struct.pack('>h', 10), # API Key struct.pack('>h', 0), # API Version struc...
# ClientId ]) req = GroupCoordinatorRequest[0]('foo') header = RequestHeader(req, correlation_id=4, client_id='client3') assert header.encode() == expect def test_decode_message_set_partial(): encoded = b''.join([ struct.pack('>q', 0), # Msg Offset ...
pymanopt/pymanopt
tests/test_manifolds/test_fixed_rank.py
Python
bsd-3-clause
7,028
0
import numpy as np from numpy import linalg as la from numpy import testing as np_testing from pymanopt.manifolds import FixedRankEmbedded from .._test import TestCase class TestFixedRankEmbeddedManifold(TestCase): def setUp(self): self.m = m = 10 self.n = n = 5 self.k = k = 3 se...
u @ s @ v.T) def test_ehess2rhess(self): pass def test_retr(self): # Test that the result is on the manifold and that for small # tangent vectors it has little effect. x = self.man.rand(
) u = self.man.randvec(x) y = self.man.retr(x, u) np_testing.assert_allclose(y[0].T @ y[0], np.eye(self.k), atol=1e-6) np_testing.assert_allclose(y[2] @ y[2].T, np.eye(self.k), atol=1e-6) u = u * 1e-6 y = self.man.retr(x, u) y = y[0] @ np.diag(y[1]) @ y[2] ...
EPFL-LCSB/pytfa
pytfa/__init__.py
Python
apache-2.0
151
0
# -*- coding:
utf-8 -*- """ Thermodynamic analysis for Flux-Based Analysis .. moduleauthor:: pyTFA team """ from .thermo.tmodel import
ThermoModel
paradigmsort/MagicValidate
pyx/metapost/path.py
Python
mit
12,868
0.003575
# -*- coding: ISO-8859-1 -*- # # Copyright (C) 2011 Michael Schindler <m-schindler@users.sourceforge.net> # # This file is part of PyX (http://pyx.sourceforge.net/). # # PyX 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...
lf.ly_pt def right_tension(self): return self.ry_pt def left_curl(self): return self.lx_pt def right_curl(self): return self.rx_pt left_given = left_curl right_given = right_curl def linked_len(self): """returns the length of a circularly linked list of knots""" ...
p = p.next return n def __repr__(self): result = "" # left if self.ltype == mp_endpoint: pass elif self.ltype == mp_explicit: result += "{explicit %s %s}" % (self.lx_pt, self.ly_pt) elif self.ltype == mp_given: result += "{given ...
fbradyirl/home-assistant
homeassistant/components/torque/sensor.py
Python
apache-2.0
3,807
0
"""Support for the Torque OBD application.""" import logging import re import voluptuous as vol from homeassistant.core import callback from homeassistant.components.http import HomeAssistantView from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_EMAIL, CONF_NAME from hom...
TFORM_SCHEMA.e
xtend( { vol.Required(CONF_EMAIL): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def convert_pid(value): """Convert pid from hex string to integer.""" return int(value, 16) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up t...
glwagner/py2Periodic
build/lib/py2Periodic/hydrostaticWavesInXY.py
Python
mit
10,836
0.01698
import doublyPeriodic import numpy as np; from numpy import pi import time class model(doublyPeriodic.numerics): def __init__( self, name = "hydrostaticWaveEquationExample", # Grid parameters nx = 128, Lx = 2.0*pi, ny = None, Ly ...
ticity initial condition: Gaussian vortex rVortex = self.Lx/20 q0 = 0.1*self.f0 * np.exp( \ - ( (self.XX-self.Lx/2.0)**2.0 + (self.YY-self.Ly/2.0)**2.0 ) \ / (2*rVortex**2.0) \ ) soln[:, :, 0] = q0 ## Default wave initial condition: plane w...
tisfies specified dispersion relation. kExact = np.sqrt(self.alpha)*self.kappa kApprox = 2.0*pi/self.Lx*np.round(self.Lx*kExact/(2.0*pi)) # Set initial wave velocity to 1 A00 = -self.alpha*self.f0 / (1j*self.sigma*kApprox) A0 = A00*np.exp(1j*kApprox*self.XX) soln[:, :, ...
djkonro/client-python
kubernetes/client/models/v1_resource_quota.py
Python
apache-2.0
7,239
0.001796
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds :return: The kind of this V1ResourceQuota. :rtype: str """ return self._kind @kind.setter def kind(self, kind): """ Sets the kind of this V1ResourceQuota. Kind is a stri...
senting the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds :param kind: The kind of this V1ResourceQuota. :type: str...
M4gn4tor/mastercard-api-python
Services/moneysend/domain/card_mapping/createmapping.py
Python
bsd-3-clause
108
0.009259
class CreateM
apping(object): def __init__(self): self.request_id = '' se
lf.mapping = ''
praetorian-inc/pentestly
recon/core/framework.py
Python
gpl-3.0
40,377
0.003715
from __future__ import print_function from contextlib import closing import cmd import codecs import inspect import json import os import random import re import socket import sqlite3 import string import subprocess import sys import traceback #================================================= # SUPPORT CLASSES #=====...
ork._script: print('%s' % (line))
if Framework._record: recorder = codecs.open(Framework._record, 'ab', encoding='utf-8') recorder.write(('%s\n' % (line)).encode('utf-8')) recorder.flush() recorder.close() if Framework._spool: Framework._spool.write('%s%s\n' % (self.prompt, line)) ...
igemsoftware2017/USTC-Software-2017
biohub/core/conf/__init__.py
Python
gpl-3.0
10,903
0.000459
import sys import os import os.path import json import filelock import tempfile import logging import warnings import multiprocessing from django.core.exceptions import ImproperlyConfigured from django.utils.functional import LazyObject, empty from biohub.utils.collections import unique from biohub.utils.module impor...
return val
ue def validate_throttle(self, value, default): if not isinstance(value, dict): raise TypeError("'THROTTLE' should be a dict, got type %r." % type(type(value))) default_value = default() default_value.update(value) return default_value def __delattr__(self, name)...
fotcorn/liveinconcert
event/migrations/0001_initial.py
Python
mit
777
0.003861
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('artist', '0002_auto_20150322_1630'), ] operations = [ migrations.CreateModel( name='Event', fields=[...
('location', models.CharField(max_length=500, verbose_name='Location')),
('date_time', models.DateTimeField(verbose_name='Date & Time')), ('artist', models.ForeignKey(to='artist.Artist')), ], options={ }, bases=(models.Model,), ), ]
ljean/coop_cms
coop_cms/templatetags/__init__.py
Python
bsd-3-clause
43
0.023256
#
-*- coding: utf-8 -*-
"""template tags"""
CooperLuan/sasoup
examples/__init__.py
Python
mit
16
0.0625
# encoding: u
tf8
arista-eosplus/pyeapi
test/system/test_api_system.py
Python
bsd-3-clause
9,596
0.000625
# # Copyright (c) 2014, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of condit...
esp = dut.api('system').set_iprouting(False) self.assertTrue(resp, 'dut=%s' % dut) self.asser
tIn('no ip routing', dut.running_config) def test_set_iprouting_to_no(self): for dut in self.duts: dut.config('ip routing') resp = dut.api('system').set_iprouting(disable=True) self.assertTrue(resp, 'dut=%s' % dut) self.assertIn('no ip routing', dut.running_c...
pdeesawat/PSIT58_test_01
Code_Affect_Damage_Death_countries/Myanmar_total_death.py
Python
apache-2.0
1,846
0.026002
"""Import Module Plotly To Ploting Graph""" import plotly.plotly as py import plotly.graph_objs as go """Open and Read CSV from database""" data = open('Real_Final_database_02.csv') alldata = data.readlines() listdata = [] for i in alldata: listdata.append(i.strip().split(',')) type_z = ['Flood', 'Epidemic', 'Drou...
00db'] trace = [] """Select and Set variable
Data affect that happen in each disaster in Myanmar""" for i in range(5): year_x = [] death_z = [] types_y = [] for j in listdata: if j[0] == 'Myanmar' and j[2] == type_z[i]: year_x.append(int(j[1])) death_z.append(int(j[5])) types_y.append(type_z[i]) tra...
mozilla/medlem
medlem/api/tests.py
Python
mpl-2.0
5,529
0
import json import mock from django.test import TestCase from django.core.urlresolvers import reverse class TestAPI(TestCase): @mock.patch('ldap.initialize') def test_exists(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = re...
hat 400 Bad Request errors are proper JSON self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual( json.loads(response.content),
{'error': "missing key 'mail'"} ) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'}, } def search_s(base, scope, filterstr, *args, **kwargs...
hivesolutions/appier
src/appier/legacy.py
Python
apache-2.0
13,083
0.02217
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Appier Framework # Copyright (c) 2008-2021 Hive Solutions Lda. # # This file is part of Hive Appier Framework. # # Hive Appier Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apach...
HTTPError = urllib.error.HTTPError else: HTTPError = urllib2.HTTPError if PYTHON_3: HTTPConnection = http.client.HTTPConnection #@UndefinedVariable else: HTTPConnection = httplib.HTTPConnection if PYTHON_3: HTTPSConnection = http.client.HTTPSConnection #@UndefinedVariable else: HTTPSConnection = httplib.HTTPS...
ept Exception: _execfile = None try: _reduce = reduce #@UndefinedVariable except Exception: _reduce = None try: _reload = reload #@UndefinedVariable except Exception: _reload = None try: _unichr = unichr #@UndefinedVariable except Exception: _unichr = None def with_meta(meta, *bases): return meta("C...
pmrowla/p101stat
tests/test_functional.py
Python
bsd-3-clause
101
0
# -*- coding:
utf-8 -*- """Functional tests using WebTest. See: http
://webtest.readthedocs.org/ """
lucasberti/telegrao-py
plugins/melenbra.py
Python
mit
2,962
0.002701
import json import time import sched from api import send_message scheduler = sched.scheduler(time.time, time.sleep) def load_reminders(): reminders = {} try: with open("data/reminders.json") as fp: reminders = json.load(fp) except Exception: with open("data/reminders.json",...
altime(futuretime) response = "belesinhaaaaa vo lenbra dia " + time.strftime("%d/%m/%y as %H:%M:%S", futuretime)
+ " sobr \"" + message + "\"" send_message(chat, response) def run(): scheduler.enter(1, 1, check_time) scheduler.run()
madhavsuresh/chimerascan
chimerascan/deprecated/breakpoint.py
Python
gpl-3.0
751
0.003995
''' Created on Jun 11, 2011 @author: mkiyer ''' class Breakpoint(object): def __init__(self): self.name = None self.seq5p = None self.
seq3p = None self.chimera_names = [] @property def pos(self): """ return position of break along sequence measured from 5' -> 3' """ return len(self.seq5p) @staticmethod def from_list(fields): b = Breakpoint() b.name =
fields[0] b.seq5p = fields[1] b.seq3p = fields[2] b.chimera_names = fields[3].split(',') return b def to_list(self): fields = [self.name, self.seq5p, self.seq3p] fields.append(','.join(self.chimera_names)) return fields
forkbong/qutebrowser
qutebrowser/config/config.py
Python
gpl-3.0
23,166
0.000216
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S...
-> Callable: """Filter calls to the decorated function. Gets called when a function should be decorated. Adds a filter which returns if we're not interested in the change-event and calls the wrapped function if we are. We assume the function passed doesn't take any para
meters. Args: func: The function to be decorated. Return: The decorated function. """ if self._function: @functools.wraps(func) def func_wrapper(option: str = None) -> Any: """Call the underlying function.""" ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/android/gyp/get_device_configuration.py
Python
mit
2,134
0.007498
#!/usr/bin/env python # # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Gets and writes the configurations of the attached devices. This configuration is used by later build steps to determine which de...
even if all but # one device were rejected for other reasons (e.g. two devices attached, # one w/o root). build_utils.PrintBigWarning( 'Multiple devices attached. ' 'Installing to the preferred device: ' '%(id)s (%(description)s)' % (device_configurat
ions[0])) build_device.WriteConfigurations(device_configurations, options.output) if __name__ == '__main__': sys.exit(main(sys.argv))
sjl767/woo
py/tests/psd.py
Python
gpl-2.0
5,075
0.032906
''' Test particle generator, that the resulting PSD curve matches the one on input. ''' import unittest from woo.core import * from woo.dem import * from minieigen import * import numpy class PsdSphereGeneratorTest(unittest.TestCase): def setUp(self): self.gen=PsdSphereGenerator(psdPts=[(.05,0),(.1,20),(.2...
3% tolerance here self.assertAlmostEqual(dMin,oPsd[0][0],delta=relDeltaD*dMin) self.assertAlmostEqual(dMax,oPsd[0][-1],delta=relDeltaD*dMax) class BiasedPositionTest(unittest.TestCase): def testAxialBias(self): 'Inlet: axial bias' bb=AxialBias(axis=0,d01=(2,1),fuzz=.1) d0,d...
b.fuzz/2.)
francxk/moves-event
movesevent/models/movesUser.py
Python
mit
1,082
0.014787
# -*- coding: utf-8 -*- ''' Created on 18 oct 2013 @author: franck ''' from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from movesevent.models.movesApp import MovesApp class MovesUser(models.Mod...
eturn '%s/%s' % (self.user.username, self.app.app_name); # Cela semble obligatoire pour la generation de la base class Meta: app_label='movesevent' unique_together = (("use
r", "app"),) verbose_name = "Moves user"
blossomica/airmozilla
airmozilla/main/migrations/0013_auto_20160223_1757.py
Python
bsd-3-clause
1,622
0.00185
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('main', '0012_auto_20160204_1503'), ] operations = [ migrations.AlterModelOptions( name='eventassignment', ...
migrations.AlterField( model_name='template', name='content', field=models.TextField(help_text=b"The HTML framework for this template. Use <code>{{ any_variable_name }}</code> for per-event tags. Other Jinja2 constructs are available, along with the related <code>request</cod...
ou can also reference <code>autoplay</code> and it's always safe. Additionally we have <code>vidly_tokenize(tag, seconds)</code>, <code>edgecast_tokenize([seconds], **kwargs)</code> and <code>akamai_tokenize([seconds], **kwargs)</code><br> Warning! Changes affect all events associated with this template."), ...
asedunov/intellij-community
python/testData/joinLines/BackslashBetweenTargetsInImport-after.py
Python
apache-2.0
15
0.133333
i
mport foo,
bar
delapsley/relman
relman/test.py
Python
apache-2.0
1,179
0.000848
# Copyright 2016 David Lapsley # # 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...
he License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import jira import source import unittest import mock class TestSource(unittest.TestCase): ...
k.Mock(return_value=None)) @mock.patch('jira.JIRA.search_issues', mock.Mock(return_value=[0, 1, 2, 3])) def test_something(self): server = 'server' user = 'user' password = 'password' jql = '' s = source.JIRASource(server, user, password, jql) idx ...
traltixx/pycolbert
pycolbert.py
Python
gpl-2.0
853,594
0.004569
import os import sys import subprocess testP = { "2005": [ { "date": "2005-10-17", "videos": [ "http://thecolbertreport.cc.com/videos/61f6xj/intro---10-17-05", "http://thecolbertreport.cc.com/videos/w9dr6d/first-show", "http://thecolbertreport.cc.com/videos/63ite2/the-word---t...
05", "http://thecolbertreport.cc.com/videos/kzin67/the-word---bacchanalia", "http://thecolbertreport.cc.com/videos/5icgst/all-you-need-to-know---illegal-immigration", "http://thecolbertreport.cc.com/videos/fydq17/lesley-stahl", "http://thecolbertreport.cc.com/videos/235ftw/better-know-a-...
], "guest": "Lesley Stahl" }, { "date": "2005-10-19", "videos": [ "http://thecolbertreport.cc.com/videos/vmoc19/intro---10-19-05", "http://thecolbertreport.cc.com/videos/gpmykq/the-word---disappointed", "http://thecolbertreport.cc.com/videos/95k30i/stephen-settles-the...
Kramer477/lasio
tests/test_open_file.py
Python
mit
2,943
0.002718
import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import pytest from lasio import read test_dir = os.path.dirname(__file__) egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn) def test_open_url(): l = read("https://raw.githubusercontent.com/kinverarity1/" ...
les" "/1.2/sample_curve_api.las") def test_open_file_object(): with open(egfn("sample.las"), mode="r") as f: l = read(f) def test_open_filename(): l = read(egfn("sample.las")) def test_open_incorrect_filename(): with pytest.raises(OSError):
l = read(egfn("sampleXXXDOES NOT EXIST.las")) def test_open_string(): l = read("""~VERSION INFORMATION VERS. 1.2: CWLS LOG ASCII STANDARD -VERSION 1.2 WRAP. NO: ONE LINE PER DEPTH STEP ~WELL INFORMATION BLOCK #MNEM.UNIT DATA TYPE INFORMATION #--------- ----...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/pylint/test/input/func_dotted_ancestor.py
Python
agpl-3.0
231
0.004329
"""bla""" # pylint: disable=no-absolute-im
port __revision__ = 'yo' from input import func_w02
33 class Aaaa(func_w0233.AAAA): """test dotted name in ancestors""" def __init__(self): func_w0233.AAAA.__init__(self)
fretsonfire/fof-python
src/NetworkTest.py
Python
mit
2,106
0.004274
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
et): self.packet = packet class TestServer(Network.Server): def createConnection(self, sock): return TestConnection(sock) class NetworkTest(unittest.TestCase): def testHandshake(self): s = TestServer() c = TestConnection() c.connect("localhost") c.
sendPacket("moikka") Network.communicate(100) client = s.clients.values()[0] assert client.packet == "moikka" assert client.id == 1 def tearDown(self): Network.shutdown() if __name__ == "__main__": unittest.main()
mlnichols/quaternion_class
setup.py
Python
mit
214
0.060748
from distutils.core import setup setup (
name = 'quaternion_class' author = 'M
atthew Nichols' author_email = 'mattnichols@gmail.com' packages = ['quaternion'] package_dir = {'quaternion':src} )
tokibito/django-edamame
example/note/views.py
Python
mit
1,407
0.002132
from django.shortcuts import render from django.conf.urls import patterns, url from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from edamame import base, utils, generic from . import models class SiteViews(base....
(r'^$', self.wrap_view(self.index), name='index'), url(r'^test_page$', self.wrap_view(self.test_page), name='test_page'), ) return urlpatterns site_views = SiteViews() class NoteViews(generic.ModelViews): model = models.Note success_url = reverse_lazy('note:index')...
base.Views): members_only = utils.to_method(render, template_name='members_only.html') view_decorators = ( (login_required, (), {'login_url': 'auth:login'}), ) def get_urls(self): urlpatterns = patterns( '', url(r'^$', self.wrap_view(self.members_only), name='mem...