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
eduNEXT/edunext-platform
lms/djangoapps/course_wiki/tests/test_tab.py
Python
agpl-3.0
2,388
0
""" Tests for wiki views. """ from django.conf import settings from django.test.client import RequestFactory from lms.djangoapps.courseware.tabs import get_course_tab_list from common.djangoapps.student.tests.factories import AdminFactory, UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTes...
settings.WIKI_ENABLED = True self.course.allow_public_wiki_access = False assert self.get_wiki_tab(self.user, self.course) is None assert self.get_wiki_tab(self.instructor, self.course) is not None def test_wiki_enabled_false(self): """Test wiki tab when Enabled setting is Fa...
= False assert self.get_wiki_tab(self.user, self.course) is None assert self.get_wiki_tab(self.instructor, self.course) is None def test_wiki_visibility(self): """Test toggling of visibility of wiki tab""" settings.WIKI_ENABLED = True self.course.allow_public_wiki_access = T...
cswelin/kevo-polyglot
polykevo.py
Python
mit
1,943
0.004632
from polyglot.nodeserver_api import SimpleNodeServer, PolyglotConnector from polykevo_types import KevoDiscovery, KevoLock VERSION = "0.2.0" class KevoNodeServer(SimpleNodeServer): controller = [] locks = [] def setup(self): super(KevoNodeServer, self).setup() self.poly.logger.info('Con...
'kevodisco') self.controller.discover() self.update_config() except Exception as e: self.poly.logger.info('KevoNodeServer setup caught exception: %s', e) def poll(self): try: self.poly.logger.info("poll") self.report_driver
s() except Exception as e: self.poly.logger.info('KevoNodeServer setup caught exception: %s', e) def long_poll(self): try: self.poly.logger.info("long_poll") if len(self.locks) >= 1: self.controller.refreshAll() except Exception as e: ...
assumptionsoup/pymel
tests/test_animation.py
Python
bsd-3-clause
11,519
0.006945
import sys import unittest import traceback import maya.cmds as cmds import pymel.core as pm import pymel.util as util import pymel.util.testing as testing class TestConstraintVectorQuery(testing.TestCaseExtended): def setUp(self): cmds.file(new=1, f=1) def _doTestForConstraintType(self, constraintT...
valName = '%s_%
s' % (type(val).__name__, valName) testName = 'test_%s_%s_%s' % (func.__name__, flag, valName) test.__name__ = testName # add the test to the class setattr(cls, testName, test) @classmethod def addKeyframeTimeTests(cls): for val, expected in [ ...
evanprs/openspr
liveplot.py
Python
mit
5,661
0.007596
#!/usr/bin/env python # Combination of matplotlib sample code to create embedded animations from random import random from time import time import csv import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.animati...
ow = AnimWindow(self) self.animWindow.pack() class AnimWindow(tk.Frame): def __init__(self, master, xlim=20, ylim=1, *arg
s, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.master = master self.xlim = xlim self.xlim_0 = xlim # so we can return to original scaling self.ylim = ylim self.ylim_0 = ylim self.active = True self.t0 = time() self.data = ([],[...
zasdfgbnm/tensorflow
tensorflow/contrib/estimator/python/estimator/multi_head_test.py
Python
apache-2.0
24,796
0.005202
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
sigmoid(expected_logits1), 'head2': _sigmoid(expected_logits2),
} spec = multi_head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.PREDICT, logits=logits) self.assertItemsEqual( (_DEFAULT_SERVING_KEY, 'head1', 'classification/head1', 'predict/head1', 'head2', 'classification/head...
kidchang/compassv2-api
compass/db/config_validation/default_validator.py
Python
apache-2.0
5,205
0
# Copyright 2014 Huawei Technologies Co. Ltd # # 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 ...
e_config_helper(session,
config[elem], name_col, id_col, id_value, meta_table, ...
liao1995/DataAnalysis
NaiveBayes.py
Python
gpl-3.0
2,150
0.016744
import csv def list_words(text): words = [] words_tmp = text.lower().split() for p in words_tmp: if p not in words and len(p) > 2: words.append(p) return words def training(texts): c_words ={} c_categories ={} c_texts = 0 c_tot_words =0 for t in texts: ...
category = c category_prob = prob_total_c return (category, category_prob) if __name__ == "__main__":
with open('training.csv') as f: subjects = dict(csv.reader(f, delimiter=',')) p,c,t,tp = training(subjects.items()) #First Test clase = classifier("Available on Term Life - Free",p,c,t,tp) print("Result: {0} ".format(clase)) #Second Test with open("test.csv") as f: ...
hip-odoo/odoo
addons/crm/models/crm_team.py
Python
agpl-3.0
3,700
0.003243
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval class Team(models.Model): _name = 'crm.team' _inherit = ['mail.alias.mixin', 'crm.team'] resource_calendar_id = fields.Many2o...
his box to manage leads in this sales team.") use_opportunities = fields.Boolean('Opportunities', default=True, help="Check this box to manage opportunities in th
is sales team.") alias_id = fields.Many2one('mail.alias', string='Alias', ondelete="restrict", required=True, help="The email address associated with this team. New emails received will automatically create new leads assigned to the team.") def get_alias_model_name(self, vals): return 'crm.lead' ...
prasannav7/ggrc-core
src/ggrc/migrations/versions/20131009115538_307bd54ac651_pop_sample_evidence.py
Python
apache-2.0
2,175
0.013793
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """pop sample evidence document joins Revision ID: 307bd54ac651 Revises: 2814f1...
ksheet_id'], ['id'] ) op.create_foreign_key( 'sample_worksheet_document', 'responses', 'documents', ['sample_worksheet_id'], ['id'] ) op.create_foreign_key( 'sample_evidence_document',
'responses', 'documents', ['sample_evidence_id'], ['id'] ) op.drop_column("responses", "population_worksheet") op.drop_column("responses", "sample_worksheet") op.drop_column("responses", "sample_evidence") def downgrade(): op.add_column("responses", sa.Column("population_worksheet", sa.Stri...
gensmusic/test
l/python/test/logging/multiple-loger-and-formatter.py
Python
gpl-2.0
870
0.002299
#!/usr/bin/python #coding:utf-8 import logging logger = logging.getLogger("simple_example") logger.setLevel(logging.DEBUG) # create file handler whistreamhandler logs even debug messages filehandler = logging.FileHandler("spam.log") filehandler.setLevel(logging.DEBUG) # create console handler with a higher log level s...
g.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") streamhandler.setFormatter(formatter) filehandler.setFormatter(formatter) # add the handlers to logger logger.addHandler(streamhandler) logger.addHandler(filehandler) # "applicat...
essage") logger.critical("critical message")
zubie7a/Algorithms
LeetCode/01_Easy/lc_266.py
Python
mit
532
0.003759
# 266 - Palindrome Permutation (Easy) # https://leetcode.com/problems/palindrome-permutation/ from collections import
Counter class Solution(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ # Check if characters in a string can form a palindrome. # All values have to happen by multiples of 2, or just one # happening an odd amount of times. ...
x % 2 == 1, Counter(list(s)).values()) return len(odds) <= 1
SunPower/PVMismatch
pvmismatch/tests/test_pvconstants.py
Python
bsd-3-clause
1,544
0.000648
from pvmismatch import * import os import numpy as np BASEDIR = os.path.dirname(__file__) def test_pvconst_npts_setter(): """Test pvconst property and setter methods""" pvconst = pvconstants.PVconstants() assert pvconst.npts == pvconstants.NPTS assert len(pvconst.pts) == pvconst.npts assert pvco...
sert pvconst.negpts[0] == 1 assert pvconst.negpts[-1] > 0 def test_minimum_current_close_to_max_voc_gh110(): """ Tests that minimum current in ``calcSeries`` is reasonably close to the maximum open circuit current of all cells in module. This came up in GitH
ub issue 110 that the resolution of the plots, and hence the underlying data, at high cell temperature was too coarse. """ pvsys = pvsystem.PVsystem() pvsys.setTemps(388) expected = np.loadtxt(os.path.join(BASEDIR, 'gh110.dat')) calculated = np.concatenate( [[pvsys.Isys], [pvsys.Vsys...
HARDWAREdotASTRO/ROBh.aTnetwork
Robhat/Robhat/Dome/Sensors.py
Python
mit
9,062
0.003421
# -*- coding: utf-8 -*- import time import math import numpy as np from toolz.curried import operator as op import importlib.util from typing import Union, Text, NewType, List, Callable, Tuple try: importlib.util.find_spec('RPi.GPIO') importlib.util.find_spec('smbus2 ') import smbus2 as smbus import RPi...
al (bytes): A word starting at adr """ high = self.read_byte(adr) low = self.read_byte(adr + 1) val = (high << 0) + low return val def read_word_2c(self, adr: I2C_Address) -> bytes: """ Read a word with some conversions Args: adr (I2C_Add...
tart Returns: val (bytes): The converted values. """ val = self.read_word(adr) return -((65535 - val) + 1) if val >= 0x8000 else val def write_byte(self, adr: I2C_Address, value: bytes) -> bool: """ Write a byte to the I2C device Args: ...
wileeam/airflow
airflow/providers/google/cloud/operators/speech_to_text.py
Python
apache-2.0
4,187
0.002627
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
g, project_id: Optional[str] = None, gcp_conn_id: str = "google_cloud_default",
retry: Optional[Retry] = None, timeout: Optional[float] = None, *args, **kwargs ) -> None: self.audio = audio self.config = config self.project_id = project_id self.gcp_conn_id = gcp_conn_id self.retry = retry self.timeout = timeout se...
flavour/iscram
modules/s3/s3validators.py
Python
mit
71,023
0.004182
# -*- coding: utf-8 -*- """ Custom Validators @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: (c) 2010-2012 Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the...
-------------------- class IS_LAT(object): """ example: INPUT(_type="text", _name="name", requires=IS_LAT()) latitude has to be in degrees between -90 & 90 """ def __init__(self, error_message = "Latitude/Northing should be between -90 & 90!" ): ...
, value): try: value = float(value) if self.minimum <= value <= self.maximum: return (value, None) except ValueError: pass return (value, self.error_message) class IS_LON(object): """ example: INPUT(_type="text", _name="na...
jhamman/xarray
xarray/tests/test_backends.py
Python
apache-2.0
172,910
0.000694
import contextlib import itertools import math import os.path import pickle import shutil import sys import tempfile import warnings from contextlib import ExitStack from io import BytesIO from pathlib import Path from typing import Optional import numpy as np import pandas as pd import pytest from pandas.errors impor...
signed": True, "
add_offset": 10, "scale_factor": np.float32(0.1), } # Create signed data corresponding to [0, 1, 127, 128, 255] unsigned sb = np.asarray([0, 1, 127, -128, -1], dtype="i1") return Dataset({"x": ("t", sb, attributes)}) def create_signed_masked_scaled_data(): encoding = { "_FillValue"...
eigengrau/x-selection-pipe
src/xselection/cli.py
Python
gpl-3.0
1,840
0.00163
"""Monitor Xorg selections, optionally sync them, and print changes to stdout. """ import signal import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk from xselection.selection import Selection from xselection.util.argparse import ArgumentParser parser = ArgumentParser() parser.add_argume...
chronization is achieved by connecting all selections in a cirular # graph. pairwise = zip(selections[:-1], selections[1:]) for (selection1, selection2) in pairwise: selection1.add_action(selection2.set) selection2.add_action(selection1.set) # Tie up the circle. ...
ections[-1] last.add_action(first.set) first.add_action(last.set) for selection in selections: selection.connect() # Work around bug 622084. signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.main()
Oinweb/py-fly
resources/views.py
Python
bsd-2-clause
1,070
0.002804
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from fly_project import settings from fly_project import constants from api.models import ResourceLink from api.models impo
rt Badge, Me, Notification @login_required(login_url='/authentication') def resources_page(request): # BADGE ID #28 # Check to see if the logged in User has the Badge wit the ID #1. If not # then create it now. me = get_object_or_404(Me, user=request.user.id) badge = get_object_or_404(Badge, id=28...
type=2, title=badge.title, description=badge.description, user=me.user, badge=badge, ) return render(request, 'resources/view.html',{ 'settings': settings, 'constants': constants, 'resources': ResourceLink.objects.all(), ...
Flavsditz/projects
eyeTracking/pupil/pupil_src/shared_modules/atb/constants.py
Python
gpl-2.0
1,491
0.00939
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (C) 2009-2010 Nicolas P. Rougier # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #---------------...
UINT16, TW_TYPE_INT32, TW_TYPE_UINT32, TW_TYPE_FLOAT, TW_TYPE_DOUBLE, TW_TYPE_
COLOR32, TW_TYPE_COLOR3F, TW_TYPE_COLOR4F, TW_TYPE_CDSTRING, _, TW_TYPE_QUAT4F, TW_TYPE_QUAT4D, TW_TYPE_DIR3F, TW_TYPE_DIR3D) = range(0,23) # typedef ETwType for static (fixed size) strings def TW_TYPE_CSSTRING(n): return (0x30000000+((n)&0xfffffff)) # typedef enum ETwParamValueType (TW_PARAM_...
unicefuganda/edtrac
edtrac_project/rapidsms_httprouter_src/rapidsms_httprouter/tests/test_send_messages.py
Python
bsd-3-clause
2,204
0.024047
from django.test import TestCase from rapidsms_httprouter_src.rapidsms_httprouter.management.commands.send_messages import Command from rapidsms_httprouter_src.rapidsms_httprouter.models import MessageBatch, Message from rapidsms.models import Backend, Connection class SendMessagesCommandTestCase(TestCase): def ...
ext=%(text)s&to=%(recipient)s&smsc=%(backend)s&%(priority)s" self.command.f
etch_url = self.fake_get_url def fake_get_url(self, url): if "400" in url: return 403 return 200 def create_message(self, id, backend): fake_connection = Connection(identity=str(id)) fake_connection.backend, created = Backend.objects.get_or_create(name=backend) fake_connection.save() message = Mess...
slewt/TabPy
tabpy-server/tests/test_rest.py
Python
mit
5,180
0.008301
import unittest import json import sys try: from unittest.mock import Mock except ImportError: from mock import Mock import requests from tabpy_client.rest import * class TestRequestsNetworkWrapper(unittest.TestCase): def test_init(self): rnw = RequestsNetworkWrapper() def test_init_with...
sponse(200) session.post.return_value = mock_response(200) session.put.return_value = mock_response(200) session.delete.return_value = mock_response(204) self.rnw = RequestsNetworkWrapper(session=session) def test_GET(self): url = 'abc' data = {'foo':'bar'} ...
timeout=None) def test_GET_InvalidData(self): url = 'abc' data = {'cat'} try: self.assertEqual(self.rnw.GET(url, data), 'json') except: e=sys.exc_info()[0] self.assertEquals(e,TypeError) def test_GET_InvalidURL(self): url...
devthat/zipencrypt
tests/python2/test_encryption.py
Python
mit
3,249
0.000308
import io import tempfile import unittest from zipencrypt import ZipFile, ZipInfo, ZIP_DEFLATED from zipencrypt.zipencrypt2 import _ZipEncrypter, _ZipDecrypter class TestEncryption(unittest.TestCase): def setUp(self): self.plain = "plaintext" * 3 self.pwd = b"password" def test_roundtrip(sel...
zipfd.read("file1.txt", pwd=self.pwd) self.assertEqual(self.plain, content) def test_writestr_with_zipinfo_keep_file_open(self):
zinfo = ZipInfo(filename="file1.txt") zinfo.flag_bits |= 0x8 with ZipFile(self.zipfile, mode="w") as zipfd: zipfd.writestr(zinfo, self.plain, pwd=self.pwd) content = zipfd.read("file1.txt", pwd=self.pwd) self.assertEqual(self.plain, content) def test_write_with_...
fiorix/cyclone
cyclone/tests/test_mail.py
Python
apache-2.0
2,169
0
# # Copyright 2014 David Novakovic # # 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 wri...
com", "bar@example.com", "hi thar", "This is a message." ) self.assertTrue(isinstance(message.to_addrs, list)) def test_attach(self): open("foo.txt", "w").write("sometext") self.message.attach("foo.txt") self.assertTrue(self.message.msg) ...
foobar") sio = self.message.render() self.assertTrue("foo@example.com" in sio.getvalue()) @patch("cyclone.mail.reactor.connectTCP") def test_sendmail(self, conn): sendmail( {"host": "localhost", "tls": True}, self.message ) self.assertTrue(conn.ca...
google-research/google-research
low_rank_local_connectivity/data_provider_test.py
Python
apache-2.0
2,084
0.006718
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
ining: cases.append(("case_%d" % i, d, s, t)) i += 1 return tuple(cases) class DataProviderTest(tf.test.TestCase, parameterized.TestCase): def test_import(self): self.assertIsNotNone(get_data_provider) @parameterized.named_parameters(*_get_test_cases()) def test_dataset(self, dataset_nam...
size = 1 image_shape = _IMAGE_SHAPE_DICT[dataset_name] dataset = get_data_provider(dataset_name)( subset=subset, batch_size=batch_size, is_training=is_training) images, labels = dataset.images, dataset.labels im, l = self.evaluate((images, labels)) self.assertEqual(im.shape,...
googleapis/python-analytics-admin
samples/generated_samples/analyticsadmin_v1alpha_generated_analytics_admin_service_archive_custom_dimension_async.py
Python
apache-2.0
1,521
0.001972
# -*- 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...
ically generated for illustrative purposes only. # It may require m
odifications 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_ArchiveCustomDimension_async] from google.analytics import admin_v1alpha async def...
HydrelioxGitHub/home-assistant
homeassistant/components/rss_feed_template/__init__.py
Python
apache-2.0
2,910
0
"""Support to export sensor values via RSS feed.""" from html import escape from aiohttp import web import voluptuous as vol from homeassistant.components.http import HomeAssistantView import homeassistant.helpers.config_validation as cv CONTENT_TYPE_XML = 'text/xml' DEPENDENCIES = ['http'] DOMAIN = 'rss_feed_templ...
est, entity_id=None): """Generate the R
SS view XML.""" response = '<?xml version="1.0" encoding="utf-8"?>\n\n' response += '<rss>\n' if self._title is not None: response += (' <title>%s</title>\n' % escape(self._title.async_render())) for item in self._items: response += ' ...
morefreeze/scrapy_projects
caoporn/caoporn/middlewares/spider.py
Python
mit
870
0.005747
# -*- coding: utf-8 -*- import pymo
ngo from scrapy.http import Request class CheckPointSpider(object): """record check point to mongo""" collection_name = 'chec
kpoint' def process_spider_output(self, response, result, spider): """record this page """ mongo_uri=spider.crawler.settings.get('MONGO_URI') mongo_db=spider.crawler.settings.get('MONGO_DB') client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] def add...
myarjunar/QGIS
python/plugins/processing/algs/qgis/SpatialJoin.py
Python
gpl-2.0
10,601
0.001415
# -*- coding: utf-8 -*- """ *************************************************************************** SpatialJoin.py --------------------- Date : October 2013 Copyright : (C) 2013 by Joshua Arnott Email : josh at snorfalorpagus dot net *******************...
try: bbox = inGeom.buffer(10, 2).boundingBox() else: bbox = inGeom.boundingBox() bufferedBox = vector
.bufferedBoundingBox(bbox, 0.51 * precision) joinList = index.intersects(bufferedBox) if len(joinList) > 0: count = 0 for i in joinList: inFeatB = mapP2[i] inGeomB = vector.snapToPrecision(inFeatB.geometry(), precision) ...
ddico/odoo
addons/website_gengo/__manifest__.py
Python
agpl-3.0
544
0.001838
# -*- coding: utf-8 -*- # Par
t of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Gengo Translator', 'category': 'Website/Website', 'summary': 'Translate website in one-click', 'description': """ This module a
llows to send website content to Gengo translation service in a single click. Gengo then gives back the translated terms in the destination language. """, 'depends': [ 'website', 'base_gengo' ], 'data': [ 'views/website_gengo_templates.xml', ] }
parpg/parpg
parpg/gui/slot.py
Python
gpl-3.0
889
0.00225
# This file is part of PARPG. # PARPG 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. # PARPG is distributed in the h
ope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should hav
e received a copy of the GNU General Public License # along with PARPG. If not, see <http://www.gnu.org/licenses/>. from fife.extensions.pychan import Icon class Slot(Icon): def _setImage(self, source): self._image = source def _getImage(self): return self._image image = property(_ge...
leifos/boxes
asg_project/asg/urls.py
Python
mit
562
0.005338
__author__ = 'leif' from django.conf.urls import patterns, url, include import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^start/(?P
<num>[0-9]+)/$', views.startgame, name='startgame'), url(r'^pick/', views.pick, name='pick'), url(r'^query/$', views.query, name='
query'), url(r'^assess/$', views.assess, name='assess'), url(r'^players/(?P<username>[a-zA-Z0-9_.+@-]+)', views.profile_page, name='profile'), url(r'^leaderboard/$', views.leaderboard, name='leaderboard'), )
quantopian/zipline
zipline/examples/buy_and_hold.py
Python
apache-2.0
1,568
0
#!/usr/bin/env python # # Copyright 2015 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
ld example data. #
github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) def handle_data(context, data): if not context.has_ordered: for stock in cont...
p5py/p5
p5/visualTests/sanityTests/2DSanityTests/test28.py
Python
gpl-3.0
745
0.013423
from p5 import * mx = 0 my = 0 easing = 0.05 radius = 24 edge = 100 inner = edge + radius def setup(): size(640, 360) no_stroke() ellips
e_mode("RADIUS") rect_mode("CORNER") def draw(): background(51) global mx, my, easing, radius, edge, inner if abs(mouse_x - mx) > 0.1: mx = mx + (mouse_x - mx) * easing if abs(mouse_y - my) > 0.1: my = my + (mouse_y- my) * easing mx = c...
edge], width - 2*edge, height - 2*edge) fill(255) ellipse([mx, my], radius, radius) if __name__ == '__main__': run()
amenonsen/ansible
lib/ansible/module_utils/network/iosxr/facts/facts.py
Python
gpl-3.0
2,778
0.00396
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The facts class for iosxr this file validates each subset of facts and selectively calls the appropriate facts gathering function """ from __future__ import absolute_imp...
ollect the facts for iosxr :param legacy_facts_type: List of legacy facts types :param resource_facts_type: List of resource fact types :param data: previously collected conf :rtype: dict :return: the fact
s gathered """ netres_choices = FactsArgs.argument_spec['gather_network_resources'].get('choices', []) if self.VALID_RESOURCE_SUBSETS: self.get_network_resources_facts(netres_choices, FACT_RESOURCE_SUBSETS, resource_facts_type, data) if self.VALID_LEGACY_GATHER_SUBSETS: ...
codilime/cloudify-dsl-parser
dsl_parser/interfaces/constants.py
Python
apache-2.0
813
0
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
the License for the specific language governing
permissions and # * limitations under the License. from dsl_parser.interfaces import utils INTERFACES = 'interfaces' SOURCE_INTERFACES = 'source_interfaces' TARGET_INTERFACES = 'target_interfaces' NO_OP = utils.no_op()
edx-solutions/edx-platform
openedx/core/djangoapps/catalog/migrations/0002_catalogintegration_username.py
Python
agpl-3.0
503
0.001988
# -*- coding
: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AddField( model_name='catalogintegration', na
me='service_username', field=models.CharField(default=u'lms_catalog_service_user', help_text='Username created for Course Catalog Integration, e.g. lms_catalog_service_user.', max_length=100), ), ]
frejanordsiek/hdf5storage
tests/test_marshaller_plugins.py
Python
bsd-2-clause
3,575
0.00028
# Copyright (c) 2014-2021, Freja Nordsiek # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions ...
api_versions() def test_find_thirdparty_marshaller_plugins(): found_example = False apivs = hdf5storage.plugins.supported_marshaller_api_versions() plugins = hdf5storage.plugins.find_thirdparty_marshaller_plugins() assert isinstance(plugins, dict) assert set(apivs) == set(plugins) for k, v in ...
, str) assert isinstance(v2, pkg_resources.EntryPoint) if k2 == 'example_hdf5storage_marshaller_plugin': found_example = True assert has_example_hdf5storage_marshaller_plugin == found_example @pytest.mark.skipif(has_example_hdf5storage_marshaller_plugin, ...
astropy/astropy-tools
discontinued_usage/unify_section_headings.py
Python
bsd-3-clause
2,718
0.002208
#!/usr/bin/env python """ Find the sets of characters used in RST section headers, and replace with a standard sequcne For input like :: ########## header ########## Section ******** Subsection =========== Section 2 ********** and HEADER_CHAR_LEVELS = '*=-^"+:~' this should produce :: *****...
ile HEADER_CHAR_LEVELS = '*=-^"+:~' def replace_header_chars(filename): header_chars = '' level = -1 rx = re.compile(r'^(\S)\1{3,}\s*$') with open(filename
, 'r') as infile, tempfile.NamedTemporaryFile(suffix='.rst', delete=False) as outfile: for i, line in enumerate(infile): match = rx.match(line) if match: char = match.group(1) if char in header_chars: # Existing header char: go back out...
vakaras/db-utils
src/db_utils/validators/phone_number.py
Python
lgpl-3.0
5,663
0
#!/usr/bin/python """ Validators of phone numbers. """ from db_utils.validators.exceptions import ValidationError from db_utils.validators.phone_codes import COUNTRIES_PHONE_CODES_BY_CODE from db_utils.validators.phone_codes import COUNTRIES_PHONE_CODES from db_utils.decorators.unicode import UnicodeArguments def...
mber is too short?') for region in COUNTRIES_PHONE_CODES_BY_CODE[ number.c
ountry_code]['regions']: if value.startswith(region['code']): number.region_code = region['code'] number.region = region['region'] return value[len(region['code']):] raise self.validation_exception_type( u'Unknown phone number region....
xuanthanhbk92/Programe-for-Linux
PluralSight/linux-systems-programming/2-linux-systems-programming-m2-exercise-files/pythonio.py
Python
gpl-3.0
281
0.017794
#!/usr/bin/python3 import sys if len(sys.arg
v) != 3: print("usage: python io blocksize blockcount") sys.exit(1) size = int(sys.arg
v[1]) count = int(sys.argv[2]) buffer = bytearray(size) f = open("pythonio.out", 'wb') for i in range(0,count): f.write(buffer) f.close()
polarise/Code
feature_length_distribution.py
Python
gpl-2.0
877
0.057013
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import division
import sys import pysam import BioClasses import cPickle def length_from_region( region ): seqname, start_stop = region.split( ":" ) start, stop = map( int, start_stop.split( "-" )) return stop - start + 1 def main( fn ): with open( fn ) as f: genes = cPickle.load( f ) print "\t".join([ "gene_id", "UTR_len"...
cds() if equal_cds is not None: print "\t".join( map( str, [ gene_id, length_from_region( G.get_overall_UTR_region( "equal_cds" )), length_from_region( equal_cds[0].cds_region_str()), equal_cds[0].get_cds_length() ])) if __name__ == "__main__": try: fn = sys.argv[1] except IndexError: print >> sys.stderr, "...
vialette/binreconfiguration
binreconfiguration/storagesystem/snapshotreporter.py
Python
mit
2,093
0.028189
"""Storage unit snapshots easy reporter""" class SnapshotReporter(object): class RowReporter(object): def __init__(self, storage_unit_snapshot): self._report = {} for bin_snapshot in storage_unit_snapshot: for key in bin_snapshot: if key != 'name' and key != 'capacity': if key not in self._re...
in storage_unit_snapshots] def values(self, key): return [row.values(key) for row in self._rows] def min(self, key): """Return the min vector for key *key*.""" return [row.min(key) for row in self._rows] def average(self, key): """Return the average vector for key *key*.""" return [row.average(key) for...
s] def max(self, key): """Return the max vector for key *key*.""" return [row.max(key) for row in self._rows] def last(self): return self._rows[-1] def last_values(self, key): return self._rows[-1].values(key) def last_min(self, key): return self._rows[-1].min(key) def last_average(self, key): ret...
ibackus/compare-changa-builds
compchanga/runTest.py
Python
mit
17,957
0.010525
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
# Use absolute paths directory = os.path.abspath(directory) # Use ChaN
Ga in the run directory changaDir = os.path.abspath(outputDir) # Set up ChaNGa command if runner is None: runner = os.path.join(changaDir, 'charmrun') if nproc is not None: runner += ' +p{0}'.format(nproc) changa = os.path.join(changaDi...
viqueen/closure-templates
python/bidi.py
Python
apache-2.0
16,021
0.006741
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
. _HAS_NUMERALS_RE = re.compile(r'\d') # Simplified regular expression for am HTML tag (opening or closing) or an HTML # escape - the things we want to skip over in order to ignore their ltr # characters. _HTML_SKIP_RE = re.compile('<[^>]*>|&[^;]+;') # Regular expressio
n to check if a string looks like something that must # always be LTR even in RTL text, e.g. a URL. When estimating the # directionality of text containing these, we treat these as weakly LTR, # like numbers. _IS_REQUIRED_LTR_RE = re.compile(r'^http[s]?://.*') # A practical pattern to identify strong LTR/RTL characte...
eternallyBaffled/itrade
itrade_wxpropquote.py
Python
gpl-3.0
21,182
0.005382
#!/usr/bin/env python # ============================================================================ # Project Name : iTrade # Module Name : itrade_wxpropquote.py # # Description: wxPython quote properties display # # The Original Code is iTrade code (http://itrade.sourceforge.net). # # The Initial Developer ...
label = wx.StaticText(self, wx.ID_ANY, message('prop_currency')) box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) label = wx.S
taticText(self, wx.ID_ANY, self.m_quote.currency()) box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) label = wx.StaticText(self, wx.ID_ANY, message('prop_typeofclock')) box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.liveText = wx.StaticText(self, wx.ID_ANY, self.m_quote.sv_type_of...
node-/tetra-master
src/utils.py
Python
mit
1,092
0.011905
#!/usr/bin/python # Jake Kosberg # # Utilities import os import sys import pygame def cell_hovered(cell, mouse_pos): mx, my = mouse_pos if ((mx > cell.xpos and mx < cell.xpos + cell.width) and (my > cell.ypos and my < cell.ypos + cell.height)): return True else: return False ...
d mx < monster.xpos + monster.width) and (my > monster.ypos and my < monster.ypos + monster.width) and monster.selected == Fa
lse): monster.select() return monster elif monster.selected == True: monster.deselect() return False
saltstack/salt
salt/_logging/handlers.py
Python
apache-2.0
9,030
0.000664
""" salt._logging.handlers ~~~~~~~~~~~~~~~~~~~~~~ Salt's logging handlers """ import copy import logging import logging.handlers import queue import sys from collections import deque from salt._logging.mixins import ExcInfoOnLogLevelFormatMixin # from salt.utils.versions import warn_until_date log = lo...
mat(name=__name__) # ) self.__max_queue_size = max_queue_size super().__init__(level=level) self.__messages = deque(maxlen=max_queue_size) def handle(self, record): self.acquire() self.__messages.append(record) self.release() def sync_with_h
andlers(self, handlers=()): """ Sync the stored log records to the provided log handlers. """ if not handlers: return while self.__messages: record = self.__messages.popleft() for handler in handlers: if handler.level > record....
Taapat/enigma2-plugin-blurayplayer
src/BlurayPlayerDirBrowser.py
Python
gpl-2.0
1,598
0.021902
from __future__ import print_function import os from Components.ActionMap import ActionMap from Components.config import config from Components.FileList import FileList from Components.Sources.StaticText import StaticText from Screens.Screen import Screen from . import _ from .BlurayUi import BlurayMain class Blur...
.ok }) self.setTitle(_('Please select the blu-ray disc')) def ok(self): fileName = self['filelist'].getFilename() if fileName and fileName[-1:] == '/' and \ os.path.isdir(os.p
ath.join(fileName, 'BDMV/STREAM/')): self.session.open(BlurayMain, fileName) elif self['filelist'].canDescent(): self['filelist'].descent() elif fileName and fileName[-1:] != '/': currentDir = self['filelist'].getCurrentDirectory() iso_path = os.path.join(currentDir, fileName) try: from Plugins.E...
PawseySupercomputing/Develop-with-MPI
Solutions/python/ex2-pingpong/pingpong.py
Python
cc0-1.0
950
0.024211
########################################################################## ## ## An MPI program to send a message back and forth between two ranks ## using a blocking send mpi_send(), and a blocking recieve mpi_recv(). ## ## NumPy is used to allocate the message buffer in terms of size and ## type. ##############...
2 MPI tasks" errorcode = comm.Abort() # Perform multiple exchanges between the 2 MPI Tasks nexchange = 100 for i in range(nexchange): sender = i % 2 recver = 1 - sender if rank==sender: data = np.ones( (1,),
dtype=np.int ) comm.Send( [data, MPI.INT], dest=recver, tag=9999 ) else: data = np.empty( [1], dtype=np.int ) comm.Recv( data, source=sender, tag=9999 )
yangdw/PyRepo
src/annotation/gfirefly/gfirefly/gfirefly/dbentrust/util.py
Python
mit
8,514
0.015388
#coding:utf8 ''' Created on 2013-5-8 @author: lan (www.9miao.com) ''' from dbpool import dbpool from MySQLdb.cursors import DictCursor from numbers import Number from gtwisted.utils import log import traceback from gfirefly.utils.singleton import Singleton M2DB_PORT = 5000 M2DB_HOST = "127.0.0.1" SYNC_TYPE = 1 clas...
except Exc
eption,e: log.err(e,traceback.format_exc()) log.err(sql) cursor.close() conn.close() if(count >= 1): return True return False def DBTest(): sql = """SELECT * FROM tb_item WHERE characterId=1000001;""" conn = dbpool.connection(write=False,tablename="tb_item") cursor =...
zirou30/python_student
82.py
Python
gpl-3.0
387
0.005222
idade = 12 if idade < 4: preco = 0 elif idade < 18: preco = 5 elif idade < 65: preco = 10 else: preco = 5 print('Seu custo de admissão e R$' + str(preco) + '.') ''' Foi adicionado mais bloco de instrução elif para idades abaixo de 65. Se caso a ida
de for maior que 18 e menor qu
e 65 o bloco e executado, caso a idade seja acima de 65 executa o último bloco else. '''
thica/ORCA-Remote
src/scripts/tools/tool_repositorymanager/RepManager.py
Python
gpl-3.0
16,092
0.013673
# -*- coding: utf-8 -*- """ ORCA Open Remote Control Application Copyright (C) 2013-2020 Carsten Thielepape Please contact me by : http://www.orca-remote.org/ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publ...
rt import ToUnicode from ORCA.utils.TypeConvert import EscapeUnicode from ORCA.utils.Filesystem import AdjustPathToOs from ORCA.utils.FileName import cFileName from ORCA.utils.LogError import LogError from ORCA.vars.Replace import ReplaceVars from ORCA.vars.Access
import SetVar from ORCA.vars.Actions import Var_DelArray from ORCA.utils.XML import XMLPrettify from ORCA.utils.Path import cPath from ORCA.download.RepManagerEntry import cRepManagerEntry import ORCA.Globals as Globals oRepositoryManager:Union[cRepositoryManager,None] = None def ...
ckclark/leetcode
py/construct-the-rectangle.py
Python
apache-2.0
304
0
cla
ss Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ ans = None W = 1
while W * W <= area: if area % W == 0: ans = [area / W, W] W += 1 return ans
YaguangZhang/EarsMeasurementCampaignCode
Trials/lib/Test2_baseband_rx_file_sink_Mod.py
Python
mit
14,988
0.008607
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Test2 Baseband Rx File Sink # Generated: Mon Jun 12 17:02:58 2017 ################################################## if __name__ == '__main__': import ctypes import sys i...
ink") self.restoreGeometry(self.settings.value("geometry").toByteArray()) #
################################################# # Variables ################################################## self.samp_rate = samp_rate = 1.4e6 self.rx_gain = rx_gain = 30 self.freq = freq = 1e9 ################################################## # Blocks ...
svisser/palabra
tests/test_prefs.py
Python
gpl-3.0
3,065
0.001305
# This file is part of Palabra # # Copyright (C) 2009 - 2011 Simeon Visser # # Palabra 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. ...
BLACKLIST] = "/th
e/path" self._writeRead() self.assertEqual(preferences.prefs[constants.PREF_BLACKLIST], "/the/path") def testColor(self): preferences.prefs[constants.COLOR_PRIMARY_SELECTION + "_red"] = 1234 self._writeRead() self.assertEqual(preferences.prefs[constants.COLOR_PRIMARY_SELECTI...
danaoira/CurriculumGraphVisualizer
cgc.py
Python
mit
5,047
0.015257
# cgc.py - Curriculum Graph Converter - Dana Toribio import graphviz import os import re import subprocess import sys re_courses = re.compile('\w+\s\d+\w*') # regex for courses header = r'''from graphviz import Digraph g = Digraph('studyplan', filename='studyplan.gv') g.attr('graph', fontname='Helvetica') g.attr('no...
se) and ('--' in line): trk_electives = trk_electives + 'c2' + coreq_edge(course[0], course[1], False
) elif (course): trk_electives = trk_electives + 'c2' + node(course[0]) elif (write_to is 'suggestions') and course: suggestions = suggestions + 'g' + node(course[0]) else: pass nf.write(header + '\n') nf.write(legend + '\n') nf.write(req_electives + '\n') nf.write(trk_electives + '\n') nf.write(suggestions...
wotek/response-builder
docs/conf.py
Python
mit
8,236
0.006192
# -*- coding: utf-8 -*- # # Response Builder documentation build configuration file, created by # sphinx-quickstart on Wed Jan 29 11:43:14 2014. # # This file is execfile()d with the current direct
ory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in anoth...
ctory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a min...
wangpanjun/doit
doc/tutorial/cmd_from_callable.py
Python
mit
228
0.004386
from doit.action import CmdAct
ion def task_hello(): """hello cmd """ def create_cmd_string(): return "echo hi" return { 'actions': [CmdAction(create_cmd_string)], 'verbosity':
2, }
ostree/plaso
plaso/parsers/winevt.py
Python
apache-2.0
7,068
0.005801
# -*- coding: utf-8 -*- """Parser for Windows EventLog (EVT) files.""" import pyevt from plaso import dependencies from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import specification from plaso.parsers import interface from plaso.parsers import manager...
ME, display_name, exception)) for record_index, evt_record in enumerate(evt_file.records): try: self._ParseRecord(parser_mediator, record_index, evt_record) except IOError as exception: parser_mediator.ProduceParseError( u'unable to parse event record: {0:d} with error: {1:s...
record_index, exception)) for record_index, evt_record in enumerate(evt_file.recovered_records): try: self._ParseRecord( parser_mediator, record_index, evt_record, recovered=True) except IOError as exception: parser_mediator.ProduceParseError(( u...
CommonsDev/dataserver
scout/migrations/0003_auto__add_field_map_bucket.py
Python
agpl-3.0
8,430
0.008185
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Map.bucket' db.add_column(u'scout_map', 'bucket', self.gf('django.db.m...
s.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'position': ('django.contrib.gis.db.models.fields.PointField', [], {'geography': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }...
ango.db.models.fields.CharField', [], {'max_length': '30'}), 'icon_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'marker_color': ('django.db.models.fields.CharField', [], {'max_lengt...
izeigerman/accordion-bot
accordion/accordion_bot.py
Python
mit
7,225
0.002076
import urllib.request import random import re from accordion.history_storage import FileHistoryStorage from accordion.url_hash_provider import YouTubeUrlHashProvider from accordion.short_link_resolver import ShortLinkResolver from accordion.utils import calculate_hash from telegram.ext import (MessageHandler, Filters, ...
%02X' % (id & 0xFFFFFFFF) def _load_lines(self, file_name): try: with open(file_name, 'r') as f: lines = f.readlines() return [x.strip() for x in lines] except: return [] def _create_history_record(self, update): return { ...
message.from_user.username, 'originator_user_id': update.message.from_user.id } def _calculate_hash(self, payload): return calculate_hash(payload) def _url_payload(self, url): with urllib.request.urlopen(url) as response: return response.read() def _store_n...
knowitnothing/btcx
gui/qt/systray.py
Python
mit
1,337
0.000748
import PyQt4.QtGui as QG import PyQt4.QtCore as QC def chunk(seq, size): for i in xrange(0, len(seq), size): yield seq[i:i+size] class TextSysTray(object): def __init__(self, parent, text, ntray=2, **kwargs): self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)] self._curr_...
try: t = next(tc) except StopIteration: t = '' painter.dra
wText(pix.rect(), QC.Qt.AlignRight, t) painter.end() stray.setIcon(QG.QIcon(pix)) if __name__ == "__main__": app = QG.QApplication([]) win = QG.QDialog() trayicon = TextSysTray(win, '888.8', chunk_size=3) trayicon.show() win.show() app.exec_()
irskep/computerwords
computerwords/markdown_parser/parser_support.py
Python
bsd-3-clause
2,981
0.001342
from .exceptions import SourceException def log(text, *args, **kwargs): return # TODO: use logging print(text.format(*args, **kwargs)) class ParseError(SourceException): def __init__(self, token, msg=None): if msg is None: msg = "Unable to parse token {}".format(token.name) ...
urn result return (None, i) return parse_alternatives def sequence_rule(Cls, form, *sequence): def sequence_parser(tokens, i, config): (nodes, i) = parse_sequence(tokens, i, config, *sequence) if nodes: return (Cls(form, *nodes), i) else:
return None return sequence_parser def validate(validator, parse_fn): """validator may simply return False, or raise a ParseError""" def wrapper_fn(tokens, i, config): (node, i) = none_to_duple(parse_fn(tokens, i, config), i) if node and validator(node, config): return (nod...
xdevelsistemas/taiga-back-community
taiga/projects/userstories/migrations/0011_userstory_tribe_gig.py
Python
agpl-3.0
534
0.001873
# -*- coding: utf-8 -*- from __futu
re__ import unicode_literals from django.db import migrations, models import picklefield.fields class Migration(migrations.Migration): dependencies = [ ('userstories', '0010_remove_userstory_watchers'), ] operations = [ migrations.AddField( model_name='userstory', ...
s.PickledObjectField(editable=False, null=True, default=None, verbose_name='taiga tribe gig', blank=True), ), ]
dtschan/weblate
weblate/trans/tests/test_angularjs_checks.py
Python
gpl-3.0
3,834
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2016 Michal Čihař <michal@cihar.com> # Copyright © 2015 Philipp Wolfer <ph.wolfer@gmail.
com> # # This file is part of Weblate <https://weblate.org/> # # 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 the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General ...
saltyrtc/saltyrtc-server-python
saltyrtc/server/util.py
Python
mit
11,300
0.000442
""" This module provides utility functions for the SaltyRTC Signalling Server. """ # noinspection PyUnresolvedReferences from typing import Coroutine # noqa from typing import ( Any, Awaitable, Callable, List, Mapping, Optional, TypeVar, cast, ) import asyncio import binascii import li...
ional[logbook.compat.RedirectLoggingHandler] _logger_convert_level_handler = None # type: Optional[logbook.compat.L
oggingHandler] try: # noinspection PyUnresolvedReferences import logbook except ImportError: class _Logger: """ Dummy logger in case :mod:`logbook` is not present. """ def __init__(self, name: str, level: Optional[int] = 0) -> None: self.name = name s...
tedkulp/bossogg
boss3/xmlrpc/Util.py
Python
gpl-2.0
1,506
0.025896
#Boss Ogg - A Music Server #(c)2003 by Ted Kulp (wishy@comcast.net) #This project's homepage is: http://bossogg.wishy.org # #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 L...
erver. Parameters: * None Returns: * Struct * version - string * name - string """ def handleRequest(self, cmd, argstuple): session = Session() args = [] fo
r i in argstuple: args.append(i) if (session.hasKey('cmdint')): cmdint = session['cmdint'] if cmd == "version": return cmdint.util.version() # vim:ts=8 sw=8 noet
tijko/bluebird
setup.py
Python
mit
639
0.004695
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup, Extension, find_packages except ImportError: from distutils.core import setup, Extension import sys, platform if platform.system() != 'Linux': print('Invalid Platform, must be Linux-based system...exiting setup') sys.ex...
nternals', install_requires=['pyelftools'], py_modules=['bluebird'], ext_modules=[Extension('bluebird_cext', sources=['bluebi
rd_cext/bluebird_cext.c'])] )
Huyuwei/tvm
python/tvm/autotvm/task/topi_integration.py
Python
apache-2.0
19,668
0.003254
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
or tracing self.func_to_reflection = { topi.nn.conv2d: lambda x: setattr(topi.nn, 'conv2d', x), topi.nn.conv2d_NCHWc: lambda x: setattr(topi.n
n, 'conv2d_NCHWc', x), topi.nn.conv2d_NCHWc_int8: lambda x: setattr(topi.nn, 'conv2d_NCHWc_int8', x), topi.nn.depthwise_conv2d_nchw: lambda x: setattr(topi.nn, 'depthwise_conv2d_nchw', x), topi.nn.group_conv2d_nchw: lambda x: setattr(topi.nn, 'group_conv2d_nchw', x), ...
funbaker/astropy
astropy/units/format/console.py
Python
bsd-3-clause
2,766
0.000362
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "Console" unit format. """ from . import base, core, utils class Console(base.Base): """ Output-only format for to display pretty formatting at the console. For example:: >>> import astro...
mpose().to_string('console')) # doctest: +FLOAT_CMP m^2 kg 2.1798721*10^-18 ------ s^2 """ _times = "*" _line = "-" @classmethod def _get_unit_name(cls, unit): return unit.get_format_name('console')
@classmethod def _format_superscript(cls, number): return '^{0}'.format(number) @classmethod def _format_unit_list(cls, units): out = [] for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: out.ap...
googlemaps/openapi-specification
dist/snippets/maps_http_geocode_winnetka/maps_http_geocode_winnetka.py
Python
apache-2.0
300
0.01
#
[START maps_http_geocode_winnetka] import requests url = "https://maps.googleapis.com/maps/api/geocode/json?address=Winnetka&key=YOUR_API_KEY" payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload) print(response.text) # [END maps_http_geocode_winnetk
a]
iulian787/spack
var/spack/repos/builtin/packages/r-philentropy/package.py
Python
lgpl-2.1
1,356
0.002212
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RPhilentropy(RPackage): """Computes 46 optimized distance and similarity measures for comp...
org/src/contrib/Archive/philentropy" version('0.4.0', sha256='bfd30bf5635aab6a82716299a87d44cf96c7ab7f4ee069843869bcc85c357127') depends_on('r@3.1.2:', type=('build', 'run')) depend
s_on('r-rcpp', type=('build', 'run')) depends_on('r-dplyr', type=('build', 'run')) depends_on('r-kernsmooth', type=('build', 'run'))
smallyear/linuxLearn
salt/salt/states/postgres_group.py
Python
apache-2.0
7,913
0.000126
# -*- coding: utf-8 -*- ''' Management of PostgreSQL groups (roles) ======================================= The postgres_group module is used to create and manage Postgres groups. .. code-block:: yaml frank: postgres_group.present ''' from __future__ import absolute_import # Import Python libs # Import s...
**db_args) else: cret = None if cret: ret['comment'
] = 'The group {0} has been {1}d'.format(name, mode) if update: ret['changes'][name] = update elif cret is not None: ret['comment'] = 'Failed to create group {0}'.format(name) ret['result'] = False else: ret['result'] = True return ret def absent(name, ...
dotoscat/Polytank-ASIR
polytanks/ogf4py3/component.py
Python
agpl-3.0
4,129
0.00557
# ogf4py3 # Copyright (C) 2017 Oscar Triano @cat_dotoscat # 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 License, or # (at your option) any later version. # Th...
platform (Entity or None): This is the last platform which this entity's component has touched. touch_floor (Bool): Tells if *platform* is not None. """
FOOT = 1000 PLATFORM = 1001 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.platform = None @property def touch_floor(self): return self.platform is not None def reset(self): self.platform = None @stati...
craigcitro/pydatalab
tests/bigquery/api_tests.py
Python
apache-2.0
15,440
0.006412
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file exc
ept # in compliance with
the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See ...
smallyear/linuxLearn
salt/salt/modules/redismod.py
Python
apache-2.0
10,610
0
# -*- coding: utf-8 -*- ''' Module to provide redis functionality to Salt .. versionadded:: 2014.7.0 :configuration: This module requires the redis python module and uses the following defaults which may be overridden in the minion configuration: .. code-block:: yaml redis.host: 'localhost' redis.port: ...
if not host: host = __salt__['config.option']('redis.host') if not port: port = __salt__['config.option']('redis.port') if not db: db = __salt__['config.option']('redis.db') if not password: password = __salt__['config.option']('
redis.password') return redis.StrictRedis(host, port, db, password) def bgrewriteaof(host=None, port=None, db=None, password=None): ''' Asynchronously rewrite the append-only file CLI Example: .. code-block:: bash salt '*' redis.bgrewriteaof ''' server = _connect(host, port, db...
manicmaniac/headlessvim
headlessvim/process.py
Python
mit
3,571
0
#!/usr/bin/env python # -*- coding:utf-8 -*- """ .. note:: This module is not designed to be used by user. """ import contextlib import distutils.spawn import fcntl import os import pty import select import subprocess class Process(object): """ A class representing a background *Vim* process. """ de...
elf._stdin.closed:
self._stdin.close() @contextlib.contextmanager def _close(self): self._close_stream() yield self._process.wait() def _make_nonblock(self, fd): fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
CanonicalLtd/landscape-client
landscape/client/monitor/tests/test_service.py
Python
gpl-2.0
3,091
0
from mock import Mock from landscape.lib.testing import FakeReactor from landscape.client.tests.helpers import ( LandscapeTest, FakeBrokerServiceHelper) from landscape.client.monitor.config import MonitorConfiguration, ALL_PLUGINS from landscape.client.monitor.service import MonitorService from landscape.clien...
terinfo import ComputerInfo from landscape.client.monitor.loadaverage import LoadAverage class MonitorServiceTe
st(LandscapeTest): helpers = [FakeBrokerServiceHelper] def setUp(self): super(MonitorServiceTest, self).setUp() config = MonitorConfiguration() config.load(["-c", self.config_filename]) class FakeMonitorService(MonitorService): reactor_factory = FakeReactor ...
cessor/galena
src/galena/moment.py
Python
lgpl-3.0
1,283
0
import datetime class Duration(object): SECOND = 1 MINUTE = 60 * SECOND HOUR = 60 * MINUTE DAY = 24 * HOUR UNITS = [DAY, HOUR, MINUTE, SECOND] def __init__(self, seconds): self._seconds = seconds def _unit_values(self): value = self._seconds for unit in self.UNITS...
%d_%H-%M' def __init__(self, datetime): self._datetime = datetime @classmethod def now(cls): return Moment(datetime.datetime.now()) @classmethod def from_string(cls, string): date = datetime.datetime.strptime(string, Moment.PATTERN) return Moment(date) def __s...
>' % str(self) def __sub__(self, other): seconds = (self._datetime - other._datetime).total_seconds() return Duration(seconds)
russellmayhew/satchmo
satchmo/apps/payment/modules/purchaseorder/forms.py
Python
bsd-3-clause
1,253
0.005587
from django import forms from django.core.exceptions import ImproperlyConfigured from payment import signals from payment.forms import SimplePayShipForm from payment.modules.purchaseorder.models import PurchaseOrder from satchmo_utils import app_enabled from signals_ahoy import signals class PurchaseorderPayShipForm(S...
payment.modules.purchaseorder in your INSTALLED_APPS') super(PurchaseorderPayShipForm, self).__init__(*args, **kwargs) def save(self, request, cart, contact, payment_module): """Save the order and the po information for this orderpayment""" signals.form_presave.send(PurchaseorderPayShi...
et('po_number', ''), order=self.order) po.save() self.purchaseorder = po signals.form_postsave.send(PurchaseorderPayShipForm, form=self)
mkhuthir/learnPython
Book_learning-python-r1.1/ch10/regex/entries/admin.py
Python
mit
443
0
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Entry @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('Regular Expression', {'fields': ['pattern', 'test_string']}), ('Other Information', {'fields': ['user', 'date_added']}), ...
tern', 'test_string', 'user') list_filter = ['user'] sear
ch_fields = ['test_string']
AuthEceSoftEng/rnn2source
src/sample-labeled.py
Python
mit
5,387
0.003341
import argparse import numpy as np import pickle import time import jsbeautifier from pygments.lexers.javascript import JavascriptLexer from pygments.token import Token from utils import build_labeled_model, temp typoes = {Token.Literal.String.Regex: 'r', Token.Keyword: 'k', Token.Literal.String: 's', Toke...
produced_file.write(jsbeauti
fier.beautify(text, opts)) print 'printed file' sampled[:] = [] sampled_labels[:] = [] break if len(sampled) > 15000: char_in = np.zeros((1, 1, vocab_size)) char_in[0, 0, 1] = 1 label_in = np.zeros((1, 1, label_size)) ...
landlab/landlab
tests/components/vegetation_dynamics/test_vegetation_dynamics.py
Python
mit
3,024
0.000331
""" Unit tests for \ landlab.components.vegetation_dynamics.vegetation_dynamics """ import numpy as np import pytest from numpy.testing import assert_array_almost_equal (_SHAPE, _SPACING, _ORIGIN) = ((20, 20), (10e0, 10e0), (0.0, 0.0)) _ARGS = (_SHAPE, _SPACING, _ORIGIN) def test_name(veg): assert veg.name =...
E[0] - 1) * _SPACING[0] def test_field_getters(veg): for name in veg.grid["node"]: field = veg.grid["node"][name] assert isinstance(field, np.ndarray) assert field.shape == ( veg.grid.number_of_node_rows * veg.grid.nu
mber_of_node_columns, ) for name in veg.grid["cell"]: field = veg.grid["cell"][name] assert isinstance(field, np.ndarray) assert field.shape == ( veg.grid.number_of_cell_rows * veg.grid.number_of_cell_columns, ) with pytest.raises(KeyError): veg.grid...
suyashphadtare/test
erpnext/accounts/doctype/payment_tool/test_payment_tool.py
Python
agpl-3.0
6,947
0.026918
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest, frappe, json from frappe.utils import flt test_dependencies = ["Item"] class TestPaymentTool(unittest.TestCase): def test_make_jo...
e_voucher(self, test_record, args): doc = frappe.copy_
doc(test_record) doc.update(args) doc.insert() doc.submit() return doc def create_against_jv(self, test_record, args): jv = frappe.copy_doc(test_record) jv.get("entries")[0].update(args) if args.get("debit"): jv.get("entries")[1].credit = args["debit"] elif args.get("credit"): jv.get("entries")[...
zenoss/pywbem
pywbem/_nocasedict.py
Python
lgpl-2.1
19,000
0
# # (C) Copyright 2003-2007 Hewlett-Packard Development Company, L.P. # (C) Copyright 2006-2007 Novell, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the ...
be preserved when adding them to the new dictionary. """ # The internal dictionary, with lower case keys. An item in this dict # is the tuple (original key, value). self._data = OrderedDict() # Flag indicating whether unnamed keys (a key of `None`) is allowed. ...
Can be set to allow unnamed keys. self.allow_unnamed_keys = False # In by far the most cases, NocaseDict objects are created without # any init parameters. # Step 1: Add a single positional argument if args: if len(args) > 1: raise TypeError( ...
gradiuscypher/twitter_gradiusbot
mention_processing.py
Python
mit
657
0
import datetime def road_to_10k(tweet_list, author): status_count = author.statuses_count tweets_today = len(tweet_list) tweets_remaining = 10000 - status_count last_day = datetime.datetime(2014, 12, 31) today = datetime.datetime.now() days_remaining = (last_day - today).days + 1 tweets_pe...
aining reply = "@" + author.name + ":\n" reply += "Sent: " + str(status_count) + " tweets so far.\n"
reply += "Sent: " + str(tweets_today) + " tweets today.\n" reply += "Remaining: " + str(days_remaining) + " days.\n" reply += "Tweets/Day: " + str(tweets_per_day) return reply
FacundoAcevedo/gondolero
gondolero/web/urls.py
Python
gpl-3.0
2,275
0.00044
from django.conf.urls import url from django.contrib.auth import views as auth_views from django.views.generic import Temp
lateView from . import views app_name = 'web' urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="front.html"), name='front'), url(r'^index$', views.IndexView.as_view(), name='index'), # Accounts url('^accounts/login/', auth_views.l
ogin, {'template_name': 'login.html'}, name="login"), url('^accounts/logout/', auth_views.logout, name="logout"), url('^accounts/change/', auth_views.password_change, name="password_change"), url('^accounts/register/', views.UserRegister.as_view(), name="register"), # url...
yt4766269/pytorch_zoo
LeNet/train.py
Python
apache-2.0
1,456
0.005495
from __future__ import print_function import torch import torch.nn as nn from torch.autograd import Variable import matplotlib.pyplot as plt import torch.optim as optim import read_image from Net import Net from CONSTANT import TRAIN_BATCH_SIZE, TEST_BATCH_SIZE, EPOCH, CALCULATE_LOSS from tensorboard_logger import con...
t.cuda() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(params=net.parameters(),lr = 1e-2, momentum=0.9) plt.figure(num=1) plt_x = [] plt_y = [] configure('runs/run-1') for epoch in range(32): running_loss = 0.0 for i, data in enumerate(read_image.trainloader): inputs, labels = data ...
s = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.data[0] if i % CALCULATE_LOSS == CALCULATE_LOSS - 1: # print every 100 mini-batches print('[%d, %5d] loss: %.5f' % (epoch , i, running_loss / CALCULATE_LOSS)) ...
ares/robottelo
robottelo/cli/base.py
Python
gpl-3.0
16,309
0
# -*- encoding: utf-8 -*- """Generic base class for cli hammer commands.""" import logging import re from robottelo import ssh from robottelo.cli import hammer from robottelo.config import settings class CLIError(Exception): """Indicates that a CLI command could not be run.""" class CLIBaseError(Exception): ...
ostree-branch Manipulate ostree branches package Manipulate packages. package-group Manipulate package groups partition-table Manipulate partition tables. ping Get the status of the server ...
arch puppet modules. puppet-module View Puppet Module details. report Browse and read reports. repository Manipulate repositories repository-set Manipulate repository sets on the server role ...
maoaiz/django-admin-conf-vars
django_admin_conf_vars/migrations/0005_auto_20180725_1624.py
Python
bsd-3-clause
756
0.002646
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_admin_conf_vars', '0004_configurationvariable_description'), ] operations = [ migrations.AlterField( mode...
migrations.AlterField( model_name='configurationvariable', name='editable', field=models.BooleanField(default=True, help_text='The variable can be edited in the admin or
not'), ), ]
Perlence/elaborate-lastfm-charts
elaboratecharts/app.py
Python
bsd-3-clause
246
0
fr
om flask import Flask from . import config from . import ElaborateCharts app = Flask(__name__) app.config['SECRET_KEY'] = config.SECRET_KEY charts = ElaborateCharts(app) if __name__ == '__main__': app.run(host='12
7.0.0.1', debug=True)
dantebarba/docker-media-server
plex/Subliminal.bundle/Contents/Libraries/Shared/guessit/plugins/transformers.py
Python
gpl-3.0
9,454
0.005183
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
perty def name(self): return self.__class__.__name__ def supported_properties(self): return {} def second_pass_options(self, mtree, options=None):
return None def should_process(self, mtree, options=None): return True def process(self, mtree, options=None): pass def post_process(self, mtree, options=None): pass def register_arguments(self, opts, naming_opts, output_opts, information_opts, webservice_opts, other_o...
mezz64/home-assistant
homeassistant/components/climacell/weather.py
Python
apache-2.0
17,080
0.001171
"""Weather component that handles meteorological data for your location.""" from __future__ import annotations from abc import abstractmethod from collections.abc import Mapping from datetime import datetime from typing import Any, cast from pyclimacell.const import ( CURRENT, DAILY, FORECASTS, HOURLY...
tity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_API_VERSION, CONF_NAME, LENGTH_INCHES, LENGTH_MILES, PRESSURE_INHG, SPEED_KILOMETERS_PER_HOUR, SPEED_MILES_PER_HOUR, TEMP_FAHRENHEIT, ) from homeassistant.core import HomeAssistant from ho...
platform import AddEntitiesCallback from homeassistant.helpers.sun import is_up from homeassistant.util import dt as dt_util from homeassistant.util.speed import convert as speed_convert from . import ClimaCellDataUpdateCoordinator, ClimaCellEntity from .const import ( ATTR_CLOUD_COVER, ATTR_PRECIPITATION_TYPE...
zentralopensource/zentral
zentral/contrib/mdm/payloads.py
Python
apache-2.0
6,407
0.001873
import logging import plistlib from django.http import HttpResponse from django.urls import reverse from zentral.conf import settings from zentral.utils.certificates import split_certificate_chain from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier from zentral.utils.payloads import sign_pa...
profile_response(data, filename): response = HttpResponse(data, content_type="application/x-apple-aspen-config") response['Content-Disposition'] = 'attachment; filename="{}.mobileconfig"'.format(filename) return response def build_profile(display_name, suffix, content, payload_t
ype="Configuration", payload_description=None, sign=True, encrypt=False): profile = {"PayloadUUID": generate_payload_uuid(), "PayloadIdentifier": get_payload_identifier(suffix), "PayloadVersion": 1, "PayloadDisplayName": display_name, "Pa...
chaosk/trinitee
trinitee/lib/unittest.py
Python
bsd-3-clause
1,028
0.027237
from django.test import TestCase as DjTestCase """ Based on http://stackoverflow.com/questions/2897609/#4934325 """ class TestCase(DjTestCase): def assertMessageCount(self, response, expect_num): """ Asserts that exactly the given number of messages have been sent. """ actual_num = len(response.context['mes...
: %s != %s' % (msg.level, level)) return else: messages_str = ", ".join
('"%s"' % m for m in messages) self.fail('No message contained text "%s", messages were: %s' % (text, messages_str))
andrew-christianson/Polyglot-Euler
Problem 18.py
Python
mit
2,376
0.002525
import random def read_tri(flike): tri_arr = [] for line in flike: line = line.strip("\n") tri_arr.append([int(s) for s in line.split(" ")]) return tri_arr # def valid_path(path): # if path[0] != 0: # return False # for idx, pidx in enumerate(path[1:]): # if not (pi...
path = [initial_idx] # for idx, row in enumerate(reversed(tri_arr)): # if idx == 0: # continue # prev_i = idx - 1 # prev_p = path[prev_i] # if prev_p >= len(row): # path.append(len(row) - 1) # elif prev_p == 0: # p
ath.append(0) # else: # if row[prev_p] > row[prev_p - 1]: # path.append(prev_p) # elif row[prev_p] == row[prev_p - 1]: # path.append(random.choice([prev_p, prev_p-1])) # else: # path.append(prev_p-1) # return reversed(path) ...
release-engineering/product-definition-center
pdc/apps/auth/admin.py
Python
mit
448
0
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Red Hat # Licensed un
der The MIT License (MIT) # http://opensource.org/licenses/MIT # from django.contrib import admin from . import models class UserAdmin(admin.ModelAdmin): list_display = ('username', 'last_connected') admin.site.register(models.User, UserAdmin) admin.site.reg
ister(models.Resource) admin.site.register(models.ResourcePermission) admin.site.register(models.ResourceApiUrl)
nat13ejo/garn
garn/__init__.py
Python
mit
2,328
0.002577
""" Garn is a small Kwant_ based package for doing effective mass calculations on two models of contact geometry effects on semiconductor nanowires. This documentation is of the software and how it is used and will not cover the physics behind the simulations. A formal introduction to the pr
oject is publiched in `Numerical simulations of contact geometry effects on transport properties of semiconductor nanowires <http://lup.lub.lu.se/student-papers/record/8878322>`_. .. _Kwant: http://kwant-project.org/ Using Garn ---------- As any python package when the package is in your python path type .. code-bl...
l to any of the two wire classes :class:`~garn.Wire3D` or :class:`~garn.Wire2D`. In this case :class:`~garn.Wire3D`. .. code-block:: Python wire = garn.Wire2D(base=3, wire_length=30, lead_length=5, identifier="test-2D", step_length=1) Now you can plot the system with the :meth:`~garn.s...
BestSonny/examples
word_language_model/main.py
Python
bsd-3-clause
7,524
0.002658
import argparse import time import math import torch import torch.nn as nn from torch.autograd import Variable import data import model parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model') parser.add_argument('--data', type=str, default='./data/penn', help='...
hidden) model.zero_grad() output, hidden = model(data, hidden) loss = criterion(output.view(-1, ntokens), targets) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. torch.nn.utils.clip_grad_norm(model.parameters(), args.clip...
p.data.add_(-lr, p.grad.data) total_loss += loss.data if batch % args.log_interval == 0 and batch > 0: cur_loss = total_loss[0] / args.log_interval elapsed = time.time() - start_time print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.2f} | ms/batch {:5.2f} | ' ...
poppingtonic/call-power
call_server/political_data/countries/us_state.py
Python
agpl-3.0
3,011
0.001993
import random from sunlight import openstates, response_cache from . import DataProvider from ...campaign.constants import (TARGET_CHAMBER_BOTH, TARGET_CHAMBER_UPPER, TARGET_CHAMBER_LOWER, ORDER_IN_ORDER, ORDER_SHUFFLE, ORDER_UPPER_FIRST, ORDER_LOWER_FIRST) class USStateData(DataProvider): KEY_OPENSTATE...
ates:{id}' def __init__(self,
cache, api_cache=None): self.cache = cache if api_cache: response_cache.enable(api_cache) def load_data(self): "Not needed, data provided over Sunlight OpenStates API, and cached on response" pass def cache_set(self, key, val): if hasattr(self.cache, 'set'):...