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 |
|---|---|---|---|---|---|---|---|---|
python-cmd2/cmd2 | cmd2/py_bridge.py | Python | mit | 4,605 | 0.001303 | # coding=utf-8
"""
Bridges calls made inside of a Python environment to the Cmd2 host app
while maintaining a reasonable degree of isolation between the two.
"""
import sys
from contextlib import (
redirect_stderr,
redirect_stdout,
)
from typing import (
IO,
TYPE_CHECKING,
Any,
List,
NamedT... | """Returns True if the command succeeded, otherwise False"""
# If data was set, then use it to determine success
if self.data is not None:
return bool(self.data)
# Otherwise check if stderr was filled out
else:
return not self.stderr
class PyBridge:
""... | cmd2.Cmd') -> None:
self._cmd2_app = cmd2_app
self.cmd_echo = False
# Tells if any of the commands run via __call__ returned True for stop
self.stop = False
def __dir__(self) -> List[str]:
"""Return a custom set of attribute names"""
attributes: List[str] = []
... |
pordnajela/AlgoritmosCriptografiaClasica | Transposicion/TransposicionGrupo.py | Python | apache-2.0 | 3,845 | 0.036468 | #!/usr/bin/env python3
# -*- co | ding: UTF-8 -*-
class TransposicionGrupo(object):
"""
"""
def __init__(self, cadena=None, clave=None):
self.cadena = cadena #Recibe una lista, la longitud de cada elemento es a longitud de la clave
self.clave = clave
self.textoClaro = ""
self.textoCifrado = ""
sel | f.caracterRelleno = "₫" #₫
def cifrar(self, cantidadRellenoB64=0):
textoCifrado = ""
linea_a_cifrar = None
saltosLinea = len(self.cadena)-1
i = 0
for linea in self.cadena:
if i < saltosLinea:
linea_a_cifrar = self.dividirGrupos(linea,cantidadRellenoB64)
textoCifrado = textoCifrado + self.__cifrar... |
daryl314/markdown-browser | pycmark/cmarkgfm/CmarkDocument.py | Python | mit | 3,664 | 0.002729 | import ctypes
from . import cmarkgfm
from ..util.TypedTree import TypedTree
cmarkgfm.document_to_html.restype = ctypes.POINTER(ctypes.c_char)
class CmarkDocument(object):
def __init__(self, txt, encoding='utf_8'):
if not isinstance(txt, bytes):
txt = txt.encode(encoding=encoding)
sel... | :
tag = cmarkgfm.cmark_node_get_type_string(node).decode()
if tag == 'table' and children is None:
return cls._tableToAST(node)
elif tag == 'list' and len(attr) == 0:
return cls._listToAST(node)
if children is None:
children = [cls._toAST(c) for c in... | m.cmark_node_get_literal(node).decode()
if tag == 'heading':
attr['Level'] = cmarkgfm.cmark_node_get_heading_level(node)
if tag == 'code_block':
attr['Info'] = cmarkgfm.cmark_node_get_fence_info(node).decode()
if tag in {'link', 'image'}:
attr['Destination'] =... |
augustoqm/MCLRE | src/recommender_execution/run_rec_mrbpr.py | Python | gpl-3.0 | 5,871 | 0.002044 | #!/usr/bin/python
# =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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 Lice... | #########
# AUXILIAR FUNCTIONS
##############################################################################
def get_mrbpr_confs():
""" Yield the MRBPR Models Configurations """
pass
##############################################################################
# MAIN
########################################... | # ------------------------------------------------------------------------
# Define the argument parser
PARSER = ArgumentParser(description="Script that runs the mrbpr event recommender algorithms for" \
" a given 'experiment_name' with data from a given 'region'")
... |
honzajavorek/tipi | tipi/repl.py | Python | mit | 2,146 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from tipi.compat import unicode
f | rom tipi.html import HTMLFragment
__all__ = ('Replacement', 'replace')
class Replacement(object):
"""Replacement representation."""
skipped_tags = (
'code', 'kbd', 'pre', 'samp', 'script', 'style', 'tt', 'xmp'
)
textflow_tags = (
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'c... | pattern, replacement):
self.pattern = pattern
self.replacement = replacement
def _is_replacement_allowed(self, s):
"""Tests whether replacement is allowed on given piece of HTML text."""
if any(tag in s.parent_tags for tag in self.skipped_tags):
return False
if a... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_recoverable_databases_operations.py | Python | mit | 10,559 | 0.004072 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | n_id: str,
resource_group_name: str,
server_name: str,
**kwargs: Any
) -> HttpRequest:
a | pi_version = "2014-04-01"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recoverableDatabases')
path_format_arguments = {
"subscriptionId": _SERIALIZER.u... |
explosion/spaCy | spacy/tests/lang/da/test_exceptions.py | Python | mit | 1,824 | 0.000551 | import pytest
@pytest.mark.parametrize("text", ["ca.", "m.a.o.", "Jan.", "Dec.", "kr.", "jf."])
def test_da_tokenizer_handles_abbr(da_tokenizer, text):
tokens = da_tokenizer(text)
assert len(tokens) == 1
@pytest.mark.parametrize("text", ["Jul.", "jul.", "Tor.", "Tors."])
def test_da_tokenizer_handles_ambigu... | "Netværket kører over TCP/IP", 4),
],
)
def test_da_tokenizer_slash(da_tokenizer, text, n_tokens):
tokens = da_tokenizer(text)
assert len(tokens) == | n_tokens
|
plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/_legendrank.py | Python | mit | 406 | 0.002463 | import _plotly_utils.basevalidators
class LegendrankValidator(_plotly_ | utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="legendrank", parent_name="scatter", **kwargs):
super(LegendrankValidator, self).__init__(
| plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs
)
|
chenc10/Spark-PAF | examples/src/main/python/mllib/gradient_boosting_regression_example.py | Python | apache-2.0 | 2,443 | 0.001637 | #
# 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 us... | sions and
# limitations under the License.
#
"""
Gradient Boosted Trees Regression Example.
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
# $example on$
from pyspark.mllib.tree import GradientB | oostedTrees, GradientBoostedTreesModel
from pyspark.mllib.util import MLUtils
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonGradientBoostedTreesRegressionExample")
# $example on$
# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_da... |
django-bmf/django-bmf | tests/appapis/test_sites_setting.py | Python | bsd-3-clause | 285 | 0 | # | !/usr/bin/python
# ex:set fileencoding=utf-8:
# flake8: noqa
from __future__ import unicode_literals
from django.test import TestCase
from unittest import expectedFailure
class SettingTests(TestCase):
@expectedFailure
def test_fails(self):
self.assertTrue(False)
| |
keighrim/kaldi-yesno-tutorial | steps/nnet3/chain/gen_topo3.py | Python | apache-2.0 | 1,879 | 0.008515 | #!/usr/bin/env python
# Copyright 2012 Johns Hopkins University (author: Daniel Povey)
# Generate a topology file. This allows control of the number of states in the
# non-silence HMMs, and in the silence HMMs. This is a modified version of
# 'utils/gen_topo.pl' that generates a different type of topology, one tha... | rt argparse
parser = argparse.ArgumentParser(description="Usage: steps/nnet3/chain/gen_topo.py "
"<colon-separated-nonsilence-phones> <colon-separated-silence-phones>"
"e.g.: steps/nnet3/chain/gen_topo.pl 4:5:6:7:8:9: | 10 1:2:3\n",
epilog="See egs/swbd/s5c/local/chain/train_tdnn_a.sh for example of usage.");
parser.add_argument("nonsilence_phones", type=str,
help="List of non-silence phones as integers, separated by colons, e.g. 4:5:6:7:8:9");
parser.add_argument("silence_phones", ... |
rchakra3/generic-experiment-loop | model/helpers/decision.py | Python | gpl-2.0 | 339 | 0 | import random
class Decision(object):
def __init__(self, name, min_val, ma | x_val):
self.name = name
self.min_val = min_val
self.max_val = max_val
def generate_valid_val(self):
return random.uniform(self.min_val, self.max_val)
def get_range(self):
return (self.min_v | al, self.max_val)
|
sou-komatsu/checkgear | checkgear/checkgear.py | Python | mit | 138 | 0.007246 | #!/usr/bin/env python
# coding: utf-8
class | CheckGear():
def __init__(self):
pass
def proc(self):
print | 'test'
|
bgxavier/nova | nova/objects/instance.py | Python | apache-2.0 | 57,332 | 0.000157 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | uid
# Version 1.13: Added delete_metadata_key()
# Version 1.14: Added numa_topology
# Version 1.15: PciDeviceList 1.1
# | Version 1.16: Added pci_requests
# Version 1.17: Added tags
# Version 1.18: Added flavor, old_flavor, new_flavor
# Version 1.19: Added vcpu_model
# Version 1.20: Added ec2_ids
VERSION = '1.20'
fields = {
'id': fields.IntegerField(),
'user_id': fields.StringField(nullable=True),... |
mozilla/normandy | normandy/recipes/management/commands/update_recipe_signatures.py | Python | mpl-2.0 | 2,612 | 0.001914 | from datetime import timedelta
import markus
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone
from normandy.recipes.models import Recipe
from normandy.recipes.exports import RemoteSettings
metrics = markus.get_metri... | ote_settings.approve_changes()
metrics.gauge("signed", count, tags=["force"] if force else [])
recipes_to_unsign = Recipe.objects.only_disabled().exclude(signature=None)
count = recipes_to_unsign.count()
if count == 0:
self.stdout.write("No disabled recipes to unsign")
... | + recipe.approved_revision.name)
sig = recipe.signature
recipe.signature = None
recipe.save()
sig.delete()
metrics.gauge("unsigned", count, tags=["force"] if force else [])
self.stdout.write("all signing done")
def get_outdated_recipe... |
huvermann/MyPiHomeAutomation | HomeAutomation/thingUtils.py | Python | mit | 125 | 0.016 | import platform
def is_windows():
"""Return | s true if current platform is windows"""
| return any(platform.win32_ver()) |
dowski/statvent | tests/test_thread_safety.py | Python | bsd-2-clause | 677 | 0.004431 | import threading
import Queue
import statvent
jobs = Queue.Queue()
done = Queue.Queue()
def do_inc():
while True:
job = jobs.get()
if job is None:
| done.put(None)
break
statvent.incr('thread.test')
def test_10k_iterations_in_N_threads_results_in_10k_incrs():
n = 25
threads = []
for i in xrange(n):
t = threading.Thread(target=do_inc)
t.start()
threads.append(t)
for i in xrange(5000):
jobs.put(i)
... | atvent.get_all()['thread.test']
assert actual == 5000, actual
|
balbinot/arghphot | arghphot/logutil.py | Python | mit | 652 | 0.010736 | import logging
import colorlog
from logging.config import fileConfig
import json
class mylogger():
def __init__(self, sdict, logfn):
fileConfig('./logging_config.ini', defaults={'logfilename': logfn})
self.logger = logging.getLogger()
self.sdict = sdict
#save or open | from json file
def __call__(self, type, key, value, msg):
if key:
self.sdict[key] = value
if type==1:
self.logger.info(msg)
elif type | ==2:
self.logger.warning(msg)
elif type==3:
self.logger.error(msg)
elif type==4:
self.logger.exception(msg)
|
JiaminXuan/leetcode-python | best_time_to_buy_and_sell_stock_iii/solution.py | Python | bsd-2-clause | 846 | 0 | class Solution:
# @param prices, a list of int | eger
# @return an integer
def maxProfit(self, prices):
if not prices:
return 0
n = le | n(prices)
m1 = [0] * n
m2 = [0] * n
max_profit1 = 0
min_price1 = prices[0]
max_profit2 = 0
max_price2 = prices[-1]
for i in range(n):
max_profit1 = max(max_profit1, prices[i] - min_price1)
m1[i] = max_profit1
min_price1 = min(mi... |
imk1/IMKTFBindingCode | processLolaResults.py | Python | mit | 4,260 | 0.026761 | import sys
import argparse
import numpy as np
def parseArgument():
# Parse the input
parser = argparse.ArgumentParser(description="Process results from LOLA")
parser.add_argument("--lolaResultsFileNameListFileName", required=True, help="List of file names with LOLA results")
parser.add_argument("--lolaHeadersFileN... | ue, help="Headers for database region lists used in LOLA")
parser.add_argument("--lolaHeadersExcludeFileName", required=False, default=None, \
help="Headers for database region lists used in LOLA that sh | ould not be included, should be subset of lolaHeadersFileName")
parser.add_argument("--fileNamePartsInHeader", action='append', type=int, required=False, default=[1], \
help="Parts of the file name that are in the lola headers, where parts are separated by .'s")
parser.add_argument("--outputFileName", required=True... |
bankonme/MUE-Src | qa/rpc-tests/test_framework.py | Python | mit | 4,729 | 0.003383 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
# Add python-bitcoinrpc to module search path:
import os
import sys
sys.path.app... | import logging
logging.basicConfig(level=logging.DEBUG)
os.environ['PATH'] = self.options.srcdir+":"+os.environ['PATH']
check_json_precision()
success = False
try:
if not os.path.isdir(self.options.tmpdir):
os.makedirs(self.options.tmpdir)... | success = True
except JSONRPCException as e:
print("JSONRPC error: "+e.error['message'])
traceback.print_tb(sys.exc_info()[2])
except AssertionError as e:
print("Assertion failed: "+e.message)
traceback.print_tb(sys.exc_info()[2])
except Excepti... |
cjlee112/socraticqs2 | mysite/ct/signals.py | Python | apache-2.0 | 5,199 | 0.002693 | """
Django signals for the app.
"""
import logging
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.com... | else None
unit_lesson = instance.unitLesson
unit_lesson_id = unit_lesson.id if unit_lesson else None # it's a thread
# | Exclude instructors, e.g. the ones submitting in preview mode
for instructor in instructors:
if student_id == instructor.id:
return
# Define if it's a milestone question (either first, middle, or last)
milestone = None
questions = unit_lesson.unit.all_orct()
... |
melqkiades/yelp | source/python/recommenders/multicriteria/multicriteria_base_recommender.py | Python | lgpl-2.1 | 3,524 | 0.001703 | from abc import ABCMeta
from recommenders.similarity.weights_similarity_matrix_builder import \
WeightsSimilarityMatrixBuilder
from tripadvisor.fourcity import extractor
from recommenders.base_recommender import BaseRecommender
from utils import dictionary_utils
__author__ = 'fpena'
class MultiCriteriaBaseReco... | user from the cluster | in order to avoid bias
if self._num_neighbors is None:
return cluster_users
similarity_matrix = self.user_similarity_matrix[user_id].copy()
similarity_matrix.pop(user_id, None)
ordered_similar_users = dictionary_utils.sort_dictionary_keys(
similarity_matrix)
... |
squadran2003/filtering-searching-mineral-catalogue | filtering-searching-mineral-catalogue/minerals/apps.py | Python | mit | 91 | 0 | from django.apps import AppConfig
class Mi | neralsConfig(AppC | onfig):
name = 'minerals'
|
hltbra/pycukes | specs/console_examples/stories_with_hooks/support/env.py | Python | mit | 392 | 0.005102 | from pycukes import BeforeAll, AfterAll, BeforeEach, AfterEach
@BeforeAll
def add_message1_attr(context):
context.counter = 1
@BeforeEach
def | add_message_attr(context):
context.counter += 1
setattr(context, 'message%d' % context.counter, 'msg')
@AfterEach
def increment_one(context):
context.counter += 1
@AfterAll
def show_hello_ | world(context):
print 'hello world'
|
josephlewis42/magpie | magpie/lib/jinja2/testsuite/filters.py | Python | bsd-3-clause | 19,379 | 0.000929 | # -*- coding: utf-8 -*-
"""
jinja2.testsuite.filters
~~~~~~~~~~~~~~~~~~~~~~~~
Tests for the jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Markup, Environment
fro... | '{{ foo|dictsort(false, "value") }}'
)
out = tmpl.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})
assert out == ("[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]|"
"[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]|"
"[('aa', 0), ('b', 1), ('c', 2), ('A... | der(foo=list(range(10)))
assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"
"[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")
def test_slice(self):
tmpl = env.from_string('{{ foo|slice(3)|list }}|'
'{{ foo|slice(3, "X")|list }}')
... |
gregorschatz/pymodbus3 | pymodbus3/bit_read_message.py | Python | bsd-3-clause | 8,239 | 0 | # -*- coding: utf-8 -*-
"""
Bit Reading Request/Response messages
--------------------------------------
"""
import struct
from pymodbus3.pdu import ModbusRequest
from pymodbus3.pdu import ModbusResponse
from pymodbus3.pdu import ModbusExceptions
from pymodbus3.utilities import pack_bitstring, unpack_bitstring
clas... | def set_bit(self, address, value=1):
""" Helper function to set the specified bit
:param address: The bit to set
:param value: The value to set the bit to
"""
self.bits[address] = (value != 0)
def re | set_bit(self, address):
""" Helper function to set the specified bit to 0
:param address: The bit to reset
"""
self.set_bit(address, 0)
def get_bit(self, address):
""" Helper function to get the specified bit's value
:param address: The bit to query
:return... |
kuiche/chromium | third_party/scons/scons-local/SCons/Debug.py | Python | bsd-3-clause | 6,593 | 0.00546 | """SCons.Debug
Code for debugging SCons internal things. Not everything here is
guaranteed to work all the way back to Python 1.5.2, and shouldn't be
needed by most users.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge... | formize
def func_shorten(func_tuple):
f = func_tuple[0]
for t in shorten_list:
i = string.find(f, t[0])
if i >= 0:
if t[1]:
i = i + len(t[0])
return (f[i:],)+func_tuple[1:]
return func_tuple
TraceFP = {}
if sys.platform == 'win32':
TraceDefault ... | t becomes the default for the next call to Trace()."""
global TraceDefault
if file is None:
file = TraceDefault
else:
TraceDefault = file
try:
fp = TraceFP[file]
except KeyError:
try:
fp = TraceFP[file] = open(file, mode)
except TypeError:
... |
mouseratti/guake | guake/main.py | Python | gpl-2.0 | 15,344 | 0.001369 | # -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 progra... | y with some old comma | nd line programs
os.environ["TERM"] = "xterm-256color"
# Force use X11 backend underwayland
os.environ["GDK_BACKEND"] = "x11"
# do not use version keywords here, pbr might be slow to find the version of Guake module
parser = OptionParser()
parser.add_option(
'-V',
'--version',
... |
adamcharnock/django-su | django_su/templatetags/su_tags.py | Python | mit | 270 | 0 | # -*- coding: utf-8 -*-
from django | import template
from ..utils import su_login_callback
register = template.Library()
@register.inclusion_tag('su/login_link.html', takes_contex | t=False)
def login_su_link(user):
return {'can_su_login': su_login_callback(user)}
|
WillWeatherford/mars-rover | photos/migrations/0003_rover.py | Python | mit | 852 | 0.001174 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-19 07:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration( | migrations.Migration):
dependencies = [
('photos', '0002_auto_20160919_0737'),
]
operations = [
migrations.CreateModel(
name='Rover',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | nique=True)),
('name', models.CharField(max_length=30)),
('landing_date', models.DateField()),
('max_date', models.DateField()),
('max_sol', models.IntegerField()),
('total_photos', models.IntegerField()),
],
),
]
|
destroy/SleekXMPP-gevent | sleekxmpp/stanza/__init__.py | Python | mit | 399 | 0 | """
| SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza.error import Error
from sleekxmpp.stanza.stream_error import StreamError
from sleekxmpp.stanza.iq import Iq
from sleekxmpp.sta... | nce import Presence
|
whummer/moto | moto/kms/responses.py | Python | apache-2.0 | 14,169 | 0.003882 | from __future__ import unicode_literals
import base64
import json
import re
import six
from moto.core.responses import BaseResponse
from .models import kms_backends
from .exceptions import NotFoundException, ValidationEx | ception, AlreadyExistsException, NotAuthorizedException
reserved_aliases = [
'alias/aws/ebs',
'alias/aws/s3',
'alias/aws/redshift',
'alias/aws/rds',
]
class KmsResponse(BaseResponse):
@property
def parameters(self):
return json.loads(self.body)
@property
def kms_backend(self... | ption = self.parameters.get('Description')
tags = self.parameters.get('Tags')
key = self.kms_backend.create_key(
policy, key_usage, description, tags, self.region)
return json.dumps(key.to_dict())
def update_key_description(self):
key_id = self.parameters.get('KeyId')
... |
benallard/pythoncard | test/testCipher.py | Python | lgpl-3.0 | 3,613 | 0.016883 | import unittest
from pythoncardx.cr | ypto import Cipher
from pythoncard.security import CryptoException, RSAPublicKey, KeyBuilder, KeyPair
class testCipher(unittest.TestCase):
def testInit(self):
c | = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, False)
self.assertEqual(Cipher.ALG_RSA_NOPAD, c.getAlgorithm())
try:
c.update([], 0, 0, [], 0)
self.fail()
except CryptoException as ce:
self.assertEqual(CryptoException.INVALID_INIT, ce.getReason())
try:
... |
hubert667/AIR | src/python/ranker/AbstractRankingFunction.py | Python | gpl-3.0 | 2,935 | 0.003407 | # This file is part of Lerot.
#
# Lerot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Lerot is distributed in the hope tha... | def next(self):
raise NotImplementedError("Derived class needs to implement "
"next.")
def next_det(self):
raise No | tImplementedError("Derived class needs to implement "
"next_det.")
def next_random(self):
raise NotImplementedError("Derived class needs to implement "
"next_random.")
def get_document_probability(self, docid):
raise NotImplementedError("Derived class needs to implement... |
dz0/websheets | grade_java.py | Python | agpl-3.0 | 5,860 | 0.014164 | import config, json, cgi, sys, Websheet, re, os
def grade(reference_solution, student_solution, translate_line, websheet, student):
if not re.match(r"^\w+$", websheet.classname):
return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>")
dump = {
... | category = "Runtime Error"
errmsg = ssf(runtimeOutput[runtimeOutput.index("<div class='error'>Runtime error:"):], "<pre >", "\n")
elif "<div class='all-passed'>" in runtimeOutput:
category = "Passed"
epilogue = websheet.epilogue
else:
category = "Failed Tests"
if "<div class='erro... | :
errmsg = ssf(runtimeOutput, "<div class='error'>", '</div>')
else:
return ("Internal Error", "<b>stderr</b><pre>" + runUser.stderr + "</pre><b>stdout</b><br>" + runUser.stdout)
return (category, runtimeOutput)
|
chrippa/livestreamer | src/livestreamer/plugins/servustv.py | Python | bsd-2-clause | 758 | 0.001319 | #!/usr/bin/env python
import re
from livestreamer.plugin import Plugin
from livestreamer.stream import HDSStream
_channel = dict(
at="servustvhd_1@51229",
de="servustvhdde_1@75540"
)
STREAM_INFO_URL = "http://hdiosstv-f.akamaihd.net/z/{channel}/manifest.f4m"
_url_re = re.compile(r"http://(?:www.)?servustv.co... | f):
url_match = _url_re.match(self.url)
if url_match:
if url_match.group | (1) in _channel:
return HDSStream.parse_manifest(self.session, STREAM_INFO_URL.format(channel=_channel[url_match.group(1)]))
__plugin__ = ServusTV
|
arenadata/ambari | ambari-server/src/main/python/ambari_server/BackupRestore.py | Python | apache-2.0 | 6,601 | 0.009998 | #!/usr/bin/env ambari-python-wrap
'''
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 (th... | ESTORE_PROCESS = 'restore'
SUPPORTED_PROCESSES = [BACKUP_PROCESS, RESTORE_PROCESS]
# The list of files where the ambari server state is kept on the filesystem
AMBARI_FILESYSTEM_STATE | = [AmbariPath.get("/etc/ambari-server/conf"),
AmbariPath.get("/var/lib/ambari-server/resources"),
AmbariPath.get("/var/run/ambari-server/bootstrap/"),
AmbariPath.get("/var/run/ambari-server/stack-recommendations")]
# What to use when no ... |
SpamScope/spamscope | tests/test_phishing.py | Python | apache-2.0 | 4,631 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... | .pop("body", None)
email.pop("subjects", None)
email.pop("from", None)
phishing.check_phishing(
email=email,
attachments=self.attachments,
urls_body=self.urls,
urls_attachments=self.urls,
target_keys=self.targets,
subject_k... | m(body)
self.assertTrue(flag_form)
body = self.email.get("body")
flag_form = phishing.check_form(body)
self.assertFalse(flag_form)
def test_form_value_error(self):
parser = mailparser.parse_from_file(mail_test_5)
body = parser.mail.get("body")
flag_form = ph... |
Kesel/django | demo/views.py | Python | mit | 459 | 0.002179 | import platform
import pip
from django import get_version
from django.shortcuts import render
def home(request):
"""
renders the deployment server details on the screen.
:param request: The django formatted HttpRequest
:return: renders context c with the demo template.
"""
c = dict(python_ver... | ython_version(), django_version=get_version(), pip_version=pip.__version__)
return render(request, 'demo/demo.html', c)
| |
18F/regulations-site | regulations/generator/layers/definitions.py | Python | cc0-1.0 | 1,632 | 0 | from django.template import loader
from regulations.generator.layers.base import InlineLayer
from regulations.generator.section_url import SectionUrl
from regulations.generator.layers import utils
from ..node_types import to_markup_id
class DefinitionsLayer(InlineLayer):
shorthand = 'terms'
data_source = | 'terms'
def __init__(self, layer):
self.layer = layer
self.template = loader.get_template(
'regulations/layers/definition_citation.html')
self.sectional = False
self.version = None
self.rev_urls = SectionUrl()
self.rendered = {}
# precomputation
| for def_struct in self.layer['referenced'].values():
def_struct['reference_split'] = def_struct['reference'].split('-')
def replacement_for(self, original, data):
""" Create the link that takes you to the definition of the term. """
citation = data['ref']
# term = term w/... |
jslhs/sunpy | sunpy/gui/__init__.py | Python | bsd-2-clause | 1,811 | 0.005522 | #-*- coding: utf-8 -*-
# Author: Matt Earnshaw <matt@earnshaw.org.uk>
from __future__ import absolute_import
import os
import sys
import sunpy
from PyQt4.QtGui import QApplication
from sunpy.gui.mainwindow import MainWindow
from sunpy.io import UnrecognizedFileTypeError
class Plotman(object):
""" Wraps a MainWin... | ainWindow()
self.open_files(paths)
def open_files(self, inputs):
VALID_EXTENSIONS = [".jp2", ".fits", ".fts"]
to_open = | []
# Determine files to process
for input_ in inputs:
if os.path.isfile(input_):
to_open.append(input_)
elif os.path.isdir(input_):
for file_ in os.listdir(input_):
to_open.append(file_)
else:
... |
sdoumbouya/ovirt-node | src/ovirt/node/setup/core/status_page.py | Python | gpl-2.0 | 8,877 | 0.000113 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# status_page.py - Copyright (C) 2012 Red Hat, Inc.
# Written by Fabian Deutsch <fabiand@redhat.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;... | n(plugins.NodePlugin):
"""This is the summary page, summarizing all sorts of informations
There are no validators, as there is no input.
"""
_model = None
def name(self):
return "Status"
def rank(self):
return 0
def model(self):
net_status, net_br, net_addrs = ut... | etworking_status()
net_addrs_str = ""
if net_addrs:
net_addrs_str = "\nIPv4: {inet}\nIPv6: {inet6}".format(**net_addrs)
num_domains = virt.number_of_domains()
return {
"status": virt.hardware_status(),
"networking": net_status,
"networkin... |
wcmitchell/insights-core | insights/parsers/ceilometer_conf.py | Python | apache-2.0 | 1,890 | 0.000529 | """
CeilometerConf - file ``/etc/ceilometer/ceilometer.conf``
=========================================================
The ``/etc/ceilometer/ceilometer.conf`` file is in a standard '.ini' format,
and this parser uses the IniConfigFile base class to read this.
Given a file containing the following test data::
[D... | on_coordination
[api]
port = 8777
host = 192.0.2.10
[central]
[collector]
udp_address = 0.0.0.0
udp_port = 4952
[compute]
[coordination]
backend_url = redis: | //:chDWmHdH8dyjsmpCWfCEpJR87@192.0.2.7:6379/
Example:
>>> config = shared[CeilometerConf]
>>> config.sections()
['DEFAULT', 'alarm', 'api', 'central', 'collector', 'compute', 'coordination']
>>> config.items('api')
['port', 'host']
>>> config.has_option('alarm', 'evaluation_interval')
True
... |
timopulkkinen/BubbleFish | ppapi/generators/idl_thunk.py | Python | bsd-3-clause | 16,821 | 0.009036 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Generator for C++ style thunks """
import glob
import os
import re
import sys
from idl_log import ErrOut, InfoOut, WarnOut
fr... | k'
if is_callback_func:
call_args = args[:-1] + [('', 'enter.callback()', '', '')]
meta.AddInclude('ppapi/c/pp_completion_callback.h')
else:
call_args = args
if args[0][0] == 'PP_Instance':
call_arglist = ', '.join(a[1] for a in call_args)
function_container = 'functions'
else:
call_ar... | ', '_')
function_name += version
invocation = 'enter.%s()->%s(%s)' % (function_container,
function_name,
call_arglist)
handle_errors = not (member.GetProperty('report_errors') == 'False')
if is_callback_func:
body = '%s\n' % _... |
google/grumpy | lib/itertools_test.py | Python | apache-2.0 | 5,660 | 0.011131 | # Copyright 2016 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 by applicable law or a... |
got = tuple(itertools.product(*args))
assert got == want, 'tuple(product%s) == %s, want %s' % (args, got, want)
def TestPermutations():
cases = [
(('AB',), (('A', 'B'), ('B', 'A'))),
(('ABC', 2), (('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B'))),
((range(3),), ((0, 1, 2)... | ange(3), 4), ()),
]
for args, want in cases:
got = tuple(itertools.permutations(*args))
assert got == want, 'tuple(permutations%s) == %s, want %s' % (args, got, want)
def TestCombinations():
cases = [
((range(4), 3), ((0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3))),
]
for args, want in cases:
g... |
BackupTheBerlios/xml2ddl-svn | xml2ddl/FirebirdInterface.py | Python | gpl-2.0 | 15,609 | 0.010635 | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
from downloadCommon import DownloadCommon, getSeqName
from DdlCommonInterface import DdlCommonInterface
import re
class FbDownloader(DownloadCommon):
def __init__(self):
self.strDbms = 'firebird'
def connect(self, info):
try:
... | : 'integer',
9 : 'quad',
7 : 'smallint',
12 : 'date',
13 : 'time',
35 : 'timestamp',
37 : 'varchar',
}
strType = ''
if nType in types:
strType = types[nType]
if nType not in [14, 40, 37]:... |
return strType
def hasAutoincrement(self, strTableName, strColName):
strSql = "SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS WHERE UPPER(RDB$GENERATOR_NAME)=UPPER(?);"
self.cursor.execute(strSql, [getSeqName(strTableName, strColName)[0:31]])
rows = self.cursor.fetchall()
... |
grigoryk/calory-game-server | dishes/admin.py | Python | gpl-2.0 | 727 | 0 | from django.contrib import admin
from .models import (
Image, NutritionalDataDish, NutritionalDataGu | ess, Dish, Guess)
class ImageInline(admin.StackedInline):
model = Image
class NutritionalDataDishInline(admin.StackedInline):
model = NutritionalDataDish
class DishAdmin(admin.ModelAdmin):
list_display = ('description', 'is_vegetarian', 'created_at')
inlines = [
ImageInline,
Nutrit... | onalDataDishInline
]
class NutritionalDataGuessInline(admin.StackedInline):
model = NutritionalDataGuess
class GuessAdmin(admin.ModelAdmin):
inlines = [NutritionalDataGuessInline]
admin.site.register(Image)
admin.site.register(Dish, DishAdmin)
admin.site.register(Guess, GuessAdmin)
|
stephenhelms/WormTracker | python/tsstats.py | Python | apache-2.0 | 8,100 | 0.006667 | import numpy as np
import numpy.ma as ma
from numpy import linalg as LA
import matplotlib.pyplot as plt
import itertools
import collections
from scipy import stats
def acf(x, lags=500, exclude=None):
if exclude is None:
exclude = np.zeros(x.shape)
exclude = np.cumsum(exclude.astype(int))
# from s... | dd > 0)] = np.pi
phc_correct = ddmod - dd
phc_correct[np.abs(dd)<np.pi] = 0
ph_correct = np.zeros(x.shape)
ph_correct[idxc[1:]] = phc_correct
up = x + ph_correct.cumsum()
return up
def nextpow2(n):
'''
Returns the next highest power of 2 from n
'''
m_f = np.log2(n)
m_i = np... | rates a randomized surrogate dataset for X, preserving linear temporal
correlations. If independent is False (default), linear correlations
between columns of x are also preserved.
If X contains missing values, they are filled with the mean of that
channel.
The algorithm works by randomizing the p... |
nipe0324/kaggle-keypoints-detection-keras | plotter.py | Python | apache-2.0 | 1,057 | 0.02176 | import os
import matplotlib.pyplot as plt
def plot_hist(history, model_name=None):
plt.plot(history['loss'], linewidth=3, label='tra | in')
plt.plot(history['val_loss'], linewidth=3, label='valid')
plt.grid()
plt.legend()
plt.xlabel('epoch')
plt.ylabel('loss')
plt.ylim(1e-4, 1e-2)
plt.yscale('log')
if model_name:
path = os.path.join('images', model_na | me + '-loss.png')
plt.savefig(path)
else:
plt.show()
def plot_model_arch(model, model_name):
from keras.utils.visualize_util import plot
path = os.path.join('images', model_name + '.png')
plot(model, to_file=path, show_shapes=True)
def plot_samples(X, y):
fig = plt.figure(figsize=(6, 6))
fig.sub... |
BenjaminSchubert/Pyptables | pyptables/executors.py | Python | mit | 6,181 | 0.00178 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Defines several helpers to add rules to Iptables
"""
from configparser import SectionProxy
from contextlib import suppress
from ipaddress import ip_address, ip_network
import re
import socket
from pyptables.iptables import Iptables, Ip6tables, IptablesRule
__author... | rn ip_address(socket.get | hostbyname(name))
return None
def setup_global_begin(config: SectionProxy) -> None:
"""
Sets up the tables globally for ipv4 and ipv6
:param config: the configuration used
"""
# noinspection PyUnresolvedReferences
def setup(handler: Iptables, _config: SectionProxy) -> None:
"""
... |
davidam/python-examples | security/md5/test/test_md5py.py | Python | gpl-3.0 | 352 | 0.008523 | #!/usr/bin/env python
import unittest
from app.md5py import MD5
class TddInPythonExample(unittest.TestCase):
def test_object_program(self):
m = MD5()
m.update("1234")
hexdigest = m.hexd | igest()
self.a | ssertEqual("81dc9bdb52d04dc20036dbd8313ed055", hexdigest)
if __name__ == '__main__':
unittest.main()
|
tysonholub/twilio-python | twilio/base/list_resource.py | Python | mit | 180 | 0 | class ListRes | ource(object):
def __init__(self, version):
"""
:param Version version:
"""
self._version = version
""" :type: Ver | sion """
|
kikinteractive/MaxMind-DB-Reader-python | maxminddb/decoder.py | Python | apache-2.0 | 5,904 | 0 | """
maxminddb.decoder
~~~~~~~~~~~~~~~~~
This package contains code for decoding the MaxMind DB data section.
"""
from __future__ import unicode_literals
import struct
from maxminddb.compat import byte_from_int, int_from_bytes
from maxminddb.errors import InvalidDatabaseError
class Decoder(object): # pylint: disa... | type_num = next_byte + 7
if type_num < 7:
raise InvalidDatabaseError(
'Something went horribly wrong in the decoder. An '
'extended type resolved to a type number < 8 '
'({type})'.format(type=type_num))
return type | _num, offset + 1
def _verify_size(self, expected, actual):
if expected != actual:
raise InvalidDatabaseError(
'The MaxMind DB file\'s data section contains bad data '
'(unknown data type or corrupt data)'
)
def _size_from_ctrl_byte(self, ctrl_byt... |
cs-shadow/phabricator-tools | py/abd/abdt_branch__t.py | Python | apache-2.0 | 10,066 | 0 | """Test suite for abdt_branch."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
# c... | rver.test'
bob_user = 'Bob'
bob_email = 'bob@server.test'
self._dev_commit_new_empty_file('ALICE1', alice_user, alice_email)
self._dev_commit_new_empty_file('BOB1', bob | _user, bob_email)
self._dev_commit_new_empty_file('ALICE2', alice_user, alice_email)
phlgit_push.push(self.repo_dev, branch_name, 'origin')
self.repo_arcyd('fetch', 'origin')
author_names_emails = branch.get_author_names_emails()
self.assertTupleEqual(
author_names... |
jemenake/LogicProjectTools | AudioArchiver.py | Python | mit | 5,075 | 0.021084 | #! /usr/bin/python
# Derived from dupinator.py.
#
# This program takes a list of pathnames to audio files and moves them to a central archive.
# It replaces the original with a symbolic link to the archived version.
# The archived version will have several names (all hard-linked): the MD5 hash (with the extension)
# a... | irectory doesn't exist, create it
###
def ensuredir(pathname):
if not os.path.isdir(pathname):
try:
os.mkdir(pathname)
except:
print "Can't create mandatory directory: " + pathname + " : Does it exist? Do we have permissions?"
exit()
###
### If a file is in the archive
###
def is_in_archive(md5):
pathna... | ith a particular name
###
def has_alias(md5, alias):
pathname = get_archive_alias_name(md5, alias)
return os.path.isfile(pathname)
###
### Do we want this file?
### (Used to indicate if a file qualifies as an audio file)
###
def want(pathname):
return pathname.endswith(".aif")
###
###
###
pathnames = list()
for ... |
wknet123/harbor | tools/migration/migration_harbor/versions/0_4_0.py | Python | apache-2.0 | 2,016 | 0.008433 | # Copyright (c) 2008-2016 VMware, 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 by applicabl... | log, poid_uptime (policy_id, update_time) on table replication_job
op.create_index('pid_optime', 'access_log', ['project_id', 'op_time'])
op.create_index('poid_uptime', 'replication_job', ['policy_id', 'update_time'])
#create tables: repository
| Repository.__table__.create(bind)
def downgrade():
"""
Downgrade has been disabled.
"""
pass
|
gmarke/erpnext | erpnext/accounts/utils.py | Python | agpl-3.0 | 16,635 | 0.025008 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
imp... | y=None):
# if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
cond = " ifnull(disabled, 0) = 0"
if fiscal_year:
c | ond += " and fy.name = %(fiscal_year)s"
else:
cond += " and %(transaction_date)s >= fy.year_start_date and %(transaction_date)s <= fy.year_end_date"
if company:
cond += """ and (not exists(select name from `tabFiscal Year Company` fyc where fyc.parent = fy.name)
or exists(select company from `tabFiscal Year C... |
JuezUN/INGInious | inginious/frontend/pages/course.py | Python | agpl-3.0 | 4,665 | 0.00493 | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Course page """
import web
from inginious.frontend.pages.utils import INGIniousPage
class CoursePage(INGIniousPage):
""" Course page """
def get_... | last_submissions:
| submission["taskname"] = tasks[submission['taskid']].get_name_or_id(self.user_manager.session_language())
tasks_data = {}
user_tasks = self.database.user_tasks.find(
{"username": username, "courseid": course.get_id(), "taskid": {"$in": list(tasks.keys())}})
is_admin = self.user... |
padilin/Discord-RPG-Bot | character.py | Python | mit | 2,055 | 0.008273 | import discord
import os.path
import json
from discord.ext import commands
class Character():
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context = True)
async def char (self, ctx):
"""Character Creation. Asks for all information then builds Json file."""
... | os.path.isfile('cs_{}'.format(userid)) is True:
await | self.bot.say('You\'re already on my list!')
else:
def checkname(msg):
return msg.content.startswith('name: ')
def checkclass(msg):
return msg.content.startswith('class: ')
await self.bot.say('You look new here, what\'s your name? \nname... |
F5Networks/f5-common-python | f5/bigip/tm/net/tunnels.py | Python | apache-2.0 | 3,153 | 0 | # coding=utf-8
#
# Copyright 2016 F5 Networks 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 a... | ributed 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.
#
"""BIG-IP® Network tunnels module.
REST URI
``http://localhost/mgmt/tm/net/tunnels``
GUI Path
``Netw... | urce
class TunnelS(OrganizingCollection):
"""BIG-IP® network tunnels collection"""
def __init__(self, net):
super(TunnelS, self).__init__(net)
self._meta_data['allowed_lazy_attributes'] = [
Gres,
Tunnels,
Vxlans,
]
class Tunnels(Collection):
""... |
arruda/pyfuzzy | fuzzy/set/ZFunction.py | Python | lgpl-3.0 | 1,985 | 0.009068 | # -*- coding: iso-8859-1 -*-
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later ver... | .
#
# You should have received a copy of the GNU Lesser G | eneral Public License along with
# this program; if not, see <http://www.gnu.org/licenses/>.
#
__revision__ = "$Id: ZFunction.py,v 1.13 2009/08/07 07:19:19 rliebscher Exp $"
from fuzzy.set.SFunction import SFunction
class ZFunction(SFunction):
r"""Realize a Z-shaped fuzzy set::
__
\
... |
moxuanchen/BMS | core/views/admin/login.py | Python | apache-2.0 | 1,670 | 0.000599 | # -*- coding: utf-8 -*-
import urllib
from . import admin
from flask import request
from flask import url_for
from flask import redirect
from flask import render_template
from flask_login import UserMixin
from flask_login import login_user
from flask_login import logout_user
from flask_login import login_required
from... | '')
if next:
next = urllib.unquote(next)
return render_json(0, {'href': next, 'delaySuccess': True})
return render_json(0, {'href': '/admin/dashboard', 'delaySuccess': True})
return render_template('/admin/signin.html')
@admin.route('/signout', methods=['GET'])
def signout(... | ate('/admin/dashboard.html')
|
Morteo/kiot | devices/thermostat/config.py | Python | mit | 1,329 | 0.009782 | #!/usr/bin/python3
import machine
from update_display import update_display as update_display_function
config = {
"gateway": {
# "type": "electrodragon-wifi-iot-relay-board-spdt-based-esp8266"
"id": "thermostat"
# "description": "Thermostat Control near Kitchen"
},
"devices": [
{
"type": "Di... |
"id": "display",
# "description": "OLED IC2 128 x 64 display",
"update_display_function": update_display_function,
"width": 128,
"height": 64,
"display_type": "SSD1306_I2C",
"i2c": {
| "bus": -1,
"gpio_scl": 4,
"gpio_sda": 5
}
},
{
"type": "DHTDevice",
"id": "dht",
# "description": "Digital Humidity and Temperature sensor",
"dht_type": 22,
"gpio": 14,
"just_changes": True,
"freq": 60
},
{
"type": "SwitchDevice",... |
xArm-Developer/xArm-Python-SDK | xarm/x3/base.py | Python | bsd-3-clause | 102,034 | 0.002388 | #!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2020, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
import re
import time
import math
import threading
try:
from multiprocessing.pool import ThreadPool
except... | eout = kwargs.get('timeout', None)
self._filters = kwargs.get('filters', None)
self._enable_heartbeat = kwargs.get('enable_heartbeat', False)
self._enable_report = kwargs.get('enable_report', True)
self._report_type = kwargs.get('report_type', 'rich')
sel... | t('forbid_uds', False)
self._check_tcp_limit = kwargs.get('check_tcp_limit', False)
self._check_joint_limit = kwargs.get('check_joint_limit', True)
self._check_cmdnum_limit = kwargs.get('check_cmdnum_limit', True)
self._check_simulation_mode = kwargs.get('check_simu... |
plotly/python-api | packages/python/plotly/plotly/validators/violin/_width.py | Python | mit | 472 | 0 | import _plotly_utils.basevalidators
class WidthValida | tor(_plotly_utils.basevalidators.Number | Validator):
def __init__(self, plotly_name="width", parent_name="violin", **kwargs):
super(WidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
min=kwargs.pop("min", 0),
role=k... |
ghislainv/deforestprob | test/test_get_started.py | Python | gpl-3.0 | 9,570 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
# author :Ghislain Vieilledent
# email :ghislain.vieilledent@cirad.fr, ghislainv@gmail.com
# web :https://ecology.ghislainv.fr
# python_version :>=2.7
# license... | 42, 0.75358937, 0.66791346,
0.75602843, 0.42494845, 0.77653139, 0.60509306,
0.60846943, 0.76187008, 0.73278992, 0.72792572,
0.47661681, 0.59456417, 0.71894598, 0.6731302,
0.74964489, 0.77247818, 0.78289747, 0.74200682,
0.78940242,... | 0.75078253, 0.77527468, 0.69907386, 0.71991522])
assert np.allclose(gstart["pred_icar"][0:100], p)
def test_rho(gstart):
r = np.array([-3.72569484e-02, -1.16871478e-01, -1.82400711e-01,
2.13446770e-01, -6.44591325e-01, -9.89850864e-02,
1.10439030e-01, -2.31551563e-02, -3... |
MadeiraCloud/salt | sources/salt/utils/validate/path.py | Python | apache-2.0 | 1,466 | 0 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
salt.utils.validate.path
~~~~~~~~~~~~~~~~~~~~~~~~
Several path related validators
''... |
# Lets get the parent directory of the provided path
parent_dir = os.path.dirname(path)
if not os.access(parent_dir, os.F_OK):
# Parent directory does not e | xit
return False
# Finally, return if we're allowed to write in the parent directory of the
# provided path
return os.access(parent_dir, os.W_OK)
|
Debian/openjfx | modules/web/src/main/native/Tools/Scripts/webkitpy/tool/steps/checkpatchrelevance.py | Python | gpl-2.0 | 2,708 | 0 | # Copyright (C) 2017 Apple 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:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | NY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
import re
from webkitpy.common.system.executive import ScriptError
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
_log = logging.getLogger(__name__)
... | lassmethod
def options(cls):
return AbstractStep.options() + [
Options.group,
]
jsc_paths = [
"JSTests/",
"Source/JavaScriptCore/",
"Source/WTF/"
"Source/bmalloc/",
]
group_to_paths_mapping = {
'jsc': jsc_paths,
}
def _change... |
matrix-org/synapse | synapse/handlers/read_marker.py | Python | apache-2.0 | 2,249 | 0.001334 | # Copyright 2017 Vector Creations Ltd
#
# 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 ... | ses a notifier to indicate that account data should be sent down /sync if
the read marker has changed.
"""
with await self. | read_marker_linearizer.queue((room_id, user_id)):
existing_read_marker = await self.store.get_account_data_for_room_and_type(
user_id, room_id, "m.fully_read"
)
should_update = True
if existing_read_marker:
# Only update if the new marker... |
maurobaraldi/ll_interview_application | luizalabs/employees/tests/tests_models.py | Python | gpl-3.0 | 866 | 0.001155 | from model_mommy import mommy
from django.test import TestCase
from ..models import Department, Employee
class DepartmentTestMommy(TestCase):
"""Department's modle test case."""
def test_department_creation_mommy(self):
"""Test create department's model."""
new_department = mommy.make('employ... | assertEqual(new_department.__str__(), new_department.name)
class EmployeeTestMommy(TestCase):
"""Employee's model test cazse."""
def test_employee_creation_mommy(self):
"""Test create department's model."""
new_employee = mommy.make('employees.Employee')
self.assertTrue(isinstance(new... | _employee.first_name, new_employee.last_name))
|
raccoongang/socraticqs2 | mysite/mysite/tests/celery.py | Python | apache-2.0 | 2,987 | 0.002343 | import datetime
import mock
from django.utils import timezone
from mock import Mock, call, PropertyMock
from django.test import TestCase
from django.contrib.sessions.models import Session
from mysite.celery import send_outcome, check_anonymous
class Ce | leryTasksTest(TestCase):
@mock.patch('mysite.celery.UserSession.objects.filter')
@mock.patch('mysite.celery.User.objects.filter')
def test_check_anonymous_user_session_no_session(self, mock_User_filter, mock_UserSession_filter):
mock_user = Mock(i | d=1)
call_mock_User_filter = [mock_user]
mock_session = Mock(id=2)
# user_session.session
p = PropertyMock(return_value=3, side_effect=Session.DoesNotExist('Object Does not exist'))
type(mock_session).session = p
call_mock_UserSession_filter = [mock_session]
m... |
weewx/weewx | bin/weeimport/cumulusimport.py | Python | gpl-3.0 | 20,404 | 0.000784 | #
# Copyright (c) 2009-2019 Tom Keffer <tkeffer@gmail.com> and
# Gary Roderick
#
# See the file LICENSE.txt for your full rights.
#
"""Module to interact with Cumulus monthly log files and import raw
observational data for use with weeimport.
"""
from __future__ import with_statement
f... | self.rain_source_confirmed = None
# Units of measure for some obs (eg temperatures) cannot be derived from
# th | e Cumulus monthly log files. These units must be specified by the
# user in the import config file. Read these units and fill in the
# missing unit data in the header map. Do some basic error checking and
# validation, if one of the fields is missing or invalid then we need
# to catch th... |
jchrismer/PiQuad | Calibration/Inertial_Calibration.py | Python | gpl-3.0 | 9,316 | 0.012988 | __author__ = 'joseph'
import statistics
import numpy as np
class AccelData(object):
def __init__(self,Accel):
#Static accelerometer data
self.Accel = Accel
def applyCalib(self,params,Accel):
ax = params['ax']
ay = params['ay']
az = params['az']
scaling_Matrix ... | Ua = AccelData.Accel[:,index+1]
# Apply predicted rotation to accele | rometer and compare to observed
Ug = np.dot(R,a)
diff = Ua - Ug
# store the magnitude of the difference and update the static interval index
resid[index] = diff[0]**2 + diff[1]**2 + diff[2]**2
index += 1
return resid
#TODO: Move to misc. kinematics
def quaternion_RK4(gyro... |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/functions/special/tests/test_gamma_functions.py | Python | gpl-3.0 | 12,392 | 0.000484 | from sympy import (
Symbol, gamma, I, oo, nan, zoo, factorial, sqrt, Rational, log,
polygamma, EulerGamma, pi, uppergamma, S, expand_func, loggamma, sin,
cos, O, cancel, lowergamma, exp, erf, beta, exp_polar, harmonic, zeta,
factorial)
from sympy.core.function import ArgumentIndexError
from sympy.utilit... | (1, 2)*sqrt(pi)
assert gamma(Rational(5, 2)) == Rational(3, 4)*sqrt(pi)
assert gamma(Rational(7, 2)) == Rational(15, 8)*sqrt(pi)
assert gamma(Rational(-1, 2)) == -2*sqrt(pi)
| assert gamma(Rational(-3, 2)) == Rational(4, 3)*sqrt(pi)
assert gamma(Rational(-5, 2)) == -Rational(8, 15)*sqrt(pi)
assert gamma(Rational(-15, 2)) == Rational(256, 2027025)*sqrt(pi)
assert gamma(Rational(
-11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8))
assert gamma(Rat... |
obi-two/Rebelion | data/scripts/templates/object/building/lok/shared_mining_cave_01.py | Python | mit | 440 | 0.047727 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
re | sult = Buildin | g()
result.template = "object/building/lok/shared_mining_cave_01.iff"
result.attribute_template_id = -1
result.stfName("building_name","cave")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
privacyidea/privacyidea | tests/ldap3mock.py | Python | agpl-3.0 | 28,972 | 0.002106 | # -*- coding: utf-8 -*-
"""
2020-09-07 Cornelius Kölbel <cornelius.koelbel@netknights.it>
Add exception
2017-04-26 Friedrich Weber <friedrich.weber@netknights.it>
Make it possible to check for correct LDAPS/STARTTLS settings
2017-01-08 Cornelius Kölbel <cornelius.koelbel@netknights.it>
... | port, division, unicode_literals
)
from passlib.hash import ldap_salted_sha1
from ast import literal_eval
import uuid
from ldap3.utils.conv import escape_bytes
import ldap3
import re
import pyparsing
from .smtpmock import get_wrapped
from collections import namedtuple, Sequence, Sized
from privacyidea.lib.utils impo... | e
DIRECTORY = "tests/testdata/tmp_directory"
Call = namedtuple('Call', ['request', 'response'])
_wrapper_template = """\
def wrapper%(signature)s:
with ldap3mock:
return func%(funcargs)s
"""
def _convert_objectGUID(item):
item = uuid.UUID("{{{0!s}}}".format(item)).bytes_le
item = escape_bytes(i... |
Bergurth/aes_cmdl.py | aes_cmdl.py | Python | gpl-3.0 | 2,518 | 0.004369 | import os, random, struct, sys
from Crypto.Cipher import AES
import getpass
from optparse import OptionParser
import hashlib
parser = OptionParser()
parser.add_option("-p")
(options, args) = parser.parse_args()
if(len(sys.argv) < 2):
print "usage: python aes_cmdl.py input_file_name <output_file_name> -p <pa... | given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
in_filename:
Name of the i | nput file
out_filename:
If None, '<in_filename>.enc' will be used.
chunksize:
Sets the size of the chunk which the function
uses to read and encrypt the file. Larger chunk
sizes can be faster for some files and machines.
chunksize must be div... |
mbareta/edx-platform-ft | lms/djangoapps/ccx/migrations/0027_merge.py | Python | agpl-3.0 | 289 | 0 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ccx', '0026_auto_20170831_0420'),
('ccx', '0026_auto_20170831_0554'),
]
operations = [
]
| |
gregpuzzles1/Sandbox | htmllib-example-1.py | Python | gpl-3.0 | 812 | 0.002463 | # File: htmllib-example-1.py
import htmllib
import formatter
import string
class Parser(htmllib.HTMLParser):
# return a dicti | onary mapping anchor texts to lists
# of associated hyperlinks
def __init__(self, verbose=0):
self.anchors = {}
f = formatter.NullFormatter()
htmllib.HTMLParser.__init__(self, f, verbose)
def anchor_bgn(self, href, name, type):
self.save_bgn()
self.anchor = p
d... | anchors.get(text, []) + [self.anchor]
file = open("contemplate_his_majestic_personhood.html")
html = file.read()
file.close()
p = Parser()
p.feed(html)
p.close()
for k, v in p.anchors.items():
print k, "=>", v
print
|
lizardsystem/lizard-damage | lizard_damage/migrations/0004_auto__del_field_geoimage_name__add_field_damageevent_landuse_slugs__ad.py | Python | gpl-3.0 | 10,066 | 0.007451 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'GeoImage.name'
db.delete_column('lizard_damage_geoimage', 'name')
# Adding fiel... | django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
},
'lizard_damage.damageeventresult': {
'Meta': {'object_name': 'DamageEventResult'},
'damage_event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_damage.DamageEvent']"}),
... | ld', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'north': ('django.db.models.fields.FloatField', [], {}),
'south': ('django.db.models.fields.FloatField', [], {}),
'west': ('django.db.models.fields.FloatFie... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdecore/KTzfileTimeZone.py | Python | gpl-2.0 | 414 | 0.009662 | # encoding: utf-8 |
# module PyKDE4.kdecore
# from /usr/lib/python3/dist-packages/PyKDE4/kdecore.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtNetwork as __PyQt4_QtNetwork
from .KTimeZone import KTimeZone
class KTzfileTimeZone(KTimeZone):
| # no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
|
gxx/auto_pull_request | auto_pull_request/plugins/pep8_info.py | Python | gpl-2.0 | 1,315 | 0.001521 | # coding=utf-8
"""Auto pull request pep8 plugin"""
import subprocess
from git import Repo
from . import MASTER_BRANCH
from .base import AutoPullRequestPluginInterface, section_order
from ..nodes import NumberedList, DescriptionNode, CodeNode, NodeList, HeaderNode
class Pep8Plugin(AutoPullRequestPluginInterface):
... | bprocess.PIPE)
output, errors = process.communicate(diff)
if errors:
raise | Exception(errors)
else:
return filter(None, output.strip().split('\n'))
@section_order(10)
def section_pep8_standards_compliance(self):
diff = self._get_diff_against_master()
pep8_compliance = self._get_pep8_compliance(diff)
if pep8_compliance:
value = No... |
amarquand/nispat | pcntoolkit/model/rfa.py | Python | gpl-3.0 | 7,985 | 0.007013 | from __future__ import print_function
from __future__ import division
import numpy as np
import torch
class GPRRFA:
"""Random Feature Approximation for Gaussian Process Regression
Estimation and prediction of Bayesian linear regression models
Basic usage::
R = GPRRFA()
hyp = R.estimate(... | X is not None) and (y is not None):
self.post(hyp, X, y)
de | f _numpy2torch(self, X, y=None, hyp=None):
if type(X) is torch.Tensor:
pass
elif type(X) is np.ndarray:
X = torch.from_numpy(X)
else:
raise(ValueError, 'Unknown data type (X)')
X = X.double()
if y is not None:
if type(y) is t... |
zeickan/Django-Store | store/api.py | Python | apache-2.0 | 3,203 | 0.029044 | # -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpRequest, QueryDict, HttpResponseRedirect
import json
import conekta
from store.models import *
from store.forms import *
### PETICIONES API PARA EL CARRITO
def delBasket(request):
id = str(request.GET.get('id'))
if request.GET.ge... |
response = callback + '(' + response + ');'
return HttpResponse(respons | e,content_type="application/json")
import pprint
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def conektaio(request):
try:
data = json.loads(request.body)
except:
data = False
if data:
try:
pedido = Pedido.objects.get(custom=data['data']['object']['refer... |
larsbutler/swift | swift/container/replicator.py | Python | apache-2.0 | 12,083 | 0 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | nfo)
if len(POLICIES) > 1:
sync_args += tuple(replication_info[k] for k in
('status_changed_at', 'count',
'storage_policy_index'))
return sync_args
def _handle_sync_response(se | lf, node, response, info, broker, http,
different_region):
parent = super(ContainerReplicator, self)
if is_success(response.status):
remote_info = json.loads(response.data)
if incorrect_policy_index(info, remote_info):
status_changed_... |
vCentre/vFRP-6233 | frappe/desk/page/messages/messages.py | Python | mit | 3,886 | 0.024447 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... | tact'] == frappe.session['user']:
# return messages
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and (owner=%(contact)s
or reference_name=%(user)s
or owner=reference_name)
order by creation des... | """, frappe.local.form_dict, as_dict=1)
else:
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and ((owner=%(contact)s and reference_name=%(user)s)
or (owner=%(contact)s and reference_name=%(contact)s))
... |
koery/win-sublime | Data/Packages/Package Control/package_control/commands/add_channel_command.py | Python | mit | 1,328 | 0.003012 | import re
import sublime
import sublime_plugin
from ..show_error import show_error
from ..settings import pc_settings_filename
class AddChannelCommand(sublime_plugin.WindowCommand):
"""
A command to add a new channel (list of repositories) to the user's machine
"""
def run(self):
self.windo... | ut panel handler - adds the provided URL as a channel
:param input:
A s | tring of the URL to the new channel
"""
input = input.strip()
if re.match('https?://', input, re.I) == None:
show_error(u"Unable to add the channel \"%s\" since it does not appear to be served via HTTP (http:// or https://)." % input)
return
settings = sublime.... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/absl/logging/__init__.py | Python | mit | 35,420 | 0.007143 | # Copyright 2017 The Abseil Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | sl import flags
from absl.logging import converter
import six
if six.PY2:
import thread as _thread_lib # For .get_ident().
else:
import threading as _thread_lib # For .get_ident().
FLAGS = flags.FLAGS
# Logging levels.
FATAL = converter.ABSL_FATAL
ERROR = converter.ABSL_ERROR
WARNING = converter.ABSL_WARNING... | G # Deprecated name.
INFO = converter.ABSL_INFO
DEBUG = converter.ABSL_DEBUG
# Regex to match/parse log line prefixes.
ABSL_LOGGING_PREFIX_REGEX = (
r'^(?P<severity>[IWEF])'
r'(?P<month>\d\d)(?P<day>\d\d) '
r'(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)'
r'\.(?P<microsecond>\d\d\d\d\d\d) +'
r'... |
endlessm/chromium-browser | third_party/llvm/lldb/test/API/macosx/queues/TestQueues.py | Python | bsd-3-clause | 17,019 | 0.001351 | """Test queues inspection SB APIs."""
from __future__ import print_function
import unittest2
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestQueues(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUn... | "
def check_queue_for_valid_queue_id(self, queue):
self.assertTrue(
queue.GetQueueID() != 0, "Check queue %s for valid QueueID (got 0x%x)" %
(queue.GetName(), queue.GetQueue | ID()))
def check_running_and_pending_items_on_queue(
self, queue, expected_running, expected_pending):
self.assertTrue(
queue.GetNumPendingItems() == expected_pending,
"queue %s should have %d pending items, instead has %d pending items" %
(queue.GetName(),
... |
innoteq/devpi-slack | devpi_slack/main.py | Python | bsd-3-clause | 1,761 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
from devpi_common.request import new_requests_session
from devpi_slack import __version__
def devpiserver_indexconfig_defaults():
return {"slack_icon": None, "slack_hook": None, "slack_user": None}
def devpiserver_on_upload... | _USER", "devpi")
if not slack_hook:
return
session = new_requests_session(agent=("devpi-slack", __version__))
try:
r = session.post(
slack_hook,
data={
'payload': json.dumps({
"text": "Uploaded {}=={} to {}".format(
... | l": slack_icon,
"username": slack_user,
})
})
except session.Errors:
raise RuntimeError("%s: failed to send Slack notification %s",
project, slack_hook)
if 200 <= r.status_code < 300:
log.info("successfully sent Slack no... |
Pikecillo/genna | external/4Suite-XML-1.0.2/Ft/Lib/Terminal.py | Python | gpl-2.0 | 11,043 | 0.002083 | ########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Lib/Terminal.py,v 1.6.4.1 2006/09/18 17:05:25 jkloth Exp $
"""
Provides some of the information from the terminfo database.
Copyright 2005 Fourthought, Inc. (USA).
Detailed license and copyright information... | ns)
def _escape_win32(self, codes):
"""Translates the ANSI color codes into the Win32 API equivalents."""
# get the current text attributes for the stream
size, cursor, attributes, window = \
_win32con.GetConsoleScreenBufferInfo(self._handle)
for code in map(int, fil... | ult_attribute
elif code == 1: # bold
# bold only applies to the foreground color
attributes |= _win32con.FOREGROUND_INTENSITY
elif code == 30: # black
attributes &= _win32con.BACKGROUND
elif code == 31: # red
attributes ... |
annarev/tensorflow | tensorflow/python/keras/regularizers.py | Python | apache-2.0 | 12,860 | 0.003421 | # 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... |
import math
import six
from tensorflow.python.keras import backend
from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object
from tensorflow.python.keras.utils.generic_utils import serialize_keras_object
from tensorflow.python.ops import math_ops
from tensorflow.python.util.tf_export import ke... | if not isinstance(x, (float, int)):
raise ValueError(('Value: {} is not a valid regularization penalty number, '
'expected an int or float value').format(x))
if math.isinf(x) or math.isnan(x):
raise ValueError(
('Value: {} is not a valid regularization penalty number, '
... |
joelwilliamson/cs234 | a1/a01q2b.py | Python | gpl-2.0 | 3,280 | 0.051829 | #!/usr/bin/python2
import check
from fractions import gcd
# Algorithm taken from en.wikipedia.org/wiki/Line-line-_intersection
# All code written by Joel Williamson
## intersection: Int Int Int Int Int Int Int Int -> (union "parallel" (tuple Int Int Int Int))
##
## Purpose: Treating the input as 4 pairs of integers,... | ter == "parallel") :
continue
if inter in intersections :
continue
if ((inter[0]*inter[0])/(inter[1]*inter[1]) + (inter[2]*inter[2])/(inter[3]*inter[3]) >= R*R) :
continue
intersections[inter] = True
segments += 1
return segments
## Tests:
check.expect('Example 1',pieces(10,3,[-15,1,10],[15,1... |
# Be sure to do lots more of your own testing!
|
neo4j/neo4j-python-driver | tests/integration/examples/test_config_unencrypted_example.py | Python | apache-2.0 | 1,486 | 0.000673 | # Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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... | mport[]
# isort: on
# python -m pytest tests/integration/examples/test_config_unencrypted_example.py -s -v
class ConfigUnencryptedExample(DriverSetupExample):
# tag::config-unencrypted[]
def __init__(self, uri, auth):
self.driver = GraphDatabase.driver(uri, auth=auth, encrypted=False)
# end::con... | viceUnavailable as error:
if isinstance(error.__cause__, BoltHandshakeError):
pytest.skip(error.args[0])
|
miraculixx/geocoder | geocoder/api.py | Python | mit | 11,482 | 0 | #!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
from geocoder.osm import Osm
from geocoder.w3w import W3W
from geocoder.bing import Bing
from geocoder.here import Here
from geocoder.yahoo import Yahoo
from geocoder.baidu import Baidu
from geocoder.tomtom import Tomtom
from geocoder.arcgis impo... | 'geocode': W3W,
'reverse': W3WReverse,
},
'yandex': {
'geocode': Yandex,
'reverse': YandexReverse,
},
'mapquest': {
'geocode': Mapquest,
'reverse': MapquestReverse,
},
'geolytica': {'geocode': Geolytica},
... | 'bing': {
'geocode': Bing,
'reverse': BingReverse,
},
'google': {
'geocode': Google,
'reverse': GoogleReverse,
'timezone': Timezone,
'elevation': Elevation,
},
}
if isinstance(location, (list, dict)) and method =... |
tebeka/arrow | python/examples/plasma/sorting/sort_df.py | Python | apache-2.0 | 6,843 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | if you run this code on more data, this is just a
# small example that can run on a laptop.
#
# The | values we used to get a speedup (on a m4.10xlarge instance on EC2) were
# object_store_size = 84 * 10 ** 9
# num_cores = 20
# num_rows = 10 ** 9
# num_cols = 1
client = None
object_store_size = 2 * 10 ** 9 # 2 GB
num_cores = 8
num_rows = 200000
num_cols = 2
column_names = [str(i) for i in range(num_c... |
tallakahath/pymatgen | pymatgen/io/vasp/sets.py | Python | mit | 58,824 | 0.000357 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals, print_function
import abc
import re
import os
import glob
import shutil
import warnings
from itertools import chain
from copy import deepcopy
import six
impo... | e doing.
Improper overriding the as_dict and from_dict protocols is the major
cause of implementation headaches. If you need an example, look at how the
MPStaticSet or MPNonSCFSets are constructed.
The above are recommendations. The following are UNBREAKABLE rules:
1. All input sets must take in a structure o... | nts_settings are absolute. Any new sets you
implement must obey this. If a user wants to override your settings,
you assume he knows what he is doing. Do not magically override user
supplied settings. You can issue a warning if you think the user is wrong.
3. All input sets must save all supplied args and kwar... |
Tehsmash/networking-cisco | networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/b29f1026b281_add_support_for_ucsm_vnic_templates.py | Python | apache-2.0 | 1,374 | 0.002183 | # Copyright 2016 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | under the License.
"""Add support for UCSM VNIC Templates
Revision ID: b29f1026b281
Revises: 13bd9ebffbf5
Create Date: 2016-02-18 15:12:31.294651
"""
# revision identifiers, used by Alembic.
revision = 'b29f1026b281'
down_revision = '13bd9ebffbf5'
from alembic import op
import sqlalchemy as sa
def upgrade():
... | _id', sa.Integer(), nullable=False),
sa.Column('vnic_template', sa.String(length=64), nullable=False),
sa.Column('device_id', sa.String(length=64), nullable=False),
sa.Column('physnet', sa.String(length=32), nullable=False),
sa.Column('updated_on_ucs', sa.Boolean(), nullable=False),
... |
mixedup4x4/Speedy | Contents/LanScan.py | Python | gpl-3.0 | 7,956 | 0.007793 | import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddr | ess = []
executionTime = 0
def __init__(self,fromIp,toIp):
startTime = time.time()
self.fromIp = fromIp # from 192.168.1.x
self.toIp = toIp # to 192.168.x.x
self.__checkIfIpIsValid(fromIp)
| self.__checkIfIpIsValid(toIp)
self.__getRange(fromIp,toIp)
self.__shellToQueue()
#self.__checkIfUp() # run by the shellToQueue queue organizer
self.__computerInfoInQueue()
endTime = time.time()
self.executionTime = round(endTime - startTime,3)
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.