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 |
|---|---|---|---|---|---|---|---|---|
google/personfinder | tests/server_test_cases/input_escaping_tests.py | Python | apache-2.0 | 5,290 | 0.000378 | # Copyright 2019 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 or agreed to in writing,... | something
| # like that) is escaped automatically by Django, so we don't need to
# test the complete list of fields. We'll test a few of them just to
# make sure Django autoescaping doesn't accidentally get disabled.
self.s.submit(create_form,
own_info='no',
give... |
crossbario/autobahn-testsuite | autobahntestsuite/autobahntestsuite/case/case1_2_4.py | Python | apache-2.0 | 1,353 | 0.022173 | ###############################################################################
##
## Copyright (c) Crossbar.io Technologies GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at... | se
class Case1_2_4(Case):
DESCRIPTION = """Send binary message message with payload of length 127."""
EXPECTATION = """Receive echo'ed binary message (with payload as sent). Clean close with normal code."""
def onOpen(self):
payload = "\xfe" * 127
self.expected[Case.OK] = [("message",... | self.expectedClose = {"closedByMe":True,"closeCode":[self.p.CLOSE_STATUS_CODE_NORMAL],"requireClean":True}
self.p.sendFrame(opcode = 2, payload = payload)
self.p.killAfter(1)
|
jpulec/django-loggit | loggit/models.py | Python | bsd-3-clause | 3,864 | 0.001553 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.template.context import Context
from django.template.loader import get_template_from_string
from django.utils import timezone
import swapper
class BaseLogEntry(models.Model):
"""
A base class that implements the... | se method just return | s the name.
"""
return unicode(self.name)
class TemplateLogEvent(BaseLogEvent):
"""
A subclass of BaseLogEvent that renders a template using django's
templating engine. The current entry is added to the context that is passed
to the template.
"""
template = models.TextField()
... |
FDio/vpp | test/test_syslog.py | Python | apache-2.0 | 8,129 | 0.000246 | #!/usr/bin/env python3
import unittest
from framework import VppTestCase, VppTestRunner
from util import ppp
from scapy.packet import Raw
from scapy.layers.inet import IP, UDP
from syslog_rfc5424_parser import SyslogMessage, ParseError
from syslog_rfc5424_parser.constants import SyslogFacility, SyslogSeverity
from vpp... | Syslog Protocol test """
self.vapi.syslog_set_sender(src_address=self.pg0.local_ip4,
collector_address=self.pg0.remote_ip4)
config = self.vapi.syslog_get_sender()
self.assertEqual(str(config.collector_address),
self.pg0.remote_ip4)
... | self.assertEqual(config.max_msg_size, 480)
appname = 'test'
msgid = 'testMsg'
msg = 'this is message'
sd1 = {'exampleSDID@32473': {'iut': '3',
'eventSource': 'App',
'eventID': '1011'}}
sd2 = {'example... |
jreback/pandas | pandas/tests/test_optional_dependency.py | Python | bsd-3-clause | 1,518 | 0 | import sys
import types
import pytest
from pandas.compat._optional import VERSIONS, import_optional_dependency
import pandas._testing as tm
def test_import_optional():
match = "Missing .*notapac | kage.* pip .* conda .* notapackage"
with pytest.raises(ImportError, match=match) | :
import_optional_dependency("notapackage")
result = import_optional_dependency("notapackage", raise_on_missing=False)
assert result is None
def test_xlrd_version_fallback():
pytest.importorskip("xlrd")
import_optional_dependency("xlrd")
def test_bad_version(monkeypatch):
name = "fakemo... |
juanchopanza/NeuroM | neurom/check/tests/test_morphtree.py | Python | bsd-3-clause | 7,427 | 0.000539 | # Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | nit_radius
sec = []
for _ in range(5):
sec.append([0, 0, 0, radius, 0, 0])
radius = new_radius(radius, mode)
return Section(np.array(sec))
radius = 1.
tree = fake_tree(radius, mode)
tree.add_child(fake_tree(tree.points[-1][COLS.R], mode))
tree.add_chil... | .array([[0, 0, 0, 1.0, 0, 0],
[0, 0, 0, 0.75, 0, 0],
[0, 0, 0, 0.5, 0, 0],
[0, 0, 0, 0.25, 0, 0]]))
ch0 = Section(np.array([[0, 0, 0, 0.375, 0, 0],
[0, 0, 0, 0.125, 0, 0],
... |
alexryndin/ambari | ambari-server/src/main/resources/common-services/STORM/0.9.1/package/scripts/nimbus_prod.py | Python | apache-2.0 | 2,557 | 0.007431 | #!/usr/bin/env python
"""
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");... | ture(StackFea | ture.ROLLING_UPGRADE, params.version):
conf_select.select(params.stack_name, "storm", params.version)
stack_select.select("storm-client", params.version)
stack_select.select("storm-nimbus", params.version)
def start(self, env, upgrade_type=None):
import params
env.set_params(params)
sel... |
derekperry/oaxmlapi | oaxmlapi/utilities.py | Python | mit | 4,499 | 0 | # -*- coding: utf-8
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
try:
import simplejson as json
except ImportError:
import json
ADDRESS_FIELDS = (
'first', 'middle', 'last', 'salutation', 'email', 'phone',
'fax', 'mobile', 'addr1', 'addr2', ... | cation',
'Category', 'Category_1', 'Category_2', 'Category_3', 'Category_4',
'Category_5', 'Ccrate', 'Company', 'Contact', 'Costcategory',
'Costcenter', 'Costtyp | e', 'Currency', 'Currencyrate', 'CustField',
'Customer', 'Customerpo', 'Customerpo_to_project', 'CustomerProspect',
'Date', 'Deal', 'Dealcontact', 'Dealschedule', 'Department', 'Entitytag',
'Envelope', 'Error', 'Estimate', 'Estimateadjustment',
'Estimateexpense', 'Estimatelabor', 'Estimatemarkup', 'Esti... |
amm042/pywattnode | pypowerscout.py | Python | gpl-2.0 | 2,227 | 0.008985 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from http://homepage.hispee | d.ch/py430/python/daemon.py
###########################################################################
# configure these paths:
LOGFILE = '/var/log/powerscout.log'
PIDFILE = '/var/run/powerscout.pid'
# and let USERPROG be the main function of your project
import powerscoutLogger
USERPROG = powerscoutLogger.main
#####... | ##############################################
#based on Jürgen Hermanns http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
import sys, os
class Log:
"""file like for writes with auto flush after each write
to ensure that everything is logged, even during an
unexpected exit."""
def __init__... |
tensorflow/tensorflow | tensorflow/python/debug/lib/debug_v2_ops_test.py | Python | apache-2.0 | 31,247 | 0.005024 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | fer_size = 4
self.tfdbg_run_id = "test_tfdbg_run"
self.writer = debug_events_writer.DebugEventsWriter(
self.dump_root, self.tfdbg_run_id, self.circular_buffer_size)
def tearDown(self):
self.writer.Close()
super(DebugIdentityV2OpTest, self).tearDown | ()
@test_util.run_in_graph_and_eager_modes
def testSingleTensorFullTensorDebugModeWithCircularBufferBehavior(self):
@def_function.function
def write_debug_trace(x):
square = math_ops.square(x)
gen_debug_ops.debug_identity_v2(
square,
tfdbg_context_id="deadbeaf",
o... |
devilry/devilry-django | devilry/devilry_gradingsystem/widgets/filewidget.py | Python | bsd-3-clause | 973 | 0.001028 | from django import forms
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
class FeedbackEditorFileWidget(forms.ClearableFileInput):
"""
Clearable file widget.
Can be made un-clearable (for required fields) using the
``clearable`` argument for ``__init_... | ingsystem/widgets/feedbackeditorfilewidget.django.html'
def __init__(self, feedbackfile, attrs=None):
self.feedbackfile = feedbackfile
super( | FeedbackEditorFileWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
attrs = attrs or {}
input_html = forms.FileInput.render(self, name, value, attrs)
output = render_to_string(self.template_name, {
'input_html': input_html,
'feedbackfile': self... |
FriedrichK/python-edifact | edifact/message_headers/una.py | Python | apache-2.0 | 1,786 | 0.00056 | class UNA(object):
"""Wrapper class for UNA (Service String Advice) components."""
c | omponent_data_element_separator = ':'
data_element_separator = '+'
decimal_mark = ','
release_character = '?'
segment_terminator = '\''
@staticmethod
def is_valid_una_string(input_string):
"""Return True if input_string is valid, False if not."""
| if not input_string[:3] == 'UNA':
input_string = 'UNA' + input_string
if not input_string:
return False
if len(input_string) < 9:
return False
if not input_string[7] == ' ':
return False
return True
def __init__(self, src_string=... |
lijunxyz/leetcode_practice | 4_sum_medium/Solution2.py | Python | mit | 2,496 | 0.022035 | # https://oj.leetcode.com/problems/4sum/
# Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
#
# Note:
# Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= ... | newItem=[num[fi] for fi in items];
newItem=tuple(sorted(newItem));
| res.add((newItem));
i+=1;
j-=1;
elif(total<target):
i+=1;
else:
j-=1;
# Now convert the set to array.
resNums= [];
for item in res:
resNums.append([i for i in item]);
... |
gjcarneiro/yacron | yacron/cron.py | Python | mit | 16,835 | 0 | import asyncio
import asyncio.subprocess
import datetime
import logging
from collections import OrderedDict, defaultdict
from typing import Any, Awaitable, Dict, List, Optional, Union # noqa
from urllib.parse import urlparse
from aiohttp import web
import yacron.version
from yacron.config import (
JobConfig,
p... |
async def _web_get_status(self, request: web.Request) -> web.Response:
out = []
for name, job in self.cron_jobs.items():
running = self.running_jobs.get(name, None)
if running:
out.append(
{
"job": name,
... | pid": [
runjob.proc.pid
for runjob in running
if runjob.proc is not None
],
}
)
else:
crontab = job.schedule # type: Union[CronTab, str]
... |
JaggedVerge/mmap_backed_array | mmap_backed_array/tests/test_slice_decoding.py | Python | gpl-3.0 | 5,134 | 0.010129 | """
Tests for slice decoding
"""
import pytest
from mmap_backed_array.slice_decoding import (
_decode_index,
_decode_old_slice,
_decode_slice,
)
def test_decode_slice_bad_parameter():
"""Test that bad parameters to decode_slice raise"""
with pytest.raises(TypeError):
_decode_slice("this is... | h pytest.raises(TypeError):
_decode_slice(s, 10)
s = slice(1,"Bad stop type",1)
with pytest.raises(TypeError):
_decode_slice(s, 10)
# Different code path exists with negative steps, must retest for types in this case
s = slice("bad start type", 1, -1)
with pytest.raises(T | ypeError):
_decode_slice(s, 10)
s = slice(1, "bad stop typ", -1)
with pytest.raises(TypeError):
_decode_slice(s, 10)
def test_decode_index_bad_parameter():
"""Test that bad parameters passed to decode_index raise"""
s = slice(1,2,3)
with pytest.raises(TypeError):
_decode_in... |
JmilkFan/my-code-repertory | DBStressTesting/db_stresstesting_gevent.py | Python | apache-2.0 | 6,680 | 0 | # Scripts are mainly used for stress testing of different databases,
# The way to test is to use Python modules to connect database then
# Repeatedly insert data.
#
# You can use this script in the following ways:
# such as:
#
# python db_stresstesting_multi_thread.py -i <mysql_server_ipaddr> -u root \
# ... | self._session.add(new_test)
self._session.commit()
def query_data(self):
data_total = self._session.query(
func.count("*")).select_from(Stre | ssTestTable).scalar()
return data_total
def _get_engine(self, uri, debug=False):
try:
engine = create_engine(uri, pool_size=100, pool_recycle=7200,
echo=debug)
except Exception as err:
logging.info(">>> %s" % err)
... |
panoplyio/panoply-python-sdk | panoply/events.py | Python | mit | 401 | 0 | class Emitter(object):
_events = None
def __init__(self):
self._events = {}
def on(self, name, fn):
self._events.setdefault(name, set([])).add(fn)
return self
def fire(self, name, data):
for fn in self._events.get("*", set([])):
fn( | name, data)
for fn in self._events | .get(name, set([])):
fn(data)
return self
|
catherinedevlin/rideshare-matchmaker | traveller/apps.py | Python | cc0-1.0 | 93 | 0 | from djang | o.apps import AppConfig
class TravellerConfig(AppConfig):
name = 'traveller | '
|
OCA/l10n-brazil | l10n_br_coa_simple/tests/test_l10n_br_coa_simple.py | Python | agpl-3.0 | 945 | 0 | # Copyright (C) 2020 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo.tests.common import TransactionCase
class L10nBrSimpleCOA(TransactionCase):
def setUp(self):
super(L10nBrSimpleCOA, self).setUp()
self.l10n_br_coa_simple = self.env.ref(
... | te do Plano de Contas Simplificado"}
)
def test_l10n_br_coa_simple(self):
"""Test to install the chart of accounts template in a new company"""
self.env.user.company_ids += self.l10n_br_company
self.env.user.company_id = self.l10n_br_company
self.l10n_br_coa_simple.try_loadi... | ompany.chart_template_id
)
|
xcgspring/dependence_repo | manager/dependence_repo_manager/main.py | Python | apache-2.0 | 357 | 0 |
import | sys
from PyQt4 import QtGui
from dependence_repo_manager.core.manager import RepoManager
from dependence_repo_manager.core.main_window import MainWindow
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
manager = RepoManager()
manager.config()
mainWin = MainWindow(manager)
| mainWin.show()
sys.exit(app.exec_())
|
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/client_add_distributed_object_listener_codec.py | Python | apache-2.0 | 1,677 | 0.004174 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE, EVENT_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
# hex: 0x000900
_REQ... | ean(buf, _REQUEST_LOCAL_ONLY_OFFSET, local_only)
return OutboundMessage(buf, False)
def decode_response(msg):
initial_frame = msg.next_frame()
return FixSizedTypesCodec.decode_uuid(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)
def handle(msg, handle_distributed_object_event=None):
message_type = msg... | age_type()
if message_type == _EVENT_DISTRIBUTED_OBJECT_MESSAGE_TYPE and handle_distributed_object_event is not None:
initial_frame = msg.next_frame()
source = FixSizedTypesCodec.decode_uuid(initial_frame.buf, _EVENT_DISTRIBUTED_OBJECT_SOURCE_OFFSET)
name = StringCodec.decode(msg)
se... |
Spotipo/spotipo | unifispot/utils/modelhelpers.py | Python | agpl-3.0 | 8,979 | 0.009355 | from flask import Blueprint,current_app
from flask.json import JSONEncoder as BaseJSONEncoder
import arrow
from flask_babelplus import format_datetime as _format_datetime
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.properties import ColumnProperty
from unifispot.core.db import db
from dateutil import... | iers = self.__form_fields_modifiers__ or dict()
for field_name in field_names:
if field_name in avoid:
continue
modifier = modifiers.get(field_name)
| if modifier:
if isinstance(modifier, basestring):
modifier = getattr(self,modifier)
value = modifier(form,field_name)
else:
value = modifier(self,form,field_name)
else:
value = getattr(form,fie... |
samuelclay/NewsBlur | vendor/oauth2client/tools.py | Python | mit | 5,656 | 0.007249 | # Copyright (C) 2010 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 or agreed to in writ... | and re-run this')
print('application with the command-line parameter ')
print()
print(' --noauth_local_webserver')
print()
else:
print('Go to the following link in your browser:')
print()
print(' ' + authorize_url)
print()
code = None
if FLAGS.auth_local_webserver:
httpd.h... | tpd.query_params:
code = httpd.query_params['code']
else:
print('Failed to find "code" in the query parameters of the redirect.')
sys.exit('Try running with --noauth_local_webserver.')
else:
code = input('Enter verification code: ').strip()
try:
credential = flow.step2_exchange(code, ... |
infinity0/bjsim | bj/rule.py | Python | bsd-3-clause | 2,501 | 0.037185 | from collections import namedtuple
from fractions import Fraction
from bj.hand import Hand as H
from bj.game import GameStateDist
class BJRule(namedtuple('BJRule', 'name pay playHouse actions defaultDecks')):
pass
def __BJ_pay(h, p):
if p.isBust():
return -1
if p.isNat():
return 0 if h.isNat() else Fraction(3... | lse 1
if h.isBust():
return 0 if h.is22() else 1
if h.isNat():
return -1
hm = h.value
pm = p.value
return 0 if hm == pm else 1 if pm > hm else -1
def __BJS_playHouse(gs):
if gs.done:
return GameStateDist.inject(gs)
h = gs.currentHand()
if h.canHit() and (h.value <= 16 or h.isA17()):
return gs.hit()
el... | as).
Cannot surrender. Blackjack pays 1:1. Dealer must hit soft-17 and pushes on 22.
We do not (yet) simulate or estimate a strategy for switching.
"""
BJS = BJRule("Blackjack Switch", __BJS_pay, __BJS_playHouse, ('H', 'S', 'D', 'P'), 8)
def __BJV_pay(h, p):
if p.isBust():
return -1
if p.isNat():
return 0 if h.... |
bigfatnoob/DISCAW | where2.py | Python | mit | 11,873 | 0.036469 | """
# A Better Where
WHERE2 is a near-linear time top-down clustering alogithm.
WHERE2 updated an older where with new Python tricks.
## Standard Header Stuff
"""
from __future__ import division,print_function
import sys
sys.dont_write_bytecode = True
from lib import *
from numpy import var
from Models import *... | (x,one)]
lst = sorted(lst)
if m._split == "variance":
variance, mid = sdiv(map(first, lst))
elif m._split == "centroid":
centroid, mid = centroid(map(first,lst))
else: #median
mid = len(lst)//2
wests = map(second,lst[:mid])
easts = map(second,lst[mid:])
# Projection of midpoint, used for f... | the leaf in which the test node
belongs by comparing the projection of
test node between the extreme nodes
"""
def leaf(m,one,node):
if node._kids:
east = node.east
west = node.west
mid_cos = node.mid_cos
a = dist(m,one,west)
b = dist(m,one,east)
c = dist(m,west,east)
if c == 0:
retu... |
tensorflow/graphics | tensorflow_graphics/geometry/transformation/rotation_matrix_common.py | Python | apache-2.0 | 3,167 | 0.001579 | # Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | lid rotation matrix by checking
that $$\mathbf{R}^T\mathbf{R} = \mathbf{I}$$ and $$\det(\ | mathbf{R}) = 1$$.
Note: In the following, A1 to An are optional batch dimensions.
Args:
matrix: A tensor of shape `[A1, ..., An, K, K]`, where the last two
dimensions represent a rotation matrix in K-dimensions.
atol: The absolute tolerance parameter.
name: A name for this op that defaults to "r... |
madsmtm/fbchat | tests/test_search.py | Python | bsd-3-clause | 398 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from fbchat.models import ThreadType
def test_search_for(client1):
users = client1.searchForUsers("Mark Zuckerberg")
assert len(users) > 0
u = users[0]
| assert u.uid == "4"
assert u.type == ThreadType.USER
assert u.photo[: | 4] == "http"
assert u.url[:4] == "http"
assert u.name == "Mark Zuckerberg"
|
ferriman/SSandSP | raspberrypi/expo.py | Python | gpl-3.0 | 693 | 0.047619 | import RPi.GPIO as GPIO
import time
import pygame
GPIO.setmode(GPIO.BCM)
PIR_PIN = 4
GPIO.setup(PIR_PIN,GPIO.IN)
time.sleep(2)
playing = 0
start = 0
count = 0
limit = 10
while True | :
time.sleep(1)
if GPIO.input(PIR_PIN):
if playing == 0:
start | = 1
if playing == 1:
start = 0
count = 0
#print "PIR activat"
if start == 1:
pygame.mixer.init()
pygame.mixer.music.load("/home/pi/eb.mp3")
pygame.mixer.music.play(-1,0.0)
playing = 1
#print "MUSICA inici"
if count == limit and playing == 1:
playing = 0
pygame.mixer.music.stop()
pygame... |
ergs/rever | tests/test_dag.py | Python | bsd-3-clause | 4,047 | 0.001483 | """DAG tests"""
from rever.dag import find_path
from rever.activity import Activity
def test_empty():
path, _ = find_path({}, set())
assert [] == path
def test_single():
path, _ = find_path({'a': Activity()}, {'a'})
assert ['a'] == path
def test_two_unrelated():
dag = {'a': Activity(), 'b': Ac... | ne():
path, already_done = find_path({'a': Activity()}, {'a'}, done={'a'})
assert [] == path
assert ['a'] == already_done
def test_two_unrelated_done():
dag = {'a': Activity(), 'b': Activity()}
path, already_done = find_path(dag, {'a', 'b'}, done={'a'})
assert ['b'] == path
assert ['a'] ==... | test_two_dep_done():
dag = {'a': Activity(), 'b': Activity(deps=set('a'))}
path, already_done = find_path(dag, {'b'}, done={'a'})
assert ['b'] == path
assert ['a'] == already_done
def test_three_linear_done():
dag = {'a': Activity(), 'b': Activity(deps=set('a')), 'c': Activity(deps=set('b'))}
... |
realopenit/bubble | bubble/commands/cmd_pipe.py | Python | gpl-3.0 | 1,350 | 0.002963 | # -*- coding: utf-8 -*-
# Part of bubble. See LICENSE file for full copyright and licensing details.
import click
from ..cli import STAGES
from ..commands.cmd_pull import cli as pull
from ..commands.cmd_transform import cli as transform
from ..commands.cmd_push import cli as push
@click.command('pipe', short_help=... | say_green(' | Streaming Pipe finsished')
return True
return False
|
biomodels/BIOMD0000000360 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setup(name='BIOMD0000000360',
version=20140916,
description='BIOMD0000000360 from BioModels',
| url='http://www.ebi.ac.uk/biomodels-main/BIOMD0000000360',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packages(),
package_data={'': ['*.xml', 'README.md']}, |
) |
llvmpy/llvmpy | llvm/tests/test_intrinsic_basic.py | Python | bsd-3-clause | 3,537 | 0.002262 | import unittest
import sys
import math
from llvm.core import (Module, Type, Function, Builder)
import llvm.core as lc
import llvm.ee as le
from .support import TestCase, BITS, tests
class TestIntrinsicBasic(TestCase):
def _build_module(self, float):
mod = Module.new('test')
functy = Type.func... | e.int(), 2)]))
self._template(mod, func, lambda x: x**2)
def test_powi_f64(self):
float = Type.double()
mod, func, b = self._build_module(float)
intr = Function.intrinsic(mod, lc.INTR_POWI, [float])
b.ret(b | .call(intr, [func.args[0], lc.Constant.int(Type.int(), 2)]))
self._template(mod, func, lambda x: x**2)
tests.append(TestIntrinsicBasic)
if __name__ == '__main__':
unittest.main()
|
gerardroche/sublime-php-grammar | tests/test_indentation.py | Python | bsd-3-clause | 1,981 | 0.002019 | import glob
import os
import re
from PHPGrammar.tests import unittest
class TestFile():
def __init__(self, description, actual_content, expected_content, syntax=None):
self.description = description
self.actual_content = actual_content
self.expected_content = expected_content
sel... | XPECT' not in res:
raise RuntimeError(error_message)
description = res[r | es.index('TEST') + 1].strip()
actual_content = res[res.index('FILE') + 1].strip()
expected_content = res[res.index('EXPECT') + 1].strip()
syntax = None
if 'SYNTAX' in res:
syntax = res[res.index('SYNTAX') + 1].strip()
else:
description ... |
irinabov/debian-qpid-python | qpid_tests/broker_0_8/tx.py | Python | apache-2.0 | 8,155 | 0.005395 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | e law or agre | ed 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.
#
from qpid.client import Client, Closed
fro... |
NickCarneiro/curlconverter | fixtures/python/post_with_data_with_percent_sign.py | Python | mit | 118 | 0 | import reque | sts
data = {
'secret': '*%5*!'
}
response = requests.post('https://p | ostman-echo.com/post', data=data)
|
pjbull/cookiecutter | tests/test_hooks.py | Python | bsd-3-clause | 10,560 | 0.000379 | """Tests for `cookiecutter.hooks` module."""
import os
import errno
import stat
import sys
import textwrap
import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name, multiple_hooks=False):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks... | ooks_dir='hooks_dir') is None
def test_hook_not_found(self):
"""`find_hooks` should return None if the hook could not be found."""
with utils.work_in(self.repo_path):
assert hooks.find_hook('unknown_hook') is None
class TestExternalHooks(object):
"""Class to unite tests for hooks ... | /')
hooks_path = os.path.abspath('tests/test-hooks/hooks')
def setup_method(self, method):
"""External hooks related tests setup fixture."""
self.post_hook = make_test_repo(self.repo_path, multiple_hooks=True)
def teardown_method(self, method):
"""External hooks related tests teard... |
eonpatapon/rally | rally/plugins/openstack/scenarios/nova/services.py | Python | apache-2.0 | 1,390 | 0 | # Copyright 2016 IBM Corp.
# 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... | S IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import logging
from rally import consts
f | rom rally.plugins.openstack import scenario
from rally.plugins.openstack.scenarios.nova import utils
from rally.task import validation
LOG = logging.getLogger(__name__)
class NovaServices(utils.NovaScenario):
"""Benchmark scenarios for Nova agents."""
@validation.required_services(consts.Service.NOVA)
... |
dsweet04/rekall | rekall-gui/rekall_gui/plugins/webconsole/__init__.py | Python | gpl-2.0 | 907 | 0 | #!/usr/bin/env python2
# Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Author: Mikhail Bushkov realbushman@gmail.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... | of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY | WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple ... |
tseaver/google-cloud-python | phishingprotection/google/cloud/phishingprotection_v1beta1/__init__.py | Python | apache-2.0 | 1,064 | 0.00094 | # -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | hishingProtectionServiceClient(
ph | ishing_protection_service_client.PhishingProtectionServiceClient
):
__doc__ = phishing_protection_service_client.PhishingProtectionServiceClient.__doc__
__all__ = ("types", "PhishingProtectionServiceClient")
|
sataako/fmio-server | fmio/redisinterface.py | Python | mit | 247 | 0.004049 | import os
from redis import StrictRedis
import urlparse
redis_url = os.getenv('REDIS_URL')
urlparse.uses_netloc.append('redis')
url = urlparse | .urlparse(redis_url)
conn = | StrictRedis(host=url.hostname, port=url.port, db=0, password=url.password)
|
it-projects-llc/misc-addons | odoo_backup_sh_dropbox/models/ir_config_parameter.py | Python | mit | 777 | 0.001287 | # Copyright 2019 Dinar Gabbasov <https://it-projec | ts.info/team/GabbasovDinar>
# License MIT (https://opensource.org/licenses/MIT).
import logging
from odoo import api, models
from odoo.addons.odoo_backup_sh.models.odoo_backup_sh import ModuleNotConfigured
_logger = logging.getLogger(__name__)
try:
import dropbox
except ImportError as err:
_logger.debug(err... | dropbox_access_token = self.sudo().get_param(
"odoo_backup_sh_dropbox.dropbox_access_token"
)
if not dropbox_access_token:
raise ModuleNotConfigured("no access token given for dropbox")
return dropbox.Dropbox(dropbox_access_token)
|
CSD-Public/stonix | src/stonix_resources/InstallingHelper.py | Python | gpl-2.0 | 23,912 | 0.00966 | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | except RuntimeError as err :
# Calling read() on a closed ZipFile will raise a
# RuntimeError
self.logger.log(LogPriority.DEBUG,
["InstallingHelper.un_archive",
... | try :
# using os.open as regular open doesn't give the
# ability to set permissions on a file.
target = os.open(os.path.join(destination, internal_filename), os.O_CREAT | os.O_WRONLY , perm)
... |
maxpumperla/betago | betago/training/checkpoint.py | Python | mit | 2,572 | 0.000778 | from __future__ import absolute_import
import os
import h5py
from keras.models import Sequential
from keras.optimizers import | Adadelta
from keras.layers.core import Dense, Activation
from . import kerashack
__all__ = [
'TrainingRun',
]
class Traini | ngRun(object):
def __init__(self, filename, model, epochs_completed, chunks_completed, num_chunks):
self.filename = filename
self.model = model
self.epochs_completed = epochs_completed
self.chunks_completed = chunks_completed
self.num_chunks = num_chunks
def save(self):... |
farragar/game-engine | src/game.py | Python | mit | 318 | 0 | from engine import Game
import writer
from example_game import states, achievements
if __ | name__ == '__main__':
game = Game(states, achievements)
writer.init(100)
while not game.over:
game.step()
game.test_achievements()
writer.print_game_over()
| input()
game.save_and_quit()
|
pyladiesmedellin/lessons | lesson_4/2_6_lists_functions.py | Python | gpl-3.0 | 664 | 0.004518 | # -*- coding: utf-8 -*-
# recurso de referencia: http://www.tutorialspoint.com/python/python_lists.htm
lista_de_asignaturas_teoricas = [ 'matematicas', 'lengua castellana']
# el la funcion len() es usado para obtener la cantidad de elementos en una lista
print "cantidad de elementos en la lista lista_de_asignaturas_... | icas)
lista_de_numeros = [1, 2, 3, 4, 2, 3, 7, 8]
# hallar elemento de mayor valor en una lista con numeros
print "elemento de mayor valor"
print max(lista_de_numeros)
# 8
# hallar ele | mento de menor valor en una lista con numeros
print "elemento de menor valor"
print min(lista_de_numeros)
# 1
|
toumorokoshi/uranium | uranium/lib/__init__.py | Python | mit | 103 | 0 | """
lib is for underlying fu | nctionality driving Uranium, that is n | ot
meant for public consumption.
"""
|
grantathon/computer_vision_machine_learning | project/HierarchicalRandomForest_sklearn.py | Python | mit | 5,309 | 0.003014 | from sklearn import tree, ensemble
from randomforest import *
import numpy as np
from pprint import pprint
class HierarchicalRandomForest(object):
def __init__(self, n_estimators=100, n_procs=1):
self.classifiers = [ensemble.RandomForestClassifier(n_estimators=n_estimators, n_jobs=n_procs) for i in range(... | from the three chained random forest
probs = self.classifiers[0].predict_proba(test_examples)
hierarchy_inputs = np.concatenate([probs, test_examples], axis=1)
probs = self.classifiers[1].predict_proba(hierarchy_inputs)
hierarchy_inputs = np.concatenate([probs, test_examples], axis=1)
... | hy_inputs)
# probs = self.classifiers[0].predict_proba(test_examples)
# probs = self.classifiers[1].predict_proba(probs)
# prediction_probs = self.classifiers[2].predict_proba(probs)
# probs = self.classifiers[0].predict_proba(test_examples)
# prediction_probs = self.classifier... |
jeremybrodt/mbed | tools/settings.py | Python | apache-2.0 | 3,231 | 0.0065 | """
mbed SDK
Copyright (c) 2016 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... | -template=[{severity}] {file}@{line}: {id}:{message}"]
BUILD_OPTIONS = []
# mbed.org username
MBED_ORG_USER = ""
CLI_COLOR_MAP = {
"warning": "yellow",
"error" : "red"
}
##############################################################################
# User Settings (file)
###################################... | ########################################
try:
# Allow to overwrite the default settings without the need to edit the
# settings file stored in the repository
from mbed_settings import *
except ImportError:
pass
##############################################################################
# User Setti... |
emesene/emesene | emesene/gui/base/MainWindowBase.py | Python | gpl-3.0 | 4,799 | 0.001875 | '''base implementation of a main window'''
# -*- coding: utf-8 -*-
# This file is part of emesene.
#
# emesene 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
#... | lf.on_new_conversation(cid, [account], False)
#this calls the e3 Handler
self.session.new_conversation(account, cid)
def _on_mail_count_changed(self, count):
' | ''update ui widget with new email count'''
pass
def _on_social_request(self, conn_url):
pass
def _on_broken_profile(self, profile_url):
'''called when a person has a broken profile'''
dialog = extension.get_default('dialog')
dialog.broken_profile(self.session.close, pro... |
ooffeerr/django-first-app | mysite/free_games/migrations/0001_initial.py | Python | apache-2.0 | 812 | 0.002463 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
| name='Game',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
| ('game_description', models.CharField(max_length=200)),
('game_title', models.CharField(max_length=50)),
('image_url', models.URLField()),
('game_url', models.URLField()),
('pub_date', models.DateTimeField(verbose_name=b'date published')),
... |
balint256/cyberspectrum | spur_search.py | Python | gpl-2.0 | 6,742 | 0.033966 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# spur_search.py
#
# Copyright 2014 Balint Seeber <balint256@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version ... | nel_graph.add_horz_line(noise, 'gray', '--', id=' | noise')
fft_channel_graph.add_horz_line(spur_threshold, 'gray', '-', id='spur_threshold')
fft_channel_graph.add_points(lo_spurs, 'go')
def query_save(self, which):
if which == 'fft_graph':
if self.options.only_save_spurs:
return (self.total_spur_count > 0)
return None
def shutdown(self):
return... |
nuagenetworks/monolithe | monolithe/generators/lang/java/converter.py | Python | bsd-3-clause | 2,306 | 0.001735 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent 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 copyright
# no... | G, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT | , INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGL... |
cornett/coho | doc/conf.py | Python | isc | 4,671 | 0.000214 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Coho documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 4 22:59:13 2017.
#
# 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
# autog... | per').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTe... | o.tex', 'Coho Documentation',
'Ben Cornett', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'coho', 'Coho Documentation',
[... |
dpendl00/headphones | lib/beetsplug/fetchart.py | Python | gpl-3.0 | 11,700 | 0.000085 | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | downloading art: {0}'.format(url))
try:
with closing(requests_session.get(url, stream=True)) as resp:
if 'Content-Type' not in resp.headers \
or resp.headers['Content-Type'] not in CONTENT_TYPES:
log.debug(u'fetchart: not an image')
return
... | with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, delete=False) \
as fh:
for chunk in resp.iter_content():
fh.write(chunk)
log.debug(u'fetchart: downloaded art to: {0}'.format(
util.displayable_path(fh.name)
))
... |
s-hertel/ansible | lib/ansible/cli/scripts/ansible_connection_cli_stub.py | Python | gpl-3.0 | 12,922 | 0.002476 | #!/usr/bin/env python
# Copyright: (c) 2017, 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
__requires__ = ['ansible_core']
import fcntl
import hashlib
import os
impor... | while True:
data = recv_data(s)
if not data:
break
log_messages = self.connection.get_option('persistent_log_messages')
if log_messages:
display.display("jsonrpc request: % | s" % data, log_only=True)
request = json.loads(to_text(data, errors='surrogate_or_strict'))
if request.get('method') == "exec_command" and not self.connection.connected:
self.connection._connect()
signal.alarm(self.connection.get_opti... |
shimpe/frescobaldi | frescobaldi_app/widgets/colorbutton.py | Python | gpl-2.0 | 3,109 | 0.002573 | # This file is part of the Fr | escobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, | or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy o... |
rkwitt/quicksilver | code/vectormomentum/Code/Python/Libraries/CAvmCommon.py | Python | apache-2.0 | 34,587 | 0.03669 | from PyCA.Core import *
import PyCA.Common as common
import numpy as np
import matplotlib.pyplot as plt
def SplatSafe(outMass, g, mass):
mType = mass.memType()
if mType == MEM_DEVICE:
minmaxl = MinMax(mass)
maxval = max([abs(x) for x in minmaxl])
if maxval > 2000.00:
... | 1.0)
CoAdInf(scratchV, mhat ,m)
Sub_I(out_v, scratchV)
diffOp.applyInverseOperator(out_v)
return out_v
# end ComputeVhat
def EvaluateRHSFwd(out_v, v, phi):
'''
Evaluate RHS for forward integration of \frac{d\phi}{dt}=v\circ\phi
'''
ApplyH(out_v, v, phi, BACKGROUND_STRATEGY_PART... | '''
'''
#first compute vhat_t
ComputeVhat(out_v, scratchV, I, Ihat, m, mhat, diffOp)
#compute Dvmhat
JacobianXY(scratchV, v, mhat)
#Add both
Add_I(scratchV, out_v)
#deform
ApplyH(out_v, scratchV, g, BACKGROUND_STRATEGY_PARTIAL_ZERO);
return out_v
#end EvaluateRHSBwd
def In... |
milmd90/TwitterBot | twitter/_file_cache.py | Python | apache-2.0 | 5,588 | 0.002326 | #!/usr/bin/env python
import errno
import os
import re
import tempfile
from hashlib import md5
class _FileCacheError(Exception):
"""Base exception class for FileCache related errors"""
class _FileCache(object):
DEPTH = 3
def __init__(self, root_directory=None):
self._InitializeRootDirectory(ro... | s from feed; object does all computation on construction
properties:
RT, MT - boolean
URLs - list of URL
Hashtags - list of tags
"""
self.Owner = timeline_owner
self.tw | eet = tweet
self.UserHandles = ParseTweet.getUserHandles(tweet)
self.Hashtags = ParseTweet.getHashtags(tweet)
self.URLs = ParseTweet.getURLs(tweet)
self.RT = ParseTweet.getAttributeRT(tweet)
self.MT = ParseTweet.getAttributeMT(tweet)
# additional intelligence
if ... |
ESOedX/edx-platform | openedx/core/djangoapps/credit/models.py | Python | agpl-3.0 | 28,155 | 0.001634 | # -*- coding: utf-8 -*-
"""
Models for Credit Eligibility for courses.
Credit courses allow students to receive university credit for
successful completion of a course on EdX
"""
from __future__ import absolute_import
import datetime
import logging
from collections import defaultdict
import pytz
import six
from con... | zy(
"Plain text or html content for displaying custom message inside "
"credit eligibility email content which is sent when user has met "
"all credit eligibility requirements."
)
)
receipt_email_message = models.TextField(
default="",
help_text=ugett... | "credit receipt email content which is sent *after* paying to get "
"credit for a credit course."
)
)
thumbnail_url = models.URLField(
default="",
max_length=255,
help_text=ugettext_lazy(
"Thumbnail image url of the credit provider."
)
)
... |
aek/solt_sftp | src/solt_sftp/__init__.py | Python | mit | 1,132 | 0.000883 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015 Axel | Mendoza <aekroft@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the | rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions ... |
rapidpro/ureport-web-participation | features/environment.py | Python | agpl-3.0 | 1,127 | 0.006211 | import time
import uuid as uuid
from splinter.browser import Browser
from django.contrib.auth.models import User
from webparticipation.apps.ureporter.models import Ureporter
from webparticipation.apps.ureport_auth.models import PasswordReset
def before_all(context):
context.browser = Browser('chrome')
time.sle... | me1 = 'user999999991'
uid = uuid.uuid4()
uid1 = uuid.uuid4()
Ureporter.objects.create(uuid=uid,
user=User.objects.create_user(username=username, email=email, password=password))
Ureporter.objects.create(uuid=uid1,
user=User.objects.create_user(u... | te()
Ureporter.objects.all().delete()
PasswordReset.objects.all().delete()
def after_all(context):
context.browser.quit()
context.browser = None
context.server = None |
mistydemeo/gyp | pylib/gyp/xcode_emulation.py | Python | bsd-3-clause | 55,087 | 0.00777 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This module contains classes that help to emulate xcodebuild behavior on top of
other build systems, such as make and ninja.
"""
import copy
import gyp.common... | spec.get('product_extension', wrapper_extension)
elif self.spec['type'] == 'executable':
return '.' + self.spec.get('product_extension', 'app')
else:
assert False, "Don't know extension for '%s', target '%s'" % (
self.spec['type'], self.spec['target_name'])
def GetProductName(self):
... | Returns PRODUCT_NAME."""
return self.spec.get('product_name', self.spec['target_name'])
def GetFullProductName(self):
"""Returns FULL_PRODUCT_NAME."""
if self._IsBundle():
return self.GetWrapperName()
else:
return self._GetStandaloneBinaryPath()
def GetWrapperName(self):
"""Returns... |
andyraib/data-storage | python_scripts/env/lib/python3.6/site-packages/matplotlib/tests/test_figure.py | Python | apache-2.0 | 6,508 | 0.000154 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import xrange
from nose.tools import assert_equal, assert_true
from matplotlib.testing.decorators import image_comparison, cleanup
from matplotlib.axes import Axes
import matplotlib.p... | = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=MyClass())
plt.close(fig)
@cleanup
d | ef test_set_fig_size():
fig = plt.figure()
# check figwidth
fig.set_figwidth(5)
assert_equal(fig.get_figwidth(), 5)
# check figheight
fig.set_figheight(1)
assert_equal(fig.get_figheight(), 1)
# check using set_size_inches
fig.set_size_inches(2, 4)
assert_equal(fig.get_figwidth... |
Yelrado/evadoc | languages/es.py | Python | gpl-3.0 | 22,321 | 0.022446 | # coding: utf-8
{
'!langcode!': 'es',
'!langname!': 'Español',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN',
'%d days ago'... | errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.',
'cannot create file': 'no es posible crear archivo',
'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"',
'Change Password': 'Cambie la Contraseña',
'Change pa | ssword': 'Cambie la contraseña',
'change password': 'cambie la contraseña',
'check all': 'marcar todos',
'Check to delete': 'Marque para eliminar',
'clean': 'limpiar',
'Clear CACHE?': '¿Limpiar CACHÉ?',
'Clear DISK': 'Limpiar DISCO',
'Clear RAM': 'Limpiar RAM',
'Click on the link %(link)s to reset your password': 'Puls... |
nycrecords/intranet | app/__init__.py | Python | mit | 1,884 | 0 | import datetime
import json
import os
from flask import Flask, abort, g, render_template, session, request
from flask_bootstrap import Bootstrap
from flask_login import LoginManager, current_user
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import con... | url_prefix="/auth")
@app.before_request
def before_req | uest():
app.permanent_session_lifetime = datetime.timedelta(minutes=15)
session.permanent = True
session.modified = True
g.user = current_user
@app.errorhandler(503)
def maintenance(e):
with open(os.path.join(app.instance_path, 'maintenance.json')) as f:
main... |
VitalPet/addons-onestein | hr_employee_number/models/hr_employee.py | Python | agpl-3.0 | 1,051 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = 'hr.employee'
employee_number = fields.Char(copy=False)
@api.model
def c... | number = get_employee_sequence(self.env['ir.sequence'])
if not self.search([
('employee_number', '=', number)
], limit=1):
vals['employee_number'] = number
searching = False
return super(HrEmployee, self).create(v... | ]
|
PeteCrighton/Praesence | praesence/xmlwitch.py | Python | mit | 3,819 | 0.001047 | from __future__ import with_statement
import sys
from xml.sax import saxutils
from keyword import kwlist as PYTHON_KWORD_LIST
is_py2 = sys.version[0] == '2'
if is_py2:
from StringIO import StringIO
else:
from io import StringIO
__all__ = ['Builder', 'Element']
__license__ = 'BSD'
__version__ = ... | e().decode(self._encoding).strip()
else:
return self._document.getvalue()
def write(self, content):
"""Write raw content to the document"""
if is_py2 and type(content) is not unicode:
content = content.decode(self._encoding)
self._document.writ | e('%s' % content)
def write_escaped(self, content):
"""Write escaped content to the document"""
self.write(saxutils.escape(content))
def write_indented(self, content):
"""Write indented content to the document"""
self.write('%s%s\n' % (self._indent * self._indentation, ... |
antoinecarme/pyaf | tests/artificial/transf_None/trend_PolyTrend/cycle_12/ar_12/test_artificial_32_None_PolyTrend_12_12_20.py | Python | bsd-3-clause | 260 | 0.088462 | i | mport pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order = 12 | ); |
willkuhn/wingrid | setup.py | Python | gpl-3.0 | 528 | 0.003788 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md',encoding='utf-8') as f:
readme = f.read()
with open('LICENSE',encoding='utf-8') as f:
license = f.read()
setup(
name='wingrid',
version='0.1.0',
description='Quantitatively compare appearances of insect wi... | ',
url='https://github.com/willkuhn/wingrid',
license=license,
packages=find_pa | ckages()
)
|
ivaano/zato | code/zato-web-admin/test/zato/admin/web/views/__init__.py | Python | gpl-3.0 | 154 | 0 | # -*- codin | g: utf-8 -*-
"""
Copyright (C) 2012 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPL | v3, see LICENSE.txt for terms and conditions.
"""
|
ioggstream/mysql-utilities | mysql/fabric/protocols/xmlrpc.py | Python | gpl-2.0 | 28,648 | 0.000803 | #
# Copyright (c) 2013,2014, Oracle and/or its affiliates. All rights reserved.
#
# 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; version 2 of the License.
#
# This program is distributed in the... | ddr=client_address[0],
expires=str(AUTH_EXPIRES))
).hexdigest()
return b64encode(data + ';' + str(AUTH_EXPIRES))
def _digest_denonce(nonce):
data, expires = b64decode(nonce).split(';')
return data, int(expires)
def _auth_id(client_address, username, realm):
return sha1(':'.join([... | :
(_, attrstr) = header.split(' ', 1)
matches = _RE_DIGEST_AUTH_HEADER.split(attrstr)
allowed = ('username', 'realm', 'nonce', 'response',
'nc', 'cnonce', 'qop', 'algorithm', 'uri',
'opaque')
attrs = {}
if matches:
for match in matches:
key, value ... |
jdfekete/progressivis | progressivis/stats/min.py | Python | bsd-2-clause | 5,630 | 0.000533 | from __future__ import annotations
import logging
import numpy as np
from ..core.utils import indices_len, fix_loc
from ..core.bitmap import bitmap
from ..core.module import ReturnRunStep
from ..table.module import TableModule
from ..table.table import Table
from ..core.slot import SlotDescriptor, Slot
from ..utils.... | .reset_all(slot, run_number)
# else : deletes are not sensitive, just ignore them
if slot.updated.any():
sensitive_update_ids = slot.updated.changes & sensitive_ids_bm
if sensitive_update_ids and self.are_critical(
sensitive_update_ids, slot.data()
... | ight become greater than the current MIN
# so we will process these updates as creations
# and we avoid a reset
indices = slot.updated.next(length=step_size, as_slice=False)
if indices is None:
if not slot.created.any():
return self._re... |
python-cmd2/cmd2 | cmd2/plugin.py | Python | mit | 847 | 0.001181 | #
# coding=utf-8
"""Classes for the cmd2 plugin system"""
from typing import (
Optional,
)
import attr
from .parsing import (
Statement,
)
@attr.s(auto_attribs=True)
class Postpars | ingData:
"""Data class containing information passed to postparsing hook methods"""
stop: bool
statement: Statement
@attr.s(auto_attribs=True)
class PrecommandData:
"""Data class containing information passed t | o precommand hook methods"""
statement: Statement
@attr.s(auto_attribs=True)
class PostcommandData:
"""Data class containing information passed to postcommand hook methods"""
stop: bool
statement: Statement
@attr.s(auto_attribs=True)
class CommandFinalizationData:
"""Data class containing info... |
notapresent/rtrss | tests/test_torrentfile.py | Python | apache-2.0 | 2,078 | 0 | import unittest
import bencode
from rtrss import torrentfile
testdata = dict({'some key': 'some value'})
encoded_testdata = bencode.bencode(testdata)
class TorrentFileTestCase(unittest.TestCase):
def test_torrentfile_decoded_equals_encoded(self):
tf = torrentfile.TorrentFile(encoded_testdata)
... | def test_add_announce_reflected_in_encoded(self):
tf = torrentfile.TorrentFile(testdata)
test_announcer = 'test announcer'
tf.add_announcer(test_announcer)
decoded = bencode.bdecode(tf.encoded)
self.assertIn('announce', decoded)
self.as | sertEqual(test_announcer, decoded['announce'])
def test_init_raises_valueerror(self):
with self.assertRaises(ValueError):
_ = torrentfile.TorrentFile(None)
|
mhbu50/erpnext | erpnext/hr/doctype/leave_period/test_leave_period.py | Python | gpl-3.0 | 775 | 0.028387 | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
import erpnext
test_dependencies = ["Employee", "Leave Type", "Leave Policy"]
class TestLeavePeriod(unittest.TestCase):
pass
def create_leave_period(from_date, to_date, company=None):
leave_perio... | ctive=1), 'name')
if leave_period:
return frappe.get_doc("Leave Period", leave_period)
leave_period = frappe.get_doc({
"doctype": "Leave Period",
"company": company or erpnext.ge | t_default_company(),
"from_date": from_date,
"to_date": to_date,
"is_active": 1
}).insert()
return leave_period
|
KerstenDoering/PubMed2Go | full_text_index/search_not_title_or_text.py | Python | isc | 3,389 | 0.011213 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Copyright (c) 2014, Kersten Doering <kersten.doering@gmail.com>, Bjoern Gruening <bjoern.gruening@gmail.com>
"""
#Kersten Doering 17.06.2014
#check http://xapian.org/docs/queryparser.html for syntax and functions
import xappy
conn = xappy.SearchConnection("xapian... | "%s\t%s\t%s\t%s" % (result.rank, result.id,results.g | et_hit(index).highlight('title')[0], "<i>no abstract</i>")
#HTML output:
#open HTML file
outfile = open("Xapian_query_results_NOT.html","w")
#document header
start_string = """
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="content-type" conte... |
drorasaf/mongomock | mongomock/collection.py | Python | bsd-3-clause | 73,434 | 0.000994 | from __future__ import division
import collections
from collections import OrderedDict
import copy
from datetime import datetime
import functools
import itertools
import json
import math
import threading
import time
import warnings
try:
from bson import json_util, SON
except ImportError:
json_utils = SON = Non... | return {'nRemoved': op_result.get('n')}
err = op_result.get("err")
if err:
return {"writeErrors": [err]}
return {}
self.builder.executors.append(exec_remove)
def remove(self):
assert not self.is_upsert
self.r | egister_remove_op(multi=True)
def remove_one(self,):
assert not self.is_upsert
self.register_remove_op(multi=False)
def register_update_op(self, document, multi, **extra_args):
if not extra_args.get("remove"):
validate_ok_for_update(document)
collection = self.buil... |
mindriot101/fitsio-cffi | testing/test_direct_wrapper.py | Python | mit | 1,990 | 0 | import os
import pytest
from cffitsio._cfitsio import ffi, lib
@pytest.fixture
def fits_open_file(test_file):
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_open_file(f, test_file.encode('utf-8'), 0, status)
assert status[0] == 0
return (f, status)
def test_create_file(tmpdir):
... | f, test_file.encode('utf-8'), 0, status)
assert status[0] = | = 0
lib.fits_close_file(f[0], status)
assert status[0] == 0
def test_get_hdu_num(fits_open_file):
f, status = fits_open_file
# Should be open on the first hdu
hdunum = ffi.new('int *')
lib.fits_get_hdu_num(f[0], hdunum)
assert hdunum[0] == 1
def test_fits_movabs_hdu(fits_open_file):
... |
cupy/cupy | tests/cupyx_tests/scipy_tests/special_tests/test_erf.py | Python | mit | 4,572 | 0 | import unittest
import numpy
import cupy
from cupy import testing
import cupyx.scipy.special # NOQA
def _boundary_inputs(boundary, rtol, atol):
left = boundary * (1 - numpy.copysign(rtol, boundary)) - atol
right = boundary * (1 + numpy.copysign(rtol, boundary)) + atol
return [left, boundary, right]
c... | ndom(self, name, xp, scp, dtype, scale, offset):
import scipy.special # NOQA
a = testing.shaped_random((2, 3), xp, dtype, scale=scale) + offset
@cupy.fuse()
def f(x):
return getattr(scp.special, name)(x)
return f(a)
@testing.for_dtypes( | ['f', 'd'])
@testing.numpy_cupy_allclose(atol=1e-5, scipy_name='scp')
def check_unary_boundary(self, name, xp, scp, dtype, boundary):
import scipy.special # NOQA
a = _boundary_inputs(boundary, 1.0 / 1024, 1.0 / 1024)
a = xp.array(a, dtype=dtype)
@cupy.fuse()
def f(x):
... |
dichen001/Go4Jobs | JackChen/Google/10. Regular Expression Matchi.py | Python | gpl-3.0 | 1,031 | 0.00291 | class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if not s or not p:
return False
ls, lp = len(s), len(p)
mem = [[False] * (lp+1) for _ in range(ls+1)]
mem[0][0] = True
... | if p[j-1] == '*' and mem[0][j-2]:
mem[0][j] = True
# precess others
for i in range(1, ls+1):
for j in range(1, lp+1):
if s[i-1] == p[j-1] or p[j-1] == '.':
| mem[i][j] = mem[i-1][j-1]
if p[j-1] == '*':
if p[j-2] != s[i-1] and p[j-2] != '.':
mem[i][j] = mem[i][j-2]
else:
mem[i][j] = mem[i][j-2] or mem[i][j-1] or mem[i-1][j]
return mem[ls][lp]
s = Solutio... |
andrewjrobinson/SportsReview | sportsreview/common/modulemanager.py | Python | lgpl-3.0 | 6,326 | 0.00743 | # /*******************************************************************************
# * (c) Andrew Robinson (andrewjrobinson@gmail.com) 2014 *
# * *
# * This file is part of SportsReview. ... | try:
if obj.__PROCESS_FRAME__ == True:
cls._processframemodules[str(name)] = obj
except:
pass
return cls._processframemodules.values()
@classmethod
def getProcessFrameModule | (cls, name):
'''Gets a single Process frame module by name'''
cls.getProcessFrameModules(False)
return cls._processframemodules[str(name)]
################################
@classmethod
def getCaptureGroupModules(cls, refresh=True):
'''Gets a list of all cap... |
fpischedda/yaff | setup.py | Python | bsd-3-clause | 1,425 | 0 | import sys
from setuptools | import setup
version = __import__('yaff').__version__
if sys.hexversion < 0x02070000:
EXTRA_INSTALL_REQUIRES = ['backport_collections']
else:
EX | TRA_INSTALL_REQUIRES = []
setup(
name='yaff',
version=version,
description='Yet Another Faield Framework',
author='Francesco Pischedda',
author_email='francesco.pischedda@gmail.com',
url='https://github.com/fpischedda/yaff',
packages=('yaff', 'yaff.conf', 'yaff.animation', 'yaff.animation.l... |
PyQuake/earthquakemodels | code/cocobbob/coco/code-postprocessing/cocopp/genericsettings.py | Python | bsd-3-clause | 16,876 | 0.006459 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""This module contains some variables settings for COCO.
These variables are used for producing figures and tables
in rungeneric1, -2, and -many.
For setting variables dynamically see config.py, where some
of the variables here and some
"""
import numpy as np
test... | (10, 1.0, 1e-1, 1e-3, 1e-5, 1.0e-8)
dim_related_markers = ('+', 'v', '*', 'o', 's', 'D', 'x')
dim_related_colors = ('c', 'g', 'b', 'k', 'r', 'm', 'k', 'y', 'k', 'c', 'r', 'm')
rldDimsOfInterest = (5, 20)
simulated_runlength_bootstrap_sample_size = 10 + 990 / (1 + 10 * max((0, in_a_hurry))) # for tables and plots
... | n pprldistr.plot method, on graph for each
# single_target_function_values = (1e1, 1e0, 1e-1, 1e-2, 1e-4, 1e-6, 1e-8) # one figure for each, seems not in use
# summarized_target_function_values = (1e0, 1e-1, 1e-3, 1e-5, 1e-7) # currently not in use, all in one figure (graph?)
# summarized_target_function_values = (1... |
jplevyak/pyc | tests/t24.py | Python | bsd-3-clause | 62 | 0.048387 | y = 2
class b:
def g(self):
| print y
a = b()
| x = a.g
x()
|
kerkeslager/sandbox | mini/mini.py | Python | mit | 27,970 | 0.011191 | from __future__ import print_function
import re
import traceback
class MiniObject(object):
def __init__(self, py_object, **meta):
( "The following python types map to the following mini types:\n"
" bool -> boolean\n"
" str -> string\n"
" int -> integer\n"
... | llection):
result = NIL
for item in reversed(py_collection):
result = MiniObject(MiniPair(item, result))
return result
def cons_collection_to_py_collection(cons_collection):
while cons_collection != NIL:
yield car(cons_collection)
cons_collection = cdr(cons_collection)
to | ken_regex = re.compile(r'''(?mx)
(\s*|\#.*?\n)*(?:
(?P<open_parenthese>\()|
(?P<close_parenthese>\))|
(?P<number>\-?\d+\.\d+|\-?\d+)|
(?P<string>"[^"]*")|
(?P<identifier>[_A-Za-z\?\-\+\*/=\>\<]+)|
(?P<symbol>\:[_A-Za-z\?\-\+\*/=\>\<]*)
)''')
def parse_all(source):
def parse(matches,... |
kball/ambry | ambry/cli/source_run/count_deps.py | Python | bsd-2-clause | 260 | 0.015385 | '''Script for source run to print the umber of dependencies that a source bundle has'''
def run(args, bundle_dir, bundle, repo):
#if bundle.is_built:
# return
deps = bundle.config.build.get('dependencies',{})
print len(deps), bu | ndle_dir
| |
feibl/search-rex | tests/test_views_case_based.py | Python | mit | 6,795 | 0 | from test_base import BaseTestCase
from search_rex.recommendations.data_model.case_based import\
InMemoryQueryDataModel
from search_rex.recommendations.data_model.case_based import\
PersistentQueryDataModel
from search_rex.recommendations.neighbourhood.case_based import\
ThresholdQueryNeighbourhood
from sea... | d_search_results(query_caesar, max_num_recs=2)
records = [rec.record_id for rec in recs]
assert records == [record_caesar, record_brutus]
def test__recommend_search_results__include_internal_documents(self):
views = view_matrix
| copies = copy_matrix
include_internal_records = True
def recommend_search_results(query_string, max_num_recs=10):
return self.recommend_search_results(
query_string, include_internal_records, max_num_recs)
import_test_data(views=views, copies=copies)
... |
SHSIDers/oclubs | oclubs/filters/__init__.py | Python | mit | 462 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
"""oclubs filters."""
from __future__ import absolute_import
from oclubs.filters.resfilter import ResFilter, ResFilterConverter
from oclubs.filters.clubfilter import ClubFilter, ClubFilterConverter
from oclubs.filters.roomfilter import RoomFilter, RoomFilterConverter
... | mFilterConverter']
| |
lepture/mardict | utils/helper.py | Python | bsd-3-clause | 2,325 | 0.00043 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
help_txt = """
:help, show this help menu. :help [command] for detail
:dict [word], only find translation on dict.cn
:google [sentence], only find translation on google api
:lan2lan [sentence], translate from one language to another language
:add [word], add new word to yo... | clear
"""
help_add = """
help on add:
[usage] :add (word)
[intro] add the new word to your library(storing your unfamiliar word)
[eg] :add hello
more on http://mard | ict.appspot.com/help/#add
"""
help_del = """
help on del:
[usage] :del word
[intro] delete the word from your library
[eg] :del hello
more on http://mardict.appspot.com/help/#del
"""
help_list = """
help on list:
[usage] :list (number)
[intro] list a certain number of words from your library.
[eg] :list 9
this func... |
googleapis/python-dlp | samples/generated_samples/dlp_v2_generated_dlp_service_inspect_content_async.py | Python | apache-2.0 | 1,405 | 0.000712 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 per... | ated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dlp
# [START dlp_v2_generated_DlpService_InspectContent_async]
from google.cloud import dlp_v2
async ... |
colloquium/spacewalk | backend/spacewalk/common/__init__.py | Python | gpl-2.0 | 607 | 0 | #
# Copyright (c) 2009 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOS | E. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this softwar | e or its documentation.
#
|
yotamfr/prot2vec | src/python/prot2vec.py | Python | mit | 23,941 | 0.002088 | #!/usr/bin/env python
from gensim import matutils
from gensim.models import doc2vec
from gensim.models.word2vec import LineSentence
from gensim.models.word2vec import Word2Vec
from pymongo import MongoClient
from tqdm import tqdm
from sklearn.preprocessing import OneHotEncoder
from scipy import sparse
from models im... | _length = args["seq_length"]
emb_dim = args["word_embedding_dim"]
datapath = args["data_path"]
ECOD = args['ecod_fasta']
PDB = args['pdb_fasta']
PDBNR = args['pdbnr_fasta']
UNIPROT = args['uniprot_sprot_fasta']
client = MongoClient('mongodb://localhost:27017/')
dbname = args["db"]
db = client[dbname]
consts = {
... | DGE_GRAPHICS": lambda: {
'width': 1.0,
'fill': '"#889999"',
'type': '"line"'
},
"NODE_GRAPHICS": lambda: {
'x': np.random.randint(-10e3, 10e3)
, 'y': np.random.randint(-10e3, 10e3)
, 'w': 20.0, 'h': 20.0
, 'type': '"ellipse"', 'fill': '"#0000ff"'
,... |
toinsson/pyrealsense | setup.py | Python | apache-2.0 | 2,524 | 0.000792 | from setuptools import find_packages
from os import path, environ
import io
import | os
import re
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy as np
def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf8")
) as fp:
re... | sion(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# fetch include and librar... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/cryptography/hazmat/primitives/cmac.py | Python | bsd-3-clause | 2,221 | 0 | # This fi | le is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
AlreadyFi... | rs, mac
@utils.register_interface(mac.MACContext)
class CMAC(object):
def __init__(self, algorithm, backend, ctx=None):
if not isinstance(backend, CMACBackend):
raise UnsupportedAlgorithm(
"Backend object does not implement CMACBackend.",
_Reasons.BACKEND_MISSIN... |
xaxa89/mitmproxy | setup.py | Python | mit | 4,202 | 0.000952 | import os
import runpy
from codecs import open
from setuptools import setup, find_packages
# Based on https://github.com/pypa/sampleproject/blob/master/setup.py
# and https://python-packaging-user-guide.readthedocs.org/
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), en... | 1, <1.1",
"h2>=3.0, <4",
"html2text>=2016.1.8, <=2016.9.19",
"hyperframe>= | 5.0, <6",
"jsbeautifier>=1.6.3, <1.7",
"kaitaistruct>=0.6, <0.7",
"passlib>=1.6.5, <1.8",
"pyasn1>=0.1.9, <0.3",
"pyOpenSSL>=16.0, <17.0",
"pyparsing>=2.1.3, <2.3",
"pyperclip>=1.5.22, <1.6",
"requests>=2.9.1, <3",
"ruamel.yaml>=0.13.2, <0.15",
... |
ddipp/Euler_solutions | p021.py | Python | gpl-2.0 | 1,443 | 0.000694 | #!/usr/bin/env python3
# ===============================================================================
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n
# which divide evenly into n).
# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and
# each of a and b are call... | nd(n)
return lis
de | f ListToDict(lis):
d = {}.fromkeys(lis, 0)
for i in lis:
d[i] += 1
return d
def divisors(n):
df = ListToDict(PrimeFactors(n))
div = [1]
for p, r in df.items():
div = [d * p**e for d in div for e in range(r + 1)]
div.sort()
return div[:-1]
def solution():
s = 0
... |
sam81/pysoundanalyser | pysoundanalyser/dialog_generate_sound.py | Python | gpl-3.0 | 34,547 | 0.015052 | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2017 Samuele Carcagno <sam.carcagno@gmail.com>
# This file is part of pysoundanalyser
# pysoundanalyser 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 Foundatio... | ignTop)
self.hbl.addLayout(self.grid_0)
self.hbl.addLayout(self.grid_1)
self.scrollAreaWidgetContents = QWidget()#QFrame()
#self.scrollAreaW | idgetContents.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
self.scrollAreaWidgetContents.setLayout(self.hbl)
self.scrollArea = QScrollArea()
#self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollAreaWidgetContent... |
SimenB/thefuck | thefuck/rules/cd_mkdir.py | Python | mit | 578 | 0 | import re
from thefuck.utils import for_app
from thefuck.specific.sud | o import sudo_support
from thefuck.shells import shell
@sudo_support
@for_app('cd')
def match(command):
return (
command.script.startswith('cd ') and any((
'no such file or directory' in command.output.lower(),
'cd: can\'t cd to' in command.output.lower(),
'does not exi... | dir -p \\1', 'cd \\1')
return re.sub(r'^cd (.*)', repl, command.script)
|
MicroPyramid/Django-CRM | invoices/serializer.py | Python | mit | 3,430 | 0 | from rest_framework import serializers
from invoices.models import Invoice, InvoiceHistory
from common.serializer import (
UserSerializer,
OrganizationSerializer,
BillingAddressSerializer,
)
from teams.serializer import TeamsSerializer
class InvoiceSerailizer(serializers.ModelSerializer):
from_address... | request_obj = kwargs.pop("request_obj", None)
super(InvoiceCreateSerializer, self).__init__(*args, **kwargs)
self.org = request_obj.org
def validate_invoice_title(self, invoice_title):
if self.instance:
if (
Invoice.objects.filter(
invoi... | voice_title, org=self.org
)
.exclude(id=self.instance.id)
.exists()
):
raise serializers.ValidationError(
"Invoice already exists with this invoice_title"
)
else:
if Invoice.objects.filter... |
ggyeh/TVML-Kodi-Addons | scripts/kodi_utils.py | Python | apache-2.0 | 14,730 | 0.007739 | import base64, random, string, sys, os, logging, json, re, bs4, cgi
from StringIO import StringIO
import struct
from contextlib import contextmanager
import sqlite3, time
import multiprocessing
from globals import PROCESSES, REPOSITORIES, SERVICES
logger = logging.getLogger(__name__)
PROXY_CONFIG='proxy_mode'
LANGUAGE... | ans['string'])
return ans
except:
logger.exception('Encountered error in get_config')
return _default
def set_config(id, value):
for i in range(10):
try:
value = json.dumps(value)
with open_db() as DB:
DB.execute('update CONFIG set string=... | DB.execute('insert into CONFIG values(?,?)', (id, value, ))
trigger(TRIGGER_CONFIG_CHANGED, {'id': id, 'value': value})
break
except sqlite3.OperationalError:
time.sleep(1)
except:
logger.exception('Failed to update DB')
break
def get_pla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.