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
mass-project/mass_hash_request
mass_hash_request.py
Python
mit
9,725
0.001131
#! /usr/bin/env python import argparse import logging import sys import os import json import re import tarfile from datetime import datetime from mass_api_client import ConnectionManager from mass_api_client.resources import Sample, FileSample, IPSample, URISample, DomainSample PROGRAM_NAME = "MASS Hash Request" PR...
th + '/SampleNotFound', 'w').close() def generate_report_dir(path, result): reports_path = path + '/Reports' reports = result.get_reports() for report in repor
ts: analysis_system = re.search('/analysis_system/([^/]*)/', report.analysis_system).group(1) analysis_system_path = '{}/{}'.format(reports_path, analysis_system) touch_path(analysis_system_path) for key in report.json_report_objects: report_object_path = '{}/{}.json'.format...
thomas-coudrat/pca_analysis
pca_analysis.py
Python
mit
11,101
0.00009
#!/usr/bin/env python # Calculate principal component analysis on multivariate data stored in a .csv # file and display it in a 2D plot (optional 3D) # # https://github.com/thomas-coudrat/pca_analysis # Thomas Coudrat <thomas.coudrat@gmail.com> # from __future__ import unicode_literals, print_function import pandas a...
plt from sklearn.decomposition import PCA import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib as mpl from sklearn.preprocessing import StandardScaler, MinMaxScaler def main(): """ Runs the pca_analysis script """ # Collect arguments csvPath, rounded, proj...
sep=",").dropna() # Use the colors provided if "color" in df.columns: colors = df.color.values dfData = df.drop("color", axis=1) colors = [[int(a) for a in x.split(":")] for x in colors.tolist()] # if not generate a gradient from colormap else: dfData = df cm = ...
thaim/ansible
lib/ansible/modules/cloud/google/gcp_compute_backend_service.py
Python
mit
44,362
0.004328
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
_future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["...
ce description: - A Backend Service defines a group of virtual machines that will serve traffic for load balancing. This resource is a global backend service, appropriate for external load balancing or self-managed internal load balancing. - For managed internal load balancing, use a regional backend service instea...
akx/stackspy
stackspy/detectors/frameworks/pyramid.py
Python
mit
587
0.018739
# -- encoding: utf-8 -- from __future__ im
port with_statement from stackspy.utils import first import difflib def probe_pyramid_no_slashes(context): test_url = first(u.url for u in context.html_urls if len(u.relative_url) > 2 and u.endswith("/")) if test_url: with_slash = context.get_url(test_url) without_slash = context.get_url(test_url.rstrip("/")) ...
], 1, 0.8) != []: test_url.add_result("Pyramid", "Don't care about slashes behavior", detail="Tested against %s" % without_slash.url, confidence=0.3)
mozts2005/OuterSpace
server/lib/ige/ospace/IPlayer.py
Python
gpl-2.0
43,445
0.028473
# # Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/] # # This file is part of IGE - Outer Space. # # IGE - Outer Space 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 t...
ick (TODO remove in 0.5.33) if not hasattr(obj, "fullName"): obj.fullName = obj.name # check if player is a leader if not obj.galaxies: log.debug
(obj.oid, obj.name, "IS NOT IN ANY GALAXY") else: galaxy = tran.db[obj.galaxies[0]] if galaxy.imperator != obj.oid and obj.imperator > 0: log.debug(obj.oid, "Removing imperator/leader bonus") obj.imperator = 0 ## NON VALIDATING CODE (DERIVED ATTRS AND SO ON) # get best technologies for planet...
dimagi/commcare-hq
corehq/apps/saved_reports/exceptions.py
Python
bsd-3-clause
302
0
class Unsu
pportedSavedReportError(Exception): """ For unknown (discontinued/legacy) saved-reports """ pass class UnsupportedScheduledReportError(Exception): """ For unknown (discontinued/legacy) scheduled-reports """
pass class ReportNotFound(Exception): pass
jfunez/scielo-manager
scielomanager/journalmanager/tests/tests_modelmanagers.py
Python
bsd-2-clause
36,083
0.000055
# coding: utf-8 from django.test import TestCase from django_factory_boy import auth from journalmanager import ( models, modelmanagers, ) from journalmanager.tests import modelfactories class JournalManagerTests(TestCase): def _make_user(self, *collection): user = auth.UserF(is_active=True) ...
ion2 = modelfactories.CollectionFactory.create() user = self._make_user(collection1, collection2) collection2.make_default_to_user(user) journal1 = modelfactories.JournalFactory.create(collection=collection1) journal2 = modelfactories.JournalFactory.create(collection=collection2) ...
y.create() def get_user_collections(): return user.user_collection.all() user_journals = models.Journal.userobjects.all( get_all_collections=get_user_collections) self.assertEqual(user_journals.count(), 2) self.assertIn(journal1, user_journals) self.ass...
protonn/Electrum-Cash
gui/kivy/uix/dialogs/fx_dialog.py
Python
mit
3,539
0.002543
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder Builder.load_string(''' <FxDialog@Popup> id: popup title: 'Fiat Currency' size_hint: 0.8, 0.8 pos_hint: {'top':0.9} BoxLayout: orientation: 'vertical' B...
f self.fx.is_enabled() else '' ex = self.ids.exchanges ex.values = exchanges ex.text = (mx if mx in exchanges else excha
nges[0]) if self.fx.is_enabled() else '' def on_exchange(self, text): if not text: return if self.fx.is_enabled() and text != self.fx.exchange.name(): self.fx.set_exchange(text) def add_currencies(self): currencies = sorted(self.fx.exchanges_by_ccy.keys()) if se...
nerdvegas/rez
src/rez/cli/gui.py
Python
apache-2.0
648
0
# SPDX-License-Identifier: Apache-2.0 # Copyright Contributors to the Rez Project """ Run the Rez GUI application. """ def setup_parser(parser, completions=False): parser.add_argument( "--diff", nargs=2, metavar=("RXT1", "RXT2"), help="open in diff mode with the given contexts") FILE_action ...
parser=None, extra_arg_groups=None): from rezgui.app import run run(opts,
parser)
arizvisa/syringe
template/image/pict/v1.py
Python
bsd-2-clause
1,778
0.007312
from .base import * class OpStash(object): cache = {} @classmethod def Add(cls, object): t = object.type cls.cache[t] = object @classmethod def Lookup(cls, type): return cls.cache[type] @classmethod def Define(cls, pt): cls.Add(pt) return pt class ...
(Integer, 'cmpSize'), (Long, 'planeBytes'), (Long, 'pmTable'), (Long, 'pmReserved'), ] class directBitsRect(pstruct.type): opcode = 0x009
a _fields_ = [ (pixMap, 'pixMap'), (bounds, 'srcRect'), (bounds, 'dstRect'), (Integer, 'mode'), ] class File(parray.terminated): _object_ = OpRecord def isTerminator(self, value): return int(value['code']) == 0xff
tsennikova/scientists-analysis
clustering/u-shapelets_clustering.py
Python
mit
10,783
0.010294
''' Created on 15 Aug 2016 @author: sennikta ''' import os from os import listdir import numpy import json import operator from operator import itemgetter from itertools import islice import math import dis from itertools import islice # TODO: try Livenstein distance, base_dir = os.path.dirname(o...
td_b-(mean_a+std_a) # print ' curr_gap = ', curr_gap, cluster_a if curr_gap>gap: gap=curr_gap cluster = cluster_a # print cluster # print 'returned values ', shapelet, gap, cluster return gap, cluster, shapelet def clustering(sax_dict, shapelets, gap_dic...
= int(262*0.05) ub = int(262*0.6) # lb = 4 # ub = 6 candidate_dict = {} sorted_candidate_dict = {} gap_shap_dict = {} for i in range(0,len(shapelets)): curr_gap = 0 # if iter == 0: # shapelets[i] = str(shapelets[i].replace('\'','')) # shape...
OpenClovis/SAFplus-Availability-Scalability-Platform
src/ide/umlEditor.py
Python
gpl-2.0
42,936
0.0218
import pdb import math import time from types import * import wx import wx.lib.wxcairo import cairo import rsvg import yang import svg import wx.lib.scrolledpanel as scrolled #from wx.py import shell, #from wx.py import version import dot from common import * from module import Module from entity import * from model ...
panel.statusBar.
SetStatusText("Click on an entity and drag to another entity to create a relationship.",0); return True def OnUnselect(self,panel,event): return True def OnEditEvent(self,panel, event): pos = panel.CalcUnscrolledPosition(event.GetPositionTuple()) ret = False if isinstance(event,wx.MouseEvent):...
Oweoqi/metagoofil
extractors/metadataPDF.py
Python
gpl-2.0
3,062
0.049314
#!/usr/bin/env python2 # # metadataPDF.py - dump pdf metadata # # Copy of Yusuke's dumppdf to add dumpmeta import sys, re, os from pdfminer.psparser import PSKeyword, PSLiteral from pdfminer.pdfparser import PDFDocument, PDFParser from pdfminer.pdftypes import PDFStream, PDFObjRef, resolve1, stream_value from pdfminer...
) # return "ok" #except: # print "[x] Error in PDF extractor, Metadata catalog" try: for xref in doc.xrefs: info_ref=xref.trailer.get('Info') if info_ref: info=resolve1(info_ref) self.metadata=info self.raw = info if self.raw == None:
return "Empty metadata" else: return "ok" except Exception,e: return e print "\t [x] Error in PDF extractor, Trailer Info" def getEmails(self): em=myparser.parser(self.text) return em.emails() def getHosts(self,domain): em=myparser.parser(self.text,domain) return em.hostnames() def...
mozvip/Sick-Beard
sickbeard/show_queue.py
Python
gpl-3.0
18,584
0.004036
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 t...
class ShowQueue(generic_queue.GenericQueue):
def __init__(self): generic_queue.GenericQueue.__init__(self) self.queue_name = "SHOWQUEUE" def _isInQueue(self, show, actions): return show in [x.show for x in self.queue if x.action_id in actions] def _isBeingSomethinged(self, show, actions): return self.currentItem !...
slundberg/shap
tests/plots/test_bar.py
Python
mit
509
0.005894
''' This file contains tests for the bar plot. ''' import matplotlib.pyplot as plt import pytest import shap from .utils import explainer # (pytest fixture do not remove) pylint: disable=unused-import @pytest.mark.mpl_image_compare def test_simple_bar(explainer): # pylint: disable=redefined-outer-name """ Check ...
fig = plt.figure() shap.plots.bar(shap_values, show=Fa
lse) plt.tight_layout() return fig
ESOedX/edx-platform
openedx/core/djangoapps/service_status/views.py
Python
agpl-3.0
1,236
0
""" Django Views for service status app """ from __future__ import absolute_import import json import time from celery.exceptions import TimeoutError from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_): """ An e...
esult try: value = result.get(timeout=4.0) success = True except TimeoutError:
value = None success = False output = { 'success': success, 'task_id': task_id, 'value': value, 'time': time.time() - start, } return HttpResponse(json.dumps(output, indent=4), content_type="application/json")
OddBloke/jenkins-job-linter
integration_tests/conftest.py
Python
apache-2.0
203
0
def pytest_addoption(parser): parser.addoption('--jenkins-doc
ker', action='store', defau
lt='jenkins/jenkins', help='The Jenkins Docker container to launch')
qedsoftware/commcare-hq
custom/ewsghana/tests/test_urgent_alerts.py
Python
bsd-3-clause
5,270
0.003036
from datetime import datetime from casexml.apps.stock.models import StockReport from corehq.apps.commtrack.models import StockState from corehq.apps.products.models import Product from corehq.apps.sms.models import SMS from corehq.apps.sms.tests.util import setup_default_sms_test_backend, delete_domain_phone_numbers ...
reate_stock_report(self.loc2, {'tp2': 0}) create_stock_report(self.loc3, {'tp2':
0}) urgent_stockout_alert.send() self.assertEqual(SMS.objects.count(), 1) self.assertEqual(SMS.objects.all().first().text, URGENT_STOCKOUT % { 'location': self.district.name, 'products': "Test Product2", }) create_stock_report(self.loc1, {'tp': 0}) ...
zstackorg/zstack-woodpecker
integrationtest/vm/simulator/dhcp_server_ip/test_dhcp_for_networkSegment_ipv6.py
Python
apache-2.0
2,459
0.00122
''' 1.create public network with Network segment 1.1 add ipv6 address 2.check dhcp ip address @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations...
est_logger("add ip v4 range to l3 network") public_network.add_ipv6_range( ip_range_name, start_ip, endip, gate_way, prifixLen, dhcp_system_tags) if public_network.check_dhcp_ipaddress().find(dhcp_ip_for_public.lower()) == -1: test_util.test_fail("dhcp server ip create fail") test_util.test...
to be define ''' def error_cleanup(): pass ''' to be define ''' def env_recover(): pass
arnaudmorin/python-ovh
tests/test_client.py
Python
bsd-3-clause
16,541
0.003809
# -*- encoding: utf-8 -*- # # Copyright (c) 2013-2017, OVH SAS. # 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, t...
_key) self.assertEqual('This is a *real* custom application key', api._application_secr
et) self.assertEqual('I am customingly kidding', api._consumer_key) @mock.patch.object(Client, 'call') def test_time_delta(self, m_call): api = Client(ENDPOINT, APPLICATION_KEY, APPLICATION_SECRET, CONSUMER_KEY) m_call.return_value = 1404395895 api._time_delta = None # ...
ktan2020/legacy-automation
win/Lib/site-packages/runsnakerun/homedirectory.py
Python
mit
2,694
0.01559
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to...
"""Get a shell folder
by shell-constant from COM interface""" return shell.SHGetFolderPath( 0,# null hwnd type, # the (roaming) appdata path 0,# null access token (no impersonation) 0 # want current value, shellcon.SHGFP_TYPE_CURRENT isn't available, this seems to work ) def appdatadirecto...
ebukoz/thrive
erpnext/patches/v7_1/set_student_guardian.py
Python
gpl-3.0
850
0.021176
from __future__ import unicode_literals import frappe def execute(): if frappe.db.exists("DocType", "Guardian"): # 'Schools' module changed to the 'Education' # frappe.reload_doc("schools", "doctype", "student") # frappe.reload_doc("schools", "doctype", "student_guardian") # frappe.reload_doc("schools", "doc...
dent_sibling") if "student" not in frappe.db.get_table_columns("Guardian"): return guardian = frappe.get_all("Guardian", fields=["name", "student"]) for d in guardian: if d.student: student = frappe.get_doc("Student", d.student) if student: student.append("guardians", {"guardian":
d.name}) student.save()
jemofthewest/GalaxyMage
data/core/abilities/slow.py
Python
gpl-2.0
246
0.004065
VERSION = 1 NAME = _("Slow") DESCRIPTION = _("De
creases the speed of a unit.") ABILITY_TYPE = ACTION COST = 5 TARGET_TYPE = HOSTILE RANGE = Diamond(1, 5, 16) AOE = Single()
EFFECTS = [Status(Status.SLOW, power=1.0, hit=0.5, duration=5)]
jddeal/python-cmr
setup.py
Python
mit
455
0.002198
from setuptools import setup setup( name="python-cmr", version="0.4.1", license="MIT", url="https://github.com/jddeal/python-cmr", description="Python wrapper to the NASA Common Metadata Repository (CMR) API.", long
_description=open("README.rst").read(), author="Justin Deal, Matt Isnor", author_email="deal.justin@gmail.com, isnor.matt@gmail.com", packages=["cmr"], install_requires=[
"requests", ] )
taikedz/bash-builder
examples/myip/bin/find_section.py
Python
gpl-3.0
667
0.008996
#!/usr/bin/env python3 import sys import re def isSectionStart(line, interface=""): sectionpattern = "^[0-9]+:\\s+%s" return re.match(sectionpattern%interface, line) != None def printSection(interface, lines): in_section = False for line in lines: if in_section: if isSectionStart...
return print(line, end='') else: if isSectionStart(line, interface):
in_section = True print(line, end='') def main(): interface = sys.argv[1] lines = sys.stdin.readlines() printSection(interface, lines) if __name__ == "__main__": main()
jacksarick/My-Code
Events/CCC/Q2.py
Python
mit
256
0.035156
maze = {} counter = 1 for i in range(input()): u_i = raw_input() u_i = [int(x) for x in u_i.split(" ")][::-1] maze[counter] = u_i[1:] counter += 1 def run_maze(start, path=[]): global maze graph = maze for node in maze[start]: path.append(node
)
dlab-berkeley/collaboratool-archive
bsd2/vagrant-ansible/ansible/lib/ansible/__init__.py
Python
apache-2.0
765
0
# (c) 2012-2013, Michael DeHaan <michael.dehaan@gmail.com> # # 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 Softw
are Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; wi
thout even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. __version__ = '1.3.3' __author__ = 'M...
vguerci/Deluge.app
deluge/plugins/pluginbase.py
Python
gpl-3.0
2,833
0.00353
# # pluginbase.py # # Copyright (C) 2007-2010 Andrew Resch <andrewresch@gmail.com> # # Deluge is free software. # # You may 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 lat...
delete it here. # # import deluge.component as component from deluge.log import LOG as log class PluginBase(component.Component): upd
ate_interval = 1 def __init__(self, name): super(PluginBase, self).__init__(name, self.update_interval) def enable(self): raise NotImplementedError("Need to define an enable method!") def disable(self): raise NotImplementedError("Need to define a disable method...
luca76/QGIS
python/plugins/processing/algs/gdal/gdal2xyz.py
Python
gpl-2.0
2,687
0.000372
# -*- coding: utf-8 -*- """ *************************************************************************** gdal2xyz.py --------------------- Date : September 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com **************...
'gdal2xyz.bat',
GdalUtils.escapeAndJoin(arguments)] else: commands = ['gdal2xyz.py', GdalUtils.escapeAndJoin(arguments)] GdalUtils.runGdal(commands, progress)
saraivaufc/askMathPlus
askmath/views/forum/category/category.py
Python
gpl-2.0
2,975
0.001681
from askmath
.entities import TextMessage from askmath.forms import CategoryForm from askmath.models import Category as CategoryModel from django.contrib import messages from django.shortcuts import render from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.translation import ...
gories = CategoryModel.objects.filter(exists=True) return render(request, "askmath/forum/category/view_categories.html", {'request': request, 'categories': categories}) def view_categories_removed(self, request): categories = CategoryModel.objects.filter(exists=False) ...
Abjad/abjad
tests/test_setting.py
Python
gpl-3.0
1,315
0.00076
import abjad def test_setting_01(): r""" Works with score metronome mark interface. Does not include LilyPond \set command. """ staff = abjad.Staff("c'8 d'8 e'8 f'8") score
= abjad.Sco
re([staff]) abjad.setting(score).tempoWholesPerMinute = "#(ly:make-moment 24 1)" assert abjad.lilypond(score) == abjad.string.normalize( r""" \new Score \with { tempoWholesPerMinute = #(ly:make-moment 24 1) } << \new Staff { ...
botswana-harvard/edc-offstudy
edc_offstudy/view_mixins.py
Python
gpl-2.0
2,362
0.00127
from django.apps import apps as django_apps from django.core.exceptions import ObjectDoesNotExist from django.views.generic.base import ContextMixin class SubjectOffstudyViewMixinError(Exception): pass class SubjectOffstudyViewMixin(ContextMixin): """Adds subject offstudy to the context. Declare with ...
@property def subject_offstudy(self): """Returns a model instance either saved or unsaved. If a save instance does not exits, returns a new unsaved instance. """ model_cls = self.subject_offstudy_model_cls try: subject_offstudy = model_cls.objects.get( ...
dentifier) except AttributeError as e: if 'subject_identifier' in str(e): raise SubjectOffstudyViewMixinError( f'Mixin must be declared together with SubjectIdentifierViewMixin. Got {e}') raise SubjectOffstudyViewMixinError(e) return subject_of...
gnar/pyhack
monster.py
Python
mit
1,815
0.02314
import ui import misc import monster_template class Location(object): def __init__(self, level, x=0, y=0, move_pts=0): self.level = level self.x = x self.y = y self.move_pts = move_pts class Monster(object): def __init__(self, tmpl): if isinstance(tmpl, str): tmpl = monster_template.db[t...
ad: self.hp += hp def injure(self, hp): self.hp -= hp def kill(self): self.set_hp(0) @property def is_dead(self): return self.hp <= 0 @property def is_alive(self): return self.hp > 0 ################################################################################ # Melee atta...
# ################################################################################ def attack(self, target): ui.ifpc(self, "You attack the %s", target.name) if not target.is_pc: target.kill() class PC(Monster): def __init__(self): supe...
theheros/kbengine
kbe/res/scripts/common/Lib/ctypes/test/test_stringptr.py
Python
lgpl-3.0
2,559
0.001172
import unittest from ctypes import * import _ctypes_test lib = CDLL(_ctypes_test.__file__) class StringPtrTestCase(unittest.TestCase): def test__POINTER_c_char(self): class X(Structure): _fields_ = [("str", POINTER(c_char))] x = X() # NULL pointer access ...
har buf = c_buffer(b"abcdef") self.assertEqual(strchr(buf, b"c"), b"cdef") self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") # XXX These calls are dangerous, because the first argument # to strchr is no longer valid after
the function returns! # So we must keep a reference to buf separately strchr.restype = POINTER(c_char) buf = c_buffer(b"abcdef") r = strchr(buf, b"c") x = r[0], r[1], r[2], r[3], r[4] self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000")) del buf ...
eatbyte/Swift
test/unit/proxy/test_sysmeta.py
Python
apache-2.0
15,680
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
verning permissions and # limitations under the License. import unittest import os from tempfile import mkdtemp from urllib import quote import shutil f
rom swift.common.storage_policy import StoragePolicy from swift.common.swob import Request from swift.common.utils import mkdirs, split_path from swift.common.wsgi import monkey_patch_mimetools, WSGIContext from swift.obj import server as object_server from swift.proxy import server as proxy import swift.proxy.controll...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/cookiecutter/find.py
Python
agpl-3.0
1,092
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.find ----------------- Functions for finding Cookiecutter templates and other components. """ import logging import os from .exceptions import NonTemplatedInputDirException def find_template(repo_dir): """ Determines which child directory of `...
:param repo_dir: Local directory of newly cloned repo. :returns project_template: Relative path to project template. """ logging.debug('Searching {0} for the project template.'.format(repo_dir)) repo_dir_contents = os.listdir(repo_dir) project_template = None for item in repo_dir_contents:...
ject_template: project_template = os.path.join(repo_dir, project_template) logging.debug( 'The project template appears to be {0}'.format(project_template) ) return project_template else: raise NonTemplatedInputDirException
Donkyhotay/MoonPy
zope/app/i18n/browser/translate.py
Python
gpl-3.0
4,221
0.003554
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
addMessage(msg_id, msg, language) # Handle edited Messages keys = filter(lambda k: k.startswith('edit-msg_id-'), self.request.keys()) keys = map(lambda k: k[12:], keys) for key in keys: msg_id = self.request['edit-msg_id-'+key] for language ...
est['edit-%s-%s' %(language, key)] if msg != self.context.translate(msg_id, target_language=language): self.context.updateMessage(msg_id, msg, language) return self.request.response.redirect(self.request.URL[-1]) def del...
rwl/PyCIM
CIM15/IEC61968/PaymentMetering/ConsumptionTariffInterval.py
Python
mit
7,711
0.001945
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
his consumption tariff interval. """ return self._Charges def setCharges(self, value): for p in self._Charges: filtered = [
q for q in p.ConsumptionTariffIntervals if q != self] self._Charges._ConsumptionTariffIntervals = filtered for r in value: if self not in r._ConsumptionTariffIntervals: r._ConsumptionTariffIntervals.append(self) self._Charges = value Charges = property(getCha...
ovresko/erpnext
erpnext/demo/user/stock.py
Python
gpl-3.0
4,466
0.027094
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe, random, erpnext from frappe.desk import query_report from erpnext.stock.stock_ledger import NegativeStockError from erpn...
frappe.db.get_global('demo_manufacturing_user')) make_purchase_receipt() make_delivery_note() make_stock_reconciliation() su
bmit_draft_stock_entries() make_sales_return_records() make_purchase_return_records() def make_purchase_receipt(): if random.random() < 0.6: from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt report = "Purchase Order Items To Be Received" po_list =list(set([r[0] for r in qu...
thunderhoser/GewitterGefahr
gewittergefahr/gg_utils/target_val_utils_test.py
Python
mit
20,771
0.000193
"""Unit tests for target_val_utils.py.""" import copy import unittest import numpy import pandas from gewittergefahr.gg_utils import linkage from gewittergefahr.gg_utils import target_val_utils from gewittergefahr.gg_utils import storm_tracking_utils as tracking_utils TOLERANCE = 1e-6 # The following constants are u...
ndas.DataFrame.from_dict(THIS_DICT) END_OF_PERIOD_INDICES = numpy.array([2, 3, 7], dtype=int) # The following constants are used to test _find_dead_storms. MIN_LEAD_TIME_FOR_DEAD_SEC = 3600 THIS_DICT = { tracking_utils.CELL_END_TIME_COLUMN: THESE_END_TIMES_UNIX_SEC, tracking_utils.VALID_TIME_COLUMN: THESE_VA...
constants are used to test target_params_to_name. MIN_LEAD_TIME_SEC = 900 MIN_LINK_DISTANCE_METRES = 1. MAX_LINK_DISTANCE_METRES = 5000. MIN_FUJITA_FOR_OCCURRENCE = 0 MIN_FUJITA_FOR_GENESIS = 2 WIND_SPEED_PERCENTILE_LEVEL = 97.5 WIND_SPEED_CUTOFFS_KT = numpy.array([10, 20, 30, 40, 50], dtype=float) WIND_REGRESSION_N...
ChrisTimperley/EvoAnalyser.py
src/representation/__init__.py
Python
mit
81
0
import storage from representation import
Representation from patch impor
t Patch
wobh/xpython
scrabble-score/scrabble_score_test.py
Python
mit
826
0.001211
import unittest from scrabble import score class WordTest(unittest.TestCase): def test_invalid_word_scores_zero(self): self.assertEqual(0, score('')) self.assertEqual(0, score(' \t\n')) self.assertEqual(0, score('hous3')) self.assertEqual(0, score('wo rd')) def tes
t_scores_very_short_word(self): self.assertEqual(1,
score('a')) def test_scores_other_very_short_word(self): self.assertEqual(4, score('f')) def test_simple_word_scores_the_number_of_letters(self): self.assertEqual(6, score("street")) def test_complicated_word_scores_more(self): self.assertEqual(22, score("quirky")) def test_s...
sean-/patroni
patroni/ha.py
Python
mit
4,394
0.003641
import logging import psycopg2 from patroni.dcs import DCSError logger = logging.getLogger(__name__) class Ha: def __init__(self, state_handler, etcd): self.state_handler = state_handler self.dcs = etcd self.cluster = None self.old_cluster = None def load_cluster_from_dcs(s...
te_handler.start() if not has_lock: return 'started as a secondary' logger.info('started as readonly because i had the session lock') self.load_cluster_from_dcs() if self.cluster.is_unlocked(): if self.state_handler.is_heal...
ock(): if self.state_handler.is_leader() or self.state_handler.role == 'master': return 'acquired session lock as a leader' else: self.state_handler.promote() return 'promoted self to lead...
dcchivian/kb_gblocks
lib/kb_gblocks/kb_gblocksServer.py
Python
mit
23,262
0.000129
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from json...
') # Does it have too many arguments? if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params)
elif isinstance(params, dict): # Do not accept keyword arguments if the jsonrpc version is # not >=1.1. if request['jsonrpc'] < 11: raise KeywordError result = method(ctx, **params) else: # No params resu...
dongguangming/pdfdocument
pdfdocument/document.py
Python
bsd-3-clause
22,270
0.000045
# coding=utf-8 from reportlab.lib import colors from reportlab.lib.enums import TA_RIGHT from reportlab.lib.fonts import addMapping from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import cm, mm from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from repo...
\n', '<br />'), (u'\r', ''), ] for p, q in REPLACE_MAP: text = text.replace(p, q) return text de
f normalize(text): """ Some layers of reportlab, PDF or font handling or whatever cannot handle german umlauts in decomposed form correctly. Normalize everything to NFKC. """ if not isinstance(text, string_type): text = string_type(text) return unicodedata.normalize('NFKC', text) d...
benrbray/matey
matey_pyc/setup.py
Python
mit
453
0.05298
from distutils.core i
mport setup, Extension; # matey extension module matey_module = Extension( "_matey", extra_compile_args=["-Wno-unused-variable"], sources=["src/mateymodule.c", "src/matrix.c"] ); # distribution setup(name="matey", version="0.0", description="Numerical linear algebra for pyrates, aaarrggh!", author="Benjam...
tey", ext_modules=[matey_module], packages=["matey"]);
flavour/eden
modules/unit_tests/s3/s3resource.py
Python
mit
159,086
0.002728
# -*- coding: utf-8 -*- # # S3Resource Unit Tests # # To run this script use: # python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3/s3resource.py # import datetime import json import unittest from lxml import etree from gluon import * from gluon.storage import Storage from s3 import * from s3dal i...
query = resource.get_query() af = S3AxisFilter(query.as_dict(flat=True), tablename) rfield = S3ResourceField(resource, "facility_type_id") values, _ = af.values(rfield) assertTrue("1" in values) assertFalse("2" in values)
assertTrue("3" in values) resource = s3db.resource(tablename) q = (FS("facility_type_id").contains([1, 2, 3])) & \ (~(FS("facility_type_id") != 2)) resource.add_filter(q) query = resource.get_query() af = S3AxisFilter(query.as_dict(flat...
gregvonkuster/icqsol
tests/testPotentialIntegrals.py
Python
mit
3,128
0.007353
#!/usr/bin/env python from icqsol.bem.icqPotentialIntegrals import PotentialIntegrals from icqsol.bem.icqLaplaceMatrices import getFullyQualifiedSharedLibraryName import numpy def testObserverOnA(order): paSrc = numpy.array([0., 0., 0.]) pbSrc = numpy.array([1., 0., 0.]) pcSrc = numpy.array([0., 1., 0.]) ...
1, 1); ptIds.SetId(2, 3) pdata.InsertNext
Cell(vtk.VTK_POLYGON, ptIds) ptIds.SetId(0, 1); ptIds.SetId(1, 2); ptIds.SetId(2, 3) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) addr = int(pdata.GetAddressAsString('vtkPolyData')[5:], 0) gMat = numpy.zeros((2,2), numpy.float64) if PY_MAJOR_VERSION < 3: fullyQualifiedLibName = pkg_resources...
ChristosChristofidis/h2o-3
h2o-py/tests/testdir_munging/pyunit_sub_gsub.py
Python
apache-2.0
893
0.022396
import sys sys.path.insert(1, "../../") import h2o def sub_gsub_check(ip,port): # Connect t
o a pre-existing cluster h2o.init(ip,port) frame = h2o.import_frame(path=h2o.locate("smalldata/iris/iris.csv")) # single column (frame) frame["C5"] = frame["C5"].gsub("s", "z") assert frame[0,4] == "Iriz-zetoza", "Expected 'Iriz-zetoza', b
ut got {0}".format(frame[0,4]) frame["C5"]= frame["C5"].sub("z", "s") assert frame[1,4] == "Iris-zetoza", "Expected 'Iris-zetoza', but got {0}".format(frame[1,4]) # single column (vec) vec = frame["C5"] vec = vec.sub("z", "s") assert vec[2,0] == "Iris-setoza", "Expected 'Iris-setoza', but got...
cjratcliff/variational-dropout
main.py
Python
gpl-3.0
1,649
0.043663
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def main(): dataset ...
far10, cifar100 # Load the data # It will be downloaded first if necessary if dataset == 'mnist': (X_train, y_train), (X_test, y_test) = mnist.load_data() img_size = 28 num_classes = 10 num_channels = 1 elif dataset == 'cifar10': (X_train, y_train), (X_test, y_test) = ci
far10.load_data() img_size = 32 num_classes = 10 num_channels = 3 elif dataset == 'cifar100': (X_train, y_train), (X_test, y_test) = cifar100.load_data() img_size = 32 num_classes = 100 num_channels = 3 lb = LabelBinarizer() lb.fit(y_train) y_train_one_hot = lb.transform(y_train) y_test_one_hot = ...
KITPraktomatTeam/Praktomat
src/checker/migrations/0006_merge.py
Python
gpl-2.0
297
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('checker', '0005_C_
CPP_Infrastructur_2018'), ('checker', '0005_junitchecker'), ] ope
rations = [ ]
cwisecarver/osf.io
api_tests/files/views/test_file_detail.py
Python
apache-2.0
24,117
0.001866
from __future__ import unicode_literals import itsdangerous import mock import pytz from nose.tools import * # flake8: noqa from addons.github.models import GithubFileNode from addons.osfstorage import settings as osfstorage_settings from api.base.settings.defaults import API_BASE from api_tests import utils as api_...
rt_equal(res.status_code, 200) assert_is_not_none(guid) assert_equal(res.json['data']['attributes']['guid'], guid._id) @mock.patch('api.base.throttling.CreateGuidThrottle.allow_request') def test_file_guid_not_created_with_basic_auth(self, mock_allow): res = self.app.get(self.file_url +...
auth=self.user.auth) guid = res.json['data']['attributes'].get('guid', None) assert_equal(res.status_code, 200) assert_equal(mock_allow.call_count, 1) assert guid is None @mock.patch('api.base.throttling.CreateGuidThrottle.allow_request') def test_file_guid_created_with_cookie(...
theZiz/OPKManager
repositories/official.py
Python
gpl-2.0
3,617
0.036218
#!/usr/bin/python #CHANGE ONLY, IF YOU KNOW, WHAT YOU DO! #OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID! import subprocess import argparse import time import calendar import string import sys class RegisterAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): print "Official...
scription_part.split('<')[0]) sys.stdout.write('\n') found_long = 1 if (found_version and found_image and found_long): break print "" def main(): parser = argparse.ArgumentParser(description="Ziz's Repository script") parser.add_argument('--register', nargs=0, action=RegisterAction) parser.ad...
se_args() if __name__ == "__main__": main()
mdmintz/SeleniumBase
seleniumbase/core/browser_launcher.py
Python
mit
45,149
0
import json import logging import os import random import re import sys import time import urllib3 import warnings from selenium import webdriver from selenium.common.exceptions import WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from seleniumbase.config import proxy...
rome_options def _set_chrome_options( browser_name, downloads_path, headless, locale_code, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disa
ble_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio): chrome_options = webdriver.ChromeOpt...
huijuannan/OMOOC2py
_src/om2py6w/xieriji/bin/bottle.py
Python
mit
149,613
0.003563
#!/home/hjnan/OMOOC2py/_src/om2py6w/xieriji/bin/python # -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template ...
encode, quote as urlquote, unquote as urlunquote from Cookie impo
rt SimpleCookie from itertools import imap import cPickle as pickle from StringIO import StringIO as BytesIO from ConfigParser import SafeConfigParser as ConfigParser if py25: msg = "Python 2.5 support may be dropped in future versions of Bottle." warnings.warn(msg, DeprecationWarni...
schleichdi2/OPENNFR-6.1-CORE
bitbake/lib/bb/ui/taskexp.py
Python
gpl-2.0
12,394
0.002501
# # BitBake Graphical GTK based Dependency Explorer # # Copyright (C) 2007 Ross Burton # Copyright (C) 2007 - 2008 Richard Purdie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundatio...
self.pkg_treeview.get_selection().select_path(pkg_path[0]) self.pkg_treeview.scroll_to_cell(pkg_path[0]) def on_cursor_changed(self, selection): (model, it) = selection.get_selected() if it is None: current_package = None else: current_package ...
raph): for task in depgraph["tdepends"]: self.pkg_model.insert(0, (task,)) for depend in depgraph["tdepends"][task]: self.depends_model.insert (0, (TYPE_DEP, task, depend)) class gtkthread(threading.Thread): quit = threading.Event() def __init__(self, shutdown):...
joaopcanario/eventex
eventex/core/tests/test_view_home.py
Python
mit
486
0.002058
from django.test import TestCase class HomeTest(TestCase): def setUp(self): self.response = self.client.get('/') def test_get(self):
"""GET / must return status code 200""" self.assertEqual(200, self.response.status_code) def test_template(self): """Must use index.html""" self.assertTemplateUsed(self.response, 'index.html') def test_subscri
ption_link(self): self.assertContains(self.response, 'href="/inscricao/"')
flavour/porto
models/msg.py
Python
mit
32,132
0.009243
# -*- coding: utf-8 -*- """ Messaging module """ module = "msg" if deployment_settings.has_module(module): def messaging_tables(): """ Load the tables required for Messaging, when-required""" # Message priority msg_priority_opts = { 3:T("High"), 2:T("Medium"),...
#Field("default_country_code", "integer", default=44), *s3_timestamp()) # --------------------------------------------------------------------- tablename = "msg_modem_settings" table = db.define_table(tablename, ...
_baud", "integer", default = 115200), Field("enabled", "boolean", default = True), #Field("preference", "integer", default = 5), To be used later *s3_timestamp()) # --------------------------------------------------...
uranusjr/django
django/db/backends/base/base.py
Python
bsd-3-clause
24,419
0.000573
import copy import time import warnings from collections import deque from contextlib import contextmanager import _thread import pytz from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS from django.db.backends import utils from django.db.bac...
""" Ensure the connection's timezone is set to `self.timezone_name` and return whether it changed or not. """ return False @cached_property def timezone(self): """ Time zone for datetimes stored as naive values in the database. Return a tzinfo ob...
e supports time zones, the adapter handles aware datetimes so Django doesn't need to.) """ if not settings.USE_TZ: return None elif self.features.supports_timezones: return None elif self.settings_dict['TIME_ZONE'] is None: return timezone.utc ...
VioletRed/script.module.urlresolver
lib/urlresolver/plugins/vidto.py
Python
gpl-2.0
3,698
0.008112
""" This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the
GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Special thanks for help with this resolver go out to t0mm0, jas0npc, mash2k3, Mikey1234,voinage and of course Eldorado. Cheers guys :) """ import re from t0mm0.common.net import Net from urlresolver.plugnpl...
thfabian/serialbox2
src/serialbox-python/sdb/sdbcore/stencilfieldmapper.py
Python
bsd-2-clause
12,094
0.004217
#!/usr/bin/python3 # -*- coding: utf-8 -*- ##===----------------------------------------------------
-------------------------*- Python -*-===## ## ## S E R I A L B O X ## ## This file is distributed under terms of BSD license. ## See LICENSE.txt for more information. ## ##===------------------------------------------------------------------------------------------===## from numpy im...
ox import SerialboxError class StencilFieldMapper(StencilDataDataListener): def __init__(self, input_stencil_data, reference_stencil_data, use_async_api=True): self.__use_async_api = use_async_api # References self.__input_stencil_data = input_stencil_data self.__reference_stenci...
Maximilian-Reuter/SickRage
sickbeard/properFinder.py
Python
gpl-3.0
12,920
0.004102
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: https://sickrage.tv # Git: https://github.com/SiCKRAGETV/SickRage.git # # This file is part of SickRage. # # SickRage 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...
ot, see <http://www.gnu.org/licenses/>. import re import time import datetime import operator import threadin
g import traceback import sickbeard from sickbeard import db from sickbeard import helpers, logger from sickbeard.search import snatchEpisode from sickbeard.search import pickBestResult from sickbeard.common import DOWNLOADED, SNATCHED, SNATCHED_PROPER, Quality, cpu_presets from sickrage.helper.exceptions import Auth...
beni55/edx-platform
common/lib/xmodule/xmodule/modulestore/mixed.py
Python
agpl-3.0
40,382
0.003417
""" MixedModuleStore allows for aggregation between multiple modulestores. In this way, courses can be served up both - say - XMLModuleStore or MongoModuleStore """ import logging from contextlib import contextmanager import itertools import functools from contracts import contract, new_contract from opaque_keys im...
ngs['ENGINE'] if is_xml: # restrict xml to only load courses in mapping store_settings['OPTIONS']['course_ids'] = [ course_key.to_deprecated_string() for course_key, store_key in self.mappings.iteritems() if store_ke...
], self.contentstore, store_settings.get('DOC_STORE_CONFIG', {}), store_settings.get('OPTIONS', {}), i18n_service=i18n_service, fs_service=fs_service, user_service=user_service, signal_handler=signal_handler,...
Neil741/ryu-master
ryu/lib/ofctl_v1_2.py
Python
apache-2.0
24,202
0
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
% instruction.metadata) actions.append(buf) else: continue return actions def to_match(dp, attrs): convert = {'in_p
ort': int, 'in_phy_port': int, 'metadata': to_match_metadata, 'dl_dst': to_match_eth, 'dl_src': to_match_eth, 'eth_dst': to_match_eth, 'eth_src': to_match_eth, 'dl_type': int, 'eth_type': int, ...
saeschdivara/GitRepoAnalyser
gireoan/Analyser.py
Python
mit
10,395
0.00481
# Time import time # Regex import re # Git from dulwich.repo import Repo from dulwich.objects import Blob # Gireoan from gireoan.repo import Author from gireoan.repo.File import File from gireoan.report.Export import ChartExporter from gireoan.report.Report import FileEndingReport, AuthorsCommitReport ###########...
s commits" % (author_name, author_commit_count)) print("############################################") def report_commits_per_file(self): print("############################################") for file_path in self.file_paths: repo_file = self.file_paths[file_path] ...
###") def report_top_10_commited_files(self): print("############################################") top_ten = [] for file_path in self.file_paths: top_ten.append(self.file_paths[file_path]) # Sort the files by the number of commits sorted_top_ten = sorted(to...
mo-g/iris
lib/iris/tests/unit/analysis/test_PROPORTION.py
Python
gpl-3.0
2,261
0
# (C) British Crown Copyright 2013 - 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...
Test_units_func(tests.IrisTest): def test(self): self.assertIsNotNone(PROPORTION.units_func) new_units = PROPORTION.units_func(None) self.assertEqual(new_units, 1) class Test_masked(tests.IrisTest): def setUp(self): self.cube = iris.cube.Cube(ma.masked_equal
([1, 2, 3, 4, 5], 3)) self.cube.add_dim_coord(DimCoord([6, 7, 8, 9, 10], long_name='foo'), 0) self.func = lambda x: x >= 3 def test_ma(self): cube = self.cube.collapsed("foo", PROPORTION, function=self.func) self.assertArrayEqual(cube.data, [0.5]) c...
dhermes/gmail-imap-migrate
step1_make_new_labels.py
Python
apache-2.0
895
0.013408
#!/usr/bin/env python # Libraries import imapclient # Local imports import account_settings import utils def get_all_folders(username, password): server = utils.login_to_server(username, password) all_folders = server.list_folders() all_folders = [triple[2] for triple in all_folders] return all_folders, s...
olders_old, server_old = get_all_folders( account_settings.OLD_USERNAME, account_settings.OLD_PASSWORD) # We don't need the old server connection any longer. server_old.logout() all_folders_new, server_new = get_all_folders( account_settings.NEW_USERNAME, account_settings.NEW_PASSWORD)
uncreated_old_folders = set(all_folders_old).difference(all_folders_new) for folder in uncreated_old_folders: server_new.create_folder(folder) print 'Created', folder server_new.logout() if __name__ == '__main__': main()
Courtagen/StarCluster
starcluster/commands/listimages.py
Python
gpl-3.0
1,349
0
# Copyright 2009-2013 Justin Riley # # This file is part of StarCluster. # # StarCluster 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 Foundati
on, either version 3 of the License, or (at your option) any # later version. # # StarCluster is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # de...
.org/licenses/>. from base import CmdBase class CmdListImages(CmdBase): """ listimages [options] List all registered EC2 images (AMIs) """ names = ['listimages', 'li'] def addopts(self, parser): parser.add_option( "-x", "--executable-by-me", dest="executable", ...
elainenaomi/sciwonc-dataflow-examples
dissertation2017/Experiment 1B/instances/8_2_workflow_full_10files_secondary_wmj_1sh_3rs_with_annot_with_proj_3s/taskevent_2/ConfigDB_TaskEvent_2.py
Python
gpl-3.0
561
0.005348
HOST = "wfSciwoncGW:enw1989@172.3
1.25.253:27001,172.31.25.251:27001,172.31.2.76:27001/?authSource=admin" PORT = "" USER = "" PASSWORD = "" DATABASE = "googlew" READ_PREFERENCE = "secondary" WRITE_CONCERN = "majority" COLLECTION_INPUT = "task_events" COLLECTION_OUTPUT = "task_events_info" PREFIX_COLUMN = "g_" ATTRIBUTES = ["event type", "CPU request",...
nts.dat" OUTPUT_FILE = "task_events_info_2.dat"
bmentges/brainiak_api
tests/utils.py
Python
gpl-2.0
754
0.002653
import unittest import urlparse class URLTestCase(unittest.TestCase): def assertQueryStringArgsEqual(self, querystring1, querystring2): # clean-up
'?' if isinstance(querystring1, basestring) and querystring1.startswith('?'): querystring1 = querystring1[1:] if isinstance(querystring2, basestring) and querystring2.startswith('?'): querystring2 = querystring2[1:] if isinstance(querystring1, str) or isinstance(queryst...
= urlparse.parse_qs(querystring1) if isinstance(querystring2, str) or isinstance(querystring2, unicode): querystring2 = urlparse.parse_qs(querystring2) self.assertDictEqual(querystring1, querystring2)
anoidgit/pamath
linux/long_double_math.py
Python
gpl-3.0
811
0.022195
from ctypes import cdll, byref, c_long, c_double lib_pamath = cdll.LoadLibrary("./long_double_math_core.so") lib_pamath.sum_vec.restype = c_longdouble lib_pamath.dot_vec.restype = c_longdouble lib_pamath.cos_vec.restype = c_longdouble def sum_vec(vl)
: ilen = len(vl) Vec = c_longdouble * ilen return lib_pamath.sum_vec(byref(Vec(*vl)), c_long(ilen)) def dot_vec(v1, v2): ilen = len(v1) Vec = c_longdouble * ilen return lib_pamath.dot_vec(byref(Vec(*v1)), byref(Vec(*v2)), c_long(ilen)) def cos_vec(v1, v2): ilen = len(v1) Vec = c_longdouble * ilen return lib_...
os_vec(byref(Vec(*v1)), byref(Vec(*v2)), c_long(ilen)) def mul_vec(v1, v2): ilen = len(v1) Vec = c_longdouble * ilen vrs = Vec() lib_pamath.mul_vec(byref(Vec(*v1)), byref(Vec(*v2)), byref(vrs), c_long(ilen)) return list(vrs)
Vvucinic/Wander
venv_2_7/lib/python2.7/site-packages/pandas/core/reshape.py
Python
artistic-2.0
39,134
0.000358
# pylint: disable=E1101,E1103 # pylint: disable=W0703,W0622,W0613,W0201 from pandas.compat import range, zip from pandas import compat import itertools import numpy as np from pandas.core.series import Series from pandas.core.frame import DataFrame from pandas.core.sparse import SparseDataFrame, SparseSeries from pa...
return
MultiIndex(levels=self.new_index_levels, labels=result_labels, names=self.new
jrialland/python-astar
tests/london/test_london_underground.py
Python
bsd-3-clause
2,878
0.004864
import astar import os imp
ort sys import csv import math from difflib import SequenceMatcher import unittest class Station: def __init__(self, id, name, position): self.id = id self.name = name self.position = position self.links = [] def build_data(): """builds the 'map' by reading the data files""" ...
sv'))) next(r) # jump the first line for record in r: id = int(record[0]) lat = float(record[1]) lon = float(record[2]) name = record[3] stations[id] = Station(id, name, (lat, lon)) r = csv.reader(open(os.path.join(rootdir, 'underground_routes.csv'))) next(r) #...
Gebesa-Dev/Addons-gebesa
sale_order_everywhere/models/mrp_production.py
Python
agpl-3.0
716
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import fields, models class MrpProduction(models.Model): _inherit = 'mrp.production' sale_id = fields.Many2one( 'sale.
order', string='Sale order', copy=False, ) partner_id = fields.Many2one( 'res.partner', string='Customer', copy=False, ) client_order_ref = fields.Char( string='Customer ref', copy=False, ) city_shipping = fields.Char( string='City'...
warehouse', string='Warehouse', )
rbramwell/pulp
playpen/v2_plugins/distributors/harness_distributor/distributor.py
Python
gpl-2.0
4,394
0.002276
# -*- coding: utf-8 -*- # # Copyright © 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or impli...
tten as part of the publish') if write_files: if os.path.exists(publish_dir): shutil.rmtree(publish_dir) os.makedirs(publish_dir) for u in units: file_name = os.path.basename(u.storage_path) publish_file_name = os.path.join(pu...
py(u.storage_path, publish_file_name) # Fake a slow publish if one is requested publish_delay_in_seconds = config.get('publish_delay_in_seconds', None) if publish_delay_in_seconds is not None: _LOG.info('Faking a long publish with delay of [%s] seconds' % publish_delay_in_seconds) ...
dagar/Firmware
Tools/HIL/run_tests.py
Python
bsd-3-clause
3,547
0.003947
#! /usr/bin/python import serial, time import subprocess from subprocess import call, Popen from argparse import ArgumentParser import re def do_test(port, baudrate, test_name): databits = serial.EIGHTBITS stopbits = serial.STOPBITS_ONE parity = serial.PARITY_NONE ser = serial.Serial(port, baudrate, d...
e.time() > timeout_start + timeout: print("Error, timeout") finished = 1 break # run test ser.write('tests ' + test_name + '\n') time.sleep(0.05) finished = 0 timeout = 300 # 5 minutes timeout_start = time.time() timeout_newline = time.time() whil...
if test_name + " PASSED" in serial_line: finished = 1 success = True elif test_name + " FAILED" in serial_line: finished = 1 success = False if time.time() > timeout_start + timeout: print("Error, timeout") print(test_name + "...
zkbt/mosasaurus
scripts/wasp94/wasp94_ut140801.py
Python
mit
1,142
0.012259
from wasp94_base import * # create a night to analyze from mosasaurus.Night import Night n = Night('ut140801', instrument=i) n.createNightlyLog(remake=False) # create an observation from mosasaurus.Observation import Observation o = Observation(t, i, n) o.setupFilePrefixes(
science=['WASP-94'], reference=['WASP-94'], flat=['flat']) # create a reducer to analyze this observation from mosasaurus.Reducer import Reducer r = Reducer(o, visualize=False) r.reduce() from mosasaurus.Cube import Cube c = Cube(o, width=16) c.populate(shift=False, max=None) c.setStars(target='aperture_709_1066', co...
sasaurus.WavelengthRecalibrator import WavelengthRecalibrator wr = WavelengthRecalibrator(c) #c.imageCube(keys=['raw_counts'], stars=[c.target]) #c.imageCube() #c.populate(shift=True, max=None) #c.imageCube(keys=['raw_counts'], stars=[c.target]) #c.imageCube() #c.exportShiftStretch() #c.shiftCube() #c.imageCube(key...
crowning-/dash
qa/rpc-tests/p2p-acceptblock.py
Python
mit
12,477
0.003046
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from...
and white_node respectively. The test: 1. Generate one block on each node, to leave IBD. 2. Mine a new block on each tip, and deliver to each node from node's peer. The tip should advance. 3. Mine a block that forks the previous block, and deliver to each node
from corresponding peer. Node0 should not process this block (just accept the header), because it is unrequested and doesn't have more work than the tip. Node1 should process because this is coming from a whitelisted peer. 4. Send another block that builds on the forking block. Node0 should process thi...
stoic1979/chatzilla
dashboard/utils.py
Python
gpl-3.0
1,054
0.000949
from django.contrib.auth.models import User from django.contrib.sessions.models import Session from django.utils import timezone from django.http import HttpResponse, HttpResponseRedirect from rest_framework.renderers import JSONRenderer class JSONResponse(HttpResponse): """ An HttpResponse that renders its c...
= [] # build a list of user ids from that query for session in sessions: data = session.get_decoded() uid_list.append(dat
a.get('_auth_user_id', None)) # query all logged in users based on id list return User.objects.filter(id__in=uid_list)
ptitjes/quodlibet
quodlibet/ext/events/headphonemon.py
Python
gpl-2.0
5,689
0.000176
# Copyright 2015 Christoph Reiter # 2017 Nick Boultbee # # 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. impo...
onitor(GObject.Object): """Monitors the headphone connection state advertised by pulseaudio. After start() is called will emit a signal in case headphones get connected or disconnected. If pulseaudio isn't active this will w
ork but always return a disconnected status. The changed signal will never be emitted with the same status multiple times. """ __gsignals__ = { 'action': (GObject.SignalFlags.RUN_LAST, None, (object,)), } def __init__(self): super(HeadphoneMonitor, self).__init__() ...
caglar/Arcade-Universe
arcade_universe/tests/patches_matrix.py
Python
bsd-3-clause
858
0.005828
import numpy as np import math def get_patches(mat, patch_size=(4,4)): if mat.ndim == 1: dim = math.sqrt(mat.shape[0]) mat.reshape((dim, dim)) mat_rows = mat.shape[0] mat_cols = mat.shape[1] patches = None for i in xrange(mat_rows / patch_size[0]): for j in xrange(mat_cols...
else: patches = np.vstack(([patches], [patch])) return patches arr = np.array(xrange(32 * 32
)).reshape(32, 32) patches = get_patches(arr) print patches
google-research/falken
service/learner/brains/observation_preprocessor_test.py
Python
apache-2.0
9,414
0.003505
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
0.0, # XZ-angle player to entity1 0.0, # YZ-angle player to entity1 _dist(1.0), # distance player to entity1 0.0, # XZ-angle player to entity2 math.pi/2, # YZ-angle player to entity2 _dist(1.0), # dis...
tity3 0.0, # YZ-angle player to entity3 _dist(2.0) # distance player to entity3 ] # We're rounding aggressively because batch norm adds noise. self.assertSequenceAlmostEqual(preprocessed, want, delta=0.05) @parameterized.parameters(['v1', 'v2']) def test_prepro...
ograycode/ServiceZen
servicezen/settings.py
Python
mit
5,916
0.001183
# Django settings for servicezen project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'dat...
IN_REDIRECT_URL = ( '/' ) LOGOUT_URL = ( '/auth/logout/' ) ROOT_URLCONF = 'servicezen.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'servicezen.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django...
n Windows. # Don't forget to use absolute paths, not relative paths. 'templates' ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the nex...
sean-abbott/auto_build_env
src/abe/create_skeleton.py
Python
mit
3,540
0.003955
__author__ = 'sean-abbott' # RED this whole thing should be swapped out for cookiecutter # https://github.com/audreyr/cookiecutter import os import sys import shutil import inspect from pkg_resources import resource_filename import click from jinja2 import Environment, PackageLoader import utils # YELLOW create_b...
DIR_LIST = [ 'dependencies' ] def _create_skel_dirs(j_ctx_dict): dir_list = [ 'src', 'test', os.path.join('src', os.path.basename(j_ctx_dict['target_dir'])) ] if not os.path.exists(os.path.dirname(j_ctx_dict['target_dir'])): click.echo("Pa...
for d in dir_list: os.mkdir(os.path.join(j_ctx_dict['target_dir'], d)) except OSError as oe: if oe.errno == 2: click.echo('Failed to create directory {}'.format(oe.filename)) sys.exit(1) else: raise # YELLOW use utils def _render_template(env, j_c...
ericl1u/eece7398
sim_and_plot.py
Python
gpl-3.0
7,267
0.007981
''' Copyright (C) 2014 Terry Stewart and Travis DeWolf This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distrib...
# # connect up mouse event if specified if self.mouse_control: self.target = self.shell.controller.gen_target(arm) # get pixel width of fig (-.2 for the padding) self.fig_width = (fig.get_figwidth() - .2
\ * fig.get_figwidth()) * fig.get_dpi() def move_target(event): # get mouse position and scale appropriately to convert to (x,y) if event.xdata is not None: self.target = np.array([event.xdata, event.ydata]) ...
mjuopperi/djoser
djoser/utils.py
Python
mit
4,015
0.000996
from django.conf import settings as django_settings from django.core.mail import EmailMultiAlternatives, EmailMessage from django.template import loader from rest_framework import response, status try: from django.contrib.sites.shortcuts import get_current_site except ImportError: from django.contrib.sites.mod...
from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes return urlsafe_base64_enc
ode(force_bytes(pk)).decode() except ImportError: from django.utils.http import int_to_base36 return int_to_base36(pk) def decode_uid(pk): try: from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_text return force_text(urlsafe_bas...
cshallue/models
research/object_detection/metrics/oid_od_challenge_evaluation_utils.py
Python
apache-2.0
4,148
0.001929
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
f shape [num_boxes] containing detection scores for the boxe
s. standard_fields.DetectionResultFields.detection_classes: integer numpy array of shape [num_boxes] containing 1-indexed detection classes for the boxes. """ return { standard_fields.DetectionResultFields.detection_boxes: data[['YMin', 'XMin', 'YMax', 'XMax']].as_matrix...
kartta-labs/mapwarper
lib/tilestache/TileStache-1.51.5/TileStache/Goodies/__init__.py
Python
mit
34
0.029412
""" Addi
tional extras go
here. """
Mikescher/Project-Euler_Befunge
compiled/Python3/Euler_Problem-024.py
Python
mit
2,977
0.055425
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 import gzip, base64 _g = ("AR+LCAAAAAAABACdUDGOAyEM/AoHW7FBYna5XIKQdQ9B3BUr0VJZKXj8mZAUKXMuzGA8nsHsse3h8/x1uaq3g/RxHNpa8PtcxQ3btQEu/YP8NMA0pWdODzAm0sSU4TLf" + "qw1hRUVItKFGrJ36QD5ThIum/DDZPM4ldiHuaApBkqAaUC1Qfz/6Q3l59bFAFZFs54tluRSpdadvWlUfc8pIojt...
)if(sp()!=0)else(15) def _15(): sa(sp()+1) v0=sp() v1=sp() sa(v0) sa(v1) sa(sr()); return (17)if(sp()!=0)else(16) def _16(): global t0 sp(); sa(sp()-1) sa(sr()); sa(0) v0=sp() t0=gr(sp(),v0) t0=t0-48 sa(120) v0=sp() v1=sp() sa(v0) sa(v1)...
,flush=True) return 1 def _17(): v0=sp() v1=sp() sa(v0) sa(v1) sa(sr()); sa(0) v0=sp() sa(gr(sp(),v0)) sa(sp()-120) return 14 def _18(): v0=sp() v1=sp() sa(v0) sa(v1) sa(sp()-1) v0=sp() v1=sp() sa(v0) sa(v1) return 15 def _19(): gw...
detrout/pykolab
pykolab/xml/utils.py
Python
gpl-3.0
386
0.007772
import datetime import pytz def to_dt(dt): """ Convert a naive date or datetime to a tz-aware datetime. """ if type(dt) == 'datetime.date' or not hasattr(dt, 'hour')
: dt = datetime.datetime(dt.year, dt.month, dt.day, 0, 0, 0,
0) else: if dt.tzinfo == None: return dt.replace(tzinfo=pytz.utc) else: return dt
wathen/PhD
MHD/FEniCS/mesh/test.py
Python
mit
5,783
0.007781
from dolfin import * import ipdb # Print log messages only from the root process in parallel parameters["std_out_all_processes"] = False; # Load mesh from file mesh = Mesh() domain_vertices = [Point(1.0, -1.0), Point(6.0, -1.0), Point(6.0, 1.0), Point(1.0, 1.0)...
3, u1.vector(), b3, "gmres", "default") end() # Plot solution plot(p1, title="Pressure", rescale=True) plot(u1, title="Velocity", scalarbar=True) # Save to file ufile << u1 pfile << p1 # Move to next time step u
0.assign(u1) t += dt print "t =", t # Hold plot interactive()
tddv/readthedocs.org
readthedocs/projects/migrations/0026_project_content_types.py
Python
mit
564
0.001773
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-05-02 06:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0025_
remove_project_content_types'), ] operations = [ migrations.AddField( model_name='proje
ct', name='content_types', field=models.ManyToManyField(blank=True, choices=[('', '---------')], to='projects.ProjectContentType', verbose_name='Content types'), ), ]
spookylukey/django-autocomplete-light
test_project/admin_test_autocomplete/models.py
Python
mit
335
0
from django.db import models class Foo(models.Model): name = models.CharField(max_length=100) bar = models.ForeignKey('Bar', related_name='bar_fk') def __unicode__(self): return self.name class Bar(models.Model): name =
models.CharField(max_length=100) def __unicode__(self): return self
.name
jumpserver/jumpserver
apps/settings/serializers/basic.py
Python
gpl-3.0
2,221
0.004052
import uuid from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AnnouncementSerializer(serializers.Serializer): ID = serializers.CharField(required=False, allow_blank=True, allow_null=True) SUBJECT = serializers.CharField(required=True, max_length=1024, label=...
lizers.CharField(label=_("Content")) LINK = serializers.URLField( required=False, allow_null=True, allow_blank=True, label=_("More url"), default='', ) def to_representation(self, instance): defaults = {'ID': '',
'SUBJECT': '', 'CONTENT': '', 'LINK': '', 'ENABLED': False} data = {**defaults, **instance} return super().to_representation(data) def to_internal_value(self, data): data['ID'] = str(uuid.uuid4()) return super().to_internal_value(data) class BasicSettingSerializer(serializers.Seri...
X-DataInitiative/tick
tick/prox/tests/prox_l2sq_test.py
Python
bsd-3-clause
2,342
0
# License: BSD 3 clause import unittest import numpy as np from numpy.linalg import norm from numpy.testing import assert_almost_equal from tick.prox import ProxL2Sq from tick.prox.tests.prox import TestProx class ProxL2SqTest(object): def test_ProxL2Sq(self): """...Test of ProxL2Sq """ ...
5 * l_l2sq * norm(coeffs[3:8]) ** 2., delta=self.delta) assert_almost_equal( prox.call(coeffs, step=t), out, decimal=self.decimal_places) prox = ProxL2Sq(l_l2sq, (3, 8), positive=True).as
type(self.dtype) out = coeffs.copy() out[3:8] *= 1. / (1. + t * l_l2sq) idx = out[3:8] < 0 out[3:8][idx] = 0 self.assertAlmostEqual( prox.value(coeffs), 0.5 * l_l2sq * norm(coeffs[3:8]) ** 2., delta=self.delta) assert_almost_equal( prox...
bacilla-ru/fias2postgresql
fias.py
Python
gpl-2.0
8,843
0.002746
#!/usr/bin/env python3 # coding=utf-8 """ # fias2postgresql Импорт ФИАС (http://fias.nalog.ru) в PostgreSQL. Необходимы: * *python3.2+* с пакетами [requests](http://docs.python-requests.org/en/latest/), [lxml](http://lxml.de) * *unrar* * [*pgdbf*](https://github.com/kstrauser/pgdbf), обязательно с [патчем](https:...
rom dhouse); create index on house(aoguid); drop table dhouse; alter table houseint add primary key(houseintid); delete from houseint where houseintid in (select houseintid from dhousint); create index on houseint(aoguid); drop table dhousint; create table if no...
rk); create index on landmark(aoguid); drop table dlandmrk; create index tmp_idx_nordoc_normdocid on nordoc(normdocid); create table tmp_nordoc_dup as select distinct * from nordoc where normdocid in ( select normdocid from nordoc group by normdocid having count(no...
codeforsanjose/MobilityMapApi
src/sa_api_v2/cors/tests.py
Python
gpl-3.0
9,375
0.001493
#from django.core.exceptions import PermissionDenied #import mock from django.test import TestCase from django.core.exceptions import PermissionDenied from nose.tools import assert_true, assert_false, assert_raises, assert_is_not_none, assert_equal from sa_api_v2.cors.auth import OriginAuthentication from sa_api_v2.cor...
heck_api_authorization, # get_request) # self.assertEqual(None, # ApiKeyAuthentication(None).authenticate(get_request)) # # Still logged in. # self.assertEqual(get_request.user.is_authenticated(), True) # def test_check_api_auth__key_invalid(self...
m .auth import check_api_authorization, KEY_HEADER # from .auth import ApiKeyAuthentication # from django.core.exceptions import PermissionDenied # key = '12345' # ip = '1.2.3.4' # get_request = mock.Mock(**{'user.is_authenticated.return_value': False, # ...
kobotoolbox/kobocat
onadata/apps/viewer/models/export.py
Python
bsd-2-clause
6,342
0
# coding: utf-8 import os from tempfile import NamedTemporaryFile from django.core.files.storage import get_storage_class from django.db import models from django.db.models.signals import post_delete from django.utils.translation import ugettext as _ from onadata.apps.logger.models import XForm def export_delete_ca...
ull=True, blank=True) # time of last submission when this export
was created time_of_last_submission = models.DateTimeField(null=True, default=None) # status internal_status = models.SmallIntegerField(default=PENDING) export_url = models.URLField(null=True, default=None) class Meta: app_label = "viewer" unique_together = (("xform", "filename"),)...
kevinhikali/ml_kevin
tf/tf_hello.py
Python
gpl-3.0
180
0
# -*- coding: utf-8 -*- """ @author: kevinhikali @email: hming
wei@gmail.com """ import tensorflow as tf hello = tf.constant("Hello") sess = tf.Ses
sion() print(sess.run(hello))
GaZ3ll3/numba
numba/targets/ufunc_db.py
Python
bsd-2-clause
34,872
0.000057
"""This file contains information on how to translate different ufuncs into numba. It is a database of different ufuncs and how each of its loops maps to a function that implements the inner kernel of that ufunc (the inner kernel being the per-element function). Use the function get_ufunc_info to get the information r...
c_db): # some of these imports would cause a problem of circular # imports if done at global scope when importing the numba # module. from . import builtins, npy
funcs, cmathimpl ufunc_db[np.negative] = { '?->?': builtins.bool_invert_impl, 'b->b': builtins.int_negate_impl, 'B->B': builtins.int_negate_impl, 'h->h': builtins.int_negate_impl, 'H->H': builtins.int_negate_impl, 'i->i': builtins.int_negate_impl, 'I->I': bui...