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
zmap/zannotate
asnames/__main__.py
Python
apache-2.0
3,472
0.006048
import json import urllib2 import re class CIDRReportASNameDump(object): """ASNNameDump represents the full list of registered AS Numbers on CIDR report. Acts as an iterator that will provide tuples: (AS Number, AS Name)""" CIDR_REPORT_URL = "http://www.cidr-report.org/as2.0/autnums.html" ENTRY_RE...
untry present. id_org = description country = None # this format is terrible, but we'll try to parse it out anyway. if " - " in id_org and id_org.split(" - ", 1)[0].isupper(): name, org = id_org.split(" - ", 1) #...
ame, org = id_org.split(" ", 1) elif "-" in id_org and id_org.split("-", 1)[0].isupper(): name, org = id_org.split("-", 1) else: name, org = id_org, None if name: name = unicode(name, errors="ignore").encode("utf...
ShakoHo/fxos-certsuite
mcts/webapi_tests/moztime/test_time.py
Python
mpl-2.0
2,856
0.006653
from datetime import datetime import time from mcts.webapi_tests.semiauto import TestCase class TestTime(TestCase): """ This is a test for the `MozTime API`_ which will: - Get the current date/time and ask the test user to verify - Set the current date/time to a user-specified value, and ask the tes...
#get the new date and time from user and pass to script to set str_date = self.prompt("Please enter a date to be changed in"\ " format dd/mm/yyyy") if str_date is None: self.fail("Must enter a date") str_time = self.prompt("Plea
se enter a time to be changed in" \ " format HH:MM") if str_time is None: self.fail("Must enter a time") date_struct = datetime.strptime(str_date, '%d/%m/%Y') date_format = date_struct.strftime('%B %d, %Y') date_n_time = date_...
jomorais/pyfase
examples/pingpong/pong.py
Python
gpl-3.0
655
0.003053
#!/usr/bin/python __author__ = 'joaci' try: import ti
me from pyfase import MicroService except Exception as e: print('require module exception: %s' % e) exit(0) class Pong(MicroService): def __init__(self): super(Pong, self).__init__(self, sender_endpoint='ipc:///tmp/sender', receiver_endpoint='ipc:///tmp/receiver') def on_connect(self): ...
est a pong ###' % service) time.sleep(2) self.request_action('ping', {}) Pong().execute()
dodobas/osm-export-tool2
jobs/models.py
Python
bsd-3-clause
9,975
0.002506
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import uuid from django.contrib.auth.models import Group, User from django.contrib.gis.db import models from django.contrib.gis.geos import GEOSGeometry from django.contrib.postgres.fields import ArrayField from django.db.models.fields imp...
'Translation'), (TRANSFORM, 'Transform') ) id = models.AutoField(primary_key=True, editable=False) uid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) name = models.Ch
arField(max_length=255, default='', db_index=True) user = models.ForeignKey(User, related_name='user') config_type = models.CharField(max_length=11, choices=CONFIG_TYPES, default=PRESET) filename = models.CharField(max_length=255) upload = models.FileField(max_length=255, upload_to=get_upload_path) ...
VinnieJohns/ggrc-core
src/ggrc_basic_permissions/migrations/versions/20160603120209_c9218e757bc_rename_admin_role_from_ggrc_admin_to_.py
Python
apache-2.0
1,169
0.001711
# Copyright (C) 2017 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Rename admin role from gGRC Admin to Administrator. Create Date: 2016-06-03 12:02:09.438599 """ from alembic import op import sqlalchemy as sa from sqlalch...
rivileges')) def downgrade(): op.execute(roles_table.update()
.where(roles_table.c.name == 'Administrator') .values(name='gGRC Admin', description='gGRC System Administrator with super-user ' 'privileges'))
mfcovington/django-lab-members
lab_members/migrations/0012_scientist_email.py
Python
bsd-3-clause
523
0.001912
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('lab_members', '0011_auto_20141130_2335'),
] operations = [ migrations.AddField( model_name='scientist', name='email', field=models.EmailField(help_text='Please enter email address', max_length=75, null=True, verbose_name='
email address'), preserve_default=True, ), ]
mrculler/movieface
face_types.py
Python
gpl-3.0
4,296
0.003957
# Defines some types import collections Movie = collections.namedtuple("Movie", ["movie_id", "collection_id", "is_renamed", "filename"]) Collection = collections.namedtuple("Collection", ["collection_id", "display_name", "extension", "path", "drop_path"]) # Full definitions are below (generated by specifying "verb...
self)) # # __dict__ = property(_asdict) # # def _replace(_self, **kwds): # 'Return
a new Collection object replacing specified fields with new values' # result = _self._make(map(kwds.pop, ('collection_id', 'display_name', 'extension', 'path', 'drop_path'), _self)) # if kwds: # raise ValueError('Got unexpected field names: %r' % kwds.keys()) # return result # # def _...
virtualeconomycoin/vec
share/qt/clean_mac_info_plist.py
Python
mit
917
0.016358
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the Virtualeconomycoin-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir =...
ycoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr
[1].replace("\n", ""); fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
gifford-lab/bcbio-nextgen
bcbio/variation/population.py
Python
mit
12,759
0.003762
"""Provide infrastructure to allow exploration of variations within populations. Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite database of variations for query and evaluation. """ import collections import csv from distutils.version import LooseVersion import os import subprocess import ...
ni_vcf) gemini_db = create_gemini_db(gemini_vcf, data, gemini_db, ped_file) return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None, "vcf": multisample_vcf if is_batch else None}]] def
create_gemini_db(gemini_vcf, data, gemini_db=None, ped_file=None): if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not utils.file_exists(gemini_db): if not vcfutils.vcf_has_variants(gemini_vcf): return None with file_transaction(data, gemini_db) ...
TheImagingSource/tiscamera
tools/tcam-capture/tcam_capture/TcamView.py
Python
apache-2.0
21,385
0.001777
# Copyright 2017 The Imaging Source Europe GmbH # # 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 ...
self.imagesaver = MediaSaver(self.serial, self.caps, MediaType.image) self.imagesaver.saved.connect(self.image_saved_callback)
self.imagesaver.error.connect(self.image_error_callback) self.image_fng.set_settings(self.settings.image_name) fn = self.image_fng.create_file_name("image") self.imagesaver.current_filename = fn self.imagesaver.save_image(get_encoder_dict()[image_type]) def image_saved_callback(se...
jos4uke/getSeqFlankBlatHit
lib/python2.7/site-packages/Cython/Compiler/Nodes.py
Python
gpl-2.0
349,102
0.002819
# # Parse tree nodes # from __future__ import absolute_import import cython cython.declare(sys=object, os=object, copy=object, Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object, py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=obje...
und in signature annotation") arg_type = annotation.analyse_as_type(env) if arg_type is not None:
if explicit_pytype and not explicit_ctype and not arg_type.is_pyobject: warning(annotation.pos, "Python type declaration in signature annotation does not refer to a Python type") base_type = CAnalysedBaseTypeNode( annotation.pos, type=arg_type, is_arg=True) e...
usc-isi/nova
nova/api/ec2/cloud.py
Python
apache-2.0
69,515
0.000561
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
n 'CloudController' def _get_image_state(self, image): # NOTE(vish): fallback status if image_state isn't set state = image.get('status') if state == 'active': state = 'available' return image['properties'].get('image_state', state) def describe_availability_zones(s...
min): return self._describe_availability_zones_verbose(context, **kwargs) else: return self._describe_availability_zones(context, **kwargs) def _get_zones(self, context): """Return available and unavailable zones."...
tongjixianing/projects
pylib/cqlshlib/formatting.py
Python
apache-2.0
12,345
0.002754
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
port EMPTY from cassandra.util import datetime_from_timestamp from util import UTC is_win = platform.system() == 'Windows' unicode_controlchars_re = re.compile(r'[\x00-\x31\x7f-\xa0]') controlchars_re = re.compile(r
'[\x00-\x31\x7f-\xff]') def _show_control_chars(match): txt = repr(match.group(0)) if txt.startswith('u'): txt = txt[2:-1] else: txt = txt[1:-1] return txt bits_to_turn_red_re = re.compile(r'\\([^uUx]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|U[0-9a-fA-F]{8})') def _make_turn_bits_red_f(color...
diogo149/CauseEffectPairsChallenge
code/param.py
Python
gpl-3.0
2,724
0.001101
from __future__ import print_function # THIS IS A TEST import cPickle as pickle # import pickle class Param(object): """ Class that allows you to store values when training and retrieve values when testing as either a function result, or a value. """ class ParamStore(object): def __init__(s...
self.values = {} def __exit__(self, type, value, traceback): Param.instance = None with open(self.
filename, 'w') as outfile: pickle.dump(self.values, outfile) def __getitem__(self, key): return self.values[key] def __setitem__(self, key, value): self.values[key] = value instance = None trainMode = False @staticmethod def v(identifier, value...
VirusTotal/content
Packs/Orca/Integrations/Orca/Orca_test.py
Python
mit
26,935
0.001596
from datetime import datetime import pytest import json from Orca import OrcaClient, BaseClient, DEMISTO_OCCURRED_FORMAT, fetch_incidents DUMMY_ORCA_API_DNS_NAME = "https://dummy.io/api" mock_alerts_response = { "version": "0.1.0", "status": "success", "total_items": 58, "total_ungrouped_items": 58, ...
a", "account_action_id_ctx": {
"data": "11111111-1111-1111-1111-8a529a011111" }, "scan_id_ctx": { "data": "11111111-1111-1111-1111-8a529a011111_111111111111_bucket-111111e11111-us-east-1" }, "first_seen": "2020-11-08T13:03:37+00:00" }, ...
vmalloc/weber-cli
weber/cli/generate.py
Python
bsd-3-clause
427
0.004684
import click from .. import templates @click.group() def generate(): pass @gene
rate.command() @click.argument('name') @click.option('--path', required=True) @click.pass_context def blueprint(ctx, name, path): app = ctx.obj templates.extract_template( 'snippets/blueprint.py', app.get_blueprint_directory().join(name +
'.py'), ctx={ 'blueprint': {'name': name, 'path': path}})
nabin-info/hackerrank.com
validate-list-of-email-address-with-filter.py
Python
mit
747
0.032129
#!/usr/bin/python import sys imp
ort re re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$') def valid_email(s): return not (re_valid_email.search(s) == None) N = int(raw_input().strip()) A = [] for i in range(N): A += [ str(raw_input().strip()) ] A.sort() V = filter(valid_email, A) print V #### INPUT ## ## 3 ##...
@hackerrank.com ## #### OUTPUT ## ## ['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara@hackerrank.com'] #### INPUT ## ## 5 ## dheeraj-234@gmail.com ## itsallcrap ## harsh_1234@rediff.in ## kunal_shin@iop.az ## matt23@@india.in ## #### OUTPUT ## ## ['dheeraj-234@gmail.com', 'harsh_1234@rediff.in', 'kunal_s...
radoondas/elasticbeat
vendor/github.com/elastic/beats/packetbeat/tests/system/test_0061_nfs.py
Python
apache-2.0
1,469
0
from packetbeat import BaseTest """ Tests for the NFS """ class Test(BaseTest): def test_V3(self): """ Should correctly parse NFS v3 packet """ self.render_config_template( nfs_ports=[20
49], ) self.run_packetbeat(pcap="nfs_v3.pcap") objs = self.read_output() assert len(objs) == 1 o = objs[0] assert o["type"] == "nfs" assert o["rpc.auth_flavor"] == "unix" assert "rpc.time" in o assert "rpc.time_str" in o assert "rpc.call_...
t_v4(self): """ Should correctly parse NFSv4.1 packet """ self.render_config_template( nfs_ports=[2049], ) self.run_packetbeat(pcap="nfs_v4.pcap") objs = self.read_output() assert len(objs) == 1 o = objs[0] assert o["type"] ==...
yasoob/PythonRSSReader
venv/lib/python2.7/dist-packages/sessioninstaller/backends/synaptic.py
Python
mit
3,567
0.002803
#!/usr/bin/env python # -*- coding: utf-8 -*- """Make use of synaptic as backend.""" # Copyright (C) 2008-2010 Sebastian Heinlein <devel@glatzor.de> # Copyright (C) 2005-2007 Canonical # # Licensed under the GNU General Public License Version 2 # # This program is free software; you can redistribute it and/or modify # ...
e>, " \ "Michael Vogt <mvo@canonical.com" import tempfile from gettext import gettext as _ from gi.repository import GObject from defer import Deferred import sessioninstaller.errors class SynapticBackend(obje
ct): """Make use of Synaptic to install and remove packages.""" def _run_synaptic(self, xid, opt, tempf, interaction): deferred = Deferred() if tempf: opt.extend(["--set-selections-file", "%s" % tempf.name]) #FIXME: Take interaction into account opt.extend(["-o", "S...
mjumbewu/django-model-filters
model_filters/templatetags/model_nodes.py
Python
bsd-3-clause
4,549
0.005716
from django.db.models.manager import Manager from django.template import Context, Node, Variab
le from django.template.loader import get_template class BaseModelBlockNode (Node): def __init__(self, thing, resolved=True): """ thing -- The thing (probably a model instance or a list of model instances) to be rendered as a block. resolved -- If True, then ``thing`` is a...
will contain the value of the thing. """ self.thing = thing self.resolved = resolved def get_template_variable(self, thing, type_of_thing): """ Return the name of the template variable that should be used to render the thing. If the variable name does not r...
YourCyborg/Sun-RPI
src/comms/models.py
Python
bsd-3-clause
32,624
0.00564
""" Models for the comsystem. The Commsystem is intended to be used by Players (thematic IC communication is probably best handled by custom commands instead). The comm system could take the form of channels, but can also be adopted for storing tells or in-game mail. The comsystem's main component is the Message (Msg...
ine Django meta options"
verbose_name = "Message" # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that ...
plotly/python-api
packages/python/plotly/plotly/graph_objs/surface/contours/_x.py
Python
mit
17,141
0.000992
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class X(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "surface.contours" _path_str = "surface.contours.x" _valid_props = { "color", "end...
ghlightcolor(self, val): self["highlightcolor"] = val # highlightwidth # -
------------- @property def highlightwidth(self): """ Sets the width of the highlighted contour lines. The 'highlightwidth' property is a number and may be specified as: - An int or float in the interval [1, 16] Returns ------- int|float ""...
neutrons/FastGR
addie/processing/mantid/master_table/import_from_database/conflicts_solver.py
Python
mit
6,804
0.003086
from __future__ import (absolute_import, division, print_function) from collections import defaultdict import numpy as np from qtpy.QtWidgets import QMainWindow, QTableWidget, QRadioButton, QTableWidgetItem from addie.utilities import load_ui from addie.utilities.list_runs_parser import ListRunsParser #from addie.u...
hich row to use to fix conflict _row = _get_checked_row(table_ui=table_ui) this_json['any_conflict'] = False # chemical_formula, geometry, etc. chemical_formula = str(table_ui.item(_row, 1).text()) geometry = str(table_ui.item(_row, 2).text())
mass_density = str(table_ui.item(_row, 3).text()) sample_env_device = str(table_ui.item(_row, 4).text()) this_json['resolved_conflict'] = {'chemical_formula': chemical_formula, 'geometry': geometry, 'mass_densi...
wzyy2/PiBox
PiBox/sh/datapoint_tools/num.py
Python
gpl-2.0
3,324
0.011131
#/bin/env python # -*-coding:utf8-*- ''' # Any issues or improvements please contact jacob-chen@iotwrt.com ''' import urllib import json if __name__ == '__main__': choose = int(raw_input('1.write 2.read 3.edit 4.remove 5.history')) domain = raw_input('domain(as 192.168.10.106:8000) : ') sensor_i...
nput('key(as 2012-12-12T11:11:11) : ') params = urllib.urlencode({'key': key}) f = urllib.urlopen("http://" + domain + "/API/sensor/" + sensor_id + "/datapoint/get/?%s" % params) get = f.read() print 'ret body:', get s = json.loads(get) print 'key:',s['key'],'value:',s['v...
key = raw_input('key(as 2012-12-12T11:11:11) : ') value = float(raw_input('value(float) : ')) params = urllib.urlencode({'key': key, 'value' : value}) f = urllib.urlopen("http://" + domain + "/API/sensor/" + sensor_id + "/datapoint/edit/?%s" % params) get = f.read() print ...
berkmancenter/mediacloud
apps/topics-base/tests/python/topics_base/media/test_normalize_url.py
Python
agpl-3.0
481
0
# n
oinspection PyProtectedMember from topics_base.media import _normalize_url, MAX_URL_LENGTH def test_normalize_url(): """Test normalize_url().""" assert _normalize_url('http://www.foo.com/') == 'http://foo.com/' assert _normalize_url('http://foo.com') == 'http://foo.com/' assert _normalize_url('http://...
TH
davidam/python-examples
basics/cadena.py
Python
gpl-3.0
1,315
0
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
ater ve
rsion. # This file 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 # al...
frankosan/pypers
pypers/steps/samtools/bamcheck.py
Python
gpl-3.0
1,886
0.011135
from pypers.core.step import CmdLineStep class BamCheck(CmdLineStep): spec = { "version": "0.1.19", "descr": [ "Run the samtools bamcheck utility against a bam file,", "generating a text stats file suitable for plot-bamcheck.", "If a target file is provided, also...
"descr" : "a list of b
am files to be checked", } ], "outputs": [ { "name" : "output_files", "type" : "file", "value" : "{{input_files}}.bamcheck.txt", "descr" : "text file with qc on bam file", ...
guorendong/iridium-browser-ubuntu
tools/perf/profile_creators/large_profile_extender.py
Python
bsd-3-clause
713
0.004208
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from profile_creators import cookie_profile_extender from profile_creators import history_profile_extender from profile_creators import profile_extender cla...
ileExtender(profile_extender.Pr
ofileExtender): """This class creates a large profile by performing a large number of url navigations.""" def Run(self): extender = history_profile_extender.HistoryProfileExtender( self.finder_options) extender.Run() extender = cookie_profile_extender.CookieProfileExtender( self.finde...
mgadi/naemonbox
sources/psdash/gevent-1.0.1/greentest/test__threading_patched_local.py
Python
gpl-2.0
510
0.003922
from gevent import monkey; monkey.patch_all() import threading localdata = threading.lo
cal() localdata.x = "hello" assert localdata.x == 'hello' success = [] def func(): try: localdata.x raise AssertionError('localdata.x must raise AttributeError') except AttributeError: pass assert localdata.__dict__ ==
{}, localdata.__dict__ success.append(1) t = threading.Thread(None, func) t.start() t.join() assert success == [1], 'test failed' assert localdata.x == 'hello'
bundlewrap/bundlewrap
bundlewrap/items/symlinks.py
Python
gpl-3.0
6,528
0.001225
from collections import defaultdict from os.path import dirname, normpath from shlex import quote from bundlewrap.exceptions import BundleError from bundlewrap.items import Item from bundlewrap.utils.remote import PathInfo from bundlewrap.utils.text import mark_for_translation as _ from bundlewrap.utils.text import is...
and item.name
== self.attributes['owner']: if item.attributes['delete']: raise BundleError(_( "{item1} (from bundle '{bundle1}') depends on item " "{item2} (from bundle '{bundle2}') which is set to be deleted" ).format( ...
jldbc/pybaseball
pybaseball/split_stats.py
Python
mit
8,655
0.003582
import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from typing import Dict, Optional, Tuple, Union import bs4 as bs import pandas as pd import re def download_url(url: str) -> bytes: """ Gets the content from the url specified """ session =...
.index.drop(0)) level_data = level_data.set_index(['Player ID', 'Split Type', 'Split']) level_data = level_data.drop(index=['Split
'], level=2) level_data = level_data.apply( pd.to_numeric, errors='coerce').convert_dtypes() level_data = level_data.dropna(axis=1
sammdot/circa
client.py
Python
bsd-3-clause
11,289
0.029498
import logging import pathlib import socket import sys import threading from channel import Channel, ChannelList, User from server import Server from util.nick import nickeq, nicklower from util.msg import Message class Client: def __init__(self, server, nick, username, realname, **conf): self.sock = None self...
) try: self.sock.connect((self.conf["server"], self.conf["port"])) self.server = Server(self.conf["server"], self.conf["port"]) logging.info("Connected to %s", self.server.host) self.send("NICK", self.conf["nick"]) if "password" in self.conf: self.send("PASS", self.conf["password"]) self.send(...
"], 8, "*", \ self.conf["realname"]) threading.Thread(name="listen", target=self.listen).start() except socket.error as e: logging.error("Cannot connect to %s: %s", self.conf["server"], e) self.sock.close() self.sock = None def send(self, *msg): """Send a raw message to the server.""" if not s...
MOOOWOOO/qblog
qblog.py
Python
gpl-3.0
633
0
# coding: utf-8 from app imp
ort db, app from app.auth.models import Role from app.user.models import User from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Server, Shell, Manager __author__ = 'Jux.Liu' manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, U...
reloader=True) manager.add_command("runserver", server) if __name__ == "__main__": manager.run()
subeax/grab
grab/spider/__init__.py
Python
mit
90
0
from grab.spider.base import Spider,
Task, Data, NullTask fro
m grab.spider.error import *
plotly/python-api
packages/python/plotly/plotly/validators/scattercarpet/marker/colorbar/_tickformat.py
Python
mit
516
0
import _plotly_utils.basevalidators class TickformatValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="tickformat", parent_name="scattercarpet.marker.colorbar", **kwargs ): super(TickformatValidator, self).__init__( plo...
, "style"),
**kwargs )
rgmining/tripadvisor
setup.py
Python
gpl-3.0
3,543
0.000847
# # setup.py # # Copyright (c) 2017 Junpei Kawamoto # # This file is part of rgmining-tripadvisor-dataset. # # rgmining-tripadvisor-dataset 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...
data_files: if not isinstance(f, tuple): continue for i, u in enumerate(f[1]): base = path.basename(u) f[1][i] = path.join(sys.prefix, f[0], base) if not path.exists(f[1][i]): f[1][i] = path.join(sys.prefix, "loc...
(f[1][i]): f[1][i] = path.join(site.getuserbase(), f[0], base) if not path.exists(f[1][i]): f[1][i] = urllib.urlretrieve(u, base)[0] return distutils.command.install_data.install_data.run(self) def load_requires_from_file(filepath): """Read a package...
stephane-martin/salt-debian-packaging
salt-2016.3.3/salt/runners/asam.py
Python
apache-2.0
11,014
0.001725
# -*- coding: utf-8 -*- ''' Novell ASAM Runner ================== .. versionadded:: Beryllium Runner to interact with Novell ASAM Fan-Out Driver :codeauthor: Nitin Madhok <nmadhok@clemson.edu> To use this runner, set up the Novell Fan-Out Driver URL, username and password in the master configuration at ``/etc/salt/...
__name__) def __virtual__(): ''' Check for ASAM Fan-Out driver configuration in master config file or directory and load runner only if it is specified ''' if not HAS_LIBS or not HAS_SIX: return False if _get_asam_configuration() is False: return False return True def _g...
_config = __opts__['asam'] if 'asam' in __opts__ else None if asam_config: try: for asam_server, service_config in six.iteritems(asam_config): username = service_config.get('username', None) password = service_config.get('password', None) protocol...
hydroshare/hydroshare_temp
ga_ows/views/wfs.py
Python
bsd-3-clause
31,334
0.007149
""" An implementation of OGC WFS 2.0.0 over the top of Django. This module requires that OGR be installed and that you use either the PostGIS or Spatialite backends to GeoDjango for the layers you are retrieving. The module provides a generic view, :py:class:WFS that provides standard WFS requests and responses and :p...
artindex','1')) request['max_feat
ures'] = int(request.get('maxfeatures', '1')) request['output_format'] = request.get('outputformat',"application/gml+xml; version=3.2") class AdHocQueryParameters(RequestForm): type_names = MultipleValueField() aliases = MultipleValueField(required=False) filter = f.CharField(required=False) fi...
stackforge/kolla
kolla/tests/test_methods.py
Python
apache-2.0
5,853
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
'base_package_type': 'rpm', } result = methods.handle_repos(template_vars, ['grafana', 'ceph'], 'disable') expectCmd = 'RUN dnf config-manager --disable grafana ' expectCmd += '
--disable centos-ceph-nautilus || true' self.assertEqual(expectCmd, result) # NOTE(hrw): there is no disabling of repos for Debian/Ubuntu def test_disable_repos_debian(self): template_vars = { 'base_arch': 'x86_64', 'base_distro': 'debian', 'base_package_type...
mrunge/horizon_lib
horizon_lib/utils/validators.py
Python
apache-2.0
1,727
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
nse for the specific language governing permissions and limitations # under the License. from django.core.exceptions import ValidationError # noqa from django.utils.translation import ugettext_lazy as _ from horizon_lib import conf def validate_port_range(port): if port not in range(-1, 65536): rais...
ip_proto): if ip_proto not in range(-1, 256): raise ValidationError(_("Not a valid IP protocol number")) def password_validator(): return conf.HORIZON_CONFIG["password_validator"]["regex"] def password_validator_msg(): return conf.HORIZON_CONFIG["password_validator"]["help_text"] def validate_...
ophiry/dvc
tests/test_repro.py
Python
apache-2.0
5,073
0.002957
import os from dvc.command.remove import CmdRemove from dvc.command.repro import CmdRepro from dvc.command.run import CmdRun from dvc.executor import Executor from tests.test_cmd_run import RunBasicTest class ReproBasicEnv(RunBasicTest): def setUp(self): super(ReproBasicEnv, self).setUp() self.f...
11.py' self.create_file_and_commit(self.file11_code_file, 'import sys' + os.linesep + 'print(open(sys.argv[1]).readline().strip())') self.settings.parse_args(['run', '--stdout', self.file_name11, '--...
on', self.file11_code_file, self.file_name1]) CmdRun(self.settings).run() self.file_name2 = os.path.join('data', 'file2') self.file2_code_file = 'file2.py' self.create_file_and_commit(self.file2_code_file, 'print("Bobby")') self.settings.parse...
amosnier/python_for_kids
book_code/appendixb/ch16-checkerboard.py
Python
gpl-3.0
1,319
0.00834
from tkinter import * import random import time class Game: def __init__(self): self.tk = Tk() self.tk.title("Game") self.tk.resizable(0, 0) self.tk.wm_attributes("-topmost", 1) self.canvas = Canvas(self.tk, width=500, height=500, bd=0, highlightthickness=0)...
PhotoImage(file="background.gif") w = self.bg.width() h = self.bg.height() draw_background = 0 for x in range(0, 5): for y in range(0, 5): if draw_background == 1: self.canvas.create_image(x *
w, y * h, image=self.bg, anchor='nw') draw_background = 0 else: draw_background = 1 self.sprites = [] self.running = True def add(self, sprite): self.sprites.append(sprite) def mainloop(self): ...
zhlinh/leetcode
0091.Decode Ways/solution.py
Python
apache-2.0
1,111
0.0018
#!/usr/bin/env pyth
on # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-02 Last_modify: 2016-03-02 ****************************************** ''' ''' A message containing letters from A-Z is being encoded to num...
determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2. ''' class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ if not s...
getting-things-gnome/liblarch
tests/signals_testing.py
Python
lgpl-3.0
5,708
0
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Liblarch - a library to handle directed acyclic graphs # Copyright (c) 2011-2012 - Lionel Dricot & Izidor Matušov # # This program is free software: you can redistribute it and/or modify it under # the terms of the...
ct): ''' A class to test callbacks ''' def __init__(self, unittest, generator, signal_name, should_be_caught=True, how_many_signals=1, error_code="No error code set"): self.signal_catched_event = threading.Event() self.generator = generator self...
ould_be_caught self.error_code = error_code def _on_failure(): # we need to release the waiting thread self.signal_catched_event.set() self.missed = True # then we notify the error # if the error_code is set to None, we're expecting it to fail...
dmnfarrell/peat
PEATDB/Ekin/Ekin_map.py
Python
mit
23,383
0.016893
#!/usr/bin/env python # # Protein Engineering Analysis Tool DataBase (PEATDB) # Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen # # 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 ver...
selectioncommand=self.update_elements) self.group_type_box.grid(row=row,column=0,columnspan=1,sticky='news') self.group_type_box.configure(listbox_bg='white') self.group_type_box.configure(listbox_selectmode='single') self.group_type_box.configure(listbox_exportselection=0) ...
nesl/mercury
Services/Mapping/tmpBatch.py
Python
gpl-2.0
1,450
0.035862
import os import sys filenames = [ 'Albuquerque_6x6.tfix', 'Atlanta_6x6.tfix', 'Austin_6x6.tfix', 'Baltimore_6x6.tfix', 'B
oston_6x6.tfix', 'Charlotte_6x6.tfix', 'Chicago_6x6.tfix', 'Cleveland_6x6.tfix', 'Columbus_6x6.tfix', 'Dallas_6x6.tfix', 'Denver_6x6.tfix', 'Detroit_6x6.tfix', 'El_Paso_6x6.tfix', 'Fort_Worth_6x6.tfix', 'Fresno_6x6.tfix', 'Houston_6x6.tfix', 'Indianapolis_6x6.tfix', 'Jacksonville_6x6.tfix', 'Kansas_City_2_6x6.tfix', 'K...
fix', 'Los_Angeles_6x6.tfix', 'Memphis_6x6.tfix', 'Mesa_6x6.tfix', 'Milwaukee_6x6.tfix', 'Nashville_6x6.tfix', 'New_Orleans_6x6.tfix', 'New_York_6x6.tfix', 'Oklahoma_City_6x6.tfix', 'Omaha_6x6.tfix', 'Philadelphia_6x6.tfix', 'Phoneix_6x6.tfix', 'Portland_6x6.tfix', 'Sacramento_6x6.tfix', 'San_Antonio_6x6.tfix', 'San_Di...
studywolf/NDMPS-paper
code/test_ndmps_fs_discrete_spa_frontend.py
Python
gpl-3.0
1,619
0.004941
import numpy as np import importlib import itertools import nengo from models import ndmps_fs_discrete_spa_frontend importlib.reload(ndmps_fs_discrete_spa_frontend) from models.ndmps_fs_discrete_spa_frontend import generate input_signals = ['ZERO']#, 'ONE', 'TWO', 'THREE', 'FOUR', # 'FIVE', 'SIX', '...
priate file name input_signal =
input_signal.lower().replace(' ', '') np.savez_compressed('results/data/discrete_fs/time_steps', sim.trange()) np.savez_compressed('results/data/discrete_fs/data_%s' % input_signal, sim.data[probe]) np.savez_compressed('results/data/discrete_fs/data_%s_x_neurons' % input_signal, sim...
StegSchreck/RatS
tests/unit/icheckmovies/test_icheckmovies_ratings_inserter.py
Python
agpl-3.0
1,934
0.000517
import os from unittest import TestCase from unittest.mock import patch from RatS.icheckmovies.icheckmovies_ratings_inserter import ICheckMoviesRatingsInserter TESTDATA_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "assets") ) class ICheckMoviesInserterTest(TestCase): ...
tch("RatS.icheckmovies.icheckmovies_ratings_inserter.Select") @patch("RatS.base.base_ratings_uploader.save_movies_to_csv") @patch("RatS.icheckmovies.icheckmovies_ratings_inserter.ICheckMovies") @patch("RatS.base.base_ratings_inserter.RatingsInserter.__init__") @patch("RatS.utils.browser_handler.Firefox"...
int: disable=too-many-arguments site_mock.browser = browser_mock inserter = ICheckMoviesRatingsInserter(None) inserter.site = site_mock inserter.site.site_name = "ICheckMovies" inserter.failed_movies = [] inserter.exports_folder = TESTDATA_PATH inserter.csv_filena...
AlexSafatli/DataMiningImplementations
naive-bayes/ID3_classifier.py
Python
gpl-2.0
13,649
0.011869
#!/bin/python # ID3_classifier.py # ------------------------- # Winter 2013; Alex Safatli # ------------------------- # A program that carries out # the ID3 algorithm on a # given data file; extended # in order to act as a classifier # a la NB_classifier. # # Usage: python ID3_classifier.py # Imports import os, sys ...
= b.value and x in data] classsubset = [] for x in datasubset: classsubset.append(self.classes_target[x]) if len(set(classsubset)) == 1: # If stopping condition reached. All same class. cla = classsubset[0] n...
ttribute(cla,None,b) # leaf node b.attr = node majorityclass.append(cla) continue elif len(set(classsubset)) == 0: # No class; means not majority class. cla = None for cl in self.classes_target: ...
diego-d5000/MisValesMd
env/lib/python2.7/site-packages/django/contrib/gis/gdal/__init__.py
Python
mit
2,676
0
""" This module houses ctypes interfaces for GDAL objects. The following GDAL objects are supported: CoordTransform: Used for coordinate transformations from one spatial reference system to another. Driver: Wraps an OGR data source driver. DataSource: Wrapper for the OGR data source object, supports...
al_full_version, GDAL_VERSION # NOQA from django.contrib.gis.gdal.raster.source import GDALRaster # NOQA from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform # NOQA from django.contrib.gis.gdal.geometries import OGRGeometry # NOQA
HAS_GDAL = True __all__ += [ 'Driver', 'DataSource', 'gdal_version', 'gdal_full_version', 'GDAL_VERSION', 'SpatialReference', 'CoordTransform', 'OGRGeometry', ] except GDALException: HAS_GDAL = False try: from django.contrib.gis.gdal.envelope import Envelope __all__ += ...
edofic/ggrc-core
src/ggrc/converters/base.py
Python
apache-2.0
5,472
0.008589
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENS
E file> """Base objects for csv file converters.""" from collections import defaultdict from ggrc import settings from ggrc.utils import structures from ggrc.cache.memcache import MemCache from ggrc.converters import get_exportables from ggrc.converters.base_block import BlockConverter from ggrc.converters.import_he...
converters. This class contains and handles all block converters and makes sure that blocks and columns are handled in the correct order. It also holds cache objects that need to be shared between all blocks and rows for mappings and similar uses. """ CLASS_ORDER = [ "Person", "Program", ...
manchicken/gist_per_day
gist_reminder.py
Python
unlicense
554
0.01444
#!/usr/bin/env python # This program is designed to send a single email to me once a day if it doesn't see a commit # in the last 24 hours to gist_a_
day. from gistapi import Gist, Gis
ts import gmail import pprint config = { 'sender' : 'davidelmets4peace@gmail.com', 'senderpw' : 'yuslohaw', 'recipient' : 'themanchicken@gmail.com', 'subject' : 'Don\'t forget to create a gist!', 'gistuser' : 'manchicken', 'api_token' : '069598e0300ee0445b48' } gistfetch = Gists.fetch_by_u...
netscaler/neutron
neutron/services/metering/agents/metering_agent.py
Python
apache-2.0
11,158
0
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # Author: Sylvain Afchain <sylvain.afchain@enovance.com> # # 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.apach...
ingAgent, self).__init__(host=self.conf.host) def _load_drivers(self): """Loads plugin-driver from configuration.""" LOG.info(_("Loading Metering driver %s"), self.conf.driver) if not self.conf.driver: raise SystemExit(_('A metering driver must be specified')) self.meter...
ing_notification(self): for label_id, info in self.metering_infos.items(): data = {'label_id': label_id, 'tenant_id': self.label_tenant_id.get(label_id), 'pkts': info['pkts'], 'bytes': info['bytes'], 'time': info['time']...
molpopgen/fwdpy11
fwdpy11/_functions/simplify_tables.py
Python
gpl-3.0
2,314
0.002593
from typing import List, Tuple, Union import fwdpy11._fwdpy11 import fwdpy11._types import numpy as np def simplify(pop, samples): """ Simplify a TableCollection stored in a Population. :param pop: A :class:`fwdpy11.DiploidPopulation` :param samp
les: A list of samples (node indexes). :return: The simplified tables and array mapping input sample IDs to output IDS :rtype: tuple Note that the samples argument is agnostic with respect to the time of the nodes in the input tables. Thus, you may do things like simplify to a set of "currently-a...
ttr:`fwdpy11.DiploidPopulation.ancient_sample_metadata`. If the input contains ancient samples, and you wish to include them in the output, then you need to include their IDs in the samples argument. .. note:: Due to node ID remapping, the metadata corresponding to nodes becomes a bit more ...
CGATOxford/CGATPipelines
CGATPipelines/pipeline_docs/pipeline_motifs/trackers/Context.py
Python
mit
156
0
from CGATRe
port.Tracker import * from IntervalReport import * class ContextSummary(IntervalTracker, SingleTableTrackerRows): table = "con
text_stats"
wakamori/GoForIt
1/1-2.py
Python
bsd-2-clause
1,719
0.002327
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import random import sys class DayLife: """Life in a day.""" def __init__(self, date, life): """Set birth datetime and life.""" self.birthdate = date self.life = life f
inalyear = self.birthdate.year + self.life finaldate = datetime.datetime(finalyear, self.birthdate.month, self.birthdate.day) self.finaldate = finaldate - datetime.timedelta(days=1) def now(self): """Calculate current time.""" curdate = datetime...
(self.finaldate - self.birthdate).days curdays = (curdate - self.birthdate).days curtime = datetime.timedelta(days=1) / maxdays curtime = curtime * curdays return datetime.time( (curtime.seconds / 60) / 60, (curtime.seconds / 60) % 60, ...
spahan/unixdmoain
lib/afslib/tests/vos.py
Python
bsd-3-clause
376
0.013298
#coding: utf-8 import sys sys.path.append("/opt/UD2/lib/afslib") import afslib vos = a
fslib.VolumeServer() # for vol in vos.volumes: # print vol print vos print "Fileservers : %s " % str(vos.fileserv) testvol = ("testvolume", "urz-mars.urz.unibas.ch", "/vicepa") vos.create(testvol)
import os print(os.popen("vos exa testvolume").read()) vos.remove(testvol)
dougwig/x-neutron-lbaas
neutron_lbaas/openstack/common/systemd.py
Python
apache-2.0
3,066
0
# Copyright 2012-2014 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
otification on the socket. :param notify_socket: local socket address :type notify_socket: string :param timeout: socket timeout :type timeout: float :returns: 0 service ready 1 service not ready 2 timeout occurred ""...
AF_UNIX, socket.SOCK_DGRAM) sock.settimeout(timeout) sock.bind(_abstractify(notify_socket)) try: msg = sock.recv(512) except socket.timeout: return 2 finally: sock.close() if 'READY=1' in msg: return 0 else: return 1 if __name__ == '__main__': # ...
Distrotech/dia
plug-ins/python/diadissect.py
Python
gpl-2.0
6,191
0.048134
# # Dissect a diagram by rendering it and accumulating invalid # renderer calls to object selection. # # Copyright (c) 2014 Hans Breuer <hans@breuer.org> # # 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 Soft...
1], msg)) if self.f : self.f.write ("Warni
ng: %s, %s\n" % (self.current_objects[-1], msg)) def Error (self, msg) : self.errors.append ((self.current_objects[-1], msg)) if self.f : self.f.write ("Error: %s, %s\n" % (self.current_objects[-1], msg)) def draw_object (self, object, matrix) : self.current_objects.append (object) # XXX: check matrix # ...
its-dirg/oidc-fed
src/services/op/op.py
Python
apache-2.0
3,497
0.002574
import json import ssl import jinja2 import yaml from flask import jsonify from flask.app import Flask from flask.globals import request, current_app from flask.templating import render_template from jwkest.jwk import keyrep from oic.oic.provider import Provider from oic.utils.authn.authn_context import AuthnBroker fr...
entication_endpoint(): response = current_app.op.provider.authorization_endpoint(request.query_string.decode("utf-8")) return redirect(response.message, 303) @app.route("/token", methods=["get", "post"]) def token_endpoint(): client_authn = request.headers.get("Authorization") if request.method == "G...
t.get_data() response = current_app.op.provider.token_endpoint(data.decode("utf-8"), authn=client_authn) return response.message, response.status, response.headers @app.errorhandler(OIDCFederationError) def exception_handler(error): response = app.make_response(str(error)) response.status_code = 400 ...
kevgathuku/django-dotenv
tests.py
Python
bsd-3-clause
4,694
0.000213
import os import unittest import warnings from dotenv import parse_dotenv, read_dotenv class ParseDotenvTestCase(unittest.TestCase): def test_parses_unquoted_values(self): env = parse_dotenv('FOO=bar') self.assertEqual(env, {'FOO': 'bar'}) def test_parses_values_with_spaces_around_equal_sign...
{'FOO': 'test', 'BAR': 'quote test'}) def test_does_not_expand_variables_in_single_quoted_values(self): env = parse_dotenv("BAR='quote $FOO'") self.assertEqual(env, {'BAR': 'quote $FOO'}) def test_does_not_expand_escaped_variables(self):
env = parse_dotenv('FOO="foo\\$BAR"') self.assertEqual(env, {'FOO': 'foo$BAR'}) env = parse_dotenv('FOO="foo\${BAR}"') self.assertEqual(env, {'FOO': 'foo${BAR}'}) def test_parses_export_keyword(self): env = parse_dotenv('export FOO=bar') self.assertEqual(env, {'FOO': 'b...
rndusr/urwid
urwid/display_common.py
Python
lgpl-2.1
31,238
0.002401
#!/usr/bin/python # Urwid common display code # 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 License, or ...
tions. Pure # white and black are taken from the color cube, since the gray range does # not include them, and the basic colors are more likely to have been # customized by an end-user. def _gray_num_256(gnum): """Return ths colo
r number for gray number gnum. Color cube black and white are returned for 0 and 25 respectively since those values aren't included in the gray scale. """ # grays start from index 1 gnum -= 1 if gnum < 0: return _CUBE_BLACK if gnum >= _GRAY_SIZE_256: return _CUBE_WHITE_256...
quantumlib/Cirq
cirq-google/cirq_google/engine/abstract_program.py
Python
apache-2.0
6,521
0.000767
# Copyright 2021 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt
ain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for th...
rface for quantum programs. The quantum program represents a circuit (or other execution) that, when combined with a run context, will become a quantum job. """ import abc import datetime from typing import Dict, List, Optional, Sequence, Set, TYPE_CHECKING, Union import cirq from cirq_google.engine.client import qu...
Fenugreek/tamarind
bools.py
Python
gpl-3.0
1,641
0.005484
""" Some utilities for bools manipulation. Copyright 2013 Deepak Subburam 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. """ ...
0 meaning dictionary[key] == val, -1 meaning dictionary[key] <= val, -2 meaning dictionary[key] < val, None meaning dictionary[key] != val. """ count = 0 net = 0 for key, cond_value in list(conditions.items()): count += 1 cond, value = cond_value field_value = ...
value <= value elif cond == 0: result = field_value == value elif cond == 2 : result = field_value > value elif cond == -2: result = field_value < value elif cond == 0: result = field_value != value else: raise AssertionError('Bad...
gerardroche/sublime-phpunit
tests/test_is_valid_php_version_file_version.py
Python
bsd-3-clause
3,218
0
from PHPUnitKit.tests import unittest from PHPUnitKit.plugin import is_valid_php_version_file_version class TestIsValidPhpVersionFileVersion(unittest.TestCase): def test_invalid_values(self): self.assertFalse(is_valid_php_version_file_version('')) self.assertFalse(is_valid_php_version_file_versi...
n_file_version('7.1')) self.assertTrue(is_valid_php_version_file_version('7.2')) def test_major_dot_x_versions(self): self.assertTrue(is_valid_php_version_file_version('5.x')) self.assertTrue(is_valid
_php_version_file_version('6.x')) self.assertTrue(is_valid_php_version_file_version('7.x')) self.assertTrue(is_valid_php_version_file_version('8.x')) def test_major_dot_minor_dot_x_versions(self): self.assertTrue(is_valid_php_version_file_version('7.0.x')) self.assertTrue(is_valid_p...
Kiganshee/Flip-Sign
FlipDotSign.py
Python
cc0-1.0
9,790
0.005414
""" Since this is basically firmware, it should be able to handle a lot of hard coding. Some of the elements, especially the events to add, will be difficult to allow the user to send. 1. ??? 2. List of message objects 3. Pop random element off list of message objects 4. When list reaches X entries, start the ???...
the internet is up check = [] GetGoogleSheetData(google_sheet_id, get_credentials(), lstCalendars, check) lstTemporaryMessag
es = check print("Pulled google sheet data") except IOError: # if the internet is down, do nothing print("Found no internet connection when pulling google sheet data.") pass except ValueError: print("No google service when opening google sheet....
noemis-fr/old-custom
product_tags/product.py
Python
agpl-3.0
1,476
0.00542
# -*- coding: utf-8 -*- ################################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Julius Network Solutions SARL <contact@juli
us.fr> # # 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...
ABILITY 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/>. # ##################################################################...
lichenhui/guahao
guahao_beijing/login.py
Python
apache-2.0
2,160
0.043961
#!/usr/bin/env python #coding=utf8 #负责模拟登陆 # import pycurl import StringIO from urllib import urlencode import get_login_code def GetLoginInfo(post_data,cookie_file,proxy): login_url = "http://www.bjguahao.gov.cn/comm/logon.php" #cookie_file = './Cookie/cookie.txt' ch = pycurl.Curl() buffer_con = StringIO.StringI...
640321199001020977','cookie.txt','login_code_img.gif','http://125.46.100.198:9999') login_info = Login('李晨辉','142726199305301214','cookie.txt','login_code_img.gif',False) fo = open('login_response.txt
', 'w') fo.write(login_info) fo.close() print login_info
wackywendell/parm
setup.py
Python
bsd-3-clause
1,332
0.003754
#! /usr/bin/env python # System imports from setuptools import Extension, setup # Third-party modules - we depend on numpy for everything import numpy # Obtain the numpy include directory. This logic works across numpy versions. try: numpy_include = numpy.get_include() except AttributeError: numpy_include =...
Extension( "_" + name, [swig_file], include_dirs=[numpy_include, "src"], extra_compile_args=compile_opts + ["-DSWIG_TYPE_TABLE=" + name, '-std=c++98'], ) for name, swig_file, compile_opts in module_opts ] setup( name="pyparm", description="None", author="Wendell Smith",...
['pyparm'], ext_modules=swigged_modules )
labsquare/CuteVariant
cutevariant/gui/plugins/word_set/__init__.py
Python
gpl-3.0
1,098
0.001821
from PySide2.QtWidgets import QApplication __title__ = "Wordsets editor" __description__ = "A plugin to manage word sets" __long_description__ = """ <p>This plugin allows to create sets of words that can be matched with the attributes of the project's variants.</p> <p> Once the addition of a word set is started, a man...
lters Editor</em> plugin with a filter of the type: <pre>gene IN ('WORDSET', 'my_word_set')</pre></li> <li>the <em>VQL Editor</em> plugin with a VQL request of the type: <pre>SELECT chr,pos,ref,alt,gene FROM variants WHERE gene IN WORDSET['my_word_set']</pre></li> </ul> """ __author__
= "Sacha schutz" __version__ = "1.0.0"
opengovt/ckan-agency-management-tool
mandrill_email.py
Python
agpl-3.0
2,565
0
import os import json import jinja2 import logging import datetime from request import global_vars from settings i
mport MANDRILL_API_KEY, MANDRILL_SENDER from settings import CURRENT_URL, MANDRILL_API_BASE_ENDPOINT from google.appengine.api import url
fetch jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True) def send_email(receiver_name=False, receiver_email=False, subject=False, content={}, email_type=False, many_receiver=False): if not subject or not email_type: retu...
lamby/pkg-fabric
tests/test_operations.py
Python
bsd-2-clause
31,113
0.000418
from __future__ import with_statement import os import shutil import sys import types from contextlib import nested from StringIO import StringIO import unittest import random import types from nose.tools import raises, eq_, ok_ from fudge import with_patched_object from fabric.state import env, output from fabric....
test_prompt_with_default(): """ prompt() appends gi
ven default value plus one space on either side """ s = "This is my prompt" d = "default!" prompt(s, default=d) eq_(sys.stdout.getvalue(), "%s [%s] " % (s, d)) # # run()/sudo() # def test_sudo_prefix_with_user(): """ _sudo_prefix() returns prefix plus -u flag for nonempty user """ ...
MicroWorldwide/tweeria
web/functions.py
Python
mit
10,763
0.00223
# -*- coding: utf-8 -*- # General functions for web part and parser import datetime import time import re RE_MESSAGE_VARS = re.compile('(\{([^\}]*)\})') RE_TAGS = re.compile('<[^<]+?>', re.U + re.I + re.M) RE_PARAGRAPH = re.compile('\n', re.U + re.I + re.MULTILINE) RE_OUT_FORMAT = re.compile('(\'|`)', re....
uest" rel="/obj/13/' + str(data['quest_UID']) + '">[' + data['quest'] + ']</span>' elif m[0] == '{winner_guild}': pattern = '<span class="guild" rel="/obj/11/' + str(data['winner_guild']) + '">[' + data['winner_guild_name'] + ']</span>' elif m[
0] == '{looser_guild}': pattern = '<span class="guild" rel="/obj/11/' + str(data['looser_guild']) + '">[' + data['looser_guild_name'] + ']</span>' elif m[0] == '{winner_faction}': pattern = '<span class="guild" rel="/obj/12/' + str(data['winner_fa...
tapomayukh/projects_in_python
sandbox_tapo/src/refs/Python Examples_Pygame/Python Examples/pygame_base_template.py
Python
mit
1,067
0.022493
# Sample Python/Pygame Programs # Simpson College Computer Science # http://cs.simpson.edu import pygame # Define some colors black = ( 0, 0, 0) white = ( 255, 255, 255) green = ( 0, 255, 0) red = ( 255, 0, 0) pygame.init() # Set the height and width of the screen size=[700,500] screen=...
ock() # -------- Main Program Loop ----------- while done==False: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked
close done=True # Flag that we are done so we exit this loop # Set the screen background screen.fill(black) # Limit to 20 frames per second clock.tick(20) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line...
nrc/dxr
tests/test_empty_tree/test_empty_tree.py
Python
mit
241
0.004149
from dx
r.testing import DxrInstanceTestCase class TestEmptyTree(DxrInstanceTestCase): """Tests for empty source tree""" def test_empty(self): """Test empty""" self.found_nothing('path:*.*', is_case_sensitive=Fals
e)
AMOboxTV/AMOBox.LegoBuild
plugin.video.youtube/resources/lib/youtube/client/login_client.py
Python
gpl-2.0
12,698
0.00378
__author__ = 'bromix' import time import urlparse from resources.lib.kodion import simple_requests as requests from resources.lib.youtube.youtube_exceptions import LoginException class LoginClient(object): CONFIGS = { 'youtube-tv': { 'system': 'All', 'key': 'AIzaSyAd-YEOqZz9nXVz...
lient_secret='', grant_type=''): headers = {'Host': 'www.youtube.com', 'Connection': 'keep-alive', 'Origin': 'https://www.youtube.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/40.0.2214.28 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Accept': '*/*', 'DNT': '1', 'Referer': 'https://www.youtube.com/tv', 'Accept-Encoding': 'gzip, deflate', ...
ajdawson/eofs
lib/eofs/iris.py
Python
gpl-3.0
25,623
0
"""Meta-data preserving EOF analysis for `iris`.""" # (c) Copyright 2013-2016 Andrew Dawson. All Rights Reserved. # # This file is part of eofs. # # eofs 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 ...
n) any later version. # # eofs 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 hav
e received a copy of the GNU General Public License # along with eofs. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) # noqa import collections from copy import copy from iris.cube import Cube from iris.coords import DimCoord from . import standard fr...
whichwit/scm-stv
mlms/_get-mlms.py
Python
gpl-2.0
725
0.009655
# -*- coding: utf-8 -*- import pyodbc cs = { 'server':'ahwsqlinind019.ind1.stvincent.org', 'database':'st2cpr1.tst_153', #'database':'st1bprvb.st1', 'user':'scmis', 'pw':'year04', } conn = pyodbc.connect(
driver='{SQL Server}', server=cs['server'], uid=cs['user'], pwd=cs['pw'], ) if not conn: raise IOError cursor = conn.cursor() sql = """ select Name , replace(convert(varchar(max),Logic),'{{{SINGLE-QUOTE}}}',char(39)) as Logic"""+""" from {db}.dbo.CV3MLM where Active = 1 and Status = 4 ...
te(row.Logic)
sergei-maertens/discord-bot
bot/plugins/stats/resources.py
Python
mit
619
0.001616
from import_export import fields, resources class GamesPlayedResource(resources.Resource): game = fields.Field(attribute='game__name', column_name='game') time = fields.Field(attribute='time', column_name='time (hours)') num_players = fields.Field(attribute='num_players', column_name='num_players') ...
ate_game(self, obj): return obj['game__name'] def dehydrate_time(self, obj): return obj['time'].total_seconds() / 3600 def dehydrate_num_players(self, obj): return obj['num_play
ers']
AustinRoy7/Pomodoro-timer
venv/Lib/os.py
Python
mit
36,970
0.002218
r"""OS routines for NT or Posix depending on what system we're on. This exports: - all functions from posix, nt or ce, e.g. unlink, stat, etc. - os.path is either posixpath or ntpath - os.name is either 'posix', 'nt' or 'ce'. - os.curdir is a string representing the current directory ('.' or ':') - os.pardir...
__all__.extend(_get_exports_list(posix)) del posix elif 'nt' in _names: name = 'nt' linesep = '\r\n' from nt import * try: from nt import _exit __all__.append('_exit') except ImportError: pass import ntpath as path import nt __all__.
extend(_get_exports_list(nt)) del nt try: from nt import _have_functions except ImportError: pass elif 'ce' in _names: name = 'ce' linesep = '\r\n' from ce import * try: from ce import _exit __all__.append('_exit') except ImportError: pass # ...
deepmind/xmanager
xmanager/xm/core.py
Python
apache-2.0
23,876
0.006451
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
`s; - if it's a job generator, we return `{}`. """ if args is not None: # In order to give users control on what is shown as work unit arguments we # don't alter them if a value is given. return args def deduce_args_for_job(job: job_blocks.Job) -> Dict[str, Any]: args = { 'args': jo...
y: value for key, value in args.items() if value} def deduce_args_for_job_group(group: job_blocks.JobGroup) -> Dict[str, Any]: args = {} for job_name, job in group.jobs.items(): job_args = deduce_args(job) if job_args: args[job_name] = job_args return args deduce_args = pattern_mat...
google/layered-scene-inference
lsi/visualization/html_utils.py
Python
apache-2.0
1,782
0.00954
#!/usr/bin/python # # Copyright 2018 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 ag...
future__ import division from __future__ import print_function def html_page(content): init_text = '<!DOCTYPE html>\n<html>\n<head>\n{}\n</head>\n<body>\n'.format( page_style() ) end_text = '\n</html>\n</body>\n' return init_text + content + end_text def page_style(): """Html style string. Ar
gs: Returns: style_str: HTML sytle string """ style_str = '''<style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 10px; } </style>''' return style_str def image(rel_path, caption, height, width): img_str = '<img src="{}" alt="{}" style="width:{}px;...
comic/comic-django
app/grandchallenge/workstation_configs/forms.py
Python
apache-2.0
2,610
0.0023
from django.forms import ModelForm from grandchallenge.core.forms import SaveFormInitMixin from grandchallenge.core.widgets import JSONEditorWidget from grandchallenge.workstation_configs.models import ( KEY_BINDINGS_SCHEMA, OVERLAY_SEGMENTS_SCHEMA, WorkstationConfig, ) class WorkstationConfigForm(SaveFo...
"show_display_plugin", "show_image_switcher_plugin", "show_algorithm_output_plugin", "show_overlay_plugin", "show_invert_tool", "show_flip_tool", "show_window_level_tool", "show_reset_tool", "show_overlay_selection_t...
"auto_jump_center_of_gravity", ) widgets = { "overlay_segments": JSONEditorWidget( schema=OVERLAY_SEGMENTS_SCHEMA ), "key_bindings": JSONEditorWidget(schema=KEY_BINDINGS_SCHEMA), } help_texts = { "overlay_segments": ( ...
afolmert/mentor
src/models.py
Python
gpl-2.0
12,011
0.003663
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- # # Copyright (C) 2007 Adam Folmert <afolmert@gmail.com> # # This file 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, or (at your option) #...
algorithms - it should be just as a proxy # between database and any more
advanced algorithm # e.g. database importer # btw. they should use the same classes with the probe program # TODO progress bar for importing and possibility to cancel if is a long # operatoin def importQAFile(self, file, clean=True): """Import cards from given question&answer file. ...
AndreMiras/order_map_symbols
order_map_symbols.py
Python
mit
2,082
0.00048
#!/usr/bin/env python import argparse from operator import itemgetter def extract_symbols_text(map_file_text): start_pattern = "Common symbol size file" stop_pattern = "Discarded input sections" start_index = map_file_text.index(start_pattern) + len(start_pattern) stop_index = map_f...
line = { "variable": variable, "size": size, "filename": filename, } symbols_dicts.append(line) return symbols_dicts
def sort_symbols(symbols_dicts): sorted_symbols_dicts = sorted(symbols_dicts, key=itemgetter('size')) return sorted_symbols_dicts def print_symbols(symbols_dicts): string_format = "%20s\t%20s\t%20s" print(string_format % ("variable", "size", "filename")) for symbols in symbols_dicts: var...
sio2project/oioioi
oioioi/maintenancemode/apps.py
Python
gpl-3.0
115
0
from django.apps import AppConfig cl
ass MaintenancemodeAppConfig(AppConfig):
name = "oioioi.maintenancemode"
geosolutions-it/cread-workflows
publishVector.py
Python
apache-2.0
1,125
0.010667
from cread.geonodemanager import GeonodeManager import os import zipfile # The data entry form ##DomainName=string host[:port] ##StoreName=string police_station_wgs84 ##Layer=vector ##UserName=
string admin ##Password=string geoserver # Get the path on FileSystem of the layer loaded on QGIS and selected by the user myfilepath = processing.getObject(Layer).dataProvider().dataS
ourceUri() # Access to the shapefile folder and create a zip to upload it using geoserver REST interface (myDirectory,nameFile) = os.path.split(myfilepath) zipf = zipfile.ZipFile(os.path.join(myDirectory,'shpUpload.zip'), 'w') for file in os.listdir(myDirectory): print file if(str(file) != "shpUpload.zip"): ...
JointBox/jointbox
src/common/validators.py
Python
gpl-3.0
913
0.003286
# JointBox - Your DIY smart home. Simplified. # Copyright (C) 2017 Dmitry Berezov
sky # # JointBox 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. # # JointBox is distributed in the hope that it...
r 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/>. def boolean(value): return isinstance(value, bool) def integer(value): return isinstance(value, int) def module_id(value): return True
rexdf/wp2octopress
wp2oct/authoring.py
Python
gpl-3.0
244
0
# coding: utf-8 __author__ = 'Rexdf'
__email__ = 'rexdf@rexdf.org' __copyright__ = "Copyright 2014, %s <http://blog.rexdf.org>" % __author__ __license__ = 'GNU GPL 3' __status__ = 'Development' __url__ = 'http:
//github.com/rexdf/wp2octopress'
gramps-project/addons-source
DataEntryGramplet/DataEntryGramplet.gpr.py
Python
gpl-2.0
761
0.021025
#------------------------------------------------------------------------ # # Register Gramplet # #------------------------------------------------------------------------ register(GRAMPLET, id="Data Entry Gramplet", name=_("Data Entry Gramplet"), description = _("Gramplet for quick data entr...
detached_width = 510, detached_height = 480, version = '1.0.46', gramps_target_version = "5.1", status=STABLE, # not yet tested with python 3 fname="DataEntryGramplet.py", help_url="Data Entry Gramplet", navtypes=[
"Person"], )
switch-model/switch-hawaii-studies
database/DB_Code/study_dates/study_hour.py
Python
apache-2.0
2,084
0.008637
#!/usr/bin/python # -*- coding: utf-8 -*- import datetime import os import psycopg2 import sys con = None f = None try: ################ CHANGE THESE PARAMETERS ONLY ################ con = psycopg2.connect(database='switch', host='localhost', port='5432', user='deepakc_super', password='myPassword') ...
ur; """ cur.execute(query) con.commit() except psycopg2.DatabaseError, e
: if con: con.rollback() print 'Error %s' % e sys.exit(1) except IOError, e: if con: con.rollback() print 'Error %s' % e sys.exit(1) finally: if con: con.close()
Starofall/RTX
rtxlib/preprocessors/__init__.py
Python
mit
779
0.001284
from colorama import Fore from rtxlib import info, error, debug from rtxlib.preprocessors.SparkPreProcessor import SparkPreProcessor def init_pre_processors(wf): """ we look into the workflows definition and run the required preprocessors """ if hasattr(wf, "pre_processors"): pp = wf.pre_processors ...
p["instance"] = SparkPreProce
ssor(wf, p) else: info("> Preprocessor | None", Fore.CYAN) def kill_pre_processors(wf): """ after the experiment, we stop all preprocessors """ try: for p in wf.pre_processors: p["instance"].shutdown() info("> Shutting down Spark preprocessor") ...
google-research/google-research
yoto/utils/__init__.py
Python
apache-2.0
608
0.001645
# coding=utf-8 # Copyright 2022 The Google Research 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific lang...
tomaaron/raiden
tools/genesis_builder.py
Python
mit
1,166
0.000858
# -*- coding: utf-8 -*- from ethereum.utils import sha3, encode_hex, denoms from raiden.utils import privatekey_to_address from raiden.tests.utils.blockchain import GENESIS_STUB CLUSTER_NAME = 'raiden' def generate_accounts(seeds): """Create private keys and addresses for all seeds. """ return { ...
ict( privatekey=encode_hex(sha3(seed)), address=encode_hex(privatekey_to_address(sha3(seed))) ) for seed in seeds} def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000): """ Create a genesis-block dict with allocation for all `accounts`. :param accounts: list of...
is dict """ genesis = GENESIS_STUB.copy() genesis['extraData'] = CLUSTER_NAME genesis['alloc'] = { account: { 'balance': str(initial_alloc) } for account in accounts } # add the one-privatekey account ("1" * 64) for convenience genesis['alloc']['19e7e376e7...
hdunderscore/hd-io_scene_fbx
__init__.py
Python
gpl-2.0
15,423
0.001426
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # This program is distrib...
", ""), ('-X', "-X Up", ""), ('-Y', "-Y Up", ""), ('-Z', "-Z Up", ""), ), defau
lt='Y', ) # 7.4 only bake_space_transform = BoolProperty( name="Bake Space Transform", description=("Bake space transform into object data, avoids getting unwanted rotations to objects when " "target space is not aligned with Blender's space " "(WARN...
nwokeo/supysonic
venv/lib/python2.7/site-packages/mutagen/_senf/_print.py
Python
agpl-3.0
10,191
0
# -*- coding: utf-8 -*- # Copyright 2016 Christoph Reiter # # 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...
oding errors. Tries hard to get everything on screen as is, but will fall back to "?" if all fails. This does not conflict with ``colorama``, but will not use it on Windows. """ sep = kwargs.get("sep") sep = sep if sep is not None else " " end = kwargs.get("end") end = end if end is not ...
sep, end, file, flush) else: _print_unix(objects, sep, end, file, flush) def _print_unix(objects, sep, end, file, flush): """A print_() implementation which writes bytes""" encoding = _encoding if isinstance(sep, text_type): sep = sep.encode(encoding, "replace") if not isinstance...
eckardm/archivematica
src/dashboard/src/components/api/urls.py
Python
agpl-3.0
1,766
0.002831
# This file is part of Archivematica. # # Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General P
ublic License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Archivematica 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 PURP...
more details. # # You should have received a copy of the GNU General Public License # along with Archivematica. If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import url, patterns from django.conf import settings from components.api import views urlpatterns = patterns('', url(r'transfer/appro...
wearpants/osf.io
tests/test_prereg.py
Python
apache-2.0
3,366
0.000297
from nose.tools import * # noqa from modularodm import Q from website.prereg import prereg_landing_page as landing_page from website.prereg.utils import drafts_for_user, get_prereg_schema from website.project.model import ensure_schemas, MetaSchema from tests.base import OsfTestCase from tests import factories cl...
instance(schema, MetaSchema) assert_equal(schema.name, 'Prereg Challenge') def test_get_prereg_schema_can_return_erpc_metaschema(self): schema = get_prereg_schema('erpc') assert_is_instance(schema, MetaSchema) assert_equal(schema.name, 'Election Research Preacceptance Competition') ...
assert_raises(ValueError): get_prereg_schema(campaign='invalid')
louisq/staticguru
utility/jdk_override.py
Python
mit
1,445
0.00692
""" The MIT License (MIT) Copyright (c) 2016 Louis-Philippe Querel l_querel@encs.concordia.ca 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...
TNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from ...
tility.abstract_override import AbstractOverride class JdkOverride(AbstractOverride): def _get_override_format(self): return 'JAVA_HOME="%s"' def _get_default_format(self): return '' def __init__(self, *args): AbstractOverride.__init__(self, *args) self.name = "JDK"
rkrp/2timepad-breaker
crack.py
Python
gpl-3.0
1,264
0.006329
#!/usr/bin/python import re from sys import argv from orig import strxor #Load dictionary for validation with open('cracklib-small', 'r') as fp: wordlist = set(fp.read().split('\n')) def isprintable(inp): words = inp.split(' ') if len(words) == 1: return False for word in words: wor...
fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904".decode('hex') #Loading the other ciphertexts encrypted with the same key with open('inputs', 'r') as fp: cts = fp.read().split('\n') text = argv[1] #Guessed part of the...
se_t = case_t.decode('hex') c1c2 = strxor(ct, case_t) for i in range(len(c1c2)): res = strxor(text, c1c2[i:i+len(text)]) if isprintable(res): print i, res print if __name__ == '__main__': main()