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
asttra/pysces
pysces/tests/__init__.py
Python
bsd-3-clause
622
0.003215
""" PySCeS - Python Simulator for Cellular Systems (ht
tp://pysces.sourceforge.net) Copyright (C) 2004-2015 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved, Brett G. Olivier ([email protected]) Triple-J Group for Molecular Cell Physiology Stellenbosch University, South Africa. Permission to use, modi
fy, and distribute this software is given under the terms of the PySceS (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Brett G. Olivier """ # Init file used for distutils install
ltworf/relational
relational_gui/guihandler.py
Python
gpl-3.0
16,612
0.001987
# Relational # Copyright (C) 2008-2020 Salvo "LtWorf" Tomaselli # # Relational 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. # # Thi...
gram) def optimizeProgram(self): self.undo_program = self.ui.txtMultiQuery.toPlainText() result = optimizer.optimize_program( self.ui.txtMultiQuery.toPlainText(), self.user_interface.relations
) self.ui.txtMultiQuery.setPlainText(result) def optimize(self): '''Performs all the possible optimizations on the query''' self.undo = self.ui.txtQuery.text() # Storing the query in undo list res_rel,query = self.user_interface.split_query(self.ui.txtQuery.text(),None) t...
acontry/altcoin-arbitrage
arbitrage/public_markets/market.py
Python
mit
4,037
0.001734
import time import requests import config import logging class Market(object): def __init__(self): self.name = self.__class__.__name__ self.p_coin = config.p_coi
n self.s_coin = config.s_coin self.depth = {'asks': [], 'b
ids': [], 'last_updated': 0} self.prices = {'last_updated': 0} # Configurable parameters self.update_rate = 60 self.fees = {"buy": {"fee": 0.002, "coin": "p_coin"}, "sell": {"fee": 0.002, "coin": "s_coin"}} def get_depth(self): # If the update rate dictates that it is time t...
nikpap/inspire-next
inspirehep/modules/workflows/views/__init__.py
Python
gpl-2.0
998
0
# -*- coding: utf-8 -
*- # # This
file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio 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. # # Invenio is distrib...
erdem/django-selenium-example
todoapp/todoapp/wsgi.py
Python
mit
391
0
""" WS
GI config for todoapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MO...
t_wsgi_application()
kaskr/CppAD
bin/proj_desc.py
Python
epl-1.0
6,719
0.016669
#! /bin/python3 # $Id # ----------------------------------------------------------------------------- # CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell # # CppAD is distributed under multiple licenses. This distribution is under # the terms of the # Eclipse Public Licen...
------ # update cppad_conf_dir # cppad_conf_dir = os.environ['HOME'] + '/cppad.svn/conf' if os.path.exists(cppad_conf_dir ) : cmd = 'svn update ' + cppad_conf_dir print( cmd ) else : cmd = 'svn checkout https://projects.coin-or.org/svn/CppAD/conf ' cmd += cppad_conf_dir
print( cmd ) # ----------------------------------------------------------------------------- # get the current verison of the file # file_name = cppad_conf_dir + '/projDesc.xml' file_ptr = open(file_name, 'r') file_data = file_ptr.read() file_ptr.close() # -------------------------------------------------------------...
richo/groundstation
test/test_all_stores.py
Python
mit
438
0
import os from support import store_fixture impo
rt groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore def test_creates_required_dirs(self): for d in groundstation.store.git_store.GitStore.required_dirs: path = os.path.join(self.path, d)
self.assertTrue(os.path.exists(path)) self.assertTrue(os.path.isdir(path))
whlteXbread/photoManip
photomanip/tests/test_metadata.py
Python
mit
3,503
0
import os from shutil import copyfile from photomanip.metadata import ImageExif, SetExifTool from nose import tools ORIGINAL_IMAGE_FILENAME = 'photomanip/tests/turd_ferguson.jpeg' TEST_IMAGE_FILENAME = 'photomanip/tests/image_exif_test.jpg' ORIGINAL_PHOTO_FILENAME = 'photomanip/tests/test_photo_0.jpg' TEST_PHOTO_01...
red_tags[mapped_key]) def test_calculate_exposure_time(self): tag_list = self.image_exif._generate_tag_list(['exposure_time']) stored_tags = self.get_stored_tags(tag_list, TEST_PHOTO_01_FILENAME) tools.eq_(stored_tags['EXIF:ExposureTime'], 0.0013333333
33) def test_get_tags_containing(self): tag_list = self.image_exif._generate_tag_list(['keywords']) stored_tags = self.get_stored_tags(tag_list, TEST_PHOTO_01_FILENAME) result = self.image_exif.get_tags_containing( stored_tags['IPTC:Keywords'], 'faceit365') tools.eq_(res...
MSFTOSSMgmt/WPSDSCLinux
LCM/scripts/python3/GetDscConfiguration.py
Python
mit
3,596
0.003893
#!/usr/bin/env python3 import fileinput import sys import subprocess import json import time import datetime import os import os.path from OmsConfigHostHelpers import write_omsconfig_host_telemetry, write_omsconfig_host_switch_event, write_omsconfig_host_log, stop_old_host_instances import warnings with warnings.catch_...
) # Open the dsc host lock file. This also creates a file if it does not exist dschostlock_filehandle = open(dsc_host_lock_path, 'w') print("Opened the dsc host lock fi
le at the path '" + dsc_host_lock_path + "'") dschostlock_acquired = False # Acquire dsc host file lock for retry in range(10): try: flock(dschostlock_filehandle, LOCK_EX | LOCK_NB) dschostlock_acquired = True break ...
RedHatInsights/insights-core
insights/parsers/tests/test_max_uid.py
Python
apache-2.0
635
0
import doctest import pytest from insights.parsers import max_uid, ParseException, SkipException from insights.parsers.max_uid import MaxUID from insights.tests import context_wrap def test_max_uid(): with pytest.raises(SkipException): MaxUID(context_wrap("")) with pytest.raises(ParseException): ...
ma
x_uid = MaxUID(context_wrap("65536")) assert max_uid is not None assert max_uid.value == 65536 def test_doc_examples(): env = { 'max_uid': MaxUID(context_wrap("65534")), } failed, total = doctest.testmod(max_uid, globs=env) assert failed == 0
dilynfullerton/tr-A_dependence_plots
src/deprecated/int/ExpInt.py
Python
cc0-1.0
719
0
"""ExpInt.py Definition of the namedtuple that identifies a set of interaction files from which to derive data """ from __future__ import division from __future__ import unicode_literals from collections import namedtuple # noinspection PyClassHasNoInit class ExpInt(namedtuple('ExpInt', ['e', 'hw', 'base', 'rp'])): ...
ta. e: max e-level hw: hw frequency base: (default None) the mass number that normal ordering was done WRT rp: (default None) the proton radius? I do not really know what this is """ __slots__ = () def __str__(self): return str(tupl
e(self._asdict().values())).replace(', None', '') ExpInt.__new__.__defaults__ = (None, None)
ColdSauce/define
testclass.py
Python
bsd-2-clause
1,700
0.018235
import requests from os import system from time import time class dict: def __init__(self,key,urbankey,tkey): self.key = key self.urbankey = urbankey self.tkey = tkey def getDefinition(self,word): definition = requests.get("http://api.wordnik.com/v4/word.json/%s/definitions?api_k...
).json()[0]["text"] return definition def getHyphenation(self,word): hyphenation = requests.get("http://api.wordnik.com/v4/word.json/%s/hyphenation?api_key=%s" % (word,self.key)).json() return hyphenation def getAudio(self,word): url = requests.get("http://api.wordnik.com/v4/word...
quests.get("https://mashape-community-urban-dictionary.p.mashape.com/define?term=%s" % word, headers={"X-Mashape-Key": self.urbankey}).json() if urb["list"]>0: return urb["list"][0]["definition"] def getThesaurus(self,word): response = requests.get("http://words.bighugelabs.com/a...
Dining-Engineers/left-luggage-detection
misc/demo/demo_cv_async.py
Python
gpl-2.0
732
0
#!/usr/bin/env python import freenect import cv from misc.demo import frame_convert cv.NamedWindow('Depth') cv.NamedWindow('RGB') keep_running = True def display_depth(dev, data, timestamp): global keep_running
cv.ShowImage('Depth', frame_convert.pretty_depth_cv(data)) if cv.WaitKey(10) == 27: keep_running = False def display_rgb(dev, data, timestamp): global keep_running cv.ShowImage('RGB', frame_convert.video_cv(data)) if cv.WaitKey(10) == 27: keep_running = False def body(*args): if ...
int('Press ESC in window to stop') freenect.runloop(depth=display_depth, video=display_rgb, body=body)
dianshen/github
day12bbs/manage.py
Python
gpl-3.0
806
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day12bbs.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the...
) raise execute_from_
command_line(sys.argv)
Init-7/demoest
demoest/demoest/doctype/cotizacion_item_recursos_humanos/cotizacion_item_recursos_humanos.py
Python
mit
272
0.007353
#
-*- coding: utf-8 -*- # Copyright (c) 2015, Daniel and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.
document import Document class CotizacionItemRecursosHumanos(Document): pass
lazaronixon/enigma2
RecordTimer.py
Python
gpl-2.0
43,499
0.030208
import os from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop, eActionMap, setPreferredTuner from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens....
and self.service_ref.ref if rec_ref and rec_ref.flags & eServiceReference.isGroup: rec_ref = getBestPlayableServiceReference(rec_ref, eServiceReference()) if not rec_ref: self.log(1, "'get best playable service for group... record' failed") return False self.setRecordingPreferredTuner() self...
service: self.log(1, "'record service' failed") self.setRec
dacb/assembly_and_binning
assess_unbinned_reads_across_samples/assess_unbinned_reads_across_samples.py
Python
mit
858
0.011655
import os import pandas as pd #import seaborn as sns total_reads = pd.read_csv('../data/sample_info/sample_read_counts.tsv', sep='\t', names = ['fastq filename', 'number of reads']) total_reads['cryptic metagenome name'] = total_reads['fastq filename'].str.strip('.fastq.gz') sample_info = pd.read_csv('../data/sample_...
), sep='
\t', index=False)
zstackorg/zstack-woodpecker
integrationtest/vm/multihosts/volumes/paths/path119.py
Python
apache-2.0
870
0.055172
import zstackwoodpecker.test_state as ts_header TestAction = ts_header.TestAction def path(): return dict(initial_formation="template4",\ path_list=[[TestAction.delete_volume, "vm1-volume1"], \ [TestAction.reboot_vm, "vm1"], \ [TestAction.create_volume, "volume1", "=scsi"]
, \ [TestAction.attach_volume, "vm1", "volume1"], \ [TestAction.create_volume_backup, "volume1", "backup1"], \ [TestAction.stop_vm, "vm1"], \ [TestAction.cleanup_ps_cache], \ [TestAction.start_vm, "vm1"], \ [TestAction.create_volume_snapshot, "volume1", 'snapshot1'], \ [TestAction.detach_volume, "volume1"...
top_vm, "vm1"], \ [TestAction.use_volume_backup, "backup1"], \ [TestAction.start_vm, "vm1"], \ [TestAction.reboot_vm, "vm1"]])
prefetchnta/questlab
bin/x64bin/python/37/Lib/_weakrefset.py
Python
lgpl-2.1
5,875
0.001021
# Access WeakSet through the weakref module. # This code is separated-out because it is needed # by abc.py to load everything else at startup. from _weakref import ref __all__ = ['WeakSet'] class _IterationGuard: # This context manager registers itself in the current iterators of the # weak conta...
__isub__(other) def __isub__(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.difference_update(ref(item) for item in other) return self def intersection(self, other...
n other if item in self) __and__ = intersection def intersection_update(self, other): self.__iand__(other) def __iand__(self, other): if self._pending_removals: self._commit_removals() self.data.intersection_update(ref(item) for item in other) return sel...
0111001101111010/open-health-inspection-api
venv/lib/python2.7/site-packages/bson/son.py
Python
gpl-2.0
8,313
0.000481
# Copyright 2009-2012 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
e that to save binary data it must be wrapped as an instance of `bson.binary.Binary`. Otherwise it will be saved as a BSON string and retrieved as unicode. .. [#int] A Python int will be saved as a BSON int32 or BSON int64 depending on its size. A BSON int32 will always
decode to a Python int. In Python 2.x a BSON int64 will always decode to a Python long. In Python 3.x a BSON int64 will decode to a Python int since there is no longer a long type. .. [#dt] datetime.datetime instances will be rounded to the nearest millisecond when saved .. [#dt2] all datet...
Chasvortex/caffe-gui-tool
CGTArrangeHelper.py
Python
unlicense
10,580
0.004253
import bpy def forceupdate(nodes): for node in nodes: if node.inputs: for inpt in node.inputs: try: inpt.default_value = inpt.default_value # set value to itself to force update return True except: pas...
routes for node in nodes: node.select = False # deselect all nodes for node in nodes: if node.type == 'REROUTE': node.select = True bpy.ops.node.delete_reconnect() # Restore selection nodes, links = get_nodes_links(treename) ...
selection = [] for node in nodes: if node.select == True: selection.append(node.name) if context.scene.NWFrameHandling == "delete": # Store selection selection = [] for node in nodes: if node.select == True and node.type != "FRAME": ...
GluuFederation/community-edition-setup
static/extension/person_authentication/DuoExternalAuthenticator.py
Python
mit
9,408
0.004464
# oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. # Copyright (c) 2016, Gluu # # Author: Yuriy Movchan # from org.gluu.service.cdi.util import CdiUtil from org.gluu.oxauth.security import Identity from org.gluu.model.custom.script.type.auth import PersonAuthentic...
else:
return False def getExtraParametersForStep(self, configurationAttributes, step): if step == 2: return Arrays.asList("duo_count_login_steps", "cas2_user_uid") return None def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Ide...
labordoc/labordoc-next
modules/docextract/lib/docextract_webinterface.py
Python
gpl-2.0
6,745
0.003262
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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 ...
dir=CFG_TMPSHAREDDIR) try: tf.write(pdf) tf.flush() refs = extract_references_from_file_xml(tf.name) finally: # Also deletes the file tf.close() return refs def make_arxiv_url(arxiv_id): """Make a url we can use to download a pdf fro...
of the record to link to """ return "http://arxiv.org/pdf/%s.pdf" % arxiv_id class WebInterfaceAPIDocExtract(WebInterfaceDirectory): """DocExtract REST API""" _exports = [ ('extract-references-pdf', 'extract_references_pdf'), ('extract-references-pdf-url', 'extract_references_pdf_url'...
jileiwang/CJ-Glo
tools/character_count.py
Python
apache-2.0
1,312
0.005335
from collections import defaultdict import codecs def count(corpus, output_file): debug = False dic = defaultdict(int) other = set() fout = codecs.open(output_file, 'w', 'utf8') for line in open(corpus, 'r'): words = line.split() for word in words: if len(word) % 3 == 0:...
tem.decode('utf8') fout.write(item2) fout.write('\n') i += 1 if i > 20 and debug:
break fout.close() if __name__ =='__main__': count('data/train.zh_parsed', 'output/count.zh') count('data/train.ja_parsed', 'output/count.ja')
alexissmirnov/donomo
donomo_archive/deps/paypal.jonboxall/standard/ipn/models.py
Python
bsd-3-clause
1,485
0.003367
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 from paypal.standard.models import PayPalStandardBase from paypal.standard.ipn.signals import * class PayPalIPN(PayPalStandardBase): """Logs PayPal IPN interactions.""" FORMAT = u"<IPN: %s %s>" class Meta: db_table = "paypal_ipn" ...
f.set_flag("Invalid postback. (%s)" % self.response) def send_signals(self): """Shout
for the world to hear whether a txn was successful.""" # Transaction signals: if self.is_transaction(): if self.flag: payment_was_flagged.send(sender=self) else: payment_was_successful.send(sender=self) # Subscription signals: else...
monetizeio/django-pgmp
django_pgmp/__init__.py
Python
lgpl-3.0
1,587
0.006305
#!/usr/bin/env python # -*- coding: utf-8 -*- #
=== django_pgmp ---------------------------------------------------------=== # This file is part of django-pgpm. django-pgpm is copyright © 2012, RokuSigma # Inc. and contributors. See AUTHORS and LICENSE for more details. # # dj
ango-pgpm 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. # # django-pgpm is distributed in the hope that it will be useful, but...
Forage/Gramps
gramps/guiQML/views/__init__.py
Python
gpl-2.0
940
0.002128
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Benny Malengier # # This program is free software; you can redistribute it a
nd/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty ...
more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id$ """ Package init for different views in guiQML. """ # DO NOT IMPORT METHODS/CLASSES FR...
vlegoff/tsunami
src/secondaires/botanique/commandes/__init__.py
Python
bsd-3-clause
1,675
0.001791
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this ...
UT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISE
D OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant les commandes du module botanique.""" from . import recolter from . import vegetal
b1naryth1ef/rowboat
rowboat/types/guild.py
Python
mit
1,573
0.001907
import os from holster.enum import Enum from rowboat.types import Model, SlottedModel, Field, DictField, text, raw, rule_matcher CooldownMode = Enum( 'GUILD', 'CHANNEL', 'USER', ) class PluginConfigObj(object): client = None class PluginsConfig(Model): def __init__(self, inst, obj): s...
"" This function can be called to ensure that this class will have all its attributes properly loaded, as they are dynamically set when plugin configs
are defined. """ plugins = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'plugins') for name in os.listdir(plugins): __import__('rowboat.plugins.{}'.format( name.rsplit('.', 1)[0] )) class CommandOverrideConfig(SlottedModel): di...
rfleschenberg/django-safedelete
safedelete/tests.py
Python
bsd-3-clause
11,086
0.001714
import django from django.conf.urls import patterns, include from django.core.exceptions import ValidationError from django.contrib import admin from django.contrib.admin.views.main import ChangeList from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.db import model...
ode__(self): return 'Article ({0}): {1}'.format(self.pk, self.name) class Order(SoftDeleteMixin): name = models.CharField(max_length=100) articles = models.ManyToManyField(Article) class VeryImportant(safedelete_mixin_factory(NO_DELETE)): name = models.CharField(max_length=200) # ADMINMODEL (F...
deleted,) + SafeDeleteAdmin.list_display admin.site.register(Category, CategoryAdmin) # URLS (FOR TESTING) urlpatterns = patterns( '', (r'^admin/', include(admin.site.urls)), ) # TESTS class SimpleTest(TestCase): def setUp(self): self.authors = ( Author.objects.create(name='author...
Ichimonji10/elts
apps/main/views.py
Python
gpl-3.0
472
0.004237
"""Business logic for all URLs in the ``main`` application. For details on what each function is responsible for, see ``main/urls.py``. That module documents both URL-to-func
tion mappings and the exact responsiblities of each function. """ from django.core import urlresolvers from django import http def index(request): # pylint: disable=W0613 """Redirect user to ELTS application."""
return http.HttpResponseRedirect(urlresolvers.reverse('elts.views.index'))
ldoktor/autotest
client/job.py
Python
gpl-2.0
50,100
0.002335
"""The main job wrapper This is the core infrastructure. Copyright Andy Whitcroft, Martin J. Bligh 2006 """ import copy, os, re, shutil, sys, time, traceback, types, glob import logging, getpass, weakref from autotest.client import client_logging_config from autotest.client import utils, parallel, kernel, xen from a...
'download') if not os.path.exists(download): os.mkdir(download) shutil.copyfi
le(self.control, os.path.join(self.resultdir, 'control')) self.control = control self.logging = logging_manager.get_logging_mana
VladKha/CodeWars
7 kyu/Exes and Ohs/solve.py
Python
gpl-3.0
69
0
def xo(s): s = s.lower()
return s.
count('x') == s.count('o')
justasabc/python_tutorials
tutorial/gui/pyqt4/widget/slider.py
Python
gpl-3.0
1,427
0.010512
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode PyQt4 tutorial This example shows a QtGui.QSlider widget. author: Jan Bodnar website: zetcode.com last edited: September 2011 """ import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self...
_() self.initUI() def initUI(self): sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) sld.setFocusPolicy(QtCore.Qt.NoFocus) sld.setGeometry(30, 40, 100, 30) sld.valueChanged[int].connect(self.changeValue) self.label = QtGui.QLabel(self)...
self.label.setGeometry(160, 40, 80, 30) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QtGui.QSlider') self.show() def changeValue(self, value): if value == 0: self.label.setPixmap(QtGui.QPixmap('mute.png')) elif value > 0 and valu...
lucabaldini/ximpol
ximpol/test/test_sensitivity_calculator.py
Python
gpl-3.0
5,090
0.001179
#!/urs/bin/env python # # Copyright (C) 2015--2016, the ximpol team. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU GengReral Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version....
eV2erg from ximpol.core.sp
line import xInterpolatedUnivariateSplineLinear from ximpol.irf import load_arf, load_mrf from ximpol.srcmodel.gabs import xpeInterstellarAbsorptionModel """The calculator ouputs have been obtained running by hand the code on the web http://www.isdc.unige.ch/xipe/index.php/sensitivity-calculator and are stored in the...
Toollabs/video2commons
video2commons/frontend/app.py
Python
gpl-3.0
7,166
0.000558
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # Copyright (C) 2015-2016 Zhuyifei1999 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) a...
dire
ct(session.get('return_to_url', url_for('main'))) @app.route('/logout') def logout(): """Logout: clear all session data.""" session.clear() return redirect(url_for('main'))
aarontropy/django-datebook
datebook/forms.py
Python
bsd-3-clause
5,875
0.027234
from django import forms from django.utils import timezone from django.utils.formats import get_format from django.utils.safestring import mark_safe from django.forms.widgets import SplitDateTimeWidget, HiddenInput from timezones.forms import TZDateTimeField from datetime import datetime import dateutil.parser from...
Picker(forms.widgets.MultiWidget): """ This widget should display a list of seven checkboxes corresponding to the seven days of the week The values for the seven checkboxes correspond to the integer values for rrule.MO, rrule.TU, and so
on The return value from this widget is a comma-separated list of the selected integers """ def __init__(self, attrs=None): widgets = [forms.CheckboxInput(),] * 7 super(WeekdayPicker, self).__init__(widgets, attrs) def decompress(self, value): """ take a comma-separated list of integers (value) and return ...
concentricsky/badgr-server
apps/mainsite/drf_fields.py
Python
agpl-3.0
3,112
0.003213
import base64 import binascii import mimetypes import urllib.parse import uuid from django.core.exceptions import ValidationError from django.core.files.base import ContentFile from django.core.files.uploadedfile import UploadedFile from django.utils.translation import ugettext as _ from rest_framework.fields import F...
uuid4()),
extension=extension)) return ret except (ValueError, binascii.Error): return super(Base64FileField, self).to_internal_value(data) class ValidImageField(Base64FileField): default_validators = [ValidImageValidator()] def __init...
skosukhin/spack
lib/spack/spack/cmd/flake8.py
Python
lgpl-2.1
10,620
0.000094
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
ile_pattern.search(source): continue for code, patterns in errors.items(): for pattern in patterns
: if pattern.search(line): line_errors.append(code) break if line_errors: line = add_pattern_exemptions(line, line_errors) outfile.write(line) if output: ...
akshayp/college-projects
c++/car-finder/lightmarker.py
Python
mit
4,319
0.012271
# Light Marker Annotation # # (c) Scott & Linda Wills 20 November 2009 import os, Image, ImageDraw SeqDir = "./seqs/" TrlDir = "./trials/" Colors = ['pink', 'red', 'green', 'blue', 'orange', 'yellow', 'skyblue', 'purple'] def LightMarker() : """ This routine walks through each...
ta[1].strip()) Xmax = int(Data[2].strip()) Ymax = int(Data[3].strip()) A = int(Data [4].strip()) FrameData[FN].append((Xmin, Ymin, Xmax, Ymax, A)) else : # do ...
Frame = Load_Frame(SeqDir + Seq, FN) Draw = ImageDraw.Draw(Frame) if FN in FrameData : FN_Data = FrameData[FN] for (Xmin, Ymin, Xmax, Ymax, A) in FN_Data : Draw_Marker(FN, Draw, Xmin, Ymin, Xmax, Ymax) ...
misterhay/GoogleAppsProvisioning
oauth2_getAllUsers.py
Python
unlicense
3,688
0.011931
#import some things we need import httplib2 from oauth2client.client import SignedJwtAssertionCredentials #included with the Google Apps Directory API from apiclient.discovery import build import csv def downloadUsers(domain, account, customerId): superAdmin = 'is@' + domain serviceAccount = account + '@develo...
st entry in this row is the
domain account = row[1] customerId = row[2] downloadUsers(domain, account, customerId) ''' for user in page: primaryEmail = page.get(user['primaryEmail']) lastLoginTime = page.get('lastLoginTime') name = page.get('name') isAdmin = page.get('isAdmin') orgUnitPath = page.get('orgUnitPath') newPage = p...
rizar/attention-lvcsr
libs/blocks/blocks/utils/__init__.py
Python
mit
18,117
0
from __future__ import print_function import sys import contextlib from collections import OrderedDict, deque import numpy import six import theano from theano import tensor from theano import printing from theano.gof.graph import Constant from theano.tensor.shared_randomstreams import RandomStateSharedVariable from t...
, the given `value` will not be copied if possible. This can save memory and speed. Defaults to False. dtype : :obj:`str`, optional The `
dtype` of the shared variable. Default value is :attr:`config.floatX`. \*\*kwargs Keyword arguments to pass to the :func:`~theano.shared` function. Returns ------- :class:`tensor.TensorSharedVariable` A Theano shared variable with the requested value and `dtype`. """ if...
chrys87/fenrir
src/fenrirscreenreader/commands/vmenu-navigation/next_vmenu_entry.py
Python
lgpl-3.0
661
0.01059
#!/bin/python # -*- coding: utf-8 -*- # Fenrir TTY screen reader # By Chrys, Storm Dragon, and contributers. from fenrirscreenreader.core import debug class command(): def __init__(self): pass def initialize(self, environment): self.env = environment
def shutdown(self): pass def getDescription(self): return _('get nex
t v menu entry') def run(self): self.env['runtime']['vmenuManager'].nextIndex() text = self.env['runtime']['vmenuManager'].getCurrentEntry() self.env['runtime']['outputManager'].presentText(text, interrupt=True) def setCallback(self, callback): pass
hackatbrown/2015.hackatbrown.org
hack-at-brown-2015/csv_import.py
Python
mit
2,999
0.002668
import csv import webapp2 from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers import models import mentor import logging import re class ImportPageHandler(blobstore_handlers.BlobstoreUploadHandler): def get(self): upload_url = blobstore.create_upload_url('/...
ging.info(person) def create_rep(person): rep = models.Rep() rep.name = person['Name'] rep.email = person['Email Address'] pn = re.sub('[^\d]', '', person['Phone Number']) if pn: rep.phone_number = pn rep.company = person['Company'] mens
Shirt = person["T-Shirt Size [Men's]"] womensShirt = person["T-Shirt Size [Women's]"] if mensShirt in ['XS', 'S', 'M', 'L', 'XL', 'XXL']: rep.shirt_gen = 'M' rep.shirt_size = mensShirt elif womensShirt in ['XS', 'S', 'M', 'L', 'XL', 'XXL']: rep.shirt_gen = 'M' rep.shirt_size...
yiliaofan/faker
faker/providers/address/sl_SI/__init__.py
Python
mit
34,150
0.013566
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as AddressProvider class Provider(AddressProvider): city_formats = ('{{city_name}}', ) street_name_formats = ('{{street_name}}', ) street_address_formats = ('{{street_name}} {{building_number}}', ) address_formats = ('{{s...
kova ulica", "Demšarjeva cesta", "Derčeva ulica", "Dergančeva ulica", "Dermotova ulica", "Detelova ulica", "Devinska ulica", "Devova ulica", "Divjakova ulica", "Do proge", "Dobrajčeva ulica
", "Dobrdobska ulica", "Dolenjska cesta", "Dolgi breg", "Dolgi most", "Dolharjeva ulica", "Dolinarjeva ulica", "Dolinškova ulica", "Dolničarjeva ulica", "Dolomitska ulica", "Drabosnjakova ulica", "Draga", "Draveljska ulica", "Dražgoška ulica", "Drenikov vrh", "Drenikova ulica", ...
saurabh6790/frappe
frappe/desk/doctype/notification_log/notification_log.py
Python
mit
4,285
0.027071
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.desk.doctype.notification_settings.notification_settings...
.strip()] users = list(set(users)) frappe.enqueue( 'frappe.desk.doctype.notification_log.notification_log.make_notification_logs', doc=doc, users=users, now=frappe.flags.in_test ) def make_notification_logs(doc, users): from frappe.soc
ial.doctype.energy_point_settings.energy_point_settings import is_energy_point_enabled for user in users: if frappe.db.exists('User', {"email": user, "enabled": 1}): if is_notifications_enabled(user): if doc.type == 'Energy Point' and not is_energy_point_enabled(): return _doc = frappe.new_doc('Not...
tu-darmstadt-ros-pkg/hector_flexbe_behavior
hector_flexbe_states/src/hector_flexbe_states/StartCheck.py
Python
bsd-3-clause
2,388
0.031407
#!/usr/bin/env python import rospy from flexbe_core import EventState, Logger from flexbe_core.proxy import ProxyPublisher from smach import CBState class StartCheck(EventState): ''' Example for a state to demonstrate which functionality is available for state implementation. This example lets the behavior wai...
'succeeded']) def execute(self, userdata): # This method is called periodically while the state is active. # Main purpose is to check stat
e conditions and trigger a corresponding outcome. # If no outcome is returned, the state will stay active. ##if rospy.Time.now() - self._start_time < self._target_time: return 'succeeded' # One of the outcomes declared above. def on_enter(self, userdata): # This method is called when the state becomes act...
javiercantero/streamlink
tests/test_plugin_bbciplayer.py
Python
bsd-2-clause
1,639
0.004881
import json import logging import unittest from requests import Response, Request from streamlink.compat import urlencode from streamlink.plugins.bbciplayer import BBCiPlayer class TestPluginBBCiPlayer(unittest.TestCase): def test_can_handle_url(self): # should match self.assertTrue( ...
w.sportal.bg/sportal_live_tv.php?str=15")) self.assertFalse(BBCiPlayer.can_handle_url("http://www.bbc.co.uk/iplayer/")) def test_vpid_hash(self): self.assertEqual( "71c345435589c6ddeea70d6f252e2a52281ecbf3", BBCiPlayer._hash_vpid("1234567890") ) def test_extract...
xample.com/?" + urlencode(dict( goto="http://example.com/?" + urlencode(dict( state=json.dumps(dict(nonce=mock_nonce)) )) ))) mock_response = Response() mock_response.history = [ Response(), # Add some extra dummy responses in to make sure we...
michalkurka/h2o-3
h2o-py/tests/testdir_algos/grid/pyunit_grid_parallel_cv_error.py
Python
apache-2.0
1,164
0.007732
import sys import os import random sys.path.insert(1, os.path.join("..", "..", "..")) import h2o from tests import pyunit_utils from h2o.grid.grid_search import H2OGridSearch from h2o.estimators.gbm import H2OGradientBoostingEstimator def grid_parallel(): train = h2o.import_file(path=pyunit_utils.locate("smallda...
gs = H2OGridSearch( H2OGradientBoostingEstimator, hyper_params=hyper_parameters, parallelism=4 ) gs.train(x=list(range(4)), y=4, training_frame=train, fold_column="fold_assignment") assert gs is not None
# only six models are trained, since CV is not possible with min_rows=100 assert len(gs.model_ids) == 6 if __name__ == "__main__": pyunit_utils.standalone_test(grid_parallel) else: grid_parallel()
ZobairAlijan/osf.io
api_tests/nodes/serializers/test_serializers.py
Python
apache-2.0
4,035
0.001239
# -*- coding: utf-8 -*- from urlparse import urlparse from nose.tools import * # flake8: noqa from dateutil.parser import parse as parse_date from tests.base import DbTestCase, ApiTestCase, assert_datetime_equal from tests.utils import make_drf_request from tests.factories import UserFactory, NodeFactory, Registrati...
user = UserFactory() req = make_drf_request() reg = RegistrationFactory(creator=user) result = RegistrationSerializer(reg, context={'request': req}).data d
ata = result['data'] assert_equal(data['id'], reg._id) assert_equal(data['type'], 'registrations') # Attributes attributes = data['attributes'] assert_datetime_equal( parse_date(attributes['date_registered']), reg.registered_date ) assert_...
Xcelled/cap-n-snap
host.py
Python
mit
1,016
0.042323
import loggingstyleadapter log = loggingstyleadapter.getLogger(__name__) from PyQt5.QtGui import QKeySequence import hotkeys, plat class Host: def __init__(self): pass #enddef def registerDestination(self, destination): print("Don't forget to implement me (registerDestination)") #end
def def registerCommand(self, name, callback, defaultHotkey=None): hk = hotkeys.default hk.registerCommand(name, callback) if defaultHotkey and plat.Supports.hotkeys: if not hk.commandHasHotkey(name) and not hk.hasHotkey(defaultHotkey): hk.add(defaultHotkey, name) else: log.info('Not registering d...
, name=name) #endif #endif #enddef def getHotkeyForCommand(self, cmd): if plat.Supports.hotkeys: return hotkeys.default.hotkeyForCommand(cmd) else: return QKeySequence() #endif #enddef def store(self, data, type, **kwargs): ''' Stores the given data ''' print('Implement me (store) for cool st...
hessler/udacity-courses
full_stack_foundations/vagrant/restaurant/database_setup.py
Python
mit
3,008
0.001662
""" This module provides database setup and configuration. """ from database_utils import establish_session from models import Restaurant, MenuItem SESSION = None def create_data(): """Function to create and set up DB and populate with data.""" global SESSION SESSION = establish_session() # Query f...
a() # Reset price of Urban Burger's Veggie Burger urban_burger = SESSION.query(Restaurant).filter_by( name="Urban Burger" ).first()
or None if urban_burger: urban_burger_veggie_burger = SESSION.query(MenuItem).filter_by( name="Veggie Burger", restaurant=urban_burger ).first() or None urban_burger_veggie_burger.price = "$2.99" SESSION.add(urban_burger_veggie_burger) SESSION.commit() p...
sevas/csxj-crawler
csxj/datasources/parser_tools/constants.py
Python
mit
590
0
from datetime import date, time NO_TITLE = u"__NO_TITLE__" NO_AUTHOR_NAME = 'None' NO_CATEGORY_NAME = 'None' NON_EXISTENT_ARTICLE_TITLE = 'NON_EXISTENT' NO_DATE = date(1970, 01
, 01) NO_TIME = time(0, 0) NO_URL = u"__NO_URL__" UNFINISHED_TAG = u"unfinished" GHOST_LINK_TAG = u"ghost link" GHOST_LINK_TITLE = u"__GHOST
_LINK__" GHOST_LINK_URL = u"__GHOST_LINK__" PAYWALLED_CONTENT = u"__PAYWALLED__" RENDERED_STORIFY_TITLE = u"__RENDERED_STORIFY__" RENDERED_TWEET_TITLE = u"__RENDERED_TWEET__" EMBEDDED_VIDEO_TITLE = u"__EMBEDDED_VIDEO_TITLE__" EMBEDDED_VIDEO_URL = u"__EMBEDDED_VIDEO_URL__"
samsu/neutron
tests/unit/ml2/drivers/freescale/test_mechanism_fslsdn.py
Python
apache-2.0
11,225
0
# Copyright (c) 2014 Freescale, 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...
k.Mock() def test_create_update_delete_network_postcommit(self): """Testing create/
update/delete network postcommit operations.""" tenant_id = 'test' network_id = '123' segmentation_id = 456 expected_seg = [{'segmentation_id': segmentation_id}] expected_crd_network = {'network': {'network_id': network_id, ...
msincenselee/vnpy
vnpy/api/easytrader/server.py
Python
mit
2,858
0
import functools from flask import Flask, jsonify, request from . import api from .log import logger app = Flask(__name__) global_store = {} def error_handle(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) # pylint: disable=broad-ex...
turn jsonify(res), 200 @app.route("/today_entrusts", methods=["GET"]) @error_handle def get_today_entrusts(): user = global_store["user"] today_entrusts = user.today_entrusts return jsonify(today_entrusts), 200 @app.route("/today_trades", methods=["GET"]) @error_handle def get_today_trades(): user ...
sts(): user = global_store["user"] cancel_entrusts = user.cancel_entrusts return jsonify(cancel_entrusts), 200 @app.route("/buy", methods=["POST"]) @error_handle def post_buy(): json_data = request.get_json(force=True) user = global_store["user"] res = user.buy(**json_data) return jsonif...
achang97/YouTunes
lib/python2.7/site-packages/botocore/docs/shape.py
Python
mit
4,763
0
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
# and attributes. from botocore.utils import is_json_value_header class ShapeDocumenter(object): EVENT_NAME = '' def __init__(self, service_name, operation_name, event_emitter, context=None): self._service_name = service_name self
._operation_name = operation_name self._event_emitter = event_emitter self._context = context if context is None: self._context = { 'special_shape_types': {} } def traverse_and_document_shape(self, section, shape, history, ...
kkdang/synapsePythonClient
tests/unit/unit_test_DictObject.py
Python
apache-2.0
784
0.022959
import os from synapseclient.dict_object import DictObject def setup(): print('\n') print('~' * 60) print(os.path.basename(__file__)) print('~' * 60) def test_DictObject(): """Test creation and property access on DictObjects""" d = DictObject({'args_working?':'yes'}, a=123, b='foobar', nerds=...
r' assert d.nerds==['chris','jen','janey'] assert hasattr(d,'nerds') assert d['nerds']==['chris','jen','janey'] assert not hasattr(d,'qwerqwer') print(d.keys()) assert all([key in d.keys() for key in ['args_working?', 'a', 'b', 'nerds
']]) print(d) d.new_key = 'new value!' assert d['new_key'] == 'new value!'
alberto-antonietti/nest-simulator
pynest/examples/one_neuron.py
Python
gpl-2.0
3,758
0
# -*- coding: utf-8 -*- # # one_neuron.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 ...
ha", params=[{'I_e':376.0}])`. # In this example we will configure these parameters in an additional # step, which is explained in the third section. neuron = nest.Create("iaf_psc_alpha") voltmeter = nest.Create("voltmeter") ####################################################################### # Third, the
neuron is configured using `SetStatus()`, which expects # a list of node handles and a list of parameter dictionaries. # In this example we use `SetStatus()` to configure the constant # current input to the neuron. neuron.I_e = 376.0 ####################################################################### # Fourth, th...
ivannotes/luigi
test/import_test.py
Python
apache-2.0
2,285
0.000875
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
luigi.Target, luigi.LocalTarget, luigi.File, luigi.namespace, luigi.RemoteScheduler, luigi.RPCError, luigi.run, luigi.build, l
uigi.Parameter, luigi.DateHourParameter, luigi.DateMinuteParameter, luigi.DateSecondParameter, luigi.DateParameter, luigi.MonthParameter, luigi.YearParameter, luigi.DateIntervalParameter, luigi.TimeDeltaParameter, luigi.IntParameter, luigi.FloatParameter, luig...
PredictiveScienceLab/inverse-bgo
demos/catalysis/__init__.py
Python
mit
124
0
""" Initialize the module. Author: Panagiotis Tsilifis
Date: 5/22/2014 """ from _forward_model_dmnless imp
ort *
EthanBlackburn/sync-engine
inbox/util/addr.py
Python
agpl-3.0
857
0
import rfc822 from flanker.addresslib import address
def canonicalize_address(addr): """Gmail addresses with and without peri
ods are the same.""" parsed_address = address.parse(addr, addr_spec_only=True) if not isinstance(parsed_address, address.EmailAddress): return addr local_part = parsed_address.mailbox.lower() hostname = parsed_address.hostname.lower() if hostname in ('gmail.com', 'googlemail.com'): l...
atjacobs/PeakUtils
peakutils/prepare.py
Python
mit
970
0
'''Data preparation / preprocessing algorithms.''' import numpy as np def scale(x, new_range=(0., 1.), eps=1e-9): '''Changes the scale of an array Parameters ---------- x : ndarray 1D array to change the scale (remains unchanged) new_range : tuple (float, floa
t) Desired range of the array eps: float Numerical precision, to detect degenerate cases (for example, when every value of *x* is equal) Returns ------- ndarray Scaled array tuple (float, float) Previous data range, allowing a rescale to the old range '''...
_[0]) < eps: mean = (new_range[0] + new_range[1]) / 2.0 xp = np.full(x.shape, mean) else: xp = (x - range_[0]) xp *= (new_range[1] - new_range[0]) / (range_[1] - range_[0]) xp += new_range[0] return xp, range_
rbaumg/trac
trac/tests/functional/tester.py
Python
bsd-3-clause
18,151
0.00011
# -*- coding: utf-8 -*- # # Copyright (C) 2008-2019 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consi...
to_url(ticket_url) tc.url(ticket_url + '$') def go_to_wiki(self, name, version=None): """Surf to the wiki page. By default this will be the latest version of the page. :param name: name of the wiki pa
ge. :param version: version of the wiki page. """ # Used to go based on a quickjump, but if the wiki pagename isn't # camel case, that won't work. wiki_url = self.url + '/wiki/%s' % name if version: wiki_url += '?version=%s' % version self.go_to_url(wi...
akrherz/iem
scripts/outgoing/wxc_azos_prec.py
Python
mit
2,603
0
""" Generate a Weather Central Formatted file of ASOS/AWOS Precip """ import os import subprocess import datetime import psycopg2.extras from pyiem.util import get_dbconn from pyiem.network import Table as NetworkTable IEM = get_dbconn("iem", user="nobody") icursor = IEM.cursor(cursor_factory=psycopg2.extras.DictCu...
(): output = open("/tmp/wxc_airport_precip.txt", "w") output.write( """Weather Central 001d0300 Surface Data TimeStamp=%s 6 4 Station 6 TODAY RAIN 6 DAY2 RAIN 6 DAY3 RAIN 6 Lat 8 Lon """ % (datetime.datetime.utcnow().strftime("%Y.%m.%d.%H%M"),) ) data = compute_obs()...
8.3f\n") % ( sid, entry["p01"], entry["p02"], entry["p03"], entry["lat"], entry["lon"], ) ) output.close() pqstr = "data c 000000000000 wxc/wxc_airport_precip.txt bogus text" cmd ...
Opentrons/labware
api/src/opentrons/protocols/api_support/util.py
Python
apache-2.0
14,987
0.000067
""" Utility functions and classes for the protocol api """ from collections import UserDict import functools import logging from dataclasses import dataclass, field, astuple from typing import (Any, Callable, Dict, Optional, TYPE_CHECKING, Union, List, Set) from opentrons import types as top_types ...
eturn right_path return default
_edges def build_edges( where: 'Well', offset: float, mount: top_types.Mount, deck: 'Deck', radius: float = 1.0, version: APIVersion = APIVersion(2, 7)) -> List[top_types.Point]: # Determine the touch_tip edges/points offset_pt = top_types.Point(0, 0, offset) edge_list = EdgeList( ...
maggotgdv/fofix
src/Theme.py
Python
gpl-2.0
126,381
0.012352
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2006 Sami Kyöstilä ...
if self.config.has_option("theme", value): if type == bool: return isTrue(self.config.get("theme", value).lower()) elif type == "color":
return self.hexToColor(self.config.get("theme", value)) else: return type(self.config.get("theme", value)) if type == "color": return self.hexToColor(default) return default #These colors are very important #bac...
JanHelbling/mitmprotector
bin/mitmprotector.py
Python
gpl-3.0
27,675
0.00271
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # mitmprotector.py - protect's you from any kind of MITM-attacks. # # Copyright (C) 2020 by Jan Helbling <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene
ral 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 FO...
NU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # try: from os import popen, getuid, path, fork, execvp, wait, unlink, chmod, getpid, kill from sys import exit from time import sleep from logging import info, warning, critical, basicConfig, DEBUG ...
antoinedube/numeric-cookiecutter
docs/conf.py
Python
gpl-3.0
9,486
0.005799
#!/usr/bin/python # coding: utf8 # # cookiecutter-py documentation build configuration file # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; valu...
'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', "sphinx_autodoc_typehints", ] # Add any paths t
hat contain templates here, relative to this directory. templates_path = ['templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toct...
ACS-Community/ACS
LGPL/CommonSoftware/acspycommon/test/acspyTestEpochHelper.py
Python
lgpl-2.1
9,573
0.042098
#!/usr/bin/env python # @(#) $Id: acspyTestEpochHelper.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $ # # Copyright (C) 2001 # Associated Universities, Inc. Washington DC, USA. # # Produced for the ALMA project # # This library is free software; you can redistribute it and/or modify it # under # the terms of the GNU L...
"%x", 0L, 0L) #print "Current time is " , pStr # test Epoch range & toUTUdate(), toJulianYear() eout.value = 0xFFFFFFFFFFFFFFFA e1.value(eout) pStr = e1.toString(acstime.TSArray,"", 0L, 0L) print pStr pStr = e1.toString(acstime.TSArray,allOut,0L, 0L) print pStr...
onds = e1.toMJDseconds() print utc, julian #, mjdSeconds eout.value = 0L e1.value(eout) pStr = e1.toString(acstime.TSArray,allOut,0L, 0L) print pStr utc = e1.toUTCdate(0L, 0L) julian = e1.toJulianYear(0L, 0L) #mjdSeconds = e1.toMJDseconds() print utc, julian #, mjdSeconds e1.fromString(acstime.TSArray...
JensTimmerman/radical.pilot
examples/running_mpi_executables.py
Python
mit
5,342
0.009173
#!/usr/bin/env python __copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu" __license__ = "MIT" import sys import radical.pilot as rp # READ: The RADICAL-Pilot documentation: # http://radicalpilot.readthedocs.org/en/latest # # Try running this example with RADICAL_PILOT_VERBOSE=debug set if # you w...
sys.exit(), and we can here catch the # corresponding KeyboardInterrupt exception for shutdown. We also catch # SystemExit (which get
s raised if the main threads exits for some other # reason). print "need to exit now: %s" % e finally: # always clean up the session, no matter if we caught an exception or # not. print "closing session" session.close () # the above is equivalent to ...
vmthunder/nova
nova/tests/api/openstack/compute/test_servers.py
Python
apache-2.0
188,039
0.000356
# Copyright 2010-2011 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, Inc. # All Rights Reserved. # Copyright 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 Li...
els from nova import exception from nova.i18n import _ from nova.image import glance from nova.ne
twork import manager from nova.network.neutronv2 import api as neutron_api from nova import objects from nova.objects import instance as instance_obj from nova.openstack.common import jsonutils from nova.openstack.common import policy as common_policy from nova import policy from nova import test from nova.tests.api.op...
glesica/django-site-news
site_news/constants.py
Python
bsd-3-clause
122
0
""" Django-site
-news con
stants. These are for convenience. """ # Category defaults DOWNTIME = 30 CHANGES = 20 INFO = 10
zhuango/python
pythonLearning/oo/FrenchDeck.py
Python
gpl-2.0
487
0.004107
#!/usr/bin/python3 Card = c
ollections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self...
._cards) def __getitem__(self, position): return self._cards[position]
IndonesiaX/edx-platform
lms/djangoapps/courseware/tests/test_microsites.py
Python
agpl-3.0
10,562
0.003124
""" Tests related to the Microsites feature """ from django.conf import settings from django.core.urlresolvers import reverse from django.test.utils import override_settings from nose.plugins.attrib import attr from courseware.tests.helpers import LoginEnrollmentTestCase from course_modes.models import CourseMode from...
site_course_enrollment(self): """ Enroll user in a course scoped in a Microsite and one course outside of a Microsite and make sure that they are only visible in the right Dashboards """ self.setup_users() email, password = self.STUDENT_INFO[1] self.login(email, ...
s appear resp = self.client.get(reverse('dashboard'), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertContains(resp, 'Robot_Super_Course') self.assertNotContains(resp, 'Robot_Course_Outside_Microsite') # Now access the non-microsite dashboard and make sure the right courses appea...
onecloud/ovs-igmp-v3
tests/appctl.py
Python
apache-2.0
2,351
0
# Copyright (c) 2012 Nicira, 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 wri...
# limitations u
nder the License. import argparse import signal import sys import ovs.daemon import ovs.unixctl import ovs.unixctl.client import ovs.util import ovs.vlog def connect_to_target(target): error, str_result = ovs.unixctl.socket_name_from_target(target) if error: ovs.util.ovs_fatal(error, str_result) ...
zulu7/pylib
crypto/stream_crypto.py
Python
bsd-3-clause
1,198
0.01586
#!/usr/bin/env python from Crypto import Random from M2Crypto import EVP from io_helper import stream from padding import pad_pkcs5, unpad_pkcs5 from chunk_buffer import ChunkBuffer ALGORITHM = 'aes_256_cbc' # AES has a fixed block size of 16 bytes regardless of key size BLOCK_SIZE = 16 ENC=1 DEC=0 def encrypt(i...
key, iv, pad=True, chunk_size=stream.DEFAULT_CHUNK_SIZE, alg=ALGORITHM): cipher = EVP.Cipher(alg=alg, key=key, iv=iv, op=ENC) size = 0 for chunk in stream.chunk_iter(in_file): out_file.write(cipher.update(chunk)) size += len(chunk) if pad: padding = pad_pkcs5(size, BLOCK_SIZE) out_file.write(ci...
=stream.DEFAULT_CHUNK_SIZE): cipher = EVP.Cipher(alg=ALGORITHM, key=key, iv=iv, op=DEC) buf = ChunkBuffer( min_size=BLOCK_SIZE, evict_fn=lambda chunk: out_file.write(chunk) ) for chunk in stream.chunk_iter(in_file): buf.append(cipher.update(chunk)) buf.append(cipher.final()) remainder = buf.ge...
Joergen/zamboni
mkt/purchase/tests/test_utils_.py
Python
bsd-3-clause
983
0
import amo import amo.tests import waffle from users.models import UserProfile from mkt.purchase.utils import payments_enabled from mkt.site.fixtures import fixture from test_utils import RequestFactory class TestUtils(amo.tests.TestCase): fixtures = fixture('user_2519') def setUp(self): self.req...
MITED=False): assert payments_enabled(self.req) def test_not_flag(self): with self.settings(PAYMENT_LIMITED=True): assert not payments_enabled(self.req) def test_flag(self): profile = UserProfi
le.objects.get(pk=2519) flag = waffle.models.Flag.objects.create(name='override-app-payments') flag.everyone = None flag.users.add(profile.user) flag.save() self.req.user = profile.user with self.settings(PAYMENT_LIMITED=True): assert payments_enabled(self.r...
SuperMarioBean/microblog
app/views.py
Python
bsd-3-clause
6,281
0.018468
from flask import render_template, flash, redirect, session, url_for, request, g from flask.ext.login import login_user, logout_user, current_user, login_required from app import app, db, lm, oid from forms import LoginForm, EditForm, PostForm, SearchForm from models import User, ROLE_USER, ROLE_ADMIN, Post from dateti...
['GET', 'POST']) @login_required def edit(): form = EditForm(g.user.nickname) if form.validate_on_submit(): g.user.nickname = form.nickname.data g.user.about_me = form.about_me.data db.session.add(g.user) db.session.commit() flash('Your changes have been saved.') ...
form.nickname.data = g.user.nickname form.about_me.data = g.user.about_me return render_template('edit.html', form = form) @app.route('/follow/<nickname>') @login_required def follow(nickname): user = User.query.filter_by(nickname = nickname).first() if user == None: flash('...
shernshiou/CarND
Term1/04-CarND-Behavioral-Cloning/model.py
Python
mit
6,595
0.006065
from keras.models import Sequential, model_from_json from keras.layers import Dense, Dropout, Activation, Flatten, Convolution2D, MaxPooling2D, Lambda, ELU from keras.layers.normalization import BatchNormalization from keras.optimizers import Adam import cv2 import csv import numpy as np import os from random import r...
return model def nvidialite_model(row=33, col=100, ch=3, dropout=0.3, lr=0.0001): # # Modified of NVIDIA CNN Model (Dysfunctional) # input_shape = (row, col, ch) model = Sequential() model.add(BatchNormalization(axis=1, input_shape=input_shape)) model.add(Convolution
2D(24, 5, 5, border_mode='valid', subsample=(2, 2), activation='elu')) model.add(Convolution2D(36, 5, 5, border_mode='valid', subsample=(2, 2), activation='elu')) model.add(Convolution2D(48, 3, 3, border_mode='valid', subsample=(1, 1), activation='elu')) model.add(Flatten()) mode...
SiggyF/dotfiles
.config/ipython/profile_default/ipython_config.py
Python
mit
18,950
0.00438
# Configuration file for ipython. c = get_config() #------------------------------------------------------------------------------ # InteractiveShellApp configuration #------------------------------------------------------------------------------ # A Mixin for applications that start InteractiveShell instances. # #...
iveShell.show_rewritten_input = True # Set the color scheme (NoColor, Linux, or LightBG). # c.TerminalInteractiveShell.colors = 'Linux' # Autoindent IPython code entered interactively. # c.TerminalInteractiveShell.autoindent = True # # c.TerminalInteractiveShell.separate_in = '\n' # Deprecated, use PromptManager.i...
nteractiveShell.prompt_in1 = 'In [\\#]: ' # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more ...
0dataloss/pyrax
samples/cloud_loadbalancers/session_persistence.py
Python
apache-2.0
1,492
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, Inc. # All Rights Reserved. # # Licen
sed under the Apache License, Version 2.0 (the "L
icense"); 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 the License is distributed on an "AS IS" B...
jzbontar/orange-tree
Orange/statistics/contingency.py
Python
gpl-3.0
10,334
0.001355
import math import numpy as np from Orange import data def _get_variable(variable, dat, attr_name, expected_type=None, expected_name=""): failed = False if isinstance(variable, data.Variable): datvar = getattr(dat, "variable", None) if datvar is not None and datvar is not var...
continue
w = row.weight if math.isnan(cval): self.unknowns[cval] += w else: self[rval, cval] += w self.row_variable = row_variable self.col_variable = col_variable return self def __eq__(self, other): return np.arr...
antivirtel/Flexget
tests/test_html5lib.py
Python
mit
689
0
from __future__ import unicode_literals, division, absolute_import from flexget.utils.soup import ge
t_soup class TestHtml5Lib(object): config = 'tasks: {}' def test_parse_broken(self, execute_task): s = """<html> <head><title>Foo</title> <body> <p class=foo><b>Some Text</b> <p><em>Some Other Text</em>""" soup = get_soup(s) body = soup.find('body') ps = body.find_all('p') ...
em.parent.name == 'p' assert soup.find('p', attrs={'class': 'foo'})
renhaocui/adPlatform
usernameExtractor.py
Python
mit
2,122
0.001414
import time import twitter import json __author__ = 'rencui' def oauth_login(): # credentials for OAuth CONSUMER_KEY = c_k CONSUMER_SECRET = c_s OAUTH_TOKEN = a_t OAUTH_TOKEN_SECRET = a_t_s # Creating the authentification auth = twitter.oauth.OAuth(OAUTH_TOKEN, ...
itter_api.users.lookup(screen_name=','.join(tempList)) tempList = []
for user in response: screenName = user['screen_name'] outputList.append(screenName) outputFile.write(json.dumps(user)+'\n') elif index == len(nameList)-1: tempList.append(userId) requestCount += 1 response = twitter_api.users.lookup(screen_name=','.join(t...
Ceasar/grammar
test_grammar.py
Python
mit
1,016
0.000984
impor
t pytest from grammar import Grammar, Production @pytest.fixture def grammar(): S = 'S' NP = 'NP' VP = 'VP' T, N, V = 'T', 'N', 'V' productions = { Production(S, [NP, VP]), Prod
uction(NP, [T, N]), Production(VP, [V, NP]), Production(T, {'the'}), Production(N, {'man', 'ball'}), Production(V, {'hit', 'took'}), } grammar = Grammar( terminals={T, N, V}, nonterminals={S, NP, VP}, productions=productions, start=S, ) ret...
darius/toot
toot7_chained.py
Python
gpl-3.0
2,474
0.005255
"Represent the analyzed program as a list of instructions." # t: tree node # dn, dv: definition names, definition values (i.e. analyzed definitions) # vn, vv: variable names, variable values import abstract_syntax as A def eval_program(program): dn = tuple(defn.name for defn in program.defns) dv = tuple(...
r, dv, ()) def run(instructions, dv, vv): stack = [] pc = 0 while pc < len(instructions): pc += instructions[pc](dv, vv, stack) return stack.pop() A.Constant.analyze = lambda t, dn, vn: do_constant(t.value) A.Variable.analyze = lambda t, dn, vn: do_variable(vn.index(t.name)) A.If .analyze...
vn)) A.Call .analyze = lambda t, dn, vn: do_call(dn.index(t.name), tuple(argument.analyze(dn, vn) for argument in t.arguments)) A.Prim2 .analyze = lambda t, dn, vn: do_prim2(t.op, ...
s6joui/MirrorOS
system/core/gesture-recognizer/sensors_raw_left.py
Python
mit
1,155
0.041558
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) TRIG = 35 ECHO = 38 GPIO.setup(TRIG,GPIO.OUT) GPIO.output(TRIG,0) GPIO.setup(ECHO,GPIO.IN) time.sleep(0.1) print ("Starting gesture recognition") try: # here you put your main loop or block of code while True: value_list = [] for x in xran...
t(); print value_list[2] except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print ("exiting") except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging # so only us...
GPIO.cleanup() # this ensures a clean exit
rahul67/hue
apps/beeswax/src/beeswax/test_base.py
Python
apache-2.0
16,313
0.010804
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
k here. 'AUX_CLASSPATH': get_run_root('ext/hadoop/hadoop') + '/share/hadoop/hdfs/hadoop-hdfs.jar' + ':' + get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/lib/hadoop-auth.jar' + ':' + get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/hadoop-common.jar' + ':...
env["JAVA_HOME"] = os.getenv("JAVA_HOME") LOG.info("Executing %s, env %s, cwd %s" % (repr(args), repr(env), cluster._tmpdir)) return subprocess.Popen(args=args, env=env, cwd=cluster._tmpdir, stdin=subprocess.PIPE) def get_shared_beeswax_server(db_name='default'): global _SHARED_HIVE_SERVER global _SHARED_...
pawelmhm/splash
splash/qwebpage.py
Python
bsd-3-clause
6,186
0.000647
# -*- coding: utf-8 -*- from __future__ import absolute_import from collections import namedtuple import sip from PyQt5.QtWebKitWidgets import QWebPage, QWebView from PyQt5.QtCore import QByteArray from twisted.python import log import six from splash.har_builder import HarBuilder RenderErrorInfo = namedtuple('Rende...
:%d): %s" % (source_id, line_number, msg), system='render') def userAgentForUrl(self, url): if self.custom_user_agent is None: return super(SplashQWebPage, self).userAgentForUrl(url) else: return self.custom_user_agent # loadFinished signal handler receives ok=False at ...
# 2. when a redirect happened before all related resource are loaded; # 3. when page sends headers that are not parsed correctly # (e.g. a bad Content-Type). # By implementing ErrorPageExtension we can catch (1) and # distinguish it from (2) and (3). def extension(self, extension, info=None, err...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/boto/mws/connection.py
Python
agpl-3.0
49,807
0.000161
# Copyright (c) 2012-2014 Andy Davidoff http://www.disruptek.com/ # # 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...
d', '/Recommendations/2013-04-01'), 'CustomerInfo': ('2014-03-01', 'SellerId', '/CustomerInformation/2014-03-01'), 'CartInfo': ('2014-03-01', 'SellerId', '/CartInformation/2014-03-01'), 'Subscriptions': ('2013-07...
zonPayments': ('2013-01-01', 'SellerId', '/OffAmazonPayments/2013-01-01'), } content_md5 = lambda c: encodebytes(hashlib.md5(c).digest()).strip() decorated_attrs = ('action', 'response', 'section', 'quota', 'restore', 'version') api_call_map = {} def add_attrs_from(func, t...
gticket/scikit-neuralnetwork
sknn/tests/test_sklearn.py
Python
bsd-3-clause
2,706
0.005174
import unittest from nose.tools import (assert_equal, assert_raises, assert_in, assert_not_in) import numpy from scipy.stats import randint, uniform from sklearn.grid_search import GridSearchCV, RandomizedSearchCV from sklearn.cross_validation import cross_val_score from sknn.mlp import Regressor as MLPR, Classifier...
SearchCV( self.__estimator__(layers=[L("Rectifier", units=12), L("Linear")], n_iter=1), param_grid={'hidden0__units': [4, 8, 12]}) clf.fit(self.a_in, self.a_out) def test_RandomGlobalParams(self): clf = RandomizedSearchCV( self.__estimator...
, 0.01)}, n_iter=2) clf.fit(self.a_in, self.a_out) def test_RandomLayerParams(self): clf = RandomizedSearchCV( self.__estimator__(layers=[L("Softmax", units=12), L("Linear")], n_iter=1), param_distributions={'hidden0__units': randint(4, 12...
stscieisenhamer/glue
glue/viewers/scatter/layer_artist.py
Python
bsd-3-clause
18,014
0.001832
from __future__ import absolute_import, division, print_function import numpy as np from matplotlib.colors import Normalize from matplotlib.collections import LineCollection from mpl_scatter_density import ScatterDensityArtist from astropy.visualization import (ImageNormalize, LinearStretch, SqrtStretch, ...
if self.state.vx_att is not None and self.state.vy_att is not None: vx = self.layer[self.state.vx_att].ravel() vy = self.layer[self.state.vy_att].ravel() if self.state.vector_mode == 'Polar':
ang = vx length = vy # assume ang is anti clockwise from the x axis vx = length * np.cos(np.ra
pyhmsa/pyhmsa
pyhmsa/fileformat/importer/emsa.py
Python
mit
12,424
0.002173
""" Importer from EMSA file format """ # Standard library modules. import datetime # Third party modules. import numpy as np # Local modules. from pyhmsa.fileformat.importer.importer import _Importer, _ImporterThread from pyhmsa.fileformat.common.emsa import calculate_checksum from pyhmsa.datafile import DataFile f...
ict # Globals and constants variables. from pyhmsa.spec.condition.detector import \ (COLLECTION_MODE_PARALLEL, COLLECTION_MODE_SERIAL, XEDS_TEC
HNOLOGY_GE, XEDS_TECHNOLOGY_SILI, XEDS_TECHNOLOGY_SDD, XEDS_TECHNOLOGY_UCAL, SIGNAL_TYPE_EDS, SIGNAL_TYPE_WDS, SIGNAL_TYPE_CLS) from pyhmsa.fileformat.common.emsa import \ (EMSA_ELS_DETECTOR_SERIAL, EMSA_ELS_DETECTOR_PARALL, EMSA_EDS_DETECTOR_SIBEW, EMSA_EDS_DETECTOR_SIUTW, EMSA_EDS_DETECTOR_SIWLS, ...
fangjing828/LEHome
home.py
Python
apache-2.0
9,281
0.004432
#!/usr/bin/env python # encoding: utf-8 # Copyright 2014 Xinyu, He <[email protected]> # # 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...
.parse(cmd) def activate(self):
Sound.play(Res.get_res_path("sound/com_begin")) self._spk.start() self.runtime.start() application = tornado.web.Application([ (r"/home/cmd", CmdHandler, dict(home=self)), ]) application.listen(self._cmd_bind_port.encode("utf-8")) tornado.ioloop.PeriodicCa...
peterayeni/dash
dash/dashblocks/migrations/0003_auto_20140804_0236.py
Python
bsd-3-clause
1,506
0.001328
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def generate_initial_block_types(apps, schema_editor): User = apps.get_model("auth", "User") root = User.objects.filter(username="root").first() if not root: root = User.objects.filter(usernam...
has_color=False,
has_video=False, has_tags=False, created_by=root, modified_by=root) class Migration(migrations.Migration): dependencies = [ ('dashblocks', '0002_auto_201...
googleapis/python-spanner
samples/generated_samples/spanner_v1_generated_database_admin_create_database_async.py
Python
apache-2.0
1,667
0.0006
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
argument(s) request = spanner_admin_database_v1.CreateDatabaseRequest( parent="parent_value", create_statement="create_statement_value", ) # Make the request operation = client.create_database(request=request) print("Waiting for operation to complete...") response = await ope...
D spanner_v1_generated_DatabaseAdmin_CreateDatabase_async]
googleapis/python-datalabeling
samples/generated_samples/datalabeling_v1beta1_generated_data_labeling_service_update_evaluation_job_sync.py
Python
apache-2.0
1,524
0.001969
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.
apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 impl
ied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for UpdateEvaluationJob # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environmen...
Microsoft/PTVS
Python/Tests/TestData/DebuggerProject/LocalsTest3.py
Python
apache-2.0
28
0.071429
de
f f(x): y = 'abc' f(42)
abhipec/academicCodes
CS350M/main.py
Python
gpl-2.0
2,153
0.006038
from tree import * from worker import * import multiprocessing import graph as graph import random # create a sample undirected graph g = graph.sampleUnDirectedGraph() # get list of all vertex in graph vertexList = g.getVertices() # initialize an empty tree object tree = Tree() # choose random node from graph, this wi...
t visited before, add it marked li
st and queue if edge not in marked: # add this edge to tree tree.addChild(queue[0],edge) marked.append(edge) queue.append(edge) # remove first element from queue queue.pop(0) # open data source file f = open('data.txt', 'r') # read data source file into a list dat...
decvalts/iris
lib/iris/tests/test_hybrid.py
Python
gpl-3.0
9,487
0.000211
# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # # Iris 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 l...
self.assertEqual(points.dtype, np.float32) self.assertAlmostEqual(points.min(), np.float32(191.84892)) self.assertAlmostEqual(points.max(), np.float32(40000))
# Convert the reference surface to float64 and check the # derived coordinate becomes float64. temp = self.cube.coord('surface_air_pressure').points temp = temp.astype('f8') self.cube.coord('surface_air_pressure').points = temp points = self.cube.coord('air_pressure').points ...