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 |
|---|---|---|---|---|---|---|---|---|
GuidoSchmidt/juli | src/models/list.py | Python | gpl-2.0 | 928 | 0 | #!/usr/bin/env python3
from app.app import db
class List(db.Model):
id = db.Column(db.Integer, primary_key=True)
locked = db.Column(db.Boolean)
weightclass_id = db.Column(db.Integer,
db.ForeignKey("weightclass.id"))
weightclass = db.relationship("Weightclass",
... | lazy="dynamic"))
def __init__(self, weightclass):
self.weightclass = weightclass
self.weightclass_id = weightclass.id
self.locked = False
def __repr__(self):
return "<List {} [locked: {}]>"\
.format(self.weightclass, self.l... | s": self.weightclass.name,
"locked": self.locked
}
|
girving/tensorflow | tensorflow/python/ops/ctc_ops.py | Python | apache-2.0 | 13,730 | 0.002185 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | lapsed by the decoder.
* `preprocess_collapse_repeated=True`, `ctc_merge_repeated=False`
Never learns to output repeated classes, as they are collapsed
in the input labels before training.
* `preprocess_collapse_repeated=False`, `ctc_merge_repeated=False`
Outputs repeated classes with blanks in betw... | eated classes.
* `preprocess_collapse_repeated=True`, `ctc_merge_repeated=True`
Untested. Very likely will not learn to output repeated classes.
The `ignore_longer_outputs_than_inputs` option allows to specify the behavior
of the CTCLoss when dealing with sequences that have longer outputs than
inputs. ... |
fajoy/nova | nova/openstack/common/rpc/impl_zmq.py | Python | apache-2.0 | 22,999 | 0.000217 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Cloudscaling Group, 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/LI... | self.can_recv:
raise RPCException(_("You cannot recv on this socket."))
return self.sock.recv_multipart()
def send | (self, data):
if not self.can_send:
raise RPCException(_("You cannot send on this socket."))
self.sock.send_multipart(data)
class ZmqClient(object):
"""Client for ZMQ sockets."""
def __init__(self, addr, socket_type=zmq.PUSH, bind=False):
self.outq = ZmqSocket(addr, socket... |
winiciuscota/OG-Bot | ogbot/scraping/movement.py | Python | mit | 3,821 | 0.003664 | from bs4 import BeautifulSoup
from datetime import datetime
from scraper import *
from general import General
def get_arrival_time(arrival_time_str):
time = datetime.strptime(arrival_time_str.strip(), '%H:%M:%S').time()
now = datetime.now()
arrival_time = datetime.combine(now, time)
return arrival_tim... | lass": "countDown"})
is_friendly = 'friendly' in count_down_td.attrs['class']
arrival_time_str = movement_row.find("td", {"class": "arrivalTime"}).text
arrival_time = get_arrival_time(arrival_time_str)
countdown_time = self.get_countdown_time(arrival_time) |
movement = FleetMovement(origin_coords, origin_planet_name, dest_coords, dest_planet_name, is_friendly,
arrival_time, countdown_time)
fleet_movements.append(movement)
return fleet_movements
def get_countdown_time(self, arrival_time):
g... |
realizeapp/realize-core | core/commands/frontend.py | Python | agpl-3.0 | 1,248 | 0.004006 | from flask.ext.script import Command, Manager, Option
from flask import current_app
import os
from subprocess import Popen
class InvalidPathException(Exception):
pass
class SyncJS(Command):
option_list = (
Option('--path', '-p', dest='path'),
)
def run_command(self, command):
cmd = P... | th(os.path.join(current_app.config['REPO_PATH'], current_app.con | fig['FRONTEND_PATH']))
for the_file in os.listdir(current_app.config['FRONTEND_PATH']):
file_path = os.path.join(current_app.config['FRONTEND_PATH'], the_file)
try:
if os.path.isfile(file_path) and the_file != ".vc":
os.unlink(file_path)
ex... |
naveensan1/nuage-openstack-neutron | nuage_neutron/plugins/common/service_plugins/l3.py | Python | apache-2.0 | 57,131 | 0.000035 | # Copyright 2016 NOKIA
#
# 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 language governing permissions and limitations
# under the License.
import copy
from logging import handlers
import netaddr
from nuage_neutron.plugins.common import constants
from nuage_neutron.plugins.common import excepti... |
dnalexander/CMPM146_P7 | p7_driver.py | Python | gpl-3.0 | 2,598 | 0.051193 | import subprocess
import json
import collections
import random
import sys
def parse_json_result(out):
"""Parse the provided JSON text and extract a dict
representing the predicates described in the first solver result."""
result = json.loads(out)
assert len(result['Call']) > 0
assert len(result['Call'][0]['Witn... | am['width']
block = ''.join([''.join([str(touch[r,c])+' ' for c in range(width)])+'\n' for r in range(width)])
return block
def side_by_side(*blocks):
"""Horizontally merge two ASCII-art pictures."""
lines = []
fo | r tup in zip(*map(lambda b: b.split('\n'), blocks)):
lines.append(' '.join(tup))
return '\n'.join(lines)
def main():
map = solve()
print side_by_side(render_ascii_dungeon(map), *[render_ascii_touch(map,i) for i in range(1,4)])
main() |
houshengbo/nova_vmware_compute_driver | nova/utils.py | Python | apache-2.0 | 39,324 | 0.000509 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
#... | gs.pop('attempts', 1)
run_as_root = kwargs.pop('run_as_root', False)
shell = kwargs.pop('shell', False)
if len(kwargs):
raise exception.NovaException(_('Got unknown keyword args '
| 'to utils.execute: %r') % kwargs)
if run_as_root and os.geteuid() != 0:
cmd = ['sudo', 'nova-rootwrap', CONF.rootwrap_config] + list(cmd)
cmd = map(str, cmd)
while attempts > 0:
attempts -= 1
try:
LOG.debug(_('Running cmd (subprocess)... |
gion86/awlsim | awlsim/core/instructions/insn_gt_d.py | Python | gpl-2.0 | 1,598 | 0.015645 | # -*- coding: utf-8 -*-
#
# AWL simulator - instructions
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# 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 Licen | se, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a ... | __future__ import division, absolute_import, print_function, unicode_literals
from awlsim.common.compat import *
from awlsim.core.instructions.main import * #@nocy
from awlsim.core.operators import *
#from awlsim.core.instructions.main cimport * #@cy
class AwlInsn_GT_D(AwlInsn): #+cdef
__slots__ = ()
def __init... |
jptomo/rpython-lang-scheme | rpython/jit/backend/x86/test/test_list.py | Python | mit | 256 | 0.003906 |
from rpython.jit.metainterp.test.test_list imp | ort ListTests
from rpython.jit.backend.x86.test.test_basic import Jit386Mixin
class TestList(Jit386Mixin, ListTest | s):
# for individual tests see
# ====> ../../../metainterp/test/test_list.py
pass
|
Conjuror/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | Python | mpl-2.0 | 12,568 | 0.002387 | import ConfigParser
import datetime
import os
import posixpath
import re
import shutil
import tempfile
import time
import traceback
from mozdevice import adb
from mozlog.structured import get_default_logger
here = os.path.split(__file__)[0]
class WaitTimeout(Exception):
pass
class DeviceBackup(object):
de... | # has changed for flame-kk builds.
set_date = datetime.datetime.fromtimestamp(set_date)
self.shell_output("touch -t %s %s" %
(set_date.strftime('%Y%m%d.%H%M%S'),
prefs_f | ile))
def prefs_modified():
times = [None, None]
def inner():
try:
listing = self.shell_output("ls -l %s" % (prefs_file))
mode, user, group, size, date, time, name = listing.split(None, 6)
mtime = "%s %s" % (da... |
sunlaiqi/fundiy | src/shop/views.py | Python | mit | 1,636 | 0.005501 | from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import RequestContext
# Create your views here.
from django.views.generic import ListView, DetailView
from .models import Category, Product
from cart.forms import CartAddProductForm
def category_list(request):
return... | l()
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
cart_product_form = CartAddProductForm()
return render(request,
'shop/product_det | ail.html',
{'product': product,
'nodes': categories,
'cart_product_form': cart_product_form}) |
edx/credentials | credentials/wsgi.py | Python | agpl-3.0 | 559 | 0 | """
WSGI config for credentials.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1 | .8/howto/deployment/wsgi/
"""
import os
from os.path import abspath, dirname
from sys import path
from dja | ngo.core.wsgi import get_wsgi_application
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "credentials.settings.local")
application = get_wsgi_application() # pylint: disable=invalid-name
|
saltstack/salt | salt/cloud/clouds/cloudstack.py | Python | apache-2.0 | 17,835 | 0.000729 | """
CloudStack Cloud Module
=======================
The CloudStack cloud module is used to control access to a CloudStack based
Public Cloud.
:depends: libcloud >= 0.15
Use of this module requires the ``apikey``, ``secretkey``, ``host`` and
``path`` parameters.
.. code-block:: yaml
my-cloudstack-cloud-config:
... | in place
def __virtual__():
"""
Set up the libcloud functions and check for CloudStack configurations.
"""
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
| return __virtualname__
def _get_active_provider_name():
try:
return __active_provider_name__.value()
except AttributeError:
return __active_provider_name__
def get_configured_provider():
"""
Return the first configured instance.
"""
return config.is_provider_configured(
... |
lot9s/pathfinder-rpg-utils | data-mining/bestiary/db/creatureDB.py | Python | mit | 6,403 | 0.00531 | '''A module containing a class for storing Creature objects in a
SQLite database.'''
import csv
import sqlite3
__all__ = ['CreatureDB']
class CreatureDB(object):
'''Class for storing Creature objects in a SQLite database.'''
def __init__(self, name='creature.db', use_nominal_cr=Fa | lse):
self.min_cr = 0.0
self.max_cr = float('inf')
# set flags
self.using_nominal_cr = use_nominal_cr
# initialize database
self.connection = sqlite3.connect(name)
self.connection.text_factory = str
self._create_table()
def _construct_table_column... | the columns in
the "creatures" table
:returns tuple that defines the columns in "creatures" table
'''
columns = ('id integer primary key autoincrement',
'name varchar(45)')
# set type of CR column depending on flag
if self.using_nominal_cr:
... |
karllessard/tensorflow | tensorflow/python/keras/feature_column/sequence_feature_column_test.py | Python | apache-2.0 | 28,269 | 0.003007 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e reordered alphabetically.
sequence_input_layer = ksfc.SequenceFeatures(
[embedding_column_b, em | bedding_column_a])
input_layer, sequence_length = sequence_input_layer({
'aaa': sparse_input_a, 'bbb': sparse_input_b,})
self.evaluate(variables_lib.global_variables_initializer())
weights = sequence_input_layer.weights
self.assertCountEqual(
('sequence_features/aaa_embedding/embedding_... |
memo/tensorflow | tensorflow/python/layers/core_test.py | Python | apache-2.0 | 14,077 | 0.006607 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | .Dense(4, name='my_dense')
dense(inputs)
def testActivation(self):
dense = core_layers.Dense(2, activation=nn_ops.relu, name='dense1')
inputs = random_ops.random_uniform((5, 3), seed=1)
outputs = dense(inputs)
self.assertEqual(outputs.op.name, 'dense1/Relu')
dense = core_layers.Dense(2, name... |
def testActivityRegularizer(self):
regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3
dense = core_layers.Dense(
2, name='my_dense', activity_regularizer=regularizer)
inputs = random_ops.random_uniform((5, 3), seed=1)
_ = dense(inputs)
loss_keys = ops.get_collection(ops.GraphKeys.REGUL... |
snicoper/snicoper.com | tests/unit/base_test.py | Python | mit | 2,024 | 0 | import json
import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
UserModel = get_user_model()
class BaseTestCase(TestCase):
"""Utilidades para todos los tests relacionados con el sitio.
Incluye Fixtures para los modelos, propiedades a lo... | test_settings = settings
self.user = self.user_model.objects.get(pk=1)
def login(self, username=None, password=None):
"""Login de usuario.
Si no se pasan username y password usara por defecto self.user.username
y 123 respectivamente.
Args:
username (str): Nombr... | password (str): Password de usuario.
Returns:
bool: True si loguea, False en caso contrario.
"""
username = self.user.username if username is None else username
password = '123' if password is None else password
return self.client.login(username=username, passw... |
its-lab/MoniTutor-Tunnel | start_couchDB_resultwriter.py | Python | gpl-3.0 | 2,457 | 0.002849 | import argparse
import logging
import signal
import time
from server.couchDB_resultwriter import CouchDbResultWriter as ResultWriter
import sys
import os
from utils import daemonize
from utils import get_logger
from utils import configure_logging
parser = argparse.ArgumentParser(description="MoniTunnel server")
parser... | DEBUG")
parser.add_argument("-l", "--logging", action="store_true", help="Write messages to syslog instead of stdout. Increase verbosity of logs with -v")
parser.add_argument("-t", "--task-exchange", default="task_exchange", help="Name of the task exchange")
parser.add_argument("-r", "--result-exchange", default="resul... | lp="Name of the result exchange")
parser.add_argument("-d", "--daemonize", action="store_true", help="Start as daemon")
parser.add_argument("-i", "--couch-db-url", default="http://couchdb:5984", help="CouchDB server API url")
parser.add_argument("-u", "--couch-db-user")
parser.add_argument("-p", "--couch-db-password")
... |
prefetchnta/questlab | bin/x64bin/python/37/Lib/tracemalloc.py | Python | lgpl-2.1 | 17,610 | 0.000227 | from collections.abc import Sequence, Iterable
from functools import total_ordering
import fnmatch
import linecache
import os.path
import pickle
# Import types and functions implemented in C
from _tracemalloc import *
from _tracemalloc import _get_object_traceback, _get_traces
def _format_size(size, sign... | stat.count, stat.count - previous.count)
else:
stat = StatisticDiff(traceback,
stat.size, stat.size,
| stat.count, stat.count)
statistics.append(stat)
for traceback, stat in old_group.items():
stat = StatisticDiff(traceback, 0, -stat.size, 0, -stat.count)
statistics.append(stat)
return statistics
@total_ordering
class Frame:
"""
Frame of a... |
mmagnus/rna-pdb-tools | rna_tools/tools/rna_filter/rna_get_dists.py | Python | gpl-3.0 | 9,035 | 0.006419 | #!/usr/bin/env python
"""rna_filter.py - calculate distances based on given restrants on PDB files or SimRNA trajectories.
The format of restraints::
(d:A1-A2 < 10.0 1) = if distance between A1 and A2 lower than 10.0, score it with 1
Usage::
$ python rna_filter.py -r test_data/restraints.txt -s test_data/C... | 8, 29 | .321, 42.618]), "O3'": array([ 53.272, 24.698, 44.789]), 'C4': array([ 54.313, 29.909, 40.572])}}
"""
V = {}
with open(pdb_fn) as f:
for line in f:
if line.startswith("ATOM"):
curr_chain_id = line[21]
curr_resi = int(line[22: 26])
curr... |
backtrace-labs/backtrace-python | tests/__init__.py | Python | mit | 3,903 | 0.003587 | import simplejson as json
import os
import subprocess
import sys
import unittest
if sys.version_info.major >= 3:
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
else:
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
tests_dir = o... | _POST(self):
self.send_response(200)
self.end_headers()
payload = self.rfile.read()
json_string = payload.decode('utf-8', 'strict')
non_local.json_object = json.l | oads(json_string)
def log_message(self, format, *args):
pass
httpd = HTTPServer(requested_server_address, RequestHandler)
host, port = httpd.server_address
exe_path = os.path.join(exe_dir, exe_name)
stdio_action = None if debug_backtrace else subprocess.PIPE
child = subprocess... |
abhishek-ch/hue | desktop/core/src/desktop/conf.py | Python | apache-2.0 | 37,361 | 0.009716 | #!/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 License, Version 2.0 (the
# "License"); you ma... | lp=_("Use poll(2) in Hue thrift pool."),
type=coerce_bool,
private=True,
default=True | )
MIDDLEWARE = Config(
key="middleware",
help=_("Comma-separated list of Django middleware classes to use. " +
"See https://docs.djangoproject.com/en/1.4/ref/middleware/ for " +
"more details on middlewares in Django."),
type=coerce_csv,
default=[])
REDIRECT_WHITELIST = Config(
key="redire... |
Drachenfels/Game-yolo-archer | server/api/outfits.py | Python | gpl-2.0 | 228 | 0 | # -*- coding: utf-8 -*-
def outfit():
collection = []
| for _ in range(0, 5):
collection.append("Item{}".format(_))
return | {
"data": collection,
}
api = [
('/outfit', 'outfit', outfit),
]
|
Romibuzi/cleo | cleo/inputs/list_input.py | Python | mit | 4,973 | 0.000804 | # -*- coding: utf-8 -*-
from .input import Input
class ListInput(Input):
"""
ListInput represents an input provided as an array.
Usage:
>>> input_ = ListInput([('name', 'foo'), ('--bar', 'foobar')])
"""
def __init__(self, parameters, definition=None):
"""
Constructor
... | rtcut).get_name(), value)
def add_long_option(self, name, value):
"""
Adds a long option value
@param name: The long option key
@type name: str
@param value: The value for the option
@type value: mixed
"""
if not self.definition.has_option(name):
... | ion.is_value_required():
raise Exception('The "--%s" option requires a value.' % name)
value = option.get_default() if option.is_value_optional() else True
self.options[name] = value
def add_argument(self, name, value):
"""
Adds an argument value
@para... |
rodekruis/shelter-database | src/web/views/session_mgmt.py | Python | mit | 5,400 | 0.003704 | #! /usr/bin/env python
#-*- coding: utf-8 -*-
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Shelter Database.
# Copyright (c) 2016 Luxembourg Institute of Science and Technology.
# All rights reserved.
#
#
#
# ***** END LICENSE BLOCK *****
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.2 $"
__d... | )
form = LoginForm()
#signup = SignupForm()
return render_template(
'login.html',
humanitarian_id_auth_uri=conf.HUMANITARIAN_ID_AUTH_URI,
client_id=conf.HUMANITARIAN_ID_CLIENT_ID,
redirect_uri=conf.HUMANITARIAN_ID_REDIRECT_URI,
loginForm=form #, si... | =['POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
flash('You are logged in', 'info')
login_user_bundle(form.user)
return form.redirect('index')
#signup = SignupForm()
return ren... |
tzpBingo/github-trending | codespace/python/tencentcloud/tione/v20191022/models.py | Python | mit | 91,250 | 0.002541 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | f.KeyPrefix = None
self.DataDistributionType = None
self.DataType = None
def _deserialize(self, params) | :
self.Bucket = params.get("Bucket")
self.KeyPrefix = params.get("KeyPrefix")
self.DataDistributionType = params.get("DataDistributionType")
self.DataType = params.get("DataType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name ... |
marc-sensenich/ansible | lib/ansible/modules/network/fortios/fortios_webfilter_urlfilter.py | Python | gpl-3.0 | 12,762 | 0.001254 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2018 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | vdom:
description: Virtual do | main used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
fos = None
def login(data):
host = data['host']
username = data['username']
password = da... |
notapresent/rbm2m | rbm2m/action/stats.py | Python | apache-2.0 | 2,721 | 0 | # -*- coding: utf-8 -*-
from sqlalchemy import func, distinct
from sqlalchemy.orm import aliased
from sqlalchemy.sql.expression import literal
from rbm2m.models import Record, Image, Scan, Genre, scan_records
def get_overview(sess):
"""
Returns aggregated statistics about records, scans, genres etc
""... | Returns list of scans currently in progress, along with
current record count for each scan
"""
rec_count = (
sess.query(func.count(scan_records.c.record_id))
.filter(scan_records.c. | scan_id == Scan.id)
.correlate(Scan)
.as_scalar()
)
rows = (
sess.query(Scan.id, Scan.started_at, Scan.est_num_records,
rec_count.label('num_records'), Genre.title)
.join(Genre, Genre.id == Scan.genre_id)
.filter(Scan.status == 'running')
... |
evernym/zeno | plenum/test/consensus/order_service/test_can_send_3pc.py | Python | apache-2.0 | 5,936 | 0.002695 | import pytest
from plenum.common.startable import Mode
def test_can_send_3pc_batch_by_primary_only(primary_orderer):
assert primary_orderer.can_send_3pc_batch()
primary_orderer._data.primary_name = "SomeNode:0"
assert not primary_orderer.can_send_3pc_batch()
def test_can_send_3pc_batch_not_participatin... | rderer, initial_s | eq_no, monkeypatch):
monkeypatch.setattr(primary_orderer._config, 'Max3PCBatchesInFlight', None)
primary_orderer.last_ordered_3pc = (primary_orderer.view_no, initial_seq_no)
primary_orderer._lastPrePrepareSeqNo = initial_seq_no + 10
assert primary_orderer.can_send_3pc_batch()
@pytest.mark.parametrize(... |
warisb/derpbox | DerpBox/file_utils.py | Python | mit | 1,062 | 0 | #!/usr/bin/env python
"""file_utils.py: convenient file operations used by derpbox"""
__author__ = "Waris Boonyasiriwat"
__copyright__ = "Copyright 2017"
import os
import hashlib
def md5(filename):
hash_md5 = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b"")... | sh_md5.update(chunk)
return hash_md5.hexdigest()
def create_file_obj(id, root_path, path):
| file_obj = {
'id': id,
'path': path,
'isDirectory': os.path.isdir(root_path + path),
}
if not file_obj['isDirectory']:
file_obj['hash'] = md5(root_path + path)
return file_obj
def get_paths_recursive(root_path):
paths = []
for root, dirs, files in os.walk(root_path)... |
Colviz/Vince | groups/group_server.py | Python | apache-2.0 | 2,451 | 0.020808 | #!/usr/bin/python
from subprocess import call
import sys
import os
from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
###Broadcast according to client group
#Show ports associated with a particular group
file = "group_port.txt" ... | #[2] - multicast (using for broadcasting), [3] - file with list of IP's,on which to broadcast
###Writing server's IP to file
#Taking the ip as input from server_ip file - just for reference
fp = open("ser | ver_ip","r")
ip = fp.read()
fp.close()
written = 0
ipp = ip
#Checking if IP already exists
fl = open(file_name,'r')
lines = fl.readlines()
for line in lines:
if line == ipp:
written = 1
fl.close()
#If not written then write IP to file
if written !=1:
file = open(file_name,"a")
file.write(ip)
file.close... |
neversun/sailfish-hackernews | pyPackages/python_firebase-noarch/firebase/firebase.py | Python | mit | 16,320 | 0.001287 | try:
import urlparse
except ImportError:
#py3k
from urllib import parse as urlparse
import json
from .firebase_token_generator import FirebaseTokenGenerator
from .decorators import http_connection
from .multiprocess_pool import process_pool
from .jsonutil import JSONEncoder
__all__ = ['FirebaseAuthentic... | at is appended to the URL like a querystring.
`headers`: Python dict. HTTP request headers.
`connection`: Predefined HTTP connection instance. If not given, it
is supplied by the `decorators.http_connection` function.
The returning value is a Py | thon dict deserialized by the JSON decoder. However,
if the status code is not 2x or 403, an requests.HTTPError is raised.
connection = connection_pool.get_available_connection()
response = make_put_request('http://firebase.localhost/users/',
'{"Ozgur Vatansever"}', {'X_FIREBASE_SOMETHING': 'Hi'}, c... |
khchine5/xl | lino_xl/lib/contacts/choicelists.py | Python | bsd-2-clause | 272 | 0.003676 | # -*- coding: UTF-8 -*-
# | Copyright 2016 Luc Saffre
# License: BSD (see file COPYING for details)
from lino.api im | port dd, _
class PartnerEvents(dd.ChoiceList):
verbose_name = _("Observed event")
verbose_name_plural = _("Observed events")
max_length = 50
|
Lilykos/invenio | invenio/celery/tasks.py | Python | gpl-2.0 | 1,196 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... |
# You should have received a copy of the GNU General Public License
# alon | g with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
from invenio.celery import celery
@celery.task
def invenio_version():
""" Task that will return the current running Invenio version """
from invenio.base.globals import cfg
return... |
laginha/django-easy-response | src/easy_response/decorators.py | Python | mit | 366 | 0.005464 | from .utils.process import to_http
from .consts import BASIC_SERIALIZATION
def serialization(basic=BASIC_SERIALIZATION):
def decorator(view):
def wrapper(request, *args, **kwargs):
response = view(request, *args, ** | kwargs)
| return to_http(request, response, basic_serialization=basic)
return wrapper
return decorator
|
commaai/openpilot | selfdrive/car/interfaces.py | Python | mit | 9,765 | 0.009421 | import os
import time
from abc import abstractmethod, ABC
from typing import Dict, Tuple, List
from cereal import car
from common.kalman.simple_kalman import KF1D
from common.realtime import DT_CTRL
from selfdrive.car import gen_empty_fingerprint
from selfdrive.config import Conversions as CV
from selfdrive.controls.l... | trol.Actuators, List[bytes]]:
pass
def create_common_events(self, cs_out, extra_gears=None, pcm_enable=True):
events = Events()
if cs_out.doorOpen:
events.add(EventName.doorOpen)
if cs_out.seatbeltUnlatched:
events.add(EventName.seatbeltNotLatched)
if cs_out.gearShifter | != GearShifter.drive and (extra_gears is None or
cs_out.gearShifter not in extra_gears):
events.add(EventName.wrongGear)
if cs_out.gearShifter == GearShifter.reverse:
events.add(EventName.reverseGear)
if not cs_out.cruiseState.available:
events.add(EventName.wrongCarMode)
if cs_out.... |
tatsy/hydra | hydra/tonemap/durand.py | Python | mit | 1,367 | 0.008047 | """
Implementation of the paper,
Durand and Dorsey SIGGGRAPH 2002,
"Fast Bilateral Fitering for the display of high-dynamic range images"
"""
import numpy as np
import hydra.io
import hydra.filters
def bilateral_separation(img, sigma_s=0.02, sigma_r=0.4):
r, c = img.shape
sigma_s = max(r, c) * sigma_s
... |
max_log_base = np.max(log_base)
log_detail = np.log10(Ldetail)
compression_factor = np.log(target_contrast) / (max_log_base - np.min(log_base))
log_absolute = compression_factor * max_log_base
log_compressed = log_base * compression_factor + log_detail - log_absolute
output = np.power(10.0, ... | range(3):
ret[:,:,c] = tmp[:,:,c] * output
ret = np.maximum(ret, 0.0)
ret = np.minimum(ret, 1.0)
return ret
|
Fierydemise/ShadowCraft-Engine | tests/objects_tests/race_tests.py | Python | lgpl-3.0 | 2,806 | 0.003207 | import unittest
from shadowcraft.objects import race
class TestRace(unittest.TestCase):
def setUp(self):
self.race = race.Race('human')
def test__init__(self):
self.assertEqual(self.race.race_name, 'human')
self.assertEqual(self.race.character_class, 'rogue')
def test_set_racials(... | ertEqual(worgen.get_racial_crit('gun'), 0.01)
self.assertEqual(worgen.get_racial_crit('axe'), 0.01)
def test_get_racial_haste(self):
self.assertEqual(self.race.get_racial_haste(), 0)
goblin = race.Race('goblin')
self.assertEqual(goblin.get_racial_haste(), 0.01)
def test_get_rac... | osts(self):
self.assertEqual(len(self.race.get_racial_stat_boosts()), 0)
orc = race.Race('orc')
orc.level = 110;
abilities = orc.get_racial_stat_boosts()
self.assertEqual(len(abilities), 2)
self.assertEqual(abilities[0]['duration'], 15)
self.assertTrue(abilities[1... |
lovekun/Notebook | python/chatroomServer.py | Python | gpl-2.0 | 654 | 0.003058 | import socket
import threading
import time
def tcplink(sock, addr):
print 'Accept new connection from %s:%s...' % addr
sock.send('Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if data == 'exit' or not data:
break
sock.send('Hello, %s!' | % data)
sock.close()
print 'Connection from %s:%s closed.' % addr
s = socket.socket(so | cket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
print 'Waiting for connection...'
while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
|
ysekky/GPy | GPy/kern/src/multidimensional_integral_limits.py | Python | bsd-3-clause | 6,207 | 0.020622 | # Written by Mike Smith michaeltsmith.org.uk
from __future__ import division
import numpy as np
from .kern import Kern
from ...core.parameterization import Param
from paramz.transformations import Logexp
import math
class Multidimensional_Integral_Limits(Kern): #todo do I need to inherit from Stationary
"""
I... | ariance between observed values.
s and t are one domain of the integral (i.e. the integral between s and t)
sprime and tprime are another domain of the integral (i.e. the integral between sprime and tprime)
We're interested in how correlated these two integrals are.
Note: We've not mu... | .g((t - tprime)/l) - self.g((s-sprime)/l))
def k_ff(self,t,tprime,l):
"""Doesn't need s or sprime as we're looking at the 'derivatives', so no domains over which to integrate are required"""
return np.exp(-((t-tprime)**2)/(l**2)) #rbf
def k_xf(self,t,tprime,s,l):
"""Covariance between ... |
QiJune/Paddle | python/paddle/trainer_config_helpers/tests/configs/projections.py | Python | apache-2.0 | 2,317 | 0 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | ayer() as m6:
m6 += dotmul_operator(a=m3, b=m4)
m6 += scaling_projection(m3)
img = data_layer(name='img', size=32 * 32)
flt = data_layer(name='filter', size=3 * 3 * 1 * 64)
with mixed_layer() as m7:
m7 += conv_operator(
img=img, filter=flt, num_filters=64, num_channels=1, filter_size=3)
m7 += ... | rs=64, num_channels=1)
with mixed_layer() as m8:
m8 += conv_operator(
img=img,
filter=flt,
num_filters=64,
num_channels=1,
filter_size=3,
stride=2,
padding=1,
trans=True)
m8 += conv_projection(
img,
filter_size=3,
num_filte... |
jenskutilek/Glyphs-Scripts | Glyphs/DecRO.py | Python | mit | 292 | 0.006849 | # MenuTitle: Copy to Background, Decompose, Remove Overlaps, Correct Path Direction
for layer in Glyphs.font.selectedLayers:
g = layer.parent
for l in g.layers:
l.background = l.copy()
l.decomposeComponents()
l.rem | oveOverlap()
l.correctPathDirection()
| |
paulftw/titan-files | tests/files/dirs_test.py | Python | apache-2.0 | 5,379 | 0.001487 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | )
# Test chronological ordering, even with out-of-order arguments.
path1 = dirs.ModifiedPath(
'/a/b/foo', modified=123123.0, action=PATH_DELETE_ACTION)
path2 = dirs.ModifiedPath(
'/a/b/foo', modified=123123.2, action=PA | TH_WRITE_ACTION)
path3 = dirs.ModifiedPath(
'/a/b/foo', modified=123123.1, action=PATH_DELETE_ACTION)
affected_dirs = dir_service.ComputeAffectedDirs([path1, path2, path3])
expected_affected_dirs = {
'dirs_with_adds': set(['/a', '/a/b']),
'dirs_with_deletes': set(),
}
self.as... |
lockwooddev/django-perseus | django_perseus/renderers/default.py | Python | mit | 2,589 | 0.001159 | from django.conf import settings
from django.test.client import Client
from .base import BaseRenderer
from django_perseus.exceptions import RendererException
import logging
import mimetypes
import os
logger = logging.getLogger('perseus')
class DefaultRenderer(BaseRenderer):
def render_path(self, path=None, v... | xists
deploy_dir = settings.PERSEUS_SOURCE_DIR
outpath = os.path.join(deploy_dir, '')
if not os.path.exists(deploy_dir):
os.makedirs(depl | oy_dir)
# create index page
if path == '/':
response, mime = self.render_page(path)
outpath = os.path.join(outpath, 'index{0}'.format(mime))
self.save_page(response, outpath)
return
# strip paths to ready them for mime... |
mfcovington/django-lab-members | lab_members/migrations/0013_advisor_url.py | Python | bsd-3-clause | 517 | 0.001934 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lab_members', '0012_sci | entist_email'),
]
operations = [
migrations.AddField(
model_name='advisor',
name='url',
field=models.URLField(help_text="Please enter advisor's websi | te", null=True, blank=True, verbose_name='advisor website'),
preserve_default=True,
),
]
|
CarlFK/veyepar | dj/main/migrations/0002_auto_20160116_2028.py | Python | mit | 1,005 | 0.002985 | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Mark',
fields=[
('id', models.AutoField(verbose_name... | o='main.Location')),
('show', models.ForeignKey(to='main.Show')),
],
options={
},
bases=(models.Model,),
),
migrations.AlterField(
model_name='episode',
name='edit_key',
field=models.CharField(default=b'6... | t=True,
),
]
|
nextgis-extra/tests | lib_gdal/ogr/ogr_gpsbabel.py | Python | gpl-2.0 | 4,660 | 0.00515 | #!/usr/bin/env python
###############################################################################
# $Id: ogr_gpsbabel.py 33793 2016-03-26 13:02:07Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read functionality for OGR GPSBabel driver.
# Author: Even Rouault <even dot rouault at mines dash paris ... | lyr = No | ne
ds = None
f = open('tmp/nmea.txt', 'rt')
res = f.read()
f.close()
gdal.Unlink('tmp/nmea.txt')
if res.find('$GPRMC') == -1 or \
res.find('$GPGGA') == -1 or \
res.find('$GPGSA') == -1:
gdaltest.post_reason('did not get expected result')
print(res)
return... |
JQIamo/artiq | artiq/test/lit/interleaving/error_inlining.py | Python | lgpl-3.0 | 447 | 0.008949 | # RUN: %python -m artiq.compiler.testbench.signature +diag %s >%t
# RUN: OutputCheck %s --file-to-check=%t
def f():
delay_mu(2)
def g():
delay_mu(2)
x = f if True else g
def h():
with interleave:
f()
# CHECK-L: ${LINE:+1}: fatal: it is | not possible to interleave this function call within a 'with interleave:' statement because the compiler could not prove that the same funct | ion would always be called
x()
|
malishevg/edugraph | lms/djangoapps/django_comment_client/helpers.py | Python | agpl-3.0 | 926 | 0.007559 | from django.conf import settings
from mako.template import Template
import os
def include_mustache_templates():
mustache_dir = settings.PROJECT_ROOT / 'templates' / 'discussion' / 'mustache'
def is_valid_file_name(file_name):
return file_name.endswith('.mustache')
def read_file(file_name):
... | ode()
def make_script_tag(id, content):
return u"<script type='text/template' id='{0}'>{1}</script>".format(id, content)
return u'\n'.join(
make_script_tag(template_id_from_file_name(file_name), process_mako(read_file(file_name)))
for file_name in os.listdir(mustache_dir)
if is_ | valid_file_name(file_name)
)
|
knuu/competitive-programming | hackerrank/algorithm/two_arrays.py | Python | mit | 221 | 0.004525 | for _ in range(int(input())):
| N, K = map(int, input().split())
print("YES" if all(a + b >= K for a, b in zip(sorted(int(x) for x in input().split()) | , reversed(sorted(int(x) for x in input().split())))) else "NO")
|
fladi/drf-haystack | drf_haystack/serializers.py | Python | mit | 10,695 | 0.002525 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import copy
import warnings
from itertools import chain
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from haystack import fields as haystack_fields
from haystack.query import EmptySearchQuerySet
... | "attribute on the serializer Meta class.")
| except AttributeError:
raise ImproperlyConfigured("%s must implement a Meta class." % self.__class__.__name__)
if not self.instance:
self.instance = EmptySearchQuerySet()
@staticmethod
def _get_default_field_kwargs(model, field):
"""
Get the required attributes... |
alexhersh/calico | calico/felix/test/__init__.py | Python | apache-2.0 | 659 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Metaswitch Networks
#
| # 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... | S,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
_log = logging.getLogger(__name__)
|
zalax303/test_django | myforum/article/models.py | Python | apache-2.0 | 786 | 0.01752 | # coding:utf-8
from django.contrib.auth.model | s import User
from django.db import models
from block.models import Block
# Create your models here.
class Article(model | s.Model):
block = models.ForeignKey(Block, verbose_name=u"所属板块")
owner = models.ForeignKey(User, verbose_name=u"作者")
title = models.CharField(verbose_name=u"标题", max_length=100)
content = models.CharField(verbose_name=u"内容", max_length=10000)
status = models.IntegerField(verbose_name=u"状态", choices=((0, u"普通"), (-... |
TonyApuzzo/fuzzyjoin | fuzzyjoin-hadoop/src/test/scripts/plot/timeline.py | Python | apache-2.0 | 2,845 | 0.027768 | #!/usr/bin/env python
#
# Copyright 2010-2011 The Regents of the University of California
#
# Licensed under the Apache License, V | ersion 2.0 (the "License"); you
# may not use thi | s 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 A... |
mineo/picard | picard/ui/infodialog.py | Python | gpl-2.0 | 15,013 | 0.001666 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# 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... | ages
if obj.metadata.images:
self.images = obj.metadata.images
if not self.images and self.existing_images:
self.images = self.existing_images
self.existing_images = []
| self.display_existing_artwork = False
self.ui.setupUi(self)
self.ui.buttonBox.addButton(
StandardButton(StandardButton.CLOSE), QtWidgets.QDialogButtonBox.AcceptRole)
self.ui.buttonBox.accepted.connect(self.accept)
# Add the ArtworkTable to the ui
self.ui.artwork_tabl... |
wangyixiaohuihui/spark2-annotation | python/pyspark/sql/utils.py | Python | apache-2.0 | 4,112 | 0.001946 | #
# 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 n... | ommand.
"""
class IllegalArgumentException(CapturedException):
"""
Passed an illegal or inappropriate argument.
"""
class Streaming | QueryException(CapturedException):
"""
Exception that stopped a :class:`StreamingQuery`.
"""
class QueryExecutionException(CapturedException):
"""
Failed to execute a query.
"""
def capture_sql_exception(f):
def deco(*a, **kw):
try:
return f(*a, **kw)
... |
autotest/virt-test | shared/scripts/dd.py | Python | gpl-2.0 | 310 | 0 | import sys
import os
if | len(sys.argv) != 3:
print "Useage: %s path size"
path = sys.argv[1]
size = int(sys.argv[2])
if not os.path.isdir(os.path.dirname(path)):
os.mkdir(os.path.dirname(path))
writefile = open(path, 'w')
writefile.seek(1024 * 1024 * size)
writefile.write('\x00') |
writefile.close()
|
artefactual/archivematica-storage-service | storage_service/locations/models/space.py | Python | agpl-3.0 | 35,298 | 0.00187 | # stdlib, alphabetical
from __future__ import absolute_import
import datetime
import errno
import logging
import os
import re
import shutil
import stat
import subprocess
import tempfile
# Core Django, alphabetical
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.transla... | _STORAGE = {DATAVERSE, DSPACE, DSPACE_REST, DURACL | OUD, SWIFT, S3}
ACCESS_PROTOCOL_CHOICES = (
(ARKIVUM, _("Arkivum")),
(DATAVERSE, _("Dataverse")),
(DURACLOUD, _("DuraCloud")),
(DSPACE, _("DSpace via SWORD2 API")),
(DSPACE_REST, _("DSpace via REST API")),
(FEDORA, _("FEDORA via SWORD2")),
(GPG, _("GPG encrypt... |
akesandgren/easybuild-framework | test/framework/module_generator.py | Python | gpl-2.0 | 69,283 | 0.003464 | ##
# Copyright 2012-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | (topdir, 'easyconfigs', 'test_ecs', 'g', 'gzip', 'gzip-1.4.eb')
eb_full_pa | th = find_full_path(eb_path)
self.assertTrue(eb_full_path)
ec = EasyConfig(eb_full_path)
self.eb = EasyBlock(ec)
self.modgen = self.MODULE_GENERATOR_CLASS(self.eb)
self.modgen.app.installdir = tempfile.mkdtemp(prefix='easybuild-modgen-test-')
self.orig_module_naming_sch... |
openqt/algorithms | projecteuler/pe489-common-factors-between-two-sequences.py | Python | gpl-3.0 | 506 | 0.018182 | #!/usr/bin/env python
# coding=utf-8
""" | 489. Common factors between two sequences
https://p | rojecteuler.net/problem=489
Let G(a, b) be the smallest non-negative integer n for which gcd(n3 \+ b, (n
\+ a)3 \+ b) is maximized.
For example, G(1, 1) = 5 because gcd(n3 \+ 1, (n \+ 1)3 \+ 1) reaches its
maximum value of 7 for n = 5, and is smaller for 0 ≤ n < 5.
Let H(m, n) = Σ G(a, b) for 1 ≤ a ≤ m, 1 ≤ b ≤ n.... |
facelessuser/sublime-markdown-popups | st3/mdpopups/pymdownx/smartsymbols.py | Python | mit | 5,483 | 0.002371 | """
Smart Symbols.
pymdownx.smartsymbols
Really simple plugin to add support for:
copyright, trademark, and registered symbols
plus/minus, not equal, arrows via:
copyright = `(c)`
trademark = `(tm)`
registered = `(r)`
plus/minus = `+/-`
care/of = `c/o`
fractions = `1/2` etc.
... | 2|3)th|1st|2nd|3rd|[04-9]th)
\b
''',
lambda m: '%s%s<sup>%s</sup>' % (
m.group('leading') if m.group('leading') else '',
| m.group('tail')[:-2], m.group('tail')[1:]
)
)
RE_ARROWS = (
"smart-arrows",
r'(?P<arrows>\<-{2}\>|(?<!-)-{2}\>|\<-{2}(?!-))',
lambda m: ARR[m.group('arrows')]
)
RE_FRACTIONS = (
"smart-fractions",
r'(?<!\d)(?P<fractions>1/4|1/2|3/4|1/3|2/3|1/5|2/5|3/5|4/5|1/6|5/6|1/8|3/8|5/8|7/8)(?!\d)',
... |
pratapvardhan/pandas | pandas/tests/scalar/period/test_asfreq.py | Python | bsd-3-clause | 36,821 | 0 | import pytest
from pandas.errors import OutOfBoundsDatetime
import pandas as pd
from pandas import Period, offsets
from pandas.util import testing as tm
from pandas._libs.tslibs.frequencies import _period_code_map
class TestFreqConversion(object):
"""Test frequency conversion of date objects"""
@pytest.mark... | ival_Q_to_A = Period(freq='A', year=2007)
ival_Q_to_M_start = Period(freq='M', year=2007, month=1)
ival_Q_to_M_end = Period(freq='M', year=2007, month=3)
ival_Q_to_W_start = Period(freq='W', year=2007, month=1, day=1)
ival_Q_to_W_end = Period(freq='W', year=2007, month=3, day=31)
... | al_Q_to_B_end = Period(freq='B', year=2007, month=3, day=30)
ival_Q_to_D_start = Period(freq='D', year=2007, month=1, day=1)
ival_Q_to_D_end = Period(freq='D', year=2007, month=3, day=31)
ival_Q_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)
ival_Q_to_H_end = Period(fre... |
trendelkampschroer/msmtools | msmtools/analysis/dense/correlations.py | Python | lgpl-3.0 | 10,071 | 0.001986 |
# This file is part of MSMTools.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# MSMTools 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 ... | observable 2 on discrete states. If not given,
the autocorrelation of obs1 will be computed
pi : ndarray, shape=(n)
stationary distributio | n vector. Will be computed if not given
times : array-like, shape(n_t)
Vector of time points at which the (auto)correlation will be evaluated
Returns
-------
"""
n_t = len(times)
times = np.sort(times) # sort it to use caching of previously computed correlations
f = np.zeros(n_t)
... |
UKPLab/sentence-transformers | examples/training/quora_duplicate_questions/training_multi-task-learning.py | Python | apache-2.0 | 9,356 | 0.007482 | """
This script combines training_OnlineContrastiveLoss.py with training_MultipleNegativesRankingLoss.py
Online constrative loss works well for classification (are question1 and question2 duplicates?), but it
performs less well for duplicate questions mining. MultipleNegativesRankingLoss works well for duplicate
quest... | eader:
train_samples_ConstrativeLoss.append(InputExample(texts=[row['question1'], row['question2']], label=int(row['is_duplicate'])))
if row['is_duplicate'] == '1':
train_samples_MultipleNegativesRankingLoss.append(InputExample(texts=[row['question1'], row['question2']], label=1))
... | les_MultipleNegativesRankingLoss.append(InputExample(texts=[row['question2'], row['question1']], label=1)) # if A is a duplicate of B, then B is a duplicate of A
# Create data loader and loss for MultipleNegativesRankingLoss
train_dataloader_MultipleNegativesRankingLoss = DataLoader(train_samples_MultipleNegativesRan... |
mtury/scapy | scapy/layers/tls/handshake.py | Python | gpl-2.0 | 61,432 | 0 | # This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# This program is published under a GPLv2 license
"""
TLS handshake fields & logic.
This module covers the handshake TLS subprotocol, except for the key exchange
mechanisms which are addressed wi... | SigAndHashAlgsField, _tls_hash_sig,
| SigAndHashAlgsLenField)
from scapy.layers.tls.session import (_GenericTLSSessionInheritance,
readConnState, writeConnState)
from scapy.layers.tls.crypto.compression import (_tls_compression_algs,
_tls_compression_algs_cls,
... |
AXAz0r/apex-sigma-core | sigma/modules/help/donate.py | Python | gpl-3.0 | 1,698 | 0.0053 | import discord
async | def donate(cmd, message, args):
if args:
if args[0] == 'mini':
mini = True
else:
mini = False
else:
mini = False
sigma_image = 'https://i.imgur.com/mGyqMe1.png'
sigma_title = 'Sigma Donation Information'
patreon_url = 'https: | //www.patreon.com/ApexSigma'
paypal_url = 'https://www.paypal.me/AleksaRadovic'
support_url = 'https://discordapp.com/invite/aEUCHwX'
if mini:
response = discord.Embed(color=0x1B6F5F, title=sigma_title)
donation_text = f'Care to help out? Come support Sigma on [Patreon]({patreon_url})!'
... |
SpazioDati/python-dandelion-eu | tests/base.py | Python | gpl-2.0 | 4,228 | 0 | """ tests can be run from the root dir with:
clean-pyc && \
APP_ID= APP_KEY= coverage run --source=. --branch `which nosetests` tests/* &&\
coverage html
"""
import os
from unittest import TestCase
from mock import patch
from dandelion import Datagem, DandelionException, DataTXT, default_config
from dandelion.base im... | cmethod
def _make_class(require_auth=True, implement_abstract=False):
class TestCla | ss(BaseDandelionRequest):
REQUIRE_AUTH = require_auth
def _get_uri_tokens(self):
if implement_abstract:
return ['']
return super(TestClass, self)._get_uri_tokens()
return TestClass
def test_abstract_methods(self):
with se... |
amaozhao/basecms | cms/test_utils/project/placeholderapp/models.py | Python | mit | 3,065 | 0.001305 | from cms.utils.urlutils import admin_reverse
from django.core.urlresolvers import reverse
from cms.utils import get_language_from_request
from cms.utils.compat.dj import python_2_unicode_compatible
from django.db import models
from cms.models.fields import PlaceholderField
from hvad.models import TranslatableModel, Tra... | if self.pk:
self.static_admin_url = admin_reverse('placeholderapp_example1_edit_field', args=(self.pk, language))
return self.pk
def dynamic_url(self, request):
language = get_language_from_request(request)
return admin_reverse('placeholderapp_example1_edit_field', args=(self... | char_1 = models.CharField(u'char_1', max_length=255)
char_2 = models.CharField(u'char_2', max_length=255)
char_3 = models.CharField(u'char_3', max_length=255)
char_4 = models.CharField(u'char_4', max_length=255)
placeholder_1 = PlaceholderField('placeholder_1', related_name='p1')
placeholder_2 = Pl... |
linebp/pandas | bench/better_unique.py | Python | bsd-3-clause | 2,143 | 0 | from __future__ import print_function
from pandas import DataFrame
from pandas.compat import range, zip
import timeit
setup = """
from pandas import Series
import pandas._tseries as _tseries
from pandas.compat import range
import random
import numpy as np
def better_unique(values):
uniques = _tseries.fast_unique(... | imer(stmt='_tseries.fast_unique(arr)',
setup=setup % sz)
numpy_timer = timeit.Timer(stmt='np.unique(arr)',
setup=setup % sz)
print(n)
num | py_result = numpy_timer.timeit(number=n) / n
wes_result = wes_timer.timeit(number=n) / n
print('Groups: %d, NumPy: %s, Wes: %s' % (sz, numpy_result, wes_result))
wes.append(wes_result)
numpy.append(numpy_result)
result = DataFrame({'wes': wes, 'numpy': numpy}, index=group_sizes)
def make_plot(numpy... |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py | Python | apache-2.0 | 15,699 | 0.001784 | """FAQ Wizard customization module.
Edit this file to customize the FAQ Wizard. For normal purposes, you
should only have to change the FAQ section titles and the small group
of parameters below it.
"""
# Titles of FAQ sections
SECTION_TITLES = {
# SectionNumber : SectionTitle; need at least one ent... | ROR = "Sorry, an error occurred"
T_ROULETTE = FAQNAME + " Roulette"
T_ALL = "The Whole " + FAQNAME
T_INDEX = FAQNAME + " Index"
T_SEARCH = FAQNAME + " Search Results"
T_RECENT = "What's New in the " + FAQNAME
T_SHOW = FAQNAME + " Entry"
T_LOG = "RCS log for %s entry" % FAQNAME
T_REVISION = "RCS revision for %s ... | E = "Deleting an entry from the " + FAQNAME
T_EDIT = FAQNAME + " Edit Wizard"
T_REVIEW = T_EDIT + " - Review Changes"
T_COMMITTED = T_EDIT + " - Changes Committed"
T_COMMITFAILED = T_EDIT + " - Commit Failed"
T_CANTCOMMIT = T_EDIT + " - Commit Rejected"
T_HELP = T_EDIT + " - Help"
# Generic prologue and epilog... |
sasmita/upm | examples/python/grovewfs.py | Python | mit | 2,489 | 0.002009 | #!/usr/bin/python
# Author: Zion Orent <zorent@ics.com>
# Copyright (c) 2015 Intel Corporation.
#
# 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 limi... | s as upmGrovewfs
def main():
# Instantiate a Grove Water Flow Sensor on digital pin D2
myWaterFlow = upmGrovewfs.GroveWFS(2)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function let... | # including functions from myWaterFlow
def exitHandler():
myWaterFlow.stopFlowCounter()
print("Exiting")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# set the flow counter to 0 and start counting
myWaterF... |
fbuitron/FBMusic_ML_be | BATCH/PlaylistAPI.py | Python | apache-2.0 | 1,427 | 0.006307 | from Networking import Networking
from Model import Playlist
from SpotifyAPI import SpotifyAPI
import Security
import json
class PlaylistAPI(SpotifyAPI):
base_url = "https://api.spotify.com"
def __init__(self, categoryID):
super(PlaylistAPI, self).__init__()
self.list_of_playlist = []
... | = json_obj['playlists']['items']
for item_index in range(len(list_of_items)):
playlist_json = json_obj['playlists']['items'][item_index]
| p = Playlist.Playlist(playlist_json)
self.list_of_playlist.append(p)
def failure(error):
print(error.content)
self.stillPaging = False
if self.hasPaging():
self.stillPaging = True
i = 0
while(self.stillPaging):
... |
gleseur/room-status | detector/daemon.py | Python | mit | 1,629 | 0.006139 | u"""
This is the daemon that must be launched in order to detect motion
and launch signals.
"""
from __future__ import unicode_literals
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from detection import PirDetector
from busy_processor import RoomBusyStatus
import settings
# Importing motion listeners
... | ETECTION_PAIRS.iteritems():
print "Initializing pair {}".format(pair_name)
detector = PirDetector(values["pir"], pair_name)
detector.setup()
detectors.append(detector)
# Subscribing listeners
rbs = RoomBusyStatus(pair_name, values["free_time"], values["lock_time"], detect... | s["room_id"], rbs)
return detectors, room_statuses
def run_daemon():
detectors, room_statuses = initialize_detection_pairs()
while True:
for detector in detectors:
detector.detect_motion()
for room_status in room_statuses:
room_status.check_idle()
time.sleep(... |
ehenneken/adsws | adsws/tests/test_factory.py | Python | gpl-2.0 | 1,777 | 0.011255 | from adsws.testsuite import make_test_suite, \
run_test_suite, AdsWSAppTestCase, FlaskAppTestCase, AdsWSTestCase
import os
import inspect
import tempfile
class FactoryTest(FlaskAppTestCase):
@property
def config(self):
return {
'SQLALCHEMY_DATABASE_URI' : 'sqlite://',
'... | instance_path = tempfile.mkdtemp()
with open(os.path.join(instance_path, 'loca | l_config.py'), 'w') as fo:
fo.write("BAR='baz'\n")
self._config['instance_path'] = instance_path
return self._config
def test_custom_config(self):
rootf = os.path.realpath(os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), '../../adsw... |
neutronpy/neutronpy | neutronpy/data/analysis.py | Python | mit | 8,726 | 0.00149 | # -*- coding: utf-8 -*-
import numbers
import numpy as np
from ..constants import BOLTZMANN_IN_MEV_K
from ..energy import Energy
class Analysis(object):
r"""Class containing methods for the Data class
Attributes
----------
detailed_balance_factor
Methods
-------
integrate
position
... | hkle : bool, optional
If True, integrates only over h, k, l, e dimensions, otherwise
integrates over all dimensions in :py:attr:`.Data.data`
Returns
-------
| result : float
The integrated intensity either over all data, or within
specified boundaries
"""
result = 0
for key in self.get_keys(hkle):
result += np.trapz(self.intensity[self.get_bounds(bounds)] - self.estimate_background(background),
... |
PyIran/website | project/database.py | Python | gpl-3.0 | 2,785 | 0.023339 | # coding: utf-8
import datetime
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.orm.session import sessionmaker
import imp
from migrate.versioning import api
engine = create_engine('sqlite:///py... | BASE_URI = 'sqlite:///pyiran.db'
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
Base = declarative_base()
Base.query = db_session.query_property()
| def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
Base.metadata.create_all(bind=engine)
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRA... |
wubr2000/googleads-python-lib | examples/dfa/v1_20/add_advertiser_user_filter.py | Python | apache-2.0 | 2,962 | 0.005402 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | oogleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
"""
# Import appropriate modules from the client library.
from googleads import dfa
USER_ID = 'INSERT_USER_ID_HERE'
ADVERTISER_ID = 'INSERT_ADVER... | '
def main(client, user_id, advertiser_id):
# Initialize appropriate service.
user_service = client.GetService(
'user', 'v1.20', 'https://advertisersapitest.doubleclick.net')
# Retrieve the user who is to be modified.
user = user_service.getUser(user_id)
# Create and configure a user filter.
adver... |
translate/translate | translate/storage/test_zip.py | Python | gpl-2.0 | 2,697 | 0.000371 | """Tests for the zip storage module"""
import os
from zipfile import ZipFile
from translate.storage import zip
class TestZIPFile:
"""A test class to test the zip class that provides the directory interface."""
def setup_method(self, method):
"""sets up a test directory"""
print("setup_metho... | a directory inside self.testzip."""
pass
def test_cre | ated(self):
"""test that the directory actually exists"""
print(self.testzip)
assert os.path.isfile(self.testzip)
def test_basic(self):
"""Tests basic functionality."""
files = ["a.po", "b.po", "c.po"]
self.touchfiles(None, files, last=True)
d = zip.ZIPFile(... |
axaxs/Cnchi | src/config.py | Python | gpl-3.0 | 1,966 | 0.03001 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# config.py
#
# Copyright 2013 Cinnarch
#
# 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... | are/cnchi/', \
'UI_DIR' : '/usr/share/cnchi/ui/', \
'DATA_DIR' : '/usr/share/cnchi/data/', \
'TMP_DIR' : '/tmp', \
'language_name' : '', \
'language_code' : '', \
'locale' : '', \
'keyboard_layout' : '', \
... | mezone_zone' : '', \
'timezone_human_country' : '', \
'timezone_comment' : '', \
'timezone_latitude' : 0, \
'timezone_longitude' : 0, \
'activate_ntp' : 1, \
'partition_mode' : 'm', \
'auto_device' : '/dev/sd... |
nburn42/tensorflow | tensorflow/python/framework/random_seed.py | Python | apache-2.0 | 5,903 | 0.003219 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _random_seed(1234)
a = tf.random_uniform([1])
b = tf.random_normal([1])
# Repeatedly running this block with the same graph will gen | erate the same
# sequences of 'a' and 'b'.
print("Session 1")
with tf.Session() as sess1:
print(sess1.run(a)) # generates 'A1'
print(sess1.run(a)) # generates 'A2'
print(sess1.run(b)) # generates 'B1'
print(sess1.run(b)) # generates 'B2'
print("Session 2")
with tf.Session() as sess2:
... |
ericshawlinux/bitcoin | test/functional/p2p_sendheaders.py | Python | mit | 26,656 | 0.002251 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of headers messages to announce blocks.
Setup:
- Two nodes:
- node0 is the node-und... | . The
first p2p connection is a control and should only ever receive inv's. The
second p2p connection tests the headers sending logic.
- node1 is used to create reorgs.
test_null_locators
==================
Sends two getheaders requests wit | h null locator values. First request's hashstop
value refers to validated block, while second request's hashstop value refers to
a block which hasn't been validated. Verifies only the first request returns
headers.
test_nonnull_locators
=====================
Part 1: No headers announcements before "sendheaders"
a. no... |
gordon-zhao/Chrome_bookmarks_to_json | src/python/html2json.py | Python | mit | 4,599 | 0.006741 | # coding: utf-8
import json
import sys
import codecs
python3 = False
if sys.version_info[0] == 3: #Python 3
python3 = True
if not python3:
reload(sys)
sys.setdefaultencoding("utf-8")
input = raw_input
def parseHTML(file_path):
fo = codecs.open(file_path, encoding='utf-8', mode='r+')
origina... | ,folder_header,folder_ender,bookmark_header,bookmark_ender]
for i in range(6):
# Prevent the min() choose the not exists value -1
if lists[i] == -1:
lists[i] = original_length + 1
nearest_element = min(lists)
if lists[3] + 8 >= ori | ginal_length: # If the folder end mark plus its length is equal to the raw file length, then escape the loop, in order to prevent the value -1 returned by find() caused the loop go over again
break
if nearest_element == folder_title_header and not block:
if not folder_title_ender > -1... |
EmuKit/emukit | tests/emukit/bayesian_optimization/test_multipoint_expected_improvement.py | Python | apache-2.0 | 2,394 | 0.002924 | import GPy
import numpy as np
from scipy.optimize import check_grad
from emukit.bayesian_optimization.acquisitions import MultipointExpectedImprovement
from emukit.model_wrappers import GPyModelWrapper
# Tolerance needs to be quite high since the q-EI is also an approximation.
TOL = 5e-3
# Tolerance for the gradient ... | 1)
y_init = np.random.rand(3, 1)
# Make GPy model
gpy_model = GPy.models.GPRegression(x_init, y_init)
model = GPyModelWrapper(gpy_model)
x0 = np.array([0.45, 0.55])
_check_grad(MultipointExpectedImprovement(model), TOL_GRAD, x0)
_check_grad(MultipointExpectedImprovement(model, fast_compute=... | f _check_grad(lp, tol, x0):
grad_error = check_grad(
lambda x: lp.evaluate(x[:, None]).flatten(), lambda x: lp.evaluate_with_gradients(x[:, None])[1].flatten(), x0
)
assert np.all(grad_error < tol)
|
LLNL/spack | var/spack/repos/builtin/packages/perl-inline/package.py | Python | lgpl-2.1 | 603 | 0.004975 | # Copyright 2013-2021 Lawrenc | e Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlInline(PerlPackage):
"""Write Perl Subroutines in Other Programming Languages"""
homepage = "https://metacpan.... | /I/IN/INGY/Inline-0.80.tar.gz"
version('0.80', sha256='7e2bd984b1ebd43e336b937896463f2c6cb682c956cbd2c311a464363d2ccef6')
depends_on('perl-test-warn', type=('build', 'run'))
|
CaptainDesAstres/Frames-Animated-By-Curve | single_track/Combination.py | Python | gpl-3.0 | 4,675 | 0.056769 | import bpy
from functions import *
class Combination():
'''A class containing all properties and methods
relative to combination settings for
Curve To Frame addon'''
def update_curves( self, context ):
'''method that must be over ride: update curve when settings have been changed'''
type(self).update_curv... | _points.insert(frame, value)
elif combination_mode == 2: # combination mode is «clamp_curve»
combination_curve.keyframe_points.insert(
frame,
max(
min (
amplitude_net_curve.evaluate(frame),
peaks_curve.evaluate(frame),
1
),
0
)
)
elif co... | bination_curve.keyframe_points.insert(
frame,
amplitude_net_curve.evaluate(frame)
)
combination_curve.keyframe_points[-1].interpolation = 'LINEAR'
# next frame
frame += 1
#erase keyframe on flat section
avoid_useless_keyframe( combination_curve )
# prevent curve edition... |
praekeltfoundation/ndoh-hub | scripts/migrate_to_whatsapp_templates/tests/test_prebirth5.py | Python | bsd-3-clause | 1,231 | 0.001625 | import unittest
from scripts.migrate_to_whatsapp_templates.prebirth5 import Prebirth5Migration
class Testprebirth5(unittest.TestCase):
def setUp(self):
self.prebirth5 = Prebirth5Migration()
def test_sequence_number_to_weeks(self):
"""
Given a certain sequence number for the prebirth ... | self.assertEqual(self.prebirth5.sequence_number_to_weeks(1), 38)
self.assertEqual(self.prebirth5.sequence_number_to_weeks(2), 38)
self.assertEqual(self.prebirth5.sequence_number_to_weeks(3), 38)
self.assertEqual(self.prebirth5.se | quence_number_to_weeks(5), 38)
self.assertEqual(self.prebirth5.sequence_number_to_weeks(14), 40)
self.assertEqual(self.prebirth5.sequence_number_to_weeks(15), 40)
def test_get_template_variables(self):
message = {
"id": "1",
"messageset": "2",
"sequence_n... |
vellonce/PizzaFria | pizzafria/localsettings.py | Python | gpl-2.0 | 585 | 0.001709 | # -*- coding: utf-8 -*-
__author__ = 'iwdev1'
from .settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pizza_db',
'USER': 'root',
'PASSWORD': 'A8d32e08.',
'HOST': '',
'PORT': '',
}
}
ALLOWED_HOSTS = []
STATIC_ROOT = ''
... | not relative paths.
o | s.path.join(PROJECT_PATH, 'templates/static/'),
) |
dokterbob/satchmo | satchmo/apps/product/modules/downloadable/migrations/0001_split.py | Python | bsd-3-clause | 18,953 | 0.007862 | # encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
depends_on = (
('product', '0010_add_discountable_categories'),
)
def forwards(self, orm):
db.rename_table('product_downloadableproduct', 'downloadable_downloadableproduct')
... | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.Cha | rField', [], {'max_length': '80', 'unique': 'True'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'P... |
jobiols/odoo-argentina | l10n_ar_partner/__openerp__.py | Python | agpl-3.0 | 1,050 | 0 | # -*- coding: utf-8 -*-
{
'author': "Moldeo Interactive,ADHOC SA,Odoo Community Association (OCA)",
'category': 'Localization/Argentina',
'depends': [
'partner_identification',
# this is for demo data, for fiscal position data on account
# and also beacuse it is essential for argenti... | er_view.xml',
'views/res_company_view.xml',
'views/res_partner_id_category_view.xml',
'views/res_partner_id_number_view.xml',
'sale_config_view.xml',
'security/security.xml',
],
'demo': [
'demo/pa | rtner_demo.xml',
],
'version': '9.0.1.3.0',
'post_init_hook': 'post_init_hook',
'pre_init_hook': 'pre_init_hook',
}
|
beppec56/core | scripting/source/pyprov/mailmerge.py | Python | gpl-3.0 | 17,916 | 0.030196 | # Caolan McNamara caolanm@redhat.com
# a simple email mailmerge component
# manual installation for hackers, not necessary for users
# cp mailmerge.py /usr/lib/libreoffice/program
# cd /usr/lib/libreoffice/program
# ./unopkg add --shared mailmerge.py
# edit ~/.openoffice.org2/user/registry/data/org/openoffice/Office/W... | s = content.getTransferDataFlavors()
if dbg:
print("PyMailSMTPService flavors len: %d" % (len(flavors),), file=dbgout)
#Use first flavor that's sane for an email body
for flavor in flavors:
if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find('text/plain') != -1:
if dbg:
print("PyMai... | lavor.MimeType)
if mimeEncoding.find('charset=UTF-8') == -1:
mimeEncoding = mimeEncoding + "; charset=UTF-8"
textmsg['Content-Type'] = mimeEncoding
textmsg['MIME-Version'] = '1.0'
try:
#it's a string, get it as utf-8 bytes
textbody = textbody.encode('utf-8')
except:
#it... |
ESS-LLP/erpnext | erpnext/hooks.py | Python | gpl-3.0 | 28,711 | 0.021351 | from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "fa fa-th"
app_color = "#e74c3c"
app_email = "info@erpnext.com"
app_license = "GNU General Public License (v3)"
sour... | : "/invoices", "to_route": "Sale | s Invoice"},
{"from_route": "/invoices/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Sales Invoice",
"parents": [{"label": _("Invoices"), "route": "invoices"}]
}
},
{"from_route": "/supplier-quotations", "to_route": "Supplier Quotation"},
{"from_route": "/supplier-quotations/<path:name>", "... |
9seconds/isitbullshit | setup.py | Python | mit | 2,097 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.command.test import test
REQUIREMENTS = (
"six",
)
with open("README.rst", "r") as resource:
LONG_DESCRIPTION = resource.read()
# copypasted from http://pytest.org/latest/goodpractises.html
class Py... | self.pytest_args = None # pylint: disable=W0201
def finalize_options(self):
test.finalize_options(self)
self.test_args = [] # pylint: disable=W0201
self.test_suite = True # pylint: disable=W0201
def r | un_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
import sys
errno = pytest.main(self.pytest_args)
sys.exit(errno)
setup(
name="isitbullshit",
description=("Small library for verifying parsed JSONs "
"if they are bullshit... |
Overdrivr/DistantIO | distantio/__init__.py | Python | mit | 295 | 0.003413 | # Copyright (C) 2014 Rémi | Bèges
# For conditions of distribution and use, see copyright notice in the LICENSE file
from distantio.DistantIO import DistantIO
from distantio.DistantIOProtocol import distantio_protocol
from distantio.SerialPort import SerialPort
from distantio.crc impor | t crc16
|
paulorauber/rl | examples/blackjack.py | Python | mit | 5,813 | 0.001892 | import numpy as np
from itertools import product
from learning.model_free import Problem
from learning.model_free import sarsa
from learning.model_free import qlearning
from learning.model_free import mc_value_iteration
from learning.model_free import sarsa_lambda
from learning.model_free import q_lambda
# from learn... | else:
my_sum -= 10
usable_ace = 0
if self.hand_value(my_sum, usable_ace) > 21:
return 0, -1
# Only nonterminal case
next_s = self.states_map[(my_sum, dealer_card, usable_ace)]
return next_s, 0
raise ... | e[2]:
print('Hand value: {0}, Dealer Showing: {1}, Action: {2}'.format(
self.hand_value(state[0], 1), state[1], self.a[policy[i]]))
print('No usable ace:')
for i, state in enumerate(self.states):
if not state[2]:
print('Hand value: {0}, De... |
ProjectFacet/facet | project/editorial/migrations/0050_auto_20171117_1716.py | Python | mit | 437 | 0.002288 | # -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('editorial', '0049_auto_20171116_1526'),
]
operations = [
migrations.AlterField(
model_name='facet',
name='story',... | ),
]
|
spyder-ide/spyder-terminal | spyder_terminal/config.py | Python | mit | 1,346 | 0.000743 | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Spyder terminal default configuration."""
import os
import sys
WINDOWS = os.name == 'nt'
LINUX = sys.platform.starts | with('linux')
CONF_SECTION = 'terminal'
CONF_DEFAULTS = [
(CONF_SECTION,
{
'sound': True,
'cursor_type': 0,
'shell': 'cmd' if WINDOWS else 'bash',
'buffer_limit': 1000,
'cu | rsor_blink': True,
'zoom': 0,
}
),
('shortcuts',
{
'terminal/copy': 'Ctrl+Alt+Shift+C' if LINUX else 'Ctrl+Alt+C',
'terminal/paste': 'Ctrl+Alt+Shift+V' if LINUX else 'Ctrl+Alt+V',
'terminal/new_terminal': 'Ctrl+Alt+T',
'terminal/clear': 'Ctrl+Alt+K',
'terminal... |
aaivazis/nautilus | nautilus/auth/util/token_encryption_algorithm.py | Python | mit | 52 | 0.019231 | def token_encryption_algorith | m():
return 'HS2 | 56' |
fernandezcuesta/ansible | lib/ansible/modules/cloud/vmware/vmware_dvswitch.py | Python | gpl-3.0 | 7,199 | 0.001945 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# 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.0',
... | choices:
- 'cdp'
- 'll | dp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'pres... |
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_bapcsaleseurope/app.py | Python | mit | 153 | 0.006536 | #encoding:utf-8
subreddit = 'BaPCSalesEurope'
t_channel = '@r_BaPCSalesEurope'
def send_po | st(submission, r2t):
| return r2t.send_simple(submission)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.