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
cameronobrien/BroadsideBot
app/intel_entry.py
Python
mit
1,447
0.004838
import datetime import csv with open('SYSTEMS.csv') as f: reader = csv.reader(f) ALLOWED_SYSTEMS = [l[0] for l
in reader] class IntelEntry: KEYS = ["timer_name", "alliance", "system", "time", "date", "location
"] def __init__(self, timer_name="", alliance="", system="", time="", date="", location=""): if timer_name != "": self.timer_name = timer_name else: raise ValueError("Provided timer not valid.") if alliance != "": self.alliance = alliance.strip() ...
oblique-labs/pyVM
rpython/memory/gc/generation.py
Python
mit
30,342
0.000857
import sys from rpython.memory.gc.semispace import SemiSpaceGC from rpython.memory.gc.semispace import GCFLAG_EXTERNAL, GCFLAG_FORWARDED from rpython.memory.gc.semispace import GC_HASH_TAKEN_ADDR from rpython.memory.gc import env from rpython.rtyper.lltypesystem.llmemory import NULL, raw_malloc_usage from rpython.rtype...
<< (scale+1)) <= newsize: scale += 1 self.nursery_scale = scale debug_print("nursery_size =", newsize) debug_print("largest_young_fixedsize =", self.largest_young_fixedsize) debug_print("largest_young_var_basesize =", self.largest_young...
lf.nursery_size >= (self.min_nursery_size << scale) # Force a full collect to remove the current nursery whose size # no longer matches the bounds that we just computed. This must # be done after changing the bounds, because it might re-create # a new nursery (e.g. if it invokes finali...
Cinntax/home-assistant
homeassistant/components/roku/remote.py
Python
apache-2.0
1,715
0.001166
"""Support for the Roku remote.""" import requests.exceptions from homeassistant.components import remote from homeassistant.const import CONF_HOST async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Roku remote platform.""" if not discovery_info: retu...
n True @property def should_poll(self): """No polling needed for Roku.""" return False def send_command(self, command,
**kwargs): """Send a command to one device.""" for single_command in command: if not hasattr(self.roku, single_command): continue getattr(self.roku, single_command)()
wmvanvliet/mne-python
mne/utils/__init__.py
Python
bsd-3-clause
4,697
0.002768
# # # WARNING # # # # This list must also be updated in doc/_templates/autosummary/class.rst if it # is changed here! _doc_special_members = ('__contains__', '__getitem__', '__iter__', '__len__', '__add__', '__sub__', '__mul__', '__div__', '__neg__', '__hash__') from ._b...
me, _check_subject, _check_pandas_installed,
_check_pandas_index_arguments, _check_event_id, _check_ch_locs, _check_compensation_grade, _check_if_nan, _is_numeric, _ensure_int, _check_preload, _validate_type, _check_info_inv, _check_channels_spatial_filter, _check_o...
okfn-brasil/viralata
viralata/views.py
Python
agpl-3.0
12,901
0
#!/usr/bin/env python # coding: utf-8 import re import bleach import passlib from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound # from flask import redirect, url_for, make_response from flask.ext.restplus import Resource from flask.ext.mail import Message from auths import get_aut...
rce): def post(self, backend): '''Completes the login with a specific backend.''' username = get_username(backend, redirect_uri='/') return create_tokens(username) # @api.route('/login/external/automatic/<string:backend>') # class StartLoginExtAutoAPI(Resource): # def get(self, backe...
ckend # (like Facebook).''' # print('AUTH-GET') # print(get_auth_url(backend, 'completeloginautoapi')) # return {'redirect': get_auth_url(backend, 'completeloginautoapi')} # # return redirect(get_auth_url(backend, 'completeloginautoapi')) # @api.route('/complete/automatic/<strin...
macmanes-lab/MCBS913
code/Junhong Chen/concatReads.py
Python
mit
925
0.016216
""" Author: Junhong Chen """ from Bio import SeqIO import gzip import sys import os pe1 = [] pe2 = [] pname = [] for dirName, subdirList, fileList in os.walk(sys.argv[1]): for fname in fileList: tmp = fname.split(".")[0] tmp = tmp[:len(tmp)-1] if t
mp not in pname: pname.append(tmp) pe1.append(dirName+"/"+tmp+"1.fq.gz") pe2.append(dirName+"/"+tmp+"2.fq.gz") def concat(name,file_list): with open(name, 'w') as w_file: for filen in file_list: print 'working with',filen ...
IO.parse(o_file, 'fastq') SeqIO.write(seq_records, w_file, 'fastq') #print pe1 #print pe2 concat(sys.argv[2]+"-pe1.fq", pe1) concat(sys.argv[2]+"-pe2.fq", pe2)
novafloss/django-agnocomplete
agnocomplete/core.py
Python
mit
20,047
0
""" The different agnocomplete classes to be discovered """ from copy import copy from six import with_metaclass from abc import abstractmethod, ABCMeta import logging from django.db.models import Q from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import force_text as text from django...
_pag
e_size def get_query_size(self): """ Return the computed default query size It takes into account: * class variables * settings, * fallback to the module constants """ return self._query_size def get_query_size_min(self): """ Re...
paulmcquad/Python
11 - Lists/sort revertdigits.py
Python
gpl-3.0
181
0.055249
def revertdigits( item ): return (item%10)*100 + (int(item/
10)%10)*10 + int(item/100) numlist
= [314, 315, 642, 246, 129, 999] numlist.sort( key=revertdigits ) print( numlist )
voxie-viewer/voxie
filters/downsample.py
Python
mit
3,821
0.001309
#!/usr/bin/python3 # # Copyright (c) 2014-2022 The Voxie Authors # # 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 limitation the rights # to use, copy,...
N 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 OTHER DEALINGS IN # THE SOFTWARE. # import numpy as np import voxie args = voxie.parse...
context.makeObject(context.bus, context.busName, args.voxie_operation, ['de.uni_stuttgart.Voxie.ExternalOperationRunFilter']).ClaimOperationAndCatch() as op: filterPath = op.FilterObject pars = op.Parameters # print (pars) properties = pars[filterPath._objectPath]['Properties'].getValue('a{sv}') # ...
richtermondt/inithub-web
inithub/inithub/context_processors.py
Python
mit
376
0.013298
''' Cre
ated on Jun 6, 2014 @author: rtermondt ''' from django.conf import settings def global_settings(request): invitation_system_setting = getattr(settings, 'INVITATION_SYSTEM', None) if invitation_system_setting == True: invite_system = True else: invite_system = False return { ...
}
regionbibliotekhalland/digitalasagor
tooltip.py
Python
gpl-3.0
8,114
0.008134
'''Michael Lange <klappnase (at) freakmail (dot) de> The ToolTip class provides a flexible tooltip widget for Tkinter; it is based on IDLE's ToolTip module which unfortunately seems to be broken (at least the version I saw). INITIALIZATION OPTIONS: anchor : where the text should be positioned inside the widg...
self._id2 = self.master.bind("<Leave>", self.leave, '+') self._id3 = self.master.bind("<ButtonPress>", self.leave, '+') self._follow_mouse = 0 if self._opts['follow_mouse']: self._id4 = self.master.bind("<Motion>", self.motion, '+') self._follow_mouse = 1
def configure(self, **opts): for key in opts: if self._opts.has_key(key): self._opts[key] = opts[key] else: KeyError = 'KeyError: Unknown option: "%s"' %key raise KeyError ##----these methods handle the callbacks on "<En...
johncburnett/Angelus
src/angelus.py
Python
gpl-2.0
953
0.008395
#!/usr/bin/env python # angelus.py - John Burnett & Will Johnson (c)2015 # # Angelus does the following: # -FFT analysis # -Partial tracking # -Modal analysis # -Resynthesis # # Angelus will eventual
ly do the following: # -FFT Analysis -> Notation # -Modal Analysis -> 3D mesh (and reverse?) from FFT_Analyzer import FFT_Analyzer from writeRObU import writeRObU from Synthesizer import Synthesizer import sys def main(): fname = sys.argv[1] title = parse_fname(fname) infile = "../audio/" + fname outf...
, analysis.modal_model) out.write() synth = Synthesizer(analysis, title) synth.write_wav() #synth.write_residual() def parse_fname(fname): s = "" for l in fname: if l != '.': s += l else: return s main()
tvtsoft/odoo8
addons/sale_contract/tests/__init__.py
Python
agpl-3.0
78
0
# -*- coding: utf-8 -*-
import common_sale_contract import test_sale_contrac
t
beardypig/streamlink
tests/streams/test_stream_wrappers.py
Python
bsd-2-clause
655
0
import unittest from streamlink.stream import StreamIOIterWrapper class TestPluginStream(unittest.TestCase): def test_iter(self): def generator(): yield b"1" * 8192 yield b"2" * 4096 yield b"3" * 20
48 fd = StreamIOIterWrapper(generator()) self.assertEqual(fd.read(409
6), b"1" * 4096) self.assertEqual(fd.read(2048), b"1" * 2048) self.assertEqual(fd.read(2048), b"1" * 2048) self.assertEqual(fd.read(1), b"2") self.assertEqual(fd.read(4095), b"2" * 4095) self.assertEqual(fd.read(1536), b"3" * 1536) self.assertEqual(fd.read(), b"3" * 512)
garyp/djwed
photologue/urls.py
Python
mit
3,400
0.008529
from django.conf import settings from django.conf.urls.defaults import * from models import * from django.views.generic import date_based, list_detail from django.contrib.auth.decorators import login_required # Number of random images from the gallery to display. SAMPLE_SIZE = ":%s" % getattr(settings, 'GALLERY_SAMPLE...
': 'date_added', 'allow_empty': True, 'queryset': Gallery.objects.filter(is_public=True), 'extra_co
ntext':{'sample_size':SAMPLE_SIZE}} urlpatterns = patterns('django.views.generic.date_based', url(r'^gallery/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[\-\d\w]+)/$', login_required(date_based.object_detail), {'date_field': 'date_added', 'slug_field': 'title_slug', 'queryset': Gallery.objects.fil...
darshan95/Shift-Reduce-Chunk-Expander
src/ssf_reader.py
Python
mit
4,608
0.052951
#!/usr/bin/python -*- coding:utf-8 -*- __Author__ = "Riyaz Ahmad Bhat" __Email__ = "riyaz.ah.bhat@gmail.com" import re from collections import namedtuple from sanity_checker import SanityChecker class DefaultList(list): """Equivalent of Default dictionaries for Indexing Errors.""" def __init__(self, defaul...
self.node = namedtuple('node', ('id', 'head', 'children', 'pos', 'poslcat', 'af', 'vpos', 'name','drel','parent', 'chunkId', '
chunkType', 'mtype', 'troot', 'coref', 'stype','voicetype', 'posn')) self.features = namedtuple('features', ('lemma','cat','gen','num','per','case','vib','tam')) def getAnnotations (self): children_ = list() for line in self.sentence.split("\n"): nodeInfo = line.decode("utf-8").split("\t") ...
ahb0327/intellij-community
python/testData/completion/importQualifiedNamespacePackage/a.after.py
Python
apache-2.0
18
0
import nspkg1.f
oo
glaudsonml/kurgan-ai
libs/Tree.py
Python
apache-2.0
2,507
0.001197
''' Tree from: http://www.quesucede.com/page/show/id/python-3-tree-implementation ''' from urllib.parse import urlparse import os (_ROOT, _DEPTH, _BREADTH) = range(3) class Node: def __init__(self, identifier): self.__identifier = identifier self.__children = [] @property def identifier...
s[key
] def __setitem__(self, key, item): self.__nodes[key] = item ''' tree = Tree() t = print("{0}".format("palestras")) tree.add_node("Harry") # root node tree.add_node("Jane", t) tree.add_node("Bill", "Harry") tree.add_node("Joe", "Jane") tree.add_node("Diane", "Jane") tree.add_node("George", ...
yosefk/heapprof
heapprof.py
Python
bsd-2-clause
3,588
0.028428
#!/usr/bin/python import sys, commands, struct, operator, subprocess, os if len(sys.argv) != 3: print 'usage:',sys.argv[0],'<program> <core>' sys.exit(1) prog, core = sys.argv[1:] # finds out the size of void*/size_t. could be hardcoded for speed... try: cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin...
e-s)%cell == 0 and (e-s)/cell < 100 class Block: def __init__(self, metadata): self.size = struct.unpack(fmt, metadata
[0:cell])[0] self.stack = struct.unpack('%d'%(len(metadata)/cell - 1)+fmt, metadata[cell:]) def find_blocks(bytes): blocks = [] end_index = 0 while True: start_index = bytes.find('HeaP',end_index) end_index = bytes.find('ProF',start_index) if not is_block(start_index, end_index): end_index ...
lunapocket/powerOverWhelming
project/src/gui/guiSelectCode.py
Python
gpl-3.0
6,372
0.010233
import sys from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5 import uic from . import guiStart from . import guiCompileSuccess # sys.path.insert(1, 'C:/Users/GuSan/Desktop/powerOverWhelming/project/src/comp_exec') from ..comp_exec import validation from . import guiErrorCode class GuiSelectCode(QtWidgets.QMainWi...
t(self.centralwidget) self.txt_select_code_3.setGeometry(QtCore.QRect(810, 140, 320, 721)) self.txt_select_code_3.setObjectName("txt_select_code_3") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(560, 40, 201, 41))
font = QtGui.QFont() font.setPointSize(16) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.btn_compile_start = QtWidgets.QPushButton(self.centralwidget) s...
atvcaptain/enigma2
lib/python/Plugins/SystemPlugins/SoftwareManager/SoftwareTools.py
Python
gpl-2.0
9,405
0.031154
# -*- coding: iso-8859-1 -*- from enigma import eConsoleAppContainer from Components.Console import Console from Components.About import about from Components.PackageInfo import PackageInfoHandler from Components.Language import language from Components.Sources.List import List from Components.Ipkg import IpkgComponent...
l = len(tokens) version = l > 1 and tokens[1].strip() or "" self.installed_packetlist[name] = version for package in self.packagesIn
dexlist[:]: if not self.verifyPrerequisites(package[0]["prerequisites"]): self.packagesIndexlist.remove(package) for package in self.packagesIndexlist[:]: attributes = package[0]["attributes"] if "packagetype" in attributes: if attributes["packagetype"] == "internal": self.packagesIndexli...
couchbaselabs/celery
celery/bin/celeryd_detach.py
Python
bsd-3-clause
4,792
0.000417
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import with_statement import os import sys from optparse import OptionParser, BadOptionError from celery import __version__ from celery.platforms import EX_FAILURE, detached from celery.utils.log import get_logger from celery.bin.base im...
self.leftovers.append(rargs.pop(0)) class detached_celeryd(object): option_list = OPTION_LIST usage = "%prog [options] [celeryd options]" version = __version__ description = ("Detaches Celery worker nodes. See `celeryd --help` " "for the list of supported worker arguments.") ...
"celery.bin.celeryd"] def Parser(self, prog_name): return PartialOptionParser(prog=prog_name, option_list=self.option_list, usage=self.usage, description=self.description, ...
openstack/zaqar
zaqar/storage/sqlalchemy/tables.py
Python
apache-2.0
2,182
0
# Copyright (c) 2013 Red Hat, 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 # # h
ttp://www.apache.org/licenses/LICENSE-2.0 # # Unless requi
red by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import sqlalchemy...
mrquim/mrquimrepo
script.video.F4mProxy/lib/flvlib/astypes.py
Python
gpl-2.0
8,332
0.00228
import os import calendar import datetime import logging from primitives import * from constants import * from helpers import OrderedAttrDict, utc """ The AS types and their FLV representations. """ log = logging.getLogger('flvlib.astypes') class MalformedFLV(Exception): pass # Number def get_number(f, max_...
_ignored = get_si16(f) return datetime.datetime.fromtimestamp(timestamp, utc) def make_date(date): if date.tzinfo: utc_date = date.astimezone(utc) else: # assume it's UTC utc_date = date.replace(tzinfo=utc) ret = make_number(calendar.timegm(utc_date.timetuple()) * 1000) of...
i16(offset) # Null def get_null(f, max_offset=None): return None def make_null(none): return '' # Object class FLVObject(OrderedAttrDict): pass def get_object(f, max_offset=None): ret = FLVObject() while True: if max_offset and (f.tell() == max_offset): log.debug("Prematur...
dgasmith/psi4
psi4/driver/procrouting/response/scf_response.py
Python
lgpl-3.0
28,511
0.002876
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2019 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
ndation, Inc., # 51 Franklin Street, Fi
fth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # from typing import Union, List try: from dataclasses import dataclass except ImportError: from pydantic.dataclasses import dataclass import numpy as np from psi4 import core from psi4.driver import constants from psi4.driver.p4util import solvers from ...
jeremiedecock/snippets
python/doctest/numpy_example.py
Python
mit
2,806
0.000713
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is a doctest example with Numpy arrays. For more information about doctest, see https://docs.python.org/3/library/doctest.html (reference) and www.fil.univ-lille1.fr/~L1S2API/CoursTP/tp_doctest.html (nice examples in French). To run doctest, execute this script...
e* `NaN` values in `a` by zeros. Replace `NaN` ("Not a Number") values in `a` by zeros. Parameters ---------- image : array_like The image to process. `NaN` values are replaced **in-place** thus this function changes the provided object. Returns ------- array_like ...
of not (`False`). This array is defined by the instruction `np.isnan(a)`. Notes ----- `NaN` values are replaced **in-place** in the provided `a` parameter. Examples -------- >>> a = numpy.array([1., 2., numpy.nan]) >>> a array([ 1., 2., nan]) >>> example4(a)...
Ginray/my-flask-blog
tests/test_user_model.py
Python
mit
5,437
0.000368
import unittest import time from datetime import datetime from app import create_app, db from app.models import User, AnonymousUser, Role, Permission class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self...
n)) self.assertTrue(u2.email == 'susan@example.org') def test_roles_and_permissions(self): u = User(email='john@example.
com', password='cat') self.assertTrue(u.can(Permission.WRITE_ARTICLES)) self.assertFalse(u.can(Permission.MODERATE_COMMENTS)) def test_anonymous_user(self): u = AnonymousUser() self.assertFalse(u.can(Permission.FOLLOW)) def test_timestamps(self): u = User(password='cat'...
bodokaiser/piwise
main.py
Python
bsd-3-clause
5,437
0.001839
import numpy as np import torch from PIL import Image from argparse import ArgumentParser from torch.optim import SGD, Adam from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision.transforms import Compose, CenterCrop, Normalize from torchvision.transforms import ToTensor, ToPILIm...
ge[0] = image[0] * .229 + .485 i
mage[1] = image[1] * .224 + .456 image[2] = image[2] * .225 + .406 board.image(image, f'input (epoch: {epoch}, step: {step})') board.image(color_transform(outputs[0].cpu().max(0)[1].data), f'output (epoch: {epoch}, step: {step})') ...
rickhenderson/code-samples
python-blender/read_hadamard_file.py
Python
gpl-3.0
1,503
0.007984
# read_hadamard_file.py # Reads data from a text file to create a 3D # version of a given Hadamard Matrix. # Created by Rick Henderson # Created on June 4, 2015 # Completed June 5, 2015 # Note: A "Hadamard File" is a text file containing rows # rows of + and - where the + indicates a 1 or a cube # and th...
bpy.context.object.location[1] = char_number * yOffset #
Now an entire row has been read, so reset char_number to 0 char_number = 0 # Program Ends
nealegibson/Infer
setup.py
Python
gpl-3.0
518
0.027027
from numpy.distutils.core import setup, Extension #from setuptools import setup, Extension setup( name = "Infer", version = "1.0", description='Python version of MCMC, plus other
inference codes under development', author='Neale Gibson', author_email='ngibson@eso.org', packages=['Infer'], package_dir={'Infer':'src'}, #and extensi
on package for solving toeplitz matrices... ext_modules = [ Extension("Infer.LevinsonTrenchZoharSolve",sources=["src/LevinsonTrenchZoharSolve.c"],), ] )
eicher31/compassion-modules
partner_communication/models/__init__.py
Python
agpl-3.0
706
0.001416
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.comp
assion.ch) # Releasing children from poverty in Jesus' name # @author: Emanu
el Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from . import communication_config from . import communication_job from . import communication_attachment from . import res_partner from . import email from ....
jordanemedlock/psychtruths
temboo/core/Library/YouTube/Playlists/ListPlaylistsByID.py
Python
apache-2.0
6,403
0.00531
# -*- coding: utf-8 -*- ############################################################################### # # ListPlaylistsByID # Returns a collection of playlists that match the provided IDs. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen...
Secret', value) def set_Fields(se
lf, value): """ Set the value of the Fields input for this Choreo. ((optional, string) Allows you to specify a subset of fields to include in the response using an xpath-like syntax (i.e. items/snippet/title).) """ super(ListPlaylistsByIDInputSet, self)._set_input('Fields', value) de...
scionrep/scioncc
src/scripts/manhole.py
Python
bsd-2-clause
3,942
0.003298
#!/usr/bin/env python # "manhole" entry point, friendlier ipython startup to remote container __author__ = 'Dave Foster <dfoster@asascience.com>' def main(): import sys, os, re, errno, json, socket from pkg_resources import load_entry_point r = re.compile('manhole-(\d+).json') if len(sys.argv) == 2...
"--PromptManager.in2_template=... ", "--PromptManager.out_template=--> ",
"--TerminalInteractiveShell.banner1=%s" % manhole_logo, "--TerminalInteractiveShell.banner2=SciON Container Manhole, connected to %s\n(press Ctrl-D to detach, quit() to exit container)\n" % mhpid] # HACK: Mock out client shutdown to avoid default shutdown on Ctrl-D from mock import pat...
kiddinn/plaso
tests/output/formatting_helper.py
Python
apache-2.0
12,029
0.001912
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the output module field formatting helper.""" import unittest from dfdatetime import semantic_time as dfdatetime_semantic_time from dfvfs.path import fake_path_spec from plaso.containers import events from plaso.lib import definitions from plaso.output impo...
tFromValues(self._TEST_EVENTS[0])) filename_string = test_helper._FormatFilename( event, event_data, event_data_stream) self.assertEqual(filename_string, 'log/syslog.1') def testFormatHostname(self): """Tests the _FormatHostname function.""" output_mediator = self._CreateOutputMediator() ...
ent_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) hostname_string = test_helper._FormatHostname( event, event_data, event_data_stream) self.assertEqual(hostname_string, 'ubuntu') def testFormatInode(self): """Tests the _FormatInode function."...
openstack/horizon
openstack_dashboard/dashboards/admin/hypervisors/compute/urls.py
Python
apache-2.0
1,052
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
IES OR CONDITIONS OF ANY KIND, eit
her express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf.urls import url from openstack_dashboard.dashboards.admin.hypervisors.compute import views urlpatterns = [ url(r'^(?P<compute_host>[^/]+)/evacuate_host$', views...
CLVsol/oehealth
oehealth_professional/__init__.py
Python
agpl-3.0
1,597
0.010645
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
# # it under the terms of the GNU Affero 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 Affero General Public License for more details. ...
craigcitro/pydatalab
google/datalab/contrib/mlworkbench/commands/_ml.py
Python
apache-2.0
33,262
0.008689
# Copyright 2017 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 agre...
features: $features_def""")) analyze_parser.add_argument('--output', required=True, help='path of output directory.') analyze_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run analysis in cloud or local.') analyze_...
help='A local or GCS tarball path to use as the source. ' 'If not set, the default source package will be used.') analyze_parser.add_cell_argument( 'training_data', required=True, help=textwrap.dedent("""\ training data. It is one of the followi...
Freso/listenbrainz-server
listenbrainz/webserver/admin/views.py
Python
gpl-2.0
206
0
f
rom flask_admin import expose from listenbrainz.webserver.admin import AdminIndexView class HomeView(AdminIndexView): @expose('/') def index(self): return self.render('admin/home.ht
ml')
erik-stephens/zabbix
zabbix/__init__.py
Python
mit
266
0
""" A pythonic interface to the Zabbix API. """ from .api import A
pi, ApiException from .objects.host import Host from .objects.hostgroup import H
ostGroup from .objects.item import Item from .objects.trigger import Trigger from .objects.itservice import ItService
shabinesh/Tabject
tabject/types.py
Python
bsd-3-clause
550
0.016364
from decimal import Decimal class Integer: def __init__(self, val=None): self.val = int(val) def __repr__(self): return self.val class Text:
def __init__(self, val=None): self.val = str(val) def __repr__(self): return self.val class Bool: def __init__(self, val=None): self.val = bool(val) def __repr__(self): return self.val class Real:
def __init__(self, val=None): self.val = Decimal(val) def __repr__(self): return self.val class Date: pass
rutsky/aiohttp
setup.py
Python
apache-2.0
4,887
0
import codecs import pathlib import re import sys from distutils.command.build_ext import build_ext from distutils.errors import (CCompilerError, DistutilsExecError, DistutilsPlatformError) from setuptools import Extension, setup if sys.version_info < (3, 5, 3): raise RuntimeError("...
ensions, cmdclass=dict(build_ext=ve_build_ext), ) try: setup(**args) e
xcept BuildFailed: print("************************************************************") print("Cannot compile C accelerator module, use pure python version") print("************************************************************") del args['ext_modules'] del args['cmdclass'] setup(**args)
TshepangRas/tshilo-dikotla
td_maternal/models/maternal_clinical_measurements_one.py
Python
gpl-2.0
738
0.004065
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from edc_registration.models import RegisteredSubject from .base_maternal_clinical_measurements import BaseMaternalCli
nicalMeasurements class MaternalClinicalMeasurementsOne(BaseMaternalClinicalMeasurement
s): height = models.DecimalField( max_digits=5, decimal_places=2, verbose_name="Mother's height? ", validators=[MinValueValidator(134), MaxValueValidator(195), ], help_text="Measured in Centimeters (cm)") class Meta: app_label = 'td_maternal' verbose_na...
pulsar-chem/Pulsar-Core
test/old/Old2/modules/CP.py
Python
bsd-3-clause
2,969
0.022903
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * import pulsar_psi4 def ApplyBasis(syst,bsname,bslabel="primary"): return psr.system.apply_si...
F") mm.change_option("PSR_MBE","METHOD","PSI4_SCF") mm.change_option("PSI4_SCF","PRINT",0) mol=psr.system.make_system(""" 0 1 O 1.2361419 1.0137761 -0.0612424 H 0.5104418 0.8944555 0.5514190 H 1.9926927 1.1973129 0.4956931 O -0.99572...
H 0.4367536 -0.3759433 -0.9973297 H -0.5031835 -0.8251492 -2.0957959 """) mol = ApplyBasis(mol,"sto-3g","sto-3g") wfn=psr.datastore.Wavefunction() wfn.system=mol MyMod=mm.get_module("PSR_CP",0) NewWfn,Egy=MyMod.deriv(0,wfn) tester.test("T...
sparkslabs/kamaelia
Code/Python/Apps/Europython09/App/BB1.py
Python
apache-2.0
1,272
0.002358
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
for msg in self.Inbox("inbox"): self.send(msg, "outbo
x") self.pause() yield 1 self.send(self.recv("control"), "signal") ServerCore(protocol=RequestResponseComponent, port=1599).run()
deprofundis/deprofundis
models/scripts/example_crbm.py
Python
mit
2,313
0.006053
from models.sampler import DynamicBlockGibbsSampler from models.distribution import DynamicBernoulli from models.optimizer import DynamicSGD from utils.utils import prepare_frames from scipy import io as matio from data.gwtaylor.path import * import ipdb import numpy as np SIZE_BATCH = 10 EPOCHS = 100 SIZE_HIDDEN = 50...
(bernoulli, sampling_steps=1) sgd = DynamicSGD(bernoulli) for epoch in range(EPOCHS): error = 0.0 for chunk_idx_list in batch_idx_list: # get batch data set data = np.zeros(sha
pe=(SIZE_BATCH, SIZE_VISIBLE, SIZE_LAG)) for idx, (start, end) in enumerate(chunk_idx_list): data[idx, :, :] = dataset[start:end, :].T hidden_0_probs, hidden_0_states, \ hidden_k_probs, hidden_k_states, \ visible_k_probs, visible_k_states = gibbs_sampler.samp...
anhstudios/swganh
data/scripts/templates/object/tangible/deed/event_perk/shared_lambda_shuttle_static_deed.py
Python
mit
487
0.045175
#### NOTI
CE: 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 = Tangible() result.template = "object/tangible/deed/event_perk/shared_lambda_shuttle_static_deed.iff" result.attribute_temp...
# return result
lonnen/socorro
socorro/unittest/lib/test_task_manager.py
Python
mpl-2.0
2,418
0.000414
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from unittest import mock from configman.dotdict import DotDict from socorro.lib.task_manager import TaskManager, defa...
cking_start(waiting_func=waiting_func) assert tm.task_func.call_count == 10 assert waiting_func.
call_count == 0
dermoth/gramps
gramps/gen/db/generic.py
Python
gpl-2.0
88,300
0.000453
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015-2016 Gramps Development Team # Copyright (C) 2016 Nick Hall # # 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...
ck(None) if db.redo_callback: db.redo_callback(_("_Redo %s") % transaction.get_description()) if update_history and db.undo_history_callback: db.undo_history_callback() return True def undo_sigs(self, sigs, undo): ""
" Helper method to undo/redo the signals for changes made We want to do deletes and adds first Note that if 'undo' we swap emits """ for trans_type in [TXNDEL, TXNADD, TXNUPD]: for obj_type in range(11): handles = sigs[obj_type][trans_type] ...
reviewboard/reviewboard
reviewboard/hostingsvcs/bugtracker.py
Python
mit
1,633
0
from djblets.cache.backend import cache_memoize class BugTracker(object): """An interface to a bug tracker. BugTracker subclasses are used to enable interaction with different bug trackers. """ def get_bug_info(self, repository, bug_id): """Get the information for the specified bug. ...
us': '', } def make_bug_cache_key(self, repository, bug_id): """Returns a key to use when caching fetched bug information."""
return 'repository-%s-bug-%s' % (repository.pk, bug_id)
TaskEvolution/Task-Coach-Evolution
taskcoach/taskcoachlib/widgets/__init__.py
Python
gpl-3.0
1,717
0.000582
''' Task Coach - Your friendly task manager Copyright (C) 2004-2013 Task Coach developers <developers@taskcoach.org> Task Coach 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 ...
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/>. ''' from notebook import Notebook, BookPage from frame import AuiManagedFrameWithDynamicCenter...
kDialog, HTMLDialog, AttachmentSelector from itemctrl import Column from listctrl import VirtualListCtrl from checklistbox import CheckListBox from treectrl import CheckTreeCtrl, TreeListCtrl from squaremap import SquareMap from timeline import Timeline from datectrl import DateTimeCtrl, TimeEntry from textctrl import ...
hackshel/py-aluminium
src/__furture__/simplepool.py
Python
bsd-3-clause
3,289
0.023995
#!/usr/bin/env python """simple thread pool @author: dn13(dn13@gmail.com) @author: Fibrizof(dfang84@gmail.com) """ import threading import Queue import new def WorkerPoolError( Exception ): pass class Task(threading.Thread): def __init__(self, queue, result_queue): threading.Thread.__init__(self) ...
: raise WorkerPoolError, 'Pool has been joined' def join( self ): self.is_in_join = True self.q.join() self.is_in_join = False return def runwithpool( self, _old ):
def _new( *args, **kwargs ): self.q.put( lambda : _old( *args, **kwargs ) ) return _new def registtopool( self, _old ): if _old.__name__ in self._registfunctions : raise WorkerPoolError, 'function name exists' self._registfu...
piton-package-manager/piton
piton/commands/outdated.py
Python
mit
1,511
0.031105
from ..utils.co
mmand import BaseCommand from ..utils.tabulate import tabulate from ..utils.info import get_packages, Sources class Colors: PURPLE = '\033[95m' OKBLUE = '\033[94m' OKGRE
EN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' UNDERLINE = '\033[4m' ENDC = '\033[0m' class Command(BaseCommand): name = "outdated" @classmethod def run(cls, args): cls._run() @classmethod def _run(cls): packages = get_packages((Sources.required, Sources.installed)) packages = list(filter(lambda...
abhattad4/Digi-Menu
tests/migrations/test_commands.py
Python
bsd-3-clause
37,861
0.002803
# -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import importlib import os import shutil from django.apps import apps from django.core.management import CommandError, call_command from django.db import DatabaseError, connection, models from django.db.migrations import questioner from dja...
' [ ] 0001_initial\n' ' [ ] 0002_second\n', out.getvalue().lower() ) call_command("migrate", "migrations", "0001", verbosity=0) out = six.StringIO() # Giving the explicit app_label tests for
selective `show_list` in the command call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True) self.assertEqual( 'migrations\n' ' [x] 0001_initial\n' ' [ ] 0002_second\n', out.getvalue().lower() ) ...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/psrc/person/home_grid_id.py
Python
gpl-2.0
2,165
0.0194
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 Unive
rsity of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label class home_grid_
id(Variable): '''The grid_id of a person's residence.''' def dependencies(self): return [my_attribute_label('household_id'), 'psrc.household.grid_id'] def compute(self, dataset_pool): households = dataset_pool.get_dataset('household') return self.g...
abalakh/robottelo
tests/foreman/api/test_docker.py
Python
gpl-3.0
47,259
0.000042
# -*- encoding: utf-8 -*- """Unit tests for the Docker feature.""" from fauxfactory import gen_choice, gen_string, gen_url from nailgun import entities from random import randint, shuffle from requests.exceptions import HTTPError from robottelo.api.utils import promote from robottelo.constants import DOCKER_REGISTRY_HU...
Create one Docker-type repo
sitory @Assert: A repository is created with a Docker image. @Feature: Docker """ for name in valid_data_list(): with self.subTest(name): repo = _create_repository( entities.Product(organization=self.org).create(), na...
akuster/yali
yali/storage/library/__init__.py
Python
gpl-2.0
125
0.008
#!
/usr/bin/python # -*- coding: utf-8 -*- from yali.storage import StorageError class LibraryError(StorageError): p
ass
mvillalba/codinghyde.ant
demos/ant/02-capabilities.py
Python
mit
769
0
""" Interrogate stick for supported capabilities. """ import sys from codinghyde.ant import driver from codinghyde.ant import node from config import * # Initialize stick = driver.USB1Driver(SERIAL, debug=DEBUG) antnode = node.Node(stick) antnode.start() # Interrogate stick # Note: This method will return
immediately, as the stick's capabilities are # interrogated on node initialization (node.start()) in order to set proper # internal Node instance state. capabilities = antnode.getCapabilities() print 'Maximum channels:', capabilities['max_channels'] print 'Maximum network keys:', capabilities['max_net_keys'] print 'St...
stop()
punchagan/zulip
zerver/lib/users.py
Python
apache-2.0
21,312
0.001548
import re import unicodedata from collections import defaultdict from typing import Any, Dict, List, Optional, Sequence, Union from django.conf import settings from django.core.exceptions import ValidationError from django.db.models.query import QuerySet from django.forms.models import model_to_dict from django.utils....
mezone from zerver.models import ( CustomProfileField, CustomProfileFieldValue, Realm, Service, UserProfile, get_realm_user_dicts, get_user_profile_by_id_in_realm, ) def check_full_name(full_name_raw: str) -> str: full_name = full_name_raw.strip() if len(full_name) > UserProfile.MA...
"Name too long!")) if len(full_name) < UserProfile.MIN_NAME_LENGTH: raise JsonableError(_("Name too short!")) for character in full_name: if unicodedata.category(character)[0] == "C" or character in UserProfile.NAME_INVALID_CHARS: raise JsonableError(_("Invalid characters in name!"))...
icyflame/batman
setup.py
Python
mit
7,976
0.000251
# -*- coding: utf-8 -*- """Installer script for Pywikibot 2.0 framework.""" # # (C) Pywikibot team, 2009-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals import itertools import os import sys PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON_VERSIO...
32. # These tests may be disabled because pywin32 depends on VC++, is time # comsuming to build, and the console window cant be accessed during appveyor # builds. # Microsoft makes available a compiler for Python 2.7 # http://www.microsoft.com/en-au/download/details.aspx?id=44266 # If you set up your own compiler for P...
ed with pywin32 may fail. Remove com/win32com/demos/ie*.py if os.name == 'nt' and os.environ.get('PYSETUP_TEST_NO_UI', '0') != '1': # FIXME: tests/ui_tests.py suggests pywinauto 0.4.2 # which isnt provided on pypi. test_deps += ['pywin32', 'pywinauto>=0.4.0'] extra_deps.update(script_deps) # Add all depe...
devopservices/ansible
lib/ansible/cache/jsonfile.py
Python
gpl-3.0
4,163
0.004324
# (c) 2014, Brian Coca, Josh Drake, et al # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ...
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 Ansible. If not, see <http://www.gnu.org
/licenses/>. import os import time import errno try: import simplejson as json except ImportError: import json from ansible import constants as C from ansible import utils from ansible.cache.base import BaseCacheModule class CacheModule(BaseCacheModule): """ A caching module backed by json files. ...
AASHE/iss
iss/management/commands/upsert_iss_domains.py
Python
mit
1,085
0
#!/usr/bin/env python """Upserts Domains from Salesforce Domain__c. """ import logging import os from django.core.management.base import BaseCommand import iss.models import iss.salesfo
rce logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-m', '--modified-within', type=int, metavar='n-days', default=7, ...
rt_domains(options['modified_within']) def upsert_domains(modified_since=7): """Upsert Domains for SF Domain__c modified in last `modified_since` days. """ logger.info('upserting domains modified in last {since} days'. format(since=modified_since)) modified_domains = (iss.salesforce.Do...
nabla-c0d3/sslyze
tests/plugins_tests/test_elliptic_curves_plugin.py
Python
agpl-3.0
2,148
0.005121
from sslyze import ServerNetworkLocation from sslyze.plugins.elliptic_curves_plugin import ( SupportedEllipticCurvesScanResult, SupportedEllipticCurvesImplementation, ) from tests.connectivity_utils import check_connectivity_to_server_and_return_info from tests.markers import can_only_run_on_linux_64 from tests...
ver i
mport ModernOpenSslServer class TestEllipticCurvesPluginWithOnlineServer: def test_supported_curves(self): # Given a server to scan that supports ECDH cipher suites server_location = ServerNetworkLocation("www.cloudflare.com", 443) server_info = check_connectivity_to_server_and_return_info...
ravello/testmill
lib/testmill/command_run.py
Python
apache-2.0
4,718
0.000848
# Copyright 2012-2013 Ravello Systems, 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 agree...
unction import argparse import textwrap from testmill import (console, manifest, keypair, login, error, application, tasks, util, inflect) from testmill.state import env usage = textwrap.dedent("""\ usage: ravtest [OPTION]... run [-i] [-c] [--new] [--vms <vmlist>] ...
plication. The application defined by <application> is loaded from the manifest (.ravello.yml). It is then created if it doesn't exist yet, and the runbook defined in the manifest is run. If --new is specified, a new application instance is always created, even if one e...
kiniou/qtile
libqtile/state.py
Python
mit
2,415
0
# Copyright (c) 2012, Tycho Andersen. All rights reserved. # # 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 limitation the rights # to use, copy, modif...
self, qtile): """ Rearrange the windows in the specified Qtile object according to
this QtileState. """ for (group, layout) in self.groups.items(): try: qtile.groupMap[group].layout = layout except KeyError: pass # group missing for (screen, group) in self.screens.items(): try: group...
ZmG/trywsk
base/admin.py
Python
apache-2.0
1,654
0.009069
__author__ = 'thatcher' from django.contrib import admin # from django.contrib.auth.models import User # from django.contrib.auth.admin import UserAdmin # from django.contrib.sessions. from django.contrib.sessions.models import Session from .models import * from base.forms import * def images_thubmnail(self): ret...
), self.alt) # return self.uri() images_thubmnail.short_description = 'Thumbnail' images_thubmnail.allow_tags = True class TeamMemberAdmin(admin.ModelAdmin): model = TeamMember list_display = ['full_name', 'sort_weight', 'show_as_team'] admin.site.register(TeamMember, TeamMemberAdmin) class NewsItemAdmin...
'author'] admin.site.register(NewsItem, NewsItemAdmin) class EventAdmin(admin.ModelAdmin): model = Event list_display = ['title', 'location', 'date_and_time'] admin.site.register(Event, EventAdmin) class PostAdmin(admin.ModelAdmin): model = GenericPost list_display = ['title', 'category', 'publicatio...
SamuelDSR/YouCompleteMe-Win7-GVIM
third_party/jedi/jedi/imports.py
Python
gpl-3.0
15,994
0.000813
""" :mod:`imports` is here to resolve import statements and return the modules/classes/functions/whatever, which they stand for. However there's not any actual importing done. This module is about finding modules in the filesystem. This can be quite tricky sometimes, because Python imports are not always that simple. ...
# os.path is a hardcoded exception, because it's a
# ``sys.modules`` modification. p = (0, 0) names.append(pr.Name(self.GlobalNamespace, [('path', p)], p, p, self.import_stmt)) continue for s, scope_names in evaluate.get_names_of_scope(scope, ...
keon/algorithms
algorithms/queues/moving_average.py
Python
mit
749
0
f
rom __future__ import division from collections import deque class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.que
ue = deque(maxlen=size) def next(self, val): """ :type val: int :rtype: float """ self.queue.append(val) return sum(self.queue) / len(self.queue) # Given a stream of integers and a window size, # calculate the moving average of all integers in the sliding window. i...
mtoshi/rancidcmd
setup.py
Python
mit
2,154
0
# -*- coding: utf-8 -*- """Racndicmd setup.py."""
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import os import sys class Tox(TestCommand): """Tox.""" user_options = [('tox-args=', 'a', "Arguments to pass to tox")] def initialize_options(self): """Init.""" TestCommand.initialize_...
): """Finalize.""" TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): """Run.""" import tox import shlex if self.tox_args: errno = tox.cmdline(args=shlex.split(self.tox_args)) else: ...
rahmonov/agile-crm-python
agilecrm/client.py
Python
mit
454
0
from .company import Co
mpany from .contact import Contact from .deal import Deal from .note import Note from .requester import Requester class AgileCRM: def __init__(self, domain, email, api_key): requester = Requester(domain, email, api_key) self.contact = Contact(requester=requester) self.company = Company(re...
te(requester=requester)
jtraver/dev
python3/matplotlib/plot1.py
Python
mit
220
0.004545
#!/usr/bin/env py
thon3 #!/usr/bin/python # https://en.wikipedia.org/wiki/Matplotlib import numpy import matplotlib.pypl
ot as plt from numpy.random import rand a = rand(100) b = rand(100) plt.scatter(a, b) plt.show()
woozzu/tf_tutorials
03_MLP_spiral2D.py
Python
mit
3,767
0.009557
''' A MLP algorithm example using TensorFlow library. This example is using generate random distribution (http://cs231n.github.io/neural-networks-case-study/) Code references: https://github.com/shouvikmani/Tensorflow-Deep-Learning-Tutorial/blob/master/tutorial.i
pynb https://github.com/aymericdamien/TensorFlow-Examples/ http://cs231n.github.io/neural-networks-case-study/ The source code modified modified by S.W. Oh. ''' from __future__ import print_function import tensorflow as tf import numpy as np from matplotlib import pyplot as plt # import Dense (fully-conne
cted) layer from util.layer import Dense ###### Generate 2D spiral random data and Plot ################################### N = 200 # number of points per class D = 2 # dimensionality K = 4 # number of classes X_train = np.zeros((N*K,D)) # data matrix (each row = single example) y_train = np.zeros((N*K,K)) # class lab...
PaloAltoNetworks/minemeld-core
tests/traced_mock.py
Python
apache-2.0
5,455
0.0033
# Copyright 2016 Palo Alto Networks, 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 agre...
%016x' % (timestamp, counter) items = [[k, v] for k, v in self.db.iteritems() if k <= starting_key] items = sorted(items, cmp=lambda x, y: cmp(x[0], y[0]), reverse=True)
return items def close(self): self.db_open = False @staticmethod def oldest_table(): tables = [t.name for t in MOCK_TABLES] LOG.debug(tables) if len(tables) == 0: return None return sorted(tables)[0] def table_factory(name, create_if_missing=True): ...
TheAnosmic/cheetahs_byte
tests/test_compile/test_jmp_add.py
Python
gpl-2.0
3,283
0
from unittest import TestCase from compile import add_jmp_opcodes, break_to_atoms from compile.jmp_add import travel, shuffle from opcode_ import PRT class TestJMPAdd(TestCase): def test_added_init_jmp(self): node_chain = PRT.build_from_string('u', None) atoms = break_to_atoms(node_chain) ...
.build_from_string('m', None) + \ PRT.build_from_string('i', None) + \ PRT.build_from_string('c', None) last = node_chain[-1] atoms = break_to_atoms(node_chain) atoms = add_jmp_opcodes(atoms) atom = atoms[0] for _ in range(len(node_chain...
atom = next_atom else: self.fail("Chain ended too soon") self.assertIn(last, atom) def test_reach_to_end_with_shuffle(self): # TODO why some are NC of NC and some NC of NODs? node_chain = PRT.build_from_string('T', None) + \ PRT....
bunnydev26/django_newboston
music/admin.py
Python
gpl-3.0
149
0
from django.contrib import admin from .models impo
rt Album, Song # Register your models here.
admin.site.register(Album) admin.site.register(Song)
marshallmcdonnell/interactive_plotting
Traits/manual/testing_hasstricttraits.py
Python
mit
547
0.005484
#!/usr/bin/env python from traits.api import HasStrictTraits, Float from mock import Mock class MyClass(HasStrictTraits): number = Float(2.0) def add_to_number(self, value): """ Add th
e value to `number`. """ self.number += value my_class = MyClass()
# Using my_class.add_to_number = Mock() will fail. # But setting the mock on the instance `__dict__` works. my_class.__dict__['add_to_number'] = Mock() # We can now use the mock in our tests. my_class.add_to_number(42) print my_class.add_to_number.call_args_list
russellb/gerrymander
gerrymander/model.py
Python
apache-2.0
15,825
0.000569
# # Copyright (C) 2014 Red Hat, 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 wr...
val in self.approvals: if approval.is_nack(): return True return False def get_age(self, now): if len(self.approvals) == 0: return now - self.createdOn age = 0 for approval in self.approvals: thisage = now - approval.grantedOn ...
patch has been reviewed by any users that are not in 'excludeusers''' hasReviewers = False for approval in self.approvals: if not approval.is_user_in_list(excludeusers): hasReviewers = True return hasReviewers def has_reviewers(self, includeusers): ...
fantoms/psychic-octo-spork
chipdisable.py
Python
gpl-3.0
1,217
0.028759
#!/usr/bin/python import Adafruit_GPIO as GPIO import time, os #print "GETTING GPIO OBJECT" gpio = GPIO.get_platform_gpio() #print "SETUP CSID1" #gpio.setup("CSID1", GPIO.OUT) #print os.path.exists('/sys/class/gpio/gpio133') #print "SETUP XIO-P1" #gpio.setup("XIO-P1", GPIO.IN) #GPIO.setup("U14_13", GPIO.IN) #prin...
"LOW", gpio.input("XIO-P0") #print "LOW", gpio.input("XIO-P1") #gpio.output("XIO-P0", GPIO.HIGH) #print "LOW", gpio.input("XIO-P0") #print "LOW", gpio.input("XIO-P1") #time.sleep(4) #gpio.output("XIO-P0", GPIO.LOW) #print "LOW", gpio.input("XIO-P0") #print "LOW", gpio.input("XIO-P1") #print "CLEA
NUP" #gpio.cleanup() gpio.setup("XIO-P0", GPIO.OUT) gpio.output("XIO-P0", GPIO.HIGH)
i3visio/osrframework
osrframework/wrappers/teamtreehouse.py
Python
agpl-3.0
3,948
0.00456
################################################################################ # # Copyright 2015-2020 Félix Brezo and Yaiza Rubio # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU Affer
o 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 FITN...
# along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ __author__ = "Felix Brezo, Yaiza Rubio <contacto@i3visio.com>" __version__ = "2.0" from osrframework.utils.platforms import Platform class Teamtreehouse(Pla...
caktus/django-opendebates
opendebates/views.py
Python
apache-2.0
19,833
0.001311
import datetime import json import logging from django.contrib import messages from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model from django.contrib.auth.decorators import login_required from django.contrib.auth.views import logout from django.contrib.sites.shortcuts import get_current_site from djan...
ideas = sort_list(citations_only, sort, ideas) return { 'ideas': ideas, 'sort': sort, 'url_name': reverse('list_ideas'), 'stashed_submission': request.session.pop( "opendebates.stashed_submission", None) if request.user.is_authenticated else None, } @rendered...
deas.html") def list_category(request, cat_id): category = get_object_or_404(Category, id=cat_id, debate=request.debate) ideas = Submission.objects.filter(category__debate=request.debate, category=cat_id) citations_only = request.GET.get("citations_only") sort = choose_sort(request, request.GET.get('sor...
joakim-hove/ert
res/enkf/queue_config.py
Python
gpl-3.0
6,283
0.001751
# Copyright (C) 2017 Equinor ASA, Norway. # # The file 'site_config.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 Lic...
self._assert_lsf(key=QueueConfig.LSF_RESOURCE_KEY) return self._lsf_driver.get_option(self.LSF_RESOURCE_KEY) @property def lsf_server(self): self._assert_lsf(key=QueueConfig
.LSF_SERVER_KEY) return self._lsf_driver.get_option(self.LSF_SERVER_KEY) @property def num_cpu(self): return self._get_num_cpu() def __eq__(self, other): if self.max_submit != other.max_submit: return False if self.queue_system != other.queue_system: ...
wvangeit/AllenSDK
setup.py
Python
gpl-3.0
1,828
0.012582
from setuptools import setup, find_packages import os import allensdk # http://bugs.python.org/issue8876#msg208792 if hasattr(os, 'link'): del os.link def prepend_find_packages(*roots): ''' Recursively traverse nested packages under the root directories ''' packages = [] for root in roots: ...
, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Natural Language :: English', '
Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Bio-Informatics' ])
m00dawg/holland
plugins/holland.lib.lvm/tests/xfs/test_snapshot.py
Python
bsd-3-clause
1,824
0.004386
import shutil from nose.tools import * from holland.lib.lvm import LogicalVolume from holland.lib.lvm.snapshot import * from tests.constants import * class TestSnapshot(object): def setup(self): self.tmpdir = tempfile.mkdtemp() def teardown(self): shutil.rmtree(self.tmpdir) def test_snap...
args, **kwargs): raise Exception("Oooh nooo!") for evt in ('initialize', 'pre-snapshot', 'pos
t-snapshot', 'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount', 'pre-remove', 'post-remove', 'finish'): snapshot.register(evt, bad_callback) assert_raises(CallbackFailuresError, snapshot.start, lv) snapshot.unregister(evt, bad_callback)...
frenzykryger/hamachi-watchdog
hamachi-watchdog.py
Python
bsd-2-clause
745
0
#!/usr/bin/env python3 import json import os import subprocess def connection_lost(network_id, timeout_seconds): p = subprocess.Popen(["hamachi", "go-online", network_id]) try: p.wait(timeout_seconds) except subprocess.TimeoutExpired: p.kill() return True return False if __na...
ds = config['timeout_seconds'] if connection_lost(network_id, timeout_seconds): print("Hamachi looks down. Rest
arting it...") os.system("systemctl restart logmein-hamachi.service") print("Hamachi was restarted")
drewkett/SU2
SU2_PY/merge_solution.py
Python
lgpl-2.1
2,861
0.00769
#!/usr/bin/env python ## \file merge_solution.py # \brief Python script for merging of the solution files. # \author F. Palacios # \version 6.1.0 "Falcon" # # The current SU2 release has been coordinated by the # SU2 International Developers Society <www.su2devsociety.org> # with selected contribut
ions from the open-source community. # # The main research teams contributing to the current release are: # - Prof. Juan J. Alonso's group at Stanford University. # - Prof. Piero Colonna's group at Delft University of Technology. # - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology. # - Pr...
of Milan. # - Prof. Rafael Palacios' group at Imperial College London. # - Prof. Vincent Terrapon's group at the University of Liege. # - Prof. Edwin van der Weide's group at the University of Twente. # - Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics. # # Copyright 2012-2018, Francisco D. P...
sysadminmatmoz/pmis
project_progress_measurement/wizard/__init__.py
Python
agpl-3.0
237
0
# -*- coding: utf-8 -
*- # Copy
right 2014-17 Eficent Business and IT Consulting Services S.L. # <contact@eficent.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from . import progress_measurements_entry
pawkoz/dyplom
blender/doc/python_api/examples/bge.texture.1.py
Python
gpl-2.0
1,051
0.001903
""" Texture Replacement +++++++++++++++++++ Example of how to replace a texture in game with an external image. ``createTexture()`` and ``removeTexture()`` are to be called from a module Python Controller. """ from bge import logic from bge import texture def createTexture(cont): """Create a new Dyna
mic Texture""" obj = cont.owner # get the reference pointer (ID) of the internal texture ID = texture.materialID(obj, 'IMoriginal.png') # create a texture object object_texture = texture.Texture(obj, ID) # create a new source with an external image url = logic.expandPath("//newtexture.jpg...
new_source = texture.ImageFFmpeg(url) # the texture has to be stored in a permanent Python object logic.texture = object_texture # update/replace the texture logic.texture.source = new_source logic.texture.refresh(False) def removeTexture(cont): """Delete the Dynamic Texture, reversing back ...
hakuya/higu
lib/hdbfs/ark.py
Python
bsd-2-clause
8,385
0.025164
import os import shutil import tempfile import zipfile class ZipVolume: def
__init__( self, path ): self.zf = zipfile.ZipFile( path, 'r' ) self.ls = {} self.__load_ls() def __load_ls( self ): ils = self.zf.infolist() for i in ils: try: ids, e = i.filename.split( '.' ) id = int( ids, 16 ) ...
rom zip' % ( i.filename, ) pass def verify( self ): return self.zf.testzip() is None def read( self, id, extension ): try: info = self.ls[id] return self.zf.open( info, 'r' ) except KeyError: return None def _debug_write( self,...
arnavd96/Cinemiezer
myvenv/lib/python3.4/site-packages/music21/ext/jsonpickle/__init__.py
Python
mit
5,049
0.00099
# -*- coding: utf-8 -*- # # Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Python libr...
disabled. Objects that are id()-identical won't be preserved across encode()/decode(), but the resulting JSON stream will be conceptually simpler. jsonpickle detects cyclical objects and will break the cycle by calling repr() instead of recursing when make_refs is set False. :param keys...
n jsonpickle will encode non-string dictionary keys instead of coercing them into strings via `repr()`. :param warn: If set to True then jsonpickle will warn when it returns None for an object which it cannot pickle (e.g. file descriptors). :param max_iter: If set to a non-negative integ...
parmarmanojkumar/MITx_Python
6002x/week2/lectureCode_intDict.py
Python
mit
1,482
0.008097
import random class intDict(object): """A dictionary with integer keys""" def __init__(self, nu
mBuckets): """Create an empty dictionary""" self.buckets = [] self.numBuckets = numBuckets for i in range(numBuckets): self.buckets.append([]) def addEntry(self, dictKey, dictVal): """Assumes dictKey an int. Adds an entry.""" hashBucket = sel...
hashBucket[i] = (dictKey, dictVal) return hashBucket.append((dictKey, dictVal)) def getValue(self, dictKey): """Assumes dictKey an int. Returns entry associated with the key dictKey""" hashBucket = self.buckets[dictKey%self.numBuckets] for e ...
Jorisvansteenbrugge/advbioinf
rosalind/python/fib.py
Python
gpl-3.0
489
0.022495
#!/usr/bin/env python from sys i
mport argv def calcRabbits(n,k): pairs = [1, 1] for i in range(2,n): #try: f1 = pairs[i-1] f2 = pairs[i-2] * 3 pairs.append((f1+f2)) # except IndexError: # pass return pairs if __name__ == "__main__": try: n = int(argv[1]) k = ...
ntK>")
gitsimon/tq_website
partners/cms_plugins/partners_plugin.py
Python
gpl-2.0
859
0.001164
from cms.models.pluginmodel import CMSPlugin from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.utils.translation import get_language from partners.models import Partner class PartnersPlugin(CMSPluginBase): name = _...
llow_children = False def render(self, context, instance, placeholder): language = get_language() if language is None: language = 'en' partners = Partner.objects.filter(active=True).translated(language).order_by('translations__name').all() context.update({ 'p...
register_plugin(PartnersPlugin)
espenak/pinax-oldversion-backup
pinax/apps/signup_codes/views.py
Python
mit
4,496
0.004448
from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext from django.contrib import messages from django.contrib.adm...
leaned_data["signup_code"] if signup_code: signup_code.use(user)
form.login(request, user) messages.add_message(request, messages.SUCCESS, ugettext("Successfully logged in as %(username)s.") % { "username": user_display(user), } ) return HttpResponseRedirect(success_url) else: ...
beddit/sleep-musicalization-web
manage.py
Python
bsd-2-clause
258
0
#!/usr/bin/env python import os import sys if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sleeptomusicweb.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.arg
v)
mattseymour/django
tests/view_tests/tests/test_static.py
Python
bsd-3-clause
5,569
0.000898
import mimetypes import unittest from os import path from django.conf.urls.static import static from django.http import FileResponse, HttpResponseNotModified from django.test import SimpleTestCase, override_settings from django.utils.http import http_date from django.views.static import was_modified_since from .. imp...
self.assertEqual(fp.read(), response_content) def test_is_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT' ) response_conten
t = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) def test_not_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF...
MichaelSEA/python_koans
python3/koans/triangle.py
Python
mit
1,017
0.003933
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a,
b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangl...
{c}") sum1 = a + b sum2 = a + c sum3 = b + c if sum1 <= c or sum2 <= b or sum3 <= a: raise TriangleError("Sum of any two sides must be greater than third one.") if a == b == c: return 'equilateral' if a == b or b == c or a == c: return 'isosceles' return 'scalene...
HalfLike/qc-web-server
app/models.py
Python
apache-2.0
1,467
0.00818
#!/usr/bin/python #! -*- coding:utf-8 -*- from sqlalchemy import Column, Integer, String from database import Base class Message(Base): __tablename__ = 'message' MessageId = Column(Integer, primary_key=True) DeviceId = Column(String(50)) MessageBody = Column(String(1000)) MessageType = Column(Inte...
"MessageType":self.MessageType, "MessageBody":self.MessageBody } def __repr__(self): return repr(self.get_json()) class UserInfo(Base): __tablename__ = 'userinfo' Devic
eId = Column(String(50), primary_key=True) UseTimes = Column(Integer) LastUseTime = Column(String(50)) def __init__(self, json): self.DeviceId = json["DeviceId"] self.UseTimes = json["UseTimes"] self.LastUseTime = json["LastUseTime"] def get_json(self): return { ...
nburn42/tensorflow
tensorflow/contrib/distribute/python/one_device_strategy.py
Python
apache-2.0
4,931
0.009126
# Copyright 2018 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...
_init__( self, distribution_strategy, tower_id=0)
@property def device(self): return self._distribution_strategy.worker_devices[0]
farvardin/txt2tags-test
targets/html5.py
Python
gpl-2.0
3,582
0.019542
""" A HTML5 target. """ from targets import _ from html import TYPE import html NAME = _('HTML5 page') EXTENSION = 'html' HEADER = """\ <!DOCTYPE html> <html> <head> <meta charset="%(ENCODING)s"> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.org"> <link rel="stylesheet" href="%(STYLE)s"...
: '<hr class="light">' , 'bar2' : '<hr class="heavy">' , 'img' : '<img~a~ src="\a" alt="">' , 'imgEmbed' : '<img~a~ src="\a" alt="">' , '_imgAlignLeft' : ' class="left"' , '_imgAlignCenter' : ' class="center"', '_imgAlignR...
sadad111/leetcodebox
Distribute Candies.py
Python
gpl-3.0
338
0
class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ result = 0 kind = list(set(candies)) if len(kind) > len(candies)/2: result = len(candi
es)/2 else: result = len(kind) return
result
nushio3/chainer
chainer/functions/local_response_normalization.py
Python
mit
4,265
0.003751
import numpy from chainer import cuda, Function def _cu_conv_sum(y, x, n): # Convolutional sum # TODO(beam2d): Use sca
n computation rdim = x.size / (x.shape[0] * x.shape[1]) cuda.elementwise(
'float* y, const float* x, int rdim, int N, int n_', ''' int half_n = n_ / 2; int offset = i / rdim * N * rdim + i % rdim; float* xi = x + offset; float* yi = y + offset; float sum_part = 0; for (int j = 0; j < N + half_n; ++j) { if (j...