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
scalien/keyspace
test/concurrency/common.py
Python
agpl-3.0
1,105
0.028959
import sys import time import sys num = 1000 print_granularity = 1000 count = 0 first = True start = 0 gran_start = 0 min = 0 max = 0 avg = 0 sum = 0 total = 0 def set_print_granularity(p): global print_gra
nularity print_granularity = p print("%s: print granularity = %s" % (sys.argv[0], print_granularity)) def loop_count(): global min, max, avg, total, gran_start, sum, start, first, count now = round(time.time()
* 1000) if not first: elapsed = now - start if elapsed < min: min = elapsed if elapsed > max: max = elapsed sum = sum + elapsed start = now count = count + 1 total = total + 1 if count % print_granularity == 0 and not first: gran_elapsed = now - gran_start gran_start = now avg = sum / print_granulari...
brandicted/nefertari-guards
tests/test_nefertari_sqla.py
Python
apache-2.0
512
0
from
mock import patch, Mock from nefertari_guards.nefertari_sqla import ACLType class TestACLType(object): @patch.object(ACLType, 'stringify_acl') @patch.object(ACLType, 'validate_acl') def test_process_bind_param(self, mock_validate, mock_str): mock_str.return_value = [[1, 2, [3]]] obj = A...
[1, 2, [3]]])
Gateswong/GatesBlog
blog/blogs/routes.py
Python
mit
1,892
0.001057
from flask import (render_template, redirect, url_for, request ) from sqlalchemy.orm.exc import ( NoResultFound, ) from . import blogs from ..models.post import Post from ..utils import (load_page_meta, NotSetup, ...
request.args.get("tags", None) if tags: tags = tags.split(",") category = reques
t.args.get("category", "") posts = Post.query_page_of_posts(skip=(page_num - 1) * 25, limit=25, tags=tags, category=category) return render_template("blogs/index.html", pos...
kacperadach/draftkings_points_scripts
NFL_Draftkings/ConvertToDraftKings.py
Python
mit
1,778
0.005624
from constants import OFFENSIVE_SCORING_MULTIPLIERS, DEFENSIVE_SCORING_MULTIPLIERS def convert_to_DK(data): if data['position'] == 'DEF': return _get_defensive_scoring(data['stats']) else: return _get_offensive_scoring(data['stats']) def _get_offensive_scoring(data): return round(_get_offe...
ta.items(): try: points += int(val) * OFFENSIVE_SCORING_MULTIPLIERS[int(key)] except KeyError: continue return points def _get_defensive_multiplier_scoring(data): points = 0 for key, val in data.items(): try: points += int(val) * DEFENSIVE_SCORING...
continue return points def _get_offensive_conditional_scoring(data): points = 0 if '5' in data and int(data['5']) >= 300: points += 3 if '14' in data and int(data['14']) >= 100: points += 3 if '21' in data and int(data['21']) >= 100: points += 3 return points def _get_...
sgallagher/reviewboard
reviewboard/scmtools/svn/subvertpy.py
Python
mit
10,969
0
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import logging import os from datetime import datetime try: from subvertpy import ra, SubversionException, __version__ from subvertpy.client import Client as SVNClient, api_version, get_config has_svn_backend = (__version__ ...
with 'start' being the most recent commit in the range. If 'start' is not specified, then it will default to 'HEAD'. If 'end' is not specified, it will default to '1'. To limit the commits to the given path, not factoring in history from any branch operations, set 'limit_to_path' ...
mit = { 'revision': six.text_type(revision), } if 'svn:date' in props: commit['date'] = datetime.strptime(props['svn:date'], '%Y-%m-%dT%H:%M:%S.%fZ') if 'svn:author' in props: commit[...
westernx/mayatools
docs/conf.py
Python
bsd-3-clause
8,898
0.006631
# -*- coding: utf-8 -*- # # mayatools documentation build configuration file, created by # sphinx-quickstart on Wed Sep 19 09:51:46 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
= None # Output file base name for HTML
help builder. htmlhelp_basename = 'mayatoolsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for t...
dios-game/dios-cocos
src/oslibs/cocos/cocos-src/tools/cocos2d-console/plugins/plugin_jscompile/__init__.py
Python
mit
12,716
0.005033
#!/usr/bin/python # ---------------------------------------------------------------------------- # cocos "jscompile" plugin # # Copyright 2013 (C) Intel # # License: MIT # ---------------------------------------------------------------------------- ''' "jscompile" plugin for cocos command line tool ''' __docformat__ =...
""" index = -1 for el in l: if jsfile.rfind(el) != -1: # print "index:"+str(index+1)+", el:"+el return index+1
index = index + 1 return -1 def js_filename_pre_order_compare(self, a, b): return self._js_filename_compare(a, b, self._pre_order, 1) def js_filename_post_order_compare(self, a, b): return self._js_filename_compare(a, b, self._post_order, -1) def _js_filename_compare(self, a,...
BeenzSyed/tempest
tempest/api/object_storage/test_container_sync.py
Python
apache-2.0
5,432
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
hod def setU
pClass(cls): super(ContainerSyncTest, cls).setUpClass() cls.containers = [] cls.objects = [] # Default container-server config only allows localhost cls.local_ip = '127.0.0.1' # Must be configure according to container-sync interval container_sync_timeout = \ ...
mekanix/geonode
geonode/base/management/commands/restore.py
Python
gpl-3.0
15,906
0.004149
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 ...
Node application data' option_list = BaseCommand.option_list + ( make_option( '-i', '--ignore-errors', action='store_true', dest='ignore_errors', default=False, help='Stop after any errors are encountered.'), make_option( ...
default=False, help='Forces the execution without asking for confirmation.'), make_option( '--backup-file', dest='backup_file', type="string", help='Backup archive containing GeoNode data to restore.')) def handle(self, **options): ...
SamB/debian-codeville
Codeville/agent.py
Python
bsd-3-clause
8,321
0.001442
# Written by Ross Cohen # see LICENSE.txt for license information from bencode import bdecode, bencode from crypt import crypt from errno import EINTR import os try: import select except ImportError: import selectpoll as select import sha import socket import SRP from cStringIO import StringIO import struct A...
dentities = {} self.allow_shutdown = 0 return def listen_sock(self, auth_path, auth_file): if self.auth_file is not None: print 'Auth socket already set' return None self.auth_path = auth_path self.auth_file = auth_file sock = socket.socket...
sock) return sock def listen(self): if self.auth_file is None: print 'No socket to listen on' return 1 self.shutdown_flag = 0 while not self.shutdown_flag: try: sock_list = self.poll_obj.poll() except select.error, re...
catherinemoresco/feedme
static/bs4/builder/_htmlparser.py
Python
gpl-2.0
8,541
0.000937
"""Use the HTMLParser library to parse HTML files that aren't too bad.""" __all__ = [ 'HTMLParserTreeBuilder', ] from HTMLParser import ( HTMLParser, HTMLParseError, ) import sys import warnings # Starting in Python 3.2, the HTMLParser constructor takes a 'strict' # argument, which we'd like to s...
n, UnicodeDammit from bs4.builder import ( HTML, HTMLTreeBuilder, STRICT, ) HTMLPARSER = 'html.parser' class BeautifulSoupHTMLParser(HTMLParser): def handle_starttag(self, name, attrs): # XXX namespace self.soup.handle_starttag(name, None, None, dict(attrs)) def handle_endta...
self.soup.handle_endtag(name) def handle_data(self, data): self.soup.handle_data(data) def handle_charref(self, name): # XXX workaround for a bug in HTMLParser. Remove this once # it's fixed. if name.startswith('x'): real_name = int(name.lstrip('x'), 16) ...
aws-quickstart/taskcat
taskcat/_project_generator_runner.py
Python
apache-2.0
546
0.001832
# TODO delete this file after integrating with cli option parser # this is only here to illustrate generator's usage # run as: python path/to/runner.py <project_destination> # # pylint: skip-file import sys from
taskcat.project_generator import ( FilesystemService, ProjectConfiguration, ProjectGenerator, ) DESTINATION = sys.argv[1] CONFIG = ProjectConfiguration( "owner@example.com", "awesome_quicksta
rt", "quickstart", ["us-east-1", "us-west-2"] ) ProjectGenerator(CONFIG, DESTINATION, FilesystemService()).generate()
swift-lang/swift-e-lab
parsl/configs/theta_local_ipp_multinode.py
Python
apache-2.0
1,212
0.002475
from parsl.providers import CobaltProvider from parsl.launchers import AprunLauncher from parsl.config import Config from parsl.executors.ipp import IPyParallelExecutor from parsl.executors.ipp_controller import Controller # This is an example config, make sure to # replace the specific values below with the l...
ker_init='', # Input your worker_init if needed account='ALCF_ALLOCATION', # Please replace ALCF_ALLOCATION with your ALCF allocation cmd_timeout=60 ),
controller=Controller(public_ip='PUBLIC_IP'), # Please replace PUBLIC_IP with your public ip ) ], )
muranga/ataps
ataps/settings/prod.py
Python
unlicense
219
0
"""Production settings and globals.""" from os import envi
ron from common import * SERVER_EMAIL = EMAIL_HOST_USER SECRET_KEY = environ.get('SECRET_KEY', SECRET_KEY) ALLOWED_HOSTS = ['.herokuapp.com'] SEND_SM
S = True
schenc3/InteractiveROSETTA
InteractiveROSETTA/extensions.py
Python
gpl-2.0
5,948
0.003531
import sys import os.path import platform iRosetta_path = sys.argv[1] icons = [("cfg", "Rosetta Configuration File"), ("cst", "Constraints File"), ("ensb", "Ensemble Archive"), ("fasta", "FASTA Sequence"), ("gz", "Compressed GZ Archive"), ("irm", "InteractiveROSETTA Module"...
le", "Rosetta Design Palette"), ("scan", "Point Mutant Scan")] if (platform.system() == "Windows"): # We need to update the Windows registry # These changes probably won't take effect until the user logs back in import _winreg for icon, desc in icons: # Create filetype key regpa...
pass reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, regpath, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(reg_key, "", 0, _winreg.REG_SZ, icon + "_auto_file") _winreg.CloseKey(reg_key) # Create description for file type regpath = "Software\\Classes\\" + icon + "_auto_file" ...
migua1204/jikexueyuan
极客学院/BusStopBoard/node_modules/.3.4.0@node-gyp/gyp/pylib/gyp/MSVSSettings_test.py
Python
apache-2.0
65,937
0.000197
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the MSVSSettings.py file.""" import StringIO import unittest import gyp.MSVSSettings as MSVSSettings class TestSequence...
'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'CPreprocessOptions': 'a string1', 'DefaultCharType': '1', 'DLLDataFileName': 'a_file_name', 'EnableErrorChecks': '1', 'ErrorCheckAllocations': 'tru...
: 'true', 'ErrorCheckEnumRange': 'true', 'ErrorCheckRefPointers': 'true',
gangadharkadam/v5_erp
erpnext/accounts/report/accounts_payable/accounts_payable.py
Python
agpl-3.0
461
0.015184
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public Licen
se v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.accounts.report.accounts_receivable.accounts_receivable import ReceivablePayableReport def execute(filters=None): args = { "party_type": "Supplier", "naming_by":
["Buying Settings", "supp_master_name"], } return ReceivablePayableReport(filters).run(args)
unt-libraries/aubreylib
aubreylib/__init__.py
Python
bsd-3-clause
1,068
0
# Resource Representation reference dictionary (METS USE) USE = { 'high_res': 1, 'thumbnail': 2, 'med_res': 3, 'ocr': 4, 'bounding_box': 5, 'transcription': 6, 'translation': 7, 'zoom': 8, 'cdx': 9, 'square': 10, } # View method for mimetypes VIEW_TYPE_MIMETYPES = { 'image/p...
'text', 'text/xml': 'xml', 'application/zip': 'file', 'video/x-flv': 'video',
'video/mp4': 'video', None: 'file', } EMAIL_REGEX = r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}' # Metadata location tuple. Used to specify potential source systems # for metadata files. METADATA_LOCATIONS = () # Static file location tuple. Used to specify potential source # systems for static files. STAT...
danyul/flaskmogrify
setup.py
Python
mit
1,927
0.000519
import re from setuptools import find_packages, setup try: import pypandoc readme = pypandoc.convert('README.md', 'rst') history = pypandoc.convert('CHANGELOG.md', 'rst') except (ImportError, OSError): with open('README.md') as readme_file, \ open('CHANGELOG.md') as history_file: re...
g', url='https://github.com/danyul/flaskmogrify', packages=find_packages(), include_package_data=True, install_requires=requirements, li
cense="MIT", zip_safe=False, keywords='flask convert text transform ajax single page application', classifiers=[ 'Natural Language :: English', 'Programming Language :: Python :: 3.6', ], extras_require={ "dev": dev_requirements }, test_suite='tests', tests_re...
stxnext/intranet-open
src/intranet3/intranet3/models/client.py
Python
mit
2,225
0.008539
from pyramid.decorator import reify from sqlalchemy import Column, ForeignKey, orm, distinct from sqlalchemy.types import String, Integer from sqlalchemy import event from intranet3.models import Base, User, DBSession, Project class Client(Base): __tablename__ = 'client' id = Column(Integer, primary_key=True...
.filter(Project.active==True).all() emails = [] for emails_str in emails_cols: if emails_str[0]: emails.extend([ email.strip() for email in emails_str[0].split('\n') if '@' in email ]) return emails @event.listens_for(Client.coordinator_id,...
def after_set(target, value, oldvalue, initiator): """ Used for coordinators managment, see Project model""" if value != oldvalue: target.old_coordinator = oldvalue
ritstudentgovernment/PawPrints
auth/auth_backend.py
Python
apache-2.0
1,971
0.000507
""" auth_backend.py Peter Zujko (@zujko) Defines Django authentication backend for shibboleth. 04/05/17 """ from django.contrib.auth.models import User class Attributes(): EDU_AFFILIATION = 'urn:oid:1.3.6.1.4.1.4447.1.41' FIRST_NAME = 'urn:oid:2.5.4.42' LAST_NAME = 'urn:oid:2.5.4.4' USERNAME = 'urn:...
h user user = User.objects.get(username=username) except User.DoesNotExist: # If user does not exist in DB, Create a user object and save to DB user = User(username=username, email=username + "@rit.edu") user.set_unusable_password() ...
.format(first_name, last_name) user.profile.display_name = "{}{}".format( first_name[0], last_name[0]) # Set user Affiliation user.profile.has_access = 0 if 'Student' in affiliation: user.profile.has_access = 1 user.profile.sa...
Arafatk/sympy
sympy/printing/latex.py
Python
bsd-3-clause
72,271
0.001314
""" A Printer which converts an expression into its LaTeX equivalent. """ from __future__ import print_function, division from sympy.core import S, Add, Symbol from sympy.core.function import _coeff_isneg from sympy.core.sympify import SympifyError from sympy.core.alphabets import greeks from sympy.core.operations im...
pr): """ Returns True if the expression needs to be wrapped in brackets when passed as an argument to
a function, False otherwise. This is a more liberal version of _needs_brackets, in that many expressions which need to be wrapped in brackets when added/subtracted/raised to a power do not need them when passed to a function. Such an example is a*b. """ if not self._needs_bracke...
sbaechler/simpleshop
simpleshop/content.py
Python
bsd-3-clause
1,129
0.005314
import plata from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils.translatio
n import ugettext_l
azy as _ from feincms.admin.item_editor import FeinCMSInline from django import forms class ProductInline(FeinCMSInline): raw_id_fields = ('product',) class SingleProductTeaserContent(models.Model): product = models.ForeignKey(plata.product_model()) feincms_item_editor_inline = ProductInline class M...
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
Final_assignment/lib/sentimentAnalyzerVader.py
Python
mit
1,401
0.014276
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 27 16:23:07 2017 @author: user """ ## FOUND HERE http://www.nltk.org/howto/sentiment.html ## Source code http://www.nltk.org/_modules/nltk/sentiment/vader.html ## http://www.nltk.org/api/nltk.sentiment.html ## Hutto, C.J. & Gilbert, E.E. (2014). VAD...
is of Social Media Text. Eighth International Conference on ## Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014. ## http://www.postgresqltutorial.com/postgresql-python from nltk.sentiment.vader import SentimentIntensityAnalyzer import psycopg2 import sys reload(sys) #Prevents errors with utf-8 encoding not...
tencoding('utf8') def SentimentAnalyzer(tweets): sid = SentimentIntensityAnalyzer() #need to nltk.download() to use all the packages sentiment_tweets = [] #for i in range(10): for tweet in tweets: tweet_id = tweet[0] tweet_id = str(tweet_id) tweet_id = int(tweet_id) ...
claudep/translate
translate/storage/placeables/parse.py
Python
gpl-2.0
3,307
0.000907
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free
Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is 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 Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. """ Contains the ``parse`` function that parses normal strings into StringElem- based "rich" string element trees. """ i...
RLejolivet/MarioMakerLevelsBot
MarioMakerLevelsBot/MarioMakerLevelsBot/ui/window.py
Python
mit
18,935
0.003063
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'window.ui' # # Created: Tue Dec 22 17:18:58 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_MainWindow(object): def setupUi(se...
y_fakes_checkbox") self.verticalLayout_3.addWidget(self.hide_likely_fakes_checkbox) self.hide_potentially_checkbox = QtG
ui.QCheckBox(self.widget_3) self.hide_potentially_checkbox.setObjectName("hide_potentially_checkbox") self.verticalLayout_3.addWidget(self.hide_potentially_checkbox) self.subs_only_checkbox = QtGui.QCheckBox(self.widget_3) self.subs_only_checkbox.setObjectName("subs_only_checkbox") ...
Algomorph/AMBR
vgg_utils.py
Python
apache-2.0
6,177
0.002428
""" FeatExtractor is a feature extraction specialization of Net. """ import numpy as np import cv2 import caffe import time import getpass import os.path def transform_image(img, over_sample=False, mean_pix=[103.939, 116.779, 123.68], image_dim=256, crop_dim=224): # convert to BGR if len(img.shape) < 3 or i...
.extract(images) print('non-batch extraction time(s):', time.time() - start) start = time.time() feats2 = extractor.extract_batch(images) print('batch extraction time(s):', time.time() - start) print(len(feats1['fc6']), len(feats2['f
c6'])) for i in range(len(feats1['fc6'])): print feats1['fc6'][i].shape print(feats1['fc6'][i] == feats2['fc6'][i]).all()
carolinux/QGIS
python/utils.py
Python
gpl-2.0
18,015
0.002998
# -*- coding: utf-8 -*- """ *************************************************************************** utils.py --------------------- Date : November 2009 Copyright : (C) 2009 by Martin Dobias Email : wonder dot sk at gmail dot com ************************...
* *************************************************************************** """ __author__ = 'Martin Dobias' __date__ = 'November 2009' __copyright__ = '(C) 2009, Martin Dobias' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' ...
is.core import QGis, QgsExpression, QgsMessageLog, qgsfunction, QgsMessageOutput from qgis.gui import QgsMessageBar import sys import traceback import glob import os.path import ConfigParser import warnings import codecs import time import functools # ###################### # ERROR HANDLING warnings.simplefilter('de...
theovoss/BoggleSolver
bogglesolver/test/test_cli.py
Python
mit
548
0.001825
#!/usr/bin/env python """Test for the command line interface.""" import unittest from bogglesolver.cli import main class TestCli(unittest.TestCase): """Tests for the cli.""" def tes
t_main(self): """Verify 'bogglesolver' can be called.""" self.assertIs(None, main([])) def test_main_help(self): """Verify 'bogglesolver --help' can be requested.""" self.assertRaises(SystemExit, main, ['--help'])
self.assertRaises(SystemExit, main, ['-h']) if __name__ == '__main__': unittest.main()
jorisvandenbossche/DS-python-data-analysis
notebooks/_solutions/case2_observations_processing22.py
Python
bsd-3-clause
80
0.025
plot_da
ta_selection = plot_data[["plot", "decimalLongitude", "decimalLatitud
e"]]
likelyzhao/mxnet
example/rcnn/rcnn/core/loader.py
Python
apache-2.0
22,692
0.001895
import mxnet as mx import numpy as np from mxnet.executor_manager import _split_input_slice from rcnn.config import config from rcnn.io.image import tensor_vstack from rcnn.io.rpn import get_rpn_testbatch, get_rpn_batch, assign_anchor from rcnn.io.rcnn import get_rcnn_testbatch, get_rcnn_batch class TestLoader(mx.io...
def provide_label(self): return [(k, v.shape) for k, v in zip(self.label_name, self.label)] def reset(self): self.cur = 0 if self.shuffle: if self.aspect_grouping: widths = np.array([r['
width'] for r in self.roidb]) heights = np.array([r['height'] for r in self.roidb]) horz = (widths >= heights) vert = np.logical_not(horz) horz_inds = np.where(horz)[0] vert_inds = np.where(vert)[0] inds = np.hstack((np.rand...
Towdium/WebAPIs
webapi/__init__.py
Python
lgpl-3.0
471
0
f
rom flask import Flask, Response import webapi.unblock as lib_unblock import webapi.unsplash as lib_unsplash app = Flask(__name__) @app.route('/') def root(): return 'Welcome to towdium.me APIs' @app.route('/unsplash/<path:path>') def unsplash(path): data = lib_unsplash.request(path) return '' if data...
ck(filename): return lib_unblock.request(filename)
ezietsman/msc-thesis
spectroscopy/extracted/trailed_FT.py
Python
mit
1,182
0.021997
#!/usr/bin/python # Make a FT of every wavelength (column pixel) import pylab as pl import pyfits as pf import astronomy as ast import os files = os.listdir(os.curdir) ff = [] for f in files: name,ext = os.path.splitext(f) if name[:2] == 'EC': ff.append(f) specgram = [] t = [] trailed_ft = [] for s...
ad['CRVAL1'] step = head['CDELT1'] length = head['NAXIS1'] xx = start + pl.arange(0,length)*step # hydrogen alpha w1 = xx > 6523 w2 = xx < 6603 data = pf.getdata(spec) t.append(head['HJD']) specgram.append(pf.getdata(spec)[w1*w2]) allspec = None specgram = pl.array(specgram) ...
t i pl.figure() pl.imshow(trailed_ft,aspect='auto',vmin=0,vmax=0.03e-14,\ cmap=pl.cm.jet,extent=(0.0,4000.0,6523,6603),origin='lower') #pl.gray() pl.colorbar() pl.xlabel('Frequency (c/d)') pl.ylabel('Wavelength') pl.title('Trailed Fourier Transform') pl.savefig('trailed_ft2.png') pl.show()
ObsidianBlk/GemRB--Unofficial-
gemrb/GUIScripts/bg1/CharGenGui.py
Python
gpl-2.0
11,889
0.050046
import GemRB from GUIDefines import * from ie_stats import * import CharGenCommon import GUICommon import Spellbook import CommonTables import LUCommon import LUProfsSelection def Imprt(): GemRB.SetToken("NextScript","CharGen") GemRB.SetNextScript("ImportFile") #import return def setPlayer(): MyChar = GemRB.GetVa...
ounds(): MyChar = GemRB.GetVar ("Slot") GemRB.Se
tPlayerSound(MyChar,"") #name def unsetName(): MyChar = GemRB.GetVar ("Slot") GemRB.SetPlayerName (MyChar, "", 0) def getName(TextAreaControl): MyChar = GemRB.GetVar ("Slot") name = GemRB.GetPlayerName(MyChar) if(name != ""): TextAreaControl.Append(name + "\n") #divine spells def setDivineSpells(): MyChar ...
feigaochn/leetcode
p77_combinations.py
Python
mit
567
0.001764
# author: Fei Gao # # Combinations # # Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. # For example, # If n = 4 and k = 2, a solution is: # [ # [2,4], # [3,4], # [2,3], # [1,2], # [1,3], # [1,4], # ] import itertools class Solution: # @return a list of lists...
def combine(self, n, k): return [list(p) for p in itertools.combinations(range(1, n + 1), k)] def main
(): solver = Solution() print(solver.combine(4, 2)) pass if __name__ == '__main__': main() pass
approximata/edx_mit_6.00.2x
pset1/ps1_partition.py
Python
mit
769
0.010403
#From codereview.stackexchange.com def partitions(set_): if not set_: yield [] return for i in range(2**len(set_)//2): parts = [set(), set()] for item in set_: parts[i&1].add(item) i >>= 1 for b in partitions(parts[1]): ...
that will fetch all of the available # partitions for you to use for your brute force algorithm. def get_partitions(set_): for partition in partitions(set_): yield [list(elt) for elt in partition] ### Uncomment the foll
owing code and run this file ### to see what get_partitions does if you want to visualize it: #for item in (get_partitions(['a','b','c','d'])): # print(item)
rajul/tvb-framework
tvb/interfaces/web/entities/context_model_parameters.py
Python
gpl-2.0
9,421
0.006156
# -*- coding: utf-8 -*- # # # TheVirtualBrain-Framework Package. This package holds all Data Management, and # Web-UI helpful to run brain-simulations. To use it, you also need do download # TheVirtualBrain-Scientific Package (for simulators). See content of the # documentation-folder for more details. See also http:/...
e ("Baycrest") # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by the Free # Software Foundation. This program is distributed in
the hope that it will be # useful, 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 # Public License along with this program; if not, you can ...
lnls-dig/dsp-cores
hdl/testbench/divider/Manifest.py
Python
lgpl-3.0
317
0.015773
action = "simulation" sim_tool = "modelsim" top_module = "div_tb" vcom_opt = "-2008" target = "xilinx" syn_device = "xc7a200t" machine_pkg = "uvx_1
30M" # uvx_130M sirius_130M modules = {"lo
cal" : ["../../", "../../ip_cores/general-cores/", "../../sim/test_pkg/"]} files = ["div_tb.vhd"]
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_htmlparser.py
Python
epl-1.0
10,454
0.001722
"""Tests for HTMLParser.py.""" import HTMLParser import pprint import sys import unittest from test import test_support class EventCollector(HTMLParser.HTMLParser): def __init__(self): self.events = [] self.append = self.events.append HTMLParser.HTMLParser.__init__(self) def get_eve...
tity;&#32; <!--comment1a -></foo><bar>&lt;<?pi?></foo<bar comment1b--> <Img sRc='Bar' isMAP>sample text &#x201C; <!--comment2a-- --comment2b--><!> </Html> """, [ ("data", "\n"), ("decl", "DOCTYPE html PUBLIC 'foo'"), ("data", "\n"), ("starttag", "html", []), ("entityref", "entity"), ("charref", ...
ata", "sample\ntext\n"), ("charref", "x201C"), ("data", "\n"), ("comment", "comment2a-- --comment2b"), ("data", "\n"), ("endtag", "html"), ("data", "\n"), ]) def test_unclosed_entityref(self): self._run_check("&entityref foo", [ ("entityref", "entityref"), ...
aa403/betfair.py
betfair/meta/datatype.py
Python
mit
514
0
# -*- coding: utf-8 -*- class DataType(o
bject): def __init__(self, type, preprocessor=None): self.type = type self.preprocessor = preprocessor def preprocess(self, value): return self.preprocessor(value) if self.preprocessor else value def serialize(self, value): return value def unserialize(self, value): ...
elf.type): return processed return self.type(processed)
google-research/long-range-arena
lra_benchmarks/image/configs/pathfinder32/base_pathfinder32_config.py
Python
apache-2.0
1,992
0.014558
# Copyright 2021 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
onfig.warmup = (TRAIN_EXAMPLES // config.batch_size) * 1 config.steps_per_cycle = (TRAIN_EXAMPLES // config.batch_size) * NUM_EPOCHS # model params config.model = ml_collections.ConfigDict() config.model.num_layers = 1 config.model.num_heads = 2 config.model.emb_dim = 32 config.model.dropout_rate = 0.1 ...
config.model.attention_dropout_rate = 0.1 config.model.classifier_pool = 'MEAN' config.model.learn_pos_emb = False config.trial = 0 # dummy for repeated runs. return config
WheatonCS/Lexos
test/unit_test/test_rolling_windows_model.py
Python
mit
12,643
0
import numpy as np import pandas as pd from lexos.models.rolling_window_model import RollingWindowsModel, \ RWATestOptions from lexos.receivers.rolling_window_receiver import RWAFrontEndOptions, \ WindowUnitType, RWATokenType, RWARatioTokenOptions, RWAWindowOptions, \ RWAAverageTokenOptions, RWAPlotOptions ...
e=RWATokenType.string, token_frame=pd.DataFrame( data={ "numerator": ["t"], "denominator": ["a"] } ) ), average_token_options=None, passage_file_id=0, w...
ons( window_size=3, window_unit=WindowUnitType.letter ), plot_options=RWAPlotOptions( individual_points=False, black_white=False ), milestone="ta", text_color="#000000" ) ) # Get ...
carquois/blobon
blobon/books/migrations/0030_auto__add_field_invoice_date_of_issue.py
Python
mit
12,495
0.008083
# -*- 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 'Invoice.date_of_issue' db.add_column('books_invoice', 'date_of_issue', ...
auto_now_add': 'True', 'blank': 'True'}), 'date_of_issue': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField
', [], {'primary_key': 'True'}), 'invoice_number': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'notes': ('django.db.models.fields.CharFi...
artsturdevant/425supplemental_material
sevens/cleartherack/migrations/0002_auto__del_field_itemstock_in_stock__add_field_itemstock_stock_status.py
Python
mit
5,841
0.007704
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ItemStock.in_stock' db.delete_column(u'cleartherack_itemstock', 'in_stock') # Add...
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': {'object_name': 'User'}, 'date_joined': ('dj...
': '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'}), u'id': ('django.db.mod...
ryran/upvm
modules/string_ops.py
Python
apache-2.0
3,658
0.006014
# -*- coding: utf-8 -*- # Copyright 2015 Ravshello Authors (rsaw@redhat.com; https://github.com/ryran/ravshello) # Copyright 2016 upvm Contributors (see CONTRIBUTORS.md file in source) # License: Apache License 2.0 (see LICENSE file in source) # Modules from standard library from __future__ import print_function from ...
: return '\033[1;1m' + '\033[7m' + str(txt) + '\033[0m' return txt def BOLD(txt): """Return text in bold.""" if enableColor: return '\033[1;1m' + str(txt) + '\033[0m' return txt def red(txt): """Return text in red.""" if enableColor: return '\033[31m' + str(txt) + '\033...
1m' + str(txt) + '\033[0m' return txt def bgRED(txt): """Return text in red background (& bolded).""" if enableColor: return '\033[1;1m' + '\033[41m' + str(txt) + '\033[0m' return txt def yellow(txt): """Return text in yellow.""" if enableColor: return '\033[33m' + str(txt) + '...
darkk/ansible
plugins/inventory/ec2.py
Python
gpl-3.0
20,903
0.003492
#!/usr/bin/env python ''' EC2 external inventory script ================================= Generates inventory that Ansible can understand by making API request to AWS EC2 using the Boto library. NOTE: This script assumes Ansible is being executed where the environment variables needed for Boto have already been set:...
achmentId - ec2_client_token - ec2_deleteOnTermination - ec2_description - ec2_deviceIndex - ec2_dns_name - ec2_eventsSet - ec2_group_name - ec2_hy
pervisor - ec2_id - ec2_image_id - ec2_instanceState - ec2_instance_type - ec2_ipOwnerId - ec2_ip_address - ec2_item - ec2_kernel - ec2_key_name - ec2_launch_time - ec2_monitored - ec2_monitoring - ec2_networkInterfaceId - ec2_ownerId - ec2_persistent - ec2_placement - ec2_platform - ec2_previous_stat...
PyDataMadrid2016/Conference-Info
talks_materials/20160409_1015_Understanding_Random_Forests/latex/src/07_train_cart.py
Python
mit
519
0.001927
def train_
decision_tree(x, y): feature, value = get_best_split(x, y) x_left, y_left = x[x[feature] < value], y[x[feature] < value] if len(y_left.unique()) > 1: left_node = train_decision_tree(x_left, y_left) else: left_node = None x_right, y_right = x[x[feature] >= value], y[x[feature] >= va...
else: right_node = None return Node(feature, value, left_node, right_node)
PanDAWMS/panda-harvester
pandaharvester/harvestercore/job_spec.py
Python
apache-2.0
20,923
0.000956
""" Job spec class """ import copy import datetime from past.builtins import long from future.utils import iteritems from .spec_base import SpecBase class JobSpec(SpecBase): # has output file HO_noOutput = 0 HO_hasOutput = 1 HO_hasZipOutput = 2 HO_hasTransfer = 3 HO_hasPostZipOutput = 4 ...
lf, job_status=None): if job_status is None: job_status = self.status return job_status in ['finished', 'failed', 'cancelled', 'missed'] # get status def get_status(self): # don't report the final status while staging-out if self.is_final_status() and self.subStatus ...
d \ (self.subStatus in ['to_transfer', 'transferring'] or not self.all_events_done()): return 'transferring' return self.status # check if all events are done def all_events_done(self): retVal = True for eventSpec in self.events: if eventSpec.subS...
BenaroyaResearch/bripipetools
bripipetools/io/picardmetrics.py
Python
mit
5,099
0.001961
""" Class for reading and parsing Picard metrics files. """ import logging import re from bs4 import BeautifulSoup logger = logging.getLogger(__name__) class PicardMetricsFile(object): """ Parser to read tables of metrics generated by one of several Picard tools, typically stored in an HTML file, and re...
rics)) return metrics def parse(self): """ Parse metrics table and return dictionary. """ try: self._read_file() self._get_table() table_format = self._check_table_format() if table_format == 'long': return self...
f.path)) return {}
FallenWarrior2k/cardinal.py
src/cardinal/cogs/saucenao.py
Python
mit
8,997
0.003001
import re from dataclasses import dataclass from logging import getLogger from typing import List, Optional from aiohttp import ClientError, ClientSession from aioitertools import chain as achain from discord import Colour, Embed from discord.ext.commands import Cog, Context, command # from ..utils import maybe_send ...
green() if float(self.similarity) >= 85 else Colour.light_grey() # TODO: Set proper title from meta object embed = Embed(title='Found potential source.', colour=color) embed.set_thumbnail(url=self.thumbnail) embed.set_footer(text='Powered by SauceNAO.') # At least one entry sho...
he case, # I can always add a `if links else 'None found' later embed.add_field(name='Links', value=' | '.join(self.meta.links), inline=False) if self.meta.artist: embed.add_field(name='Artist', value=self.meta.artist, inline=True) embed.add_field(name='Similarity', value=f'...
mrunge/openstack_horizon
openstack_horizon/test/api_tests/neutron_tests.py
Python
apache-2.0
16,003
0
# Copyright 2012 NEC Corporation # # 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 ag...
est_network_update(self): network = {'network': self.api_networks.first()} network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() form_data = {'network': {'name': 'net1'}} neutronclient.update_network(network_id, body=form_data)\ .AndR...
elf.request, network_id, name='net1') self.assertIsInstance(ret_val, api.neutron.Network) def test_network_delete(self): network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_network(...
guineawheek/Dozer
dozer/sources/TwitchSource.py
Python
gpl-3.0
7,912
0.002528
"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notificat...
_name} is now live on Twitch!" embed.colour = self.color embed.description = data['title'] embed.url = f"https://www.twitch.tv/{data['user_name']}" embed.add_field(name="Playing", value=games[data['game_id']], inline=True) embed.add_field(name="Watching", value=data['viewer_co...
me, url=embed.url, icon_url=self.users[data['user_id']].profile_image_url) embed.set_image(url=data['thumbnail_url'].format(width=1920, height=1080)) start_time = parser.isoparse(data['started_at']) embed.timestamp = start_time return embed def generate_plain_text(self, data, gam...
anhstudios/swganh
data/scripts/templates/object/building/tatooine/shared_housing_tatt_style02_large.py
Python
mit
479
0.045929
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/tatooine/shared_housing_tatt_style02_large.iff" result.attribute_te...
e_id = -1 result.stfName("building_name","housing_ta
tt_style01_large") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
wxgeo/geophar
wxgeometrie/sympy/series/sequences.py
Python
gpl-2.0
29,580
0.000507
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.core.mul import Mul from sympy.core.singleton import S, Singleton from sympy.core.symbol import Dummy, Symbol from sympy.core.compatibility import (range, integer_types, with_metaclass, i...
'__add__') def __radd__(self, other): return self + other def __sub__(self, other): """Returns the term-wise subtraction of 'self' and 'other'. ``other`` should be a sequence. Examples ======== >>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n >>> SeqFormula(n**2) - (SeqFormula(n)) SeqFormula(n**2 - n, (n, 0, oo)) """ if not isinstance(other, SeqBase): raise TypeError('cannot subtract sequence and %s' % type(other)) return SeqAdd(self, -other) @call_highest_priority('__s...
leifos/pagefetch
pagefetch_project/pagefetch/game_model_functions.py
Python
mit
4,327
0.006471
__author__ = 'leif' import json import os import sys import random from ifind.common.pagecapture import PageCapture from ifind.common.utils import convert_url_to_filename, read_in_urls from game_models import Page, Category sys.path.append(os.getcwd()) from configuration import DATA_DIR from configuration import MEDI...
c = Category(name=category_name, icon=icon, desc=desc, is_shown=True) c.save() return c def populate_pages(url_list, category, halved_screen_shot=False): """ :param url_list: a list of the urls for the pages that are going to be populated :param category: the category in which the pages fa...
r url in url_list: # create PageCapture object - specify the browser to be 800 x 600. try: pc = PageCapture(url,800, 600) url_file_name = convert_url_to_filename(url)+'.png' # To change to accomodate for the new changes image_file_name = os.path.join(DATA...
cosmozhang/NCRF-AE
process_data.py
Python
bsd-3-clause
7,056
0.005244
import cPickle import numpy as np import sys from collections import OrderedDict def format_chars(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i...
tag_labels_set.append(np.array(example_ta
g_labels, dtype = "int32")) chars_set.append(np.array(example_char, dtype = "int32")) # restart a new example after one finishes example_words = [] example_tag_labels = [] example_char = [] count += 1 else: # ...
anoopkunchukuttan/indic_nlp_library
contrib/hindi_to_kannada_transliterator.py
Python
mit
2,212
0.026221
import sys from indicnlp import common common.set_resources_path(INDIC_NLP_RESOURCES) from indicnlp import loader from indicnlp.normalize import indic_normalize from indicnlp.transliterate import unicode_transliterate if __name__ == '__main__': """ This script transliterates Hindi to Kannada. It removes/rema...
','\u093e') ## remove nukta
line=line.replace('\u093c','') ## add halant if word ends with consonant #if isc.is_consonant(isc.get_phonetic_feature_vector(line[-1],'hi')): # line=line+'\u094d' words=line.split(' ') outwords=[] for word in line.split(' '): ...
rolepoint/appengine-mapreduce
python/src/mapreduce/namespace_range.py
Python
apache-2.0
14,002
0.008356
#!/usr/bin/env python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
string.uppercase + '._-')) MAX_NAMESPACE_LENGTH = 100 MIN_NAMESPACE = '' NAMESPACE_BATCH_SIZE = 50 def _setup_constants(alphabet=NAMESPACE_CHARACTERS,
max_length=MAX_NAMESPACE_LENGTH, batch_size=NAMESPACE_BATCH_SIZE): """Calculate derived constant values. Only useful for testing.""" global NAMESPACE_CHARACTERS global MAX_NAMESPACE_LENGTH global MAX_NAMESPACE global _LEX_DISTANCE global NAMESPACE_BATCH_SIZE NAMESPACE_CHARAC...
skariel/webalchemy
examples/three_d_earth/three_d_earth.py
Python
mit
5,235
0.00382
from webalchemy import config FREEZE_OUTPUT = 'webglearth.html' class Earth: def __init__(self): self.width = window.innerWidth self.height = window.innerHeight # Earth params self.radius = 0.5 self.segments = 64 self.rotation = 6 self.scene = new(THREE....
enderer.domElement.onmouseup = self.wrap(self, self.mouseup) self.renderer.domElement.onmousedown = self.wrap(self, self.mousedown) def mousemove(self, e): self.mdx += e.screenX - self.mx self.mdy += e.screenY - self.my self.mx = e.screenX self.my = e.screenY def mouseu...
elf, e): self.mx = e.screenX self.my = e.screenY self.renderer.domElement.onmousemove = self.wrap(self, self.mousemove) def wrap(self, object, method): def wrapper(): return method.apply(object, arguments) return wrapper def render(self): if Math.abs...
simone-campagna/daikon
test_zirkon/tfractions/fraction_type.py
Python
apache-2.0
610
0
# -*- coding: utf-8 -*- __all__ = [ 'Fraction', ] class Fraction(object): def __init__(self, numerator, denominator): self._numerator = numerator
self._denominator = denominator @property def numerator(self): return self._numerator @property def denominator(self): return self._denominator @property def value(self): return self._numerator / self._denominator def __repr__(self): return "{}({!r}...
)
Squishymedia/feedingdb
src/feeddb/feed/middleware.py
Python
gpl-3.0
319
0.003135
from feeddb.feed.util import FeedUploadStatus from d
jango.http import HttpResponseRedirect class FeedUploadStatusMiddleware(): def process_request(self, request): request.feed_upload_status = FeedUploadStatus(session=request.session) request.feed_upload_status.update_with_
querystring(request.GET)
JamesLinEngineer/RKMC
addons/script.ftvguide/gui.py
Python
gpl-2.0
60,618
0.002029
# # Copyright (C) 2014 Tommy Winther # http://tommy.winther.nu # # Modified for FTV Guide (09/2014 onwards) # by Thomas Geppert [bluezed] - bluezed.apps@gmail.com # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General P
ublic License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WAR
RANTY; 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 Public License # along with this Program; see the file LICENSE.txt. If not, write to # the Free Sof...
WoLpH/EventGhost
eg/WinApi/SerialPortScan.py
Python
gpl-2.0
4,912
0.000611
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2016 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
ID if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_HARDWAREID, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLa...
err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) szHardwareID = stringBuffer.value # friendly name if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_FRIENDLYNAME, None, cast(stringBuffer, PBYTE), ...
andrewtcrooks/taskorganizer
tasklist/app/views/home.py
Python
mit
2,390
0
"""Home operations.""" from django.http import HttpResponseRedirect from django.shortcuts import render from tasklist.app.forms import SignupForm from tasklist.app.models import User, Task def main_page(request): """Main view.""" if 'user_id' in request.session: user_obj = User.objects.filter(id=requ...
for i in range(len(task_obj)): if task_obj[i].id in id_list: task_obj[i].complete = True else: task_obj[i].c
omplete = False task_obj[i].save() incomplete_items = total_items - complete_items data = {'fname': request.session['first_Name'], 'user': user_obj, 'task': task_obj, 'a': 0, 'complete_items': complete_items, ...
sndrtj/varda
varda/api/__init__.py
Python
mit
166
0
""" REST serve
r API. .. moduleauthor:: Martijn Vermaat <martijn@vermaat.name
> .. Licensed under the MIT license, see the LICENSE file. """ from .views import api
DavidAlt/ITG
python/test-gui-template-as-text.py
Python
gpl-3.0
1,512
0.001984
# -*- coding: utf-8 -*- """ Created on Tue Nov 27 11:19:54 2018 @author: david """ from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidge...
self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitl...
dgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
stadtgestalten/stadtgestalten
grouprise/features/contributions/urls.py
Python
agpl-3.0
489
0
from django.conf.urls import url fr
om . import views urlpatterns = [ url( r'stadt/associations/(?P<association_pk>[0-9]+)/contributions/' r'(?P<contribution_pk>[0-9]+)/reply-to-author/$', views.ReplyToAuthor.as_view(), name='reply-to-author' ), url( r'(?P<entity_slug>[\w-]+)/(?P<association_slug>[\w-...
9]+)/delete/$', views.Delete.as_view(), name='delete-contribution', ), ]
Aldriana/ShadowCraft-Engine
shadowcraft/objects/old_proc_data.py
Python
lgpl-3.0
7,030
0.000569
allowed_procs = { 'heroic_grace_of_the_herald': { 'stat': 'crit', 'value': 1710, 'duration': 10, 'proc_name': 'Herald of Doom', 'behaviours': {'default': 'grace_of_the_herald'} }, 'heroic_key_to_the_endless_chamber': { 'stat': 'agi', 'value': 1710, ...
rigger': 'all_attacks', 'on_crit': True }, 'prestors_talisman_of_machination': { 'icd': 75, 'proc_chance': .1, 'trigger': 'all_attacks' }, 'rickets_magnetic_fireball': { # ICD should be verified. 'icd': 120, 'proc_chance': .2, 'trigger': '...
{ 'icd': 100, 'proc_chance': .1, 'trigger': 'all_attacks' }, 'the_hungerer': { 'icd': 60, 'proc_chance': 1., 'trigger': 'all_attacks' }, 'the_twilight_blade': { # PPM/ICD is a guess and should be verified. 'icd': 0, 'ppm': 1...
marcy-terui/lamvery
tests/__init__.py
Python
mit
113
0
""" la
mvery ---- Yet another deploy tool for AWS Lambda in the
virtualenv environment. """ __version__ = '0.0.1'
The-BFG/GenericCV
src/neighborhoodOperators.py
Python
gpl-3.0
2,307
0.030776
import numpy, math def kernel(name, k = 3): return { 'sobel': numpy.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])/8, 'gauss': gauss_kernel(k) }.get(name) def convolution(img, kernel): kernel = numpy.array(kernel) rowk = kernel[0] colk = kernel.transpose()[0] / kernel[0,0] if not (abs(colk.reshape(-1,1).dot...
de(a): column = numpy.arange(len(a) - 2).reshape((len(a) - 2, 1)) row = numpy.arange(2, -1, -1) index = column + row A = numpy.array(a)[index] return numpy.min(A, axis=1) def erode(img): img = img[:, :, 0] mat = [row_erode(row) for row in img] img = numpy.transpose(numpy.array(mat)) mat = [row_erode(row...
g(img): return dilatate(erode(img)) def gradient(img): return dilatate(img) - erode(img)
yunify/qingcloud-cli
qingcloud/cli/iaas_client/actions/s2/attach_to_s2_shared_target.py
Python
apache-2.0
2,022
0.001978
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the Licens...
.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitat...
om qingcloud.cli.misc.utils import explode_array from qingcloud.cli.iaas_client.actions.base import BaseAction class AttachToS2SharedTargetAction(BaseAction): action = 'AttachToS2SharedTarget' command = 'attach-to-s2-shared-target' usage = '%(prog)s -s <shared_target> -v <volumes> [-f <conf_file>]' ...
wevote/WeVoteServer
party/models.py
Python
mit
4,748
0.004002
# party/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.db import models import wevote_functions.admin from wevote_settings.models import fetch_next_we_vote_id_party_integer, fetch_site_unique_id_prefix from exception.models import handle_record_not_found_exception logger = wevote_...
" exception_multiple_object_returned = False created = False if not party_id_temp: success = False status = 'MISSING_PARTY_TEMP_ID' elif not party_name: success = False status = 'MISSING_PARTY_NAME' else:
new_party, created = Party.objects.update_or_create( party_id_temp=party_id_temp, ctcl_uuid=ctcl_uuid, defaults=updated_values) if new_party or len(new_party): success = True status = 'PARTY_SAVED' else: ...
treverhines/RBF
docs/scripts/gproc.e.py
Python
mit
1,343
0.013403
''' This script demonstrates how to create a periodic Gaussian process using the *gpiso* function. ''' import numpy as np import matplotlib.pyplot as plt from sympy import sin, exp, pi
from rbf.basis import get_r, get_eps, RBF from rbf.gproc import gpiso np.random.seed(1) period = 5.0 cls = 0.5 # characteristic length scale var = 1.0 # variance r = get_r() # get symbolic variables eps = get_eps() # create a symbolic expression of the periodic covariance function expr = exp(-sin(r*pi/period)**2/e...
RBF using the symbolic expression basis = RBF(expr) # define a Gaussian process using the periodic RBF gp = gpiso(basis, eps=cls, var=var) t = np.linspace(-10, 10, 1000)[:,None] sample = gp.sample(t) # draw a sample mu,sigma = gp(t) # evaluate mean and std. dev. # plot the results fig,ax = plt.subplots(figsize=(6,4)) ...
venthur/wyrm
test/test_calculate_csp.py
Python
mit
4,999
0.0018
from __future__ import division import unittest import numpy as np np.random.seed(42) from wyrm.types import Data from wyrm.processing import calculate_csp class TestCalculateCSP(unittest.TestCase): EPOCHS = 50 SAMPLES = 100 SOURCES = 2 CHANNELS = 10 def setUp(self):
# create a random noise signal with 50 epochs, 100 samples, and # 2 sources # even epochs and source 0: *= 5 # odd epochs and source 1: *= 5 self.s = np.random.randn(self.EPOCHS, self.SAMPLES, self.SOURCES) self.s[ ::2, :, 0] *= 5 self.s[1::2, :, 1] *= 5 # the ...
r 'signal' which 50 epochs, 100 samples and 10 channels self.X = np.empty((self.EPOCHS, self.SAMPLES, self.CHANNELS)) for i in range(self.EPOCHS): self.X[i] = np.dot(self.A, self.s[i].T).T noise = np.random.randn(self.EPOCHS, self.SAMPLES, self.CHANNELS) * 0.01 self.X += nois...
rmoorman/appier
src/appier/export.py
Python
apache-2.0
11,824
0.007867
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Appier Framework # Copyright (c) 2008-2015 Hive Solutions Lda. # # This file is part of Hive Appier Framework. # # Hive Appier Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apach...
data source data = data.decode("utf-8") data_s = json.loads(data) for _key, entity in data_s.items(): # verifies if the "native" object id value for the mongo # database exists and if that's the case tries to convert # the v
alue from the "underlying" string value to object # identifier, defaulting to a string value if it fails if "_id" in entity: try: entity["_id"] = bson.ObjectId(entity["_id"]) except: entity["_id"] = entity["_id"] # retrieves the key value for th...
rwl/PyCIM
CIM15/IEC61970/Informative/InfOperations/ChangeSet.py
Python
mit
5,204
0.001537
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitat
ion the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or sub...
WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR...
Taifxx/xxtrep
context.addtolib/resources/lib/ext/li2_.py
Python
gpl-3.0
6,356
0.028801
# -*- coding: utf-8 -*- # # Copyright (C) 2016 Taifxx # # 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....
Listitems Object ... class vidItems: def __init__(self, dirPath=Empty, srcName=Empty): if not dirPath : self.norm_init() else : self.jsp_init (dirPath, srcName) def jsp_init(self, dirPath, srcName): jsp = getJsp(dirPath, srcName) #import resources.lib.g...
GUI #GUI.dlgOk(str( jsp.count )) ## Current jsp data ... self.vidFolderNameDef = Empty self.vidCPath = jsp.link self.vidCName = jsp.name self.vidIsEmpty = True self.vidFolCount = jsp.count ## Local items list... self...
tanglei528/ceilometer
ceilometer/transformer/conversions.py
Python
apache-2.0
9,418
0.000106
# -*- encoding: utf-8 -*- # # Copyright © 2013 Red Hat, Inc # # Author: Eoghan Glynn <eglynn@redhat.com> # # 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/license...
mp=s.timestamp, resource_metadata=s.resource_metadata ) def handle_sample(self, context, s): """Handle a sample, converting if necessary."""
LOG.debug(_('handling sample %s'), (s,)) if (self.source.get('unit', s.unit) == s.unit): s = self._convert(s) LOG.debug(_('converted to: %s'), (s,)) return s class RateOfChangeTransformer(ScalingTransformer): """Transformer based on the rate of change of a sample volum...
openstack/os-brick
os_brick/tests/test_utils.py
Python
apache-2.0
11,110
0
# (c) Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 re...
_test_method) exception_log = self.LOG.debug.call_args_list[1] self.assertIn('exception', str(exception_log))
self.assertIn('test message', str(exception_log)) def test_utils_trace_method_with_time(self):
mstoppert/adventofcode
06/answer.py
Python
mit
1,930
0.003109
import numpy file = open("input.txt") lights = numpy.zeros((1000,1000), 'int') def split_instruction(line): split = line.split(' ') if "turn on" in line or "turn off" in line: instruction = "%s_%s" % (split[0], split[1]) first_pair = [int(x) for x in split[2].split(",")] second_pair =...
d_pair[1] + 1): if instruction == "turn_on": lights[x][y] = 1 elif instruction == "turn_off": lights[x][y] = 0 elif instruction == "toggle": if lights[x][y] == 1: lights[x][y] = 0 else: ...
def apply_instruction_second_star(instruction, first_pair, second_pair): for x in xrange(first_pair[0], second_pair[0] + 1): for y in xrange(first_pair[1], second_pair[1] + 1): if instruction == "turn_on": lights[x][y] += 1 elif instruction == "turn_off": ...
rscarson/Lavendeux
bin/extensions/hostname.py
Python
mit
433
0.030023
from lavendeux import Types, Errors from socket import getfqdn, setdefaulttimeout def call(args
): # Check number of arguments if len(args) != 1: return (Types.ERROR, Errors.INVALID_ARGS) setdefaulttimeout(0.5) try: return (Types.STRING, getfqdn(args[0])) except socket.gaierror: return (Types.ST
RING, args[0]) def help(): return "Function which translates an ip address into its associated domain name."
RonnyPfannschmidt/execnet-test
doc/example/py3topy2.py
Python
mit
387
0.002584
import execnet gw = execnet.makegate
way("popen//python=python2") channel = gw.remote_exec(""" import numpy array = numpy.array([1,2,3]) while 1: x = channel.receive() if x is None: break array = numpy.append(array, x) channel.send(repr(array)) """) for x in range(10): channel.send(x) channel.send(No...
t (channel.receive())
endlessm/chromium-browser
third_party/grpc/src/src/python/grpcio_tests/tests/unit/_cython/_common.py
Python
bsd-3-clause
4,044
0
# Copyright 2017 gRPC 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 writing...
d(event) self._due[event.tag] -= 1 self._condition.notify_all() if self._due[event.tag] <= 0: self._due.pop(event.tag) if not self._due: return
thread = threading.Thread(target=in_thread) thread.start() for tag in tags: self._due[tag] += 1 def event_with_tag(self, tag): with self._condition: while True: if self._events[tag]: return self._events[tag].pop(0) ...
c3nav/c3nav
src/c3nav/mapdata/grid.py
Python
apache-2.0
2,343
0
import bisect import string from abc import ABC, abstractmethod from typing import Optional from django.conf import settings class AbstractGrid(ABC): enabled = False @abstractmethod def get_square_for_point(self, x, y) -> Optional[str]: pass @abstractmethod def get_squares_for_bounds(se...
ols
= tuple(float(x) for x in cols) self.rows = tuple(sorted(rows)) self.cols = tuple(sorted(cols)) if self.rows == rows: self.invert_y = False elif self.rows == tuple(reversed(rows)): self.invert_y = True else: raise ValueError('row coordinates a...
mdavid/cherokee-webserver-svnclone
admin/plugins/extensions.py
Python
gpl-2.0
2,529
0.011862
# Cheroke Admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # This pro...
vsrv_rule_get_next ('vs
erver!%s'%(vsrv_num)) # Apply CTK.cfg['%s!match'%(next_pre)] = 'extensions' CTK.cfg['%s!match!extensions'%(next_pre)] = new_ext return {'ret': 'ok', 'redirect': '/vserver/%s/rule/%s' %(vsrv_num, next_rule)} # Modifications return CTK.cfg_apply_post() class Plugin_...
RaisingTheDerp/raisingthebar
root/devtools/WildcardSearch.py
Python
gpl-3.0
1,401
0.052106
from __future__ import generators import os import re import stat # # Useful function to return a list of files in a directory based on a dos-style wildcard like "*.txt" # # for name in WildcardSearch( "d:/hl2/src4/dt*.cpp", 1 ): # print name # def WildcardSearch( wildcard, bRecurse=0 ): # First find the base direc...
re.IGNORECASE ) return __GetFiles_R( matcher, dirName, bRecurse ) def __GetFiles_R( matcher, dirName, bRecurse ): fileList = []
# For each file, see if we can find the regular expression. files = os.listdir( dirName ) for baseName in files: filename = dirName + "/" + baseName mode = os.stat( filename )[stat.ST_MODE] if stat.S_ISREG( mode ): # Make sure the file matches the search string. if matcher.match( baseName ): fileLi...
artemrizhov/pymorphy
pymorphy/morph_tests/hyphen.py
Python
mit
3,259
0.007288
#coding: utf-8 from pymorphy.morph_tests.base import MorphTestCase, unittest2 class TestHyphen(MorphTestCase): def test_dict(self): self.assertHasInfo(u'САНКТ-ПЕТЕРБУРГА', u'САНКТ-ПЕТЕРБУРГ', u'С', u'lemma(С).suffix(АНКТ-ПЕТЕРБУРГА)') def test_immutable_left(self): self.assertHasInfo(u'ИНТЕРН...
'PDF-ДОКУМЕНТОВ', u'PDF-ДОКУМЕНТ', u'С', u'hyphen-prefix') self.assertHasInfo(u'АММИАЧНО-СЕЛИТРОВОГО', u'АММИАЧНО-СЕЛИТРОВЫЙ', u'П', u'hyphen-prefix') def test_mutable_left(self): self.assertHasInfo(u'БЫСТРО-БЫСТРО', u'БЫСТРО-БЫСТРО', u'Н', u'word-formation') self.assertHasInfo(u'КОМАНД-УЧА...
АСТНИЦА', u'С', u'word-formation') self.assertHasInfo(u'БЕГАЕТ-ПРЫГАЕТ', u'БЕГАТЬ-ПРЫГАТЬ', u'Г', u'word-formation') self.assertHasInfo(u'ДУЛ-НАДУВАЛСЯ', u'ДУТЬ-НАДУВАТЬСЯ', u'Г', u'word-formation') def test_extra_prefix(self): self.assertHasInfo(u'ПОЧТОВО-БАНКОВСКИЙ', u'ПОЧТОВО-БАНКОВСКИЙ'...
lare-team/lare.js
test_app/tests/test_lare_request.py
Python
mit
9,862
0.002129
from __future__ import unicode_literals from django.core.urlresolvers import reverse from selenium.common.exceptions import NoSuchElementException from .helpers import SeleniumTestCase class LareRequestTest(SeleniumTestCase): def test_lare_request_depth_1(self): self.browser_get_reverse('index') ...
se_link.click() self.wait.until(lambda browser: browser.title == 'no-lare-response-title') self.assert_title('no
-lare-response-title') self.assert_content('no-lare-response-content') self.assert_body_attr('lare-done', None) self.browser_go_back() # On Chrome/Webkit caching will return the content out of the lare xhr-response, not a new initial content. # fix #16 - lare load + fallback ...
mozilla/kitsune
kitsune/questions/tests/test_forms.py
Python
bsd-3-clause
3,899
0.000513
from collections import OrderedDict from django.contrib.auth.models import AnonymousUser from kitsune.questions.forms import NewQuestionForm, WatchQuestionForm from kitsune.questions.tests import TestCaseBase from kitsune.users.tests import UserFactory from nose.tools import eq_ class WatchQuestionFormTests(TestCase...
, "name": "Firefox on desktop", "categories": OrderedDict( [ ( "cookies", { "name": "Cookies", "topic": "cookies", "tags": ["coo...
ng", "ff_version", "os", "plugins"], } form = NewQuestionForm(product=product, data=data) form.is_valid() expected = {} actual = form.cleaned_metadata eq_(expected, actual) # Test with metadata data["os"] = "Linux" form = NewQuestionForm(product=p...
NetworkManager/NetworkManager-ci
run/centos-ci/cico_gitlab_trigger.py
Python
gpl-3.0
12,762
0.003291
#!/usr/bin/env python import sys import json import os import datetime import time from pprint import pprint default_os = '8-stream' ##next_os = 'RHEL8.4' #next_branch_base = 'rhel-8' jenkins_url = 'https://jenkins-networkmanager.apps.ocp.ci.centos.org/' class GitlabTrigger(object): def __init__(self, data): ...
params.append({'name': 'TEST_BRANCH', 'value': 'master'}) params.append({'name': 'REFSPEC', 'value': gt.commit}) project_dir = "NetworkManager-code-mr"
if gt.repository == 'NetworkManager-ci': # NMCI always use main for code params.append({'name': 'TEST_BRANCH', 'value': gt.commit}) params.app
beol/reviewboard
reviewboard/notifications/email.py
Python
mit
32,206
0.000217
from __future__ import absolute_import, unicode_literals import email import logging from email.utils import formataddr from collections import defaultdict from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.urlresolvers import rev...
**kwargs): """Send e-mail when a review is published. Listens to the :py:data:`~reviewboard.reviews.signals.review_published` signal and sends e-mail if this type of notification is enabled through the ``mail_send_review_mail``
site configuration setting). """ siteconfig = SiteConfiguration.objects.get_current() if siteconfig.get('mail_send_review_mail'): mail_review(review, user, to_submitter_only) def reply_published_cb(sender, user, reply, trivial, **kwargs): """Send e-mail when a review reply is published. ...
saisankargochhayat/algo_quest
leetcode/14.LongestCommonPrefix/soln.py
Python
apache-2.0
684
0.02924
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: res = [] common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])] return "".join(res)
# Enumeration soln # def longestCommonPrefix(self, strs): # """ # :type strs: List[str] # :rtype: str # """ # if not strs: # return "" # shortest = min(strs,key
=len) # for i, ch in enumerate(shortest): # for other in strs: # if other[i] != ch: # return shortest[:i] # return shortest
botswana-harvard/edc-lab
edc_lab/models/aliquot.py
Python
gpl-2.0
1,273
0
from edc_base.model_managers import HistoricalRecords from edc_base.model_mixins import BaseUuidModel from edc_base.sites import CurrentSiteManager from edc_search.model_mixins import SearchSlugModelMixin, SearchSlugManager from ..managers import AliquotManager from .model_mixins import AliquotModelMixin, AliquotIdent...
'parent_identifier', 'requisition_identifier'] on_site = CurrentSiteManager() objects = Manager() history = HistoricalRecords() @property def human_readable_identifier(self): """Returns a human readable aliquot identifier. """ x = self.aliquot_ide...
x[6:10], x[10:14], x[14:18])
michaelBenin/sqlalchemy
test/engine/test_execute.py
Python
mit
70,582
0.003117
# coding: utf-8 from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, \ config, is_ import re from sqlalchemy.testing.util import picklers from sqlalchemy.interfaces import ConnectionProxy from sqlalchemy import MetaData, Integer, String, INT, VARCHAR, func, \ bindparam, select, event, Type...
# 1.2.2c1, 1.2.2) @testing.skip_if(lambda : testing.against('mysql+mysqldb'), 'db-api flaky') @testing.fails_on_everything_except('postgresql+psycopg2', 'postgresql+pypostgresql', 'mysql+mysqlconnector', 'mysql+pymysql', 'mysql+cymy
sql') def test_raw_python(self): def go(conn): conn.execute('insert into users (user_id, user_name) ' 'values (%(id)s, %(name)s)', {'id': 1, 'name' : 'jack'}) conn.execute('insert into users (user_id, user_name) ' ...
kdheepak89/pypdevs
pypdevs/allocators/autoAllocator.py
Python
apache-2.0
2,745
0.003643
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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...
ns: float -- the time at which to perform the allocat
ions (and save them) """ # No need for any run time information return 0.0
wikimedia/operations-debs-python-pykafka
pykafka/test/kafka_instance.py
Python
apache-2.0
21,916
0.000319
""" Copyright 2013 Parse.ly, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
download dir try: os.makedirs(self._bin_dir) except OSError as exception: if exception.errno != errno.EEXIST: raise # Download and extract log.info('Downloading Kafka.') curr_dir = os.getcwd() os.chdir(self._bin_dir) url_fm...
l_fmt.format( scala_version=self._scala_version, kafka_version=self._kafka_version ) p1 = subprocess.Popen(['curl', '-vs', url], stdout=subprocess.PIPE) p2 = subprocess.Popen(['tar', 'xvz', '-C', self._bin_dir, '--strip-components', '1'], ...
INTI-CMNB-FPGA/fpga_helpers
fpgahelpers/fpga_deps.py
Python
gpl-3.0
7,332
0.021959
#!/usr/bin/python # -*- coding: utf-8 -*- # # FPGA Deps collects the files of an HDL project # Copyright (C) 2015-2019 INTI # Copyright (C
) 2015-2019 Rodrigo A. Melo # # 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 hop...
eral Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Assumptions: # * Files are well formed. # * VHDL: # * A file could have one or more packages and/or one or more entities. # * The a...
moonbury/notebooks
github/Numpy/Chapter5/ufuncmethods.py
Python
gpl-3.0
428
0
from __future__ import print_function import numpy as np a = np.arange(9) print("Reduce", np.add.reduce(a)) print("Accumulate", np.add.accumulate(a)) print("Reduceat", np.add.redu
ceat(a, [0, 5, 2, 7])) print("Reduceat step I", np.add.reduce(a[0:5])) print("Reduceat step II", a[5]) print("
Reduceat step III", np.add.reduce(a[2:7])) print("Reduceat step IV", np.add.reduce(a[7:])) print("Outer", np.add.outer(np.arange(3), a))
ivano666/tensorflow
tensorflow/g3doc/how_tos/adding_an_op/zero_out_op_1.py
Python
apache-2.0
1,041
0
# 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...
uage governing permissions and # limitations under the License. # ==============================================
================================ """ZeroOut op Python library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import tensorflow as tf _zero_out_module = tf.load_op_library( os.path.join(tf.resource_loader.get_data_files_path(), ...
hfp/libxsmm
samples/deeplearning/sparse_training/fairseq/fairseq/data/monolingual_dataset.py
Python
bsd-3-clause
7,469
0.001473
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from . import data_utils, FairseqDataset def collate(samples, pad_idx, eos_idx): if len(samples) == 0: ...
arget = future_target return source, self._filter_vocab(target) def _maybe_add_bos(self, source, target): if self.add_bos_token: source = torch.cat([source.new([self.vocab.bos()]), source]) if target is not None: target = torch.cat([target.new([self.tgt_voca...
urce, target def _filter_vocab(self, target): if len(self.tgt_vocab) != len(self.vocab): def _filter(target): mask = target.ge(len(self.tgt_vocab)) if mask.any(): target[mask] = self.tgt_vocab.unk() return target i...