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
godiard/read-activity
epubview/jobs.py
Python
gpl-2.0
10,330
0.001065
# Copyright 2009 One Laptop Per Child # Author: Sayamindu Dasgupta <sayamindu@laptop.org> # WebKit2 port Copyright (C) 2018 Lubomir Rintel <lkundrak@v3.sk> # # 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 ...
Returns the number of pages in file ''' return self._filedict[filename][0] def get_base_pageno_for_file(self, filename): ''' Returns the pageno which
begins in filename ''' for key in list(self._pagemap.keys()): if self._pagemap[key][0].replace('file://', '') == filename: return key return None def get_remfactor_for_file(self, filename): ''' Returns the remainder factor (1 - fraction ...
martin-ejdestig/sork
sork/commands/__init__.py
Python
gpl-3.0
66
0
from .
import analyze from . import assembler from . import check
rs/webassets
src/webassets/filter/cssutils.py
Python
bsd-2-clause
1,512
0.000661
from __future__ import absolute_import import logging import logging.handlers from web
assets.filter import Filter __all__ = ('CSSUtilsFilter',) class CSSUtilsFilter(Filter): """Minifies CSS by removing whitespace, comments etc., using the Python `cssutils <http://cthedot.de/cssutils/>`_ library. Note that since this works as a parser on the syntax level, so invalid CSS in...
def setup(self): import cssutils self.cssutils = cssutils try: # cssutils logs to stdout by default, hide that in production if not self.env.debug: log = logging.getLogger('assets.cssutils') log.addHandler(logging.handlers.MemoryH...
Azure/azure-sdk-for-python
sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_operations.py
Python
mit
31,189
0.005483
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
trol, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct par
ameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if skiptoken is not None: query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 's...
barentsen/dave
milesplay/fitData.py
Python
mit
20,751
0.01277
#============================================================================== # # Author: Miles Currie # Created: 06/21/2016 # # Cleaned up a little # # #============================================================================== import numpy as np import matplotlib.pyplot as plt import dave.fileio.mastio as m...
rgetPixelArrayFromFits(fits, hdr) # get the thruster firing indeces q = fits['QUALITY'].astype(np.uint32) idx1 = q & kplrfits.SapQuality['DefiniteRollTweak'] idx2 = q & kplrfits.SapQuality['MomDump'] idx3 = idx1 + idx2 return cube, idx3 def normalize(lcvMatrix): lcvMatrix
Norm = [] for lcv in lcvMatrix: if np.std(lcv) == 0.0: continue else: lcv = (lcv - np.mean(lcv))/np.std(lcv) lcvMatrixNorm.append(lcv) return np.array(lcvMatrixNorm) def getPrinComps(lcvMatrixNorm): return np.linalg.svd(lcvMatrixNorm, full_mat...
rohitranjan1991/home-assistant
homeassistant/components/zha/lock.py
Python
mit
6,641
0.000602
"""Locks on Zigbee Home Automation networks.""" import functools import voluptuous as vol from zigpy.zcl.foundation import Status from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeas...
nit this sensor.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK) async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_...
self._doorlock_channel, SIGNAL_ATTR_UPDATED, self.async_set_state ) @callback def async_restore_last_state(self, last_state): """Restore previous state.""" self._state = VALUE_TO_STATE.get(last_state.state, last_state.state) @property def is_locked(self) -> bool: ...
unicef/un-partner-portal
backend/unpp_api/apps/partner/migrations/0016_auto_20170920_0340.py
Python
apache-2.0
4,330
0.001617
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-20 03:40 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('partner', '0015_auto_20170912_0844'), ] operations = ...
ame='registration_number', ), migrations.RemoveField( model_name='partnerprofile', name='register_country', ), migrations.AddField( model_name='partner', name='engagement_operate_desc', field=mode
ls.CharField(blank=True, max_length=255, null=True, verbose_name="Briefly describe the organization's engagement with the communities in which you operate"), ), migrations.AddField( model_name='partner', name='staff_in_country', field=models.CharField(blank=True, choi...
cliftonmcintosh/openstates
billy_metadata/vt.py
Python
gpl-3.0
2,384
0.003356
metadata = dict( name='Vermont', abbreviation='vt', capitol_timezone='America/New_York', legislature_name='Vermont General Assembly', legislature_url='http://legislature.vermont.gov/', chambers = { 'upper': {'name': 'Senate', 'title': 'Senator', 'term': 2}, 'lower': {'name': 'Hou...
={'2009-2010': {'type': 'primary', 'display_name': '2009-2010 Regular Session', '_scraped_name': '2009-2010 Session', }, '2011-2012': {'type': 'primary', 'displ...
d_name': '2011-2012 Session', }, '2013-2014': {'type': 'primary', 'display_name': '2013-2014 Regular Session', '_scraped_name': '2013-2014 Session', }, ...
mazvv/travelcrm
travelcrm/lib/helpers/fields.py
Python
gpl-3.0
49,205
0.002175
# -*coding: utf-8-*- from collections import namedtuple from pytz import common_timezones from webhelpers2.html import tags from webhelpers2.html import HTML from ...interfaces import IServiceType from ...resources.accomodations import AccomodationsResource from ...resources.employees import EmployeesResource from ....
view: bufferview, %(on_before_load)s %(on_success_load)s """ % ({ 'url': self._url, 'id_field': s
elf._id_field, 'text_field': self._text_field, 'columns': ( jsonify(self._fields) if not isinstance(self._fields, basestring) else self._fields ), 'id': jsonify(self._value), 'obj_id': self._id, 'on...
petrblahos/modellerkit
step02/tkl.py
Python
mit
3,894
0.001284
""" A micro tk app with a list driven by the model. """ import logging from Tkinter import * from ttk import Treeview import hotlist class MVCList(Treeview): def __init__(self, parent, model): Treeview.__init__( self, parent, columns=["COL0", "COL1"]...
= self.insert("", index, text="") self.counter += 1 for (index, value) in enumerate(data): self.set(item, index, value) class Application(Frame): def add_item(self): """ The handler for t
he add button. """ self.counter += 1 self.list_model.append((str(self.counter), "hello")) def del_item(self): """ The handler for the delete button. """ sel = self.list_view.selection() if not sel: return sel_index ...
eJRF/ejrf
questionnaire/features/pages/sections.py
Python
bsd-3-clause
958
0.004175
from questionnaire.features.pages.base import PageObject class CreateSectionPage(PageObject): def __init__(self, browser, questionnaire): super(CreateSectionPage, self).__init__(browser) self.url = '/questionnaire/entry/%s/section/new/' % questionnaire.id def verify_current_position_of_sectio...
sition): if self.browser.driver.name == 'internet explorer': self.assert_page_html_contains( "<option selected=\"selected\" value=\"%s\">%s</option>" % (position, position)) else: self.assert_page_html_contains( "<option value=\"%s\" selected=\"sel...
uestionnaire, section): super(CreateSubSectionPage, self).__init__(browser) self.url = '/questionnaire/entry/%s/section/%s/subsection/new/' % (questionnaire.id, section.id)
repotvsupertuga/tvsupertuga.repository
plugin.video.youtube/resources/lib/youtube_plugin/kodion/items/audio_item.py
Python
gpl-2.0
1,840
0
__author__ = 'bromix' from .base_item import BaseItem class AudioItem(BaseItem): def __init__(self, name, uri, image=u'', fanart=u''): BaseItem.__init__(self, name, uri, image, fanart) self._duration = None self._track_number = None self._year = None self._genre = None ...
elf): return self._album def set_genre(self, genre): self._genre = unicode(genre) def get_genre(self): return self._genre def set_year(self, year): self._year = int(year) def set_year_from_datetime(self, date_time): self.set_year(date_time.year)
def get_year(self): return self._year def set_track_number(self, track_number): self._track_number = int(track_number) def get_track_number(self): return self._track_number def set_duration_from_milli_seconds(self, milli_seconds): self.set_duration_from_seconds(int(mill...
mari-linhares/tensorflow-workshop
code_samples/MNIST_Estimators/keras/using_input_fn/pros_experiment.py
Python
apache-2.0
4,311
0.010206
# coding: utf-8 # A Custom Estimator for MNIST using Keras and an input function. # # See also: # * https://www.tensorflow.org/extend/estimators # * https://www.tensorflow.org/get_started/mnist/beginners # In[ ]: from __future__ import absolute_import from __future__ import division from __future__ import print_fun...
5), activation='relu')(pool1) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) flat = Flatten()(pool2) dense = Dense(1024, activation='relu')(flat) logits = Dense(10, activation='softmax')(de
nse) loss = tf.losses.softmax_cross_entropy( onehot_labels=targets, logits=logits) train_op = tf.contrib.layers.optimize_loss( loss=loss, global_step=tf.contrib.framework.get_global_step(), learning_rate=params["learning_rate"], optimizer="SGD") ...
iulian787/spack
var/spack/repos/builtin/packages/py-qtawesome/package.py
Python
lgpl-2.1
801
0.002497
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyQtawesome(PythonPackage): """FontAwesome icons in PyQt and PySide applications""" h...
4cfd') version('0.3.3', sha256='c3c
98ee4df0133ae42d202fea20253f8746266b4541c5df4269ca4131792ce0f') depends_on('py-setuptools', type='build') depends_on('py-qtpy', type=('build', 'run')) depends_on('py-six', type=('build', 'run'))
rabipanda/tensorflow
tensorflow/python/estimator/canned/head_test.py
Python
apache-2.0
151,483
0.00536
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
n_classes=3, loss_reduction='invalid_loss_reduction') with self.assertRaisesRegexp( ValueErr
or, r'Invalid loss_reduction: none'): head_lib._multi_class_head_with_softmax_cross_entropy_loss( n_classes=3, loss_reduction=losses.Reduction.NONE) def test_loss_fn_arg_labels_missing(self): def _loss_fn(logits): del logits # Unused with self.assertRaisesRegexp( ValueError, ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/i/inherit_non_class.py
Python
mit
1,693
0.015357
"""Test that inheriting from something which is not a class emits a warning. """ # pylint: disable=no-init, import-error, invalid-name, using-constant-test, useless-object-inheritance # pylint: disable=missing-docstring, too-few-public-methods, no-absolute-import from missing import Missing if 1: Ambigu...
t inherit from instance. """ class Bad1(lambda abc: 42): # [inherit-non-class] """ Can't inherit from lambda. """ class Bad2(object()): # [inherit-non-class] """ Can't inherit from an instance of object. """ class Bad3(return_class): # [inherit-non-class] """ Can't inherit from function. """ ...
pass class Good1(int): pass class Good2(type): pass class Good3(type(int)): pass class Good4(return_class()): pass class Good5(Good4, int, object): pass class Good6(Ambiguous): """ Inherits from something ambiguous. This could emit a warning when we will have ...
xbmc/atv2
xbmc/lib/libPython/Python/Lib/idlelib/idlever.py
Python
gpl-2.0
23
0
IDL
E_VERSION = "1.1.5"
redbox-mint/redbox
config/src/main/config/portal/default/redbox/scripts/download.py
Python
gpl-2.0
7,869
0.002415
import os from com.googlecode.fascinator.api.indexer import SearchRequest from com.googlecode.fascinator.api.storage import StorageException from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult from org.apache.tapestry5.internal.services import URLEncoderImpl from org.apache.tapestry5.internal import ...
getStorage().getObject(oid) else: # We have a special storage ID from the index
object = self.services.getStorage().getObject(sid) except StorageException, e: #print "Failed to access object: %s" % (str(e)) return None, None # Grab the payload from the rest of the URL pid = uri[slash+1:] if pid == "": # We want the s...
jakevdp/bokeh
bokeh/transforms/image_downsample.py
Python
bsd-3-clause
2,114
0.010407
import numpy as np from ..objects import ServerDataSource try: import scipy import scipy.misc except ImportError as e: print(e) def source(**kwargs): kwargs['transform'] = {'resample':'heatmap'} kwargs['data'] = {'x': [0], 'y': [0], 'gl...
n / 3.), 1) subset = subset[::x_downsample_factor, ::y_downsample_factor] image = scipy.misc.imresize(subset, (x_resolution, y_resolution), interp='nearest') bounds = image_x_axis[x_bounds[0]:x_bounds[1]] dw = np.max(bounds) - np.min(bounds) bounds = image_y_axis...
set_y': image_y_axis[y_bounds[0]], 'dw': dw, 'dh': dh, }
yudingding6197/fin_script
batchHis.py
Python
gpl-2.0
2,384
0.027265
#!/usr/bin/env python # -*- coding:gbk -*- import sys import re import os import datetime import urllib import urllib2 from openpyxl import Workbook from openpyxl.reader.excel import load_workbook from internal.common import * from internal.ts_common import * #Èç¹ûÐèÒª¼Ç¼µ½csvÎļþÖУ¬ÐÞ¸Äaddcsv=1 addcsv = 0 prepath =...
rvice/view/vMS_tradedetail.php" xmlfile = "internal/array.xml" pindex = len(sys.argv) if pindex<4: sys.stderr.write("Usage: " +os.path.basename(sys.argv[0])+ " ´úÂë ¿ªÊ¼Ê±¼ä<YYYYMMDD or MMDD>
½áÊøÊ±¼ä<YYYYMMDD or MMDD> Ç¿ÖÆÌæ»»<0 or 1> [arr=[number, number...]]\n") exit(1); code = sys.argv[1] if (len(code) != 6): sys.stderr.write("Len should be 6\n") exit(1); ret, code = parseCode(code) if ret!=0: exit(1); #print code delta1=datetime.timedelta(days=1) today = datetime.date.today() ret,stdate = parseD...
safwanrahman/kitsune
kitsune/users/views.py
Python
bsd-3-clause
28,388
0
import os from ast import literal_eval from datetime import datetime from django.conf import settings from django.contrib import auth, messages from django.c
ontrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.http import (HttpResponsePermanentRe
direct, HttpResponseRedirect, Http404, HttpResponseForbidden) from django.views.decorators.cache import never_cache from django.views.decorators.http import (require_http_methods, require_GET, require_POST) from django.shortcuts import get_object_or_404...
jmcanterafonseca/fiware-cygnus
test/acceptance/tools/cygnus.py
Python
agpl-3.0
54,276
0.009526
# -*- coding: utf-8 -*- # # Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U # # This file is part of fiware-cygnus (FI-WARE project). # # fiware-cygnus is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Foun...
without_table' DATABASE_MISSING = u'database_missing' MAX_TABLE_LENGTH = 64 # mongo/sth STH_DATABASE_PREFIX = u'sth' STH_COLLECTION_PREFIX = u'sth' AGGR = u'aggr' class Cygnus: """ cygnus class with generals features """ # -------------------------------...
""" constructor :param protocol: protocol used in cygnus requests :param host: host used in cygnus, in multi-instances, will be incremental :param host: port used in cygnus :param management_port : management port to know the version :param version : cygnus version ...
npadgen/read-a-script
read-a-script.py
Python
bsd-3-clause
13,084
0.001146
#!/usr/bin/env python3 # # $Id$ import os import re import sys import subprocess import argparse import readchar import textwrap import json import logging from utils import mixrange LOGGER = logging.getLogger("read-a-script") LOGGER.addHandler(logging.StreamHandler()) VOICES = { # Spring and Port Wine "raf...
e = self._voices[role_to_speak] else: voice = self._voices[None]
line = "{} says: {}".format(role, line) sys.stdout.write("\n{}\n".format(role.upper())) if role == self.role and not self.mute: if self.display_role: sys.stdout.write("{}\n".format(textwrap.fill(line, self._columns))) while True: sys.stdou...
kcsry/django-tinymce
tests/test_url.py
Python
mit
1,553
0.005151
import pytest from pytest import raises from tinymce.utils import parse_profile, ConfigurationError def test_convert_urls(): profile = {} P = parse_profile(profile) assert 'convert_urls' not in P profile = {'convert_urls': False} P = parse_profile(profile) assert P['convert_urls'] == False ...
h raises(ConfigurationError): P = parse_profile(profile) def test_document_base_url(): profile = {} P = parse_profile(profile) assert 'document_base_url' not in P profile = {'document_base_url': '/path/'} P = parse_profile(profile) assert P['document_base_url'] == '/path/' profile...
= {'document_base_url': 'lol'} with raises(ConfigurationError): P = parse_profile(profile) def test_allow_script_urls(): # FIXME: access denied in docs pass
LeMaker/LNdigitalIO
examples/blink.py
Python
gpl-3.0
209
0
from time import sleep import
LNdigitalIO DELAY = 1.0 # seconds if __name__ == "__main__": LNdigital = LNdigitalIO.LNdigitals()
while True: LNdigital.leds[7].toggle() sleep(DELAY)
bop/bauhaus
lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py
Python
mit
37,549
0.003915
""" sqldiff.py - Prints the (approximated) difference between models and database TODO: - better support for relations - better support for constraints (mainly postgresql?) - support for table spaces with postgresql - when a table is not managed (meta.managed==False) then only do a one-way sqldiff ? show differ...
trospection_module() self.cursor = connection.cursor() self.django_tables = self.get_django_tables(options.get('only_existing', True)) self.db_tables = self.introspection.get_table_list(self.cursor) self.differences = [] self.unknown_db_fields = {} self.new_db_fields = s...
self.null = {} self.DIFF_SQL = { 'error': self.SQL_ERROR, 'comment': self.SQL_COMMENT, 'table-missing-in-db': self.SQL_TABLE_MISSING_IN_DB, 'field-missing-in-db': self.SQL_FIELD_MISSING_IN_DB, 'field-missing-in-model': self.SQL_FIELD_MISSING_IN_MODEL...
Guymer/PyGuymer
MPLS/load_PlayListMark.py
Python
apache-2.0
2,438
0.010254
# -*- coding: utf-8 -*- ############################################################################################## # This file is deprecated because Python 2.x is deprecated # # A Python 3.x version of this file can be found at:
# # # # https://github.com/Guymer/PyGuymer3/blob/master/MPLS/load_PlayListMark.py # ############################################################################################## def load_PlayListMark(fobj): ...
bles ... ans = {} length3 = 0 # [B] # Read the binary data ... ans[u"Length"], = struct.unpack(u">I", fobj.read(4)) ans[u"NumberOfPlayListMarks"], = struct.unpack(u">H", fobj.read(2)); ...
ivmech/iviny-scope
lib/xlsxwriter/test/comparison/test_chart_bar20.py
Python
gpl-3.0
2,215
0.000451
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013, John McNamara, jmcnamara@cpan.org # import unittest import os from ...workbook import Workbook from ..helperfunctions import _compare_xlsx_files class TestCompareXLSXFiles(unittest.TestC...
f os.path.exists(self.got_filename): os.remove(self.got_filename) if __name__
== '__main__': unittest.main()
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/bipartite/tests/test_matrix.py
Python
gpl-3.0
2,915
0.001715
import pytest np = pytest.importorskip("numpy") sp = pytest.importorskip("scipy") sparse = pytest.importorskip("scipy.sparse") import networkx as nx from networkx.algorithms import bipartite from networkx.testing.utils import assert_edges_equal class TestBiadjacencyMatrix: def test_biadjacency_matrix_weight(se...
te.biadjacency_matrix(nx.Graph(), []) def test_empty_graph(self): with pytest.raises(nx.NetworkXError): bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), []) def test_duplicate_row(self): with pytest.raises(nx.NetworkXError): bipartite.biadjacency_matrix(nx.Graph([(1, 0)...
uplicate_col(self): with pytest.raises(nx.NetworkXError): bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [0], [1, 1]) def test_format_keyword(self): with pytest.raises(nx.NetworkXError): bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [0], format="foo") def test_from...
matrix-org/synapse
synapse/handlers/federation_event.py
Python
apache-2.0
78,447
0.002307
# Copyright 2021 The Matrix.org Foundation C.I.C. # # 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...
ge.state self._state_handler = hs.get_state_handler() self._event_creation_handler = hs.get_event_creation_handler() self._event_auth_handler = hs.get_event_auth_handler() self._message_handler = hs.get_message_handler() self._action_generator = hs.get_action_generator() ...
void a circular dependency by deferring execution here self._get_room_member_handler = hs.get_room_member_handler self._federation_client = hs.get_federation_client() self._third_party_event_rules = hs.get_third_party_event_rules() self._notifier = hs.get_notifier() self._is_mi...
DistrictDataLabs/yellowbrick
docs/api/text/umap_vis.py
Python
apache-2.0
1,667
0.0018
#!/usr/bin/env python3 # ID: umap_vis.py [73a44e5] jchealy@gmail.com $ """ Manually generate figures for the UMAP documentation. """ ########################################################################## ## Imports ########################################################################## import matplotlib.pyplot...
outpath=outpath) if __name__ == "__main__": # Load and vectorize the corpus corpus = load_hobbies() tfidf = TfidfVectorizer() docs = tfidf.fit_transform(corpus.data) labels = corpus.target # Whole corpus visualization umap(docs, labels, "images/umap.png") # Whole corpus visuali
zation umap(docs, labels, "images/umap_cosine.png", metric="cosine") # No labels umap(docs, None, "images/umap_no_labels.png", labels=["documents"], metric="cosine") # Apply clustering instead of class names clusters = KMeans(n_clusters=5) clusters.fit(docs) centers = ["c{}".format(c) for...
rado0x54/project-euler
python/problem0011.py
Python
mit
2,145
0.197669
#!/usr/bin/env python3 """Project Euler - Problem 11 Module""" from numpy import * def problem11(grid, nr_adjacent): """Problem 11 - Largest product in a grid""" re
sult = 0 GRID_SHAPE = grid.shape for row in range(0, GRID_SHAPE[0] - (nr_adjacent-1)): for col in range(0, GRID_SHAPE[1] - (nr_adjacent-1)): subgrid = GRID[row:row+nr_adjacent, col:col+nr_adjacent] # Check n rows and columns m
axval = 0 for i in range(0, nr_adjacent): maxval = max(maxval, prod(subgrid[i, :]), prod(subgrid[:, i])) # Check diagonals maxval = max(maxval, prod(diag(subgrid)), prod(diag(fliplr(subgrid)))) result = max(result, maxval) return result GRID = array(...
balageorgetown/georgetown-calendar
test/__init__.py
Python
mit
530
0.007547
__author__ = 'bvenkatesan' import unittest class InitializationTes
ts(unittest.TestCase): def setUp(self): print Exception (
"setting up") def tearDown(self): print("teardown") def test_sanity(self): """ check world is sane.. 2 + 2 = 4 """ self.assertEquals(2+2,4) def test_import(self): """ We are able to import gtcal """ try: import gtcal ...
Alignak-monitoring-contrib/alignak-app
test/test_system.py
Python
agpl-3.0
3,803
0.000263
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015-2018: # Matthieu Estrada, ttamalfor@gmail.com # # This file is part of (AlignakApp). # # (AlignakApp) is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Sof...
r('/tmp/test-app') # Create folder with no permisson return False under_test = mkdir('/usr/local/test-app') self.assertFalse(under_test) def test_install_file(self): """Install (Copy) Origi
n and Sample Files""" # Assert files are no present self.assertFalse(os.path.isfile('/tmp/images.ini')) self.assertFalse(os.path.isfile('/tmp/images.ini.sample')) install_file('etc', '/tmp', 'images.ini') # Assert files are installed self.assertTrue(os.path.isfile('/tm...
atomic-labs/zulip
zerver/worker/queue_processors.py
Python
apache-2.0
13,796
0.003407
from __future__ import absolute_import from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from django.core.handlers.base import BaseHandler from zerver.models import get_user_profile_by_email, \ get_user_profile_by_id, get_prereg_user_by_email, get_client from zerver.lib.context_man...
invitee = get_prereg_user_by_email(data["email"]) referrer = get_user_profile_by_email(data["referrer_email"]) do_send_confirmation_email(invitee, referrer) # queue invitation reminder for two days from now. link = Confirmation.objects.get_link_for_object(invitee) send_local_em...
il", {'activate_url': link, 'referrer': referrer, 'voyager': settings.VOYAGER, 'external_host': settings.EXTERNAL_HOST, ...
coffeestats/coffeestats-django
coffeestats/caffeine_oauth2/views.py
Python
mit
6,196
0
from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail from django.shortcuts import redirect from django.template.loader import render_to_string from django.urls import reverse_laz...
m
ail_body_text_template = 'caffeine_oauth2/mail_registered_body.txt' def get_form_class(self): """ Returns a customized form class for the coffeestats application model. """ return CoffeestatsApplicationForm def form_valid(self, form): application = form.save(commit=Fal...
ktdreyer/teuthology
teuthology/orchestra/opsys.py
Python
mit
4,270
0
import ast import re class OS(object): """ Class that parses either /etc/os-release or the output of 'lsb_release -a' and provides OS name and version information. Must be initialized with OS.from_lsb_release or OS.from_os_release """ __slots__ = ['name', 'version', 'codename', 'package_type...
.literal_eval(python_val) (name, version, codename) = python_val name = name.lower().replace(' ', '') if name.startswith('redhat'): name = 'rhel' elif name.startswith('centos'): name = 'centos' elif name.startswith('fedora'): name = 'fedora' ...
ion obj.codename = codename.lower() obj._set_package_type() return obj @classmethod def from_lsb_release(cls, lsb_release_str): """ Parse output from lsb_release -a and populate attributes Given output like: Distributor ID: Ubuntu Descrip...
jmahmood/pytbar
pytbar/__init__.py
Python
mit
83
0.012048
__au
thor__ = 'jawaad' from tbar import * from redis import * from tornado imp
ort *
Meriipu/quodlibet
quodlibet/ext/editing/iconv.py
Python
gpl-2.0
2,311
0.000433
# Copyright 2006 Joe Wreschnig # # 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. # Encoding magic. Show off the submenu...
Gtk.Label(label=i) item_label.set_alignment(0.0, 0.5) item.add(item_label) item.connect('activate', self.__convert) submenu.append(item) s
elf.set_submenu(submenu) def __convert(self, item): self.__value = item.value self.activate() def activated(self, tag, value): try: return [(tag, self.__value)] except AttributeError: return [(tag, value)]
Duke-Medical-Instrumentation/Respi-Rite
Software/FinalCode/debugFiles/debugAlgorithm.py
Python
apache-2.0
2,033
0.006886
#!/usr/bin/python import Adafruit_BBIO.ADC as ADC import time import os ADC.setup() n = 100 count = 0 start = [1]*n print('Calibrating...') # Create first list of n voltage readings while True: voltage = ADC.read("P9_39") voltage = 2*1.8*voltage start.pop(0) start.append(voltage) count = count...
*new_thresh fine_thresh = 0.2*new_thresh #print mean_vol # print accessed_out, max_vol, new_thresh, init_thresh, fine_thresh # print breathleft, success, unsuccess if breathleft == 0: print '\nFINISHED!' break i
f breathinit == 0: if accessed_out > init_thresh: breathinit = 1 print('Breath is initialized') elif breathinit == 1: if accessed_out > max_vol: max_vol = accessed_out elif accessed_out < fine_thresh: breathinit = 0 if max_vol > new...
isidroamv/netmiko
netmiko/huawei/huawei_ssh.py
Python
mit
2,964
0.00135
from __future__ import print_function from __future__ import unicode_literals import time import re from netmiko.cisco_base_connection import CiscoSSHConnection from netmiko import log class HuaweiSSH(CiscoSSHConnection): def session_preparation(self): """Prepare the session after the connection has been...
f, config_command='system-view'): """Enter configuration mode.""" return super(HuaweiSSH, self).config_mode(config_command=config_command) def exit_config_mode(self, exit_config='return'): """Exit configuration mode.""" return super(HuaweiSSH, self).exit_config_mode(exit_config=exit...
"""Checks whether in configuration mode. Returns a boolean.""" return super(HuaweiSSH, self).check_config_mode(check_string=check_string) def check_enable_mode(self, *args, **kwargs): """Huawei has no enable mode.""" pass def enable(self, *args, **kwargs): """Huawei has ...
myfavouritekk/TPN
tools/propagate/sequence_roi_gt_propagation.py
Python
mit
3,197
0.003128
#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG (myfavouritekk@gmail.com) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import...
ument('annot_file', default=None,
help='Ground truth annotation file. [None]') parser.add_argument('save_file', help='Save zip file') parser.add_argument('--job', dest='job_id', help='Job slot, GPU ID + 1. [1]', default=1, type=int) parser.add_argument('--length', type=int, default=20, hel...
CINPLA/expipe-dev
python-neo/neo/test/iotest/test_nestio.py
Python
gpl-3.0
34,432
0.000261
# -*- coding: utf-8 -*- """ Tests of neo.io.exampleio """ # needed for python 3 compatibility from __future__ import absolute_import, division import warnings try: import unittest2 as unittest except ImportError: import unittest import quantities as pq import numpy as np from neo.io.nestio import ColumnIO f...
sampling_period=pq.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') def test_id_column_none_multiple_neurons(self): """ Tests if function correctly raises an error if the user tries to read from a file...
tain unit IDs, but data for multiple units. """ filename = get_test_file_full_path( ioclass=NestIO, filename='0time-1255-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(Valu...
brandsoulmates/incubator-airflow
airflow/operators/s3_to_redshift_operator.py
Python
apache-2.0
5,544
0.008838
# -*- coding: utf-8 -*- # # 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 ...
ame = s3_parts[0] prefix = s3_parts[1] if self.s3.check_for_prefix(bucket_name, prefix, "/"): # Build the query unload_query = self._build_query(a_key, s_key, s3_path, load_options) # Add to a WLM qu
eue, if desired if self.wlm_queue: self._assign_to_query_group(unload_query) logging.info('Executing COPY command...') self.hook.run(unload_query, self.autocommit) logging.info("COPY command complete...") else: logging....
ghorn/rawesome
rawe/newton/nmhe.py
Python
lgpl-3.0
10,700
0.012243
# Copyright 2012-2013 Greg Horn # # This file is part of rawesome. # # rawesome is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ...
) for j
in range(1,traj.dvMap._deg+1)] \ for name in traj.dvMap._xNames]) Z = C.DMatrix([[traj.lookup(name,timestep=k,degIdx=j) for j in range(1,traj.dvMap._deg+1)] \ for name in traj.dvMap._zNames]) newton.isolver.setOutput(C.veccat...
thomasorb/orb
orb/utils/fft.py
Python
gpl-3.0
13,896
0.005181
#!/usr/bin/python # *-* coding: utf-8 *-* # Author: Thomas Martin <thomas.martin.1@ulaval.ca> # File: fft.py ## Copyright (c) 2010-2020 Thomas Martin <thomas.martin.1@ulaval.ca> ## ## This file is part of ORB ## ## ORB is free software: you can redistribute it and/or modify it ## under the terms of the GNU General Pu...
b.constants def mod2pi(a): """Return the smallest signed modulo 2 pi of any angle in radians """ return
np.arctan2(np.sin(a), np.cos(a)) def clean_phase(ph): """Return a cleaned phase vector (which does not depend on an arbitrary modulo pi) """ ph = orb.utils.vector.robust_unwrap(np.copy(ph), 2*np.pi) if np.any(np.isnan(ph)): ph.fill(np.nan) else: # set the first sample at the smalle...
twitter/pants
src/python/pants/backend/python/tasks/python_bundle.py
Python
apache-2.0
3,763
0.009035
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from pants.backend.python.targets.python_app import PythonApp from pants.base....
check.all_vts: bundle_dir = self.get_bundle_dir(vt.target.id, vt.results_dir) archive_format = self.resolved_option(self.get_options(), vt.target, 'archive') archiver = archive.create_archiver(archive_format) if archive_format else None
archive_path = self._get_archive_path(vt, archive_format) if not vt.valid: # Only recreate the bundle/archive if it's changed self._bundle(vt.target, bundle_dir) if archiver: archiver.create(bundle_dir, vt.results_dir, vt.target.id) self.context.log.info( ...
BorgERP/borg-erp-6of3
l10n_hr/account_tax_payment/__openerp__.py
Python
agpl-3.0
2,207
0.007703
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Module: account_tax_payment # Author: Goran Kliska # mail: gkliskaATgmail.com # Copyright (C) 2011- Slobodni programi d.o.o., Zagreb # htt...
"description" : """ Author: Goran Kliska @ Slobodni programi d.o.o. http://www.slobodni-programi.hr Contributions: Description: Manages taxes that are deductible only when payed & reconciled. Adds new field "Tax payment journal" for journal, and two new fields in Tax Code For Storno/Contra Tax Code us...
on" : "0.1", "author" : "Slobodni programi d.o.o.", "category" : "Localisation/Croatia", "website": "http://www.slobodni-programi.hr", 'depends': [ 'account', 'account_storno', ], 'init_xml': [], 'update_xml': [ 'security/ir.mo...
data-exp-lab/girder
plugins/item_tasks/server/json_tasks.py
Python
apache-2.0
9,715
0.002265
from girder.api import access from girder.api.describe import autoDescribeRoute, Description from girder.api.rest import boundHandler, filtermodel from girde
r.constants import AccessType from girder.exceptions import RestException from girder.models.folder import Folder from girder.models.item import Item from girder.models.token import Token from girder.models.user import User from girder.plugins.jobs.models.job import Job from girder.plugins.worker import utils from . im...
ption('Create item task spec based on a task in a docker image.') .notes('This operates on an existing item, turning it into an item task ' 'using introspection of a docker image.') .modelParam('id', 'The ID of the item that the task spec will be bound to.', model=Item, level=AccessTy...
mmasaki/trove
trove/common/strategies/storage/base.py
Python
apache-2.0
1,530
0
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
None): """Persist information from the stream.""" @abc.abstractmethod def load(self, location, backup_checksum): """Load a stream from a persisted storage locatio
n.""" @abc.abstractmethod def load_metadata(self, location, backup_checksum): """Load metadata for a persisted object.""" @abc.abstractmethod def save_metadata(self, location, metadata={}): """Save metadata for a persisted object."""
evangelistalab/forte
tests/pytest/hf/test_df_hf.py
Python
lgpl-3.0
1,224
0.000817
import pytest from forte.solvers import solver_factory, HF def test_df_rhf(): """Test DF-RHF on HF.""" ref_energy = -100.04775218911111 # define a molecule xyz = """ H 0.0 0.0 0.0 F 0.0 0.0 1.0 """ # create a molecular model input = solver_factory(molecule=xyz, basis='cc-pVTZ',...
FIT') # specify the electronic state state = input.state(charge=
0, multiplicity=1, sym='a1') # create a HF object and run hf = HF(input, state=state) hf.run() assert hf.value('hf energy') == pytest.approx(ref_energy, 1.0e-10) if __name__ == "__main__": test_df_rhf() test_df_rhf_select_aux()
ricardog/raster-project
projections/diropt.py
Python
apache-2.0
504
0.015873
import argparse import os class FullPaths(argparse.Action):
"""Expand user- and relative-paths""" def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values))) @classmethod def is_dir(x, dirname): """Checks if a path is an actual directory""" if not os.path.isdir(dirname): m...
entTypeError(msg) else: return dirname
jwang-net/sector-scraper
sectorscraper/linkstocsv_nyse.py
Python
bsd-3-clause
1,727
0.005211
# coding=utf-8 import os import csv import datetime import re home = os.path.expanduser('~') mainfolder = home + '/scrapecollect/' nysefile = mainfolder + 'healthcare-NYSE_filings_sorted_final.csv' nyselinks = mainfolder + 'healthcare-NYSE_links.csv' nyseview = mainfolder + 'healthcare-NYSE-view.csv' nysefinal = main...
i[3] = 'Documents' for a in testlist: tick = str(a[1]).strip() print(tick) for row in testlist2: tick1 = row[0] print(tick1) link = row[1] a[3] = '<a href=\"' + link + '\">' + 'Documents' + '</a>' if tick1 == tick: ...
estfile2.close() with open(nyseview) as testfile3, open(nysefinal, 'wt') as testfile4: reader = csv.reader(testfile3) writer = csv.writer(testfile4) finalrows = [] for x in testfile3: nospaces = re.sub('\s\s+', ' ', x) finalrows.append(str(nospaces)) writer.writerow(finalrows) ...
ferdinandvwyk/gs2_analysis
run.py
Python
gpl-2.0
13,244
0.006418
# Standard import os import sys # Third Party import numpy as np from netCDF4 import Dataset import f90nml as nml #local import field_helper as field class Run(object): """ Run object which stores basic simulation information. """ def __init__(self, cdf_file): """ Initialize with Net...
* \ self.omega * self.t) self.upar_i = field.field_to_real_space(self.upar_i)*self.rho_star self.upar_e = field.field_to_real_space(self.upar_e)*self.rho_star def read_t
par(self, lab_frame=False): """ Read the parallel temperature. """ self.tpar_i = field.get_field(self.cdf_file, 'tpar_igomega_by_mode', 0) self.tpar_e = field.get_field(self.cdf_file, 'tpar_igomega_by_mode', 1) if lab_frame: for ix in range(self.nkx): ...
yangxianbo/jym
account/migrations/0002_mail_server.py
Python
gpl-3.0
834
0.004796
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.CreateModel( name='mail_server', fields=[ ...
('mailuser', models.CharField(max_length=255, verb
ose_name=b'\xe7\x94\xa8\xe6\x88\xb7\xe5\x90\x8d')), ('mailpasswd', models.CharField(max_length=255, verbose_name=b'\xe5\xaf\x86\xe7\xa0\x81')), ], ), ]
ThiefMaster/indico-plugins
livesync/tests/simplify_test.py
Python
mit
3,890
0.002314
# This file is part of the Indico plugins. # Copyright (C) 2002 - 2021 CERN # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. import pytest from indico.testing.util import bool_matrix from indico_lives...
ico_livesync.simplify import SimpleChange, process_records class Dummy: pass @pytest.fixture def queue_entry_dummy_object(monkeypatch): monkeypatch.setattr(LiveSyncQueueEntry, 'object', object) @pytest.mark.parametrize(('ch
ange', 'invalid'), ( (ChangeType.created, True), (ChangeType.deleted, True), (ChangeType.data_changed, True), (ChangeType.protection_changed, False), (ChangeType.moved, False), )) @pytest.mark.usefixtures('queue_entry_dummy_object') def test_process_records_c...
bdutro/mopidy-raspiradio
mopidy_raspiradio/gui.py
Python
apache-2.0
6,429
0.004355
import time from luma.core import cmdline, error from luma.core.interface.serial import i2c, spi from luma.core.render import canvas from luma.oled.device import ssd1306, ssd1322, ssd1325, ssd1331, sh1106 from PIL import ImageFont import timers class ProgressBar(object): __progress_padding = 2 __progress_heigh...
onfig['clock_font_size']) self.update_thread = timers.UpdateInterval(1.0/config['refresh_rate'], self.tick) self.cur_time = time.time() _, height = self.font.getsize(self.format_time()) self.y_pos = fi
nd_center(device_args.height, height) self.lcd_width = device_args.width def format_time(self): return time.strftime(self.__clock_str, time.localtime(self.cur_time)) def tick(self, force_redraw=False): new_time = time.time() if new_time != self.cur_time: self.cur_ti...
iw3hxn/server
openerp/modules/loading.py
Python
agpl-3.0
19,023
0.00389
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you ca...
k, v in list(sys.modules.items()): if k.startswith('openerp.') and sys.modules.get(k[8:]) is None: sys.modules[k[8:]] = v def load_module_graph(cr, graph, status=None, perform_checks=True, skip_mo
dules=None, report=None): """Migrates+Updates or Installs all module nodes from ``graph`` :param graph: graph of module nodes to load :param status: status dictionary for keeping track of progress :param perform_checks: whether module descriptors should be checked for validity (prints warnings ...
analytics-pros/mozilla-bedrock
tests/functional/firefox/desktop/test_desktop.py
Python
mpl-2.0
633
0.00158
# 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/. import pytest from pages.firefox.desktop.desktop import DesktopPage @pytest.mark.skip_if_firefox(reason='Download but...
lay() assert page.primary_download_button.
is_displayed
JohnDoee/thomas
thomas/streamers/direct.py
Python
mit
1,265
0.000791
from ..plugin import StreamerBase class DirectStreamer(StreamerBase): plugin_name = 'direct' def __init__(self, item, allowed_extensions=None): self.item = item self.allowed_extensions = [x.lower() for x in allowed_extensions or []] def _find_best_item(self, item): best_size, bes...
found_size > best_size: best_size = found_size best_item = found_item if item.is_readable: if item['size'] > best_size and (not self.allowed_extensions o
r item.id.split('.')[-1].lower() in self.allowed_extensions): best_size = item['size'] best_item = item return best_size, best_item def evaluate(self, include_fileset=False): best_size, best_item = self._find_best_item(self.item) if inclu...
cvium/Flexget
flexget/plugins/filter/seen.py
Python
mit
11,590
0.002934
""" Listens events: forget (string) Given string can be task name, remembered field (url, imdb_url) or a title. If given value is a task name then everything in that task will be forgotten. With title all learned fields from it and the title will be forgotten. With field value only that particular field i...
for row in session.execute(select([field_table.c.id, field_table.c.value], field_table.c.field == 'imdb_url')): new_values = {'field': 'imdb_id', 'value': extract_id(row['value'])} session.exe
cute(update(field_table, field_table.c.id == row['id'], new_values)) ver = 1 if ver == 1: field_table = table_schema('seen_field', session) log.info('Adding index to seen_field table.') Index('ix_seen_field_seen_entry_id', field_table.c.seen_entry_id).create(bind=session.bind) ...
Praxyk/Praxyk-DevOps
server/unittest/server_unit_tests.py
Python
gpl-2.0
310
0.019355
#!/bin/env python # @info -
Unit testing suite for the main server program. We will spin it up on localhost # and send test API requests to it, making sure the correct responses are received. from unit_test import * class serverUnitTest(UnitTest) : def __init__(self, testargs) :
pass
swcurran/tfrs
backend/api/migrations/0012_auto_20170928_1737.py
Python
apache-2.0
4,787
0.001462
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0011_merge'), ] operations = [ migrations.CreateModel( name='CreditTradeZeroReason', fields=[...
), migrations.RemoveField( model_name='opportunityhistory', name='opportunityFK', ), migrations.RemoveField( model_name='opportunityhistory', name='userFK', ), migrations.RemoveField( model_name='opportunitystatu...
migrations.RemoveField( model_name='credittrade', name='historySet', ), migrations.RemoveField( model_name='credittrade', name='plainEnglishPhrase', ), migrations.RemoveField( model_name='fuelsupplier', name='fue...
chernals/georges
georges/manzoni/maps/madx_combined_dipole.py
Python
gpl-3.0
11,408
0.002104
""" This code is from MAD-X twiss.f90. It is used to allow comparisons between the MAD-X tensor and the generated code for MAD8 or Transport style tensor computation. """ import numpy as np from numpy import sqrt, cos, sin, cosh, sinh zero = 0 one = 1 two = 2 three = 3 four = 4 six = 6 nine = 9 twelve = 12 fifteen = 1...
* # ! c (double) cosine-like function. c(k,l) * # ! s (double) sine-like function. s(k,l) * # ! d
(double) dispersion function. d(k,l) * # ! f (double) integral of dispersion function. f(k,l) * # !----------------------------------------------------------------------* # double precision, intent(IN) :: el, sk1 # double precision, intent(OUT) :: c, s...
diplomacy/research
diplomacy_research/models/datasets/feedable_dataset.py
Python
mit
5,758
0.003473
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 rest...
operty def is_started(self): """ Determin
es if the dataset has been started """ return self._is_started @property def is_initialized(self): """ Determines if the iterator is initialized """ return self._is_initialized @property def is_closing(self): """ Determines if the dataset is closing """ return s...
tigeorgia/fixmystreet
apps/mainapp/views/reports/subscribers.py
Python
gpl-2.0
2,154
0.025534
from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext as _ from apps.mainapp.models import Report, ReportSubscriber from apps.mainapp.forms import ReportSubscriberForm de...
eports/subscribers/confirm.html", { "subscriber": subscriber, }, context_instance=RequestContext(request)) def unsubscribe(request, confirm_token ): subscriber = ge
t_object_or_404(ReportSubscriber, confirm_token = confirm_token ) report = subscriber.report subscriber.delete() return render_to_response("reports/subscribers/message.html", { "message": _("You have unsubscribed from updates to:") + report.title, }, context_instance=Reque...
Rygelouv/Images-bookmark-python-
account/views.py
Python
gpl-3.0
4,942
0.000607
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.con
trib.auth import authenticate, login from django.http import JsonResponse from django.views.decorators.http import re
quire_POST from account.models import Profile, Contact from actions.models import Action from common.decorators import ajax_required from .forms import LoginForm, UserRegistrationForm, UserEditForm, ProfileEditForm from actions.utils import create_action def user_login(request): if request.method == 'POST': ...
antoinecarme/pyaf
tests/artificial/transf_Integration/trend_PolyTrend/cycle_0/ar_/test_artificial_128_Integration_PolyTrend_0__100.py
Python
bsd-3-clause
267
0.086142
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 0, transfor
m = "Integratio
n", sigma = 0.0, exog_count = 100, ar_order = 0);
davidwhogg/LensTractor
lenstractor/dm.py
Python
gpl-2.0
12,090
0.033912
# ============================================================================ ''' This file is part of the lenstractor project. Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford). Description ----------- General-purpose data management classes and functions: * Order a pile of FITS files into scifiles and...
def Read_in_data(scifile,varfile,SURVEY='PS1',vb=False): hdulist = pyfits.open(scifile) sci = hdulist[0].data hdr = hdulist[0].header hdulist.close() NX,NY = sci.shape
if (varfile is not None): hdulist = pyfits.open(varfile) var = hdulist[0].data hdulist.close() else: # Make a var image from the sci image... background = np.median(sci) diffimage = sci - background # Get the flux-to-count conversion factor from header, at least in SDSS: ...
Stark-Mountain/meetup-facebook-bot
meetup_facebook_bot/server.py
Python
mit
4,314
0.000927
import random import time from flask import (Flask, flash, redirect, render_template, request, session, url_for) from flask_admin import Admin from flask_babelex import Babel from flask_wtf import Form from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from wtforms import v...
ta != admin_login or self.passkey.data != admin_password:
time.sleep(random.uniform(1, 2.2)) return False return True @babel.localeselector def get_locale(): if request.args.get('lang'): session['lang'] = request.args.get('lang') return session.get('lang', 'en') def is_facebook_challenge_request(request): if request.args.ge...
ACBL-Bridge/Bridge-Application
Logic/trick_handle.py
Python
mit
8,305
0.00289
from verbose import * from card_value import * import pycurl from io import BytesIO class Trick: def __init__(self, trump, playerlst): # The trick pile self.tpile = [] # 0 = Clubs, 1 = Diamonds, 2 = Hearts, 3 = Spades, 4 = No Trump self.trump = trump self.playerlst = playerl...
buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, 'http://gibrest.bridgebase.com/u_bm/robot.php?&pov=' + pov[cp % 4] + '&h=' + h + '&d=' + d + '&v=' + v + '&n=' + n + '&s=' + s + '&e=' + e + '&w=' + w + '&o=' + o + '&src=' + src)
c.setopt(c.WRITEDATA, buffer) c.perform() output = str(buffer.getvalue()).split() if verbose: print("Cold Output: " + str(output)) # Getting the specific value in the xml document if (len(output) >= 17): ...
ynop/spych
spych/data/features/pipeline/splicing.py
Python
mit
1,313
0.003046
import enum import numpy as np from . import base from spych.utils import array class SpliceStage(base.ProcessingStage): def __init__(self, splice_size=4, splice_step=1): self.splice_size = splice_size self.splice_step = spl
ice_step def process(self, feature_matrix): processed = array.splice_features(feature_matrix, self.splice_size, self.splice_step, repeat_border_frames=True) return processed.copy() class UnspliceMergeType(enum.Enum): COMPUTE_MEAN = 'mean' TAKE_CENTER_FRAME = 'center_frame' class Unspli...
plice_size = splice_size self.splice_step = splice_step self.merge_type = merge_type def process(self, feature_matrix): if self.merge_type == UnspliceMergeType.COMPUTE_MEAN: return array.unsplice_features(feature_matrix, self.splice_size, self.splice_step) elif self.merg...
CARocha/sitioreddes
envivo/migrations/0001_initial.py
Python
mit
1,272
0.007075
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Envi
vo' db.create_table(u'envivo_envivo', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('titulo', self.gf('django.db.models.fiel
ds.CharField')(max_length=200)), ('url', self.gf('django.db.models.fields.TextField')()), ('vivo', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal(u'envivo', ['Envivo']) def backwards(self, orm): # Deleting model 'Envivo' ...
avtomato/HackerRank
Algorithms/_02_Implementation/_29_Find_Digits/solution.py
Python
mit
190
0.005263
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) num = str(n) print(len([i for i in num if int(i) != 0 and n
% int(i) == 0]))
kartoza/geonode
geonode/people/__init__.py
Python
gpl-3.0
1,584
0.001894
# -*- 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 ...
wing you"), _("Another user has started following you"),), ("account_approve", _("User requested access"), _("A new user has requested access to the site"),), ("account_active", _("Account activated"), _("This account is now active an...
lf): super(PeopleAppConfig, self).ready() default_app_config = 'geonode.people.PeopleAppConfig'
Akrog/cinder
cinder/tests/test_fujitsu_compatibility.py
Python
apache-2.0
2,530
0
# Copyright (c) 2015 FUJITSU LIMITED # # 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...
f setUp(self): super(FJDriverCompatibility, self).setUp() self.manager = importutils.import_object(CONF.volume_manager) # Stub definition self.stubs.Set( eternus_dx_common.FJDXCommon, '__init__', self.fake_init) def _load_driver(self, driver): self.manager.__ini...
r_module_name(self): return "%s.%s" % (self.manager.driver.__class__.__module__, self.manager.driver.__class__.__name__) def fake_init(self, prtcl, configuration=None): msg = "selected protocol is %s" % prtcl self.assertTrue((prtcl == 'FC') or (prtcl == 'iSCSI'), m...
DLR-SC/tigl
ci/conda/oce-static/remove-system-libs.py
Python
apache-2.0
1,087
0.00552
#!/usr/bin/env python # @author: Martin Siggel <martin.siggel@dlr.de> # # This script fixes the cmake exports file by # removing explicit linking to system libraries import sys, re def remove_absolute_paths(line): """ Removes libraries from the line that are found under /usr
""" if sys.platform == 'win32': return line elif sys.platform == 'darwin': return re.sub('/Applications/[-_a-zA-Z0-9/.]+.framework[;]?', '', line) else: return re.sub('/usr/[-_a-zA-Z0-9/]+.so[;]?', '', line) def fix_paths(filename): with open(filename) as f: lines =...
BRARIES" in line or "INTERFACE_LINK_LIBRARIES" in line: lines[i] = remove_absolute_paths(line) fout = open(filename,'w') fout.write("".join(lines)) fout.close() if __name__ == "__main__": assert(len(sys.argv) == 2) filename = sys.argv[1] fix_paths(filename)
datapythonista/viri
libviri/viric.py
Python
gpl-3.0
4,141
0.002898
# Copyright 2011, Marc Garcia <garcia.marc@gmail.com> # # This file is part of Viri. # # Viri 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, version 3 of the License. # # Viri is distributed in the hope that ...
ocal' class ViriError(Exception): pass class BaseCommand(object): def add_arguments(self, parser): pas
s def run(self): pass def connect_and_run(self, host, run, hosts, keyfile, certfile, timeout, **args): self.connection = XMLRPCClient( 'https://{0}/'.format( host if ':' in host else ':'.join( [host, str(DEFAULT_PORT)])), ...
nilicule/mopidy-audioaddict
mopidy_audioaddict/__init__.py
Python
mit
1,094
0
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.3.1' class Extension(ext.Extension): dist_name = 'Mopidy-AudioAddict' ext_name = 'audioaddict' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__fi...
ad(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['username'] = config.String(optional=True) schema['password'] = config.Secret(optional=True) schema['quality'] = config.String(optional=True) schema['difm'] = config.Boolean...
o'] = config.Boolean(optional=True) schema['frescaradio'] = config.Boolean(optional=True) return schema def setup(self, registry): from .actor import AudioAddictBackend registry.add('backend', AudioAddictBackend)
nwchandler/ansible
lib/ansible/modules/cloud/cloudstack/cs_instance_nic.py
Python
gpl-3.0
8,254
0.000364
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2017, Marc-Aurèle Brothier @marcaurele # (c) 2017, René Moser <mail@renemoser.net> # # 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 Soft...
Name of instance. required: true aliases: ['name'] network: descrip
tion: - Name of the network. required: true ip_address: description: - IP address to be used for the nic. required: false default: null vpc: description: - Name of the VPC the C(vm) is related to. required: false default: null domain: description: - Domain t...
gaeran/lipan
portscan/portscan/migrations/0001_initial.py
Python
gpl-3.0
617
0.001621
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-26 00:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ScanRe...
, fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.Ch
arField(max_length=20)), ('service', models.CharField(max_length=70)), ], ), ]
kawamon/hue
desktop/core/ext-py/thriftpy2-0.4.12/tests/test_const.py
Python
apache-2.0
975
0
# -*- coding: utf-8 -*- import thriftpy2 thriftpy2.install_import_hook() import const_thrift as const # noqa def test_num_const(): assert -10 == const.NEGATIVE_I16 assert -123.456 == const.NEGATIVE_DOUBLE assert 10 == const.I16_CONST assert 100000 =
= const.I32_CONST assert 123.456 == const.DOUBLE_CONST def test_string_const(): assert "hello" == cons
t.DOUBLE_QUOTED_CONST assert "hello" == const.SINGLE_QUOTED_CONST def test_const_with_sep(): assert "hello" == const.CONST_WITH_SEP1 assert "hello" == const.CONST_WITH_SEP2 def test_list_const(): assert [1, 2, 3] == const.I32_LIST_CONST assert [1.1, 2.2, 3.3] == const.DOUBLE_LIST_CONST asser...
slandis/InkCutter
inkcutter/app/bin/serial/serialutil.py
Python
gpl-3.0
18,576
0.005168
#! python # Python Serial Port Extension
for Win32, Linux, BSD, Jython # see __init__.py # # (C) 2001-2009 Chris Liechti <cliechti@gmx.net> # this is distributed under a free software license, see license.txt # compatibility folder Python < 2.6 try: bytes bytearray except (NameError, AttributeError): # Python older than 2.6 do not have these typ...
str # bytearray is a mutable type that is easily turned into an instance of # bytes class bytearray(list): # for bytes(bytearray()) usage def __str__(self): return ''.join(self) # append automatically converts integers to characters def append(self, item): if isin...
keedio/sahara
sahara/tests/unit/service/validation/test_cluster_scaling_validation.py
Python
apache-2.0
13,492
0
# Copyright (c) 2013 Mirantis 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 writ...
} ] } self._assert_check_scaling( data=data, cluster=cluster, expected_message='Duplicates in node ' 'group names are detected') data = { 'add_node_groups': [ { 'name': 'n...
'node_processes': ['namenode'] }, ] } self._assert_check_scaling( data=data, cluster=cluster, expected_message="Can't add new nodegroup. " "Cluster already has nodegroup " "wit...
TheTimmy/spack
var/spack/repos/builtin/packages/libice/package.py
Python
lgpl-2.1
1,709
0.000585
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laborato
ry. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or mo
dify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 PARTICUL...
LinuxIsCool/unearthed
Unearthed/urls.py
Python
gpl-3.0
1,847
0.003249
"""Unearthed URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
ass = UserSerializer # # # Routers provide an easy way of automatically determining the URL conf. # router = routers.DefaultRouter() # router.register(r'users', UserViewSet) # # # Wire up our API using automatic URL routing. # # Additionally, we include login URLs for the browsable API. # u
rlpatterns = [ # url(r'^', include(router.urls)), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) # ]
emory-libraries/eulcore-history
src/eulcore/django/fedora/views.py
Python
apache-2.0
6,781
0.003392
# file django/fedora/views.py # # Copyright 2010 Emory University General Library # # 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 ...
ders may be included `only` for non-xml and non-RDF datastreams (excluded there since they may be inaccurate depending on the serialization of the content): - Content-MD5: MD5 checksum of the datastream in Fedora, if available - Content-Length: size of the datastream in Fedora If either the datast...
ra), the exception is re-raised and should be handled elsewhere. :param request: HttpRequest :param pid: Fedora object PID :param dsid: datastream ID to be returned :param type: custom object type (should extend :class:`~eulcore.fedora.models.DigitalObject`) (optional) :param repo: :cla...
botswana-harvard/edc-identifier
edc_identifier/tests/test_short_identifier.py
Python
gpl-2.0
5,167
0.000194
from faker import Faker from django.apps import apps as django_apps from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase, tag from ..models import IdentifierModel from ..short_identifier import DuplicateIdentifierError, ShortIdentifierPrefixPatternError from ..short_identifier import...
f): short_identifier = ShortIdentifier( prefix_pattern='^[0-9]{2}$', prefix=22) se
lf.assertEqual(str(short_identifier), short_identifier.identifier) def test_short_identifier_longer_than_default(self): prefix = '222' random_string_length = 7 prefix_pattern = '^[0-9]{3}$' short_identifier = ShortIdentifier( prefix_pattern=prefix_pattern, pr...
fingeronthebutton/RIDE
utest/controller/test_macro_controllers.py
Python
apache-2.0
4,898
0.000408
import unittest from nose.tools import assert_equals, assert_true, assert_false from robotide.robotapi import TestCaseFile from robotide.controller.filecontrollers import TestCaseFileController from robotide.controller.macrocontrollers import ( TestCaseController, UserKeywordController) from robotide.controller.ta...
('Timeout' in labels) def test_creation(self): for st in self.ct
rl.settings: assert_true(st is not None) assert_equals(self.ctrl.steps[0].keyword, 'No Operation') assert_true(self.ctrl.datafile is self.tcf) def test_dirty(self): self.ctrl.mark_dirty() assert_true(self.ctrl.dirty) def test_move_up(self): assert_false(self...
eddiejessup/pizza
scripts/runner.py
Python
gpl-2.0
1,614
0.002478
#!/usr/bin/env python from lammps import lammps import os import argparse parser = argparse.ArgumentParser(description='Run LAMMPS simulation with an input file') parser.add_argument('-i', '--input') parser.add_argument('--resume') parser.add_argument('--resett', default=False, action='store_true') parser.add_argumen...
rgs.out)): copt = raw_input('Dump file exists, (o)verwrite, (a)ppend, (l)eave, (c)ancel?') if copt == 'o': dump_write = True elif copt == 'l': dump_w
rite = False elif copt == 'a': dump_write = True dump_append = True else: raise Exception('Cancelled by user') if dump_write: lmp.file('dump 1 all custom {} {}.dump id type x y z fx fy fz v_f_prop_x v_f_prop_y v_f_prop_z f_f_cons[1] f_f_cons[2] f_f_cons[3] tqx tqy tqz'.format(args.ev...
f03lipe/eMec-db-retriever
src/tablegenerator.py
Python
mit
22,135
0.031887
#!/usr/bin/env python2.7 # -*- coding: UTF-8 -*- """ This module defines the TableGenerator class. Part of the pydbcollector package. by @f03lipe, 2011-2012 """ from queryassembler import QueryAssembler from dataparser import DataParser import sys # year ranges to iterate through ANOS_FHC = range(1995, 2003) ANOS_L...
bler( year=ano, select=['qtde_de_cursos', "org_acad"], where=['tecnológico', 'existia_no_ano', mod_ensino], order_by=["org_acad"], group_by=["org_acad"]).query # mquery2 cria query específica para Universidades Federais (UFs) mquery2 = lambda ano, mod_ensino: QueryAssembler(year=ano, select=['qtde_d...
s mquery3 = lambda ano, mod_ensino: QueryAssembler(year=ano, select=['qtde_de_cursos', "org_acad"], where=['tecnológico', 'existia_no_ano', 'UTF', mod_ensino], group_by=["org_acad"]).query for mod_ensino in MOD_ENSINO: print color("$ ensino: %s" % mod_ensino, 'OKBLUE') for year in ANOS_FHC+ANOS_LUL...
lmoran/SDMXPlugin
__init__.py
Python
apache-2.0
1,543
0
# -*- coding: utf-8 -*- """ /**************************************************
************************* SDMXPlugin A QGIS plugin Plugin to query SDMX data cubes as WFS feature types ------------------- begin : 2017-06-14 copyright : (C) 2017 by Luca Morandini - The AURIN Project emai...
*************************************************************************** * * * 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...
endorphinl/horizon
openstack_dashboard/dashboards/vdc/infrastructure_back/tabs.py
Python
apache-2.0
1,163
0.00086
from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.vdc.infrastructure import tables class InstanceTab(tabs.Table
Tab): name = _("Instances Tab
") slug = "instances_tab" table_classes = (tables.InstancesTable,) template_name = ("horizon/common/_detail_table.html") preload = False def has_more_data(self, table): return self._has_more def get_instances_data(self): try: marker = self.request.GET.get( ...
jdwittenauer/ionyx
tests/logger_test.py
Python
apache-2.0
297
0
from ionyx.contrib import Logger
print('Beginning logger test...') path = '/home/john/temp/log.txt' logger = Logger(path, mode='replace') logger.write("Testing replace mode") logger.close() logger = Logger(path, mode='append') logger.write("Testing append mode") logger.close()
print('Done.')
shankari/e-mission-server
emission/analysis/modelling/tour_model/trajectory_matching/DifferenceMetricPipeline.py
Python
bsd-3-clause
5,060
0.010277
from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import # Standard imports from future import standard_library standard_library.install_aliases() from builtins import str from builtins import * from past.utils import old_div fr...
amt.DTW.Dtw(routeDict[_id], routeDict[key], common.calDistance) value = value.calculate_distance() differences[_id][key] = value differences[key][
_id] = value if diff_metric == 'newDTW': value = eamt.DTW.dynamicTimeWarp(routeDict[_id], routeDict[key]) differences[_id][key] = value differences[key][_id] = value if diff_metric == 'DtwSym': value = eamt.D...
cedriclaunay/gaffer
python/GafferTest/SplinePlugTest.py
Python
bsd-3-clause
12,350
0.079838
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
Y OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import unittest import IECore import Gaffer import GafferTest class SplinePlugTest( GafferTest.TestCase ) : def testConstructor( self ) : s = IEC...
IECore.CubicBasisf.catmullRom(), ( ( 0, 0 ), ( 0, 0 ), ( 0.2, 0.3 ), ( 0.4, 0.9 ), ( 1, 1 ), ( 1, 1 ), ) ) p = Gaffer.SplineffPlug( "a", defaultValue=s ) self.assertEqual( p.getValue(), s ) s2 = IECore.Splineff( IECore.CubicBasisf.linear(), ( ( 1, 1 ), ( 1, 1 ), ...
gak/giant-multiplayer-robot-helper
src/types/games_and_players.py
Python
mit
846
0
from src.types.game import Game f
rom src.types.player import Player class GamesAndPlayers(object): def __init__(self, player_db): self.player_db = player_db def parse(self, data): pdb = self.player_db # Single values self.points = data.get('CurrentTotalPoints') # Arrays # Players before Game...
f.games = [Game(pdb).parse(g) for g in data.get('Games')] return self def missing_player_ids(self): missing = set() for game in self.games: for player in game.players: if player.has_extras(): continue if not player.id: ...
zador-blood-stained/RPLCD-i2c
test_20x4.py
Python
mit
3,707
0.001079
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import sys from RPLCD_i2c import CharLCD from RPLCD_i2c import Alignment, CursorMode, ShiftMode from RPLCD_i2c import cursor, cleared try: input = raw_input except NameError: pass ...
nput('Cursor should now be at initial position. Everything should be shifted to the right by 5 characters. ') with cursor(lcd, 3, 19): lcd.write_string('X') input('The last character on the LCD should now be an "X"') lcd.d
isplay_enabled = False input('Display should now be blank. ') with cleared(lcd): lcd.write_string('Eggs, Ham, Bacon\n\rand Spam') lcd.display_enabled = True input('Display should now show "Eggs, Ham, Bacon and Spam". ') lcd.shift_display(4) input('Text should now be shifted to the right by 4 characters. ') lcd.sh...
denis-pitul/web-trash
log/views.py
Python
gpl-2.0
1,249
0.005604
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext, loader, Template, Context from dj
ango.core.urlresolvers import reverse from log.models import Entry from datetime import datetime # Create your views here. def index(request): entries = Entry.objects.order_by('-date') template = loader.get_
template('log/index.html') context = RequestContext(request, { 'entries_list': entries, }) return HttpResponse(template.render(context)) def view(request): entry_id = int(request.GET['entry_id']) entries = Entry.objects.order_by('-id') found_entry = None for entry in entries: ...
subodhchhabra/glances
glances/snmp.py
Python
lgpl-3.0
4,837
0.002067
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
) # In Python 3, pr
ettyPrint() return 'b'linux'' instead of 'linux' if ret[name.prettyPrint()].startswith('b\''): ret[name.prettyPrint()] = ret[name.prettyPrint()][2:-1] return ret def __get_result__(self, errorIndication, errorStatus, errorIndex, varBinds): """Put results in table...