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
3DRPP/printer
Adafruit_MotorHAT/Adafruit_I2C.py
Python
mit
5,465
0.016651
#!/usr/bin/python import re import smbus # =========================================================================== # Adafruit_I2C Class # =========================================================================== class Adafruit_I2C(object): @staticmethod def getPiRevision(): "Gets the version number of ...
self.errMsg() def writeList(self, reg, list): "Writes an array of bytes using I2C format" try: if self.debug: print("I2C: Writing list to register 0x%02X:" % reg) print(list) self.bus.write_i2c_block_data(self.address, reg, list) except IOError: return self.errMsg() ...
reg, length): "Read a list of bytes from the I2C device" try: results = self.bus.read_i2c_block_data(self.address, reg, length) if self.debug: print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % (self.address, reg)) print(results) return results e...
rmfitzpatrick/ansible
lib/ansible/modules/cloud/amazon/iam_policy.py
Python
gpl-3.0
14,001
0.003785
#!/usr/bin/python # 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...
- By default the module looks for any policies that match the document you pass in, if there is a match it will not make a new policy object with the same rules. You can override this by specifying false which would allow for two policy objects with dif
ferent names but same rules. required: false default: "/" notes: - 'Currently boto does not support the removal of Managed Policies, the module will not work removing/adding managed policies.' author: "Jonathan I. Davila (@defionscode)" extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' ...
asedunov/intellij-community
python/testData/refactoring/rename/renameShadowingVariable.py
Python
apache-2.0
42
0.071429
d
ef lab(): pass lab = 1 print(l<ca
ret>ab)
zhangpf/vbox
src/VBox/ValidationKit/testmanager/config.py
Python
gpl-2.0
6,083
0.02696
# -*- coding: utf-8 -*- # $Id$ """ Test Manager Configuration. """ __copyright__ = \ """ Copyright (C) 2012-2014 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the te...
nt/builds/' ## File on the build binary share that can be
used to check that it's mounted. g_ksBuildBinRootFile = 'builds.txt' ## @} ## The time to wait for a gang to gather (in seconds). g_kcSecGangGathering = 600; ## The max time allowed to spend looking for a new task (in seconds). g_kcSecMaxNewTask = 60; ## @name Test result limits. ## In general, we will ...
emreg00/biana
biana/ext/networkx/classes/graph.py
Python
gpl-3.0
35,652
0.007405
""" Base class for undirected graphs. The Graph class allows any hashable object as a node and can associate any object with an undirected edge. Self-loops are allowed but multiple edges are not (see MultiGraph) For directed graphs see DiGraph and XDiGraph. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)\nPiet...
graph del adj[n] # now remove node delete_node = remove_node def remove_nodes_from(self, nbunch): """Remove nodes specified in nbunch. Parameters
---------- nbunch : list, iterable A container of nodes that will be iterated through once (thus it should be an iterator or be iterable). Each element of the container should be a valid node type: any hashable type except None. Examples ----...
BitcoinUnlimited/BitcoinUnlimited
qa/rpc-tests/httpbasics.py
Python
mit
4,832
0.010348
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit # # Test rpc http...
r_to_b64str(authpair), "Connection": "keep-alive"} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null
' in out1) assert(conn.sock!=None) #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) #must also resp...
grycap/vmca
one.py
Python
gpl-3.0
6,637
0.00678
# coding: utf-8 # # Virtual Machine Consolidation Agent (VMCA) # Copyright (C) 2015 - GRyCAP - Universitat Politecnica de Valencia # # 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 versi...
EMPLATES) > 0) and (vm.TEMPLATE.TEMPLATE_ID not in config.config_one.ONLY_TEMPLATES): # logging.debug("locking vm %s because its TEMPLATE is not allowed" % vm.ID) self._locked_vms.append(vm.ID) elif (vm.LCM_STATE in [ cpyutils.onec...
vmdata.state = defragger.VMData.STATE_MIGRATING self._migrating_vms.append(vm.ID) else: logging.debug("vm %s is locked because it is not in running state" % vm.ID) vmdata.state = defragger.VMData.STATE_OTHER ...
UCL-INGI/INGInious
inginious/frontend/task_problems.py
Python
agpl-3.0
9,078
0.003195
# -*- coding: utf-8 -*- # # This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for # more information about the licensing of this file. """ Displyable problems """ import gettext import json from abc import ABCMeta, abstractmethod from random import Random from inginious.common.tasks_problems i...
default=self._default) @classmethod def show_editbox(cls, template_helper, key, language): return template_helper.render("course_admin/subproblems/code.html", key=key, multiline=True) @classmetho
d def show_editbox_templates(cls, template_helper, key, language): return "" class DisplayableCodeSingleLineProblem(CodeSingleLineProblem, DisplayableProblem): """ A displayable single code line problem """ def __init__(self, problemid, content, translations, taskfs): super(DisplayableCod...
fandrefh/AnjoMeu
anjo/campaign/migrations/0005_auto__chg_field_campaign_user.py
Python
gpl-2.0
4,461
0.007622
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Campaign.user' db.alter_column(u'campaign_campaign', '...
('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta...
ailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), ...
mrname/haralyzer-api
migrations/versions/6aab1ac34c3_.py
Python
mit
2,147
0.01537
"""Initial Structure (Creating test and page tables) Revision ID: 6aab1ac34c3 Revises: None Create Date: 2015-07-19 12:58:04.968533 """ # revision identifiers, used by Alembic. revision = '6aab1ac34c3' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generat...
sa.PrimaryKeyConstraint('id') ) op.create_table('page', sa.Column('id', sa.Integer(), nullable=False), sa.Column('test_id', sa.Integer(), nullable=False), sa.Column('page_id', sa.String(length=64), nullable=False), sa.Column('fqdn', sa.String(length=256), nullable=True), sa.Column('time...
load_time', sa.Float(), nullable=True), sa.Column('js_load_time', sa.Float(), nullable=True), sa.Column('css_load_time', sa.Float(), nullable=True), sa.Column('image_load_time', sa.Float(), nullable=True), sa.Column('page_load_time', sa.Float(), nullable=True), sa.Column('page_size', sa.Float(), nul...
Spferical/cure-alzheimers-fund-tracker
code_for_good/urls.py
Python
mit
826
0
"""code_for_good URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Fu
nction views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including a
nother URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^scraper/', include('scraper.urls')), url(r'...
S41nz/TBTAF
tbtaf/test/orchestrator/samples/testOnlyTheRequired.py
Python
apache-2.0
1,271
0.013375
''' <TBTAF> <TestID
>2021</TestID> <Tags>TBTAF,Discoverer,Textbook</Tags> </TBTAF> ''' ''' Created on 06/11/2015 @author: Nander ''' from common.test import TBTestCase from common.result import TBTAFResult from common.trace import TBTAFTrace from common.event import TBTAFEvent from common.enums.verdict_type import TBTAFVerdictType from c...
class DiscovererOnlyTheRequiredTest(TBTestCase): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.testTimeout = 1984 def setup(self): TBTestCase.setup(self) print "Setup performed from DiscovererOnlyTheRequiredTest" self.testT...
asnelzin/together-app-backend
together/settings/base.py
Python
bsd-3-clause
5,584
0.000179
# Django settings for together project. import os BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) PROJECT_ROOT = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) DATABASES = { 'defaul...
ication' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) FIXTURE_DIRS = ( os.path.join(BASE_DIR, 'fixtures'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contri
b.staticfiles', 'django.contrib.admin', 'django.contrib.humanize', 'django.contrib.sitemaps', # External apps # ... 'rest_framework', 'together.apps.api', 'together.apps.rooms', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send a...
glogiotatidis/basket
basket/news/country_codes.py
Python
mpl-2.0
10,229
0
# -*- coding: utf-8 -*- SFDC_COUNTRIES = { 'af': 'Afghanistan', 'ax': 'Aland Islands', 'al': 'Albania', 'dz': 'Algeria', 'as': 'American Samoa', 'ad': 'Andorra', 'ao': 'Angola', 'ai': 'Anguilla', 'aq': 'Antarctica', 'ag': 'Antigua and Barbuda', 'ar': 'Argentina', 'am': 'Armenia', 'aw': 'Aruba...
, 'bvt': 'bv', 'bra': 'br', 'vgb': 'vg', 'iot': 'io', 'brn': 'bn', 'bgr': 'bg', 'bfa': 'bf', 'bdi': 'bi', 'khm': 'kh', 'cmr': 'cm', 'can': 'ca',
'cpv': 'cv', 'cym': 'ky', 'caf': 'cf', 'tcd': 'td', 'chl': 'cl', 'chn': 'cn', 'hkg': 'hk', 'mac': 'mo', 'cxr': 'cx', 'cck': 'cc', 'col': 'co', 'com': 'km', 'cog': 'cg', 'cod': 'cd', 'cok': 'ck', 'cri': 'cr', 'civ': 'ci', 'hrv': 'hr', 'cub': 'c...
JasonJDong/CompressBinary
IncrementalUpdate/IncrementalUpdate/main.py
Python
gpl-2.0
1,595
0.011912
import os from config import config from incremental_upload_handler import IncrementalUploadHandler from Utils.util import FileUtil from file_entity import FileEntity def gen_test_data(): server_file = os.path.join(config.server_folder,'test.txt') client_file = os.path.join(config.client_folder,'test.txt') ...
nt_handler = IncrementalUploadHandler(client_file,adler32_pair) server_handler.server_adler32_pair = a
dler32_pair diffs = client_handler.diff() log = '' for i in range(0,len(diffs)): log += str(diffs[i]) FileUtil.write_file_data(r'D:\test\log.log',log) new_server_file_info = server_handler.gen_data_block(diffs) #for i in range(0,len(new_server_file_info)): # print new_serve...
UltramaticOrange/xkcd_news
news_consts.py
Python
gpl-3.0
2,176
0.003217
# C is for constants ...and that's good enough for me. class C(object): # used in python FEEDS_FILE = 'feeds.yaml' SUBS_FILE = 'substitutions.yaml' SUBS_KWARG = 'transformations' TEMPLATE_CONFIG_FILE = 'template.yaml' # used in template.yaml config file TEMPLATE_FILE = 'templateFile' TE...
STORY_WRAPPER = 'wrapper' # div that includes image, headline, and text
STORY_TITLE = 'title' # div that contains just the headline STORY_IMAGE = 'image' # img tag that does not contain the immense volume of your mom STORY_BODY = 'body' # just the text ..... that does not contain the immense volume of your mom STORY_URL = 'url' # This is probably a step too far, bu...
research-on-research/Text-Mining-Technology-for-Research-Evolution-Analysis
code/002-003-abstracts-to-csv.py
Python
gpl-3.0
482
0.047718
import sys import csv def main(input, output): fin = open(input) fout = open(output, 'w') csvwriter = csv.writer(fout, delimiter=';', quotechar='"', doublequote=True, lineterminator="\n", quoting=csv.QUOTE_ALL) count = 0 #csvwriter.writerow(['class', 'abstract']) for line in fin: count = coun
t + 1 csvwriter.writerow(['', line.strip()]) fin.close() fout.close() print str(count) + " abstracts read!\n" if __name__ == '__main__': main(sys.argv[1],
sys.argv[2])
yasserglez/pytiger2c
packages/pytiger2c/ast/typedeclarationnode.py
Python
mit
1,319
0.00687
# -*- coding: utf-8 -*- """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.declarationnode import DeclarationNode class TypeDeclarationNode(DeclarationNode): """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. Representa las distintas declaracione...
álidos de Tiger. """ def _get_name(self): """ Método para obtener el valor de la propiedad C{name}. """ return self._name def _set_name(self, name): """ Método para cambiar el valor de la propiedad C{name}.
""" self._name = name name = property(_get_name, _set_name) def _get_type(self): """ Método para obtener el valor de la propiedad C{type}. """ return self._type type = property(_get_type) def __init__(self, name): """ I...
chevah/github-hooks-server
chevah/github_hooks_server/tests/test_hooks_server.py
Python
bsd-3-clause
5,992
0
""" Tests for requests dispatcher. Functional test using curl: curl --data '{"param1": "test"}' \ -H "X-Github-Event: issue_comment" \ -H "Content-type: application/json"\ http://localhost:8080/hook/test curl --data 'payload=%7B%22key%22%3A%22value%22%7D' \ -H "X-Github-Event: push" \ -H "Conten...
2345) def tearDown(self): CONFIGURATION['allow_cidr'] = self._allow_cidr expand_allowed_ips() CONFIGURATION['callback'] = self._callback super(Te
stServer, self).tearDown() def test_allow_cidr_change_runtime(self): """ When allow_cidr is changed at runtime, `expand_allowed_ips` must be called to update the cache. """ CONFIGURATION['allow_cidr'] = [ '192.30.252.0/22', '108.171.174.178/32', ...
geoenvo/opendims
opendims/waterlevel/migrations/0005_auto_20160713_1247.py
Python
gpl-3.0
673
0.002972
# -*- coding: utf-8 -*- # Generate
d by Django 1.9.2 on 2016-07-13 05:47 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('waterlevel', '0004_auto_20160531_1218'), ] operations = [ migra
tions.AlterModelOptions( name='watergate', options={'get_latest_by': 'pk', 'ordering': ['-pk'], 'verbose_name_plural': 'Water gates'}, ), migrations.AlterModelOptions( name='waterlevelreport', options={'get_latest_by': 'pk', 'ordering': ['-pk'], 'verbose_n...
nicoguaro/AdvancedMath
examples/heat_iterations.py
Python
mit
3,191
0.00188
""" Illustration of the heat equation Solve the heat equation using finite differences and Forward Euler. Based on: https://commons.wikimedia.org/wiki/File:Heat_eqn.gif """ from __future__ import division, print_function import numpy as np from mayavi import mlab def step_function(N, scale, X, Y, shape="crescent")...
Y - y_eye)**2/0.4 - 1 right_eye = (X - x_eye)**2/0.1 + (Y - y_eye)**2/0.4 - 1 Z[X**2 + Y**2 > 2] = 0 Z[bicorn > 0] = 0 Z[left_eye < 0] = 0 Z[right_eye < 0] = 0 Z = scale * Z return Z def data_gen(num): # Solve the heat equation with zero boundary conditions fo...
nge(ntime_anim): Z[1:N-1, 1:N-1] = Z[1:N-1, 1:N-1] + dt*(Z[2:N, 1:N-1] + Z[0:N-2, 1:N-1] + Z[1:N-1, 0:N-2] + Z[1:N-1, 2:N] - 4*Z[1:N-1, 1:N-1])/dx**2 surf = mlab.surf(X, Y, Z, colormap='autumn', warp_scale=1) # Change the visualization parameter...
polaris-gslb/polaris-core
tests/tcp_listen.py
Python
bsd-3-clause
343
0.017493
#!/usr/bin/env python3 import socket def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 5555)) s.listen(1) while 1: conn, addr = s.accept() #data = conn.recv(1024) conn.send("blabla".encode()) conn.close() if __name__ == ...
()
wummel/patool
tests/__init__.py
Python
gpl-3.0
3,628
0.001929
# -*- coding: utf-8 -*- # Copyright (C) 2010-2015 Bastian Kleineidam # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
ild.")
return func(*args, **kwargs) setattr(newfunc, fnameattr, getattr(func, fnameattr)) return newfunc return check_func
AleksandraWozniak/GetOldTweets-python
got/manager/TweetManager.py
Python
mit
4,626
0.041505
import urllib,urllib2,json,re,datetime,sys,cookielib from .. import models from pyquery import PyQuery class TweetManager: def __init__(self): pass @staticmethod def getTweets(tweetCriteria, receiveBuffer=None, bufferLength=100, proxy=None): refreshCursor = '' results = [] resultsAux = [] cookieJar...
tweets&q=%s&l=pl&src=typd&max_position=%s" #url = "https://twitter.com/i/search/timeline?f=tweets&q=%s&src=typd&max_position=%s" urlGetData = '' if hasattr(tweetCriteria, 'username'): urlGetData += ' from:' + tweetCriteria.username if hasattr(tweetCriteria, 'querySearch'): urlGetData += ' ' + twe...
if hasattr(tweetCriteria, 'since'): urlGetData += ' since:' + tweetCriteria.since if hasattr(tweetCriteria, 'until'): urlGetData += ' until:' + tweetCriteria.until if hasattr(tweetCriteria, 'topTweets'): if tweetCriteria.topTweets: url = "https://twitter.com/i/search/timeline?q=%s&l=pl&src...
open-telemetry/opentelemetry-python
exporter/opentelemetry-exporter-opencensus/setup.py
Python
apache-2.0
921
0
# Copyright The OpenTelemetry 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 agre
ed 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 the License. import os import setuptool
s BASE_DIR = os.path.dirname(__file__) VERSION_FILENAME = os.path.join( BASE_DIR, "src", "opentelemetry", "exporter", "opencensus", "version.py" ) PACKAGE_INFO = {} with open(VERSION_FILENAME, encoding="utf-8") as f: exec(f.read(), PACKAGE_INFO) setuptools.setup(version=PACKAGE_INFO["__version__"])
thomasaarholt/hyperspy
hyperspy/tests/signals/test_image.py
Python
gpl-3.0
1,942
0
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
im.to_signal1D() assert isinstance(s, Signal1D)
assert s.data.shape == (3, 4, 2) if not s._lazy: assert s.data.flags["C_CONTIGUOUS"] @lazifyTestClass class Test4D: def setup_method(self, method): self.s = Signal2D(np.random.random((2, 3, 4, 5))) def test_to_image(self): s = self.s.to_signal1D() assert isi...
erikdejonge/python_for_kids
chapter11/star_function.py
Python
gpl-2.0
341
0.017595
import turtle t = turtle.Pen() def mystar(size, filled): if filled: t.begin_fill() for x in range(1,19): t.forward(size) if x % 2 == 0: t.left(175)
else: t.left(225) if filled: t.end_fill() t.color(0.9, 0.75, 0) mys
tar(120, True) t.color(0,0,0) mystar(120, False)
Kegbot/kegbot-server
pykeg/util/celery.py
Python
gpl-2.0
2,201
0
from __future__ import absolute_import from builtins import object """Celery beat scheduler backed by Redis. The schedule will be saved as a pickled data in the key 'celery:beat:<filename>', where filename is the schedule filename configured in celery Prerequisite: You are using Redis as your broker (BROKER_URL =...
lose(self): self.logger.debug("close") self.sync() self._d = {} self._filename = None class RedisScheduler(PersistentScheduler): """Scheduler that uses a RedisShelve for storage.""" def __init__(self, *args, **kwargs): app = kwargs["app"] self.persistence = Red...
stentScheduler.__init__(self, *args, **kwargs)
googleapis/python-analytics-admin
samples/generated_samples/analyticsadmin_v1alpha_generated_analytics_admin_service_get_user_link_async.py
Python
apache-2.0
1,512
0.001984
# -*- coding: utf-8 -*- # Copyright 2022 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...
License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for GetUserLink # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require
modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-analytics-admin # [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetUserLink_async] from google.analytics import admin_v1alpha async def sample_ge...
mixman/djangodev
django/contrib/contenttypes/models.py
Python
bsd-3-clause
6,625
0.00166
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode, force_unicode class ContentTypeManager(models.Manager): # Cache to avoid re-looking up ContentType objects all over the place. # This cache is shared by all the get_for_* metho...
defaults = {'name': smart_unicode(opts.verbose_name_raw)}, ) self._add_to_cache(self.db, ct) return ct def get_for_models(self, *models): """ Given *models, returns a dictionary mapping {model: con
tent_type}. """ # Final results results = {} # models that aren't already in the cache needed_app_labels = set() needed_models = set() needed_opts = set() for model in models: opts = self._get_opts(model) try: ct = s...
audreyr/opencomparison
package/utils.py
Python
mit
269
0.007435
def uniquer(seq, idfun=None): if idfun is N
one:
def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result
SUSE/azure-sdk-for-python
azure-mgmt-iothub/setup.py
Python
mit
2,792
0.001074
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
ttribute (newer versions don't) try: import azure try: ver = azure.__version__ raise Exception( 'This package is incompatible with azure=={}. '.format(ver) + 'Uninstall it with "pip uninstall azure".'
) except AttributeError: pass except ImportError: pass # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if no...
gerv/slic
test/data/identification/test_ws.py
Python
mpl-2.0
941
0.001063
# -*- coding: utf-8 -*- ############################################################################### # This Source Code Form 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/. #################...
se(self): result = ws.collapse(" ") self.assertEqual(result, "") result = ws.collapse(" foo") self.assertEqual(result, "foo") result = ws.collapse("foo ") self.assertEqual(result, "foo") result = ws.collapse(" foo bar ") self.assertEqual(resul...
result = ws.collapse("foo\t\nbar\r") self.assertEqual(result, "foo bar") if __name__ == '__main__': unittest.main()
GISPPU/GrenadaLandInformation
geonode/layers/migrations/0010_remove_unneeded_objects.py
Python
gpl-3.0
20,864
0.008004
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): # Deleting field id db.delete_column('layers_layer', 'id') # set new primary key for layers_layer db.cr...
.TextField', [], {'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_type': ('django.db.models.fields.CharField', [], {'default'
: "'publication'", 'max_length': '255'}), 'distribution_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank':
jabeerahmed/testrepo
term1/Lessons/TensorFlow/Digits/sandbox.py
Python
gpl-2.0
2,343
0.00128
# Solution is available in the other "sandbox_solution.py" tab import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from quiz import get_weights, get_biases, linear def mnist_features_labels(n_labels): """ Gets the first <n> labels from the MNIST dataset :param n_labels: Numb...
ceholder(tf.float32) # Weights and Biases w = get_weights(n_features, n_labels) b = get_biases(n_labels) # Linear Function xW + b logits = linear(features, w, b) # Training data train_features, train_labels = mnist_features_labels(n_labels) with tf.Session() as se
ssion: # TODO: Initialize session variables # Softmax prediction = tf.nn.softmax(logits) # Cross entropy # This quantifies how far off the predictions were. # You'll learn more about this in future lessons. cross_entropy = -tf.reduce_sum(labels * tf.log(prediction), reduction_indices=1...
dianamor8/helpdeskunl
helpdeskunl/apps/home/urls.py
Python
gpl-2.0
550
0.027273
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from . import views
from . import rest from helpdeskunl.apps.home.views import * from helpdeskunl.apps.home.rest import * urlpatterns = patterns('', url(r'^$', views.index_view, name='view_home'), url(r'^(?P<username>\w+)$', views.panel_view,name = 'view_panel'), url(r'^notificaciones/list$', NotificacionesList.as_view(), name='not...
n_visto', name='notificacion_ver'), )
claudiodriussi/DynaQ
dynaq/db.py
Python
lgpl-3.0
18,697
0.001391
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # db.py # # Copyright (c) 2014 # Author: Claudio Driussi <claudio.driussi@gmail.com> # import sqlalchemy as sa import copy # sqlalchemy recognized types base_types = { 'integer': sa.Integer, 'autoinc': sa.Integer, 'bool': sa.Boolean, 'char': sa.CHAR, ...
stors. """ def __init__(self): """init variables""" PropContainer.__init__(self) self.name = '' self.types = {} self.tables =
{} def load_yaml(self, data): """ Build Database structure from a dict loaded from yaml files data is a dict loaded from a yaml files following the defined rules. The utils.YamlLoader class is used to load files with includes and precedences rules. Example: #>>> import dyn...
runcom/flocker
flocker/acceptance/test_postgres.py
Python
apache-2.0
8,587
0
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for running and managing PostgreSQL with Flocker. """ from unittest import skipUnless from uuid import uuid4 from pyrsistent import pmap, freeze, thaw from twisted.python.filepath import FilePath from twisted.trial.unittest import TestCase from ...
db_node_1_cursor.execute("SELECT * FROM test
table;") db_connection_node_1.commit() fetched_data = db_node_1_cursor.fetchone()[0] db_node_1_cursor.close() db_connection_node_1.close() self.assertEqual(fetched_data, 3) connecting_to_database.addCallback(add_data_node_1) def get_postgres_...
adngdb/socorro
socorro/unittest/external/rabbitmq/test_connection_context.py
Python
mpl-2.0
8,203
0.001097
# This Source Code Form 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/. from nose.tools import eq_, ok_, assert_raises from mock import ( Mock, call, patch ) from threading import ...
conn is conn_context_functor.pool['dwight'] ) # get the same connection again to make sure it really is the same conn = conn_context_functor.connection() ok_( conn is conn_context_functor.pool[currentThread().get
Name()] ) def test_close_connection(self): config = self._setup_config() pika_string = 'socorro.external.rabbitmq.connection_context.pika' with patch(pika_string): conn_context_functor = ConnectionContextPooled(config) conn = conn_context_functor.connecti...
LoHChina/nova
nova/tests/unit/compute/test_compute_api.py
Python
apache-2.0
128,405
0.000763
# # 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 # ...
project_id=mox.IgnoreArg(), user_id=mox.IgnoreArg(), ram=mox.IsA(int)).AndRaise(
quota_exception) self.mox.ReplayAll() for min_count, message in [(20, '20-40'), (40, '40')]: try: self.compute_api.create(self.context, instance_type, "image_href", min_count=min_count, max_coun...
jemdwood/cs234_proj
train-action-prediction.py
Python
mit
7,548
0.003577
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: train-action-prediction.py # Author: Timon Ruban import numpy as np import os import random import argparse import cv2 import tensorflow as tf import six from six.moves import queue from tensorpack import * from tensorpack.utils.serialize import * from tensorpack...
RecordsDataFlow('train') rec_test = RecordsDataFlow('test') else: rec_train = KurinDataFlow('train', record_folder=BASE_PATH, gym_game_name=env) rec_test = KurinDataFlow('test', record_folder=BASE_PATH, gym_game_name=env) return BatchData(rec_train, BATC...
rain_log', 'action_prediction-{}'.format(env)) logger.set_logger_dir(dirname) num_actions = NUM_ACTIONS[env] M = Model(num_actions) dataset_train, dataset_test = get_data(env) # How many iterations you want in each epoch. # This is the default value, don't actually need to set it in the config ...
dracidoupe/graveyard
dragon/forms/news.py
Python
mit
481
0.002079
from django import forms from django.core.validators import MinLengthValidator
from ddcz.notifications import Audience class News(forms.Form): text = forms.CharField( label="", widget=forms.Textarea(
attrs={"class": "comment__textarea", "cols": 80, "rows": 30}, ), validators=[MinLengthValidator(80)], ) audience = forms.ChoiceField( choices=((i.name, i.value) for i in Audience), label="Komu poslat e-mail" )
ruijie/quantum
quantum/tests/unit/ryu/test_ryu_db.py
Python
apache-2.0
2,027
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # 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...
# 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 os import unittest2 from quantum.db import api as db from quantum.db import models_v2 from quantum.openstack.common import cfg from quantum.plugins.ryu.common import config from quantum.plugins.ryu.db import api_v2 as db_api_v2 from quantum.plugins.ryu.db im...
PubTracker/PubTracker-Backend
PubTracker/PubTracker/urls.py
Python
gpl-2.0
315
0.012698
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = pattern
s('', # Examples: # url(r'^$', 'PubTracker.views.home', name='home'), # url(r'^blog/', include('blog.urls
')), url(r'^$', include('pub.urls')), url(r'^admin/', include(admin.site.urls)), )
chaosmaker/pyload
module/plugins/hoster/Ftp.py
Python
gpl-3.0
3,388
0.003247
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
rl) else: #Naive ftp directory listing if re.search(r'^25\d.*?"', self.req.http.header, re.M): pyfile.url = pyfile.url.rstrip('/') pkgname = "/".join((pyfile.package().name, urlparse(pyfile.url).path.rpartition('/')[2])) pyfile.ur...
RLOPT_DIRLISTONLY response = self.load(pyfile.url, decode=False) links = [pyfile.url + quote(x) for x in response.splitlines()] self.logDebug("LINKS", links) self.core.api.addPackage(pkgname, links, 1) #self.core.files.addLinks(links, pyfil...
Dancer3809/PgDumpLoader
PgDumpLoader/parser/AlterTableParser.py
Python
mit
6,462
0.00294
from parser.Parser import Parser, ParserUtils from schema.PgConstraint import PgConstraint class AlterTableParser(object): @staticmethod def parse(database, statement): parser = Parser(statement) parser.expect("ALTER", "TABLE") parser.expectOptional("ONLY") tableName = parser...
.expectOptional("OWNER", "TO"): parser.parseIdentifier() else: parser.throwUnsupportedCommand() @staticmeth
od def parseSequence(parser, sequence, sequenceName, database): while not parser.expectOptional(";"): if parser.expectOptional("OWNER", "TO"): parser.parseIdentifier() else: parser.throwUnsupportedCommand()
YutingZhang/lmdis-rep
exp-ae-celeba-mafl-30.py
Python
apache-2.0
2,477
0.005248
import tensorflow as tf import os import sys from copy import copy from model.pipeline import Pipeline from tensorflow.python import debug as tf_debug if __name__ == "__main__": num_keypoints = 30 patch_feature_dim = 8 decoding_levels = 5 kp_transform_loss = 1e4 base_recon_weight = 0.1 reco...
ion_loss_weight": keypoint_separation_loss_weight, "keypoint_separation_bandwidth": keypoint_separation_bandwidth, "keypoint_transform_loss_weight": kp_transform_loss, "keypoint_decoding_heatmap_levels": decoding_levels, "keypoint_decoding_heatmap_level_base": 0.5**(1/2), "image_...
_options"]) # ------------------------------------- model_dir = os.path.join("results/celeba_30") vp = Pipeline(None, opt, model_dir=model_dir) print(vp.opt) with vp.graph.as_default(): sess = vp.create_session() vp.run_full_train(sess, restore=True) vp.run_full_test(sess) ...
trafferty/utils
python/plot_timing.py
Python
gpl-2.0
1,690
0.010651
import matplotlib.pyplot as plt from datetime import datetime, timedelta import random # assuming your timing data in a csv file you could import csv and read the data def GetData(samplelen=20): """ As I don't wish to spend the time generating a csv file I will dummy!""" data = {'t':[], 's1':[], 's2':[], 's3':...
a['t'].append(t_current) if step % 9 == 0:
for s in ['s1', 's2']: vals[s] = random.choice([0, 1]) vals['s3'] = random.choice([0, 1]) for s in ['s1', 's2', 's3']: data[s].append(vals[s]) t_current = t_current + t_increment return data def PlotData(data, timename='t'): """ Expects a dictionary of n...
cx421774557/pengyouquan
pengyouquan/app/urls.py
Python
gpl-2.0
181
0.022099
from django.conf.urls import patterns, url from app import views urlp
atterns = patterns(' ', url(r'^$', views.index, name='index'),
url(r'^about/$', views.About, name='About'), )
marcosfede/algorithms
matrix/bomb_enemy.py
Python
gpl-3.0
2,524
0.000792
""" Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb. The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. Note that you ca...
we are next to a wall. if i == 0 or grid[i - 1][j] == 'W': col_e[j] = col_kills(grid, i, j) # makes sure the cell contains a 0 if grid[i][j] == '0': # updates the variable max_killed = max(max_killed, row_e + col_e[j]) return max_...
_kills(grid, i, j): num = 0 len_row = len(grid[0]) while j < len_row and grid[i][j] != 'W': if grid[i][j] == 'E': num += 1 j += 1 return num # calculate killed enemies for column j from row i def col_kills(grid, i, j): num = 0 len_col = len(grid) while i < len_...
bweaver2/bzrFlag
bzagents/dumb_agent.py
Python
gpl-3.0
5,712
0.003326
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is...
s all command and control logic for a teams tanks.""" new_angles = [] running_time = [] shooting_time = 2 ENEMY_TANK_MIN_DISTANCE = 1 ENEMY_TANK_MAX_DISTANCE = 5 OBSTACLE_MAX_DISTANCE = 10 OBSTACLE_MIN_DISTANCE = 1 BULLET_MAX_DISTANCE = 10 BULLET_MIN_DISTANCE = 1 FLAG_MIN_DI...
random.seed(); mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.new_angles = [] self.running_time = [] for tank in mytanks: self.new_angles.append(self.normalize_angle(tank.angle - math.pi/3)) self.running_time.append(random.uniform(3,8)) ...
QwertyManiac/seal-cdh4
seal/lib/aligner/sam_mapping.py
Python
gpl-3.0
1,761
0.0318
import re import array from seal.lib.aligner.mapping import Mapping class SAMMapping(Mapping): """ A mapping implementation for storing SAM data. A SAMMapping object is constructed from a list of SAM fields -- see http://samtools.sourceforge.net """ CIGAR_PATTERN = re.compile(r"(\d+)([MIDNSHP]
)") REFID_PATTERN = re.compile(r"\d+$") def __init__(self, sam_fields): """ Provide a sam record as a string (it will be split on tabs to get the fields) or directly a list of sam fields. """ super(SAMMapping, self).__init__() if type(sam_fields) == str: sam_fields = sam_fields.split("\t") self.__n...
if ref_id_match is not None: self.ref_id = int(ref_id_match.group()) self.tid = sam_fields[2] self.pos = int(sam_fields[3]) self.qual = int(sam_fields[4]) self.__cigar = [(int(n), c) for (n, c) in self.CIGAR_PATTERN.findall(sam_fields[5])] if sam_fields[6] == '*': # is this BWA-specific? self.mtid = N...
psiq/gdsfactory
gdsdiff/gds_diff_git.py
Python
mit
605
0
""" A GDS diff tool which can be called by git when doin
g `git diff ...` The function needs to take the arguments as described in https://git-scm.com/docs/git/2.18.0#git-codeGITEXTERNALDIFFcode """ import sys from gdsdiff import gdsdiff import pp def gds_diff_git( path, curr_file, old_file, old_hex, old_mode, new_file, new_hex, new_mode ): """ We do not us...
ts """ print(old_hex, "->", new_hex) diff = gdsdiff.gdsdiff(old_file, new_file) pp.show(diff) if __name__ == "__main__": # for f in sys.argv: # print (f) gds_diff_git(*sys.argv)
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/conf/locale/ta/formats.py
Python
mit
682
0
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use
the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F, Y' TIME_FORMAT = 'g:i A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS stri...
s.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
piraz/diasporapy
podship/test/services/account.py
Python
apache-2.0
1,299
0
#!/usr/bin/env python # # Copyright 2015 Flavio Garcia # # 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 ...
with_statement) from podship.services.account import AccountService import unittest class AccountServiceTestCase(unittest.TestCase): """ Case that covers the account service. """ def setUp(self): self.service = AccountService(self) def test_is_account_service(self): """ Dummy test t...
to get travis build working # properly. self.assertEqual(self.service.__class__, AccountService)
gtrll/orgpmp2
setup.py
Python
gpl-3.0
220
0.004545
#!/
usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['orgpmp2'], package_dir={'': 'pythonsrc'}
, ) setup(**d)
pelikanchik/edx-platform
lms/djangoapps/courseware/tests/test_about.py
Python
agpl-3.0
1,252
0
""" Test the about xblock """ from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from...
play_name="overview" ) def test_logged_in(self): self.setup_user() url = reverse('about_course', args=[self.course.id]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) def test_anonymous_user(self)...
, args=[self.course.id]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content)
kmtu/xdrfile-d
src/python/xdrfile.py
Python
bsd-2-clause
5,356
0.029313
# -*- mode: python; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- # # $Id$ # # Copyright (c) Erik Lindahl, David van der Spoel 2003-2007. # Coordinate compression (c) by Frans van Hoesel. # Python wrapper (c) by R
oland Schulz # # IN contrast to the rest of Gromacs, XDRFI
LE is distributed under the # BSD license, so you can use it any way you wish, including closed source: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including w...
lucienfostier/gaffer
python/GafferSceneUI/ScaleToolUI.py
Python
bsd-3-clause
1,986
0.003525
########################################################################## # # Copyright (c) 2016, John Haddon. 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 so...
NESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (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 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ####################################################...
pescobar/easybuild-framework
test/framework/lib.py
Python
gpl-2.0
5,005
0.003996
# # # Copyright 2018-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (...
d framework as a library."""
error_pattern = "Undefined build option: .*" error_pattern += " Make sure you have set up the EasyBuild configuration using set_up_configuration\(\)" self.assertErrorRegex(EasyBuildError, error_pattern, modules_tool) self.configure() test_mods_path = os.path.join(os.path.dirname(os.pa...
rve/pracmcm
ca/varying_v_max.py
Python
mit
10,184
0.008936
import random import sys lane_num = 2 lane = [[], []] max_car_num = 10000 road_len = 1000 h = 6 p_b = 0.94 p_0 = 0.5 p_d = 0.1 v_max = [6, int(sys.argv[1])] gap = 7 p_car = 1 p_crash = 0 time_period = 200 class Car: car_cnt = 0 def __init__(self, v = 1, lane = 1): self.size = 1 if random...
while kk < car_num and car[kk].lane != car[j].lane: kk += 1 if kk >= car_num: kk = 0 while kk < car_num and car[kk].lane != car[j].lane: kk += 1 #0 Determine p t_s = min(car[j].v, h) d = mmod(car[...
d = 2 ** 31 if int(car[j].v) > 0 and d != 2 ** 31: t_h = d / car[j].v else: t_h = t_s p = rand(car[j].v, car[k].b, t_h, t_s) b_now = car[j].b car[j].b = 0 if j > 0: v_succ[car[j - 1].lane] = v_n...
tompecina/legal
tests/test_hjp.py
Python
gpl-3.0
38,939
0.001261
# -*- coding: utf-8 -*- # # tests/test_hjp.py # # Copyright (C) 2011-18 Tomáš Pecina <tomas@pecina.cz> # # This file is part of legal.pecina.cz, a web-based toolbox for lawyers. # # This application is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # publi...
amount': '2000'}) self.assertTrue(form.is_valid()) def test_main_form(self): form = forms.MainForm( {'rounding': '0', 'model': 'none'}) self.assertTrue(form.is_valid()) form = forms.MainForm( {'rounding': '0', 'model': 'none', ...
'i\rn'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['note'], 'nn') self.assertEqual(form.cleaned_data['internal_note'], 'in') form = forms.MainForm( {'rounding': '0', 'model': 'fixed'}) self.assertFalse(form.is_valid()) ...
blaa/WaveSync
libwavesync/packetizer.py
Python
mit
7,795
0.001668
""" Packetizer class. """ import asyncio import socket import struct import zlib import ipaddress from datetime import datetime from time import time from libwavesync import time_machine class Packetizer: """Read chunks from queue, add timestamp marks and send over multicast.""" HEADER_COMPRESSED_AUDIO = b...
diff) await asyncio.sleep(0.4)
elif diff < -5: print("Input stream is lagging", diff) relative = stream_time future_ts, mark = time_machine.get_timemark(relative, self.audio_config.latency_s) if self.chunk_queue is not None: ...
shubhamgupta123/erpnext
erpnext/stock/doctype/stock_entry/test_stock_entry.py
Python
gpl-3.0
28,700
0.024878
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, unittest import frappe.defaults from frappe.utils import flt, nowdate, nowtime from erpnext.stock.doctype.serial_no.serial_no import * fr...
est_auto_material_request("_Test Item") self._test_auto_material_request("_Test Item", material_request_type="Transfer") def test_auto_material_request_for_variant(self): fields = [{'field_name': 'reorder_levels'}] set_item_variant_settings(fields) make_item_variant()
template = frappe.get_doc("Item", "_Test Variant Item") if not template.reorder_levels: template.append('reorder_levels', { "material_request_type": "Purchase", "warehouse": "_Test Warehouse - _TC", "warehouse_reorder_level": 20, "warehouse_reorder_qty": 20 }) template.save() self._test_a...
printedheart/h2o-3
h2o-docs/src/booklets/v2_2015/source/deeplearning/deeplearning_examplerun.py
Python
apache-2.0
719
0.013908
# Specify the response and predictor columns y = "C785" x = train.names[0:784] # We encode the response column as categorical for multinomial classification train[y] = train[y].asfactor() test[y] = test[y].asfactor() # Train a Deep Learning model and validate on a test set model = h2o.deeplearning(x=x, ...
training_frame=train,
validation_frame=test, distribution="multinomial", activation="RectifierWithDropout", hidden=[200,200,200], input_dropout_ratio=0.2, l1=1e-5, epochs=10)
dulrich15/spot
apps/roster/migrations/0002_auto_20151207_0017.py
Python
mit
1,095
0.000913
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0011_auto_20151207_0017'), ...
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('classroom', models.ForeignKey(to='core.Classroom')), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['use...
migrations.AlterField( model_name='assignmentgrade', name='student', field=models.ForeignKey(to='roster.Student'), preserve_default=True, ), ]
imichaelmiers/libforwardsec
sim/sim.py
Python
bsd-2-clause
11,791
0.046561
from subprocess import PIPE, Popen from sys import argv from operator import itemgetter import math, itertools, time from random import expovariate from numpy import array,save,vstack,random,arange from collections import namedtuple import click mili_p_s = 1000 s_p_m = 60 m_p_h = 60 h_p_d = 24 d_p_y = 365 milipy =...
keys={'0':0,'1':0} ctr=0 prev =0 intetvalctr = 0 msg_ctr = 0 DecTime = 0 Dertime = 0 PunTime = 0 MaxDer = 0 MaxDec = 0 with click.progressbar(intervals, label='%d msgs a second for %d seconds with %d size intervals'%(avg,timeduration,interval_length) ) as bar: ...
h,depth) Dertime += d intetvalctr+=1 msg_ctr+=1 dd = simDec(keys[path]) PunTime += simPunc(keys,path) MaxDer = max(MaxDer,d) MaxDec = max(MaxDec,dd) DecTime +=dd msg_ctr+=1 ms = 1000# max(1,interval) # int_length_in_ms #interval_length * numintervals return [window/ms,interval_length,...
jesseengel/magenta
magenta/music/chords_lib_test.py
Python
apache-2.0
10,501
0.001905
# Copyright 2019 The Magenta 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 ...
as tf NO_CHORD = constants.NO_CHORD class ChordsLibTest(tf.test.TestCase): def setUp(self): self.steps_per_quarter = 1 self.note_sequence = common_testing_lib.parse_test_proto( music_pb2.NoteSequence, """ time_signatures: { numerator: 4 denominator: 4 } ...
ression with basic triads. events = ['Cm', 'F', 'Bb', 'Eb'] chords = chords_lib.ChordProgression(events) chords.transpose(transpose_amount=7) expected = ['Gm', 'C', 'F', 'Bb'] self.assertEqual(expected, list(chords)) # Transpose ChordProgression with more complex chords. events = ['Esus2', ...
lilsweetcaligula/Online-Judges
hackerrank/algorithms/strings/easy/palindrome_index/py/solution.py
Python
mit
414
0.009662
def solution(s): i = 0 j = len(s) - 1 while i
< j:
if s[i] == s[j]: i += 1 j -= 1 else: t = s[i + 1:j + 1] if t == t[::-1]: return i else: return j return -1 testCount = int(input()) for testId in range(testCount): s = input().strip() i = soluti...
maxcutler/Courant-News
courant/core/discussions/admin.py
Python
bsd-3-clause
165
0
from django.contrib im
port admin from courant.core.discussions.models import * admin.site.register(CommentOptions) admin.site.registe
r(DefaultCommentOption)
leahrnh/ticktock_text_api
word2vec/user_input_word_all.py
Python
gpl-2.0
3,290
0.02766
import logging, gensim, pickle, re from gensim import corpora,models from nltk.corpus import stopwords import nltk from nltk.stem.lancaster import LancasterStemmer logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim import corpora,models, similarities pronounlist = ['...
_stemmed.append(text_i) if text_i in pronounlist: n_pronoun_i = n_pronoun_i + 1 else: if text not in stoplist: texts_stemmed.append(text) if text in pronounlist: ...
text not in stoplist: texts_stemmed.append(text) if text in pronounlist: n_pronoun_i = n_pronoun_i +1 n_pronoun.append(n_pronoun_i) print "this is one document" texts_all.append(texts_stemmed) print "pronoun percentage" print ...
hryamzik/ansible
lib/ansible/modules/packaging/os/pkgutil.py
Python
gpl-3.0
6,757
0.00148
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Alexander Winkler <mail () winkler-alexander.de> # based on svr4pkg by # Boyd Adamson <boyd () boydadamson.com> (2012) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division,...
= {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION =
''' --- module: pkgutil short_description: Manage CSW-Packages on Solaris description: - Manages CSW packages (SVR4 format) on Solaris 10 and 11. - These were the native packages on Solaris <= 10 and are available as a legacy feature in Solaris 11. - Pkgutil is an advanced packaging system, which res...
Azure/azure-sdk-for-python
sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2022_01_01_preview/operations/_certificates_operations.py
Python
mit
25,002
0.0046
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ers, **kwargs ) def build_list_request( subscription_id: str, resource_group_name: str, service_name: str, **kwargs: Any ) -> HttpRequest: api_version = "2022-01-01-preview" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscr...
ptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "serviceName": _SERIALIZER.url("service_name", service_name, 'str'), } url = _format_url_section(url, **path_format_arguments) # Co...
ceb8/astroquery
astroquery/casda/tests/test_casda.py
Python
bsd-3-clause
10,415
0.00192
# -*- coding: utf-8 -* # Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import requests import os from astropy.coordinates import SkyCoord import astropy.units as u from astropy.table import Table, Column from astropy.io.votable import parse from astroquery import log from astroquery.c...
rl).endswith('/phase') and method == 'POST': key = "RUN_JOB" elif str(url).endswith('1
11-000-111-000') and method == 'GET': key = "RUN_JOB" if self.first_job_pass else "COMPLETED_JOB" self.first_job_pass = False else: raise ValueError("Unexpected SODA async {} call to url {}".format(method, url)) elif 'datalink' in str(url): if 'cube-244' in str(ur...
ooici/pyon
pyon/util/capture_plugin.py
Python
bsd-2-clause
1,881
0.003721
#!/usr/bin/env python """ Hotfix for issue with BaseExceptions in nosetests's capture plugin. Sometimes in our testing, a gevent Timeout will cause nose to come crashing down with an error while it's trying to format the stdout/stderr capturing which is enabled by default. Subsequent tests in a test run will all fail...
(pyon.capture cannot format this output: %s" % str(ex)) except UnicodeError as ex: return super(PyccCapture, self).addCaptureToErr("cannot format error: %s" % str(ex), "cannot format this outpu
t, giving up")
jtorrents/networkx
networkx/release.py
Python
bsd-3-clause
8,792
0.003185
"""Release data for NetworkX. When NetworkX is imported a number of steps are followed to determine the version information. 1) If the release is not a development release (dev=False), then version information is read from version.py, a file containing statically defined version information. This file...
cs_info } fh.write(text % subs) fh.close() if vcs_info[0] == 'mercurial': # Then, we want to update version.py. writefile() else: if os.path.isfile(versionfile): # This is *good*, and the most likely place users will be when # running setu...
# Grab the version so that setup can use it. sys.path.insert(0, basedir) from version import version del sys.path[0] else: # This is *bad*. It means the user might have a tarball that # does not include version.py. Let this error raise so we can ...
Hammerstad/blog
src/settings/__init__.py
Python
mit
300
0.003333
from settings.base import *
try: from settings.local import * except ImportError: print """ Could not import local settings, if you want to set up local settings for dev run this: $ make dev or $ make prod
""" raise ImportError
xeroc/python-bitshares
bitshares/aio/witness.py
Python
mit
1,031
0
# -*- coding: utf-8 -*- from .account import Account from .instance import BlockchainInstance from graphenecommon.aio.witness import ( Witness as GrapheneWitness, Witnesses as GrapheneWitnesses, ) @BlockchainInstance.inject class Witness(GrapheneWitness): """ Read data about a witness in the chain. ...
, 2] @BlockchainInstance.inject class Witnesses(GrapheneWitnesses): """ Obtain a list of **active** witnesses and the current schedule. :param bool only_active: (False) Only retu
rn witnesses that are actively producing blocks :param bitshares blockchain_instance: BitShares() instance to use when accesing a RPC """ def define_classes(self): self.account_class = Account self.witness_class = Witness
minlexx/pyevemon
esi_client/models/get_killmails_killmail_id_killmail_hash_internal_server_error.py
Python
gpl-3.0
3,191
0.002194
# coding: utf-8 """ EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class GetKillmailsKillmailIdKillmailHashInternalServerError(obje...
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is
attribute name and the value is json key in definition. """ self.swagger_types = { 'error': 'str' } self.attribute_map = { 'error': 'error' } self._error = error @property def error(self): """ ...
SchoolIdolTomodachi/frgl
web/forms.py
Python
apache-2.0
10,316
0.004556
from django import forms from django.contrib.auth.models import User, Group from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields import BLANK_CHOICE_DASH from web import models, raw from django.utils.translation import ugettext_lazy as _, string_concat class _UserCheckEmailForm(forms.Mode...
your username and not your full name. Your username appears in the URL of your Facebook profile.')) def __init__(se
lf, *args, **kwargs): self.request = kwargs.pop('request', None) super(_AccountForm, self).__init__(*args, **kwargs) self.fields['accept_friend_requests'].widget = forms.CheckboxInput() self.fields['accept_friend_requests'].initial = True if self.request is not None: ...
pombredanne/bandit
examples/urlopen.py
Python
apache-2.0
1,879
0.000532
''' Example dangerous usage of urllib[2] opener functions The urllib and urllib2 opener functions and object can open http, ftp, and file urls. Often, the ability to open file urls is overlooked leading to code that can unexpectedly open files on the local server. This could be used by an attacker to leak information ...
etrieve('file:///bin/ls', '/bin/ls2') opener = urllib.URLopener() opener.open('file:///bin/ls') opene
r.retrieve('file:///bin/ls') opener = urllib.FancyURLopener() opener.open('file:///bin/ls') opener.retrieve('file:///bin/ls') # urllib2 handler = urllib2.HTTPBasicAuthHandler() handler.add_password(realm='test', uri='http://mysite.com', user='bo...
UpYou/relay
my_gnuradio/gr/hier_block2.py
Python
gpl-3.0
4,316
0.010426
# # Copyright 2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later versi...
isconnect two endpoints in the flowgraph. To disconnect the hierarchical block external inputs or outputs to internal block inputs or outputs, use 'self' in the connect call. If more than two arguments are provided, they are disconnected successively. """ if len (point...
rror, ("disconnect requires at least two endpoints; %d provided." % (len (points),)) else: if len (points) == 1: self._hb.disconnect(points[0].basic_block()) else: for i in range (1, len (points)): self._disconnect(points[i-1], points[i...
shh-dlce/pulotu
website/apps/core/migrations/0031_auto__add_field_glossary_slug.py
Python
apache-2.0
9,362
0.008332
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigrat
ion): def forwards(self, orm): # Adding field 'Glossary.slug' db.add_column(
u'core_glossary', 'slug', self.gf('django.db.models.fields.SlugField')(max_length=1000, null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Glossary.slug' db.delete_column(u'core_glossary', 'slug') models = { ...
samlaudev/LeetCode
Python/Search for a Range/Solution.py
Python
mit
1,176
0.003401
# Problem: Search for a Range # # Given a sorted array of integers, find the starting and ending position of a given target value. # # Your algorithm's runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # # For example, # # Given [5, 7, 7, 8, 8, 10] and ta...
start - 1 >= 0
and nums[start - 1] == nums[mid]: start -= 1 while end + 1 <= (len(nums) - 1) and nums[end + 1] == nums[mid]: end += 1 return [start, end] return [-1, -1]
staranjeet/fjord
smoketests/pages/regions/footer.py
Python
bsd-3-clause
1,847
0.005956
#!/usr/bin/env python # This Source Code Form 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/. from selenium.webdriver.common.by import By from pages.base import Page class Footer(Page): ...
rn self.selenium.find_element(*self._unless_otherwise_
noted_link_locator).text @property def creative_commons(self): return self.selenium.find_element(*self._creative_commons_link_locator).text @property def about_input(self): return self.selenium.find_element(*self._about_input_link_locator).text
denisrmp/hacker-rank
hacker-rank/warmup/diagonal_difference.py
Python
mit
280
0.010714
# https://www.hackerrank.com/challenges/diagonal-difference n = int(input().strip()) prim
ary = 0 secondary = 0 for a_i in range(n): a_temp = lis
t(map(int, input().strip().split(' '))) primary += a_temp[a_i] secondary += a_temp[- a_i - 1] print(abs(primary - secondary))
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/utils/union_find.py
Python
gpl-3.0
3,285
0.000304
""" Union-find data structure. """ from networkx.utils import groups class UnionFind: """Union-find data structure. Each unionFind instance X maintains a family of disjoint sets of hashable objects, supporting the following two methods: - X[item] returns a name for the set containing the given item...
"""Find and return the name of the set containing the object.""" # check for previously unknown object
if object not in self.parents: self.parents[object] = object self.weights[object] = 1 return object # find path of objects leading to the root path = [object] root = self.parents[object] while root != path[-1]: path.append(root) ...
tiwillia/openshift-tools
openshift/installer/vendored/openshift-ansible-3.5.5/roles/lib_utils/src/test/unit/yedit_test.py
Python
apache-2.0
10,224
0
#!/usr/bin/env python2 ''' Unit
tests for yedit ''' # To run # python -m unittest yedit_test # # ............................. # ---------------------------------------------------------------------- # Ran 29 tests in 0.133s # OK import os import sys import unittest # Removing invalid variable names for tests so that I can # keep them brief # pylin...
ins # pylint: disable=import-error # place yedit in our path yedit_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 sys.path.insert(0, yedit_path) from yedit import Yedit # noqa: E402 # pylint: disable=too-many-public-methods # Silly pylint, moar tests! class Yedit...
litex-hub/litex-boards
litex_boards/platforms/digilent_nexys4ddr.py
Python
bsd-2-clause
7,915
0.003032
# # This file is part of LiteX-Boards. # # Copyright (c) 2018-2019 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer from litex.build.openocd import OpenOCD # IOs -------------...
Misc("SLEW=FAST"), IOStandard("LVCMOS33"), ), ("sdcard", 0, Subsignal("rst", Pins("E2"), Misc("PULLUP True")), Subsignal("data", Pins("C2 E1 F1 D2"), Misc("PULLUP True")), Subsignal("cmd", Pins("C1"), Misc("P
ULLUP True")), Subsignal("clk", Pins("B1")), Subsignal("cd", Pins("A1")), Misc("SLEW=FAST"), IOStandard("LVCMOS33"), ), # DDR2 SDRAM ("ddram", 0, Subsignal("a", Pins( "M4 P4 M6 T1 L3 P5 M2 N1", "L4 N5 R2 K5 N6"), IOStandard("SST...
grnet/ganetimgr
notifications/urls.py
Python
gpl-3.0
1,080
0.001852
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
not, see <http://www.gnu.org/licenses/>. # from django.conf.urls import url from notifications import views urlpatterns = [ url(r'^usergrps/$', views.get_user_group_list, name="usergroups"), url(r'^(?P<instance>[^/]+
)/$', views.notify, name="notify"), url(r'^archive/(?P<notification>\w+)/$', views.archive, name="notification-details"), url(r'^$', views.notify, name="notify"), ]
ospalh/libanki3
libanki3/exporting.py
Python
agpl-3.0
9,791
0
# -*- coding: utf-8 -*- # Copyright: Damien Elmes <anki@ichi2.net> # Copyright © 2014 Roland Sieker <ospalh@gmail.com> # # License: GNU AGPL, version 3 or later; # http://www.gnu.org/licenses/agpl.html import os import re import shutil import zipfile from . import Collection from .hooks import runHook from .lang impo...
lf.did, children=True) # copy cards, noting used nids nids = {} data = [] for row in self.src.db.execute( "select * from cards
where id in " + ids2str(cids)): nids[row[1]] = True data.append(row) self.dst.db.executemany( "insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data) # notes strnids = ids2str(list(nids.keys())) notedata = [] for ro...
pcournut/deep-learning-for-combinatorial-optimization
MD/nnet.py
Python
mit
12,765
0.015903
import tensorflow as tf from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper from tqdm import tqdm from decoder import pointer_decoder import dataset import matplotlib.pyplot as plt # TODO """ Michel: _____________________________________________________________________ ...
d_c]), name="critic_W_embed") with tf.variable_scope("Critic"): if self.step>0: tf.get_variable_scope().reuse_variables() embeded_input_c = tf.nn.conv1d(self.input_description, W_embed_c, 1, "
VALID", name="Critic_EncoderInput") # ENCODER LSTM cell cell_c = LSTMCell(self.num_neurons_c,initializer=self.initializer) # cell = DropoutWrapper(cell, output_keep_prob=dropout) or MultiRNNCell([cell] * num_layers) # RNN-ENCODER returns the output activations [Batch size, S...
Luthaf/Chemharp
tests/lints/check-public-headers.py
Python
mpl-2.0
3,005
0
#!/usr/bin/env python # -*- coding: utf8 -*-
""" This script check that only whitelisted headers are included (transitivly) by including chemfiles.h or chemfiles.hpp. """ from __future__ import print_function import os import sys import re import codecs ROOT = os.path.jo
in(os.path.dirname(__file__), "..", "..") GENERATED_HEADERS = ["chemfiles/config.h", "chemfiles/exports.h"] ERRORS = 0 WHITELIST = [ # standard C99 headers "stdbool.h", "stdint.h", # standard C++11 headers "iterator", "functional", "cstdint", "array", "utility", "cassert", "...
Craxic/plyj
plyj/model/name.py
Python
bsd-3-clause
1,255
0.000797
from operator import attrgetter from plyj.model.source_element import Expression from plyj.utility import assert_type class Name(Expression): simple = property(attrgetter("_simple")) value = property(attrgetter("_value")) def __init__(self, value): """ Represents a name. :param va...
in value def append_name(self, name): self._simple = False if isinstance(name, Name): self._value = self._value + '.' + name._value else: self._value = self._value + '.' + name @staticmethod def ensure(se, simple): if isinstance(se, str): ...
se TypeError("Required Name, got \"{}\"".format(str(type(se)))) if simple and not se.simple: raise TypeError("Required simple Name, got complex Name") return se def serialize(self): return self.value
y73isc00l/WishGift
myproject/polls/migrations/0026_auto_20170204_1715.py
Python
apache-2.0
624
0
# -*- coding: utf-8 -*- #
Generated by Django 1.10.5 on 2017-02-04 11:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0025_remove_pool_poolsize'), ] operations = [ migrations.AddField( model_name='e...
eld( model_name='extradetails', name='pincode', field=models.IntegerField(default=0), ), ]
UCL-INGI/INGInious
inginious/frontend/task_dispensers/__init__.py
Python
agpl-3.0
2,182
0.00275
from abc import ABCMeta, abstractmethod class TaskDispenser(metaclass=ABCMeta): def __init__(self, task_list_func, dispenser_data): """ Instantiate a new TaskDispenser :param task_list_func: A function returning the list of available course tasks from the task factory :param dispen...
""" Return
s the localized task dispenser name """ pass @abstractmethod def get_dispenser_data(self): """ Returns the task dispenser data structure """ pass @abstractmethod def render_edit(self, template_helper, course, task_data): """ Returns the formatted task list edition form ...
hanlind/nova
nova/api/openstack/compute/networks.py
Python
apache-2.0
8,024
0
# Copyright 2011 Grid Dynamics # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses...
(202) @extensions.expected_errors((404, 501)) @wsgi.action("disassociate") def _disassociate_host_and_project(self, req, id, body): context = req.environ['nova.context'] context.can(net_policies.BASE_POLICY_NAME) try:
self.network_api.associate(context, id, host=None, project=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: common.raise_feature_not_supported() @wsgi.Controller.api...
marcelosandoval/tekton
backend/venv/Scripts/unidecode-script.py
Python
mit
388
0
#!C:\Users\ponto frio\PycharmProjects\MarceloSandovalScript\backend\venv\Scripts\python.exe #
EASY-INSTALL-ENTRY-SCRIPT: 'Unidecode==0.4.18','console_scripts','unidecode' __requires__ = 'Unidecode==0.4.18' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('Unidecode==0.4.18', 'console_sc
ripts', 'unidecode')() )
Haynie-Research-and-Development/jarvis
deps/lib/python3.4/site-packages/sleekxmpp/plugins/__init__.py
Python
gpl-2.0
3,265
0.000306
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010
Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.plugins.base import PluginManager, PluginNotFound, BasePlugin from sleekxmpp.plugins.base import register_plugin, load_plugin __all__ = [ # XEPS 'xep_0004', # Data Forms 'xep_0009...
y 'xep_0013', # Flexible Offline Message Retrieval 'xep_0016', # Privacy Lists 'xep_0020', # Feature Negotiation 'xep_0027', # Current Jabber OpenPGP Usage 'xep_0030', # Service Discovery 'xep_0033', # Extended Stanza Addresses 'xep_0045', # Multi-User Chat (Client) 'xep_0047', #...
sjsrey/doconce
lib/doconce/plaintext.py
Python
bsd-3-clause
10,664
0.004126
import re, sys from common import default_movie, plain_exercise, bibliography, \ cite_with_multiple_args2multiple_cites from misc import option def plain_author(authors_and_institutions, auth2index, inst2index, index2inst, auth2email): text = '\n' for author in auth2index: email...
nd plaintext inserts a double colon if title == '' or title.lower() == 'none' or title == '::': newlines.append('|-' + '-'*maxlen + '-|') else: newlines.append(title + ' ' + '-'*(maxlen-len(title)) + '--|')
for line in lines: newlines.append('| ' + line + ' '*(maxlen-len(line)) + ' |') newlines.append('|-' + '-'*maxlen + '-|') # Drop blank lines at the beginning drop = 0 for line in newlines[1:]: if re.search(r'[^\-| ]', line): break else: drop += 1 for i...