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
pombredanne/openaire
miscutil/lib/validators.py
Python
gpl-2.0
2,759
0.005437
## This file is part of Invenio. ## Copyright (C) 2012 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. ## ## Inv...
if len(val) != 10: return False r = sum([(10 - i) * (_convert_x_to_10(x)) for i, x in enumerate(val)]) return not (r % 11) def is_isbn13(val): """ Test if argument is an ISBN-13 number Courtesy Wikipedia: http://en.wikipedia.org/wiki/International_Standard_Book_Number """ va...
ight for num, weight in zip(val, (1, 3) * 6)]) ck = (10 - total) % 10 return ck == int(val[-1]) def is_isbn(val): """ Test if argument is an ISBN-10 or ISBN-13 number """ return is_isbn10(val) or is_isbn13(val) def is_issn(val): """ Test if argument is an ISSN number """ val = val.replace("-...
ipython/ipywidgets
ipywidgets/embed.py
Python
bsd-3-clause
11,226
0.002138
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. # # # Parts of this code is from IPyVolume (24.05.2017), used here under # this copyright and license with permission from the author # (see https://github.com/jupyter-widgets/ipywidgets/pull/1387) """ Functions for ge...
d.jupyter.widget-view+json"> {view_spec} </script>""" DEFAULT_EMBED_SCRIPT_URL = u'https://unpkg.com/@jupyter-widgets/html-manager@%s/dist/embed.js'%__html_manager_version__ DEFAULT_EMBED_REQUIREJS_URL = u'https:/
/unpkg.com/@jupyter-widgets/html-manager@%s/dist/embed-amd.js'%__html_manager_version__ _doc_snippets = {} _doc_snippets['views_attribute'] = """ views: widget or collection of widgets or None The widgets to include views for. If None, all DOMWidgets are included (not just the displayed ones). """ ...
simpeg/discretize
discretize/utils/code_utils.py
Python
mit
7,861
0.002799
import numpy as np import warnings SCALARTYPES = (complex, float, int, np.number) def is_scalar(f): """Determine if the input argument is a scalar. The function **is_scalar** returns *True* if the input is an integer, float or complex number. The function returns *False* otherwise. Parameters -...
else: tag = " It will be removed in a future version of discretize." def get_dep(self): class_name = type(self).__name__ message = ( f"{class_name}.{old_name} has been
deprecated, please use {class_name}.{new_name}." + tag ) warnings.warn(message, Warning) return getattr(self, new_name) def set_dep(self, other): class_name = type(self).__name__ message = ( f"{class_name}.{old_name} has been deprecated, please use {...
begor/lisp
lisp/environment.py
Python
mit
2,626
0.000381
import functools import operator class Env(dict): """ Computational environment for some expression. Implemented with recursive composition - each environment has the outer environment. Every lookup for a name N in the environment E with outer environment O goes like this: 1) E.lookup(N)...
symbol?, etc) - list processing functions (map, filter, foldl, etc) # TODO """ env = Env() env.update({ '+': lambda *args: sum(args), '*': lambda *args: functools.reduce(operator.mul, args), '-': operator.sub, '/': operator.truediv, '>': operator.gt, '<': ...
erator.lt, '>=': operator.ge, '<=': operator.le, '=': operator.eq, 'abs': abs, 'and': operator.and_, 'or': operator.or_, 'car': lambda alist: alist[0], 'cdr': lambda alist: alist[1:], 'cons': lambda head, tail: [head] + tail, 'list': lambda...
sayak-brm/struixLang
struixLexer.py
Python
apache-2.0
1,868
0.007495
## Copyright 2016 Sayak Brahmachari ## ## 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 la...
eturn word return '' def charsTill(self, end): ''' Returns following characters till given character. ''' s = "" while not self.eos: char = self.get_char() self.eat_length(1) if char == end: return s s += char def ...
arLine(self): ''' Clears the Lexer till the end of the line. ''' self.charsTill('\n')
ifduyue/django
tests/select_for_update/tests.py
Python
bsd-3-clause
17,166
0.00134
import threading import time from unittest import mock from multiple_database.routers import TestRouter from django.core.exceptions import FieldError from django.db import ( DatabaseError, NotSupportedError, connection, connections, router, transaction, ) from django.test import ( TransactionTestCase, ove...
select_for_update, args=(status,),
kwargs={'skip_locked': True}, ) thread.start() time.sleep(1) thread.join() self.end_blocking_transaction() self.assertIsInstance(status[-1], Person.DoesNotExist) @skipIfDBFeature('has_select_for_update_nowait') @skipUnlessDBFeature('has_select_for_update...
vmthunder/nova
nova/api/openstack/compute/contrib/security_groups.py
Python
apache-2.0
28,337
0.000459
# Copyright 2011 OpenStack Foundation # Copyright 2012 Justin Santa Barbara # 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/l...
.api.openstack import xmlutil from nova import compute from nova.compute import api as compute_api from nova import exception from nova.i18n import _ from nova.network.security_group import neutron_driver from nova.network.security_group import openstack_driver from nova.openstack.common import jsonutils from nova.open...
Logger(__name__) authorize = extensions.extension_authorizer('compute', 'security_groups') softauth = extensions.soft_extension_authorizer('compute', 'security_groups') def make_rule(elem): elem.set('id') elem.set('parent_group_id') proto = xmlutil.SubTemplateElement(elem, 'ip_protocol') proto.text =...
pyocd/pyOCD
pyocd/target/builtin/target_MAX32660.py
Python
apache-2.0
4,036
0.012636
# pyOCD debugger # Copyright (c) 2017-2021 Maxim Integrated (Part of Analog Devices) # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.a...
01f041, 0x68516051, 0x68816081, 0xd4fc01c9, 0x1f241d1b, 0x2c041d2d, 0x06e9d301, 0x6811d1ec, 0xd1202980, 0xd31e2c10, 0x60516881, 0xf0216851, 0x60510110, 0x60816851, 0x68196005, 0x68596301, 0x68996341, 0x68d96381, 0x685163c1, 0x0101f041, 0x68516051, 0x68816081, 0xd4fc01c9, 0x3c103310, 0x2c103510, 0x2c04d2e8, ...
0x01c96881, 0x1d1bd4fc, 0x1d2d1f24, 0xd2ee2c04, 0xa119b314, 0x91006809, 0x21006886, 0x68566056, 0x6600f026, 0x68566056, 0x0610f046, 0x68566056, 0x466e6086, 0x7b01f813, 0x1c495477, 0xd1f91e64, 0x99006005, 0x68516301, 0x0101f041, 0x68516051, 0x68816081, 0xd4fc01c9, 0x07806a40, 0xf7ffd503, 0x2001ff09, 0xf7ffb...
Gaia3D/GeepsSpatialStatistic
mainPlugin.py
Python
apache-2.0
10,903
0.004084
# -*- coding: utf-8 -*- """ /*************************************************************************** GeepsSpStats A QGIS plugin Spatial Statistics by PySAL ------------------- begin : 2014-07-01 git sha : $F...
* ***************************************************************************/ """ from PyQt4.QtGui import * from PyQt4.QtCore import * import os.path from Utility import * from Widget_MoransI import Widget_MoransI from Widget_GetisOrdsG import Widget_GetisOrdsG f...
t Widget_SpatialScan class WidgetContainer(object): def __init__(self, iface, classTemplet, dockType=Qt.RightDockWidgetArea): self.__iface = iface self.__dockwidget = None self.__oloWidget = None self.__classTemplet = classTemplet self.__title = classTemplet.title s...
vaginessa/alfred-workflows
src/app-dig/action.py
Python
mit
2,173
0.010584
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, subprocess, urllib, urllib2, hashlib import alfred alfred.setDefaultEncodingUTF8() from app import country_currency def setUsername(): usr = alfred.argv(2) if not usr: alfred.exit('no username found.') alfred.config.set(username = usr.strip...
ot in cmd_map.keys(): alfred.exit() cmd_map[cmd]() if
__name__ == '__main__': main()
sirrice/scorpionsql
scorpionsql/db.py
Python
mit
2,428
0.018534
import sys import pdb import psycopg2 from sqlalchemy import create_engine from sqlalchemy.pool import NullPool from datetime import datetime, date, timedelta from datetime import time as dttime from collections import deque, defaultdict from dateutil.parser import parse as dateparse from scorpionsql.settings import ...
pg_class.oid = pg_attribute.attrelid and attname = '%s' and pg_type.oid = atttypid""" try: row = db.execute(
q % col, table).fetchone() return row[0] except Exception as e: print e return None def db_schema(db, table): """ only works for postgres @return dictionary of column name -> data type """ typedict = [('int', int), ('double', float), ('timestamp', datetime), ('date...
fuckpubg/AHK
botpubg-mpgh/SuperBot.py
Python
apache-2.0
12,651
0.00411
# -*- coding: utf-8 -*- import json import os import time import psutil import pyautogui pubg_url = 'steam://rungameid/578080' PROCNAME = "TslGame.exe" CRASH_PROCNAME = "BroCrashReporter.exe" debug_directory = "debug_screenshots" start_state = "HELLO" play_state = "PLAYING" play_timer_max = 60 * 3 matching_state = ...
connect_button_
position = (config['reconnect_button_position']['x'], config['reconnect_button_position']['y']) # Reading timings refresh_rate = config["timers"]["refresh_rate"] wait_after_killing_a_game = config["timers"]["wait_after_killing_a_game"] start_delay = config["timers"]["start_delay"] animation_delay = config["timers"]["a...
anderscui/nails
nails/filesystem.py
Python
mit
2,608
0
# coding=utf-8 import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' ...
() return [f for f in self.find(pattern) if f.isfile] def create_if_not_exists(self): if not self.exists: os.makedirs(self.abspath) def remove(self): if self.isdir: os.removedirs(self.abspath) else: os.remove(self.abspath) def write(self...
elf, lines, mode='w', encoding='utf-8'): with open(self.abspath, mode=mode, encoding=encoding) as f: f.writelines(lines) def append(self, s): self.write(s, 'a') def appendlines(self, lines): self.writelines(lines, 'a') def readlines(self, mode='r', encoding='utf-8'): ...
yekeqiang/mypython
myftp/mypackage/ftp_module.py
Python
gpl-2.0
4,731
0.004227
import sys from ftplib import FTP ftp = FTP() class FTPClient(): """docstring for FTPClient""" def __init__(self): """ """ pass message_array = [] def log_message(self, message, clear=True): """ Logs the message to the message_array, from where it is retrieved t...
ry): """ Create the new directory in the conne
cted server in the root or in the directory specified via the parameter. :param directory: Directory name to create. """ try: ftp.mkd(directory) self.log_message("Directory {0} created successfully".format(directory)) except Exception as e: print(e) ...
Pratik151/OWASP-ZSC
core/run.py
Python
gpl-3.0
8,425
0.029792
#!/usr/bin/env python ''' OWASP ZSC https://www.owasp.org/index.php/OWASP_ZSC_Tool_Project https://github.com/zscproject/OWASP-ZSC http://api.z3r0d4y.com/ https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ] ''' import sys import os from core.compatible import * from core.alert import * fro...
def __init__(self, options): self.options = sorted(options) def complete(self, text, state): if state == 0: if text: self.matches = [s for s in self.options if s and s.startsw
ith(text)] else: self.matches = self.options[:] try: return self.matches[state] except IndexError: return None def getcommand(commands): backup_commands = commands crawler = 0 command_path = ['zsc'] command = '' while True: try: command = _input('/'.join(command_path), 'any', False) if ...
ActiveState/code
recipes/Python/576784_WSGI_optiparsing__type/recipe-576784.py
Python
mit
2,550
0.028235
""" EXAMPLE USAGE: opts = Opts(environ, opt('q', default=''), opt('pages', default=2), opt('split', default=0), opt('simple', default=0), opt('max_topics', default=40), opt('ncol', default=3), opt('save', default=False), opt('load', default=False), opt('smoothing...
e_builtin(default) else: o.type = str #raise Exception("need type for %s" % name) #if o.type==bool: o.type=int return o def type_clean(val,type): if type==bool: if val in (False,0,'0','f','false','False','no','n'): return False if va
l in (True,1,'1','t','true','True','yes','y'): return True raise Exception("bad bool value %s" % repr(val)) if type==str or type==unicode: # nope no strings, you're gonna get unicode instead! return unicodify(val) return type(val) class Opts(Struct): " modelled on trollop.rubyforge.org and gist.githu...
jobiols/management-system
mgmtsystem_action/__init__.py
Python
agpl-3.0
97
0
# -*- encoding: utf
-8 -*- from . import mgmtsystem_action from . import mgmtsystem_action_stage
gdub/mysql-connector-python
lib/mysql/connector/connection.py
Python
gpl-2.0
62,655
0.000096
# MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most # MySQL Connectors. There are special exceptio...
hake. The MySQL server will then send either an AuthSwitchRequest or an error packet. Raises NotSupportedError when we get the old, insecure password reply back. Raises any error coming from MySQL. """ self._ssl_
active = False if client_flags & ClientFlag.SSL and ssl_options: packet = self._protocol.make_auth_ssl(charset=charset, client_flags=client_flags) self._socket.send(packet) self._socket.switch_to_ssl(**ssl_options) ...
fleksso99/python_training
test/test_add_group.py
Python
apache-2.0
422
0.007109
# -*- coding: utf-8 -*- import pytest from model.group import Group from fixture.application import Application @pytest
.fixture def app(request): fixture = Application() request.addfinalizer(fixture.destroy) return fixture def test_add_group(app): app.session.login(username="admin", password="secret") ap
p.group.create(Group(name="fgfg", header="fgfg", footer="fgfgfgfg")) app.session.logout()
frappe/frappe
frappe/desk/doctype/module_onboarding/test_module_onboarding.py
Python
mit
197
0.010152
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Contributo
rs # License: MIT. See LICENSE # import frappe import unittest class TestModuleOnboarding(unittest.TestCase): p
ass
letsdie10/hostile_takeover
run_game.py
Python
gpl-3.0
6,018
0.024925
import pygame from pygame.sprite import Group from pygame.sprite import GroupSingle import game_functions as gf from settings import Settings from ship import Ship from parachute import Parachute from hostile import Helicopter from hostile import Rocket from hostile import AdvancedHelicopter from game_stats import Ga...
ShipBulletSounds() shiprai
lgun_sounds = ShipRailgunSounds() shipmissile_sounds = ShipMissileSounds() shipexplode_sounds = ShipExplodeSounds() # Sets the volume to 0.1, (range is from 0.0 to 1.0). low_volume = 0.03 mid_volume = 0.3 high_volume = 0.7 shipbullet_sounds.firing.set_volume(mid_volume) shiprailgun_sounds.start.set_volume(low_v...
greenlaw110/FrameworkBenchmarks
frameworks/Python/falcon/app.py
Python
bsd-3-clause
931
0.004296
#!/usr/bin/env python import json import falcon from email.utils import formatdate # resource endpoints class JSONResource(object): def on_get(self, request, response): response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True)) json_data = {
'message': "Hello, world!"} response.body = json.dumps(json_data) class PlaintextResource(object): def on_get(self, request, response): response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True)) response.set_header('Content-Type', 'text/plain') response.bod...
plaintext", PlaintextResource()) # entry point for debugging if __name__ == "__main__": from wsgiref import simple_server httpd = simple_server.make_server('localhost', 8080, app) httpd.serve_forever()
xiangcai/todother
module/uimodules.py
Python
lgpl-3.0
2,454
0.00652
from __future__ import division import math import urlparse import urllib import tornado.web class PersonModule(tornado.web.UIModule): def render(self, entry): return self.render_string("modules/person.html", entry=entry) class TodoModule(tornado.web.UIModule): def render(self, entry, updates=None, ...
ring = urllib.urlencode(query_args, True) return urlparse.urlunsplit((base_url.scheme, base_url.netloc, base_url.path, query_string, base_url.fragment)) class PageMudule(tornado.web.UIModule): """Pagination links display.""" def render(self, page, page_size, results_count): pages = in...
if page <= 1: page = None return update_querystring(self.request.uri, page=page) next = page + 1 if page < pages else None previous = page - 1 if page > 1 else None return self.render_string('modules/page.html', page=page, pages=pages, next=next, ...
alsrgv/tensorflow
tensorflow/examples/saved_model/integration_tests/mnist_util.py
Python
apache-2.0
1,944
0.00463
# Copyright 2019 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...
dint(0, 10, (num,), dtype=np.int64)) for num in num_train_and_test) def load_reshaped_data(use_fashion_mnist=False, fake_tiny_data=False): """Returns MNIST or Fashion MNIST or fake train and test data
.""" load = ((lambda: _load_random_data([10, 50])) if fake_tiny_data else tf.keras.datasets.fashion_mnist.load_data if use_fashion_mnist else tf.keras.datasets.mnist.load_data) (x_train, y_train), (x_test, y_test) = load() return ((_prepare_image(x_train), _prepare_label(y_train)), (...
AliOsm/arabic-text-diacritization
helpers/transliteration.py
Python
mit
2,223
0.013315
# -*- coding: utf-8 -*- import os import io import sys import argparse ARABIC_LETTERS = [ u'ء', u'آ', u'أ', u'ؤ', u'إ', u'ئ', u'ا', u'ب', u'ة', u'ت', u'ث', u'ج', u'ح', u'خ', u'د', u'ذ', u'ر', u'ز', u'س', u'ش', u'ص', u'ض', u'ط', u'ظ', u'ع', u'غ', u'ـ', u'ف', u'ق', u'ك', u'ل', u'م', u'ن', u'ه', u'و', u'...
= { u:v for u, v in zip(domain, range) } with io.open(file_path, 'r', encoding='utf8') as file: lines = file.readlines() new_lines = list() for line in lines: new_line = '' for ch in line.strip(): if ch in d.keys(): new_line += d[ch] else: new_line += ch new_lines.app...
.sep.join(file_path) with io.open(file_path, 'w', encoding='utf8') as file: file.write('\n'.join(new_lines)) print(file_path) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert from/to Buckwalter transliteration') parser.add_argument('-fp', '--file-path', help='File path to ...
agusmakmun/Some-Examples-of-Simple-Python-Script
sms/smsmasking.py
Python
agpl-3.0
959
0.007299
import sys import json import requests URL_API = 'http://smsmasking.ca/api.html' def sendSMS(sender, number, message): message_data = { 'sender' : sender, 'number' : number, 'message': message } response = requests.post(url=URL_API, data=message_data) status_code = response....
[number] [message]" pri
nt "Example:" print " python", __file__, "'yourname' +62857xxxxxxxx 'Sample Message'\n" sys.exit() sendSMS(sys.argv[1], sys.argv[2], sys.argv[3])
lahwran/crow2
crow2/test/plugin_targets/simple_package/__init__.py
Python
mit
46
0
myname = "the_package" crow2_plugin
set = True
anchore/anchore-engine
tests/functional/conftest.py
Python
apache-2.0
696
0
import pytest from tests.functional.services.api.images import (
add_image, delete_image_by_id, get_image_id, wait_for_image_to_analyze, ) from tests.functional.services.utils.http_utils import get_api_conf @pytest.fixture(scope="package") def add_image_with_teardown_package_scope(request): def _add_image_with_teardown(tag, api_conf=get_api_conf): # add i...
add_resp) wait_for_image_to_analyze(image_id, api_conf) # add teardown request.addfinalizer(lambda: delete_image_by_id(image_id, api_conf)) return add_resp return _add_image_with_teardown
mildass/tlsfuzzer
scripts/test-tls13-session-resumption.py
Python
gpl-2.0
10,739
0.000279
# Author: Hubert Kario, (c) 2018 # Released under Gnu GPL v2.0, see LICENSE file for details from __future__ import print_function import traceback import sys import getopt from itertools import chain, islice from tlslite.constants import CipherSuite, AlertLevel, AlertDescription, \ TLS_1_3_DRAFT, GroupName, ...
gotiationInfo()) ext = OrderedDict(ext) ext[ExtensionType.pre_shared_key] = psk_session_ext_gen() mods = [] mods.append(psk_ext_updater()) node = node.add_child(ClientHelloGenerator(ciphers, extensions=ext, modifiers=mods)) ext = {} ext[Extensio...
] = gen_srv_ext_handler_psk() ext[ExtensionType.key_share]
Simplistix/testfixtures
testfixtures/tests/test_django/settings.py
Python
mit
261
0.003831
SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'dja
ngo.contrib.auth', 'django.contrib.contenttypes', "testfixtures.tests.test_django", ] DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}} DEF
AULT_AUTO_FIELD='django.db.models.AutoField'
dmr/Ldtools
tests/test_backends.py
Python
bsd-2-clause
3,268
0.00153
# -*- coding: utf-8 -*- import os from unittest import TestCase from ldtools.backends import get_file_extension, RestBackend, MemoryBackend,\ FileBackend class StandardBackendReturnsRdflibGraphTestMixin(object): """Basis to assure we can use local resources in all other tests. Tests which functions the ba...
filename = "www_w3_org__People__Berners-Lee__card.xml" file_name = os.path.join(os.path.dirname(__file__), filename) self.BACKEND = FileBackend(file_name) # TODO implement file object handling, maybe use # tempfile.NamedTemporaryFile instead of file def tearDown(self): ...
def test_revert_to_old_version(self): pass # TODO class MemoryBackendTestCase(TestCase, StandardBackendReturnsRdflibGraphTestMixin): def setUp(self): filename = "www_w3_org__People__Berners-Lee__card.xml" file_name = os.path.join(os.path.dirname(__file__), filename) with open(file...
impmihai/coala
docs/conf.py
Python
agpl-3.0
9,703
0.005874
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # coala documentation build configuration file, created by # sphinx-quickstart on Sun Nov 6 21:18:18 2016. # # 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 # auto...
= True
# Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'searchbox.html', 'navigation.html', 'relations.html', 'donate.html', ] } # Additional templates that should be rendered to pages, maps page names to # template nam...
eckucukoglu/arm-linux-gnueabihf
arm-linux-gnueabihf/libc/usr/share/system-config-selinux/statusPage.py
Python
gpl-2.0
7,691
0.005071
# statusPage.py - show selinux status ## Copyright (C) 2006-2009 Red Hat, Inc. ## 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 lat...
f self.verify(_("Changing to SELinux disabled requires a reboot. It is not recommended. If
you later decide to turn SELinux back on, the system will be required to relabel. If you just want to see if SELinux is causing a problem on your system, you can go to permissive mode which will only log errors and not enforce SELinux policy. Permissive mode does not require a reboot Do you wish to continue?")) =...
SimoRihani/ProjetLS
FlaskApp/algo.py
Python
mit
4,802
0.010412
# -*- coding: utf-8 -*- """ Created on Sat Apr 22 16:47:12 2017 @author: Jasmin """ from parser import * #from parser import read_data #from parser import read_params #import parser from Methode2 import EvalWeightedSumInteract from Methode2 import * from Methode1 import * from algo3 import * #oui ...
ne[x] res = res + [l] print(data) print('RES ') print(res) return res def algorithme(File) : if (File["Method"] == "1") : return algorithme_1(File) if (File["Method"] == "2") : return algorithme_2(File) if (File["Method"] == "3") : return algor...
Pessimiste(File) def algorithme_2(File) : data_brute = read_data(File) (utilite, poids, mu_i, mu_ij, columns, N, Lambda, norm, nbProfiles, maximiser) = read_params(File) V = v(mu_i, mu_ij, N) I = i(mu_i, mu_ij, N) #test des parametres if (not param_Valide_Algo_2(V, mu_i, mu_ij, I, poi...
rr-/szurubooru
server/szurubooru/migrations/versions/49ab4e1139ef_create_indexes.py
Python
gpl-3.0
3,135
0
""" Create indexes Revision ID: 49ab4e1139ef Created at: 2016-05-09 09:38:28.078936 """ import sqlalchemy as sa from alembic import op revision = "49ab4e1139ef" down_revision = "23abaf4a0a4b" branch_labels = None depends_on = None def upgrade(): for index_name, table_name, column_name in [ ("ix_comment...
score_user_id", "post_score"), ("ix_post_score_post_id", "post_score"), ("ix_post_relation_parent_id", "post_relation"), ("ix_post_relation_c
hild_id", "post_relation"), ("ix_post_note_post_id", "post_note"), ("ix_post_feature_user_id", "post_feature"), ("ix_post_feature_post_id", "post_feature"), ("ix_post_favorite_user_id", "post_favorite"), ("ix_post_favorite_post_id", "post_favorite"), ("ix_post_user_id", "...
scylladb/scylla-cluster-tests
grow_cluster_test.py
Python
agpl-3.0
7,585
0.001582
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hop...
ails. # # Copyright (c) 2016 ScyllaDB import time import datetime import random from sdcm.tester import ClusterTester from sdcm.utils.common import get_data_dir_path from sdcm import nemesis from sdcm import prometheus class GrowClusterTest(ClusterTester): """ Test scylla cluster growth (adding nodes after...
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cluster_starting_size = self.params.get('n_db_nodes') self._cluster_target_size = self.params.get('cluster_target_size') self.metrics_srv = prometheus.nemesis_metrics_obj() def get_stress_cmd_profile(sel...
JulienLeonard/PVG
lib/Render.py
Python
gpl-2.0
3,838
0.022147
from color import * from style import * from geoutils import * from circle import * from polygon import * import time import os def defaultoutputdir(): return "/".join(os.path.dirname(os.path.realpath(__file__).replace("\\","/")).split("/")[:-1]) + "/output" class ImageDim: def __init__(s...
st: shap
es = shape for shape in shapes: self.draw(shape,style) else: if isinstance(shape,Frame): for drawing in shape.drawings(): # puts("shape",shape,"drawing",drawing) self.draw(drawing.shape(),drawing.style()) ...
fingeronthebutton/RIDE
utest/resources/robotdata/imports/outer_lib.py
Python
apache-2.0
58
0
def this_is_the_outer_lib():
print
'For imports test'
AisinoPythonTeam/PythonAiniso
gjqyxyxxcxxt/gjqyxyxxcxxt/spiders/parser/tyc_dispatcher.py
Python
apache-2.0
3,856
0.008524
# -*- coding:utf-8 -*- import re, json, time, codecs, urllib, requests, click from tyc_conf_and_parse import * class TianYanCha(): item = None session = requests.session() session.cookies.set("tnet", "123.114.125.92") referer_url = get_conf('referer_url') public_headers = get_conf('public_headers')...
f json_object['data'] == 'null' or json_objec
t['data'] == None: return [] defined_key, result = eval(info_key+'_parse')(json_object) item[defined_key] = result #print 'info_key: ', info_key #print 'defined_key: ', defined_key #print '--->: ', result def _dispatcher(self, tyc_id): #if isinstance(c...
alxgu/ansible
lib/ansible/plugins/become/pbrun.py
Python
gpl-3.0
3,362
0.001487
# -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ become: pbrun short_description: PowerBroker ru...
i: - section: p
rivilege_escalation key: become_flags - section: pbrun_become_plugin key: flags vars: - name: ansible_become_flags - name: ansible_pbrun_flags env: - name: ANSIBLE_BECOME_FLAGS - name: ANSIBLE_P...
chen0031/rekall
rekall-core/rekall/plugins/tools/json_test.py
Python
gpl-2.0
6,226
0.000803
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Author: Michael Cohen scudette@google.com # # 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 th...
ject is an exact replica of the original - this includes the same address spaces, profile and offset. Having the objects identical allows us to dereference object members seamlessly. """ for task in self.session.plugins.pslist().
filter_processes(): self.encoder.flush() data = self.encoder.Encode(task) logging.debug("%r->%s" % (task, data)) # Make sure the data is JSON serializable. self.assertEqual(data, json.loads(json.dumps(data))) self.decoder.SetLexicon(self.encoder....
humbhenri/pyOthello
othello.py
Python
mit
2,473
0.000809
#!/usr/bin/env python """ othello.py Humberto Henrique Campos Pinheiro Game initialization and main loop """ import pygame import ui import player import board from config import BLACK, WHITE, HUMAN import log logger = log.setup_custom_logger('root') # py2exe workaround # import sys # import os # sys.stdout = open(...
self.gui = ui.Gui() self.board = board.Board() self.gui.show_menu(self.start) def s
tart(self, *args): player1, player2, level = args logger.info('Settings: player 1: %s, player 2: %s, level: %s ', player1, player2, level) if player1 == HUMAN: self.now_playing = player.Human(self.gui, BLACK) else: self.now_playing = player.Computer(BLACK, level +...
lanyuwen/openthread
tools/harness-automation/cases/router_5_7_3.py
Python
bsd-3-clause
1,877
0
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
ort HarnessCase class Router_5_7_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 7 3' golden_devices_required = 4 def on_dialog(self, dialog, title): pass if __name__ == '__main__
': unittest.main()
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/gtk/_gtk/IconTheme.py
Python
gpl-2.0
2,041
0.010779
# encoding: utf-8 # module gtk._gtk # from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so # by generator 1.135 # no doc # imports import atk as __atk import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject class IconTheme(__gobject__gobject.GObject): """ Object Gtk...
ignature unknown pass def get_icon_sizes(self, *args, **kwargs): # real signature unknown pass def get_search_path(self, *args, **kwargs): # real signature unknown pass def has_icon(self, *args, **kwargs): # real signature unknown pass def list_contexts(self, *args, *...
real signature unknown pass def load_icon(self, *args, **kwargs): # real signature unknown pass def lookup_by_gicon(self, *args, **kwargs): # real signature unknown pass def lookup_icon(self, *args, **kwargs): # real signature unknown pass def prepend_search_path(self...
mysociety/yournextmp-popit
candidates/tests/dates.py
Python
agpl-3.0
728
0.004121
from datetime import date, timedelta from django.conf import settings date_in_near_future = date.today() + timedelta(days=14) FOUR_YEARS_IN_DAYS = 1462 election_date_before = lambda r: { 'DATE_T
ODAY': date.today(
) } election_date_on_election_day = lambda r: { 'DATE_TODAY': date_in_near_future } election_date_after = lambda r: { 'DATE_TODAY': date.today() + timedelta(days=28) } processors = settings.TEMPLATE_CONTEXT_PROCESSORS processors_before = processors + \ ("candidates.tests.dates.election_date_before",) proc...
uccgit/the-game
test/graph.py
Python
gpl-2.0
11,828
0.008201
#!/usr/bin/python # # Urwid graphics example program # Copyright (C) 2004-2011 Ian Ward # # This library 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 2.1 of the Licen...
# toggle between two bar types if n & 1: l.append([0,value]) else: l.append([value,0]) self.graph.set_data(l,max_value) # also
update progress if (o//repeat)&1: # show 100% for first half, 0 for second half if o%repeat > repeat//2: prog = 0 else: prog = 1 else: prog = float(o%repeat) / repeat self.animate_progress.set_completion( prog ) ...
Parsl/parsl
parsl/providers/lsf/lsf.py
Python
apache-2.0
10,602
0.003301
import os import time import logging import math from parsl.channels import LocalChannel from parsl.launchers import SingleNodeLauncher from parsl.providers.cluster_provider import ClusterProvider from parsl.providers.lsf.template import template_string from parsl.providers.provider_base import JobState, JobStatus fro...
s provider. Possible la
unchers include :class:`~parsl.launchers.SingleNodeLauncher` (the default), :class:`~parsl.launchers.SrunLauncher`, or :class:`~parsl.launchers.AprunLauncher` move_files : Optional[Bool]: should files be moved? by default, Parsl will try to move files. bsub_redirection: Bool Shou...
lissyx/build-mozharness
configs/b2g/taskcluster-spark-dogfood.py
Python
mpl-2.0
1,365
0.002198
#!/usr/bin/env python import os.path config = { "default_vcs": "tc-vcs", "default_actions": [ 'checkout-sources', 'build', 'build-symbols', 'make-updates', 'prep-upload', 'submit-to-balrog' ], "balrog_credentials_file": "balrog_credentials", "nightly_b...
po_remote_mappings": { 'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp', 'git://codeaurora
.org/': 'https://git.mozilla.org/external/caf', 'https://git.mozilla.org/b2g': 'https://git.mozilla.org/b2g', 'git://github.com/mozilla-b2g/': 'https://git.mozilla.org/b2g', 'git://github.com/mozilla/': 'https://git.mozilla.org/b2g', 'https://git.mozilla.org/releases': 'https://git.mozil...
gyoyo/MaidSafe
tools/vault.py
Python
gpl-3.0
13,159
0.023026
#!/usr/bin/env python # Copyright (c) 2012 maidsafe.net limited # 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, # ...
ing import Process, Pool import multiprocessing import utils import re import psutil import time import datetime import random import shutil import lifestuff_killer processes = {} stop_churn = 'd' def SetupBootstraps(num, user_id): print("Setting up keys ... ") prog = utils.GetProg('vault_key_helper') print pr...
"Started bootstrap with PID " + str(proc.pid)) i = 0 line_limit = 50 t_start = datetime.datetime.now() time_delta = datetime.datetime.now() - t_start timeout = 300000 while i < line_limit and time_delta < datetime.timedelta(seconds=timeout): line = proc.stdout.readline() print line if line.find(...
msuszko/django-vff
setup.py
Python
bsd-2-clause
2,489
0.003616
# Copyright 2011 Terena. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the foll...
SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE US
E OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of Terena. import os from setuptools import setup,...
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Imaging/Core/Testing/Python/WindowLevelInterface.py
Python
gpl-3.0
3,375
0.030815
#!/usr/bin/env python # a simple user interface that manipulates window level. # places in the tcl top window. Looks for object named viewer #only use this interface when not doing regression tests if (info.commands(globals(), locals(), rtExMath) != "rtExMath"): # Take window level parameters from viewer def...
als(),["2.0","*","w"])) .wl.f2.level.configure(-resolution,res,-from,expr.expr(globals(), locals(),["0.0","+","l","-","w"]),-to,expr.expr(globals(), locals(),["0.0","+","l","+","w"])) pass .wl.f1.window.set(w) .wl.f2.level.set(l) frame..ex() button..ex.exit(-text,...
pack..slice(.wl,.ex,-side,top) pack..slice.label(.slice.scale,-side,left) pack..wl.f1(.wl.f2,.wl.video,-side,top) pack..wl.f1.windowLabel(.wl.f1.window,-side,left) pack..wl.f2.levelLabel(.wl.f2.level,-side,left) pack..ex.exit(-side,left) def SetSlice (slice,__vtk__t...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/views/static.py
Python
bsd-3-clause
5,193
0.001926
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ from __future__ import unicode_literals import mimetypes import os import stat import posixpath import re try: from urllib.parse import unquote except ImportError: ...
s") def directory_index(path, fullpath): try: t = loader.select_template(['static/directory_index.html', 'static/directory_index']) except TemplateDoesNotExist: t = Template(DEFAULT_DIRECTO
RY_INDEX_TEMPLATE, name='Default directory index template') files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory' : path + '/', 'file_...
adaptive-learning/matmat-web
matmat/apps.py
Python
mit
313
0
from django.apps import AppConfig as OAppConfig from proso.django.enrichment import register_object_type_enricher class AppConfig(OAppConfig): name = 'matmat' def ready(self): from matmat.prediction im
port enrich_mean_time register_object_type_enricher(['question'], enrich_mean_t
ime)
Aloomaio/googleads-python-lib
examples/ad_manager/v201805/report_service/run_sales_report.py
Python
apache-2.0
2,040
0.008824
#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
d report data. report_downloader.DownloadReportToFile( report_job_id, export_format, report_file) report_file.close() # Display results. print 'Report job with id "%
s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client)
Veil-Framework/Veil
tools/evasion/payloads/powershell/shellcode_inject/psexec_virtual.py
Python
gpl-3.0
9,237
0.004655
""" Powershell method to inject inline shellcode Builds a metasploit .rc resource file to psexec the powershell command easily Original concept from Matthew Graeber: http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html Note: the architecture independent invoker was developed independentl...
oc(IntPtr w, uint x, uint y, uint z); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); [DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); "@\n""" baseString += """Function Get-ProcAddress { ...
[Parameter( Position = 0, Mandatory = $True )] [String] $Module, [Parameter( Position = 1, Mandatory = $True )] [String] $Procedure ) # Get a reference to System.dll in the GAC $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object ...
soerendip42/rdkit
Code/Features/test_list.py
Python
bsd-3-clause
233
0.051502
import sys tests=[ ("testExecs/testFeatures.exe","",{}), ] longTests=[ ] if __name__=='__main__': import sys
from rdkit import TestRunner failed,tests = TestRunner.
RunScript('test_list.py',0,1) sys.exit(len(failed))
luisza/dfva
src/person/models.py
Python
gpl-3.0
8,217
0.001585
# encoding: utf-8 # 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. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY;...
con el cual se autentica") data_hash = models.CharField(max_length=130, help_text="""Suma hash de datos de tamaño máximo 130 caracteres, usando el algoritmo especificado """, null=True) algorithm = models.CharField(max_length=7, choices=ALGORITH...
operatorB = models.IntegerField(default=1) operand = models.CharField(max_length=15, default='*') def __str__(self): return self.person def get_default_expiration(): return timezone.now()+relativedelta(minutes=settings.EXPIRED_DELTA) class TransactionData(models.Model): request_datetime...
Nik0l/UTemPro
Plot.py
Python
mit
76
0.013158
#Scripts
to plot the data, currently only in the context of Q&A communites.
streed/PyEndicia
endicia/test/builders/test_ChangePassPhraseXmlBuilder.py
Python
gpl-3.0
817
0.026928
from nose.tools import assert_raises from endicia.builders.ChangePassPhraseXmlBuilder import ChangePassPhraseXmlBuilder from endicia.builders.EndiciaXmlBuilder import ValueToLongError def test_ChangePassPhraseXmlBuilder_invalid_values(): """ChangePassPhraseXmlBuilder should raise ValueToLongError when each value is p...
value longer than required""" builder = ChangePassPhraseXmlBuilder() assert_raises( ValueToLongError, builder.setPartnerID, "123456789012345678901234567890123456789012345678901" ) assert_raises( ValueToLongError, builder.setRequestID, "123456789012345678901234567890123456789012345678901" ) assert_raises( ValueToL...
r.setAccountID, "1234567" ) assert_raises( ValueToLongError, builder.setPassPhrase, "12345678901234567890123456789012345678901234567890123456789012345" )
terranodo/eventkit-cloud
eventkit_cloud/tasks/tests/test_export_tasks.py
Python
bsd-3-clause
86,451
0.002059
# -*- coding: utf-8 -*- import json import logging import os import pickle import sys import uuid from unittest.mock import Mock, PropertyMock, patch, MagicMock, ANY import celery import yaml from billiard.einfo import ExceptionInfo from django.conf import settings from django.contrib.auth.models import Group, User f...
s.get.return_value = self.group self.user = User.objects.create(username="demo", email="demo@demo.com", password="demo") bbox = Polygon.from_bbox((-10.85, 6.25, -10.62, 6.40)) tags = DatamodelPreset.object
s.get(name="hdm").json_tags self.assertEqual(259, len(tags)) the_geom = GEOSGeometry(bbox, srid=4326) self.job = Job.objects.create( name="TestJob", description="Test description", user=self.user, the_geom=the_geom, json_tags=tags ) self.job.feature_save = True ...
denismakogon/trove-guestagent
trove_guestagent/openstack/common/rpc/serializer.py
Python
apache-2.0
1,600
0
# Copyright 2013 IBM Corp. # # 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...
t, entity): """Deserialize something from primitive form. :param context: Security context :param entity: Primitive to be deserialized :returns: Deserialized form of entity """ pass class NoOpSerializer(Serializer): """A serializer that does nothing.""" def se...
ty): return entity def deserialize_entity(self, context, entity): return entity
ghchinoy/tensorflow
tensorflow/contrib/slim/python/slim/data/data_decoder.py
Python
apache-2.0
2,315
0.00216
# Copyright 2016 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...
rs read data from disk, sstables or other formats, data decoders decode the data (if necessary). A data decoder is provided with a serialized or encoded piece of data as well as a list of items and returns a set of tensors, each of which correspond to the re
quested list of items extracted from the data: def Decode(self, data, items): ... For example, if data is a compressed map, the implementation might be: def Decode(self, data, items): decompressed_map = _Decompress(data) outputs = [] for item in items: outputs.append(decompressed_map[item])...
popoyz/charts
base/chart_b.py
Python
lgpl-3.0
5,726
0.000349
# -*- coding: utf-8 -*- from common.db_sum import _metric_meta_db '''get the data from table by name''' def get_data_by_name(name, status=[1], other=0): result = [] where = '' if status: status = ",".join([str(x) for x in status]) where += ' and status in ({}) '.format(status) if othe...
"""and id in ({})""".format(",".join(map(str, sid)))) if name: where.append("""and name like "%{}%" """.format(name)) if rowCount: stc = (int(current) - 1) * int(rowCount) if not stc: stc = 0 limit = "limit {},{}".format(int(current) - 1, rowCount) content = "*" ...
elds: content = ",".join(fields) sql = """ select {} from t_chart_reports where status=1 {} {} {}; """.format(content, " ".join(where), orders, limit) result = _metric_meta_db.query(sql) if iscount: if result: return result[0]['c'] else: return 0 ...
emmagordon/Axelrod
axelrod/tests/unit/test_oncebitten.py
Python
mit
4,785
0
"""Test for the once bitten strategy.""" import random import axelrod from .test_player import TestPlayer C, D = 'C', 'D' class TestOnceBitten(TestPlayer): name = "Once Bitten" player = axelrod.OnceBitten expected_classifier = { 'memory_depth': 12, 'stochastic': False, 'inspec...
def test_initial_strategy(self): """Starts by cooperating.""" P1 = axelrod.OnceBitten() P2 = axelrod.Player() self.assertEqual(P1.strategy(P2), C) def test_strategy(self): """If opponent defects at any point then the player will defect forever.""" P1
= axelrod.OnceBitten() P2 = axelrod.Player() # Starts by playing C self.assertEqual(P1.strategy(P2), C) self.assertEqual(P1.grudged, False) P2.history.append(C) self.assertEqual(P1.strategy(P2), C) self.assertEqual(P1.grudged, False) P2.history.append(C) ...
alex-ip/agdc
deprecated/vrt2bin.py
Python
bsd-3-clause
4,750
0.009053
#!/usr/bin/env python #=============================================================================== # Copyright (c) 2014 Geoscience Australia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions ar...
edistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither Geoscience Au
stralia nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIM...
honnibal/spaCy
spacy/lang/tr/syntax_iterators.py
Python
mit
1,853
0.001079
from typing import Union, Iterator, Tuple from ...tokens import Doc, Span from ...symbols import NOUN, PROPN, PRON from ...errors import Errors def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. ""...
at = doc.vocab.strings.add("flat") np_label = doc.vocab.strings.add("NP") def extend_right(w): # Playing a trick f
or flat rindex = w.i + 1 for rdep in doc[w.i].rights: # Extend the span to right if there is a flat if rdep.dep == flat and rdep.pos in (NOUN, PROPN): rindex = rdep.i + 1 else: break return rindex prev_end = len(doc) + 1 for i, wo...
sonaht/ansible
lib/ansible/modules/cloud/docker/docker_image.py
Python
gpl-3.0
21,946
0.002688
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any la...
number of seconds. required: false version_added: "2.1" name: description: - "Image name. Name format will be one of: name, repository/name, registry_server:port/name. When pushing or pulling an image the name can optionally include the tag by appending ':tag_name'." required:
true path: description: - Use with state 'present' to build an image. Will be the path to a directory containing the context and Dockerfile for building an image. aliases: - build_path required: false pull: description: - When building an image downloads any updates to the...
Glyfina-Fernando/pymtl
pymtl/tools/integration/tests/verilog_test.py
Python
bsd-3-clause
12,662
0.048728
#======================================================================= # verilog_test.py #======================================================================= from pymtl import * import os import random import pytest def _sim_setup( model, all_verilog, dump_vcd='' ): #model.vcd_file = dump_vcd # TODO: hack f...
andom.randint(0,1) last = i if e
n else last m.in_.value = i m.en .value = en sim.cycle() sim.print_line_trace() assert m.out == last #----------------------------------------------------------------------- # test_auto_Reg #----------------------------------------------------------------------- @pytest.mark.parametrize( "nbits,al...
shadowmint/py-test-watcher
src/base/idb.py
Python
apache-2.0
804
0.002488
# Copyright 2013 D
ouglas Linder # 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 # distrib...
under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from nark import * class IDb(): def connec...
vpv11110000/pyss
examples/carusel/carusel.py
Python
mit
12,857
0.014661
# #!/usr/bin/python # -*- coding: utf-8 -*- """ # carusel.py – Моделирование кассы в случае нестационарного потока покупателей **Постановка проблемы** Время Интенсивность, Количество покупок Относительная частота Суммарная частота чел/10 мин 9:00 - 11:00 2 (...
0.7 # (50-100] 0.2 0.9 # (100..120] 0.1 1.0 # f1 = FuncDiscrete(randomGenerator=random.random, dictValues={.2:lambda:random.r...
.5:lambda:random.randint(5, 20), .7:lambda:random.randint(20, 50), .9:lambda:random.randint(50, 100), 1.0:lambda:random.randint(100, 120)}) # 11:00 - 15:00 5 (0-5] ...
usc-isi-i2/WEDC
spark_dependencies/python_lib/nose2/tests/unit/test_plugin_api.py
Python
apache-2.0
1,161
0
from nose2 import events, session from nose2.tests._common import TestCase class Example(events.Plugin): commandLineSwitch = ('X', 'xxx', 'triple x') def testOutcome(self, event): pass class TestPluginApi(TestCase): def setUp(self): self.session = session.Session() self.plug = ...
ns assert self.plug in self.session.hooks.testOutcome.plugins, \ "short opt did not register plugin" def test_long_opt_registers_plugin(self): args, argv = self.session.argpars
e.parse_known_args(['--xxx']) assert self.plug in self.session.plugins assert self.plug in self.session.hooks.testOutcome.plugins, \ "long opt did not register plugin"
calin-iorgulescu/vmchecker
vmchecker/courselist.py
Python
mit
1,577
0.001268
#!/usr/bin/env python """A module to interact with the course list""" from __future__ import with_statement DEFAULT_CONFIG_FILE_LIST = '/etc/vmchecker/config.list' class CourseList(object): """A class to interact with the course list""" def __init__(self, config_file_list=DEFAULT_CONFIG_FILE_LIST): ...
2: course_list[fields[0].strip()] = fields[1].strip() self.course_list = course_list def course_names(self): """Returns a list with the names of all courses""" return self.course_li
st.keys() def course_configs(self): """Returns a list with the paths of all the config files for all courses""" return self.course_list.values() def course_config(self, course_id): """Returns the config file for the specified course""" return self.course_list[course_id]...
jinserk/PyASR
pyasr/io_func/pickle_io.py
Python
apache-2.0
2,944
0.006114
# Copyright 2013 Yajie Miao Carnegie Mellon University # 2015 Yun Wang Carnegie Mellon University # 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...
lf, shared_xy): pfile_path = self.pfile_path_list[self.cur_pfile_index] if self.feat_mat is None or len(self.pfile_path_li
st) > 1: fopen = smart_open(pfile_path, 'rb') self.feat_mat, self.label_vec = cPickle.load(fopen) fopen.close() shared_x, shared_y = shared_xy self.feat_mat, self.label_vec = \ preprocess_feature_and_label(self.feat_mat, self.label_vec, self.r...
M4rtinK/anaconda
pyanaconda/modules/common/structures/partitioning.py
Python
gpl-2.0
9,579
0.000313
# # DBus structures for the partitioning data. # # Copyright (C) 2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This prog...
Use the version 2. :return: a string with the LUKS version """ return self._luks_version @luks_version.setter def luks_version(self, version: Str): self._luks_version = version @property def pbkdf
(self) -> Str: """The PBKDF algorithm. Set Password-Based Key Derivation Function (PBKDF) algorithm for LUKS keyslot. Example: 'argon2i' :return: a name of the algorithm """ return self._pbkdf @pbkdf.setter def pbkdf(self, pbkdf: Str): self._pb...
CodeMonkeyJan/hyperspy
hyperspy/io_plugins/image.py
Python
gpl-3.0
2,860
0.00035
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
ense for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import os from scipy.mis
c import imread, imsave from hyperspy.misc.rgb_tools import regular_array2rgbx # Plugin characteristics # ---------------------- format_name = 'Signal2D' description = 'Import/Export standard image formats using PIL or freeimage' full_support = False file_extensions = ['png', 'bmp', 'dib', 'gif', 'jpeg', 'jpe', 'jpg'...
UManPychron/pychron
docs/user_guide/operation/scripts/examples/helix/extraction/felix/TrapInBonePipette.py
Python
apache-2.0
291
0.003436
''' ''' def main(): info('trap
in pipette') close(description='Bone to Minibone') close(description='Minibone to Bone') sleep(2) open(description='Bone to Turbo') sleep(15) clos
e(description='Bone to Turbo') sleep(2) open(description='Bone to Minibone')
TheCoSMoCompany/biopredyn
Prototype/python/biopredyn/datagenerator.py
Python
bsd-3-clause
7,444
0.0223
#!/usr/bin/env python # coding=utf-8 ## @package biopredyn ## Copyright: [2012-2019] Cosmo Tech, All Rights Reserved ## License: BSD 3-Clause import libsbml import libsedml from sympy import * import variable, parameter ## Data generation class, used for creating outputs from task results in a ## SED-ML work flow. c...
@param self The object pointer. # @param name New value for self.name. def set_name(self, name): self.name = name
## Returns the higher number of experiments among the data generated by each ## biopredyn.variable.Variable object in self.variables. # @param self The object pointer. # @return An integev. def get_num_experiments(self): num = 0 for v in self.variables: if v.get_num_experiments() > num: ...
dewtx29/python_ann
project/cg/homework/clip.py
Python
gpl-3.0
9,273
0.023186
from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * import sys import random import threading import time name = 'ball_glut' dotList = [] #Up Down Left Right cont_None = 0 cont_Right = 1 cont_Left = 2 cont_Down = 4 cont_Up = 8 g_Width = 800 g_Height = 600 xMin = (g_Width/2) - 50 yMin = (g_H...
tton == GLUT_LEFT_BUTTON: if(state == GLUT_DOWN): oldX = x; oldY = y; print ("click " + str(x) + " ," + str(y)) tmpC = [x,y] dotList.append(tmpC) if button == GLUT_RIGHT_BUTTON: if(state == GLUT_DOW...
x2,y2): mode1 = self.getSideAsBit(x1,y1) mode2 = self.getSideAsBit(x2,y2) if (mode1 == 0 and mode2 == 0): return True else: return False def isDiffSide(self,x1,y1 , x2,y2): mode1 = self.getSideAsBit(x1,y1) mode2 = self.getSideAsBit(x2,y2) ...
pantheon-systems/cassandra-dns
cassandranames-test.py
Python
mit
3,496
0.001716
import unittest import cassandranames from dnstypeconstants import * # Running this *will destroy* data in Cassandra. class TestCassandraName
s(unittest.TestCase): def setUp(self): cassandranames.install_schema(drop_first=True, rf=1) self.names = cassandranames.CassandraNames() def test_names(self): # Verify behavior on an initial, empty set. data = self.names.lookup("pantheon.example.com") self.assertEqual(d...
{}) # Add an "A" record. self.names.insert("pantheon.example.com", A, "192.168.0.1") # Verify that the "A" records appears in lookups. data = self.names.lookup("pantheon.example.com") self.assertEqual(data, {A: {"192.168.0.1": {"ttl": 900}}}) data = self.names.lookup("p...
infobliss/sibutest2
libraries/utils.py
Python
gpl-3.0
5,431
0.005708
''' generic library functions ''' import re # urllib works different in python 2 and 3 try catch to get the correct one try: import urllib.request as urllib2 except ImportError: import urllib2 import urllib.request import pywikibot import json from unidecode import unidecode def load_from_url(url): """ ...
infobox: license_text = '' else: license_
text = license_template.format(wikilicense=wikilicense) return pagetemplate.format( infobox=infobox, wikilicense=license_text, categories=parsed_categories) def upload_file(file_location, description, filename, username, glam_name): ''' Given a description, file_location and filename this function...
quiltdata/quilt-compiler
api/python/tests/test_session.py
Python
apache-2.0
4,576
0.000874
""" Tests for login and logout. """ import datetime from unittest.mock import patch import responses import quilt3 from .utils import QuiltTestCase class TestSession(QuiltTestCase): @patch('quilt3.session.open_url') @patch('quilt3.session.input', return_value='123456') @patch('quilt3.session.login_wit...
cess-token', expires_at=123456789, ) with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() == 'https://example.com' mocked_load_auth.assert_called_once() with patch('quilt3.session._loa...
_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() is None mocked_load_auth.assert_called_once()
sagiss/sardana
src/sardana/tango/pool/ZeroDExpChannel.py
Python
lgpl-3.0
9,005
0.005664
#!/usr/bin/env python ############################################################################## ## ## This file is part of Sardana ## ## http://www.sardana-controls.org/ ## ## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## ## Sardana is free software: you can redistribute it and/or modify ## it und...
attr = self.get_device_attr().get_attr_by_name(name) if name == "state": event_value = self.calculate_tango_st
ate(event_value) elif name == "status": event_value = self.calculate_tango_status(event_value) else: if isinstance(event_value, SardanaAttribute): if event_value.error: error = Except.to_dev_failed(*event_value.exc_info) timesta...
phansen01/RATChromaServer
testing/ChromaPoller.py
Python
mit
7,389
0.019082
import os, sys, time import zmq #import chroma.api as api #api.use_cuda() import numpy as np #from chroma.sim import Simulation #from chroma.event import Photons #import chroma.event #from uboone import uboone import ratchromadata_pb2 import photonHit_pb2 import cProfile import message_pack_cpp context = zmq.Context(...
#instead of appending to array every loop, the full size (nsphotons x 3) is al
located to begin, then #values are filled properly by incrementing stepPhotons. for j in xrange(stepPhotons, (stepPhotons+sData.nphotons)): pos[j,0] = np.random.uniform(sData.step_start_x,sData.step_end_x) pos[j,1] = np.random.uniform(sData.step_start_y,sData.step_end_y) ...
google-research/language
language/mentionmemory/encoders/mauto_encoder.py
Python
apache-2.0
8,445
0.00296
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
ed({ 'token_ids': embedding.Embed(
num_embeddings=self.vocab_size, embedding_dim=self.hidden_size, dtype=self.dtype, embedding_init=self.kernel_init, ), 'position_ids': embedding.Embed( num_embeddings=self.max_positions, embeddin...
Hakuba/youtube-dl
youtube_dl/extractor/bilibili.py
Python
unlicense
3,778
0.00163
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_str from ..utils import ( int_or_none, unescapeHTML, ExtractorError, xpath_text, ) class BiliBiliIE(InfoExtractor): _VALID_URL = r'http://www\.bilibili\.(?:tv|com)/vide...
d('./url').text, 'filesize': int_or_none(size), 'ext': 'flv', }] backup_urls = durl.find('./backup_url') if backup_urls is not None: for backup_url i
n backup_urls.findall('./url'): formats.append({'url': backup_url.text}) formats.reverse() entries.append({ 'id': '%s_part%s' % (cid, xpath_text(durl, './order')), 'title': title, 'duration': int_or_none(xpath_text(durl, './len...
open-synergy/opnsynid-partner-contact
partner_go_public/models/res_partner.py
Python
agpl-3.0
293
0
# -*- coding: utf-8 -*- # Copyright 201
8 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields class ResPartner(models.Model): _inherit = "res.partner" go_public = fields.Boolean(
string="Go Public", )
giorgiop/scipy
scipy/spatial/tests/test_kdtree.py
Python
bsd-3-clause
24,475
0.014055
# Copyright Anne M. Archibald 2008 # Released under the scipy license from __future__ import division, print_function, absolute_import from numpy.testing import (assert_equal, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_, run_module_suite) import numpy as np from scipy.spatial impo...
elf): s = 23 kk = self.kdtree.n+s d, i = self.kdtree.query(np.zeros((2,4,3)),k=kk) assert_equal(np.shape(d),(2,4,kk)) assert_equal(np.shape(i),(2,4,kk)) assert_(np.all(~np.isfinite(d[:,:,-s:]))) assert_(np.all(i[:,:,-s:] == self.kdtree.n)) def test_single_que...
ll_neighbors(self): d, i = self.kdtree.query([0,0,0],k=None,distance_upper_bound=1.1) assert_(isinstance(d,list)) assert_(isinstance(i,list)) def test_vectorized_query_all_neighbors(self): d, i = self.kdtree.query(np.zeros((2,4,3)),k=None,distance_upper_bound=1.1) assert_equ...
googleapis/python-appengine-admin
google/cloud/appengine_admin_v1/services/instances/transports/grpc.py
Python
apache-2.0
16,909
0.001656
# -*- 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...
to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and ...
JasonLG1979/gnome-shell-extensions-mediaplayer
meson_post_install.py
Python
gpl-2.0
499
0
#!/usr/bin/env python3 from os import environ, path from subprocess import call HOME = path.join(path.exp
anduser('~'), '.local/') PREFIX = environ.get('MESON_INSTALL_PREFIX', HOME) DATA_DIR = path.join(PREFIX, 'share') DEST_DIR = environ.get('DESTDIR', '') EXTENSION_DIR = path.join(DATA_DIR, "gnom
e-shell/extensions/mediaplayer@patapon.info") if not DEST_DIR: print("Installing new Schemas") call(['glib-compile-schemas', path.join(EXTENSION_DIR, 'schemas/')])
exv1p3r/PyScripts
pyNet/SWgetconf.py
Python
gpl-3.0
922
0.002169
#!/usr/bin/env python2 import getpass import telnetlib # Credentials needed to the telnet connection user = raw_input("Enter your telnet account: ") password = getpass.getpass() #Open the file which has the IP address of the devices f = open('switches.txt') # Put the IP addrs to loop the conn for line in f: prin...
HOST = line.strip() # Connection using the telnetlib tn = telnetlib.Telnet(HOST) tn.read_until("Username: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") # Cisco configuration # "terminal length 0" command show us the whole co...
saveoutput.write(readoutput) saveoutput.close()
veltri/DLV2
tests/parser/depgraph.1.test.py
Python
apache-2.0
239
0
input = """ % run with option -- depgraph % component of b must be HCF a(1) | -a(1). b(X) | b(X) :- a(X). """ output = """ % run with option -
- depgraph % component of b must
be HCF a(1) | -a(1). b(X) | b(X) :- a(X). """
ostree/plaso
plaso/parsers/sqlite_plugins/mac_document_versions.py
Python
apache-2.0
3,528
0.006803
# -*- coding: utf-8 -*- """Parser for the Mac OS X Document Versions files.""" from plaso.events import time_events from plaso.lib import eventdata from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface __author__ = 'Joaquin Moreno Garijo (Joaquin.MorenoGarijo.2013@live.rhul.ac.uk)' cl...
e(user_sid) class MacDocumentVersionsPlugin(interface.SQLitePlugin): """Parse the Mac OS X Document Versions SQLite database..""" NAME = u'mac_document_versions' DESCRIPTION = u'Parser for document revisions SQLite database files.' # Define the
needed queries. # name: name from the original file. # path: path from the original file (include the file) # last_time: last time when the file was replicated. # version_path: path where the version is stored. # version_time: the timestamp when the version was created. QUERIES = [ ((u'SELECT f.file_n...
diana-hep/rootconverter
root2avro/tests/arrayLong.py
Python
apache-2.0
1,247
0.003208
#!/usr/bin/env python # Copyright 2016 Jim Pivarski # # 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 la...
"type": {"type": "array", "items": "long"}}]} json = [{"x": [0, 1, 2]}, {"x": [-10, 11, 12]}, {"x": [-100, -101, 102]}, {"x": [20, -21, -22]}, {"x"
: [200, -201, 202]}]
ic-hep/DIRAC
src/DIRAC/FrameworkSystem/Client/MonitoringClient.py
Python
gpl-3.0
21,692
0.002213
""" Exposes singleton object gMonitor, which is instance of MonitoringClient class Uses RPC Framework/Monitoring service. Calls registerActivities exposed function """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __RCSID__ = "$Id" import time import...
of operations OP_MEAN = "mean" OP_ACUM = "acum" OP_SUM = "sum" OP_RATE = "rate" # Predefined components that can be registered COMPONENT_SERVICE = "service" COMPONENT_AGENT = "agent" COMPONENT_WEB = "web" COMPONENT_SCRIPT = "script" COMPONENT_TORNADO = "tornado" __vali
dMonitoringValues = six.integer_types + (float,) def __init__(self): self.sourceId = 0 self.sourceDict = {} self.sourceDict["componentType"] = "unknown" self.sourceDict["componentName"] = "unknown" self.sourceDict["componentLocation"] = "unknown" self.activitiesDefin...
ghchinoy/tensorflow
tensorflow/python/keras/optimizer_v2/optimizer_v2_test.py
Python
apache-2.0
31,883
0.009629
# 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...
, self.evaluate(var1)) sgd.learning_rate = learning_rate_schedule.InverseTimeDecay( 0.5, decay_steps=1.0, decay_rate=0.5) if context.executing_eagerly(): sgd.minimize(loss, [var0, var1]) else: self.evaluate(opt_op) @test_util.run_in_graph_and_eager_modes def testPrecomp...
with self.cached_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) loss = lambda: 5 * var0 + 3 * var1 # pylint: disable=cell-var-from-loop grad_loss = constant_op.constant([42, -42], dtype=dtype) sgd = gradient_desc...
v0idwalker/mgr-sources
crawl/crawl/spiders/independent.py
Python
gpl-3.0
714
0.005602
# -*- coding: utf-8 -*- import scrapy from crawl.items import theIndependentItem class IndependentSpider(scrapy.Spider): name = "www.independent.co.uk" baseURL = "https://www.independent.co.uk" allowed_domains = ["https://www.
independent.co.uk"] start_urls = ['https://www.independent.co.uk/'] def parse(self, response): link_data = response.xpath('//div[@class="content"]/h1/a') for l in link_data: data = theIndependentItem() data['url'] = self.baseURL.join(l.xpath('@href').extract()) ...
# data['tag'] = '' # data['date'] = '' # data[''] yield data
petrilli/pkpserver
tests/test_pin_validation_error.py
Python
bsd-3-clause
1,018
0.000982
# -*- coding: utf-8 -*- import unittest from flask import Flask from flask.ext.testing import TestCase from pkpserver import app as application class BaseTest(TestCase): def create_app(self): app = Flask(__name__)
app.config['TESTING'] = True application.configure_api(app) return app class TestPinValidationError(BaseTest): def test_server_is_running(self): self.assert405(self.client.get('/')) def tes
t_server_denies_get(self): self.assert405(self.client.get('/')) def test_server_allows_post(self): self.assert200(self.client.post('/')) def test_server_accepts_json(self): result = self.client.post('/', data={ "date-time": "2014-04-06T13:00:50Z", "hostname": "w...
jamesmintram/blenderplugins
jm_skel_export.py
Python
mit
6,496
0.008467
import bpy import math import mathutils from bpy_extras.io_utils import axis_conversion bl_info = { "name": "Export JM's Skeleton", "description": "", "author": "James Mintram", "version": (0, 1), "blender": (2, 75, 0), "category": "Export", } reserved_properties = ( 'cycles_visibility...
tText(text, *args) file.write(bytes(str(formatted_text), "UTF-8")) def skeleton_write(file, skeleton): Write(file, '<skeleton bone_count="{}" name="{}">\n', skeleton['count'], skeleton['name']) for bone in skeleton['bones']: Write(file, ' <bone {} {} {} parent="{}" na...
c'], 'loc_'), FormatMat4(bone['mat'], 'mat_'), bone['parent'], bone['name']) Write(file, '</skeleton>\n') # ExportHelper is a helper class, defines filename and # invoke() function which calls the file selector. from bpy_extras.io_utils import ExportHelper from ...
bdacode/hoster
hoster/turbobit_net.py
Python
gpl-3.0
5,022
0.003783
# -*- coding: utf-8 -*- """Copyright (C) 2013 COLDWELL AG 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 dist...
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/>. """ import re import time import urlparse import bs4 from ... im
port hoster, input from ...plugintools import between @hoster.host class this: model = hoster.HttpPremiumHoster name = 'turbobit.net' favicon_url = 'http://turbobit.net/favicon/fd1.ico' patterns = [ hoster.Matcher('https?', '*.turbobit.net', '!/<id>.html'), hoster.Matcher('https?', '*.t...
diana2199-cmis/diana2199-cmis-cs2
simpleprogram.py
Python
cc0-1.0
784
0.021684
import math #this simple program calculates your lucky number using you birthmonth and birthdate #this function does the calculation def calculation(birthmonth, birthdate): return (birthmonth*5-5+birthdate)/6+2 def output(name,birthmonth, birthdate,result): return """Hi {}, Your birthmonth is {}, your birthdate...
esult) #this main function organizes functions above and calls them in correct order def main(): name = raw_input("Hello :) What's your n
ame? ") birthmonth = raw_input("Type your birthmonth (in number) ") birthdate = raw_input("Type your birthdate (in number) ") result = calculation(int(birthmonth),int(birthdate)) print output(name, birthmonth, birthdate, result) main()