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 |
|---|---|---|---|---|---|---|---|---|
relekang/python-thumbnails | thumbnails/__init__.py | Python | mit | 2,899 | 0.005174 | # -*- coding: utf-8 -*-
from thumbnails.conf import settings
from thumbnails.engines import DummyEngine
from thumbnails.helpers import get_engine, generate_filename, get_cache_backend
from thumbnails.images import SourceFile, Thumbnail
__version__ = '0.5.1'
def get_thumbnail(original, size, **options):
"""
... | aram colormode: Overrides ``THUMBNAIL_COLORM | ODE``, The default colormode for thumbnails.
Supports all values supported by pillow. In other engines there is a best
effort translation from pillow modes to the modes supported by the current
engine.
:param format: Overrides the format the thumbnai... |
adsabs/ADS_records_merger | pipeline_log_functions.py | Python | gpl-3.0 | 1,639 | 0.003661 | # Copyright (C) 2011, The SAO/NASA Astrophysics Data System
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This p... | ricError(msg_str)
else:
error_string = 'Type of check "%s" cannot be handled by the "manage_check_error" function.' % type_check
logger.critical(error_s | tring)
raise GenericError(error_string)
return None |
iotile/coretools | iotileship/iotile/ship/recipe_manager.py | Python | gpl-3.0 | 4,144 | 0.002896 | import os
from iotile.core.dev import ComponentRegistry
from iotile.ship.recipe import RecipeObject
from iotile.ship.exceptions import RecipeNotFoundError
class RecipeManager:
"""A class that maintains a list of installed recipes and recipe actions.
It allows fetching recipes by name and auotmatically buildi... | ] = resource
def is_valid_action(self, name):
"""Check if a name describes a valid action.
Args:
name (str): The name of the action to check
Returns:
bool: Whether the action is known and valid.
"""
return self._recipe_actions.ge | t(name, None) is not None
def is_valid_recipe(self, recipe_name):
"""Check if a recipe is known and valid.
Args:
name (str): The name of the recipe to check
Returns:
bool: Whether the recipe is known and valid.
"""
return self._recipes.get(recipe_n... |
ondoheer/GOT-Platform | app/frontend/views.py | Python | gpl-2.0 | 197 | 0.005076 | from flask import Blueprint, re | nder_template
frontend = Blueprint('frontend', __name__)
@frontend.route('/' | )
@frontend.route('/index')
def index():
return render_template('index.html')
|
nttcom/eclcli | eclcli/orchestration/heatclient/v1/events.py | Python | apache-2.0 | 2,990 | 0 | # Copyright 2012 OpenStack Foundation
# 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 requ... | ams:
url += '?%s' % parse.urlencode(params, True)
return self._list(url, 'events')
def get(self, stack_id, resource_name, event_id):
"""Get the details for a specific event.
:param stack_id: ID of stack containing the event
:param resource_name: ID of resource the even... | o
:param event_id: ID of event to get the details for
"""
stack_id = self._resolve_stack_id(stack_id)
url_str = '/stacks/%s/resources/%s/events/%s' % (
parse.quote(stack_id, ''),
parse.quote(encodeutils.safe_encode(resource_name), ''),
... |
lyso/scrape_realestate | parser_mysql.py | Python | gpl-3.0 | 10,544 | 0.000759 | import time
import zlib
from bs4 import BeautifulSoup
# from geopy.geocoders import Nominatim as Geo
from scraper import BaseScraper
from price_parser import parse_price_text
from MySQL_connector import db_connector
db = 'realestate_db'
class Parser(object):
scr_db = 'scraper_dumps'
tgt_db = 'realestate_d... | s
def test_db(self):
conn = db_connector(db)
cur = conn.cursor()
cur.execute(
""" CREATE TABLE IF NOT EXISTS`tbl_pr | operty_ad` (
`id` INT NOT NULL,
`hash_id` INT NOT NULL,
`address` VARCHAR(100) NULL,
`price` INT NULL,
`price_text` VARCHAR(100) NULL,
`agent_name` VARCHAR(45) NULL,
... |
Mendelone/forex_trading | Algorithm.Python/PythonPackageTestAlgorithm.py | Python | apache-2.0 | 6,403 | 0.016872 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Li... | eta = numpy.array([1, 0.1, 10])
e = numpy.random.normal(size=nsample)
X = sm.add_constant(X)
y = numpy.dot(X, beta) + e
model = sm.OLS(y, X)
results = model.fit()
print "statsmodels tests >>>", results.summary()
def pykalman_test():
kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]]... | ay([[1,0], [0,0], [0,1]]) # 3 observations
kf = kf.em(measurements, n_iter=5)
print "pykalman test >>>", kf.filter(measurements)
def copulalib_test():
x = numpy.random.normal(size=100)
y = 2.5 * x + numpy.random.normal(size=100)
#Make the instance of Copula class with x, y and clayton family:: ... |
moccu/django-omnibus | examples/mousemove/example_project/connection.py | Python | bsd-3-clause | 485 | 0.002062 | from omnibus.factories import websocket_connection_factory
def mousemove_connection_factory(auth_class, pubsub):
class GeneratedConnection(websocket_connection_factory(auth_class, pubsub)):
def close_connection(self):
self.pubsub.publish(
'mousemoves', 'disconnect',
... | Connection
| |
dumrauf/web_tools | image_converter/tests/test_views.py | Python | mit | 3,078 | 0.001949 | from django.test import Client
import mock as mock
from image_converter.tests.base import ImageConversionBaseTestCase
from image_converter.utils.convert_image import convert_image_to_jpeg
__author__ = 'Dominic Dumrauf'
class ViewsTestCase(ImageConversionBaseTestCase):
"""
Tests the 'views'.
"""
def ... | 'form', response.context)
def test_upload_post_with_non_image_file(self):
"""
Tests POSTing a form which contains a file but the file is not an image.
"""
# Given
c = Client()
# When
with open(self.non_image_file_path) as fp:
response = c.post('/'... | image_file_error.html')
self.assertEqual(response.status_code, 200)
self.assertIn('file', response.context)
self.assertIn(self.non_image_file_name, response.content)
def test_upload_post_with_image_file(self):
"""
Tests POSTing a form which contains a file where the file is ... |
leafclick/intellij-community | python/helpers/pydev/_pydevd_frame_eval/pydevd_frame_eval_cython_wrapper.py | Python | apache-2.0 | 1,343 | 0.002234 | try:
try:
from _pydevd_frame_eval_ext import pydevd_frame_evaluator as mod
except ImportError:
from _pydevd_frame_eval import pydevd_frame_evaluator as mod
except ImportError:
try:
import sys
try:
is_64bits = sys.maxsize > 2 ** 32
except:
# | In Jython this call fails, but this is Ok, we don't support Jython for speedups anyways.
raise ImportError
plat = '32'
if is_64bits:
plat = '64'
# We also acc | ept things as:
#
# _pydevd_frame_eval.pydevd_frame_evaluator_win32_27_32
# _pydevd_frame_eval.pydevd_frame_evaluator_win32_34_64
#
# to have multiple pre-compiled pyds distributed along the IDE
# (generated by build_tools/build_binaries_windows.py).
mod_name = 'p... |
atodorov/pykickstart | pykickstart/commands/module.py | Python | gpl-2.0 | 4,566 | 0.001314 | #
# Martin Kolman <mkolman@redhat.com>
#
# Copyright 2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# | copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU... | GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
# subject to the GNU General Public License and may only ... |
naturalmessage/natmsgshardbig | sql/ArchiveNM.py | Python | gpl-3.0 | 2,018 | 0.018335 | # Python 3: ArchiveNM.py
# Function:
# This will collect the files in /home/postgres that
# need to be sent to a new Natural Message machine
# that is being initialized. This currently grabs
# directory server and shard server files.
# It can also be used as an archiver.
import datetime
import tarfile
import o... | mport sys
# For the version code, enter the format used
# in the naturalmsg_svr_#_#_#.py files
test_or_prod = 'prod'
version = '0_0_5'
DSTAMP = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# (do not add a trailing slash on directory names)
pgm_dir = '/var/nat | msg'
sql_dir = '/home/postgres/shard/sql/' + test_or_prod
function_dir = '/home/postgres/shard/sql/' + test_or_prod + '/functions'
pgm_files = ('naturalmsg-svr' + version + '.py',
'shardfunc_cp' + version + '.py')
sql_files = ( \
'0001create_db.sh',
'0002create_tables.sql',
'0005shardserver.sql',
'0007shardb... |
HubbeKing/Hubbot_Twisted | hubbot/user.py | Python | mit | 629 | 0 |
class IRCUser(object):
def __init__(self, user):
self.user = None
self.hostmask = None
self.last_active = None
if "!" in user:
user_array = user.split("!")
self.name = user_array[0]
if len(user_array) > 1:
user_array = user_array... | else:
self.name = user
self.user = "anon"
self.hostmask = "unknown"
|
def __str__(self):
return "{}!{}@{}".format(self.name, self.user, self.hostmask)
|
jjdmol/LOFAR | CEP/GSM/src/ms3_script.py | Python | gpl-3.0 | 2,005 | 0.002494 | #!/usr/bin/python
import sys, os, time
from itertools import count
import logging
import tkp.database.database as database
import tkp.database.dataset as ds
import tkp.database.dbregion as reg
import tkp.database.utils as dbu
import monetdb.sql
from tkp.sourcefinder import image
from tkp.config import config
from tkp.... | b_dbase = config['database']['name']
db_port = config['database']['port']
db_autocommit = config['database']['autocommit']
basedir = config['test']['datapath']
imagesdir = basedir + '/fits'
regionfilesdir = basedir + '/regions'
if db_enabled:
db = database.DataBase(host=db_host, name=db_dbase, user=db_user, passw... | DataSet(data={'dsinname': description}, database=db)
print "dataset.id:", dataset.id
i = 0
files = os.listdir(imagesdir)
files.sort()
for file in files:
my_fitsfile = accessors.FitsFile(imagesdir + '/' + file)
my_image = accessors.sourcefinder_image_from_accessor(my_fitsfile)
... |
marmstr93ng/TimeManagementSystem | tms/breakrule.py | Python | mit | 2,292 | 0.004363 | import logging
import configparser
import os
from utils import bool_query
class BreakRule(object):
def __init__(self, settings):
self.settings = settings
self.rules_record = configparser.ConfigParser()
self.rules_record.read("{}/tms/breakrules.ini".format(os.getcwd()))
self.rules... | rule to be used...')
selection = input()
| try:
int(selection)
except ValueError:
logging.warning('WARNING: Please enter a numeric value corresponding to a rule ID.')
else:
if self._check_rule_exists(selection):
selection_query = bool_query('Select Rule "{}" for use?... |
pombredanne/osrc | osrc/manage.py | Python | mit | 536 | 0 | # -*- coding: utf-8 -*-
__all__ = [
"CreateTablesCommand", "DropTablesCommand", "UpdateCommand",
]
from flask.ext.script import Command, Option
from .mo | dels import db
from .update import update
class CreateTablesCommand(Command):
def run(self):
db.create_all()
class DropTablesCommand(Command):
def run(self):
db.drop_all()
class UpdateCommand(Command):
option_list = (
Option("-s", "--since", dest="since", required=False),
... | def run(self, since):
update(since=since)
|
3Nigma/jale | main.py | Python | mit | 3,579 | 0.00475 | import random
def printifyInstruction(instr, mcs):
"""
Construct a preaty representation of the instruction in memory.
mcs -> 'maximum characters span'
"""
return "({0:{3}d}, {1:{3}d}, {2:{3}d})".format(instr['A'], instr['B'], instr['C'], mcs)
class Orbis:
def __init__(self, gSize):
se... | lf):
self.pc = 0
for g in range(self.gsize):
print "Evaluating gene {0} ...".format(self.pc / 3)
ta = self.instructions[g * 3]
tb = self.instructions[g * 3 + 1]
| tc = self.instructions[g * 3 + 2]
cstem = self.instructions[tb] - self.instructions[ta]
if (tb % 3) == 2:
# We will affect the jump part of a gene. Make sure it remains consistent with the rest of the genes
cvtor = cstem % 3
prevt... |
fyookball/electrum | lib/daemon.py | Python | mit | 14,615 | 0.001779 | #!/usr/bin/env python3
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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 withou... | join(config.path, 'daemon')
def remove_lockfile(lockfile):
try:
os.unlink(lockfile)
print_error("Removed lockfile:", lockfile)
| except OSError as e:
print_error("Could not remove lockfile:", lockfile, repr(e))
def get_fd_or_server(config):
'''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succe... |
RafaelSzefler/phi | tests/unit/request/test_form.py | Python | mit | 834 | 0 | # -*- coding: utf-8 -*-
from io import BytesIO
import pytest
from phi.request.form import FormRequest
class TestFormRequest(object):
@pytest.fixture
def form_req(self):
fr = FormRequest()
fr.charset = "utf-8"
return fr
@pytest.mark.parametrize("body, content", [
(
... | ,
])
def test_body(self, body, content, form_req):
stream = BytesIO(body.encode("utf-8"))
stream.seek(0)
form_req._content_stream = stream
form_req.content_length = len( | body)
assert form_req._get_body() == content
|
shumik/skencil-c | Sketch/UI/linedlg.py | Python | gpl-2.0 | 11,272 | 0.016856 | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2... | .opt_arrow2.grid(row = 3, column = 1, sticky = 'ew', ipady = 2)
self.arrow_gc = gc
self.arrow_bitmap = bitmap
self.opt_join = MyOptionMenu2(top, [(pixmaps.JoinMiter, JoinMiter),
| (pixmaps.JoinRound, JoinRound),
(pixmaps.JoinBevel, JoinBevel)],
command = self.set_line_join,
entry_type = 'bitmap',
highlightthickness = 0)
... |
laalaguer/pythonlearn | 01-basic/math_improved.py | Python | mit | 1,306 | 0.004594 | # We try to improve the previous 'math_operation.py' by reduce the code
# here we introduce a concept named list-comprehensive
# Knowledge points:
# 1. list-comprehensive, the [x for x in a-list]
# 2. dir() function to get the current environment variable names in space.
# 3. "in" check, we never user string.search() i... | n")
# Split user_inputed numbers into individua | l numbers, store it in a list.
possible_numbers = user_input.strip().split(" ")
# We user list comprehensive to get rid of "for" loop, reduce code amount.
float_numbers = [float(x) for x in possible_numbers]
# absolute numbers
absolute_numbers = [abs(x) for x in float_numbers]
# rounded numbers, in "int" style
int_numb... |
6desislava6/PyDay | pyday_alarms/urls.py | Python | mit | 336 | 0 | from django.conf.urls import url
from django.conf.urls import patterns
from pyday_alarms import views
app_name = 'pyday_alarms'
urlpatt | erns = [
url(r'^alarms/$', views.AlarmView.as_view(), name | ='alarms'),
]
'''urlpatterns += patterns('pyday_social_network.views',
url(r'^list/$', 'list', name='list'))
'''
|
etherkit/OpenBeacon2 | client/linux-arm/venv/lib/python3.6/site-packages/PyInstaller/hooks/hook-google.cloud.speech.py | Python | gpl-3.0 | 603 | 0.003317 | #------------------------------------------------------------ | -----------------
# Copyright (c) 2017-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#
# SPDX-License-Identifier... | Installer.utils.hooks import copy_metadata
datas = copy_metadata('google-cloud-speech')
|
geeag/kafka | tests/kafkatest/tests/client/message_format_change_test.py | Python | apache-2.0 | 4,644 | 0.004522 | # Copyright 2015 Confluent 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, s... | ")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
| self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
|
alexgorban/models | official/vision/detection/modeling/retinanet_model.py | Python | apache-2.0 | 6,957 | 0.003881 | # 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... | abel_fields, labels.keys())
boxes, scores, classes, valid_detections = self._generate_detections_fn(
outputs['box_outputs'], outputs['cls_outputs'],
labels['anchor_boxes'], labels['image_info'][:, 1:2, :])
# Discards the old output tensors t | o save memory. The `cls_outputs` and
# `box_outputs` are pretty big and could potentiall lead to memory issue.
outputs = {
'source_id': labels['groundtruths']['source_id'],
'image_info': labels['image_info'],
'num_detections': valid_detections,
'detection_boxes': boxes,
'... |
edent/Twitter-Networks | GenerateNetwork.py | Python | mit | 1,614 | 0.005576 | import glob
import os
import json
import sys
import argparse
from collections import defaultdict
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--screen-name", required=True, help="Screen name of twitter user")
args = vars(ap.parse_args())
SEED = args['screen_name']
users = defaultdict(lambda: { 'followers':... | ter_network.csv', 'w') as outf:
edge_exists = {}
for edge in edges:
key = ','.join([str(x) for x in edge])
if no | t(key in edge_exists):
outf.write('%s,%s,%d\n' % (edge[0], edge[1], edge[2]))
edge_exists[key] = True
|
ntt-sic/python-glanceclient | glanceclient/v2/shell.py | Python | apache-2.0 | 10,082 | 0.000099 | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | )
else:
member = gc.image_members.update(args.image_id, args.member_id,
args.member_status)
member = [member]
columns = ['Image ID', 'Member ID', 'Status']
utils.print_list(member, columns)
@utils.arg('image_id', metavar='<IMAGE_ID>',
... | (gc, args):
"""Create member for a given image."""
if not (args.image_id and args.member_id):
utils.exit('Unable to create member. Specify image_id and member_id')
else:
member = gc.image_members.create(args.image_id, args.member_id)
member = [member]
columns = ['Image ID', '... |
Jacy-Wang/MyLeetCode | ClimbStairs70.py | Python | gpl-2.0 | 393 | 0 | c | lass Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
nums = [0 for _ in xrange(n + 1)]
for i in x | range(1, n + 1):
if i == 1:
nums[1] = 1
elif i == 2:
nums[2] = 2
else:
nums[i] = nums[i - 1] + nums[i - 2]
return nums[n]
|
jlecker/rhythmbox-xchat-music-channel | xchat_music_channel/__init__.py | Python | mit | 2,960 | 0.004392 | import rb
import rhythmdb
import dbus
import gconf
from xchat_music_channel.conf import gconf_keys, ConfDialog
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
class XChatMusicChannelPlugin(rb.Plugin):
def activate(self, shell):
gc = gconf.client_get_default()
... | ne
self.xchat_object = None
self.xchat_hook = None
self.xchat_context = None
def deactivate(self, shell):
del self.xchat_context
if self.xchat_hook:
self.signal.remove()
self.get_xchat().Unhook(self.xchat_hook)
del self.xchat_hook
... | del self.player
del self.shell
del self.channel
del self.server
del self.signal
del self.bus
def get_xchat(self):
xchat_object = self.bus.get_object('org.xchat.service', '/org/xchat/Remote')
return dbus.Interface(xchat_object, 'org.xchat.plugin')
... |
anchor/make-magic | tools/lint.py | Python | bsd-3-clause | 3,918 | 0.026289 | #! /usr/bin/env python
'''lint for sets of items
There are many things that really shouldn't exist with a set of items. One
of the biggest is that the dependencies should form a directed acyclic graph,
with absolutely no cycles.
e.g. given the set of items {a.b,c}, if a depends on b, b depends on c,
and c depends ... | testinst = TestItem()
testinstb = TestItem()
testinst.depends = (testinstb,)
check_dependencies_are_instances(testinst)
try: # should fail
testinst = TestItem()
testinstb = TestItem()
testinst.contains = (testinstb, TestItem)
check_dependencies_are_instances(testinst)
raise Exception("Didn't catch obvio... | contains = (testinstb,)
check_dependencies_are_instances(testinst)
try: # should fail
testinst = TestItem()
testinst.predicate = lambda x: "Oh joy"
check_predicate_returns_boolean(testinst)
raise Exception("Didn't catch obvious lint error")
except LintError: pass
# SHould be fine
testinst = TestItem()
t... |
gsehub/edx-platform | lms/djangoapps/learner_dashboard/tests/test_programs.py | Python | agpl-3.0 | 9,854 | 0.00203 | # -*- coding: utf-8 -*-
"""
Unit tests covering the program listing and detail pages.
"""
import json
import re
from urlparse import urljoin
from uuid import uuid4
import mock
from bs4 import BeautifulSoup
from django.conf import settings
from django.urls import reverse, reverse_lazy
from django.test import override_s... | ramFactory(uuid=cls.program_uuid, courses=[course])
def setUp(self):
super(TestProgramDetails, self).setUp()
self.user = UserFactory()
self.client.login(usern | ame=self.user.username, password=self.password)
def assert_program_data_present(self, response):
"""Verify that program data is present."""
self.assertContains(response, 'programData')
self.assertContains(response, 'urls')
self.assertContains(response,
'"... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-vmwarecloudsimple/azure/mgmt/vmwarecloudsimple/__init__.py | Python | mit | 706 | 0.002833 | # 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 cause incorrect behavior and will be lost i | f the code is regenerated.
# --------------------------------------------------------------------------
from ._vmware_cloud_simple import VMwareCloudSimple
from ._version import VERSION
__version__ = VERSION
__all__ = ['VMwareCloudSimple']
try:
from ._patch import patch_sdk # type: ignore
patch_sdk()
except... |
super1337/Super1337-CTF | questionnaire/urls.py | Python | mit | 299 | 0.003344 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<quiz_slug>[-A-Za-z0-9_]+)/$', views.quiz, name='quiz'),
url(r'^(?P<quiz_slug>[-A-Za-z0-9_]+)/(?P<question_slug>[-A-Za-z0-9_]+)/$', views.question, name='question' | )
]
| |
goodmami/minigraph | minigraph.py | Python | mit | 16,121 | 0.003102 |
import warnings
from collections import namedtuple, defaultdict
#Node = namedtuple('Node', ('id', 'data', 'edges', 'in_edges'))
#Edge = namedtuple('Edge', ('start', 'end', 'label', 'data', 'directed'))
class MiniGraphError(Exception): pass
class MiniGraphWarning(Warning): pass
# todo: consider functools.lru_cache f... | e; label = data = None; directed = True
elif edgelen == 4:
start, end, label, data = edge; directed = True
elif edgelen == 3:
start, end, label = edge; data = None; directed = True
else:
raise MiniGraphError('Invalid ed | ge: {}'.format(edge))
if data is None: data = {}
if start not in g: g[start] = (start, {}, {}, {})
if end not in g: g[end] = (end, {}, {}, {})
e = (start, end, label, data, directed)
#add_edge(g[start][2], label, end, e)
d = g[start][2]
... |
Bathlamos/Project-Euler-Solutions | solutions/p052.py | Python | mit | 451 | 0.035477 | #
# Solution to Project Euler | problem 52
# Philippe Legault
#
# https://github.com/Bathlamos/Project-Euler-Solutions
import itertools
def compute():
c = 1
while True:
lists = [digits(c * n) for n in range(1, 7)]
if len(set(lists)) == 1: # Check that all elements are equal
return c
c += 1
def digits(n):
res = []
while n != 0:
r... | mpute()) |
simontaylor81/Syrup | SRPTests/TestScripts/Python/RenderTarget.py | Python | mit | 326 | 0.021472 | # Test for creating custom render targets.
from SRPScripting import *
import utils
rt = ri.CreateRenderTarget()
te | stTexCallback = utils.GetTestTextureCallback(ri, rt, "FullscreenTexture_PS", "tex")
def RenderFrame(co | ntext):
context.Clear((1, 0.5, 0, 1), [rt])
testTexCallback(context)
ri.SetFrameCallback(RenderFrame)
|
alexgleith/Quantum-GIS | python/plugins/sextante/algs/ftools/Delaunay.py | Python | gpl-2.0 | 4,431 | 0.002257 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Delaunay.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | y(inFeat.geometry())
point = geom.asPoint()
x = point.x()
y = point.y()
| pts.append((x, y))
ptNdx += 1
ptDict[ptNdx] = inFeat.id()
if len(pts) < 3:
raise GeoAlgorithmExecutionException("Input file should contain at least 3 points. Choose another file and try again.")
uniqueSet = Set(item for item in pts)
ids = [pts.index(item... |
mitodl/open-discussions | channels/migrations/0002_add_subscription.py | Python | bsd-3-clause | 1,675 | 0.000597 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-19 19:08
from __future__ import unicode_literals
import channels.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migr... | , channels.models.Base36IntegerField(null=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
... | erIndexTogether(
name="subscription", index_together=set([("post_id", "comment_id")])
),
]
|
ilay09/keystone | keystone/tests/unit/identity/backends/test_ldap.py | Python | apache-2.0 | 1,538 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | test_base.IdentityDriverTests):
allows_name_update = False
allows_self_service_change_password = False
expected_is_domain_aware = False
expected_default_assignment_driver = 'sql'
expected_is_sql = False
expected_generates_uuids = False
def setUp(self):
super(TestIde | ntityDriver, self).setUp()
config_fixture_ = self.useFixture(config_fixture.Config())
config_fixture_.config(
group='ldap',
url='fake://memory',
user='cn=Admin',
password='password',
suffix='cn=example,cn=com')
self.useFixture(ldapdb.... |
wukong-m2m/NanoKong | tools/demo20120423/showNodeStatus.py | Python | gpl-2.0 | 3,336 | 0.021882 | #!/usr/bin/python
import sys
sys.path.append("/Users/niels/git/nanokong/tools/python")
import wkpf
from wkpf import WuObject
numericInputWuObject = WuObject(nodeId=1, portNumber=1, wuclassId=3)
lightSensorWuObject = WuObject(nodeId=1, portNumber=2, wuclassId=5)
thresholdWuObjectScenario1 = WuObject(nodeId=1, portNumb... | t "value:", input_value
print "=== Threshold"
print "operator:", threshold_operator
print "threshold:", threshold_threshold
print "value:", threshold_value
print "output:", threshold_output
print "=== Occupacy"
print "value:", occupancy_value
print "=== And Gate"
print "in1 (threshold):", andgate_in1
... | t wuobjectsNode1
print "=== WuObjects on node 3"
print wuobjectsNode3
else: # Scenario 1
light_sensor_value = wkpf.getProperty(lightSensorWuObject, propertyNumber=0)
input_value = wkpf.getProperty(numericInputWuObject, propertyNumber=0)
threshold_operator = wkpf.getProperty(thresholdWuObjectScenario1, prope... |
kfrodgers/active-mail-filter | active_mail_filter/simple_db.py | Python | bsd-2-clause | 3,390 | 0.000295 | # Copyright (c) 2016, Kevin Rodgers
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
import redis
from uuid import uuid4
UUID = 'uuid'
class SimpleRedisDb(object):
def __init__(self, host, key, port=6379):
"""
:param host: database host
:p... | oves all keys from hash set
:return:
"""
self._open_db()
record_keys = self.redis.hkeys(self.key)
| for u in record_keys:
self.redis.hdel(self.key, u)
def get_record(self, record_key):
"""
Return record dictionary for specified UUID
:param record_key:
:return:
record dictionary or None if not found
"""
self._open_db()
record_str ... |
Aravinthu/odoo | addons/auth_signup/controllers/main.py | Python | agpl-3.0 | 6,625 | 0.003774 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import werkzeug
from odoo import http, _
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.addons.web.controllers.main import ensure_db, Home
from odoo.exceptions import UserError
... | (Home):
@http.r | oute()
def web_login(self, *args, **kw):
ensure_db()
response = super(AuthSignupHome, self).web_login(*args, **kw)
response.qcontext.update(self.get_auth_signup_config())
if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'):
# ... |
sergiohzlz/lectorcfdi | extrainfo.py | Python | apache-2.0 | 8,345 | 0.016906 | #!/usr/bin/python
#-*-coding:utf8-*-
from bs4 import BeautifulSoup as Soup
#import pandas as pd
import glob
import sys
import re
"""
Version xml de cfdi 3.3
"""
class CFDI(object):
def __init__(self, f):
"""
Constructor que requiere en el parámetro una cadena con el nombre del
cfdi.
... | ion' and
sorted(e.attrs.keys())==['importe','impuesto'])
#============emisor==========================
self.__emisorrfc = emisor['rfc']
try:
self.__emisornombre = emisor['nombre']
| except:
self.__emisornombre = emisor['rfc']
#============receptor========================
self.__receptorrfc = receptor['rfc']
try:
self.__receptornombre = receptor['nombre']
except:
self.__receptornombre = receptor['rfc']
#============... |
KiChjang/servo | tests/wpt/web-platform-tests/tools/manifest/typedata.py | Python | mpl-2.0 | 10,877 | 0.000827 | from collections.abc import MutableMapping
MYPY = False
if MYPY:
# MYPY is set to True when run under Mypy.
from typing import Any
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from typing import Set
from typing import Text
... | > Set[item.ManifestItem]
node = self._data # type: Union[Dict[Text, Any], Set[item.ManifestItem], List[Any]]
| for pathseg in key:
if isinstance(node, dict) and pathseg in node:
node = node[pathseg]
else:
break
else:
if isinstance(node, set):
return node
else:
raise KeyError(key)
node = self._json_dat... |
nh0815/PySearch | pysearch/views.py | Python | mit | 154 | 0.012987 | from | django.shortcuts import render, redirect
from django.http import HttpResponse
__author__ = 'Nick'
def index(request):
return redirect('/search') | |
SuicSoft/stk-code | tools/update_characteristics.py | Python | gpl-3.0 | 2,103 | 0.009035 | #!/usr/bin/env python3
#
# SuperTuxKart - a fun racing game with go-kart
# Copyright (C) 2006-2015 SuperTuxKart-Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of... | 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 Place - Suite 330, Boston, MA 02111-1307, U... | in the source are marked with tags, that
# contain the argument that has to be passed to create_kart_properties.py.
# The script has to be run from the root directory of this project.
import os
import re
import subprocess
from create_kart_properties import functions
def main():
# Check, if it runs in the root d... |
GeneralizedLearningUtilities/SuperGLU | python_module/stomp/test/p3_backward_test.py | Python | mit | 884 | 0 | import unittest
from stomp import backward3
class TestBackward3(unittest.TestCase):
def test_pack_mixed_string_and_bytes(self):
lines = ['SEND', '\n', 'header1:test', '\u6771']
self.assertEqual(backward3.encode(backward3.pack(lines)),
b'SEND\nheader1:test\xe6\x9d... | r1:test', b'\xe6\x9d\xb1']
self.assertEqual(backward3.encode(backward3.pack(lines)),
b'SEND\nheader1:test\xe6\x9d\xb1')
def test_decode(self):
self.assertTrue(backward3.decode(None) is None)
self.assertEqual('test', backward3.decode(b'test'))
def test_e... | code(b'test'))
self.assertRaises(TypeError, backward3.encode, None)
|
OlympusMonds/PyCircleriser | PyCircleriser.py | Python | gpl-3.0 | 8,228 | 0.007049 | #============================================================================
# Name : circ-pic.py
# Author : Luke Mondy
# ============================================================================
#
# Copyright (C) 2012 Mondy Luke
#
# This program is free software: you can redistribute it and/or modify
#... | # (x, y, rad)
dist = sqrt( (c2[0] - c1[0])**2 + (c2[1] - c1[1])**2 ) # This sqrt is killin' me...
if c1[2] + c2[2] > dist:
return True
return False
def render(circles, path, params, imsize):
log("Rendering...")
if params['bgimg']:
bg = getImage(params['bgimg'], | grey=False)
bgim = bg.resize(imsize)
bgpix = bgim.load()
col = params['bgcolour']
col = 255 if col > 255 else col
col = 0 if col < 0 else col
bgcolour = (col, col, col)
outline = (0, 0, 0)
if params['nooutline']:
outline = None
final = Image.new('RGB', imsize, ... |
monouno/site | judge/migrations/0039_remove_contest_is_external.py | Python | agpl-3.0 | 399 | 0 | # -*- coding: utf-8 -*-
# Genera | ted by Django 1.9.7 on 2016-08-09 22:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
| ('judge', '0038_profile_problem_count'),
]
operations = [
migrations.RemoveField(
model_name='contest',
name='is_external',
),
]
|
AaronGeist/Llama | core/emailsender.py | Python | gpl-3.0 | 1,822 | 0.000551 | # -*- coding:utf-8 -*-
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from core.enigma import Enigma
from model.email import Email
from util.config import Config
class EmailSender:
@classmethod
def format_addr(cls, s):
... | email.stmp_port = Config.get("email_stmp_port")
email.is_ssl = Config.get("email_is_ssl")
email.title = title
email.body = content
return email
@classmethod
def send(cls, title, content):
email = cls.generate_email(title, content)
msg = cls.build_msg(email)
... |
else:
server = smtplib.SMTP(email.stmp_server, email.stmp_port)
# server.set_debuglevel(1)
server.login(email.from_addr, email.password)
server.sendmail(email.from_addr, email.to_addr, msg.as_string())
server.quit()
if __name__ == "__main__":
EmailSender.send("... |
redline-forensics/auto-dm | controllers/main_ctrl.py | Python | gpl-3.0 | 2,757 | 0.001814 | from controllers.job_ctrl import JobController
from models.job_model import JobModel
from views.job_view import JobView
class MainController(object):
def __init__(self, main_model):
self.main_view = None
self.main_model = main_model
self.main_model.begin_job_fetch.connect(self.on_begin_jo... | found = bool(job.base_folder)
self.main_ | view.close_job_fetch_progress_dialog()
if not found:
open_anyway = self.main_view.show_job_not_found_dialog()
if not open_anyway:
return
job_view = JobView(JobController(job))
job_view.request_minimize.connect(self.main_view.close)
self.main_view.... |
shepdelacreme/ansible | lib/ansible/modules/cloud/openstack/os_volume.py | Python | gpl-3.0 | 5,265 | 0.00133 | #!/usr/bin/python
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | )
def _absent_volume(module, cloud, sdk):
changed = False
if cloud.volume_exists(module.params['display_name']):
try:
changed = cloud.delete_volume(name_or_id=module.params['display_name'],
wait=module.params['wait'],
... | ons.ResourceTimeout:
module.exit_json(changed=changed)
module.exit_json(changed=changed)
def main():
argument_spec = openstack_full_argument_spec(
size=dict(default=None),
volume_type=dict(default=None),
display_name=dict(required=True, aliases=['name']),
display_d... |
shear/rppy | temp_test_ortho.py | Python | bsd-2-clause | 1,170 | 0.005128 | import rppy
im | port numpy as np
import matplotlib.pyplot as plt
vp1 = 3000
vs1 = 1500
p1 = 2000
e1_1 = 0.0
d1_1 = 0.0
y1_1 = 0.0
e2_1 = 0.0
d2_1 = 0.0
y2_1 = 0.0
d3_1 = 0.0
chi1 = 0.0
C1 = rppy.reflectivity.Cij(vp1, vs1, p1, e1_1, d1_1, y1_1, e2_1, d2_1, y2_1, d3_1)
vp2 = 4000
vs2 = 2000
p | 2 = 2200
e1_2 = 0.0
d1_2 = 0.0
y1_2 = 0.0
e2_2 = 0.0
d2_2 = 0.0
y2_2 = 0.0
d3_2 = 0.0
chi2 = 0.0
C2 = rppy.reflectivity.Cij(vp2, vs2, p2, e1_2, d1_2, y1_2, e2_2, d2_2, y2_2, d3_2)
phi = np.arange(0, 90, 1)
theta = np.arange(0, 90, 1)
loopang = phi
theta = np.array([30])
rphti = np.zeros(np.shape(loopang))
rpzoe = np... |
thombashi/pytablewriter | test/writer/text/rst/test_rst_csv_writer.py | Python | mit | 6,875 | 0.001309 | """
.. codeauthor:: Tsuyoshi Hombas | hi <tsuyoshi.hombashi@gmail.com>
"""
from textwrap import dedent
import pytest
import pytablewriter
from ...._common import print_test_result
from ....data import (
Data,
headers,
mix_header_list,
mix_value_matrix,
null_test_data_list,
value_matrix,
value_matrix_iter,
value_matrix_wi... | Data(
table="table name",
indent=0,
header=headers,
value=value_matrix,
expected=dedent(
"""\
.. csv-table:: table name
:header: "a", "b", "c", "dd", "e"
:widths: 3, 5, 5, 4, 6
1, 123.1, "a", 1.0, 1
... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/network/ios/ios_static_route.py | Python | bsd-3-clause | 7,090 | 0.001551 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# Ansible 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 Li... | ription:
- Next hop IP of the static route.
admin_distance:
description:
- Admin distance of the static route.
default: 1
aggregate:
description: List of static route definitions.
state:
description:
- State of the static r | oute configuration.
default: present
choices: ['present', 'absent']
"""
EXAMPLES = """
- name: configure static route
ios_static_route:
prefix: 192.168.2.0
mask: 255.255.255.0
next_hop: 10.0.0.1
- name: remove configuration
ios_static_route:
prefix: 192.168.2.0
mask: 255.255.255.0
... |
quaddra/dist_job_mgr | setup.py | Python | apache-2.0 | 639 | 0.00626 | from setuptools import setup, find_packages
from dist_job | _mgr.version import VERSION
setup(
name='dist_job_mgr',
version=VERSION,
author='genForma Corp',
author_email='code@genforma.com',
url='',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points = {
'console_scripts': [
'djmctl = dist_job_... | r_main:main'
]},
install_requires=['lockfile>=0.9',], # 'python-daemon'],
license='Apache V2.0',
description='Distributed Job Manager',
long_description="description"
)
|
cidadania/e-cidadania | src/helpers/cache.py | Python | apache-2.0 | 1,903 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Clione Software
# Copyright (c) 2010-2013 Cidadania S. Coop. Galega
#
# 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.or... | ""
This file contains functions to help with caching.
"""
# Django's cache module
from django.core.cache import cache
# Cached models
from core.spaces.models | import Space
# Response types
from django.shortcuts import get_object_or_404
# Tries to get the object from cache
# Else queries the database
# Else returns a 404 error
def _get_cache_key_for_model(model, key):
"""
Returns a unique key for the given model.
We prefix the given `key` with the name of the... |
abinashk-inf/AstroBox | src/astroprint/printerprofile/__init__.py | Python | agpl-3.0 | 2,918 | 0.002742 | # coding=utf-8
__author__ = "AstroPrint Product Team <product@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 3DaGoGo, Inc - Released under terms of the AGPLv3 License"
# singleton
_instance = None
def printerProfileManager(... |
self.data = {
'driver': "marlin",
'extruder_count': 1,
'max_nozzle_temp': 280,
'max_bed_temp': 140,
'heated_bed': True,
'cancel_gcode': ['G | 28 X0 Y0'],
'invert_z': False
}
if not os.path.isfile(self._infoFile):
factoryFile = "%s/printer-profile.factory" % configDir
if os.path.isfile(factoryFile):
shutil.copy(factoryFile, self._infoFile)
else:
open(self._infoFil... |
amarquand/nispat | pcntoolkit/normative_model/norm_blr.py | Python | gpl-3.0 | 8,464 | 0.006971 | from __future__ import print_function
from __future__ import division
import os
import sys
import numpy as np
import pandas as pd
from ast import literal_eval
try: # run as a package if installed
from pcntoolkit.model.bayesreg import BLR
from pcntoolkit.normative_model.norm_base import NormBase
from pcnt... | lize BLR object because parameters were not specified
self.blr = BLR(theta=theta, X=Phi, y=y,
var_groups=self.var_groups,
warp=self.warp, **kwargs)
self.theta = self.blr.estimate(theta, Phi, y,
var_covar... | ovariates, **kwargs)
return self
def predict(self, Xs, X=None, y=None, **kwargs):
theta = self.theta # always use the estimated coefficients
# remove from kwargs to avoid downstream problems
kwargs.pop('theta', None)
Phis = create_p... |
wuzhy/autotest | client/tests/kvm/kvm.py | Python | gpl-2.0 | 5,376 | 0.000558 | import os, logging, imp
from autotest_lib.client.bin import test
from autotest_lib.client.common_lib import error
from autotest_lib.client.virt import virt_utils, virt_env_process
class kvm(test.test):
"""
Suite of KVM virtualization functional tests.
Contains tests for testing both KVM kernel code and us... | = 'yes':
raise error.TestNAError("Test dependency failed")
# Report the parameters we've received | and write them as keyvals
logging.debug("Test parameters:")
keys = params.keys()
keys.sort()
for key in keys:
logging.debug(" %s = %s", key, params[key])
self.write_test_keyval({key: params[key]})
# Set the log file dir for the logging mechanism used ... |
highfei2011/spark | python/pyspark/sql/tests/test_serde.py | Python | apache-2.0 | 6,215 | 0.00177 | #
# 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... | ="")})]
df = self.sc.parallelize(d).toDF()
k, v = list(df.head().m.items())[0]
self.assertEqual(1, k.i)
self.assertEqual("", v.s)
def test_filter_with_datetime(s | elf):
time = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000)
date = time.date()
row = Row(date=date, time=time)
df = self.spark.createDataFrame([row])
self.assertEqual(1, df.filter(df.date == date).count())
self.assertEqual(1, df.filter(df.time == time).count())
se... |
ilayn/scipy | scipy/fft/tests/test_fftlog.py | Python | bsd-3-clause | 5,819 | 0 | import warnings
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.fft._fftlog import fht, ifht, fhtoffset
from scipy.special import poch
def test_fht_agrees_with_fftlog():
# check that fht numerically agrees with the output from Fortran FFTLog,
# the results were generated... | e(3491349965)
a = | rng.standard_normal(n)
dln = rng.uniform(-1, 1)
mu = rng.uniform(-2, 2)
if optimal:
offset = fhtoffset(dln, mu, initial=offset, bias=bias)
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases... |
JelleZijlstra/cython | Cython/Compiler/Nodes.py | Python | apache-2.0 | 357,409 | 0.002781 | #
# Parse tree nodes
#
from __future__ import absolute_import
import cython
cython.declare(sys=object, os=object, copy=object,
Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object,
py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=obje... | f not name.is_string_literal:
continue |
if name.value in ('type', b'type'):
explicit_pytype = True
if not explicit_ctype:
annotation = value
elif name.value in ('ctype', b'ctype'):
explicit_ctype = True
annotation = value
if explicit_pytype an... |
nburn42/tensorflow | tensorflow/python/tools/optimize_for_inference_test.py | Python | apache-2.0 | 13,432 | 0.005435 | # pylint: disable=g-bad-file-header
# 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/LICENS... | rt gen_nn_ops
from tensorflow.python.ops import image_ops
from tensorflow.python.ops import math_ops # pylint: disable=unused-import
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import test
from tensorflow.python.tools import optimize_for_inference_lib
class OptimizeForInferenceTest(test.... | name = name
for input_name in inputs:
new_node.input.extend([input_name])
return new_node
def create_constant_node_def(self, name, value, dtype, shape=None):
node = self.create_node_def("Const", name, [])
self.set_attr_dtype(node, "dtype", dtype)
self.set_attr_tensor(node, "value", value, d... |
sandroandrade/emile-server | cruds/crud_wall_messages/models.py | Python | gpl-3.0 | 1,182 | 0.001692 | import datetime
from backend import db
from cruds.crud_user_type_destinations.models import UserTypeDestinations
from cruds.crud_users.models import Users
from cruds import format_urls_in_text
class WallMessages(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
date = db.Column( | db.Integer)
sender = db.Column(db.Integer, db.ForeignKey("users.id"))
destination = db.Column(db.Integer, db.ForeignKey("user_type_desti | nations.id"))
param_value = db.Column(db.Integer())
message = db.Column(db.Text())
def set_fields(self, fields):
self.date = fields['date']
self.sender = fields['sender']
self.destination = fields['user_type_destination_id']
self.param_value = fields['parameter']
sel... |
Gabotero/GNURadioNext | gnuradio-runtime/python/gnuradio/gr/tag_utils.py | Python | gpl-3.0 | 1,719 | 0.004072 | #
# Copyright 2003-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in t | he 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 GNU Radio; see the file COPYI... |
simeonf/sfpython | sfpython/jobs/migrations/0007_auto_20151115_0614.py | Python | apache-2.0 | 865 | 0.002312 | # -*- coding: utf-8 -*-
from __future | __ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('jobs', '0006_auto_20151115_0609'),
]
operations = [
| migrations.AlterModelOptions(
name='job',
options={'ordering': ['order'], 'verbose_name': 'Job Details', 'verbose_name_plural': 'Job Postings'},
),
migrations.AddField(
model_name='job',
name='location',
field=models.CharField(default=b'... |
Rdbaker/Rank | rank/__init__.py | Python | mit | 87 | 0 | MAJOR = 1
MINOR = 0
PATCH = | 0
__version__ = "{0}.{1}.{2}".format(MAJOR, | MINOR, PATCH)
|
idegtiarov/ceilometer | ceilometer/api/controllers/v2/base.py | Python | apache-2.0 | 8,636 | 0 | #
# Copyright 2012 New Dream Network, LLC (DreamHost)
# Copyright 2013 IBM Corp.
# Copyright 2013 eNovance <licensing@enovance.com>
# Copyright Ericsson AB 2013. All rights reserved
# Copyright 2014 Hewlett-Packard Company
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0... | automatically
# let it default to self.value
pass
| else:
if type not in self._supported_types:
# Types must be explicitly declared so the
# correct type converter may be used. Subclasses
# of Query may define _supported_types and
# _type_converters to define their o... |
yehzhang/RapidTest | examples/solutions/plus_one.py | Python | mit | 400 | 0 | class Solution(o | bject):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in range(len(digits) - 1, -1, -1):
if | digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
new_digits = [1]
new_digits.extend([0] * len(digits))
return new_digits
|
jupyter/jupyter-drive | setup.py | Python | bsd-2-clause | 2,752 | 0.002544 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
#with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-... | Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: BSD License'... | cate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Framework :: IPyt... |
asifhj/Python_SOAP_OSSJ_SAP_Fusion_Kafka_Spark_HBase | KafkaCP.py | Python | apache-2.0 | 2,510 | 0.003586 | __author__ = 'asifj'
import logging
from kafka import KafkaConsumer
import json
import traceback
from bson.json_util import dumps
from kafka import SimpleProducer, KafkaClient
from utils import Utils
logging.basicConfig(
format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(me... | if type == "srDetails":
print "+++++++++++++++++++++++++++++++++++++++++++++ | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
row = []
utils = Utils()
row = utils.validate_sr_details( document['srDetails'], row)
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
... |
Azure/azure-sdk-for-python | sdk/security/azure-mgmt-security/azure/mgmt/security/operations/_regulatory_compliance_controls_operations.py | Python | mit | 9,157 | 0.004477 | # 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 ... | :ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.security.models
:param client: Client for service requests.
:param config: Configuration of service client. |
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
... |
openfisca/openfisca-france-extension-revenu-de-base | openfisca_france_extension_revenu_de_base/cotisations.py | Python | agpl-3.0 | 7,784 | 0.004758 | # -*- coding: utf-8 -*-
from __future__ import division
from openfisca_core import reforms
from openfisca_france.model.base import FloatCol, Individus, Variable
# Build function
def build_reform(tax_benefit_system):
Reform = reforms.make_reform(
key = 'revenu_de_base_cotisations',
name = u"Réfo... | cotisation_exceptionnelle_temporaire_employeur +
prevoyance_obligatoire_cadre + # TODO contributive ou pas
vieillesse_d | eplafonnee_employeur +
vieillesse_plafonnee_employeur +
# cotisations patronales contributives dans le public
fonds_emploi_hospitalier +
ircantec_employeur +
pension_civile_employeur +
rafp_employeur +
# anci... |
Endika/account-invoice-reporting | base_comment_template/__openerp__.py | Python | agpl-3.0 | 1,121 | 0 | # -*- coding: utf-8 -*-
#
#
# Author: Nicolas Bessi
# Copyright 2013-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Softwa | re Foundation, either version 3 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 Affero Genera... | rg/licenses/>.
#
#
{"name": "Base Comments Templates",
"summary": "Comments templates on documents",
"version": "8.0.1.0.0",
"depends": ["base"],
"author": "Camptocamp,Odoo Community Association (OCA)",
"data": ["comment_view.xml",
'security/ir.model.access.csv',
],
"category": "Sale",
"insta... |
memsql/memsql-loader | memsql_loader/loader_db/storage.py | Python | apache-2.0 | 2,959 | 0.000676 | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This clas | s cannot be shared across forked processes unless
# you use fork_wrapper.
class LoaderStorage(APSWStorage):
_instance = None
_initialized = False
_instance_lock = multiprocessing.RLock()
# We use LoaderStorage as a singleton.
def __new__(cls, *args, **kwargs):
with cls._instance_lock:
... | ialized = False
return cls._instance
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get... |
datagutten/comics | comics/comics/exiern.py | Python | agpl-3.0 | 784 | 0 | from comics.aggregato | r.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Exiern'
language = 'en'
url = 'http://www.exiern.com/'
start_date = '2005-09-06'
rights = 'Dan Standing'
class Crawler(CrawlerBase):
history_capable_days = 30
... | feed.for_date(pub_date):
url = entry.summary.src('img', allow_multiple=True)
if url:
url = url[0]
url = url.replace('comics-rss', 'comics')
title = entry.title
return CrawlerImage(url, title)
|
djurodrljaca/tuleap-rest-api-client | Tuleap/RestClient/PullRequests.py | Python | lgpl-3.0 | 6,833 | 0.002927 | """
Created on 04.07.2017
:author: Humbert Moreaux
Tuleap REST API Client for Python
Copyright (c) Humbert Moreaux, All rights reserved.
This Python module is fr | ee 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.0
of the License, or (at your option) any later version.
This Python module is distributed in the hope that it will be useful, but WITHOUT ANY WA... | blic License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library. If
not, see <http://www.gnu.org/licenses/>.
"""
import json
# Public -------------------------------------------------------------------------------------------
class PullRequests(object)... |
uraplutonium/adtree-py | src/BayesUpdating.py | Python | gpl-2.0 | 2,726 | 0.005869 | # Add any code that updates the current probability
# values of any of the nodes here.
# For example, here is a method that updates the probability of
# a single node, where this node is assumed to have a single parent.
def update_node_with_one_parent(n):
'''
For all possible values pv of the current node,
... | _prob[pv] = 0.0
print " Updating current prob. of "+pv
for ppv_tuple in cartesian_prod:
print " Adding the contribution for "+str(ppv_tuple)
conditional = n.name+'='+pv+'|'+str(parent_names) +'='+str(ppv_tuple)
parent_vector_prob = reduce(lambda a,b:a*b, map(lambd... | ts, ppv_tuple))
n.current_prob[pv] += n.p[conditional] * parent_vector_prob
#update_node_with_one_parent(nodeB)
|
datalogics/scons | test/Java/JAVAC.py | Python | mit | 2,542 | 0.003934 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | LIMITED TO THE
# WARRANT | IES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER D... |
wolsen/secret-santa | secretsanta/mail.py | Python | mit | 4,308 | 0.001161 | #!/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Billy Olsen
#
# 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... | ', 'username', 'password']
def __init__(self, author, email, smtp, username, password,
template_master="master.tmpl", template_santa="santa.tmpl"):
| self.author = author
self.email = email
self.smtp = smtp
self.username = username
self.password = password
self.template_master = template_master
self.template_santa = template_santa
def send(self, pairings):
"""
Sends the emails out to the secr... |
moshthepitt/answers | questions/migrations/0014_auto_20160210_0406.py | Python | mit | 573 | 0 | # -*- coding: utf- | 8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0013_auto_20160210_0400'),
]
operations = [
migrations.AlterField(
model_name='category',
n | ame='order',
field=models.PositiveIntegerField(default=1),
),
migrations.AlterField(
model_name='question',
name='order',
field=models.PositiveIntegerField(default=1),
),
]
|
bdcht/amoco | tests/test_arch_tricore.py | Python | gpl-2.0 | 918 | 0.037037 | import pytest
from amoco.config import conf
conf.UI.formatter = 'Null'
conf.Cas.unicode = False
conf.UI.unicode = False
from amoco.arch.tricore import cpu
def test_decoder_START():
c = b'\x91\x00\x00\xf8'
i = cpu.disassemble(c)
ass | ert i.mnemonic=='MOVH_A'
assert i.operands[0] is cpu.A[15]
assert i.operands[1]==0x8000
c = b'\xd9\xff\x14\x02'
i = cpu.disassemble(c)
assert i.mnemonic=="LEA"
assert i.mode=="Long-offset"
assert i.ope | rands[2]==0x2014
c = b'\xdc\x0f'
i = cpu.disassemble(c)
assert i.mnemonic=="JI"
assert i.operands[0]==cpu.A[15]
c = b'\x00\x90'
i = cpu.disassemble(c)
assert i.mnemonic=="RET"
c = b'\x00\x00'
i = cpu.disassemble(c)
assert i.mnemonic=="NOP"
def test_decoder_ldw():
c = b'\x19\xf0\x10\x16'
i =... |
xiangke/pycopia | QA/pycopia/reports/__init__.py | Python | lgpl-2.1 | 17,925 | 0.004965 | #!/usr/bin/python2.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
# $Id$
#
# Copyright (C) 1999-2006 Keith Dart <keith@kdart.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software... | dule with a particular pattern of
paramters and it will return a report | object according to that. Any
necessary report objects and modules are specified there, and imported as
necessary.
e.g.:
get_report( ("StandardReport", "reportfile", "text/plain") )
Note that the argument is a single tuple. A list of these may be supplied
for a "stacked" report.
The first argument is a report... |
altai/altai-api | altai_api/exceptions.py | Python | lgpl-2.1 | 4,527 | 0.000221 |
# vim: tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab autoindent
# Altai API Service
# Copyright (C) 2012-2013 Grid Dynamics Consulting Services, Inc
# All Rights Reserved
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License ... | request"""
def __init__(self, name, reason=None):
super(UnknownArgument, self).__init__(
'Unknown request argument: %r' % name, name, reason)
class InvalidArgumentValue(InvalidArgument):
"""Exception raised when some client inpu | t has illegal value"""
def __init__(self, name, typename, value, reason=None):
msg = 'Invalid value for argument %s of type %s: %r' \
% (name, typename, value)
super(InvalidArgumentValue, self).__init__(msg, name, reason)
self.typename = typename
self.value = value
... |
MrSurly/micropython | tests/basics/class_inplace_op2.py | Python | mit | 1,293 | 0.000773 | # Test inplace special methods enabled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS
class A:
def __imul__(self, other):
print("__imul__")
return self
def __imatmul__(self, other):
print | ("__imatmul__")
return self
def __ifloordiv__(self, other):
print("__ifloordiv__")
return self
def __itruediv__(self, other):
print("__itruediv__")
return self
def __imod__(self, other):
print("__imod__")
return self
| def __ipow__(self, other):
print("__ipow__")
return self
def __ior__(self, other):
print("__ior__")
return self
def __ixor__(self, other):
print("__ixor__")
return self
def __iand__(self, other):
print("__iand__")
return self
def __... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/FlAv/PyScripts/Lib/flav/flav/cmd/flavcontrol/type_Result.py | Python | unlicense | 4,626 | 0.002162 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: type_Result.py
from types import *
class AvailableResult:
def __init__(self):
self.__dict__['available'] = False
def __getattr__(s... | alue
elif name == 'fix':
self.__dict__['fix'] = value
elif name == 'build':
self.__ | dict__['build'] = value
elif name == 'available':
self.__dict__['available'] = value
else:
raise AttributeError("Attribute '%s' not found" % name)
def Marshal(self, mmsg):
from mcl.object.Message import MarshalMessage
submsg = MarshalMessage()
submsg.... |
pprivulet/DataScience | Dic/getDetail.py | Python | apache-2.0 | 3,537 | 0.015653 | # -*- coding:utf-8 -*-
#html_doc = '''<div><a href="http://www.weblio.jp/content/%E5%BD%A2%E5%AE%B9%E5%8B%95%E8%A9%9E" title="形容動詞の意味" class=crosslink>形容動詞</a>「<a href= | "http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャルの意味" class=crosslink>アーティフィシャル</a>だ」が、<a href="http://www.weblio.jp/content/%E6%8E%A5%E5%B0%BE%E8%AA%9E" title="接尾語の意味" class=crosslink>接尾語</a>「さ」により<a href="http://www.weblio.jp/content/%E4%... | 味" class=crosslink>体言</a>化した形。<br><br class=nhgktD><div><!--AVOID_CROSSLINK--><p class=nhgktL>終止形</p><p class=nhgktR>アーティフィシャルだ <a href="http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャル">» 「アーティフィシャル」の意味を調べる</a></p><!--/AVO... |
gtaylor/EVE-Market-Data-Relay | emdr/daemons/announcer/main.py | Python | mit | 1,274 | 0.00314 | """
Gateways connect to Announcer daemons, sending zlib compressed JSON
representations of market data. Fro | m here, the Announcer PUBs the messages
out to anyone SUBscribing. This could be Relays, or end-users.
"""
import logging
logger = logging.getLogger(__name__)
import gevent
import zmq.green as zmq
from emdr.conf import de | fault_settings as settings
def run():
"""
Fires up the announcer process.
"""
context = zmq.Context()
receiver = context.socket(zmq.SUB)
receiver.setsockopt(zmq.SUBSCRIBE, '')
for binding in settings.ANNOUNCER_RECEIVER_BINDINGS:
# Gateways connect to the Announcer to PUB messages.
... |
Tojaj/yum-metadata-diff | yum_metadata_diff/diff_objects.py | Python | lgpl-2.1 | 10,928 | 0.001647 | import pprint
import difflib
_MAX_LENGTH = 80
def pretty_diff(d1, d2):
def safe_repr(obj, short=False):
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
return res... | repr(item))
return '\n'.join(lines)
diff = None
if not isinstance(d1, type(d2)):
return diff
if d1 == d2:
return diff
if isinstance(d1, dict):
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).s... | ence_diff(d1, d2, seq_type=tuple)
elif isinstance(d1, set):
diff = set_diff(d1, d2)
elif isinstance(d1, frozenset):
diff = set_diff(d1, d2)
return diff
class ItemDiff(object):
ITEM_NAME = "Item"
def __init__(self):
self.differences = []
def __nonzero__(self):
... |
robjordan/sitefinder | src/sitefinder_project/wsgi.py | Python | mit | 942 | 0.003185 | """
WSGI config for sitef | inder_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitefinder_project.settings.production")
from django... | cation()
# Wrap werkzeug debugger if DEBUG is on
from django.conf import settings
if settings.DEBUG:
try:
import django.views.debug
import six
from werkzeug.debug import DebuggedApplication
def null_technical_500_response(request, exc_type, exc_value, tb):
six.reraise(e... |
MachineLearningControl/OpenMLC-Python | MLC/Population/Creation/IndividualSelection.py | Python | gpl-3.0 | 2,329 | 0.001719 | # -*- coding: utf-8 -*-
# MLC (Machine Learning Control): A genetic algorithm library to solve chaotic problems
# Copyright (C) 2015-2017, Thomas Duriez (thomas.duriez@gmail.com)
# Copyright (C) 2015, Adrian Durán (adrianmdu@gmail.com)
# Copyright (C) 2015-2017, Ezequiel Torres Feyuk (ezequiel.torresfeyuk@gmail.com)
# ... | t 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 mor | e details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
from BaseCreation import BaseCreation
from MLC.db.mlc_repository import MLCRepository
class IndividualSelection(BaseCreation):
"""
Fill a Population with fix... |
natbraun/biggraphite | tests/test_drivers_utils.py | Python | apache-2.0 | 1,554 | 0 | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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... | ce()
# Failing again should not call the callback again.
self.count_down.on_failure(exc)
self.on_zero.assert_called_once()
def test_on_result(self):
result = "whatever this is not used"
for _ in xrange(self._COUNT - 1):
self.count_down.on_result(result)
... | == "__main__":
unittest.main()
|
joezippy/paywall | test-keybase.py | Python | apache-2.0 | 1,556 | 0.001928 | #!/usr/bin/python3
import cgi
import cgitb
import datetime
import json
import os
import re
import requests
import subprocess
import sys
import time
from bmdjson import check_address
print("Content-Type: text/plain\n")
print("testing keybase")
print()
print("PASS:")
signature = "BEGIN KEYBASE SALTPACK SIGNED MESSAG... | x: x[0]):
# is saying the leftmost of the pair | k,v -- alphabetic sorting of keys
# now sig_addr, sig_by, then sig_good -- display bugged me
print("[" + str(k) + "] = ", v)
print()
print("FAIL: Bad String")
signature2 = "BEGIN KEYBASE SALTPACK SIGNED MESSAGE. kXR7VktZdy27rvq v5weRa0zkDL3e9k D1e7HgTLY1WFWdi UfZI1s56lquWUJu lBvdIblMbFGwTGa M9oYSI9cU7KjGW9 2JO... |
rfhk/awo-custom | account_invoice_line_view_oaw/__init__.py | Python | lgpl-3.0 | 199 | 0 | # | -* | - coding: utf-8 -*-
# Copyright 2015-2017 Rooms For (Hong Kong) Limted T/A OSCG
# Copyright 2017 eHanse
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import models
|
joerg84/arangodb | 3rdParty/V8/v5.7.0.0/tools/gen-postmortem-metadata.py | Python | apache-2.0 | 25,114 | 0.01537 | #!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. 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
# not... | s_shift',
'value': 'Map::Numbe | rOfOwnDescriptorsBits::kShift' },
{ 'name': 'off_fp_context',
'value': 'StandardFrameConstants::kContextOffset' },
{ 'name': 'off_fp_constant_pool',
'value': 'StandardFrameConstants::kConstantPoolOffset' },
{ 'name': 'off_fp_function',
'value': 'JavaScriptFrameConstants::kFunctionOf... |
Acehaidrey/incubator-airflow | airflow/providers/google/cloud/example_dags/example_automl_nl_text_sentiment.py | Python | apache-2.0 | 3,589 | 0.001115 | #
# 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... | k.output['dataset_id']
import_dataset_task = AutoMLImportDataOperator(
task_id="import_dataset_task",
dataset_id=dataset_id,
location=GCP_AUTOML_LOCATION,
input_config=IMPORT_INPUT_CONFIG,
)
MODEL["dataset_id"] = dataset_id
create_model = | AutoMLTrainModelOperator(task_id="create_model", model=MODEL, location=GCP_AUTOML_LOCATION)
model_id = create_model.output['model_id']
delete_model_task = AutoMLDeleteModelOperator(
task_id="delete_model_task",
model_id=model_id,
location=GCP_AUTOML_LOCATION,
project_id=GCP_PR... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/ams/_params.py | Python | mit | 51,064 | 0.004015 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | get_allowed_transcription_languages,
get_allowed_analysis_modes,
get_stretch_mode_types_list,
get_storage_authentication_allowed_... | ge_account_id,
datetime_format,
validate_correlation_data,
validate_token_claim,
validate_output_ass... |
RamaneekGill/CSC320-Winter-2014 | project 2/p2.py | Python | gpl-2.0 | 12,095 | 0.015048 | import os
os.chdir('C:/Users/Ramaneek/SkyDrive/Documents/University/Third Year/CSC320/project 2/')
###########################################################################
## Handout painting code.
###########################################################################
from PIL import Image
from pylab import *... | ctor from center to one end of th | e stroke.
delta = np.array([cos(theta), sin(theta)])
time.time()
time.clock()
k=0
#####################################################################################
gray()
#imRGB_mono = np.zeros((sizeIm[0], sizeIm[1]))
#imRGB_mono = imRGB[:,:,0] * 0.30 + imRGB[:,:,1] * 0.59 + imR... |
lincolnloop/salmon | setup.py | Python | bsd-3-clause | 801 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='salmon',
version='0.3.0-dev',
description="A simple metric collector with alerts.",
long_description=open('README.rst').read(),
author="Peter Baumgarter",
author_email='pete@lincolnloop.com',
url='https://github.... | .1',
'djangorestframework==2.3.9',
'South==0.8.3',
'logan==0.5.9.1',
'gunicorn==18.0',
| 'whisper==0.9.10',
'dj-static==0.0.5',
'pytz',
],
entry_points={
'console_scripts': [
'salmon = salmon.core.runner:main',
],
},
packages=find_packages(),
include_package_data=True,
zip_safe=False,
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.