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 |
|---|---|---|---|---|---|---|---|---|
aboudreault/dnds-debian | dsc/dsctl.py | Python | gpl-2.0 | 12,699 | 0.00378 | #!/usr/bin/env python
# Copyright (C) Nicolas J. Bouliane - 2012
# dsctl - Directory Service Control
import signal
import socket
import ssl
import pprint
import sys
from dnds import *
class Connection:
sock = None
ssl_sock = None
connected = False
loggedin = False
ClientId = 0
def signal_handle... | ('dsop')
recv_req = recv_dsop.getComponentByName('searchResponse')
recv_objs = recv_req.getComponentByName('objects')
for idx in range(len(recv_objs)):
recv_obj = recv_objs.getComponentByPosition(idx)
recv_node = recv_obj.getCompone | ntByName('node')
recv_uuid = recv_node.getComponentByName('uuid')
recv_provcode = recv_node.getComponentByName('provCode')
recv_desc = recv_node.getComponentByName('description')
recv_ipaddress = recv_node.getComponentByName('ipaddress')
print "node uuid: " + str(recv_uuid) + ' p... |
apagac/cfme_tests | cfme/tests/perf/workloads/test_memory_leak.py | Python | gpl-2.0 | 4,503 | 0.003109 | import time
import pytest
from cfme.markers.env_markers.provider import providers
from cfme.utils import conf
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.grafana import get_scenario_dashboard_urls
from cfme.utils.log import logger
from cfme.utils.providers import ProviderFilter
fro... | hreshold": "1.5 GB",
"refresh_worker_threshold": "10 GB",
"vm_analysis_collectors | _worker_threshold": "1.5 GB"
})
view.workers.save.click()
@pytest.mark.usefixtures('generate_version_files')
@pytest.mark.parametrize('scenario', get_memory_leak_scenarios())
def test_workload_memory_leak(request, scenario, appliance, provider):
"""Runs through provider based scenarios setting one worker ... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_warren_imperial_worker_s01.py | Python | mit | 458 | 0.045852 | #### 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):
result = Creature()
result.template = "object/mobile/shared_warren_imperial_worker_s01.iff"
result.attribute_template_id | = 9
result.stfName("npc_name","warr | en_imperial_worker")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
percyfal/luigi | test/cmdline_test.py | Python | apache-2.0 | 8,267 | 0.003266 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | def test_bin_luigi_help(self):
returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--module', 'cmdline_test', '--help'])
self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1)
self.assertFalse(stdout.find(b'--x') != -1)
| def test_bin_luigi_help_no_module(self):
returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--help'])
self.assertTrue(stdout.find(b'usage:') != -1)
def test_bin_luigi_no_parameters(self):
returncode, stdout, stderr = self._run_cmdline(['./bin/luigi'])
self.assertTrue(s... |
kiwiPhrases/EITChousing | EITCcalculations_ver2.py | Python | mit | 6,048 | 0.016534 | import pandas as pd
import numpy as np
import re
data_path = "C:/Users/SpiffyApple/Documents/USC/RaphaelBostic"
#################################################################
################### load tax data ###############################
#upload tax data
tx = pd.read_csv("/".join([data_path, "metro_TY13.... | )
def calc_haus_eitc(group, income):
details = group[group['Nominal Earnings'] == income]
if details.shape[0] > 0:
aid = fmr[details.r_type]-details.haus_share.iloc[0]
aid[aid<0] = 0
else:
aid = pd.DataFrame(np.array([np.nan]*fmr.shape[0]))
aid.index = fmr.index
... | ]]
aid.columns = ['aid']
return(aid)
aid_incomes = {}
for income in income_vect:
aid_per_income = groups.apply(calc_haus_eitc, income=income)
aid_incomes[income] = aid_per_income.unstack(level=0)
one_family_aid = pd.concat(aid_incomes)
##############################################... |
IanMayo/january | org.eclipse.january/src/org/eclipse/january/dataset/internal/template/markers.py | Python | epl-1.0 | 12,983 | 0.003851 | ###
# *******************************************************************************
# * Copyright (c) 2011, 2016 Diamond Light Source Ltd.
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribut... | or, "length of lists should be the same"
(self.sdtype, self.spclass, self.sprim | , self.sgetel,
self.sconv, self.sform, self.sdef) = source
(self.ddtype, self.dpclass, self.dprim, self.dgetel,
self.dconv, self.dform, self.ddef) = destination
self.dcast = "(" + self.dprim + ") "
self.Sprim = self.sprim.capitalize()
self.Dprim = self.dprim.capitalize()... |
akosyakov/intellij-community | python/testData/joinLines/ListComprehension-after.py | Python | apache-2.0 | 51 | 0.019608 | rec | ords = [select.query.deco | de(r) for r in records] |
vcatalano/py-authorize | tests/test_live_customer.py | Python | mit | 3,018 | 0.000331 | import random
from authorize import Customer, Transaction
from authorize import AuthorizeResponseError
from datetime import date
from nose.plugins.attrib import attr
from unittest import TestCase
FULL_CUSTOMER = {
'email': 'vincent@vincentcatalano.com',
'description': 'Cool web developer guy',
'customer... | on
Customer.delete(customer_id)
self.assertRaises(AuthorizeResponseError, Customer.delete, customer_id)
Customer.list()
def test_live_customer_from_transaction(self):
INVALID_TRANS_ID = '123'
self.assertRaises(AuthorizeResponseError, Customer.from_transaction, INVALID_TRA... | = CUSTOMER_WITH_CARD.copy()
transaction['amount'] = random.randrange(100, 100000) / 100.0
result = Transaction.auth(transaction)
trans_id = result.transaction_response.trans_id
# Create the customer from the above transaction
result = Customer.from_transaction(trans_id)
... |
nagyistoce/devide | modules/vtk_basic/vtkRuledSurfaceFilter.py | Python | bsd-3-clause | 497 | 0.002012 | # class generated by DeVIDE::createDeVIDEModuleFromVTKObject
from module_kits | .vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkRuledSurfaceFilter(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkRuledSurfaceFilter(), 'Processing.',
('vtkPolyData',), ('... | tputFunctions=None)
|
hall1467/wikidata_usage_tracking | python_analysis_scripts/revision_comment_word_extractor.py | Python | mit | 2,427 | 0.00412 | """
returns tsv of word frequencies in revision comments
Usage:
revision_comment_word_extractor (-h|--help)
revision_comment_word_extractor <input> <output>
[--debug]
[--verbose]
Options:
-h, --help This help message is printed
<... | le.write([entry[0], entry[1]])
sum_of_word_counts += entry[1]
if verbose and i % 10000 == 0 and i != 0:
sys.stderr.write("Words written: {0}\n".format(i))
sys.stderr.flush()
print("Total word count: {0}".format(sum_of_word_counts))
if verbose:
sys.stderr... | err.flush()
main()
|
asedunov/intellij-community | python/testData/formatter/blankLineBeforeFunction.py | Python | apache-2.0 | 42 | 0.02381 | class C:
| x = 1
def foo(self): pas | s |
marian42/pixelpi | modules/animation.py | Python | mit | 2,315 | 0.047084 | import os.path
import pygame.image
import time
import ConfigParser
from helpers import *
from modules import Module
class Animation(Module):
def __init__(self, screen, folder, interval = None, autoplay = True):
super(Animation, self).__init__(screen)
if folder[:-1] != '/':
folder = folder + '/'
self.fold... | def load_single(self):
self.frames = []
bmp = pygame.image.load(self.folder + '0.bmp')
framecount = bmp.get_height() / 16
pixel_array = pygame.PixelArray(bmp)
for index in range(framecount):
frame = [[pixel_array[x, y + 16 * index] for y in range(16)] for x in range(16)]
self.frames.append(frame)
... | if self.pos >= len(self.frames):
self.pos = 0
self.screen.pixel = self.frames[self.pos]
self.screen.update()
time.sleep(self.interval / 1000.0)
def on_start(self):
print('Starting ' + self.folder)
def play_once(self):
for frame in self.frames:
self.screen.pixel = frame
self.screen.update()
... |
hickeroar/scentamint | scentamint/__init__.py | Python | mit | 1,087 | 0 | """
The MIT License (MIT)
Copyright (c) 2015 Ryan Vennell
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,... | ,
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, WH | ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
|
HenryHu/pybbs | xmppauth.py | Python | bsd-2-clause | 2,010 | 0.002985 | from UserManager import UserManager
im | port Session
from Log import Log
import sasl
class XMPPAuth(sasl.auth.Authenticator):
"""To authenticate XMPP users.
Plan to support 2 methods:
PLAIN: just username & password
X-BBS-OAUTH: use OAuth token
"""
de | f __init__(self, service_type, host, service_name):
self._service_type = service_type
self._host = host
self._service_name = service_name
self._username = None
def service_type(self):
return self._service_type
def host(self):
return self._host
def service_n... |
liuluheng/codereading | learn-cmus/scmus/.ycm_extra_conf.py | Python | mit | 5,982 | 0.025577 | # This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either... | AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# com... | IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-DHAVE_CONFIG',
'-DREALTIME_SCHEDULING',
'-DVERSION="0.1"',
'-D_REENTRANT'
'-Wall',
'-Wextra',
#'-Werror',
#'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
#'-stdlib=libc++',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won'... |
reza-arjmandi/rpi-course | session3/Interrupt.py | Python | mit | 560 | 0.008929 | ######################################################################
# Interrupt.py
#
# This program enable interrupt on gpio pin 18 for read switch
# button
############################################################### | #######
import RPi.GPIO as GPIO
import time
def myCallbac | k(channel):
print("You pressed button")
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(18, GPIO.FALLING, callback=myCallback, bouncetime=200)
i = 0
while(True):
i = i + 1
print(i)
time.sleep(0.2)
|
henry0312/LightGBM | examples/python-guide/plot_example.py | Python | mit | 2,004 | 0.001996 | # coding: utf-8
from pathlib import Path
import pandas as pd
import lightgbm as lgb
if lgb.compat.MATPLOTLIB_INSTALLED:
import matplotlib.pyplot as plt
else:
raise ImportError('You need to install matplotlib and restart your session for plot_example.py.')
print('Loading data...')
# load or create your datas... | , reference=lgb_train)
# specify your configurations as a dict
params = {
'num_leaves': 5,
'metric': ('l1', 'l2'),
'verbose': 0
}
evals_result = {} # to record eval results for plotting
print('Starting training...')
# train
gbm = lgb.train(
params,
lgb_train,
num_boost_round=100,
valid_s... | gorical_feature=[21],
callbacks=[
lgb.log_evaluation(10),
lgb.record_evaluation(evals_result)
]
)
print('Plotting metrics recorded during training...')
ax = lgb.plot_metric(evals_result, metric='l1')
plt.show()
print('Plotting feature importances...')
ax = lgb.plot_importance(gbm, max_num_feat... |
vinaypost/multiuploader | multiuploader/utils.py | Python | mit | 2,052 | 0.002437 | from __future__ import unicode_literals
import logging
import mimetypes
import os
from wsgiref.util import FileWrapper
from django.conf import settings
from django.http import HttpResponse
try:
from urllib import quote
except ImportError as ie:
from urllib.parse import quote
log = logging
# Getting file... | pe'] = type
self['Content-Length'] = os.path.getsize(filepath)
if encoding is not None:
self['Content-Encoding'] = encoding
# To inspect details | for the below code, see http://greenbytes.de/tech/tc2231/
if u'WebKit' in request.META['HTTP_USER_AGENT']:
# Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
filename_header = 'filename={}'.format(filename.encode('utf-8'))
elif u'MSIE' in request.META['HTTP_USER_... |
cngo-github/nupic | tests/unit/nupic/algorithms/anomaly_test.py | Python | agpl-3.0 | 5,644 | 0.007619 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditio... | 6]), array([1, 4, 6]),
array([10, 11, 6]), array([10, 11, 12]), array([10, 11, 12]),
| array([10, 11, 12]), array([1, 2, 6]), array([1, 2, 6]))
anomalyExpected = (0.0, 0.0, 1.0/9.0, 3.0/9.0, 2.0/3.0, 8.0/9.0, 1.0,
2.0/3.0, 1.0/3.0)
for act, pred, expected in zip(actual, predicted, anomalyExpected):
score = anomalyComputer.compute(act, pred)
self.ass... |
mrniranjan/python-scripts | reboot/check1.py | Python | gpl-2.0 | 166 | 0.018072 | from sys | import argv
script, file_name = argv
def lineprint(f):
print f.readline()
target = open(file_name)
lineprint(target)
lineprint( | target)
lineprint(target)
|
fbradyirl/home-assistant | homeassistant/components/mailgun/config_flow.py | Python | apache-2.0 | 415 | 0 | """Config flow for Mailgun | ."""
from homeassistant.helpers import config_entry | _flow
from .const import DOMAIN
config_entry_flow.register_webhook_flow(
DOMAIN,
"Mailgun Webhook",
{
"mailgun_url": "https://documentation.mailgun.com/en/latest/user_manual.html#webhooks", # noqa: E501 pylint: disable=line-too-long
"docs_url": "https://www.home-assistant.io/components/ma... |
greggian/TapdIn | django/templatetags/i18n.py | Python | apache-2.0 | 9,355 | 0.003955 | import re
from django.template import Node, Variable, VariableNode, _render_value_in_context
from django.template import TemplateSyntaxError, TokenParser, Library
from django.template import TOKEN_TEXT, TOKEN_VAR
from django.utils import translation
from django.utils.encoding import force_unicode
register = L... | f self.more():
if self.tag() == 'noop':
noop = True
else:
raise TemplateSyntaxError, "only option for 'trans' is 'noop'"
else:
noop = False
return (value, noop)
value, noop = TranslateParser(tok | en.contents).top()
return TranslateNode(value, noop)
def do_block_translate(parser, token):
"""
This will translate a block of text with parameters.
Usage::
{% blocktrans with foo|filter as bar and baz|filter as boo %}
This is {{ bar }} and {{ boo }}.
{% endblocktra... |
tonimichel/webkitpony | docs/conf.py | Python | mit | 8,098 | 0.007162 | # -*- coding: utf-8 -*-
#
# webkitpony documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 23 14:05:32 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|... | = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: et... |
Azure/azure-documentdb-python | test/query_tests.py | Python | mit | 9,355 | 0.004383 | import unittest
import uuid
import pytest
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.retry_utility as retry_utility
import test.test_config as test_config
@pytest.mark.usefixtures("teardown")
class QueryTest(unittest.TestCase):
"""Test to ensure escaping of non-ascii characters from par... | esponse_headers[METRICS_HEADER_NAME]
# Validate header is well-formed: "key1=value1;key2=value2;etc"
metrics = metrics_header.split(';')
self.assertTrue(len(metrics) > 1)
self.assertTrue(all(['=' in x for x in metrics]))
def test_max_item_count_honored_in_order_by_query(self):
... | t_definition = {'pk': 'pk', 'id': 'myId' + str(uuid.uuid4())}
docs.append(self.client.CreateItem(created_collection['_self'], document_definition))
query = 'SELECT * from c ORDER BY c._ts'
query_options = {'enableCrossPartitionQuery': True,
'maxItemCount': 1}
... |
mvaled/sentry | tests/snuba/search/test_backend.py | Python | bsd-3-clause | 53,904 | 0.002542 | from __future__ import absolute_import
import mock
import pytz
import pytest
from datetime import datetime, timedelta
from django.conf import settings
from django.utils import timezone
from hashlib import md5
from sentry import options
from sentry.api.issue_search import convert_query_values, IssueSearchVisitor, pars... | "environment": "staging",
"tags": {"server": "example.com", "url": "http://example.com"},
},
project_id=self.project.id,
)
self.group2 = Group.objects.get(id=self.event2.group.id)
assert self.group2.id == self.event2.group.id
| assert self.group2.first_seen == self.group2.last_seen == self.event2.datetime
self.group2.status = GroupStatus.RESOLVED
self.group2.times_seen = 10
self.group2.save()
GroupBookmark.objects.create(user=self.user, group=self.group2, project=self.group2.project)
GroupAssign... |
kipe/enocean | enocean/communicators/serialcommunicator.py | Python | mit | 1,554 | 0.001287 | # -*- encoding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
import logging
import serial
import time
from enocean.communicators.communicator import Communicator
class SerialCommunicator(Communicator):
''' Serial port communicator class for EnOcean radio '''
lo... | packet = self._get_from_send_queue()
if not packet:
break
try:
self.__ser.write(bytearray(packet.build()))
except serial.SerialException:
self.stop( | )
# Read chars from serial port as hex numbers
try:
self._buffer.extend(bytearray(self.__ser.read(16)))
except serial.SerialException:
self.logger.error('Serial port exception! (device disconnected or multiple access on port?)')
self.s... |
rebost/django | django/conf/locale/pl/formats.py | Python | bsd-3-clause | 1,327 | 0.001508 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j E Y'
TIME_FORMAT = 'H:i:s'
DATE... | n strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = (
'%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06'
'%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25'
# '%d. | %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006'
)
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
DATETIME_INPUT_FORMATS = (
'%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59'
'%d.%m.%Y %H:%M', # '25.10.2006 14:30'
'%d.%m.%Y', # '25.10.2006'
'... |
akvo/akvo-rsr | akvo/thumbnail_backend.py | Python | agpl-3.0 | 1,113 | 0.003594 | # -*- coding: utf-8 -*-
# Akvo RSR is | covered by the GNU Affero General Public License.
# See more details in the license.txt file located a | t the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from sorl.thumbnail.base import ThumbnailBackend, EXTENSIONS
from sorl.thumbnail.conf import settings
from sorl.thumbnail.helpers import tokey, serialize
class CustomThumbnailBa... |
ingadhoc/odoo-legal | legal_portal/__init__.py | Python | agpl-3.0 | 274 | 0 | ################## | ############################################################
# For copyright and license notices, see __ma | nifest__.py file in module root
# directory
##############################################################################
from . import controllers
|
RENCI/xDCIShare | hs_core/tests/api/rest/test_resource_flags.py | Python | bsd-3-clause | 3,544 | 0 | import os
import tempfile
from rest_framework import status
from hs_core.hydroshare import resource
from .base import HSRESTTestCase
class TestPublicResourceFlagsEndpoint(HSRESTTestCase):
def setUp(self):
super(TestPublicResourceFlagsEndpoint, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
... | 'json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_not_shareable( | self):
flag_url = "/hsapi/resource/%s/flag/" % self.pid
response = self.client.post(flag_url, {
"t": "make_not_shareable"
}, format='json')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
def test_set_resource_flag_make_shareable(self):
flag_url ... |
brion/gimp | plug-ins/pygimp/plug-ins/palette-sort.py | Python | gpl-3.0 | 13,495 | 0.003409 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 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 program is dist... | LICE:
def find_index(color, startindex=0):
for i in range(startindex, num_colors):
c = pdb.gimp_palette_entry_get_color (palette, i)
if c == color:
return i
return None
def hexcolor( | c):
return "#%02x%02x%02x" % tuple(c[:-1])
fg = pdb.gimp_context_get_foreground()
bg = pdb.gimp_context_get_background()
start = find_index(fg)
end = find_index(bg)
if start is None:
raise ValueError("Couldn't find foreground color %r in palette" % list(fg... |
Yeasayer/YoutubeVideoPage | ytdownload/apps.py | Python | mit | 134 | 0 | from __future__ impo | rt unicode_literals
from django.apps import AppConfig
class DownloadzConfig(AppConfig):
name = 'do | wnloadz'
|
dnephin/compose | compose/const.py | Python | apache-2.0 | 2,457 | 0.000407 | from __future__ import absolute_import
from __future__ import unicode_literals
import sys
from .version import ComposeVersion
DEFAULT_TIMEOUT = 10
HTTP_TIMEOUT = 60
IMAGE_EVENTS = ['delete', 'import', 'load', 'pull', 'push', 'save', 'tag', 'untag']
IS_WINDOWS_PLATFORM = (sys.platform == "win32")
LABEL_CONTAINER_NUMB... | 3.6')
COMPOSEFILE_V3_7 = ComposeVersion('3.7')
API_VERSIONS = {
COMPOSEFILE_V1: '1.21',
COMPOSEFILE_V2_0: '1.22',
COMPOSEFILE_V2_1: '1.24',
COMPOSEFILE_V2_2: '1.25',
COMPOSEFILE_V2_3: '1.30',
COMPOSEFILE_V2_4: '1.35',
COMPOSEFILE_V3_0: '1.25',
COMPOSEFILE_V3_1: '1.25',
COMPOSEFILE_V... | _3: '1.30',
COMPOSEFILE_V3_4: '1.30',
COMPOSEFILE_V3_5: '1.30',
COMPOSEFILE_V3_6: '1.36',
COMPOSEFILE_V3_7: '1.38',
}
API_VERSION_TO_ENGINE_VERSION = {
API_VERSIONS[COMPOSEFILE_V1]: '1.9.0',
API_VERSIONS[COMPOSEFILE_V2_0]: '1.10.0',
API_VERSIONS[COMPOSEFILE_V2_1]: '1.12.0',
API_VERSIONS... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/mlu/c_comm_init_op_mlu.py | Python | apache-2.0 | 2,475 | 0.000404 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | =True,
type=fluid.core.VarDesc.VarType.RAW)
block.append_op(
type='c_gen_cncl_id',
inputs={},
outputs={'Out': cncl_id_var},
attrs={
'rank': | self.rank,
'endpoint': self.current_endpoint,
'other_endpoints': self.other_endpoints
})
block.append_op(
type='c_comm_init',
inputs={'X': cncl_id_var},
outputs={},
attrs={
'nranks': self.nranks,
... |
tensorflow/datasets | tensorflow_datasets/image/pass_dataset/__init__.py | Python | apache-2.0 | 702 | 0 | # coding | =utf-8
# Copyright 2022 The TensorFlow Datasets 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 l... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""pass_dataset."""
from tensorflow_datasets.image.pass_dataset.pass_dataset import PASS
|
op/gpsupd | gpsupd/gpsd.py | Python | bsd-3-clause | 1,207 | 0.000829 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Örjan Persson
import gps
import time
import gpsupd | .connector as connector
class GpsdConnector(connector.GpsConnector):
def __init__(self, address, verbose=None):
if verbose is None:
verbose = False
self.__verbose = verbose
self.__address = address
def connect(self):
conn = gps.gps(self.__address, verbose=self.__ve... | if conn.waiting():
conn.poll()
else:
time.sleep(0.1)
continue
longitude = conn.fix.longitude
latitude = conn.fix.latitude
altitude = None
speed = None
... |
honeybadger-io/honeybadger-python | honeybadger/tests/test_middleware.py | Python | mit | 674 | 0 | import warnings
from collections import OrderedDict
from honeybadger.plugins import default_plugin_manager
from .contrib.test_django import Django | MiddlewareTestCase
from honeybadger.middleware import DjangoHoneybadgerMiddleware
__all__ = ['MiddlewareTestCase']
class MiddlewareTestCase(DjangoMiddlewareTestCase):
def test_middleware_import_warning(self):
default_plugin_manager._registered = OrderedDict()
with warnings.catch_warnings(record=T... | category, FutureWarning)
assert "moved" in str(w[-1].message)
|
bzamecnik/sms-tools | smst/utils/math.py | Python | agpl-3.0 | 692 | 0.00578 | import numpy as np
def is_power_of_two(num):
"""
Checks if num is power of two
"""
return ((num & (num - 1)) == 0) and num > 0
def rmse(x, y):
"""
Root mean square error.
: | param x: numpy array
:param y: numpy array
:return: RMSE(x,y)
"""
return np.sqrt(((x - y) ** 2).mean())
def to_db_magnitudes(amplitudes):
abs_amplitudes = abs(amplitudes)
# ensure non-zero values for logarithm
eps = np.finfo(float).eps
abs_amplitudes[abs_amplitudes < eps] = eps
# m... | itudes_db):
return 10 ** (magnitudes_db * 0.05)
|
youtube/cobalt | build/android/incremental_install/write_installer_json.py | Python | bsd-3-clause | 2,202 | 0.00772 | #!/usr/bin/env python
# Copyright 2017 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.
"""Writes a .json file with the per-apk details for an incremental install."""
import argparse
import json
import os
import sys
sys.... | default=[],
help='A glob matching the apk splits. '
'Can be specified multiple times.')
parser.add_argument(
'--native-libs',
action='append',
help='GN-list of paths to native libraries relative to '
'output directory. Can be repea... | action='store_true',
default=False,
help='Print a warning about proguard being disabled')
options = parser.parse_args(args)
options.dex_files = build_utils.ParseGnList(options.dex_files)
options.native_libs = build_utils.ParseGnList(options.native_libs)
... |
yw374cornell/e-mission-server | emission/core/wrapper/smoothresults.py | Python | bsd-3-clause | 660 | 0.024242 | import logging
import datetime as pydt
import emission.core.wrapper.wrapperbase as ecwb
class Smoothresults(ecwb.WrapperBase):
props = {"section": ecwb.WrapperBase.Access.WORM, # the section for which these points should be deleted
"deleted_points": ecwb.WrapperBase.Access.WORM, # list of IDs of deleted p... | tlier_algo": ecwb.WrapperBase.Access.WORM, # the name of the algorithm used to generate outliers
"filtering_algo": ecwb.WrapperBase.Access.WORM} # the name of the algorithm used | to filter the points
enums = {}
geojson = []
nullable = []
local_dates = []
def _populateDependencies(self):
pass
|
auntieNeo/asterisk-testsuite | tests/manager/presence_state_changed/ami_presence_state.py | Python | gpl-2.0 | 2,320 | 0 | #!/usr/bin/env python
'''
Copyright (C) 2014, Digium, Inc.
Mark Michelson <mmichelson@digium.com>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''
import logging
from test | _case import TestCase
LOGGER = logging.getLogger(__name__)
STATES = [
{'status': 'unavailable', 'subtype': 'scrambled', 'message': 'breakfast'},
| {'status': 'available', 'subtype': 'fried', 'message': 'brunch'},
{'status': 'away', 'subtype': 'poached', 'message': 'lunch'},
{'status': 'xa', 'subtype': 'meringue', 'message': 'snack'},
{'status': 'chat', 'subtype': 'custard', 'message': 'dinner'},
{'status': 'dnd', 'subtype': 'souffle', 'message'... |
delcypher/klee-runner | kleeanalysis/rank.py | Python | mit | 43,340 | 0.003899 | # vim: set sw=4 ts=4 softtabstop=4 expandtab:
import copy
import logging
import os
import math
import pprint
import statistics
from collections import namedtuple
from . import kleedir
from .kleedir import test
from .kleedir import KleeDir, KleeDirProxy
from . import analyse
from enum import Enum
_logger = logging.get... | os) > 1
if coverage_replay_infos:
assert isinstance(coverage_replay_infos, list)
assert len(result_infos) == len(coverage_replay_infos)
if bug_replay_infos:
assert isinstance(bug_replay_infos | , list)
assert len(result_infos) == len(bug_replay_infos)
reversed_rank = []
index_to_klee_dir_map = []
llvm_bc_program_path = None
llvm_bc_program_path_try = None
native_program_name = None
index_to_is_merged_map = []
index_to_number_of_repeat_runs_map = []
for index, r in ... |
keeperofdakeys/ircbots | regexbot.py | Python | agpl-3.0 | 15,901 | 0.005849 | #!/usr/bin/env python
"""
regexbot: IRC-based regular expression evaluation tool.
Copyright 2010 - 2012 Michael Farrell <http://micolous.id.au>
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 Software Foundation, ... | sg[1] in valid_separators:
separator = msg[1]
else:
str_replace = False
str_translate = False
if (str_replace or str_translate) and msg[1] == separator:
for item in ignore_list:
if item.se | arch(event.origin) != None:
# ignore list item hit
|
JohnDevitt/appengine-django-skeleton-master | mysite/urls.py | Python | bsd-3-clause | 1,353 | 0 | # Copyright 2015 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... | ific language governing permissions and
# limitations under the License.
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2.... | : url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(... |
roadmapper/ansible | test/units/modules/source_control/gitlab/test_gitlab_runner.py | Python | gpl-3.0 | 3,198 | 0.002502 | # -*- coding: utf-8 -*-
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import
import pytest
from ansible.modules.source_control.gitlab.gitlab_runner import GitLabRunner
def _... | _requirement():
from gitlab.v4.objects import Runner
except ImportError:
pytestmark.append(pytest.mark. | skip("Could not load gitlab module required for testing"))
# Need to set these to something so that we don't fail when parsing
GitlabModuleTestCase = object
resp_find_runners_list = _dummy
resp_get_runner = _dummy
resp_create_runner = _dummy
resp_delete_runner = _dummy
# Unit tests requirements... |
ssarangi/numba | numba/hsa/api.py | Python | bsd-2-clause | 1,293 | 0 | from __future__ import absolute_import, print_function
import numpy as np
from .stubs import (
get_global_id,
get_global_size,
get_local_id,
get_local_size,
get_group_id,
get_work_dim,
get_num_groups,
barrier,
mem_fence,
shared,
)
from .decorators import (
jit,
)
from .hs... | self, args):
self.args = args
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
deregister(*self.args)
def register(*args):
"""Register data into the HSA system
Returns a contextmanager for use in with-context for auto deregistration.
Use in conte... | types.data, data.nbytes)
else:
raise TypeError(type(data))
return _AutoDeregister(args)
def deregister(*args):
"""Deregister data form the HSA system
"""
for data in args:
if isinstance(data, np.ndarray):
_hsadrv.hsa_memory_deregister(data.ctypes.data, data.nbyt... |
egenerat/REST-API | uds/server.py | Python | mit | 539 | 0 | import socket
import os
server_address = '/tmp/uds_socket' |
# Unlink the socket if it already exists
try:
os.unlink(server_address)
except OSError:
if os.path.exists(server_address):
raise
# Create a socket
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
sock.bind(server... | print("Received a connection")
clientSocket.close()
|
frappe/frappe | frappe/utils/dateutils.py | Python | mit | 4,402 | 0.029986 | # Copyright (c) 2015, Frappe Technologi | es Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import frappe.defaults
import datetime
from frappe.utils import get_datetime, add_to_date, getdate
from frappe.utils.data import get_first_day, get_first_day_of_week, get_quarter_star | t, get_year_start,\
get_last_day, get_last_day_of_week, get_quarter_ending, get_year_ending
# global values -- used for caching
dateformats = {
'yyyy-mm-dd': '%Y-%m-%d',
'mm/dd/yyyy': '%m/%d/%Y',
'mm-dd-yyyy': '%m-%d-%Y',
"mm/dd/yy": "%m/%d/%y",
'dd-mmm-yyyy': '%d-%b-%Y', # numbers app format
'dd/mm/yyyy': '%d/... |
RUBi-ZA/MD-TASK | lib/strategies/normalization.py | Python | gpl-3.0 | 1,170 | 0.004274 | class base(object):
def __init__(self, matrix_type | ):
self.matrix_type = matrix_type
class standard(base):
def normalize(self, difference, reference):
return difference / reference
def get_label(self):
return "$\Delta$ %s/%s" % (self.matrix_type, self.matrix_type)
def get_prefix(self):
return "standard"
class no | nzero(base):
def normalize(self, difference, reference):
nonzero = reference > 0
return difference[nonzero] / reference[nonzero]
def get_label(self):
return "$\Delta$ %s/%s (%s>0)" % (self.matrix_type, self.matrix_type, self.matrix_type)
def get_prefix(self):
return "nonzer... |
hannesrauhe/lunchinator-gadgets | rocket_launcher/pyrocket_backend.py | Python | gpl-3.0 | 8,133 | 0.007623 | #!/usr/bin/python
# |
import usb
from time import sleep
class R | ocketManager:
vendor_product_ids = [(0x1941, 0x8021), (0x0a81, 0x0701), (0x0a81, 0xff01), (0x1130, 0x0202), (0x2123,0x1010)]
launcher_types = ["Original", "Webcam", "Wireless", "Striker II", "OIC Webcam"]
housing_colors = ["green", "blue", "silver", "black", "gray"]
def __init__(self):
self.lau... |
renstrom/passbook_flask_example | tests.py | Python | mit | 1,287 | 0.001554 | # -*- coding: utf-8 -*-
import os
import unittest
import tempfile
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from app import app, db, Pass, Registration
class PassbookTestCase(unittest.TestCase):
def setUp(self):
temp = tempfile.mkstemp()
self.temp = temp
... | 'bar': str(datetime.utcnow()),
'baz': 'Lorem ipsum dolar sit amet'
}
p = Pass('com.company.pass.example', 'ABC123', data)
db.session.add(p)
db.session.commit() |
assert Pass.query.get(1)
r = Registration('123456789', '00000000 00000000 00000000 00000000 \
00000000 00000000 00000000 00000000', p)
db.session.add(r)
db.session.commit()
assert Registration.query.get(1)
if __name__ == '__main__':
unittest.main... |
ayust/kitnirc | kitnirc/contrib/admintools.py | Python | mit | 3,850 | 0.000519 | import logging
from kitnirc.client import Channel
from kitnirc.modular import Module
from kitnirc.user import User
_log = logging.getLogger(__name__)
def is_admin(controller, client, actor):
"""Used to determine whether someone issuing a command is an admin.
By default, checks to see if there's a line of ... | KitnIRC module which provides admin functionality.
Customization of what an "admin" is can be done by overriding the
is_admin global function in this file.
"""
@Module.handle("PRIVMSG")
| def privmsg(self, client, actor, recipient, message):
if isinstance(recipient, Channel):
# Only pay attention if addressed directly in channels
if not message.startswith("%s:" % client.user.nick):
return
message = message.split(":", 1)[1]
message ... |
sdague/home-assistant | homeassistant/components/mqtt/vacuum/schema_legacy.py | Python | apache-2.0 | 19,424 | 0.000927 | """Support for Legacy MQTT vacuum."""
import json
import logging
import voluptuous as vol
from homeassistant.components import mqtt
from homeassistant.components.mqtt import (
MqttAttributes,
MqttAvailability,
MqttDiscoveryUpdate,
MqttEntityDeviceInfo,
subscription,
)
from homeassistant.components... | = config[CONF_NAME]
supported_feature_strings = config[CONF_SUPPORTED_FEATURES]
self._supported_features = strings_to_services(
supported_feature_strings, STRING_TO_SERVICE
)
self._fan_speed_list = config[CONF_FAN_SPEED_LIST]
self._qos = config[mqtt.CONF_QOS]
... | qtt.CONF_RETAIN]
self._command_topic = config.get(mqtt.CONF_COMMAND_TOPIC)
self._set_fan_speed_topic = config.get(CONF_SET_FAN_SPEED_TOPIC)
self._send_command_topic = config.get(CONF_SEND_COMMAND_TOPIC)
self._payloads = {
key: config.get(key)
for key in (
... |
OCA/l10n-italy | l10n_it_invoices_data_communication/wizard/export_file.py | Python | agpl-3.0 | 1,682 | 0.000595 | import base64
from odoo import _, exceptions, fields, models
class ComunicazioneDatiIvaExportFile(models.TransientModel):
_name = "comunicazione.dati.iva.export.file"
_description = "Export XML of invoices data communication"
file_export = fields.Binary("File", readonly=True)
filename = fields.Char(... | ata_obj.get_object_reference(
"l10n_it_invoices_data_communication",
"wizard_dati_iva_export_file_exit",
)
view_id = view_rec and vie | w_rec[1] or False
return {
"view_id": [view_id],
"view_mode": "form",
"res_model": "comunicazione.dati.iva.export.file",
"res_id": wizard.id,
"type": "ir.actions.act_window",
"target": "new",
}
|
wbyne/QGIS | tests/src/python/test_provider_ogr_gpkg.py | Python | gpl-2.0 | 6,014 | 0.002162 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for the OGR/GPKG provider.
.. note:: 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.... | h, 'testSingleToMultiPolygonPromotion.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon)
ds = None
vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'test', 'ogr')
f = QgsFeature()
f.setGeometry... | 0 1,1 1,0 0))'))
vl.dataProvider().addFeatures([f])
got = [f for f in vl.getFeatures()][0]
got_geom = got.geometry()
reference = QgsGeometry.fromWkt('MultiPolygon (((0 0, 0 1, 1 1, 0 0)))')
# The geometries must be binarily identical
self.assertEqual(got_geom.asWkb(), ref... |
BL-Labs/annotator_demonstrator | djdan/wsgi.py | Python | mit | 1,132 | 0.000883 | """
WSGI config for djdan project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | t later delegates to the Django one. For example, you could introduce WSGI
middleware here, | or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djdan.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting p... |
bwasti/caffe2 | caffe2/python/layers/split.py | Python | apache-2.0 | 1,613 | 0.00062 | ## @package split
# Module caffe2.python.layers.split
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import (
ModelLayer,
)
class Split(Mod... | \
format(input_record)
input_shape = input_record.field_type().shape
assert len(input_shape) >= axis
assert input_shape[axis] % num_splits == 0
output_shape = list(input_shape)
output_shape[axis] = int(output_shape[axis] / num_splits)
data_type = input_reco... | ape),
model.net.NextScopedBlob(name + '_output_{}'.format(i)),
)
for i in range(num_splits)
]
self.output_schema = schema.Tuple(*output_scalars)
def add_ops(self, net):
net.Split(
self.input_record.field_blobs(),
self.output_sc... |
akintolga/superdesk-aap | server/aap/macros/currency_cny_to_aud.py | Python | agpl-3.0 | 1,220 | 0.002463 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full c | opyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
from . import aap_currency_base as currency_base
from decimal import Decimal
CNY_T | O_AUD = Decimal('0.21') # backup
def get_rate():
"""Get CNY to AUD rate."""
try:
return currency_base.get_rate('CNY', 'AUD')
except:
return CNY_TO_AUD
def yuan_to_aud(item, **kwargs):
"""Convert CNY to AUD."""
rate = kwargs.get('rate') or get_rate()
if os.environ.get('BEHAV... |
hybrid-storage-dev/cinder-fs-111t-hybrid-cherry | volume/drivers/huawei/rest_common.py | Python | apache-2.0 | 81,175 | 0.000382 | # Copyright (c) 2013 - 2014 Huawei Technologies Co., Ltd.
# 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.... | ception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.openstack.common import log as logging
from cinder.openstack.common import lo | opingcall
from cinder import utils
from cinder.volume import qos_specs
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
STATUS_HEALTH = '1'
STATUS_RUNNING = '10'
DEFAULT_WAIT_TIMEOUT = 3600 * 24 * 30
DEFAULT_WAIT_INTERVAL = 5
ERROR_CONNECT_TO_SERVER = -403
ERROR_UNAUTHORIZED_TO_SERVER = -401
... |
dimagi/commcare-hq | corehq/apps/sms/forms.py | Python | bsd-3-clause | 49,749 | 0.00205 | import copy
import json
import re
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms.fields import (
BooleanField,
CharField,
ChoiceField,
IntegerField,
)
from django.forms.forms import Form
from django.urls import reverse
from... | et_sms_b | ackend_classes,
is_superuser_or_contractor,
validate_phone_number,
)
from corehq.apps.users.models import CommCareUser, CouchUser
ENABLED = "ENABLED"
DISABLED = "DISABLED"
ENABLED_DISABLED_CHOICES = (
(DISABLED, ugettext_noop("Disabled")),
(ENABLED, ugettext_noop("Enabled")),
)
DEFAULT = "DEFAULT"
CU... |
SebNickel/deep_learning | datasets.py | Python | mit | 1,241 | 0 | import numpy
from numpy import ndarray
import theano
from theano import tensor as T
import pickle
class SharedDataset:
def __init__(self,
vectors: ndarray,
labels: ndarray):
self.x = theano.shared(
value=numpy.asarray(
vectors,
... | atX
),
name='x',
borrow=True
)
# Intermittent conversion to float for GPU-compatibility.
y_as_floats = theano.shared(
value=numpy.asarray(
labels,
dtype=theano.config.floatX
),
name='y',
... | ue
)
self.y = T.cast(y_as_floats, 'int32')
@property
def vectors(self):
return self.x.get_value(borrow=True)
@property
def labels(self):
return self.y.get_value(borrow=True)
@property
def size(self):
return self.vectors.shape[0]
def save(dataset: ... |
sr-lab/verified-pam-cracklib | evaluation/csv.py | Python | bsd-3-clause | 1,804 | 0.007761 | import json
def import_json(path):
"""Decodes and returns the JSON object in the file at the specified path.
Args:
path (str): The path of the file to read.
"""
with open(path) as data_file:
return json.load(data_file)
# Import all files.
results_v = import_json('resul... | , MCR (fixed) T, MCR (HAPSL), MCR (HAPSL) T, Basic16, Basic16 T\n"
for i in range(0, 100000):
results += results_v[i]['password']
results += | ", "
results += str(results_nodict[i]['valid'])
results += ", "
results += str(results_nodict[i]['time'])
results += ", "
results += str(results_v[i]['valid'])
results += ", "
results += str(results_v[i]['time'])
results += ", "
results += str(results_nodict_mcr[i]['valid'])
resu... |
ericfourrier/auto-clean | autoc/utils/corrplot.py | Python | mit | 590 | 0.001695 | import seaborn as sns
import matplotlib.pyplot as plt
def plot_corrmatrix(df, square=True, linewidths=0.1, annot=True,
size=None, figsize=(12, 9), *args, **kwargs):
"""
Plot correlation matrix of the dataset
see doc at https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.he... | ize)
sns.heatmap(df.corr(), vmax=1, square=square, linewidths=li | newidths,
annot=annot, annot_kws={"size": size}, *args, **kwargs)
|
danydoerr/large_syn_workflow | remove_masked_regions.py | Python | mit | 1,172 | 0.006826 | #!/usr/bin/env python
from sys import stdout, stderr, exit
from optparse import OptionParser
from Bio import SeqIO, Seq, Alphabet
from cStringIO import StringIO
MINLEN_DEFAULT=10
if __name__ == '__main__':
usage = 'usage: %prog [options] <FASTA FILE>'
parser = OptionParser(usage=usage)
parser.add_option... | ')
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_help()
exit(1)
for rec in SeqIO.parse(args | [0], 'fasta'):
p = 0
c_count = 0
new_seq = StringIO()
for c in rec.seq:
if c in {'X', 'x', 'N', 'n'}:
c_count += 1
elif c_count >= options.minLength:
p -= c_count
new_seq.seek(p)
c_count = 0
... |
Lcaracol/ideasbox.lan | ideasbox/monitoring/migrations/0004_auto_20150330_0922.py | Python | mit | 403 | 0 | # -*- coding: utf-8 -*- |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('monitoring', '0003_auto_20150324_1806'),
]
operations = [
migrations.AlterUniqueTogether(
name='inventoryspecimen',
unique_... | ntory', 'specimen')]),
),
]
|
icometrix/dicom2nifti | dicom2nifti/image_reorientation.py | Python | mit | 6,865 | 0.004516 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 16:10:56 2013
@author: vterzopoulos, abrys
"""
# To ignore numpy errors:
# pylint: disable=E1101
import nibabel
import numpy
from dicom2nifti.image_volume import load, SliceType, ImageVolume
def reorient_image(input_image, output_image):
"""
Change the o... | imageVolume module to find which coordinate corresponds to each plane
# and get the image data in RAS orientation
# print 'Reading nifti'
if isinstance(input_image, nibabel.Nifti1Image):
image = ImageVolume(input_image)
else:
image = load(input_image)
# 4d have a different conversi... | w_image = _reorient_4d(image)
elif image.nifti_data.squeeze().ndim == 3 or image.nifti_data.ndim == 3 or image.nifti_data.squeeze().ndim == 2:
new_image = _reorient_3d(image)
else:
raise Exception('Only 3d and 4d images are supported')
# print 'Recreating affine'
affine = image.nifti.af... |
janmbuys/DeepDeepParser | rnn/seq2seq_decoders.py | Python | apache-2.0 | 50,214 | 0.010276 | # Copyright 2015 Google Inc. All Rights Reserved.
# Modifications copyright 2017 Jan Buys.
#
# 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
#... | .
Args:
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
initial_state: 2D Tensor with shape [batch_size x cell.state_size].
cell: rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be applied to the i-th output
| in order to generate the i+1-st input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol). This can be used for decoding,
but also for training to emulate http://arxiv.org/abs/1506.03099.
Signature -- loop_function(prev, i) = next
* prev is a 2D Tensor of shape [ba... |
anhstudios/swganh | data/scripts/templates/object/tangible/gambling/table/shared_table_base.py | Python | mit | 450 | 0.046667 | #### 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):
result = Tangible()
result.template = "object/tangible/gambling/table/shared_table_base.iff"
result.attribute_template_id = -1
result.stfName(" | item_n","gambling_table")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
JulienPobot/LeCubeMedia | src/clients/cldevice.py | Python | apache-2.0 | 1,869 | 0.010166 | # -*- coding: utf-8 -*-
import logging
import thread
from optparse import OptionParser
import sleekxmpp
class DeviceClient(sleekxmpp.ClientXMPP) :
def __init__(self, jid, password):
print "User : %s"%jid
super(DeviceClient, self).__init__(jid, password)
logging.info("XMPP client launched... | st='cube_jid', default='cube@localhost')
parser.add_option('-j', action="store", dest='self_jid', default='device@localhost')
parser.add_option('-k', action="store", dest='self_pwd', default='device')
options, args = parser.parse_args()
print options.self_jid, options.self_pwd
client = DeviceCli | ent(options.self_jid, options.self_pwd)
#thread.start_new_thread(client.start_loop, ())
print "hola"
if client.connect(use_tls=False):
client.process(block=False)
onemore = True
while onemore :
raw = raw_input('> ')
if raw=='q' :
break
else :
client.send_mess... |
jokey2k/pyClanSphere | pyClanSphere/utils/support.py | Python | bsd-3-clause | 1,485 | 0.000673 | # -*- coding: utf-8 -*-
"""
pyClanSphere.utils.support
~~~~~~~~~~~~~~~~~~~~~~~~~~
A support module. Provides various support methods and helpers.
:copyright: (c) 2009 - 2010 by the pyClanSphere Team,
(c) 2009 by Plurk Inc.,
see AUTHORS for more details.
:license: B... | word = _punctuation_re.sub(u'', word.encode('translit/long'))
if word:
result.append(word)
return unicode(delim.join(result))
class UIException(Exception):
"""Exceptions that are display | ed in the user interface. The big
difference to a regular exception is that this exception uses
an unicode string as message.
"""
message = None
def __init__(self, message):
Exception.__init__(self, message.encode('utf-8'))
self.message = message
def __unicode__(self):
... |
chrxr/wagtail | wagtail/tests/routablepage/models.py | Python | bsd-3-clause | 1,231 | 0 | from __future__ import absolute_import, unicode_literals
from django.http import HttpResponse
from wagtail.contrib.wagtailroutablepage.models import RoutablePage, route
def routable_page_external_view(request, arg="ARG NOT SET"):
return HttpResponse("EXTERNAL | VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@route(r'^$')
def main(self, request):
return HttpResponse("MAIN VIEW")
@route(r'^archive/year/(\d+)/$')
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
@route(r'^archive/author/(?... | oute(r'^external/(.+)/$')
@route(r'^external-no-arg/$')
def external_view(self, *args, **kwargs):
return routable_page_external_view(*args, **kwargs)
# By default, the method name would be used as the url name but when the
# "name" kwarg is specified, this should override the default.
@rout... |
slackeater/anal-beh | classes/gui/mylistwidget.py | Python | gpl-2.0 | 1,257 | 0.002387 | __author__ = 'snake'
from PyQt4 import QtGui, QtCore
class SiteItems(QtGui.QListWidget):
def __init__(self):
super(SiteItems, self).__init__()
def startDrag(self, dropAction):
# create mime data object
#get all selected items
selitems = ""
for i in self.selectedIte... | for site in sites.split(","):
self.addItem(site)
event.setDropAction( | QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore() |
karllessard/tensorflow | tensorflow/python/ops/tensor_array_ops_test.py | Python | apache-2.0 | 3,060 | 0.003595 | # 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/li | censes/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation | s under the License.
# ==============================================================================
"""Tests for tensor_array_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import def_function
from tensorflow.python.f... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/distributions/python/kernel_tests/transformed_distribution_test.py | Python | apache-2.0 | 12,624 | 0.006179 | # 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... | multi_logit_nor | mal.log_prob(y).eval())
self.assertAllClose(
[1, 2, 3, 2],
array_ops.shape(multi_logit_normal.sample([1, 2, 3])).eval())
self.assertAllEqual([2], multi_logit_normal.event_shape)
self.assertAllEqual([2], multi_logit_normal.event_shape_tensor().eval())
def testEntropy(self):
w... |
jeremiahyan/odoo | addons/website/tests/test_controllers.py | Python | gpl-3.0 | 1,810 | 0.003315 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import tests
from odoo.tools import mute_logger
@tests.tagged('post_install', '-at_install')
class TestControllers(tests.HttpCase):
@mute_logger('odoo.addons.http_routing.models.ir_http', 'o... | ult' in resp
suggested_links = resp['result']
last_modified_history = next(o for o in suggested_links['others'] if o["title"] == "Last modified pages")
last_modified_values = map(lambda o: o['valu | e'], last_modified_history['values'])
matching_pages = set(map(lambda o: o['value'], suggested_links['matching_pages']))
self.assertEqual(set(last_modified_values), set(last_5_url_edited) - matching_pages)
|
nabla-c0d3/sslyze | sslyze/plugins/robot/_robot_tester.py | Python | agpl-3.0 | 19,827 | 0.003783 | import socket
import types
from enum import Enum
from typing import Optional, List, Dict
import binascii
import math
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPublicNumbers
from cryptography.x509 import load_pem_x509_certificate
... | _BYTES][0]
response_2 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_POSITION_00][0]
response_3 = self._payload_responses[RobotPmsPaddingPayloadEnum.NO_00_IN_THE_MIDDLE][0]
# From the original script:
# If th | e response to the invalid PKCS#1 request (oracle_bad1) is equal to both
# requests starting with 0002, we have a weak oracle. This is because the only
# case where we can distinguish valid from invalid requests is when we send
# correctly formatted PKCS#1 message with 0x00 on a correct position.... |
zenoss/ZenPacks.Opengear.ConsoleServer | setup.py | Python | gpl-2.0 | 2,682 | 0.012677 | ################################
# These variables are overwritten by Zenoss when the ZenPack is exported
# or saved. Do not modify them directly here.
# NB: PACKAGES is deprecated
NAME = "ZenPacks.Opengear.ConsoleServer"
VERSION = "1.0"
AUTHOR = "Peter Hunt <support@opengear.com>"
LICENSE = "GPLv2"
NAMESPACE_PACKAGES... | # overwrite the values below (the ones it knows about) with new values.
name = NAME,
version = VERSION,
author = AUTHOR,
license = LICENSE,
# This is the version spec which indicates what versions of Zenoss
# this ZenPack is compatible with
compatZenossVers | = COMPAT_ZENOSS_VERS,
# previousZenPackName is a facility for telling Zenoss that the name
# of this ZenPack has changed. If no ZenPack with the current name is
# installed then a zenpack of this name if installed will be upgraded.
prevZenPackName = PREV_ZENPACK_NAME,
# Indicate to setu... |
rodo/django-extensions | tests/test_uuid_field.py | Python | mit | 2,355 | 0.005096 | import re
import uuid
import six
from django.test import TestCase
from django_extensions.db.fields import PostgreSQLUUIDField
from .testapp.models import (
UUIDTestAgregateModel, UUIDTestManyToManyModel, UUIDTestModel_field,
UUIDTestModel_pk,
)
class UUIDFieldTest(TestCase):
def test_UUID_field_create(... | , six.u('550e8400-e29b-41d4-a716-446655440010'))
class PostgreSQLUUIDFieldTest(TestCase):
def test_uuid_casting(self):
# As explain by postgres documentation
# http://www.p | ostgresql.org/docs/9.1/static/datatype-uuid.html
# an uuid needs to be a sequence of lower-case hexadecimal digits, in
# several groups separated by hyphens, specifically a group of 8 digits
# followed by three groups of 4 digits followed by a group of 12 digits
matcher = re.compile('^[\... |
gbowerman/vmsstools | cpuload/getnics.py | Python | mit | 1,010 | 0.008911 | # getnics.py - script to get the internal IP addresses from the VMs in a scale set
# to do: do not hardcode the rgname and vmssname - instead make them command line
# parameters
import azurerm
import json
# Load Azure app defaults
try:
with open('azurermconfig.json') as configFile:
configData = json.load(con... | rrent folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['appId']
app_secret = configData['appSecret']
subscription_id = configData['subscriptionId']
rgname = 'sgelastic'
vmssname = 'sgelastic'
# authenticate
access_token | = azurerm.get_access_token(tenant_id, app_id, app_secret)
nics = azurerm.get_vmss_nics(access_token, subscription_id, rgname, vmssname)
for nic in nics['value']:
#print(json.dumps(nic, sort_keys=False, indent=2, separators=(',', ': ')))
ipaddress = nic['properties']['ipConfigurations'][0]['properties']['priva... |
JasonMWhite/python_template | setup.py | Python | mit | 738 | 0.001355 | from setuptools import setup
setup(
name='python_template',
version='0.1.0',
description='A Python template re | po to save you some yak-shaving.',
long_description='',
author='Jason White',
author_email='jason.white@shopify.com',
url='https://github.com/JasonMWhite/python_template',
packages=['python_template', 'pylint_custom'],
include_package_data=True,
install_requires=[
],
license="MIT",
... | :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
],
test_suite='tests',
) |
ngr/sandbox | neuraldata/problem_set1/sandbox.py | Python | mit | 557 | 0.025135 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 05 10:02:23 2014
@author: grischenko
"""
#import numpy as np
import random
#import matplotlib.pyplot as plt
#import matplotlib.axes as axs
import pylab as mpl
x = range(25)
y = []
for i in range(25):
y.append(random.randint(1,5))
print x, y
mpl.figure()
mpl.ti... | ylabel = "vol"
#axs.Axes.set_xlabel(my.xlabel, "time | ")
#plt.draw() |
ucfopen/canvasapi | canvasapi/quiz_group.py | Python | mit | 4,094 | 0.001466 | from canvasapi.canvas_object import CanvasObject
from canvasapi.exceptions import RequiredFieldMissing
from canvasapi.util import combine_kwargs
class QuizGroup(CanvasObject):
def __str__(self):
return "{} ({})".format(self.name, self.id)
def delete(self, **kwargs):
"""
Get details of... | calls: `DELETE /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \
<https://canvas.instructure.com/doc/api/quiz_question_groups.html#method.quizzes/quiz_groups.destroy>`_
:returns: True if the result was successful (Status code of 204)
:rtype: bool
"""
response = self._requ... | _kwargs=combine_kwargs(**kwargs),
)
return response.status_code == 204
def reorder_question_group(self, order, **kwargs):
"""
Update the order of questions within a given group
:calls: `POST /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id/reorder \
<https://c... |
boldingd/BadRbm | badrbm.py | Python | mit | 3,890 | 0.004884 | #! /usr/bin/python3
import numpy
import scipy.special # for expit (a quick numpy-array-aware sigmoid)
# consider http://stackoverflow.com/questions/3985619/how-to-calculate-a-logistic-sigmoid-function-in-python
class RbmError(Exception):
pass
class rbm:
def __init__(self, i, j, rate, p=None): # i = |v|, j =... | E -= self.b.T @ h
E -= v.T @ self.W @ h
return E
def get_v(self, h):
v_probs = scipy.special.expit(self.a + (self.W @ h))
v_vals = numpy.random.rand(self.i, 1)
# there has to be some craftier way to do this
# possibly using numpy.vectorize?
v_res = n... | _probs = scipy.special.expit(self.b + (self.W.T @ v))
#h_probs = scipy.special.expit(self.b + (v.T @ self.W).T) # trying to avoid an expensive matrix invert
h_vals = numpy.random.rand(self.j, 1)
h_res = numpy.zeros((self.j, 1))
for i in range(self.j):
if h_vals[i] < h_probs[... |
graziano-giuliani/pythoncode | pyuwphysret/common/pyfiles/atmos/integral.py | Python | mit | 2,891 | 0.017987 | #!/usr/bin/env python
# integeral.py
import numpy as num
def integral(x,y):
"""
ROUTINE: INTEGRAL
USEAGE: RESULT = INTEGRAL( X, Y )
PURPOSE: Integrate tabulated data using Simpson's rule
with 3-point Lagragian interpolation. Data may be
regularly sampled in X, ... | rapezoid Method yields; result = 1.5648
The Multiple A | pplication Simpson's Method yields; result = 1.6036
IDL User Library INT_TABULATED.PRO yields; result = 1.6232
INTEGRAL.PRO yields; result = 1.6274
The Exact Solution (4 decimal accuracy) yields; result = 1.6405
AUTHOR: Liam Gumley, CIMSS/SSEC (lia... |
OlegKlimenko/py-sdoc | sdoc/sdoc2/SDoc2Visitor.py | Python | mit | 7,232 | 0.001521 | """
SDoc
Copyright 2016 Set Based IT Consultancy
Licence MIT
"""
# ----------------------------------------------------------------------------------------------------------------------
import re
from sdoc import sdoc2
from sdoc.antlr.sdoc2ParserVisitor import sdoc2ParserVisitor
from sdoc.sdoc.SDocVisitor import SDo... | '"):
option_value = option_value[1:-1]
options[option_name] = option_value
i += 1
return options
# ------------------------------------------------------------------------------------------------------------------
def get_position(self, token):
"""
... | sition
"""
line_number = token.line
column = token.column
if self._sdoc2_line == line_number:
column = self._sdoc1_column + (column - self._sdoc2_column)
line_number = self._sdoc1_line + (line_number - self._sdoc2_line)
return Position(self._sdoc1_file_name... |
DEAP/deap | setup.py | Python | lgpl-3.0 | 3,832 | 0.007046 | #!/usr/bin/env python
import sys
warnings = list()
try:
from setuptools import setup, Extension, find_packages
modules = find_packages(exclude=['examples'])
except ImportError:
warnings.append("warning: using distutils.core.setup, cannot use \"develop\" option")
from distutils.core import setup, Exten... | ors import CCompilerError, DistutilsExecError, \
DistutilsPlatformError
# read the contents of README file
from os import path
import codecs
this_directory = path.abspath(path.dirname(__file__))
long_description = codecs.open(path.join(this_directory, 'README.md'), 'r', 'utf-8').read()
import deap
if sys.platfor... | sys.version_info > (2, 6):
# 2.6's distutils.msvc9compiler can raise an IOError when failing to
# find the compiler
# It can also raise ValueError http://bugs.python.org/issue7511
ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError,
IOError, ValueError)
else:
ext_err... |
oodt-cloud/docker | examples/test-workflow/swarm/wmgr_config/rabbitmq_clients/rabbitmq_producer.py | Python | apache-2.0 | 20,108 | 0.003879 | # -*- coding: utf-8 -*-
# Adapted from:
# http://pika.readthedocs.io/en/0.10.0/examples/asynchronous_publisher_example.html
# Features:
# o Requests delivery confirmation from RabbitMQ server
# and keeps tracks of which messages have been acknowledged or not acknowledged
# o Reconnects if connection to RabbitMQ ser... | else:
LOGGER.warning('Connection closed, reopening in 5 seconds: (%s) %s',
reply_code, reply_text)
self._connection.add_timeout(5, self.reconnect)
def reconnect(self):
"""Will be invoked by the IOLoop timer if the connection is
closed. See ... | iveries = []
self._acked = 0
self._nacked = 0
self._message_number = 0
# This is the old connection IOLoop instance, stop its ioloop
self._connection.ioloop.stop()
# Create a new connection
self._connection = self.connect()
# There is now a new connecti... |
calumk/ROS-Blocks | ros_blocks/scripts/ik_solver.py | Python | mit | 1,346 | 0.002972 | import argparse
import sys
import rospy
from geometry_msgs.msg import (
PoseStamped,
Pose,
Point,
Quaternion,
)
from std_msgs.msg import Header
from baxter_core_msgs.srv import (
SolvePositionIK,
SolvePositionIKRequest,
)
def ik_solve(limb, pos, orient):
#~ rospy.init_node("rsdk_ik_serv... | spy.ServiceProxy(ns, SolvePositionIK)
ikreq = SolvePosi | tionIKRequest()
print "iksvc: ", iksvc
print "ikreq: ", ikreq
hdr = Header(stamp=rospy.Time.now(), frame_id='base')
poses = {
str(limb): PoseStamped(header=hdr,
pose=Pose(position=pos, orientation=orient))}
ikreq.pose_stamp.append(poses[limb])
try:
rospy.... |
NNPDF/reportengine | src/reportengine/tests/__init__.py | Python | gpl-2.0 | 95 | 0.010526 | # - | *- coding: utf-8 -*-
"""
Created on Wed Mar 2 12:13:32 2016
@author: Zahari Kassabov
"" | "
|
ruhulsbu/WEAT4TwitterGroups | histwords/gender_bias_plot.py | Python | mit | 5,322 | 0.009395 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 20:55:28 2017
@author: moamin
"""
import os, sys, time, gzip, math
import numpy as np,csv, json, re
#from gensim.models import Word2Vec
import matplotlib.pyplot as plt
#from sets import Set
from representations.sequentialembedding import Sequen... | bute, attribute_words):
for i in range(0, len(target_words)):
for k in range(0, len(attribute_words)):
wt = target_words[i][:-1]
at = attribute_ | words[k][:-1]
'''
try:
lib_cosine = lib_word2vec_model.similarity(wt, at)
con_cosine = con_word2vec_model.similarity(wt, at)
except:
continue
#print(wt, target, at, attribute, lib_cosine, con_cosine)
print_txt = ... |
vkaracic/Xblocks-Directory | xblock/tests/test_model.py | Python | mit | 550 | 0 | from django.test import TestCase
from xblock.models import Xblock
class XblockTest(TestCase):
def test_model(self):
Xblo | ck.objects.create(
name='test',
packages='test',
description='An xblock for testing',
version='1,0',
author='Tester',
organization='ExtensionEngine',
github_link='https://github.com/tester/xblock'
)
self.assertEqual(Xblo... | ilter(name='test').count(), 1)
|
florian-f/sklearn | examples/cluster/plot_cluster_iris.py | Python | bsd-3-clause | 2,573 | 0.001943 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
K-means Clustering
=========================================================
The plots display firstly what a K-means algorithm would yield
using three clusters. It is then shown what the effect of a bad
initializa... | iris_bad_init': KMeans(n_clusters=3, n_init=1,
init='random')}
fignum = 1
for name, est in estimators.iteritems():
fig = pl.figure(fignum, figsize=(4, 3))
pl.clf()
ax = Axes3D(fig, | rect=[0, 0, .95, 1], elev=48, azim=134)
pl.cla()
est.fit(X)
labels = est.labels_
ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float))
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
ax.set_xlabel('Petal width')
ax.set_ylabel('... |
noironetworks/group-based-policy | gbpservice/neutron/tests/unit/nfp/orchestrator/db/test_nfp_db.py | Python | apache-2.0 | 26,780 | 0.000037 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | atus'])
def test_delete_network_function(self):
network_function = self.create_network_function()
self.assertIsNotNone(network_function['id'])
self.nfp_ | db.delete_network_function(
self.session, network_function['id'])
self.assertRaises(nfp_exc.NetworkFunctionNotFound,
self.nfp_db.get_network_function,
self.session, network_function['id'])
def create_network_function_instance(self, attributes=... |
memmett/PyPFASST | examples/advection/main.py | Python | bsd-2-clause | 3,683 | 0.004887 | """Solve the advection/diffusion equation with PyPFASST."""
# Copyright (c) 2011, Matthew Emmett. 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 ret... | TICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTE | RRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from mpi4py import MPI
import argparse
import pfasst
import pfass... |
iamdork/dork | dork/git.py | Python | mit | 7,799 | 0.002821 | from subprocess import call, check_output, PIPE
from glob2 import glob, Globber
import os
import re
import config
def _git_globber_listdir(path):
if os.path.exists(path + '/.git'):
return []
else:
retur | n os.listdir(path)
def _git_globber_islink(path):
return os.path.islink(path) and not os.path.isdir(path)
class GitGlobber(Globber):
listdir = staticmethod(_git_globber_listdir)
islink = stat | icmethod(_git_globber_islink)
git_globber = GitGlobber()
def _gitless_globber_listdir(path):
return [d for d in os.listdir(path) if not d.endswith('.git')]
class GitlessGlobber(Globber):
listdir = staticmethod(_gitless_globber_listdir)
gitless_globber = GitlessGlobber()
def get_repositories(directory):
... |
aliyun/aliyun-oss-python-sdk | examples/bucket_website.py | Python | mit | 6,202 | 0.011307 | # -*- coding: utf-8 -*-
import os
import oss2
from oss2.models import (ConditionInlcudeHeader,
Condition,
Redirect,
RedirectMirrorHeaders,
MirrorHeadersSet,
RoutingRule,
... | mirror_follow_redirect=True, mirror_check_md5=True, mirror_headers=mirror_header)
# 不指定备站
redirect2 = Redirect(redirect_type=REDIRECT_TYPE_MIRROR, mirror_url='http://www.test.com/',
mirror_pass_query_string=True, mirror_follow_redirect=True, mirror_check_md5=False)
# 可以设置一条或多条,本示例展示设置多条
rule1 = ... | (rule_num=2, condition=condition2, redirect=redirect2)
website_set = BucketWebsite(index_file, error_file, [rule1, rule2])
bucket.put_bucket_website(website_set)
# 获取website配置
website_get = bucket.get_bucket_website()
print('get_bucket_website mirror type:')
print('indext_file:', website_get.index_file)
print('error_f... |
FancyRice/RitoAPI | ritoapi/tests/tests_endpoints/test_spectator_v3.py | Python | mit | 283 | 0 | from ritoa | pi.endpoints.spectator_v3 import SpectatorV3
def test_featured_games(sample_api_key, sample_rate_limit, sample_region):
spectator_v3 = SpectatorV3(sample_api_key, sample_rate_limit)
dat | a = spectator_v3.featured_games(sample_region)
assert('gameList' in data)
|
fooelisa/netmiko | netmiko/ruckus/ruckus_fastiron.py | Python | mit | 2,254 | 0.001775 | from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class RuckusFastironBase(CiscoSSHConnection):
"""Ruckus FastIron aka ICX support."""
def session_preparation(self):
"""FastIron requires to be enable mode to disable paging."""
... | ))
new_data = self.read_until_prompt_or_pattern(pattern=pattern, re_flags=re_flags)
output += new_data
if 'ssword' in new_data:
self.write_channel(self.normalize_cmd(self.secret))
output += self.read_until_prompt()
... | eep(1)
i += 1
if not self.check_enable_mode():
msg = "Failed to enter enable mode. Please ensure you pass " \
"the 'secret' argument to ConnectHandler."
raise ValueError(msg)
class RuckusFastironTelnet(RuckusFastironBase):
def __init__(self, *args... |
Quantify-world/apification | src/apification/utils/tests/test_noninstantiable.py | Python | mit | 1,632 | 0.009191 | import warnings
from apification.utils import Noninstantiable, NoninstantiableMeta
def test_noninstantiable():
e, o = None, None
try:
o = Noninstantiable()
except TypeError as e: pass
assert o is None
assert isinstance(e, TypeError)
def test_noninstantiable_keyword_self_check_invalid():... | rt A.a() is A
def test_noninstantiable_keyword_self_check_suppression():
C = None
class C(Noninstantiable):
_allow_self_as_first_arg = True
def func(self, a, b=1):
| pass
assert issubclass(C, Noninstantiable)
def test_noninstantable_inheritance():
class A(object):
_allow_self_as_first_arg = True
e = None
try:
class B(A):
__metaclass__ = NoninstantiableMeta
def a(self):
pass
except TypeError as e:
... |
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/OpenSSL/test/test_crypto.py | Python | mit | 104,799 | 0.002099 | # Copyright (c) Jean-Paul Calderone
# See LICENSE file for details.
"""
Unit tests for L{OpenSSL.crypto}.
"""
from unittest import main
import os, re
from subprocess import PIPE, Popen
from datetime import datetime, timedelta
from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
from OpenSSL.crypto i... | NuDcOtzUaeWZlZAkA8
ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
6AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
-----END RSA PRIVATE KEY-----
""")
server_cert_pem = b("""-----BEGIN CERTIFICATE-----
MIICKDCCAZGgAwIBAgIJAJn/HpR21r/8MA0GCSq... | hgPMjAxNzA2MTExMjM3NTNaMBgxFjAUBgNVBAMTDWxvdmVseSBzZXJ2ZXIw
gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAL6m+G653V0tpBC/OKl22VxOi2Cv
lK4TYu9LHSDP9uDVTe7V5D5Tl6qzFoRRx5pfmnkqT5B+W9byp2NU3FC5hLm5zSAr
b45meUhjEJ/ifkZgbNUjHdBIGP9MAQUHZa5WKdkGIJvGAvs8UzUqlr4TBWQIB24+
lJ+Ukk/CRgasrYwdAgMBAAGjNjA0MB0GA1UdDgQWBBS4kC7Ij0W1TZXZqXQFAM2e
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.