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 |
|---|---|---|---|---|---|---|---|---|
belial1337/WorldAttackMap | wss.py | Python | gpl-2.0 | 1,664 | 0.02524 | #!/usr/bin/python
import socket
import re
import binascii
import struct
import time
import sys
import random
from base64 import b64encode
from hashlib import sha1
from thread import *
events = "/var/www/map/eventstream"
with open(events) as f:
content = f.read().splitlines()
f.close()
websocket_answer = (
'H... | lete'
s.listen(10)
print "Listening for connections"
def clientthread(client):
while True:
for line in content:
length = len(line)
preamble = "\x81\x7e" + struct.pack(">i", length)[2:]
client.send(preamble+line)
print "Sending Attack Event ... | es\n"
random.seed()
n = random.random()
time.sleep(n)
client.close()
while 1:
client, address = s.accept()
print 'Got connection from', address
text = client.recv(1024)
print text
key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text)
.groups()[0]
.strip())
... |
paylogic/atilla | atilla/exceptions.py | Python | mit | 1,492 | 0.00067 | """Exceptions for APIs."""
impor | t werkzeug.exceptions
class ApiException(Exception):
"""An exception raised due to user error.
Exceptions derived from ApiException will be logge | d automatically if raised.
User will receive appropriate error response according to the content type.
"""
description = 'API error.'
error_type = 'API_ERROR'
data = None
def __init__(self, message, description=None, status_code=None, **kwargs):
"""Constructor.
:param message:... |
dchaplinsky/pep.org.ua | pepdb/core/migrations/0073_auto_20160213_0335.py | Python | mit | 8,548 | 0.002457 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0072_auto_20160210_0246'),
]
operations = [
migrations.AddField(
model_name='declaration',
n... | model_name='company2company',
name='date_finished_details',
field=models.IntegerField(default=0, verbose_name='\u0 | 442\u043e\u0447\u043d\u0456\u0441\u0442\u044c', choices=[(0, '\u0422\u043e\u0447\u043d\u0430 \u0434\u0430\u0442\u0430'), (1, '\u0420\u0456\u043a \u0442\u0430 \u043c\u0456\u0441\u044f\u0446\u044c'), (2, '\u0422\u0456\u043b\u044c\u043a\u0438 \u0440\u0456\u043a')]),
),
migrations.AlterField(
mo... |
mnhkahn/python_code | bing.py | Python | gpl-2.0 | 5,311 | 0.005791 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'backGroundC.ui'
#
# Created: Sat Jun 21 13:16:32 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
from PyQt4 import QtCore
import urllib
import os
import... | etObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(10, 10, 281, 41))
self.pushButton.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.pushButton.setObjectName(_fromUtf8("pushButton") | )
self.pushButton2 = QtGui.QPushButton(self.centralwidget)
self.pushButton2.setGeometry(QtCore.QRect(10, 60, 281, 41))
self.pushButton2.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.pushButton2.setObjectName(_fromUtf8("pushButton2"))
MainWindow.setCentral... |
elric/virtaal-debian | virtaal/plugins/terminology/models/localfile/localfileview.py | Python | gpl-2.0 | 17,737 | 0.002932 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2010 Zuza Software Foundation
#
# This file is part of Virtaal.
#
# 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 ... | s_dict = dict([ (_(name), (extension, mimetype)) for name, extension, mimetype in store_factory.supported_files() ])
supported_file_names = supported_files_dict.keys()
supported_file_names.sort(cmp=strcoll)
for name in supported_file_names:
extensions, mimetypes = supported_files_dic... | continue
new_filter = gtk.FileFilter()
new_filter.set_name(name)
if extensions:
for extension in extensions:
new_filter.add_pattern("*." + extension)
all_supported_filter.add_pattern("*." + extension)
... |
krishardy/dynip | dynip/client.py | Python | bsd-2-clause | 4,662 | 0.007508 | """
DynIP Client
A embarrisingly-simple client with sends UDP packets to the DynIP server.
"""
"""
Copyright (c) 2011, R. Kristoffer Hardy
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistribu... | ame
DEFAULT_SERVER_HOSTNAME="localhost"
# DEFAULT_SERVER_PORT:
# The port that the server is listening on
DEFAULT_SERVER_PORT=28630
logging.basicConfig()
| log = logging.getLogger(__name__)
log.setLevel(logging.WARNING)
# Prepare argparser
argparser = argparse.ArgumentParser(description="Sends a single packet to the DynIP server.")
argparser.add_argument('-v', '--verbose', help="Enable verbose (INFO-level) logging",
action='store_const',
default=logging.... |
v-iam/azure-sdk-for-python | azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py | Python | mit | 1,087 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | tailPaged
from .operation_paged import OperationPaged
__all__ = [
'MeterDetails',
'UsageDetail',
'ErrorDetails',
'ErrorResponse', 'ErrorResponseException',
'OperationDisplay',
'Operation',
'Resource',
'UsageDetailPaged',
' | OperationPaged',
]
|
dturner-tw/pants | tests/python/pants_test/goal/test_run_tracker_integration.py | Python | apache-2.0 | 1,258 | 0.005564 | # coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
from pa... | '--run-tracker-stats-local-json-file={}'.format(tmpfile),
'testprojects/src/java/org/pantsbuild/testproject/unicode/main'])
self.assert_success(pants_run)
with open(tmpfile, 'r') as fp:
stats_json = json.load(fp)
self.assertIn('outcomes', stats_json... | ats_json)
self.assertIn('run_info', stats_json)
self.assertIn('self_timings', stats_json)
self.assertIn('cumulative_timings', stats_json)
|
ActiveState/code | recipes/Python/491280_BackgroundCall_Threading_like/recipe-491280.py | Python | mit | 2,587 | 0.016622 | def example_BackgroundCall():
import urllib,time
def work():
return urllib.urlopen('http://www.python.org/').read()
bkcall=BackgroundCall(work)
print 'work() executing in background ...'
while not bkcall.is_done():
print '.',
time.sleep(0.010)
print 'done.'
print bkca... | unction )
...
if bkcall.is_done():
print "got", bkcall.get_return()
"""
id=None
done=0 #1=returned; 2=exception raised
def __init__(self, func, args=(), kwargs={}):
import th | read
def thread_bkcall():
try:
self.ret=func(*args, **kwargs)
self.done=1
except:
self.exc=sys.exc_info()
self.done=2
self.id=thread.start_new(thread_bkcall, ())
def is_done(self):
return self.done
de... |
ourbest/sns_app | utils/scheduler.py | Python | lgpl-3.0 | 41 | 0 | from datetime import datetime, | timed | elta
|
alexandre-figura/portfolio | tests/system_and_unit_tests/conftest.py | Python | gpl-3.0 | 211 | 0 | import pytest
import | webtest
from portfolio import PortfolioFlatPages
@pytest.fixture
d | ef client(app):
return webtest.TestApp(app)
@pytest.fixture
def flatpages(app):
return PortfolioFlatPages(app)
|
enhean/fredist | src/fredist/classifier.py | Python | gpl-3.0 | 8,580 | 0.006876 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Enrique Henestroza Anguiano
#
"""
Classifier for liblinear, svmlin. Agnostic about features or labels. Uses
'ranking', or dynamic classes.
"""
import sys
import os
import codecs
import svmlight
from libsvm import svmutil, svm
# Optional LIBLinear
try:
from... | self._numex_train += 1
qid = self._numex_train
else:
self._numex_dev += 1
qid = self._numex_dev
for idx in range(len(ex)):
feats = ex[idx]
| if mode == 'train':
self._max_feat = max(self._max_feat, feats[-1][0])
if idxg == idx:
glab = 1
else:
glab = 0
print >> exstream, glab, 'qid:'+str(qid),\
" ".jo... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_text/difflib_seq.py | Python | apache-2.0 | 948 | 0.006329 | import difflib
s1 = [1, 2, 3, 5, 6, 4]
s2 = [2, 3, 5, 4, 6, 1]
print('Initial data:')
print('s1 =', s1)
print('s2 =', s2)
print('s1 == s2:', s1 == s2)
print()
matcher = difflib.SequenceMatcher(None, s1, s2)
for tag, i1, i2, j1, j2 in reversed(matcher.get_opcodes()):
if tag == 'delete':
print('Remove {} from p... |
print(('Replace {} from s1[{}:{}] '
'with {} from s2[{}:{}]').format(
s1[i1:i2], | i1, i2, s2[j1:j2], j1, j2))
print(' before =', s1)
s1[i1:i2] = s2[j1:j2]
print(' after = ', s1, '\n')
print('s1 == s2:', s1 == s2)
|
lightningwolf/Flask-JqueryUiBootstrap | SAMPLE_PROJECT/wtf-app.py | Python | mit | 1,192 | 0.003356 | #!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
... | 'This is field one.')
field2 = TextField('Second Field', description='This is field two.',
validators=[Required()])
hidden_field = HiddenField('You cannot see this', description='Nope')
recaptcha = RecaptchaField('A sample recaptcha field')
def validate_hidden_field(form, field):... | SED"
return render_template('example.html', form=form)
if '__main__' == __name__:
app.run(debug=True)
|
Spinmob/spinmob | _plot_complex.py | Python | gpl-3.0 | 207 | 0.024155 | from . import _plotting_mess
data = _plot | ting_mess.complex_data
databoxes = _plotting_mess.complex_databoxes
files = _plotting_mess.complex_ | files
function = _plotting_mess.complex_function |
plotly/python-api | packages/python/plotly/plotly/validators/layout/title/_pad.py | Python | mit | 945 | 0.001058 | import _plotly_utils.basevalidators
class PadValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="pad", parent_name="layout.title", **kwargs):
super(PadValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
dat... | r
The amount of padding (in px) on the right side
of the component.
t
The amount of padding (in px) alo | ng the top of
the component.
""",
),
**kwargs
)
|
meigrafd/Sample-Code | interrupt_pause_script.py | Python | mit | 1,638 | 0.0116 | #!/usr/bin/python
from __future__ import print_function
import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
#GPIO pins
Taster1 = 24
Taster2 = 27
# GPIO-Nummer als Pinreferenz waehlen
GPIO.setmode(GPIO.BCM)
# GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren
#PULL = G... | d ISR "Interrupt" deklarieren sowie Pin entprellen
GPIO.add_event_detect(Taster1, GPIO.RISING, callback=interrupt_event, bouncetime=200)
GPIO.add_event_detect(Taster2, GPIO.RISING, callback=interrupt_event, bouncetime=200)
# keep script running
while True:
time.sleep(0.5)
if not queue.em... | t("Pausiere Script")
dictionary['pause'] = True
Pause()
print("...puh... Im super heavy busy...")
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n") |
rahulunair/nova | nova/tests/unit/test_api_validation.py | Python | apache-2.0 | 47,979 | 0.000333 | # Copyright 2013 NEC Corporation. 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 ... | f.post_schema is not None:
@validation.schema(request_body_schema=self.post_schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def check_validation_error(self, method, body, expected_detail, req=None):
if not req:
re... | =req)
except exception.ValidationError as ex:
self.assertEqual(400, ex.kwargs['code'])
if isinstance(expected_detail, list):
self.assertIn(ex.kwargs['detail'], expected_detail,
'Exception details did not match expected')
elif not ... |
hfp/libxsmm | samples/deeplearning/sparse_training/fairseq/fairseq_cli/eval_lm.py | Python | bsd-3-clause | 8,725 | 0.001375 | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Evaluate the perplexity of a trained language model.
"""
import logging
import math
import os
import torch
fr... | w > 0:
dataset = LMContextWindowDataset(
dataset=dataset,
tokens_per_sample=args.tokens_per_sample,
context_window=args.context_window,
pad_idx=tas | k.source_dictionary.pad(),
)
logger.info('{} {} {} examples'.format(args.data, args.gen_subset, len(dataset)))
# Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer)
for model in models:
model.prepare_for_inference_(args)
if args.fp16:... |
holdenweb/pyresttest | pyresttest/test_validators.py | Python | apache-2.0 | 13,922 | 0.001796 | import unittest
import validators
from binding import Context
class ValidatorsTest(unittest.TestCase):
""" Testing for validators and extract functions """
def test_validatortest_exists(self):
func = validators.VALIDATOR_TESTS['exists']
self.assertTrue(func('blah'))
self.assertTrue(fu... | ators.AbstractE | xtractor()
ext.query = '$val.vee'
ext.is_templated = True
context = Context()
context.bind_variable('val', 'foo')
self.assertEqual('$val.vee', ext.templated_query())
self.assertEqual('foo.vee', ext.templated_query(context=context))
ext.is_templated = False
... |
avatao-content/challenge-toolbox | toolbox/utils/config.py | Python | apache-2.0 | 4,202 | 0.002142 | import os
import re
import yaml
try:
from packaging.version import parse as parse_version
except ImportError:
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_e... | # pylint: disable=too-many-branches
unique_ports = set()
ssh_ports_count = 0
for port in ports:
try:
port, protocol = port.split('/', 1)
unique_ports.add(port)
try:
if not 0 < int(port) < 65536:
raise ValueError
exc... | ed_error('Invalid protocol in config.yml: %s. Valid protocols: %s', protocol, PROTOCOLS)
if protocol == 'ssh':
ssh_ports_count += 1
except Exception:
counted_error('Invalid port format. [port/protocol]')
if len(unique_ports) != len(ports):
counted_error('Du... |
Code-WvS/snapmesh | snapmesh.py | Python | gpl-3.0 | 851 | 0.011751 | #!/u | sr/bin/env python2
import snapext, os
handler = sna | pext.SnapHandler
data = dict()
@handler.route('/')
def main():
return 'Ich bin online!'
@handler.route('/check')
def key_in_data(key):
return key in data
@handler.route('/get')
def get_data(key):
return data[key] if key_in_data(key) else ''
@handler.route('/put')
def set_data(key, value):
data[key]... |
tech22info/registrator | regs/mailru_registrator.py | Python | gpl-3.0 | 106 | 0.009434 | #!/usr | /bin/python3
# encoding=utf-8
import reg_mailru_email
print (reg_mailru_email.reg_mailru_email())
| |
pystockhub/book | ch15/01.py | Python | mit | 67 | 0 | import | matplotlib.pyplot as plt
plt.plot([1, | 2, 3, 4])
plt.show()
|
DMIAlumni/pydrone-game | pydrone/drones/base.py | Python | bsd-2-clause | 790 | 0 | class BaseDrone(object):
"""
Drone interface
"""
flipflop = False
distances = []
last_direction = 0
last_modifier = 0
fuel = 2000
graph = Non | e
kb = None
algorithm = None
def __init__(self, world_size, x, y):
# Initialize knowledge base and starting position
self.actual_position = (x, y)
self.kb_generator(world_size, x, y)
def kb_generator(self, world_size, x, y):
raise NotImplementedError()
def move(sel... | entedError()
def print_status(self):
"""
Not required (ex: optimal algorithm test)
"""
pass
|
wemanuel/smry | smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/http_health_checks/delete.py | Python | apache-2.0 | 786 | 0.008906 | # Copyright 2014 Google Inc. All Rights Reserved.
""" | Command for deleting HTTP health checks."""
from googlecloudsdk.compute.lib im | port base_classes
class Delete(base_classes.GlobalDeleter):
"""Delete HTTP health checks."""
@staticmethod
def Args(parser):
cli = Delete.GetCLIGenerator()
base_classes.GlobalDeleter.Args(parser, 'compute.httpHealthChecks', cli,
'compute.http-health-checks')
@prop... |
widowild/messcripts | exercice/python2/chap15/canon01.py | Python | gpl-3.0 | 1,632 | 0.011029 | # -*- coding:Latin-1 -*-
from Tkinter import *
from math import pi, sin, cos
class Canon(object):
"""Petit canon graphique"""
def __init__(self, boss, x, y):
self.boss = | boss # référence du canevas
self.x1, self.y1 = x, y # axe de rotation du canon
# dessiner la buse du canon, à l'horizontale pour commencer :
self.lbu = 50 # longueur de la buse
self.x2, self.y2 = x + self.lbu, y
self.buse = boss.create_line(self.x1, s... | canon par-dessus :
r = 15 # rayon du cercle
boss.create_oval(x-r, y-r, x+r, y+r, fill='blue', width =3)
def orienter(self, angle):
"choisir l'angle de tir du canon"
# rem : le paramètre <angle> est reçu en tant que chaîne de car.
# il faut le tradui... |
2ndQuadrant/ansible | test/units/module_utils/facts/virtual/test_linux.py | Python | gpl-3.0 | 876 | 0.003425 | # -*- coding: utf-8 -*-
# Copyright (c) 2020 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
from ansible.module_utils.facts.virtual import linux
def test_get_virtual_fa... | ntent', return_value='')
mocker.patch('ansible.module_utils.facts.virtual.linux.get_file_lines', return_value=[])
module = mocker.Mock()
module.run_command.return_value = (0, 'BHYVE\n', '')
inst = linux.LinuxVirtual(module)
facts = inst.get_virtual_facts()
expected = {
'virtualization_... | ,
}
assert facts == expected
|
embaldridge/retriever | app/download_manager.py | Python | mit | 4,858 | 0.00247 | """This class manages dataset downloads concurrently and processes progress
output."""
import wx
from retriever.lib.download import DownloadThread
class DownloadManager:
def __init__(self, parent):
self.dialog = None
self.worker = None
self.queue = []
self.downloaded = set()
... | elf.timer.interval)
elif self.queue:
script = self.queue[0]
self.queue = self.queue[1:]
self.worker = DownloadThread(self.Parent.engine, script)
self.worker.parent = self
self.worker.start()
self.timer.Start(10)
def flush(self):
... | '\b' in s:
s = s.replace('\b', '')
if not self.dialog:
wx.GetApp().Yield()
self.dialog = wx.ProgressDialog("Download Progress",
"Downloading datasets . . .\n"
+ " " *... |
fstltna/PyImp | pyimp.py | Python | gpl-2.0 | 8,968 | 0.002119 | #!/usr/bin/env python
"""Main initialization file for empire client."""
# Copyright (C) 1998-1999 Kevin O'Connor
# Copyright (C) 2013 William Fittge
#
# 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 ... | ILE = "ImpDB"
# Check for included directory list
# The default include path is: the current directory, the program's
# directory.
includes = ['', sys.path[0]]
for i, j in opts:
if i == '-I':
includes[:0] = [j]
def pathPrefix(str, dirlist=includes):
"""Check installa... | ind the file - maybe the caller will have more luck:
return ""
# Mangle the system module path. Replace current directory with src/
# sub-directory.
sys.path[0] = os.path.join(sys.path[0], "src")
# Load modules
import empDb
import empQueue
import empCmd
# Hack! Pass on the p... |
barnone/EigenD | tools/pip_cmd/__init__.py | Python | gpl-3.0 | 715 | 0.001399 |
#
# Copyright 2009 Eigenlabs Ltd. http://www.eigenlabs.com
#
# This file is part of EigenD.
#
# EigenD is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EigenD. If not, se | e <http://www.gnu.org/licenses/>.
#
|
kouritron/uvs | libuvs/uvsconst.py | Python | bsd-3-clause | 2,870 | 0.006969 |
# this module tries to implement a replacement for python's lack of language enforced constants.
class _UVSConst(object):
# ------------------------------------------------------------------------------------------------------------------
# save the constants here
def _PASSWORD_PROMPT(self):
re... | a ValueError exception to emulate language enforced constants. """
raise ValueError("Can't change constants, don't try.")
# | ------------------------------------------------------------------------------------------------------------------
# declare them here for outside use
PASSWORD_PROMPT = property(_PASSWORD_PROMPT, _set_any_const)
MERGE3_CONFLICT_DELIMITER_START = property(_MERGE3_CONFLICT_DELIMITER_START, _set_any_const)
... |
garyForeman/LHBassClassifier | image_scrape/get_thumbnails.py | Python | agpl-3.0 | 3,278 | 0.00061 | #! /usr/bin/env python
"""
Author: Gary Foreman
Created: August 6, 2016
This script scrapes thumbnail images from thread links in the For Sale: Bass
Guitars forum at talkbass.com
"""
from __future__ import print_function
from glob import glob
import os
import sys
import urllib
from PIL import Image, ImageOps
import p... | l_url : a string with a url to a bass image
Strips filename from the end of thumbnail_url and prepends DATA_PATH.
Also ensures the file extension is jpg
"""
filename = thumbnail_url.strip('/').split('/')[-1]
basename, ext = os.path.splitext(filename)
return os.path.join(DATA_PATH, basename + '.... | ail_url):
"""
thumbnail_url : a string with a url to a bass image
Pulls dowm image from thumbnail_url and stores in DATA_DIR
"""
filename = filename_from_url(thumbnail_url)
try:
urllib.urlretrieve(thumbnail_url, filename)
except IOError:
# URL is not an image file
p... |
jwilson780/VirtualStockMarket | stockmarket/models.py | Python | mit | 2,038 | 0.008342 | from django.db import models
from django.contrib.auth.models import User
class StockStatus(models.Model):
date = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
change = models.FloatField()
volume = models.IntegerField()
average_daily_volume = models.IntegerField()
market_ca... | dels.FloatField()
price_to_earnings_growth_ratio = models.FloatField()
price_to_sales_ratio = models.FloatField()
price_to_book_ratio = models.FloatField()
class Stock(models.Model):
symbol = models.CharField(max_length=25)
exchange = models.CharField(max_length=25)
history = models.ManyToManyF... | f): return self.symbol
class Order(models.Model):
type = models.CharField(max_length=25)
amount = models.IntegerField()
stock = models.ForeignKey(Stock)
date = models.DateTimeField(auto_now_add=True)
def __unicode__(self): return u'%s %s' % (self.type, self.stock.symbol)
class Position(models... |
piw/pyCDL | pyCDL/route.py | Python | gpl-3.0 | 9,010 | 0 | import numpy as np
from definition import states_by_id
import pyproj as prj
class Route:
"""
A class of Breeding Bird Survey (BBS) route
Each Route includes the following members:
id - id number of the route
name - name of the route
stateID - to which state the route belong... | op_d = self.calc_stop()
self.stops2 = self.to_lonlat(self.stops)
else:
self.stops = np.array(())
self.stops2 = np.array(())
self.stop_d = 0.0
# output Route summary
print(self.summary())
def to_lonlat(self, pts):
"""
Convert c... | 5070 to EPSG:4326 (Longitude/Latitide)
"""
new_pts = np.zeros_like(pts)
# define input/output projections of lon/lat transformation
inProj = prj.Proj(init='epsg:5070') # Albers Equal Area
outProj = prj.Proj(init='epsg:4326') # Lat/Long Geodetic System
for i in range(... |
Honzin/ccs | tests/testAdapter/testOkcoincom/testTrades.py | Python | agpl-3.0 | 1,366 | 0.004392 | import unittest
import ccs
import time
####################################################################################################################
# OKCOINCOM #
##############################################... | e)
def testStock(self):
self.assertEqual(self.trades.stock(), self.stock)
def testMethod(se | lf):
self.assertEqual(self.trades.method(), ccs.constants.TRADES)
def testUsymbol(self):
self.assertEqual(self.trades.usymbol(), self.base + ":" + self.quote)
def testOsymbol(self):
pass
def testData(self):
pass
def testRaw(self):
pass
def testStr(self):
... |
marcosfede/algorithms | maths/prime_test.py | Python | gpl-3.0 | 1,595 | 0 | """
prime_test(n) returns a True if n is a prime number else it returns False
"""
import unittest
def prime_test | (n):
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6
return True
def prime_test2(n):
# prime numbers are gre... | for i in range(2, int(n ** 0.5) + 1):
if (n % i) == 0:
# print(num, "is not a prime number")
# print(i, "times", num//i, "is", num)
return False
# print(num, "is a prime number")
return True
# if input number is less than
# or equal t... |
pwldp/rodzice-na-czasie-pl | server/source_data/deleteCitiesWithoutSchool.py | Python | gpl-3.0 | 434 | 0.009217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import os.path
import sys
import time
#
from slughifi import *
import xlrd
#
from rncMongoDriver import rncMongoDB
#
#
#
#
| #
if __name__ == "__main__":
dburi = 'mongodb://uuuuu:ppppp@127.0.1:27017/rnc_production'
| rncdb = rncMongoDB(dburi,"rnc_production")
print rncdb
#
collCities = rncdb.mongoDB["cities"]
collCities.remove({"has_school":False})
#
# EOF
# |
tyrog236/site-perso | docs/conf.py | Python | mit | 7,708 | 0.007525 | # -*- coding: utf-8 -*-
#
# sammy documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 17 11:46:20 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# templat... | use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/desktop/libs/hadoop/src/hadoop/yarn/tests.py | Python | gpl-2.0 | 1,708 | 0.002342 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache Li | cense, 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 a... | for the specific language governing permissions and
# limitations under the License.
import logging
from nose.tools import assert_true, assert_equal, assert_not_equal
from hadoop.yarn import clients
LOG = logging.getLogger(__name__)
def test_get_log_client():
old_max_heap_size = clients.MAX_HEAP_SIZE
clients... |
jnewland/home-assistant | tests/components/ps4/test_config_flow.py | Python | apache-2.0 | 14,315 | 0 | """Define tests for the PlayStation 4 config flow."""
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.components import ps4
from homeassistant.components.ps4.const import (
DEFAULT_NAME, DEFAULT_REGION)
from homeassistant.const import (
CONF_CODE, CONF_HOST, CONF_IP... | ss):
"""Test registering an implementation and flow works."""
flow = ps4.PlayStation4FlowHandler()
flow.hass = hass
flow.location = MOCK_LOCATION
manager = hass.config_entries
# User Step Started, results in Step Creds
with patch('pyps4_homeassistant.Helper.port_bind',
return... | ow.RESULT_TYPE_FORM
assert result['step_id'] == 'creds'
# Step Creds results with form in Step Mode.
with patch('pyps4_homeassistant.Helper.get_creds',
return_value=MOCK_CREDS):
result = await flow.async_step_creds({})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
... |
mysociety/yournextmp-popit | candidates/migrations/0014_make_extra_slugs_unique.py | Python | agpl-3.0 | 789 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('candidates', '0013_remove_max_popit_ids'),
]
operations = [
migrations.AlterField(
model_name='organizatio | nextra',
name='slug',
field=models.CharField(unique | =True, max_length=256, blank=True),
),
migrations.AlterField(
model_name='partyset',
name='slug',
field=models.CharField(unique=True, max_length=256),
),
migrations.AlterField(
model_name='postextra',
name='slug',
fi... |
ssdi-drive/nuxeo-drive | nx_cx_Freeze/__init__.py | Python | lgpl-2.1 | 6,744 | 0.000445 | # coding: utf-8
"""
cx_Freeze extension
Extends:
- the 'build' command with the 'exe-command' option to allow using a
different command from 'build_exe' to build executables from Python scripts.
- the 'install' command with the 'skip-sub-commands' option to allow not
running a set of sub commands, e.g.:
install... | bdist_msi
class bdist_msi(cx_bdist_msi):
attribs = None
initial_target_dir = None
__licence = None
def finalize_options(self):
self.distribution.get_name()
| if self.initial_target_dir is None:
if distutils.util.get_platform() == 'win-amd64':
program_files_folder = 'ProgramFiles64Folder'
else:
program_files_folder = 'ProgramFilesFolder'
self.initial_target_dir = r'[%s]\%s' % (
... |
chipsecintel/chipsec | source/tool/chipsec/modules/tools/vmm/venom.py | Python | gpl-2.0 | 1,660 | 0.021687 | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#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 Fou | ndation; Version 2.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public Licens | e for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#Contact information:
#chipsec@intel.com
#
"""
QEMU VENOM vulnerability DoS PoC test... |
creasyw/IMTAphy | modules/nl/ip/PyConfig/ip/Tunnel.py | Python | gpl-2.0 | 3,273 | 0.001833 | ###############################################################################
# This file is part of openWNS (open Wireless Network Simulator)
# _____________________________________________________________________________
#
# Copyright (C) 2004-2007
# Chair of Communication Networks (ComNets)
# Kopernikusstr. 5, D-5... | 242
# email: info@openwns.org
# www: http://www.openwns.org
# _____________________________________________________________________________
#
# openWNS is free software; you can redistribute it | and/or modify it under the
# terms of the GNU Lesser General Public License version 2 as published by the
# Free Software Foundation;
#
# openWNS 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. Se... |
alexarnautu/deenux | src/deenuxapi/deezer/model/Track.py | Python | gpl-3.0 | 1,503 | 0.001331 | from src.deenuxapi.deezer.Model import Model
from src.deenuxapi.deezer.model.Artist import Artist
class Track(Model):
"""
Contains information about a track.
"""
def __init__(self, id: int, title: str, artist: Artist, duration: int = -1):
"""
Constructor of Track.
:param id: ... | return self.__title
@title.setter
def title(self, title: str):
self.__title = title
@property
def artist(self):
return self.__artist
@artist.setter
def artist(self, artist: Artist):
self.__artist = | artist
@property
def duration(self):
return self.__duration
@duration.setter
def duration(self, duration: int):
self.__duration = duration
|
daneoshiga/agoracommuns | agoracommuns/agoracommuns/core/tests/test_models.py | Python | mit | 582 | 0 | # -*- coding: utf-8 -*-
from django.test import TestCase
from model_mommy import mommy
from core.models import Agenda, Deliberation
class CoreModelsTests(TestCase):
def test_agenda_create(self):
agenda = mommy.make(Agenda)
self.assertTrue(isinstance(agenda, Agenda))
self.assertEqual(age... | liberation_create(self):
deliberation = mommy.make(Deliberation | )
self.assertTrue(isinstance(deliberation, Deliberation))
self.assertEqual(deliberation.__unicode__(), deliberation.proposal)
|
xutian/avocado-vt | virttest/tests/unattended_install.py | Python | gpl-2.0 | 63,456 | 0.000993 | from __future__ import division
import logging
import time
import re
import os
import tempfile
import threading
import shutil
import stat
import xml.dom.minidom
try:
import configparser as ConfigParser
except ImportError:
import ConfigParser
from avocado.core import exceptions
from avocado.utils import iso9660... | return unattended_file
if getattr(self, 'unattended_file'):
# Fail-back to general unattended_file
unattended_file = os.path.join(test.virtdir, self.unattended_file)
for backend in asset.get_known_backends():
found_file | = get_unattended_file(backend)
if found_file:
unattended_file = found_file
break
self.unattended_file = unattended_file
if getattr(self, 'finish_program'):
self.finish_program = os.path.join(test.virtdir,
... |
orionzhou/robin | old/nwk2txt.py | Python | gpl-2.0 | 718 | 0.01532 | #!/usr/bin/env python
import os
import os.path as op
import sys
import argparse
from Bio import Phylo
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description = 'extract leaf(tip) labels from newick tree file'
)
parser.add_argument(
'fi', nargs = '?', help = 'input file (new... | wick")
labels = []
for leaf in tree.get_terminals():
labels.append(leaf.name)
fho = open(fo, "w")
for label in reversed(labels):
fho.write(label + "\n")
fho.clos | e()
|
praekelt/vumi-go | go/apps/dialogue/vumi_app.py | Python | bsd-3-clause | 2,008 | 0 | # -*- test-case-name: go.apps.dialogue.tests.test_vumi_app -*-
import pkg_resources
import json
from vxsandbox import SandboxResource
from go.apps.jsbox.vumi_app import JsBoxConfig, JsBoxApplication
from go.apps.dialogue.utils import dialogue_js_config
class PollConfigResource(SandboxResource):
"""Resource tha... | """
return json.dumps(dialogue_js_config(conversation))
def _get_poll(self, conversation):
"""Returns the poll definition from the given dialogue.
:returns:
JSON string containing the poll definition.
"""
poll = conversation.config.get("poll")
ret... | s=False)
conversation = self.app_worker.conversation_for_api(api)
if key == "config":
value = self._get_config(conversation)
elif key == "poll":
value = self._get_poll(conversation)
else:
# matches what is returned for unknown keys by
# go.... |
aneumeier/category | oldcategory/urls.py | Python | bsd-3-clause | 1,181 | 0.008467 | #! /usr/bin/env python2.7
# -*- coding: utf-8 -*-
from django.conf.urls import url, patterns, include
from category.views import CategoryListView, CategoryCreateView, CategoryDetailView, CategoryUpdateView
from category.views import TagListView, TagDetailView, TagCreateView, TagUpdateView
urlpatterns = patterns('',... | ame="category-home-paginated"),
url(r'^category/add/$', CategoryCreateView.as_view(), name="category-add"),
u | rl(r'^category/(?P<slug>\w+)/$', CategoryDetailView.as_view(), name="category-view"),
url(r'^category/(?P<slug>\w+)/update$', CategoryUpdateView.as_view(), name="category-update"),
)
urlpatterns += patterns('',
url(r'^tag /$', TagListView.as_view(), name="tag-home"),
url(r'^tag/page/(?P<page>\w+)/$', TagLi... |
Lekensteyn/buildbot | master/buildbot/process/results.py | Python | gpl-2.0 | 2,689 | 0.000744 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | se:
return Results[status]
def worst_status(a, b):
# SKIPPED > SUCCESS > WARNINGS > FAILURE > EXCEPTION > RETRY > CANCELLED
# CANCELLED needs to be considered the worst.
for s in (CANCELLED, RETRY, EXCEPTION, FAILURE, WARNINGS, SUCCESS, | SKIPPED):
if s in (a, b):
return s
def computeResultAndTermination(obj, result, previousResult):
possible_overall_result = result
terminate = False
if result == FAILURE:
if not obj.flunkOnFailure:
possible_overall_result = SUCCESS
if obj.warnOnFailure:
... |
CELMA-project/CELMA | celma/testScan.py | Python | lgpl-3.0 | 1,495 | 0.040803 | #!/usr/bin/env python
"""Driver which checks that celma is properly running."""
import os, sys
# If we add to sys.path, then it must be an absolute path
commonDir = os.path.abspath("./../common")
# Sys path is a list of system paths
sys.path.append(commonDir)
from CELMAPy.scanDriver import ScanDriv | er
from bout_runners import basic_runner
|
directory = "CSDXMagFieldScanAr"
# Create object
scanB0 = ScanDriver(directory, runner = basic_runner)
# Set the scan
# NOTE: The scan must be in descending order in order for the growth
# rates post-processing to work
B0 = ( 1.0e-1)
Lx = ( 7.8633)
Ly = (275.2144)
scanParameters = ("B0", "Lx", "Ly")
series... |
ruibarreira/linuxtrail | usr/lib/python3.4/asyncio/test_utils.py | Python | gpl-3.0 | 11,895 | 0.000588 | """Utilities shared by tests."""
import collections
import contextlib
import io
import logging
import os
import re
import socket
import socketserver
import sys
import tempfile
import threading
import time
import unittest
from unittest import mock
from http.server import HTTPServer
from wsgiref.simple_server import WS... | # However, this isn't true for UNIX sockets,
# as | the second return value will be a path;
# hence we return some fake data sufficient
# to get the tests going
return request, ('127.0.0.1', '')
class SilentUnixWSGIServer(UnixWSGIServer):
def handle_error(self, request, client_address):
pass
class Unix... |
AIFDR/inasafe | safe/metadata/test/test_hazard_metadata.py | Python | gpl-3.0 | 886 | 0 | # coding=utf-8
"""Test Hazard | Metadata."""
from unittest import TestCase
from safe.common.utilities import unique_filename
from safe.metadata import HazardLayerMetadata
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
class TestHazardMetadata(TestCa... | d_properties(self):
metadata = HazardLayerMetadata(unique_filename())
with self.assertRaises(KeyError):
metadata.get_property('non_existing_key')
# from BaseMetadata
metadata.get_property('email')
# from HazardLayerMetadata
metadata.get_property('hazard')
... |
angea/corkami | wip/MakePE/examples/PE/max_sec.py | Python | bsd-2-clause | 3,885 | 0.003604 | # a generator for a PE with maximum number of section
# 199 sections confirmed working
SEC_NUMB = 199
SECTIONS_VSTART = 0x02000
f = open("max_sec.asm", "wt")
f.write("""; PE file with a maximum of sections
%include '..\..\consts.asm'
FILEALIGN equ 200h
SECTIONALIGN equ 1000h
org IMAGEBASE
istruc I... | 0
helloworld db "Hello World!", 0
;%%IMPORT user32.dll!MessageBoxA
;%%IMPORT kernel32.dll!ExitProcess
;%%IMPORTS
SECTION0VSIZE equ $ - Section0Start
end_:
align 200h, db 0
SECTION0SIZE equ $ - Section0Start
""" % locals())
for i in xrange(SEC_NUMB - 1):
f.write("""Section%(counter) | iStart equ %(RVA)i + IMAGEBASE
SECTION%(counter)iSIZE equ 0200h
SECTION%(counter)iVSIZE equ 1000h
jmp $ - 01000h
db 0h
align 200h, db 0
""" % {"counter":i + 1, "RVA": (i + 3)* 0x1000})
f.write("""
SIZEOFIMAGE equ %(sizeofimage)08Xh
;Ange Albertini, BSD Licence, 2011
""" % {"sizeofimage": SECTIONS_VSTART + S... |
tsdmgz/ansible | lib/ansible/modules/cloud/cloudstack/cs_securitygroup_rule.py | Python | gpl-3.0 | 12,777 | 0.00227 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | cidr == rule['cidr'])
def _get_rule(self, rules):
user_security_group_name = self.module.params.get('user_security_group')
cidr = self.module.params.get('cidr')
protocol = self.module.params.get('protocol')
start_port = self.module.params.get('start_port')
end_p... | 'start_port')
icmp_code = self.module.params.get('icmp_code')
icmp_type = self.module.params.get('icmp_type')
if protocol in ['tcp', 'udp'] and (start_port is None or end_port is None):
self.module.fail_json(msg="no start_port or end_port set for protocol '%s'" % protocol)
... |
lordnotfound404/404web | wp_joom.py | Python | gpl-2.0 | 4,272 | 0.034176 | import urllib
import os
import re
from time import sleep
from datetime import date
def welcome(modulename):
print """
|==========================================================|
|====================== [ 404 ] ========================|
|==============[ lordnotfound404@gmail.com ]==... | ttp://www.bing.com/search?q=ip%3A41.203 | .11.42+%22php%3Fid%3D%22&go=&qs=ds&form=QBLH&filt=all')
conf = open(con[0])
readd=conf.read()
find=re.findall('<h2><a href="(.*?)"',readd)
start = start+10
except IOError:
print "[ERROR]network error "
print "[Info]reconnecting "
sleep(10)
print "[Info]retrying "
... |
fdemian/Morpheus | api/Crypto.py | Python | bsd-2-clause | 288 | 0 | im | port bcrypt
def hash_password(password):
default_rounds = 14
bcrypt_salt = bcrypt.gensalt(default_rounds)
hashed_password = bcrypt.hashpw(password, bcrypt_salt)
return hashed_password
def check_password(pas | sword, hashed):
return bcrypt.checkpw(password, hashed)
|
bzzzz/cython | setup.py | Python | apache-2.0 | 12,175 | 0.005092 | from distutils.core import setup, Extension
fro | m distutils.sysconfig import get_python_lib
import os, os.path
import sys
if 'sdist' in sys.argv and sys.platform != "win32":
assert os.system("git show-ref -s HEAD > .gitrev") == 0
if sys.platform == "darwin":
# Don't create resource files on OS X tar.
os.environ['COPY_EXTENDED_ATTRIBUTES_DISABLE'] = 'tr... | )
cmdclasses[name] = cls
setup_args['cmdclass'] = cmdclasses
if sys.version_info[0] >= 3:
import lib2to3.refactor
from distutils.command.build_py \
import build_py_2to3 as build_py
# need to convert sources to Py3 on installation
fixers = [ fix for fix in lib2to3.refactor.get_fixers_fr... |
Egregors/django-autoslug-field | testautoslug/settings.py | Python | mit | 3,357 | 0.002085 | # Django settings for testautoslug project.
import os
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', ... | w how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.cont | rib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'testautoslug.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django... |
wikimedia/operations-debs-python-jsonschema | tests.py | Python | mit | 27,331 | 0.003439 | from __future__ import unicode_literals
from decimal import Decimal
import contextlib
import glob
import io
import json
import os
import re
import subprocess
import sys
if sys.version_info[:2] < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest
try:
from unittest import mock
e... | )
JSONSCHEMA_SUITE = os.path.join(THIS_DIR, "json", "bin", "jsonschema_suite")
REMOTES = subprocess.Popen(
["py | thon", JSONSCHEMA_SUITE, "remotes"], stdout=subprocess.PIPE,
).stdout
if PY3:
REMOTES = io.TextIOWrapper(REMOTES)
REMOTES = json.load(REMOTES)
def make_case(schema, data, valid):
if valid:
def test_case(self):
kwargs = getattr(self, "validator_kwargs", {})
validate(data, schema... |
GeoMatDigital/django-geomat | geomat/stein/migrations/0055_delete_classification_model.py | Python | bsd-3-clause | 313 | 0 | # Generated by Django 2. | 0.2 on 2018-02-03 17:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stein', '0054_delete_classification_relation'),
]
operations = [
migrations.DeleteModel(
name='Classification',
| ),
]
|
rneher/FitnessInference | flu/figure_scripts/flu_figures_inference.py | Python | mit | 12,931 | 0.024205 |
#########################################################################################
#
# author: Richard Neher
# email: richard.neher@tuebingen.mpg.de
#
# Reference: Richard A. Neher, Colin A Russell, Boris I Shraiman.
# "Predicting evolution from the shape of genealogical trees"
#
###################... | rgparse,sys
sys.path.append('/ebio/ag-neher/share/users/rneher/FluPrediction_code/flu/src')
import test_flu_prediction as test_flu
import analysis_utils as AU
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import scoreatpercentile
file_formats = [] #['.pdf', '.svg']
# set matplotlib plotting param... | ser.parse_args()
params.year='????'
params.sample_size = 100
D = params.diffusion = 0.5
gamma = params.gamma = 3.0
omega = params.omega = 0.001
params.collapse = False
metric = 'nuc'
# make file identifiers
base_name, name_mod = test_flu.get_fname(params)
#remove year
base_name = '_'.join(base_name.split('_')[:1]+base... |
mingjian2049/zstack-utility | cephbackupstorage/cephbackupstorage/cephagent.py | Python | apache-2.0 | 21,260 | 0.003057 | __author__ = 'frank'
import os
import os.path
import pprint
import traceback
import urllib2
import zstacklib.utils.daemon as daemon
import zstacklib.utils.http as http
import zstacklib.utils.jsonobject as jsonobject
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils.report import ... | err = '%s\n%s\nargs:%s' % (str(e), content, pprint.pformat([args, kwargs]))
rsp = AgentResponse()
rsp.success = False
rsp.error = str(e)
logger.warn(err)
return jsonobject.dumps(rsp)
return wrap
class CephAgent(object):
INIT_PATH = "/ceph/backupstorag... | ownload"
DELETE_IMAGE_PATH = "/ceph/backupstorage/image/delete"
PING_PATH = "/ceph/backupstorage/ping"
ECHO_PATH = "/ceph/backupstorage/echo"
GET_IMAGE_SIZE_PATH = "/ceph/backupstorage/image/getsize"
GET_FACTS = "/ceph/backupstorage/facts"
GET_IMAGES_METADATA = "/ceph/backupstorage/getimagesmeta... |
xxHACKYHACKYXx/hackathon-dpse | Rule booklet in Python/Setup.py | Python | gpl-2.0 | 875 | 0.012571 | """In the case that the Setup.py file fails to execute, please manually install the following packages,
or execute the requirements.sh script."""
# Installing Requirements: #
# pip install git+https://github.com/pwal | ler/pyfiglet #
# pip install colorama #
# pip install termcolor | #
# pip install blessings #
from distutils.core import setup
setup(name='DPS East Hackathon Rule booklet.',
version='1.0',
description='DPS East Hackathon Rule booklet.',
author='thel3l',
author_email='i.rithwik@protonmail.com... |
ygenc/onlineLDA | onlineldavb_new/build/scipy/scipy/optimize/tests/test_nonlin.py | Python | gpl-3.0 | 11,990 | 0.009091 | """ Unit tests for nonlinear solvers
Author: Ondrej Certik
May 2007
"""
from numpy.testing import assert_, dec, TestCase, run_module_suite
from scipy.optimize import nonlin
from numpy import matrix, diag, dot
from numpy.linalg import inv
import numpy as np
SOLVERS = [nonlin.anderson, nonlin.diagbroyden, nonlin.linea... | tisfies secant
co | nditions for last `npoints` points.
"""
jac = jac_cls(**kw)
jac.setup(self.xs[0], self.fs[0], None)
for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
jac.update(x, f)
for k in xrange(min(npoints, j+1)):
dx = self.xs[j-k+1] - self.xs[j-k]
... |
noironetworks/python-group-based-policy-client | gbpclient/tests/unit/test_cli20_natpool.py | Python | apache-2.0 | 4,756 | 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
# d... | ):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = | gbp.ShowNatPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_nat_pool(self):
"nat-pool-update myid --name myname --tags a b."
resource = 'nat_pool'
cmd = gbp.Up... |
erikmhauck/Bagster | gui/elements/__init__.py | Python | mit | 112 | 0 | from file_view_handler import FileHandler
from metadata_table import Metad | ataTable
from row_ite | m import RowItem
|
joberreiter/pyload | module/plugins/hoster/YourfilesTo.py | Python | gpl-3.0 | 2,040 | 0.006373 | # -*- coding: utf-8 -*-
import re
import urllib
from module.plugins.internal.Hoster import Hoster
class YourfilesTo(Hoster):
__name__ = "YourfilesTo"
__type__ = "hoster"
__version__ = "0.24"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?yourfiles\.(to|biz)/\? | d=\w+'
__description__ = """Youfiles.to hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("jeix", "jeix@hasnomail.de"),
("skydancer", "skydancer@hasnomail.de")]
def process(self, pyfile):
self.pyfile = pyfile
self.prepare()
self.download(sel... | self.pyfile.name = self.get_file_name()
self.wait(self.get_waiting_time())
def get_waiting_time(self):
if not self.html:
self.download_html()
#: var zzipitime = 15
m = re.search(r'var zzipitime = (\d+);', self.html)
if m is not None:
sec = int(m.g... |
holvi/python-stdnum | getmybp.py | Python | lgpl-2.1 | 3,036 | 0.001647 | #!/usr/bin/env python
# getmybp.py - script to donwnload data from Malaysian government site
#
# Copyright (C) 2013-2016 Arthur de Jong
#
# 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; ... | he hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHA | NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110... |
vbabiy/gedit-openfiles | gedit_openfiles/configuration.py | Python | gpl-2.0 | 1,698 | 0.002356 | from logger import log
import os
import gconf
import urllib
class Configuration(object):
def __init__(self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key... |
def set_value(self, key, value):
self._config[key] = value
self._write_file()
def _write_file(self):
f = file(self._file_path, "wb")
config_list = [("%s=%s\n" % (key, value)) for key,
value in self._config.iteritems()]
f.writelines(config_list)
f.cl... | le_path, "rb")
file_list = f.readlines()
f.close()
self._config = {} # reset config
for line in file_list:
line = line.strip()
if len(line) > 0:
name, value = line.split("=")
value = value.strip()
value = value.rep... |
jrutila/django-reportengine | reportengine/jsonfield.py | Python | bsd-3-clause | 5,953 | 0.003192 | """
Django JSON Field. This extends Django Model Fields to store JSON as a field-type.
"""
#TODO - Move this to utils or another application. This is tangential to reporting and useful for other things.
from django.db import models
try:
import json as simplejson
except ImportError:
from django.utils import s... | r:
val = None
return val
def south_field_triple(self):
"""
Returns a suitable description of this field for South."
:r | eturn: A tuple of field_class, args and kwargs from South's introspector.
"""
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django.db.models.fields.TextField"
args, kwargs = introspector(self)
# That's our defini... |
erdc-cm/air-water-vv | 2d/hydraulicStructures/sharp_crested_weir/deprecated/sharp_crested_weir_AV_V1/ls_n.py | Python | mit | 1,536 | 0.017578 | from proteus import *
from ls_p import *
if timeDiscretization=='vbdf':
timeIntegration = VBDF
timeOrder=2
stepController = Min_dt_cfl_controller
elif timeDiscretization=='flcbdf':
timeIntegration = FLCBDF
#stepController = FLCBDF_controller
stepController = Min_dt_cfl_controller
time_tol... | other = None
matrix = SparseMatrix
if useOldPETSc:
multilevelLinearSolver = PETSc
levelLinearSolver = PETSc
else:
| multilevelLinearSolver = KSP_petsc4py
levelLinearSolver = KSP_petsc4py
if useSuperlu:
multilevelLinearSolver = LU
levelLinearSolver = LU
linear_solver_options_prefix = 'ncls_'
nonlinearSolverConvergenceTest = 'r'
levelNonlinearSolverConvergenceTest = 'r'
linearSolverConvergenceTest = 'r... |
kiith-sa/QGIS | python/plugins/processing/saga/SagaHelpGenerator.py | Python | gpl-2.0 | 7,582 | 0.000528 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
***************************************************************************
SagaHelpGenerator.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com... | oice.Get_Item(i) for i in
range(parameterChoice.Get_Count())]
def getLibraryPaths(userPath=None):
try:
paths = os.environ['MLB_PATH'].split(':')
ex | cept KeyError:
paths = ['/usr/lib/saga/', '/usr/local/lib/saga/']
noMLBpath = True
if userPath:
paths = [userPath] + paths
print "Looking for libraries in " + ', '.join(paths)
for p in paths:
if os.path.exists(p):
return [os.path.join(p, fn) for fn in os.listdir(p... |
cernops/ceilometer | ceilometer/tests/unit/publisher/test_kafka_broker_publisher.py | Python | apache-2.0 | 8,865 | 0 | #
# Copyright 2015 Cisco Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ith mock.patch.object(publisher, '_producer') as fake_producer:
fake_producer.send_messages.side_effec | t = Exception("test")
publisher.publish_samples(mock.MagicMock(), self.test_data)
self.assertEqual(1, len(fake_producer.send_messages.mock_calls))
self.assertEqual(0, len(publisher.local_queue))
def test_publish_to_host_with_queue_policy(self):
publisher = kafka.KafkaBro... |
fberanizo/sin5016 | tests/test_db2.py | Python | bsd-2-clause | 7,829 | 0.007207 | # -*- coding: utf-8 -*-
from context import svm, mlp
import unittest, numpy
from os import listdir
from os.path import isfile, join
from scipy.io import loadmat
from sklearn.decomposition import PCA
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_scor... |
clf.fit(X, y)
# Validação com parâmetros ótimos de treino (5-fold)
validation_score = cross_val_score(clf, X=X, y=y, cv=skf_outer, | verbose=0, n_jobs=1)
print("SVM Linear - Acurácia de validação = %f" % validation_score.mean())
return clf
def train_svm_rbf(self, X, y):
"""Treina um SVM RBF e retorna o classificador treinado."""
clf = svm.SVM(kernel='rbf')
grid = {'C': [1], 'gamma': [0]}
# Realiza... |
DLR-SC/DataFinder | src/datafinder/core/configuration/properties/validators/base_validators.py | Python | bsd-3-clause | 13,874 | 0.010379 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#
#modification, are permitted provided that the following conditions are
#met:
#
... | e check.
"""
self.__inRangeValidator.minValue = _toDecimal(self.minValue)
self.__inRangeValidator | .maxValue = _toDecimal(self.maxValue)
self.__inRangeValidator(_toDecimal(value))
def _toDecimal(value):
""" Performs the conversion to C{decimal.Decimal}. """
if not isinstance(value, decimal.Decimal):
try:
value = decimal.Decimal(str(value))
except d... |
bayandin/Project-Euler | 20.py | Python | mit | 453 | 0 | #!/usr/b | in/env python
# -*- coding: utf-8 -*-
"""
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
http://projecteuler.net/problem=20
"""
factorial = 1
fo... | += int(i)
print result
|
BrianTrethewey/negui | neLineRegress/SimBatchRun.py | Python | agpl-3.0 | 11,399 | 0.02123 | import ConfigParser
import os
import re
from itertools import product
import LineRegress
import ResultScraper
def readconfig(filename):
## SETS DEFaULTS
#all defaults must be in a list even if only one value
speciesFile = ""
outFolder = ""
lineRegressConfig = ""
lambdas = [1.0]
startPopu... | = [int(value) for value in paramList]
##read in mutation Rate
if config.has_section("mutationRate"):
if config.has_option("mutationRate", "values"):
paramTemp = config.get("mutationRate", "values")
paramList = re.split(delimiters.paramTemp)
mutationRate = [float(valu... | paramTemp = config.get("lociSampleRate", "values")
paramList = re.split(delimiters.paramTemp)
lociSampling = [int(value) for value in paramList]
if config.has_section("individualSamplRate"):
if config.has_option("individualSamplRate", "values"):
paramTemp = config.get(... |
morinatsu/ZipCode | bin/make_loaddata.py | Python | mit | 2,655 | 0.001889 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""... | alcode
if line[2] != buff[2]:
return False
# include choume and not
if line[11] != buff[11]:
return False
# line contains touten(kana)
if line[5].count(u'、') != 0:
return True
if buff[5].count(u'、') != 0:
return True
... | line contains touten(kanji)
if line[8].count(u'、') != 0:
return True
if buff[8].count(u'、') != 0:
return True
return False
def merge(line, buff):
""" merge address of two lines """
new_buff = []
idx = 0
for element in line:
... |
ramaganapathy1/AMuDA-Ir-back-end | production/JVcode/Scripts/ForClassification/ela-sep.py | Python | mit | 2,166 | 0.017544 | import sys
from pymongo import MongoClient
from werkzeug.utils import secure_filename
import os
imp | ort sys
client = MongoClient('mon | godb://localhost:27017/')
db = client.ir
#li=[]
#color=open("AllColors.txt","r")
doc1=[]
doc2=[]
edgeConWT=[]
edgeElaWT=[]
edgeStart=[]
edgeEnd=[]
path="JVcode/Scripts/ForClassification/"
for file in os.listdir(path):
edgeElaWT = []
edgeConWT = []
edgeStart = []
edgeEnd = []
print (file)
if file... |
aslab/rct | higgs/branches/ros-groovy/higgs_gazebo_simulation/rqt_robot_plugins/rqt_robot_monitor/src/rqt_robot_monitor/robot_monitor.py | Python | gpl-3.0 | 24,412 | 0.000942 | # Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# 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... | _robot_monitor'), 'resource',
'robotmonitor_mainwidget.ui')
loadUi(ui_file, self, {'TimelinePane': TimelinePane})
#loadUi(ui_file, self)
obj_name = 'Robot Monitor'
self.setObject | Name(obj_name)
self.setWindowTitle(obj_name)
self._toplevel_statitems = [] # StatusItem
self._warn_statusitems = [] # StatusItem. Contains ALL DEGREES
# (device top level, device' _sub) in parallel
self._err_statusitems = [] # StatusItem
self.... |
laxmikantG/mypublisher | mypublisher/urls.py | Python | mit | 629 | 0.012719 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
# (r'^statinfo/$', 'appname.views.stat_info'),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', 'django.contrib... | enu'),
(r'^cmanager/$', 'mypublisher.views.content_manager'),
(r'^cmanager/upload$', 'mypub | lisher.views.render_upload_content'),
(r'^cmanager/upload/save$', 'mypublisher.views.save_content'),
) |
anhstudios/swganh | data/scripts/templates/object/tangible/component/dna/shared_dna_template_brackaset.py | Python | mit | 485 | 0.045361 | #### NOTICE: THI | S FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/dna/shared_dna_template_brackaset.iff"
result.attribute_template_id = -1
... | result |
mwgg/WeeChat-DeaDBeeF-np | deadbeef_np.py | Python | mit | 524 | 0.009542 | import commands
import weechat
def weechat_np(data, buffer, args):
read_track = commands.getoutput('deadbeef --nowplaying "%a - (%b) - %t [%@:BPS@bit / %@:BITRATE@kbps / %@: | SAMPLERATE | @Hz]"').split('\n')
weechat.command(buffer, '/me is currently listening to: ' + read_track[1])
return weechat.WEECHAT_RC_OK
weechat.register("deadbeef_np", "mwgg", "0.9", "MIT", "Show name of the song currently played by DeaDBeeF", "", "")
weechat.hook_command("np", "Get/send now playing info.", "", "", "", "w... |
ashbc/tgrsite | forum/models.py | Python | isc | 5,132 | 0.001559 | from django.db import models
from django.shortcuts import reverse
from users.models import Member
body_size = 32768
class Forum(models.Model):
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
blank=True, null=True,
related_name='subforums')
sort_index = models.I... | test_post(self):
return self. | thread_set.latest('pub_date')
def get_absolute_url(self):
return reverse("forum:subforum", args=(self.pk,))
# return self.thread_set.order_by('pub_date').reverse()[:1][::-1]
class Thread(models.Model):
# cascade because we need to be able to delete forums maybe?
# in which case forumless threads... |
mauodias/PyFuteBOT | configTemplate.py | Python | gpl-2.0 | 365 | 0.030137 | def __init__(self):
self.twitter = twitter()
self.facebook = | facebook()
self.core = core()
class twitter():
consumer_key='CONSUMER_KEY'
consumer_secret='CONSUMER_SECRET'
access_token_key='ACCESS_TOKEN_KEY'
access_token_secret='ACCESS_TOKEN_SECRET'
class facebook():
token='TOKEN'
group='GROUP_ID'
class core():
loopTime=60 | |
mclumd/lene | tests/ontology_tests/create_tests.py | Python | mit | 3,101 | 0.00387 | # tests.ontology_tests.create_tests
# Tests for the create functionality of the ontology
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: timestamp
#
# Copyright (C) 2014 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: create_tests.py [] benjamin@bengfort.com $
"""
Tests for the crea... | Plant | .bind(graph)
Flower.bind(graph)
Shrub.bind(graph)
# Create and bind an instance of a flower
instance = Flower.instantiate("Magnolia")
graph.add(instance)
self.assertIn(Plant.root, graph)
self.assertIn(Flower.root, graph)
self.assertIn(Shrub.root, graph)
... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/pip/_vendor/colorama/ansitowin32.py | Python | mit | 6,664 | 0.002101 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import re
import sys
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll
winterm = None
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
r... | AnsiFore.RESET: (winterm.fore, ),
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
AnsiBack.RED: (winterm.back, WinColor.RED),
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
AnsiBack.BLU... | olor.BLUE),
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
AnsiBack.RESET: (winterm.back, ),
}
def write(self, text):
if self.strip ... |
Kazade/NeHe-Website | google_appengine/google/appengine/ext/remote_api/remote_api_services.py | Python | bsd-3-clause | 17,948 | 0.001059 | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | tastore_v4': {
'AllocateIds': (datastore_v4_pb.AllocateIdsRequest,
| datastore_v4_pb.AllocateIdsResponse),
},
'file': {
'Create': (file_service_pb.CreateRequest,
file_service_pb.CreateResponse),
'Open': (file_service_pb.OpenRequest,
file_service_pb.OpenResponse),
'Close': (file_service_pb.CloseRequest,
... |
nop33/indico-plugins | chat/indico_chat/blueprint.py | Python | gpl-3.0 | 2,683 | 0.004473 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | chat', 'indico_chat', url_prefix='/event/<confId>')
# Event
blueprint.add_url_rule('/chat', 'event_page', RHChatEventPage)
# Event management
blueprint.add_url_rule('/manage/chat/', 'manage_rooms', RHChatManageEvent | )
blueprint.add_url_rule('/manage/chat/<int:chatroom_id>/', 'manage_rooms_modify', RHChatManageEventModify,
methods=('GET', 'POST'))
blueprint.add_url_rule('/manage/chat/<int:chatroom_id>/logs/', 'manage_rooms_logs', RHChatManageEventLogs)
blueprint.add_url_rule('/manage/chat/<int:chatroom_id>/lo... |
spacy-io/spaCy | spacy/cli/convert.py | Python | mit | 10,094 | 0.001684 | from typing import Optional, Any, List, Union
from enum import Enum
from pathlib import Path
from wasabi import Printer
import srsly
import re
import sys
import itertools
from ._util import app, Arg, Opt
from ..training import docs_to_json
from ..tokens import DocBin
from ..training.converters import iob_to_docs, conl... | output_file, data)
else:
with output_file.open("wb") as file_:
file_.write(data)
def autodetect_ner_format(input_data: str) -> Optional[str]:
# guess format from the first 20 lines
lines = input_data.split("\n")[:20]
format_guesses = {"ner": 0, "i | ob": 0}
iob_re = re.compile(r"\S+\|(O|[IB]-\S+)")
ner_re = re.compile(r"\S+\s+(O|[IB]-\S+)$")
for line in lines:
line = line.strip()
if iob_re.search(line):
format_guesses["iob"] += 1
if ner_re.search(line):
format_guesses["ner"] += 1
if format_guesses["io... |
civiclee/Hack4Cause2017 | src/snack-overflow/emcit/emcit/api/user.py | Python | mit | 1,756 | 0 | """User administration API"""
from flask import request, jsonify, Blueprint
from flask_login import current_user
from emcit.models import User
from emcit.resources import UserAdministrationResource
from emcit.util import required_access, api_error, validate
from emcit.schemas import user_schema
user_api = Blueprint('u... | er_id)
if not user:
return api_error('User not found', 404)
json = request.get_json()
if 'password' in request.json:
user.set_passw | ord(json.get('password'))
user.name = json.get('name')
user.email = json.get('email')
user.phone_number = json.get('phone_number')
user.role = json.get('role')
user.save()
return jsonify(UserAdministrationResource(user))
@user_api.route('/<int:id>', methods=['DELETE'])
@required_access('admi... |
mitmproxy/mitmproxy | test/mitmproxy/addons/test_modifyheaders.py | Python | mit | 6,005 | 0.000666 | import pytest
from mitmproxy.addons.modifyheaders import parse_modify_spec, ModifyHeaders
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy.test.tutils import tresp
def test_parse_modify_spec():
spec = parse_modify_spec("/foo/bar/voing", True)
assert spec.matches.pattern == "... | f.request.headers["one"] = "xxx"
mh.request(f)
assert "one" not in f.request.headers
f = tflow.tflow(resp=True)
f.response.headers["one"] = "xxx"
mh.response(f)
assert "one" not in f.respons | e.headers
tctx.configure(
mh,
modify_headers=[
"/one/"
]
)
f = tflow.tflow()
f.request.headers["one"] = "xxx"
mh.request(f)
assert "one" not in f.request.headers
f = ... |
arturh85/projecteuler | python/src/problem055.py | Python | mit | 2,561 | 0.001562 | # coding=utf-8
'''
Problem 55
24 October 2013
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Althou... | mber to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 | iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
--------------... |
VitalPet/c2c-rd-addons | c2c_reporting_tools_chricar/__terp__.py | Python | agpl-3.0 | 2,752 | 0.008727 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) Camptocamp SA
# Author: Arnaud WÃŒst
#
#
# This file is part of the c2c_report_tools module.
#
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the w... | by getting ride of uncecessary parsing and transfo | rmations (direct python to pdf generation)
- To improve reporting capabilities by getting ride of uncomplete parsers and limited middle technologies
- To make reports designs more uniform
For exemples of use, have a look at c2c_planning... |
abhishekkr/tutorials_as_code | talks-articles/machine-learning/google-courses/prework--numpy-ultraquick-tutorial.py | Python | mit | 2,051 | 0.006338 | """
## NumPy UltraQuick Tutorial
[source](https://colab.research.google.com/github/google/eng-edu/blob/main/ml/cc/exercises/numpy_ultraquick_tutorial.ipynb?utm_source=mlcc)
> create/manipulate vectors and matrices
"""
## import module as
import numpy as np
## populate array with specific numbers
### 'np.array' to... | nd_2 * 100.0
"""
Task.1 Create a Linear Dataset
to create a simple dataset consisting single feature and label
* assign int sequence from 6 to 20 to a NumPy array name 'feature'
* assign 15 values to NumPy array named 'label' as: 'label = (3) (feature) + 4'; as first value be '(3) (6) + 4 = 22'
"""
feature = np.ara... | re)
label = (feature * 3) + 4.0
print(label)
"""
Task.2 Add some noise to the dataset
to mae dataset realistic; insert random noise to each element of 'label' array
* modify each value assigned to 'label' by adding different random float between -2/+2 without 'broadcasting'
instead create noise array having same d... |
cheungpat/sqlalchemy-utils | tests/functions/test_analyze.py | Python | bsd-3-clause | 936 | 0 | from sqlalchemy_utils import analyze
from tests import TestCase
class TestAnalyzeWithPostgres(TestCase):
dns = 'postgres://postgres@localhost/s | qlalchemy_utils_test'
def test_runtime(self):
query = self.session.query(self.Article)
assert analyze(self.connection, query).runtime
def test_node_types_w | ith_join(self):
query = (
self.session.query(self.Article)
.join(self.Article.category)
)
analysis = analyze(self.connection, query)
assert analysis.node_types == [
u'Hash Join', u'Seq Scan', u'Hash', u'Seq Scan'
]
def test_node_types_with... |
andreymal/mini_fiction | mini_fiction/validation/news.py | Python | gpl-3.0 | 1,013 | 0.000987 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from mini_fiction.validation.utils import bool_coerce, safe_string_coerce, safe_string_multiline_coerce
NEWS_ITEM = {
'name': {
'type': 'string',
'coerce': safe_string_coerce,
'required': True,
'minlength': 1,
'maxlength': 64,... | alse,
'minlength': 1,
'maxlength': 192,
'default': '',
},
'content': {
'type': 'string',
'coerce': safe_string_multiline_coerce,
'required': True,
'minlength': 0,
'maxlength': 65535, |
},
'is_template': {
'type': 'boolean',
'coerce': bool_coerce,
'required': False,
'default': False,
},
'show': {
'type': 'boolean',
'coerce': bool_coerce,
'required': False,
'default': False,
},
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.