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 |
|---|---|---|---|---|---|---|---|---|
kfollette/ASTR200-Spring2017 | Homework/diff_int.py | Python | mit | 441 | 0.022676 | def diff_int(d=0.01*u.cm,a=0.001*u.cm,wl=400*u.nm):
'''
function that returns the i | ntensity of a double slit interference pattern
'''
theta = arange(-10,10,1e-5)*u.degree
x = pi*a*sin(theta)/wl*u.radian
xnew = x.decompose()
i_single = (sin(xnew)/xnew)**2
y = pi*d*sin(theta)/wl*u.radian
ynew = y.decompose()
i_double = (cos | (ynew))**2
I = i_single*i_double
plot(theta,I)
return
|
17twenty/binwalk | src/binwalk/core/parser.py | Python | mit | 13,154 | 0.004485 | # Code for performing minimal parsing of libmagic-compatible signature files.
# This allows for building a single signature file from multiple other signature files,
# and for parsing out the initial magic signature bytes for each signature (used for
# pre-processing of data to limit the number of actual calls into lib... | raw_fd.name
def parse(self, file_name):
'''
Parses magic file(s) and contatenates them into a single temporary magic file
while simultaneously removing filtered signatures.
@file_name - Magic file, or list of magic files, to parse.
Returns the name of the generated tempora... | self.signature_count = 0
self.fd = tempfile.NamedTemporaryFile()
if isinstance(file_name, type([])):
files = file_name
else:
files = [file_name]
for fname in files:
if fname:
if os.path.exists(fname) and os.path.isfile(fname):
... |
CyanogenMod/android_external_chromium-trace | trace-viewer/third_party/pywebsocket/src/mod_pywebsocket/util.py | Python | bsd-3-clause | 16,267 | 0.000184 | # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | position in the masking bytes the last mask method call
ended and resumes from that point on the next mask method call.
"""
def __init__(self, mask):
self._mask = map(ord, mask)
self._mask_size = len(self._mask)
self._count = 0
def mask(self, s):
resu | lt = array.array('B')
result.fromstring(s)
# Use temporary local variables to eliminate the cost to access
# attributes
count = self._count
mask = self._mask
mask_size = self._mask_size
for i in xrange(len(result)):
result[i] ^= mask[count]
... |
clairejaja/project-euler | src/main/python/problem2/even_fibonacci_numbers.py | Python | mit | 876 | 0.001142 | # Claire Jaja
# 11/1/2014
#
# Project Euler
# Problem 2
# Even Fibonacci numbers
#
# Each new term in the Fibonacci sequence is generated by adding
# the previous two terms.
# By starting with 1 and | 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms | in the Fibonacci sequence
# whose values do not exceed four million,
# find the sum of the even-valued terms.
def main():
max_value = 4000000
# set up first three terms
previous_previous_term = 1
previous_term = 1
current_term = 2
my_sum = 0
while current_term < max_value:
if cur... |
kennedyshead/home-assistant | homeassistant/components/accuweather/const.py | Python | apache-2.0 | 10,736 | 0 | """Constants for AccuWeather integration."""
from __future__ import annotations
from typing import Final
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_EXCEPTIONAL,
ATTR_CONDITION_FOG,
ATTR_CONDITION_HAIL,
ATTR_CONDITION_LIGHTNI... | R_ENABLED | : False,
},
"Ragweed": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:sprout",
ATTR_LABEL: "Ragweed Pollen",
ATTR_UNIT_METRIC: CONCENTRATION_PARTS_PER_CUBIC_METER,
ATTR_UNIT_IMPERIAL: CONCENTRATION_PARTS_PER_CUBIC_METER,
ATTR_ENABLED: False,
},
"RealFeelTemper... |
dallingham/regenerate | setup-win.py | Python | gpl-2.0 | 3,108 | 0.003861 |
from setuptools import setup
import py2exe
import os
import glob
__import__('gtk')
__import__('jinja2')
__import__('docutils')
setup_dict = dict(
name='regenerate',
version='1.0.0',
license='License.txt',
author='Donald N. Allingham',
author_email='dallingham@gmail.com',
description='Re... | e' : [
"data/ui/*.ui",
"data/medi | a/*",
"data/help/*.rst",
"data/extra/*",
"data/*.*",
"writers/templates/*"
]
},
include_package_data=True,
url="https://github.com/dallingham/regenerate",
scripts=[
"bin/regenerate",
"bin/regbuild",
"bin/regupdate",
... |
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_fusion_seqpool_cvm_concat_op.py | Python | apache-2.0 | 4,299 | 0.000465 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | lf.axis)}
self.attrs = {
'pooltype': self.pooltype,
'axis': self.axis,
}
def set_pooltype(self):
self.pooltype = "SUM"
d | ef set_conf(self):
pass
def test_check_output(self):
self.check_output()
class TestFusionSeqPoolCVMConcatOpCase1(TestFusionSeqPoolCVMConcatOp):
def set_conf(self):
self.lods = [[[1]]]
class TestFusionSeqPoolCVMConcatOpCase2(TestFusionSeqPoolCVMConcatOp):
def set_conf(self):
... |
DiCarloLab-Delft/PycQED_py3 | pycqed/measurement/det_fncs/hard/SignalHound.py | Python | mit | 5,908 | 0.000508 | """
SignalHound related detector functions
extracted from pycqed/measurement/detector_functions.py commit 0da380ad2adf2dc998f5effef362cdf264b87948
"""
import logging
import time
from packaging import version
import qcodes as qc
from pycqed.measurement.det_fncs.Base import Soft_Detector, Hard_Detector
from pycqed.me... | cy', frequency)
self.SH.prepare_for_measurement()
time.sleep(self.delay)
return self.SH.get_power_at_freq(Navg=self.Navg)
def get_values(self):
return ([self.a | cquire_data_point()])
def prepare(self, sweep_points):
self.swp = list(sweep_points)
# self.SH.prepare_for_measurement()
def finish(self, **kw):
self.SH.abort()
class SH_mixer_skewness_det(Soft_Detector):
'''
Based on the "Signal_Hound_fixed_frequency" detector.
generates... |
hiqdev/reppy | heppy/Error.py | Python | bsd-3-clause | 580 | 0.010345 | import logging
class Error(Exception):
def __init__(self, message, data = {}):
| self.message = message
self.data = data
def __str__(self):
return self.message + ": " + repr(self.data)
@staticmethod
def die(code, error, message = None):
if isinstance(error, Exception):
e = error
error = '{0}.{1}'.format(type(e).__module__, type(e).... | sage
#logging.exception(message)
exit(code)
|
googleapis/python-aiplatform | google/cloud/aiplatform_v1/services/specialist_pool_service/async_client.py | Python | apache-2.0 | 34,518 | 0.001477 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | itional arguments to pa | ss to the constructor.
Returns:
SpecialistPoolServiceAsyncClient: The constructed client.
"""
return SpecialistPoolServiceClient.from_service_account_file.__func__(SpecialistPoolServiceAsyncClient, filename, *args, **kwargs) # type: ignore
from_service_account_json = from_serv... |
lferran/FibbingNode | fibbingnode/southbound/main.py | Python | gpl-2.0 | 7,223 | 0 | from ConfigParser import DEFAULTSECT
from cmd import Cmd
import logging
import sys
import subprocess
import argparse
import datetime
from fibbing import FibbingManager
import fibbingnode
from fibbingnode.misc.utils import dump_threads
import signal
log = fibbingnode.log
CFG = fibbingnode.CFG
class FibbingCLI(Cmd):
... | log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
# Check for any specified physical port to use both in config file
# or in args
ports = set(p for p in CFG.sections()
| if not (p == 'fake' or p == 'physical' or p == DEFAULTSECT))
ports.update(args.ports)
if not ports:
log.warning('The fibbing node will not be connected '
'to any physical ports!')
else:
log.info('Using the physical ports: %s', ports)
return ports, instance_count,... |
gnozell/Yar-Ha-Har | lib/riotwatcher/riotwatcher.py | Python | mit | 22,700 | 0.00163 | from collections import deque
import time
import requests
# Constants
BRAZIL = 'br'
EUROPE_NORDIC_EAST = 'eune'
EUROPE_WEST = 'euw'
KOREA = 'kr'
LATIN_AMERICA_NORTH = 'lan'
LATIN_AMERICA_SOUTH = 'las'
NORTH_AMERICA = 'na'
OCEANIA = 'oce'
RUSSIA = 'ru'
TURKEY = 'tr'
# Platforms
platforms = {
BRAZIL: 'BR1',
EUR... | ed_requests
self.seconds = seconds
self.made_requests = deque()
def __reload(self):
t = time.time()
while len(self.made_requests) > 0 and self.made_requests[0] < t:
self.made_request | s.popleft()
def add_request(self):
self.made_requests.append(time.time() + self.seconds)
def request_available(self):
self.__reload()
return len(self.made_requests) < self.allowed_requests
class RiotWatcher:
def __init__(self, key, default_region=NORTH_AMERICA, limits=(RateLimit(... |
aldebaran/qibuild | python/qibuild/test/test_qibuild_find.py | Python | bsd-3-clause | 3,244 | 0.000308 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiBuild Find """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ im... | ind_target_in_build_dir(qibuild_action, record_messages):
""" Test Find Target In Build Dir """
qibuild_action.add_test_project("world")
qibuild_action.add_test_project("hello")
qibuild_action("configure", "hello")
qibuild_action("make", "hello")
record_messages.reset()
qibuild_action("find"... | ary_name("world"))
rc = qibuild_action("find", "hello", "libworld", retcode=True)
assert rc == 1
def test_find_target_in_toolchain_package(cd_to_tmpdir, record_messages):
""" Test Find Target In Toolchain Package """
qibuild_action = QiBuildAction()
qitoolchain_action = QiToolchainAction()
qib... |
brutalic/pynet_brutal | class2/GetSysNameDesc.py | Python | apache-2.0 | 1,227 | 0.007335 | #!/usr/bin/python
import getpass
import snmp_helper
from snmp_helper import snmp_get_oid,snmp_extract
import yaml
DeviceIp1 = '184.105.247.70'
DeviceIp2 = '184.105.247.71'
SnmpPort = 161
sysNameOID = '.1.3.6.1.2.1.1.5.0'
sysDescOID = '.1.3.6.1.2.1.1.1.0'
#Connecting to the devices, using methods from getpass librar... | "\nResults printed to a yam | l file.\n"
|
SebDieBln/QGIS | python/plugins/db_manager/db_plugins/oracle/plugin.py | Python | gpl-2.0 | 22,853 | 0.000131 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS (Oracle)
Date : Aug 27, 2014
copyright : (C) 2014 by Médéric RIBREUX
email : meder... | if self.schemas():
action = QAction(QApplication.translate(
"DBManagerPlugin", "&Create schema"), self)
mainWindow.registerAction(action, QApplication.translate(
"DBManagerPlugin", "&Schema"), self.createSchemaActionSlot)
| action = QAction(QApplication.translate(
"DBManagerPlugin", "&Delete (empty) schema"), self)
mainWindow.registerAction(action, Q |
stuaxo/pyHotReload | setup.py | Python | bsd-2-clause | 2,321 | 0.004308 | import glob
import os
import shutil
from distutils import sysconfig
from setuptools import setup, Command
from setuptools.command.install import install
here=os.path.dirname(os.path.abspath(__file__))
site_packages_path = sysconfig.get_python_lib()
class CleanCommand(Command):
"""Custom clean command to tidy up ... | ef run(self):
global here
for path_spec in self.CLEAN_FILES:
# Make paths absolute and relative to this path
abs_paths = glob.glob(os.path.normpath(os.path.join(here, path_spec)))
| for path in [str(p) for p in abs_paths]:
if not path.startswith(here):
# Die if path in CLEAN_FILES is absolute + outside this directory
raise ValueError("%s is not a path inside %s" % (path, here))
print('removing %s' % os.path.relpath... |
rbuffat/pyidf | tests/test_compliancebuilding.py | Python | apache-2.0 | 1,041 | 0.003842 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.compliance_objects import ComplianceBuilding
log = logging.getLogger(__name__)
class TestComplianceBuilding(unittest.TestCase):
def setUp(self) | :
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_compliancebuilding(self):
pyidf.validation_level = ValidationLevel.error
obj = ComplianceBuilding()
# real
var_building_rotation_for_appendix_g = 1.1
obj... | en(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertAlmostEqual(idf2.compliancebuildings[0].building_rotation_for_appendix_g, var_building_rotation_for_appendix_g) |
scott48074/Restorative-Justice-App | app/csv_handler.py | Python | mit | 1,556 | 0.003856 | #!/usr/bin/env python3
"""
Open csv file with each a list. All the row-lists are contained in a list. In
preparation for entry into the database the data is cleaned. This includes
validating the headers and striping and lowering the values.
"""
import csv
HEADERS = ['case number', 'case occurred from date', 'case oc... | ', 'reporting district']
def open_csv(path):
# Open the csv file lower and strip all the values. Make sure the csv is
# expect format.
with open(path) as csvfile:
reader = list(csv.reader(csvfile, delimiter=','))
rows = [[val.strip().lower() for val in row] for row in reader]
if ro... | return False
return rows
def write_receipt(path, rows):
# Write the receipt to csv file.
with open(f'{path}/receipt.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(rows)
def main():
pass
if __name__ == '__main__':
main()
|
RetroMelon/PatchWords | patchwords_project/patchwords/forms.py | Python | mit | 1,944 | 0.013374 | from django import forms
from registration.forms import RegistrationForm
from django.contrib.auth.models import User
from models import UserProfile
from models import *
class Registration(RegistrationForm):
picture = forms.ImageField(required=False)
bio = forms.CharField(widget=forms.Textarea(),required=False)... | le", "Female"),)
gender = forms.ChoiceField(widget=forms.RadioSelect,
choices=GENDER_CHOICES,required=False)
class Meta:
model = UserProfile
fields = ('picture','bio','gender')
class ParagraphForm(forms.ModelFor | m):
content = forms.CharField(max_length=200, help_text="Write your paragraph!")
choices = (
(True, 'yes'),
(False, 'no'))
end = forms.ChoiceField(choices=choices, widget=forms.RadioSelect)
class Meta:
model = Paragraph
exclude = ('story', 'parent', 'author','created_datetime')
... |
malmiron/incubator-airflow | tests/contrib/hooks/test_azure_data_lake_hook.py | Python | apache-2.0 | 5,649 | 0.00354 | # -*- coding: utf-8 -*-
#
# 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
#... | @mock.patch('airflow.contrib.hooks.azure_data_lake_hook.lib', autospec=True)
def test_download_file(self, mock_lib, mock_downloader):
from airflow.contrib.hooks.azure_data_lake_hook import AzureDataLakeHook
hook = AzureDataLakeHook(azure_data_lake_conn_id='adl_test_key')
hook.download_fil... | rue,
buffersize=4194304, blocksize=4194304)
mock_downloader.assert_called_once_with(hook.connection,
lpath='test_adl_hook.py',
rpath='/test_adl_hook.py',
... |
aquach/vim-http-client | plugin/http_client.py | Python | mit | 8,172 | 0.005996 | import json
import re
import requests
from_cmdline = False
try:
__file__
from_cmdline = True
except NameError:
pass
if not from_cmdline:
import vim
METHOD_REGEX = re.compile('^(GET|POST|DELETE|PUT|HEAD|OPTIONS|PATCH) (.*)$')
HEADER_REGEX = re.compile('^([^()<>@,;:\<>/\[\]?={}]+):\\s*(.*)$')
VAR_REGEX... | block.pop(0)
header_name, header_value = header_match.groups()
headers[header_name] = replace_vars(header_value, variables)
else:
break
data = [ replace_vars(l, variables) for l in block ]
files = None
if all([ '=' in l for l in data ]):
# Form data: separa... | def to_file(expr):
type, arg = FILE_REGEX.match(expr).groups()
arg = arg.replace('\\(', '(').replace('\\)', ')')
return open(arg, 'rb') if type == 'file' else (arg)
files = dict([(k, to_file(v)) for (k, v) in key_value_pairs.items() if FILE_REGEX.match(v)])
data = dict([(k, v)... |
rwl/PyCIM | CIM14/ENTSOE/Dynamics/IEC61970/Dynamics/ExcitationSystems/ExcitationSystemsExcAC3A.py | Python | mit | 3,453 | 0.01448 | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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... | f.kc = kc
self.se2 = se2
self.te = te
self.tf = tf
self.tb = tb
self.tc = tc
| self.vamax = vamax
self.kf = kf
self.vemin = vemin
self.ke = ke
self.vfemax = vfemax
self.tr = tr
self.e2 = e2
self.e1 = e1
self.kn = kn
self.vamin = vamin
self.kr = kr
self.efdn = efdn
super(E... |
philippjfr/bokeh | bokeh/colors/color.py | Python | bsd-3-clause | 5,085 | 0.00885 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | zero)
Returns:
Color
'''
hsl = self.to_hsl()
hsl.l = self.clamp(hsl.l + amount, 1)
return self.from_hsl(hsl)
@public((1,0,0))
| def to_css(self):
''' Return a CSS representation of this color.
*Subclasses must implement this method.*
Returns:
str
'''
raise NotImplementedError
@public((1,0,0))
def to_hsl(self):
''' Create a new HSL color by converting from this color.
... |
mialinx/testenv | testenv/contrib/memcached.py | Python | mit | 510 | 0.005882 | # -*- coding: utf-8 -*-
from .. import server, utils
class Memcached(server.Server):
binary = 'memcached'
def init(self, **kwargs):
self.binary = utils.find_binary(kwargs.get('memcached_bin', self.binary))
assert 'ip' in kwargs, "memcached servers requires <ip> option"
self.ip | = kwargs['ip']
assert 'port' in kwargs, "memcached server require <port> option"
self.port = kwargs['port']
self.command = [ self.binary, '-l', self.ip, '-p' | , self.port ]
|
andresailer/DIRAC | WorkloadManagementSystem/JobWrapper/WatchdogFactory.py | Python | gpl-3.0 | 2,478 | 0.033495 | """ The Watchdog Factory instantiates a given Watchdog based on a quick
determination of the local operating system.
"""
__RCSID__ = "$Id$"
import re
import platform
from DIRAC import S_OK, S_ERROR, gLogger
class WatchdogFactory( object ):
##################################################################... | moryLimit,
processors = processors,
jobArgs = jobArgs )
return S_OK( wd_o )
except AttributeError as e:
self.log.exception( "Failed to create %s(): %s." % ( subClassName, e ) )
return S_ERROR( "Failed... | ject" )
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
|
iw3hxn/LibrERP | mrp_bom_warning/__openerp__.py | Python | agpl-3.0 | 588 | 0.001704 | # -*- coding: utf-8 -*-
# © 201 | 7 Didotech srl (www.didotech.com)
{
"name": "BoM Warning",
"version": "4.0.1.2",
"depends": [
"mrp",
"base",
"product",
"warning"
],
"author": "Didotech srl",
"description": """
This module is aim to track the warning on Bills of Mate | rial.
""",
"website": "https://www.didotech.com",
"category": "Manufacture Resource Planning",
"data": [
'views/product_view.xml',
'views/mrp_bom_view.xml'
],
"demo": [],
"active": False,
"installable": True,
}
|
nap-complex/pythonPractice | newFile.py | Python | gpl-3.0 | 143 | 0.006993 | #!/us | r/bin/env python3
print("this is a test program to see if")
print("we can make a new | file in github")
print("and push it to the hub.")
|
cwilhelm/django-teams | setup.py | Python | bsd-3-clause | 1,758 | 0.001706 | from distutils.core import setup
import os
from teams import get_version
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir:
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.wa... | url='https://github.com/cwilhelm/django-teams/wiki',
download_url='https://github.com/cwilhelm/django-teams/zipball/master',
package_dir={'teams': 'teams'},
packages=packages,
package_data={'teams': data_files},
classifiers=['Development Status :: 4 - Beta',
| 'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
... |
madjam/mxnet | python/mxnet/ndarray/sparse.py | Python | apache-2.0 | 50,947 | 0.003199 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | NDArray or CSRNDArray or RowSparseNDArray
The copied array.
"""
if isinstance(other, NDArray):
if other.handle is | self.handle:
warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)
return
return _internal._copyto(self, out=other)
elif isinstance(other, Context):
hret = _ndarray_cls(_new_alloc_handle(self.stype, self.shape, other,
... |
prometheanfire/cloud-init | cloudinit/sources/DataSourceSmartOS.py | Python | gpl-3.0 | 29,325 | 0 | # vi: ts=4 expandtab
#
# Copyright (C) 2013 Canonical Ltd.
#
# Author: Ben Howard <ben.howard@canonical.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# Th... | r is defined by the DataDictionary
# http://us-east.manta.joyent.com/jmc/public/mdata/datadict.html
# Comments with "@datadictionary" are snippets of the definition
import base64
import binascii
im | port json
import os
import random
import re
import socket
from cloudinit import log as logging
from cloudinit import serial
from cloudinit import sources
from cloudinit import util
LOG = logging.getLogger(__name__)
SMARTOS_ATTRIB_MAP = {
# Cloud-init Key : (SmartOS Key, Strip line endings)
'instance-id': ('s... |
Star2Billing/cdr-stats | cdr_stats/apirest/view_user.py | Python | mpl-2.0 | 1,041 | 0.001921 | #
# CDR-Stats License
# http://www.cdr-stats.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2015 Star2Billing S.L.
#
# The Initial Develope... | port User
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework import viewsets
from apirest.user_serializers import UserSerializer
#from permissions import CustomObjectPermissions
class UserViewSet(vie... | = User.objects.all()
serializer_class = UserSerializer
authentication = (BasicAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticatedOrReadOnly, )
|
kevinxin90/biothings_explorer_jupyter_notebook | api_handler.py | Python | apache-2.0 | 7,479 | 0.00361 | import requests
import json
import yaml
import pandas as pd
import pprint
from jsonld_processor import jsonld2nquads, fetchvalue
from utils import int2str
class SmartAPIHandler:
def __init__(self):
# description info about endpoint, bioentity and api
self.endpoint_info = {}
self.bioentity_i... | st = yaml.load(requests.get(api_list_url).content)['APIs']
# path to fetch openapi yml file for each api
metadata_url_prefix = "https://raw.githubuserco | ntent.com/NCATS-Tangerine/translator-api-registry/kevin/"
for _api in api_list:
openapi_url = metadata_url_prefix + _api['metadata']
# check if the openapi file for the api exists first
if requests.get(openapi_url).status_code == 200:
# retrieve openapi file
... |
dbcls/dbcls-galaxy | test/functional/test_metadata_editing.py | Python | mit | 2,489 | 0.023303 | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class TestMetadataEdit( TwillTestCase ):
def test_00_metadata_edit( self ):
"""test_metadata_edit: Testing metadata editing"""
self | .logout()
self.login( email='test@bx.psu.edu' )
self.new_history( name='Test Metadata Edit' )
global history1
history1 = galaxy.model.History.query() \
.order_by( desc( galax | y.model.History.table.c.create_time ) ).first()
self.upload_file( '1.bed' )
latest_hda = galaxy.model.HistoryDatasetAssociation.query() \
.order_by( desc( galaxy.model.HistoryDatasetAssociation.table.c.create_time ) ).first()
self.home()
# Due to twill not being able to handl... |
jmagnusson/Flask-Resize | tests/test_bin.py | Python | bsd-2-clause | 2,759 | 0 | import os
import subprocess
import pytest
import flask_resize
from .decorators import requires_redis, slow
@pytest.fixture
def env(tmpdir, redis_cache):
basedir = tmpdir
conffile = tmpdir.join('flask-resize-conf.py')
conffile.write(
"""
RESIZE_URL = 'https://example.com'
RESIZE_ROOT = '{root}'
... | _usage(env):
assert 'usage: flask-resize' in run(env, 'flask-resize', '--help')[0]
@slow
def test_bin_list_images_empty(env):
assert run(env, 'flask-resize', 'list', 'images') == []
@slow
def test_bin_l | ist_has_images(
env,
resizetarget_opts,
image1_name,
image1_data,
image1_key
):
resize_target = flask_resize.ResizeTarget(**resizetarget_opts)
resize_target.image_store.save(image1_name, image1_data)
resize_target.generate()
assert run(env, 'flask-resize', 'list', 'images') == [imag... |
gsnbng/erpnext | erpnext/healthcare/doctype/therapy_session/therapy_session_dashboard.py | Python | agpl-3.0 | 226 | 0.044248 | from __f | uture__ import unicode_literal | s
from frappe import _
def get_data():
return {
'fieldname': 'therapy_session',
'transactions': [
{
'label': _('Assessments'),
'items': ['Patient Assessment']
}
]
}
|
acampbell3000/clojure-imdb-parser | run.py | Python | apache-2.0 | 4,140 | 0.003623 | #!/usr/bin/python
#
# Copyright 2012 Anthony Campbell (anthonycampbell.co.uk)
#
# 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 re... | imdb-parser.jar:"
print "\n " + latest_jar + "\n"
try:
# Execute the parser
process = subprocess.Popen(["java", "-jar", latest_jar, query_term, output_file, str(verbose)],
stdout=subprocess.PIPE)
output, stderr = process.communicate()
... | process.wait()
except exceptions.Exception as error:
print "\n Unable to execute clojure-imdb-parser.jar!"
print "\n " + str(error)
sys.exit(1)
else:
print "\n Unable to find latest clojure-imdb-parser.jar!"
sys.exit(1)
# Where we at?
... |
SecureBrain/JEB-sample-scripts | AlertMarker.py | Python | mit | 1,017 | 0.000983 | # JEB sample script
# http://www.android-decompiler.com/
#
# AlertMarker.py
# Set(unset) alert marker to focued method.
#
# Copyright (c) 2013 SecureBrain
from jeb.api import IScript
from jeb.api.dex import Dex
from jeb.api.ui import View
import string
class AlertMarker(IScript):
def run(self, jeb... | print 'unset alert'
md.setUserFlags(f & ~De | x.FLAG_ALERT)
view.refresh()
|
AppEnlight/channelstream | tests/tests_views.py | Python | bsd-3-clause | 21,292 | 0.00108 | from gevent import monkey
monkey.patch_all()
import pytest
import gevent
import marshmallow
from channelstream.server_state import get_state
from channelstream.channel import Channel
@pytest.mark.usefixtures("cleanup_globals", "pyramid_config")
class TestConnectViews(object):
def test_bad_json(self, dummy_reque... |
sorted_changed = sorted([x["key"] for x in result["changed_state"]])
assert sorted_changed == sorted(["bar", "private"])
@pytest.mark.usefixtures("cleanup_globals", "pyramid_config")
class TestSubscribeViews(object):
def test_bad_json(sel | f, dummy_request):
from channelstream.wsgi_views.server import subscribe
dummy_request.json_body = {}
try:
subscribe(dummy_request)
except marshmallow.exceptions.ValidationError as exc:
assert list(sorted(exc.messages.keys())) == ["channels", "conn_id"]
def ... |
Mrmaxmeier/BombSquad-Community-Mod-Manager | mods/BackToYou.py | Python | unlicense | 25,208 | 0.012734 | import bs
import random
import bsUtils
#import PlayerSpaz
def bsGetAPIVersion():
# see bombsquadgame.com/apichanges
return 4
def bsGetGames():
return [BackToYou]
class Icon(bs.Actor):
def __init__(self,player,position,scale,showLives=True,showDeath=True,
nameScale=1.0,nameM... | 'vAttach':'bottom'})
if self._showLives:
self._livesText = bs.newNode('text',
| owner=self.node,
attrs={'text':'x0',
'color':(1,1,0.5),
'hAlign':'left',
'vrDepth':430,
... |
Relin/LaZagne | Windows/src/LaZagne/softwares/chats/skype.py | Python | lgpl-3.0 | 4,298 | 0.034435 | from Crypto.Cipher import AES
import xml.etree.cElementTree as ET
import win32con, win32api, win32crypt
import base64, hashlib, os
import binascii, struct
from config.constant import *
from config.write_output import print_output, print_debug
from config.header import Header
from config.moduleInfo import Module... | def aes_encrypt(self, message, passphrase):
IV = '\x00\x00\x00\x00\x00\x00 | \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
aes = AES.new(passphrase, AES.MODE_CBC, IV)
return aes.encrypt(message)
# get value used to build the salt
def get_regkey(self):
try:
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Skype\\P... |
westpa/westpa | src/westext/adaptvoronoi/__init__.py | Python | mit | 82 | 0 |
from . import adaptVor_driver
from .adaptVor_driver import AdaptiveVoron | oiDrive | r
|
QingChenmsft/azure-cli | src/azure-cli-core/azure/cli/core/parser.py | Python | mit | 9,504 | 0.00263 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | ing as azlogging
logger = azlogging.get_az_logger(__name__)
class IncorrectUsageError(CLIError):
'''Raised when a command is incorrectly used and the usage should be
displayed to the user.
'''
pass
class CaseInsensitiveChoicesCompleter(argcomplete.completers.ChoicesCompleter): # pylint: disable=to... | wargs):
return (c for c in self.choices if c.lower().startswith(prefix.lower()))
# Override the choices completer with one that is case insensitive
argcomplete.completers.ChoicesCompleter = CaseInsensitiveChoicesCompleter
def enable_autocomplete(parser):
argcomplete.autocomplete = argcomplete.Completion... |
ubuntu-core/snapcraft | snapcraft/plugins/v1/crystal.py | Python | gpl-3.0 | 4,665 | 0.001501 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2019 Manas.Tech
# License granted by Canonical Limited
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# ... | "uniqueItems": True,
"items": {"type": "string"},
"default": [],
}
schema["required"] = ["source"]
return schema
@classmethod
def get_build_properties(cls):
return ["crystal-build-options"]
@classmethod
def get_pull_properties(cls):
| return ["crystal-channel"]
def __init__(self, name, options, project):
super().__init__(name, options, project)
if project._get_build_base() not in ("core", "core16", "core18"):
raise errors.PluginBaseError(
part_name=self.name, base=project._get_build_base()
... |
LouisPlisso/analysis_tools | old_create_hdf5_data_non_interacif.py | Python | gpl-3.0 | 2,240 | 0.003125 | import numpy as np
import h5py
f = h5py.File('hdf5/data_streaming.h5', 'w')
ADSL_2008 = f.create_group("ADSL_Montsouris_2008_07_01")
# retreve: ADSL_2008 = f['ADSL_Montsouris_2008_07_01']
gvb_adsl_2008 = np.load('python_flows/flows_marked_GVB_juill_2008_ADSL_cut_BGP_AS.npy')
ADSL_2008.create_dataset('GVB', data=gvb_... | = np.load('python_flows/dipcp_flows_FTTH_nov_2009.npy')
FTTH_nov_2009.create_dataset('dipcp', data=dipcp_ftth_nov_2009)
ADSL_dec_2009 = f.create_group("ADSL_Rennes_2009_12_14")
gvb_adsl_dec_2009 = n | p.load('python_flows/flows_marked_GVB_dec_2009_ADSL_BGP_AS.npy')
ADSL_dec_2009.create_dataset('GVB', data=gvb_adsl_dec_2009)
dipcp_adsl_dec_2009 = np.load('python_flows/dipcp_flows_ADSL_dec_2009.npy')
ADSL_dec_2009.create_dataset('dipcp', data=dipcp_adsl_dec_2009)
FTTH_dec_2009 = f.create_group("FTTH_Montsouris_2009_... |
byakatat/selenium-training | task19_PageObject/test_task19.py | Python | apache-2.0 | 498 | 0.002008 | from | task19_PageObject.MainPage import MainPage
def test_adding_and_deleting_from_cart(driver):
main_page = MainPage(driver)
main_page.open()
# Add 3 ducks to the cart in a loop
for i in range(1, 4):
# Click at the i-d duck
product_page = main_page.click_to_product_number(i)
produc... | cart_page.remove_all_items_from_cart()
|
jiasir/openstack-trove | lib/charmhelpers/contrib/openstack/ip.py | Python | mit | 2,332 | 0 | from charmhelpers.core.hookenv import (
config,
unit_get,
)
from charmhelpers.contrib.network.ip import (
get_address_in_network,
is_address_in_network,
is_ipv6,
get_ipv6_addr,
)
from charmhelpers.contrib.hahelpers.cluster import is_clustered
PUBLIC = 'public'
INTERNAL = 'int'
ADMIN = 'admin'... | dress_map[endpoint_type]['config']),
vip):
resolved_address = vip
else:
if config('prefer-ipv6'):
fallback_addr = get_ipv6_addr()
else:
fallback_addr = unit_get(_address_map[endpoint_type]['fallback'])
resolved_address = get... | network(
config(_address_map[endpoint_type]['config']), fallback_addr)
if resolved_address is None:
raise ValueError('Unable to resolve a suitable IP address'
' based on charm state and configuration')
else:
return resolved_address
|
kevin-coder/tensorflow-fork | tensorflow/python/autograph/impl/conversion_test.py | Python | apache-2.0 | 6,484 | 0.005244 | # Copyright 2017 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... | ass TestSubclass(TestBase):
def __init__(self, y):
super(TestSubclass, self).__init__('sub')
self.y = y
def foo(self):
return self.y
def baz(self):
return self.y
program_ctx = self._simple_program_ctx()
with self.assertRaisesRegex(NotImplementedError, 'class... | class_hierarchy_whitelisted(self):
class TestSubclass(training.Model):
def __init__(self, y):
super(TestSubclass, self).__init__()
self.built = False
def call(self, x):
return 3 * x
program_ctx = self._simple_program_ctx()
(import_node, class_node), name, _ = conversi... |
alexandrul-ci/robotframework | src/robot/parsing/populators.py | Python | apache-2.0 | 8,341 | 0.001079 | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | type](table) \
if table is not None else NullPopulator()
return bool(self._populator)
def eof(self):
self._populator.populate()
def add(self, row):
if PROCESS_CURDIR and self._curdir:
row = self._replace_curdirs_in(row)
data = DataRow(row)
if... | CURDIR}', self._curdir) for cell in row]
class FromDirectoryPopulator(object):
ignored_prefixes = ('_', '.')
ignored_dirs = ('CVS',)
def populate(self, path, datadir, include_suites=None,
warn_on_skipped=False, include_extensions=None, recurse=True):
LOGGER.info("Parsing test dat... |
jawilson/home-assistant | tests/components/usb/__init__.py | Python | apache-2.0 | 753 | 0 | """Tests for the USB Discovery integration. | """
from homeassistant.components.usb.models import USBDevice
conbee_device = USBDevice(
device="/dev/cu.usbmodemDE24338801",
vid="1CF1",
pid="0030",
serial_number="DE2433880",
manufacturer="dresden elektronik ingenieurtechnik GmbH",
description="ConBee II",
)
slae_sh_device = USBDevice(
... | pid="EA60",
serial_number="00_12_4B_00_22_98_88_7F",
manufacturer="Silicon Labs",
description="slae.sh cc2652rb stick - slaesh's iot stuff",
)
electro_lama_device = USBDevice(
device="/dev/cu.usbserial-110",
vid="1A86",
pid="7523",
serial_number=None,
manufacturer=None,
description=... |
iamsteadman/bambu-mail | bambu_mail/receivers.py | Python | apache-2.0 | 217 | 0.036866 | from bambu_mail.shortcuts import subscribe
def newsletter_op | tin | (sender, user, **kwargs):
subscribe(
user.email,
list_id = 'signup',
double_optin = False,
send_welcome = False
) |
titiushko/readthedocs.org | readthedocs/doc_builder/constants.py | Python | mit | 491 | 0.002037 | '''Doc build constants'''
from django.conf i | mport settings
from django.utils.translation import ugettext_lazy as _
DOCKER_SOCKET = getattr(settings, 'DOCKER_SOCKET', 'unix:///var/run/docker.sock')
DOCKER_VERSION = getattr(settings, 'DOCKER_VERSION', 'auto')
DOCKER_IMAGE = getattr(settings, 'DOCKER_IMAGE', 'rtfd-build')
DOCKER_LI | MITS = {'memory': '200m', 'time': 600}
DOCKER_LIMITS.update(getattr(settings, 'DOCKER_LIMITS', {}))
DOCKER_TIMEOUT_EXIT_CODE = 42
DOCKER_OOM_EXIT_CODE = 137
|
nikitanovosibirsk/district42 | tests/dict/test_dict_keys.py | Python | mit | 572 | 0 | from typing import KeysView
from baby_steps import given, then, when
from district42 import optional, schema
def test_dict_empty_keys():
with given:
sch = schema.dict
| with when:
res = sch.keys()
with then:
assert res == KeysView([])
def test_dict_keys():
with given:
sch = schema.dict({
"id": schema.int,
"name": schema.str,
optional("email"): schema.str,
})
with when:
res = sch.keys()
w... | "name", "email"])
|
petrlosa/ella | ella/core/south_migrations/0005_auto__add_field_category_content__add_field_category_template.py | Python | bsd-3-clause | 11,864 | 0.008092 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Category.content'
db.add_column('core_category', 'content', self.gf('django.db.models.fields.TextF... | 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'tree_parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Category']", 'null': 'True', 'blank': 'True'}),
'tree_path': ('django.db.models.fields.CharField', [], {'max_length': '255'})
... | 'related_name': "'depends_on_set'", 'to': "orm['contenttypes.ContentType']"}),
'dependent_id': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'target_ct': ('django.db.models.fields.related.ForeignKey', [], {... |
jamestwebber/scipy | scipy/special/tests/test_wrightomega.py | Python | bsd-3-clause | 3,616 | 0.000277 | from __future__ import division, print_function, absolute_import
import pytest
import numpy as np
from numpy.testing import assert_, assert_equal, assert_allclose
import scipy.special as sc
from scipy.special._testutils import assert_func_equal
def test_wrightomega_nan():
pts = [complex(np.nan, 0),
c... | for p in pts:
res = sc.wrightomega(p)
assert_equal(res, -1.0)
assert_(np.signbit(res.imag) == False)
@pytest.mark.parametrize('x, desired', [
(-np.inf, 0),
(np.inf, np.inf),
])
def test_wrightomega_real_infinities(x, desired):
assert sc.wrightomega( | x) == desired
def test_wrightomega_real_nan():
assert np.isnan(sc.wrightomega(np.nan))
def test_wrightomega_real_series_crossover():
desired_error = 2 * np.finfo(float).eps
crossover = 1e20
x_before_crossover = np.nextafter(crossover, -np.inf)
x_after_crossover = np.nextafter(crossover, np.inf)
... |
haozhangphd/genx-py3 | genx/models/sxrd_mult.py | Python | gpl-3.0 | 12,753 | 0.008469 | '''<h1>Library for surface x-ray diffraction simulations of superlattices</h1>
<p> The model is based on Fullertons algorithm for superlattices as
described in Phys. Rev. B vol. 45 p. 9292 (1992).
'''
# Programmed by Matts Bjorck 20091215
import numpy as np
import genx.models.sxrd
from genx.models.utils import f, rho... | sym):
'''Extracts the necessary parameters for simulating
a list of stacked slabs
'''
# Extract the parameters we need
# the star in zip(*.. | . transform the list elements to arguments
xt, yt, zt, elt, ut, oct, ct = list(zip(*[slab._extract_values()
for slab in slabs]))
x = np. r_[xt]
y = np.r_[yt]
# scale and shift the slabs with respect to each other
cn = np.cumsum(np.r_[0, c... |
bcpki/bitcoin | src/bcert/examples/mk_foo1_static.py | Python | mit | 2,934 | 0.023177 | #!/usr/bin/python
import sys
sys.path.append('..')
from bcert_pb2 import *
import binascii
# fill out a minimal bit | coin cert
cert = BitcoinCert()
# first the | data part (the part is later signed by the "higher level cert" or "the blockchain")
cert.data.version = '0.1'
cert.data.subjectname = 'Foo Inc.'
email = cert.data.contacts.add()
email.type = email.EMAIL
email.value = 'foo@fooinc.com'
url = cert.data.contacts.add()
url.type = url.URL
url.value = 'http://www.fooinc.com'... |
carlyeks/cassandra-dtest | cqlsh_tests/cqlsh_tools.py | Python | apache-2.0 | 2,124 | 0.001883 | import csv
im | port random
import cassandra
from nose.tools import assert_items_equal
class DummyColorMap(object):
def __getitem__(self, *args):
return ''
def csv_rows(filename, delimiter=None):
"""
Given a filename, opens a csv file and yields it line by line.
"""
reader_opts = {}
if delimiter i... | ert_csvs_items_equal(filename1, filename2):
with open(filename1, 'r') as x, open(filename2, 'r') as y:
assert_items_equal(list(x.readlines()), list(y.readlines()))
def random_list(gen=None, n=None):
if gen is None:
def gen():
return random.randint(-1000, 1000)
if n is None:
... |
wintoncode/winton-kafka-streams | winton_kafka_streams/state/logging/store_change_logger.py | Python | apache-2.0 | 503 | 0.001988 | class StoreChangeLogger:
def __init__(self, store_name, context) -> None:
self.topic = f'{context.ap | plication_id}-{store_name}-changelog'
self.context = context
self.partition = context.task_id.partition
self.record_collector = context.state_record_collector
def log_change(self, key: bytes, value: bytes) -> None:
if self.record_collector:
self.record_collector.send(sel... | partition)
|
geobricks/geobricks_qgis_plugin_trmm | __init__.py | Python | gpl-2.0 | 1,510 | 0 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
GeobricksTRMM
A QGIS plugin
Download TRMM daily data.
-------------------
begin : 2015-10-06
copyright : (C) ... | *
*************************************************** | ************************/
This script initializes the plugin, making it known to QGIS.
"""
# noinspection PyPep8Naming
def classFactory(iface): # pylint: disable=invalid-name
"""Load GeobricksTRMM class from file GeobricksTRMM.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
... |
wfxiang08/django178 | tests/validators/tests.py | Python | bsd-3-clause | 14,190 | 0.000918 | # -*- coding: utf-8 -*-
from __future__ import unicode_liter | als
from datetime import datetime, timedelta
import re
import types
from unittest import TestCase
from django.core.exceptions import ValidationError
from django.core.val | idators import (
BaseValidator, EmailValidator, MaxLengthValidator, MaxValueValidator,
MinLengthValidator, MinValueValidator, RegexValidator, URLValidator,
validate_comma_separated_integer_list, validate_email, validate_integer,
validate_ipv46_address, validate_ipv4_address, validate_ipv6_address,
v... |
TwilioDevEd/api-snippets | notifications/register/send-notification/send-notification.7.x.py | Python | mit | 528 | 0 | #!/usr/bin/env python
# Install | the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# To set up environmental variables, see http://twil.io/secure
ACCOUNT_SID = os.environ['TWILIO_ACCOUNT_SID']
AUTH_TOKEN = os.environ['TWILIO_AUTH_TOKEN']
client = Client(ACCOUNT_SID, AUTH_TOKEN)
notification = cl... | XXXXXXXXXXXXXXXXXX') \
.notifications.create(identity='00000001',
body='Hello Bob')
print(notification.sid)
|
sjperkins/tensorflow | tensorflow/tensorboard/backend/event_processing/plugin_asset_util.py | Python | apache-2.0 | 3,278 | 0.006406 | # Copyright 2017 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... | ow summary.FileWriter.
plugin_name: The plugin we want an asset from.
asset_name: The name of the requested asset.
Returns:
string contents of the plugin asset.
Raises:
KeyError: if the asset does not exist.
"""
asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name)
try... | tf.gfile.Open(asset_path, "r") as f:
return f.read()
except tf.errors.NotFoundError:
raise KeyError("Asset path %s not found" % asset_path)
except tf.errors.OpError as e:
raise KeyError("Couldn't read asset path: %s, OpError %s" % (asset_path, e))
|
yuuagh/pywork | 20171127/go.py | Python | gpl-3.0 | 4,158 | 0.015506 | # -*- coding:utf-8 -*-
# @author yuding
# 2017-09-23
import re
import os
import shutil
import msvcrt
import traceback
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
... | .compile(newpattern, re.S|re.I)
# 数据存入字典中
dic = {}
geneDic = {}
| for unit in result:
result2 = p2.findall(unit)
value = re.split(',', result2[0][0])
key = result2[0][1]
dic[key] = value
geneDic[key] = result2[0][2]
return (dic, geneDic)
# 获得替换的内容
def getContent(fname):
tf = open(f... |
marios-zindilis/musicbrainz-django-models | musicbrainz_django_models/models/area_attribute.py | Python | gpl-2.0 | 1,946 | 0.004111 | """
.. module:: area_attribute
The **Area Attribute** Model.
PostgreSQL Definition
---------------------
The :code:`area_attribute` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE area_attribute ( -- replicate | (verbose)
id SERIAL, -- PK
area INTEGER NOT NULL, -- references area.id
area_attribute_type INTEGER NOT | NULL, -- references area_attribute_type.id
area_attribute_type_allowed_value INTEGER, -- references area_attribute_type_allowed_value.id
area_attribute_text TEXT
CHECK (
(area_attribute_type_allowed_value IS NULL AND area_attribute_text IS NOT NULL)
OR
... |
aliyun/aliyun-oss-python-sdk | oss2/credentials.py | Python | mit | 4,941 | 0.003036 | # -*- coding: utf-8 -*-
import time
import requests
import json
import logging
import threading
from .exceptions import ClientError
from .utils import to_unixtime
from .compat import to_unicode
logger = logging.getLogger(__name__)
class Credentials(object):
def __init__(self, access_key_id="", access_key_secret... | return self.credentials
class EcsRamRoleCredentialsFetcher(object):
def __init__(self, auth_host):
self.auth_host = auth_host
def fetch(self, retry_times=3, timeout=10):
for i in range(0, retry_times):
try:
response = requests.get(self.auth_host, timeout=timeo... | at(response.status_code,
response.text))
dic = json.loads(to_unicode(response.content))
code = dic.get('Code')
access_key_id = dic.get('AccessKeyId')
access_key_secret... |
bl8/bockbuild | packages/clutter.py | Python | mit | 136 | 0.058824 | GnuXzPackage ('clutter', '1.10.6',
sources = [ 'http://source.cl | utter-project.org/sources/clutter/1.10/% | {name}-%{version}.tar.xz' ],
)
|
montyly/manticore | examples/script/introduce_symbolic_bytes.py | Python | apache-2.0 | 2,875 | 0.001043 | #!/usr/bin/env python
import sys
from manticore import issymbolic
from manticore.native import Manticore
"""
Replaces a variable that controls program flow with a tainted symbolic value. This
in turn explores all possible states under that variable's influence, and reports the
specific cmp/test instructions can be i... | 85 c0 test %eax,%eax
#
| print(f"introducing symbolic value to {state.cpu.RBP-0xc:x}")
val = state.new_symbolic_value(32, taint=(taint_id,))
state.cpu.write_int(state.cpu.RBP - 0xC, val, 32)
def has_tainted_operands(operands, taint_id):
# type: (list[manticore.core.cpu.abstractcpu.Operand], object) -> bool
... |
jorgenschaefer/healthmonitor | fabfile.py | Python | agpl-3.0 | 1,805 | 0 | # Fabric file for the health monitor.
#
# This should only be used for deployment tasks. make should be
# sufficient for development.
import os
from fabric.api import env, task, roles, lcd, local, run, put
BASE_DIR = os.path.dirname(__file__)
env.path = ":".join([
'/home | /forcer/bin/',
os.path.join(BASE_DIR, "node_modules/.bin/")
])
env.roledefs = {
'production': ['healthmonitor@loki']
}
@task
@roles('production')
def deploy():
run("test -d venv || pyvenv-3.4 venv")
run("test -f venv/lib/python3.4/site-packages/_healthmonitor.pth || "
"echo $HOME/lib > venv/l | ib/python3.4/site-packages/_healthmonitor.pth")
run("mkdir -p health.jorgenschaefer.de/static/")
run("mkdir -p lib/")
local("git archive -o deploy.tar.gz HEAD")
put("deploy.tar.gz")
local("rm deploy.tar.gz")
run("tar -C lib/ -xzf deploy.tar.gz")
run("rm deploy.tar.gz")
local("bower ins... |
fabian-paul/PyEMMA | pyemma/coordinates/clustering/regspace.py | Python | lgpl-3.0 | 6,283 | 0.002547 |
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either vers... | ,
clustercenters, self.n_jobs)
self._converged = True
except regspace | .MaxCentersReachedException:
self._converged = False
msg = 'Maximum number of cluster centers reached.' \
' Consider increasing max_centers or choose' \
' a larger minimum distance, dmin.'
self.logger.warning(msg)
warnings.warn(msg)
... |
matzika/article-tagger-system | words_similarity_detector.py | Python | gpl-2.0 | 3,189 | 0.007839 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 11:57:45 2016
@author: katerinailiakopoulou
"""
import gensim
import logging
import sys
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
"""
The Finder finds which words are similar to the one given
based on the word2vec wo... | t_file.write(str(e))
self.output_file.write('\n')
def get_pos_similar(self,input):
self.output_file.write('--- Similar words to: ' + input + '---\n')
poss = input.split('AND')
positives = []
for p in poss:
positives.append(p.strip())
try:
... | elf.output_file.write('\n')
def get_similarity(self,input):
self.output_file.write('--- Similarity between: ' + input + '---\n')
parts = input.split('-')
try:
self.output_file.write(str(self.m.similarity(parts[0], parts[1])))
except KeyError as e:
sel... |
adsorensen/girder | plugins/terms/server/__init__.py | Python | apache-2.0 | 3,937 | 0.003048 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file ex | cept in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,... | guage governing permissions and
# limitations under the License.
###############################################################################
import datetime
import hashlib
from girder import events
from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest i... |
ardi69/pyload-0.4.10 | pyload/plugin/crypter/Dereferer.py | Python | gpl-3.0 | 584 | 0.017123 | # -*- coding: utf-8 -*-
from pyload.plugin.Crypter import Crypter
class Dereferer(SimpleDereferer):
__name = "Dereferer"
| __type = "crypter"
__version = "0.11"
__pattern = r'https?://([^/]+)/.*?(?P<LINK>(ht|f)tps?(://|%3A%2F%2F).+)'
__config = [("use_subfolder" , "bool", "Save package to subfolder" , True),
("subfolder_per_pack", "bool", "Create a subfolder for each package", True)]
... | referers"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
|
chromium/chromium | testing/merge_scripts/code_coverage/merge_lib_test.py | Python | bsd-3-clause | 1,506 | 0.007968 | #!/usr/bin/env vpython
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-s | tyle license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
import unittest
import mock
import merge | _lib as merger
class MergeLibTest(unittest.TestCase):
# pylint: disable=super-with-arguments
def __init__(self, *args, **kwargs):
super(MergeLibTest, self).__init__(*args, **kwargs)
self.maxDiff = None
# pylint: enable=super-with-arguments
@mock.patch.object(subprocess, 'check_output')
def test_va... |
GroestlCoin/electrum-grs | electrum_grs/plugins/bitbox02/bitbox02.py | Python | gpl-3.0 | 27,314 | 0.002123 | #
# BitBox02 Electrum plugin code.
#
import hid
from typing import TYPE_CHECKING, Dict, Tuple, Optional, List, Any, Callable
from electrum_grs import bip32, constants
from electrum_grs.i18n import _
from electrum_grs.keystore import Hardware_KeyStore
from electrum_grs.transaction import PartialTransaction
from electr... | p32.convert_bip32_path_to_list_of_uint32(derivation)
xpub = self.bitbox02_device.electrum_encryption_key(derivation_list)
node = bip32.BIP32No | de.from_xkey(xpub, net = constants.BitcoinMainnet()).subkey_at_public_derivation(())
return node.eckey.get_public_key_bytes(compressed=True).hex()
@runs_in_hwd_thread
def get_xpub(self, bip32_path: str, xtype: str, *, display: boo |
etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/PyInstaller/hooks/hook-gi.repository.Champlain.py | Python | gpl-3.0 | 702 | 0.002849 | #-----------------------------------------------------------------------------
# Copyright (c) 2005-2020, PyInstaller Development Team.
#
# Dis | tributed 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: (GPL-2.0-or-later WITH Bootloader-exception)
#----------------------------------... | ooks import get_gi_typelibs
binaries, datas, hiddenimports = get_gi_typelibs('Champlain', '0.12')
|
kevinhikali/ml_kevin | tf/tf_cast.py | Python | gpl-3.0 | 250 | 0 | # -*- coding: utf-8 -*-
"""
@autho | r: kevinhikali
@email: hmingwei@gmail.com
"""
import tensorflow as tf
A = [[1, 2, 3, 4]]
B = [[2, 2, 3, 4]]
casted = tf.cast(tf.equal(A, B), dtype='float32') |
with tf.Session() as sess:
print(sess.run(casted))
|
bbcf/bsPlugins | tests/test_Annotate.py | Python | gpl-3.0 | 717 | 0.011158 | from unittest2 import TestCase, skip
from bsPlugins.Annotate import AnnotatePlugin
import os
path = 'testing_files/'
class Test_AnnotatePlugin(TestCase):
def setUp(self):
self.plugin = AnnotatePlugin()
def test_with_signals(self):
s | elf.plugin(**{'track':path+'KO50.bedGraph', 'assembly':'mm9',
'promoter':0, 'intergenic':0, 'UTR':0})
with open(self.plugin.output_files[0][0],'rb') as f:
content = f.readlines()
self.assertEqual(len(content),50)
def tearDown(self):
for f in os.listdir... | s --logging-filter=-tw2 test_Annotate.py
|
mrquim/mrquimrepo | repo/plugin.video.live.magellan/unCaptcha.py | Python | gpl-2.0 | 14,966 | 0.029467 | # -*- coding: utf-8 -*-
import random
import re
import time
import urlparse, urllib,urllib2,cookielib
from base64 import b64encode
import xbmc
import xbmcgui,xbmcaddon,os
__scriptID__ = 'plugin.video.live.magellan'
__addon__ = xbmcaddon.Addon(__scriptID__)
class cInputWindow(xbmcgui.WindowDialog):
def __init__(s... | cgui.ControlButton(imgX+pw+pw,imgY, pw, ph, '3', font='font1');#,focusTexture=check_image ,noFocusTexture=uncheck_image);#,checkWidth=220,checkHeight=150)
self.chkbutton[3]= xbmcgui.ControlButton(imgX,imgY+ | ph, pw, ph, '4', font='font1');#,focusTexture=check_image ,noFocusTexture=uncheck_image);#,checkWidth=220,checkHeight=150)
self.chkbutton[4]= xbmcgui.ControlButton(imgX+pw,imgY+ph, pw, ph, '5', font='font1');#,focusTexture=check_image ,noFocusTexture=uncheck_image);#,checkWidth=220,checkHeight=150)
self... |
scikit-image/skimage-demos | mm_color_cluster.py | Python | bsd-3-clause | 2,030 | 0.000985 | # Auto-clustering, suggested by Matt Terry
from skimage import io, color, exposure
from sklearn import cluster, preprocessing
import numpy as np
import matplotlib.pyplot as plt
url = 'http://blogs.mathworks.com/images/steve/2010/mms.jpg'
import os
if not os.path.exists('mm.jpg'):
print("Downloading M&M's...")
... | x):
ax.set_xticks([])
ax.set_yticks([])
# Display all clusters
for i | in range(N):
mask = (labels == i)
mm_cluster = mm_lab.copy()
mm_cluster[..., 1:][~mask] = 0
ax = plt.subplot2grid((2, N), (1, i))
ax.imshow(color.lab2rgb(mm_cluster))
no_ticks(ax)
ax = plt.subplot2grid((2, N), (0, 0), colspan=2)
ax.imshow(mm)
no_ticks(ax)
# Display histogram
L, a, b = mm_... |
allenai/allennlp | allennlp/modules/seq2vec_encoders/seq2vec_encoder.py | Python | apache-2.0 | 1,215 | 0.005761 | from allennlp.modules.encoder_base import _EncoderBase
from allennlp.common import Registrable
class Seq2VecEncoder(_EncoderBase, Registrable):
"""
A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a
single vector. Input shape : `(batch_size, sequence_length, input_di... | entedError
def get_output_dim(sel | f) -> int:
"""
Returns the dimension of the final vector output by this `Seq2VecEncoder`. This is `not`
the shape of the returned tensor, but the last element of that shape.
"""
raise NotImplementedError
|
william-fiset/Survival | __init__.py | Python | apache-2.0 | 79 | 0.012658 | f | rom .main import main
# run the program
if __name__ == '__main__':
main( | ) |
SelvorWhim/competitive | Codewars/PrincipalDiagonalVsSecondaryDiagonal.py | Python | unlicense | 396 | 0.007576 | def sum_diagonal_principal(matrix):
return sum(matrix[i][i] for i in range(len(matrix)))
def sum_diagonal_secondary(matrix):
return sum(matrix[i][-i-1] for i in range(len(matrix)))
def diagonal(matrix):
s1 = sum_diagonal_principal(matrix)
s2 = sum_diagonal_secondary(matrix)
| return "Principal Diagonal win!" if s1 > s2 else "Secondary Diagonal win!" | if s1 < s2 else "Draw!"
|
AlexWPerfComm/Python-JIRA | const/Constants.py | Python | mit | 65 | 0 | AUTH_URL = "https://quality.hubwoo.com/rest/auth/latest/s | essi | on"
|
squilter/ardupilot | libraries/AP_MSP/Tools/pymsp.py | Python | gpl-3.0 | 18,847 | 0.014114 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: Alex Apostoli
based on https://github.com/hkm95/python-multiwii
which is under GPLv3
"""
import struct
import time
import sys
import re
class MSPItem:
def __init__(self, name, fmt, fields):
self.name = name
self.format ... | repeat is not None:
for i in range(len(fields)):
self.values[fields[i]] = []
for j in range(repeat):
self.values[fields[i]].append(values[j*len(fields)])
else:
for i in range(len(fields)):
... | self.values[fields[i]] = values[i]
dataSize -= fmt_size
ofs += fmt_size
msp.by_name[self.name] = self
#print("Got %s" % self.name)
class PyMSP:
""" Multiwii Serial Protocol """
OSD_RSSI_VALUE = 0
OSD_MAIN_BATT_VOLTAGE = 1
OSD_CROSSH... |
imankulov/gevent-websocket | setup.py | Python | bsd-3-clause | 946 | 0.002114 | from setuptools import setup, find_packages
setup(
name="gevent-websocket",
version="0.3.6",
description="Websocket handler for the gevent pywsgi server, a Python network library",
long_description=open("README.rst").read(),
author="Jeffrey Gelens",
author_email="jeffrey@noppo.pro",
license... | d_packages(exclude=["examples","tests"]),
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Operating System :: | MacOS :: MacOS X",
"Operating System :: POSIX",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
],
)
|
OWStimpson/oscar_webstore | oscar_webstore_root/forked_apps/catalogue/__init__.py | Python | bsd-3-clause | 68 | 0 | default_app_config = 'fork | ed_apps.catalogue.config.Catal | ogueConfig'
|
Teekuningas/mne-python | mne/io/nirx/nirx.py | Python | bsd-3-clause | 13,599 | 0 | # Authors: Robert Luke <mail@robertluke.net>
#
# License: BSD (3-clause)
from configparser import ConfigParser, RawConfigParser
import glob as glob
import re as re
import os.path as op
import numpy as np
from ..base import BaseRaw
from ..constants import FIFF
from ..meas_info import create_info, _format_dig_points
f... | rmat version is supported
if not any(item == hdr['GeneralInfo']['NIRStar'] for item in
["\"15.0\"", "\ | "15.2\""]):
raise RuntimeError('MNE does not support this NIRStar version'
' (%s)' % (hdr['GeneralInfo']['NIRStar'],))
if "NIRScout" not in hdr['GeneralInfo']['Device']:
warn("Only import of data from NIRScout devices have been "
"thoroughl... |
qma/pants | src/python/pants/backend/python/tasks/checkstyle/plugin_subsystem_base.py | Python | apache-2.0 | 886 | 0.006772 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.subsystem... | .
register('--skip', default=False, | action='store_true',
help='If enabled, skip this style checker.')
def get_plugin(self, python_file):
return self.get_plugin_type()(self.get_options(), python_file)
def get_plugin_type(self):
raise NotImplementedError('get_plugin() not implemented in class {}'.format(type(self)))
|
jamesbdunlop/defaultMayaLibrary | tools/rigComponentBuilder.py | Python | apache-2.0 | 4,466 | 0.005598 | import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
import maya.cmds as cmds
import constants as const
import rigBuildLib as complib
reload(complib)
class Component(object):
def __init__(self):
self.cmpdata = {}
self.compName = None
self.compSide = None
self.... | eturn self.compName
@property
def side(self):
return self.compSide
@property
def color(self):
return self.compCo | lor
def setCompColor(self):
if self.side == "L":
self.compColor = 14
elif self.side == "R":
self.compColor = 13
else:
self.compColor = 25
def addCustomInput(self, name):
grpName = "{}_input".format(name)
inputGrp = complib.createGroup... |
alexlo03/ansible | test/units/modules/network/f5/test_bigip_gtm_pool.py | Python | gpl-3.0 | 11,200 | 0.000446 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# 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
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... | ortError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python libr | ary")
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
... |
informatics-isi-edu/deriva-py | deriva/transfer/backup/__main__.py | Python | apache-2.0 | 361 | 0.00554 | import sys
from deriva.transfer import DerivaBackupCLI
DESC = "Deriva Catalog Backup Utility - CLI"
INFO = "For m | ore information see: https://github.com/informatics-isi-edu/deriva-py"
def mai | n():
cli = DerivaBackupCLI(DESC, INFO, hostname_required=True, config_file_required=False)
return cli.main()
if __name__ == '__main__':
sys.exit(main())
|
emmuchira/kps_erp | erpnext/accounts/party.py | Python | gpl-3.0 | 16,798 | 0.025063 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import datetime
from frappe import _, msgprint, scrub
from frappe.defaults import get_user_permissions
from frappe.model.utils import get... | Company"))
if party:
account = frappe.db.get_value("Party Account",
{"parenttype": party_type, "parent": party, "company": company}, "account")
if not account and party_type in ['Customer', 'Supplier' | ]:
party_group_doctype = "Customer Group" if party_type=="Customer" else "Supplier Type"
group = frappe.db.get_value(party_type, party, scrub(party_group_doctype))
account = frappe.db.get_value("Party Account",
{"parenttype": party_group_doctype, "parent": group, "company": company}, "account")
if not a... |
jameshiew/dj-stripe | djstripe/utils.py | Python | mit | 4,844 | 0.002685 | # -*- coding: utf-8 -*-
"""
.. module:: djstripe.utils.
:synopsis: dj-stripe - Utility functions related to the djstripe app.
.. moduleauthor:: @kavdev, @pydanny, @wahuneke
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
from django.conf import setti | ngs
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ImproperlyConfigured
from django.db.models.query import QuerySet
from django.utils import timezone
ANONYMOUS_USER_ERROR_MSG = (
"dj-stripe's payment checking mechanisms requir... | go.contrib.auth's "
"login_required decorator or a LoginRequiredMixin. "
"Please read the warning at "
"http://dj-stripe.readthedocs.org/en/latest/usage.html#ongoing-subscriptions."
)
def subscriber_has_active_subscription(subscriber, plan=None):
"""
Helper function to check if a subscriber has an... |
roadmapper/ansible | lib/ansible/modules/cloud/vmware/vmware_deploy_ovf.py | Python | gpl-3.0 | 22,956 | 0.002701 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Matt Martz <matt@sivel.net>
#
# 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'... | Length': self.si | ze,
'Content-Type': 'application/octet-stream',
}
if self._create:
# Non-VMDK
method = 'PUT'
headers['Overwrite'] = 't'
else:
# VMDK
method = 'POST'
headers['Content-Type'] = 'application/x-vnd.vmware-streamVmdk... |
sserkez/ocelot | mint/flash_tune.py | Python | gpl-3.0 | 2,806 | 0.024947 | '''
main tuning script, LCLS
'''
import numpy as np
from ocelot.mint.mint import Optimizer, Action
from ocelot.mint.flash1_interface import FLASH1MachineInterface, FLASH1DeviceProperties, TestInterface
mi = FLASH1MachineInterface()
dp = FLASH1DeviceProperties()
#opt = Optimizer(mi, dp)
opt = Optimizer(TestInterfac... | ['H3SFELC', 'H4SFELC', 'H10SMATCH', 'D11SMATCH', 'H12SMATCH']
setup = log.MachineSetup()
#setup.save_lattice(lat, "init.txt")
lat_all = MagneticLattice(lattice)
setup.load_lattice("init.txt", lat_all)
or | bit["bpms"] = get_dict(lat, bpms)
seq_min_orb = [Action(func=opt.min_orbit, args=[orbit, 'simplex' ] )]
opt.eval(seq_bump)
apply_bump(cors, currents, dI, alpha=0.1)
"""
|
delmic/odemis | src/odemis/gui/conf/test/conf_test.py | Python | gpl-2.0 | 6,386 | 0.001097 | # -*- coding: utf-8 -*-
"""
:created: 27 Aug 2014
:author: Éric Piel
:copyright: © 2014 Éric Piel, Delmic
This file is part of Odemis.
.. license::
Odemis is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License version 2 as published by the Free Software ... | en(conf.last_extension), 12)
def test_save(self):
# Will fail if setting the properties goes wrong
conf = gui.conf.get_acqui_conf()
conf.last_path = u"/home/booo/"
conf.last_format = "HDF5"
conf.last_extension = ".h5"
conf.f | n_ptn = u"{timelng}-test {cnt}"
def test_save_unicode(self):
conf = gui.conf.get_acqui_conf()
conf.last_path = u"/home/boooµ/"
conf.last_format = "HDF5"
conf.last_extension = ".h5"
conf.fn_ptn = u"{timelng}-test {cnt} µm value"
class CalibrationConfigTest(ConfigTest, unitt... |
marcuschia/ShaniXBMCWork | other/livetvPlayer.py | Python | gpl-2.0 | 7,065 | 0.045294 | # -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin
import urllib2,urllib,cgi, re
import HTMLParser
import xbmcaddon
import json
import traceback
import os
import cookielib
from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP
import datetime
import sys
import time
import CustomPlayer
import c... | )
player = CustomPlayer.MyXBMCPlayer()
start = time.time()
#xbmc.Player().play( liveLink,listitem)
player.play( liveLink,listitem)
while player.is_active:
xbmc.sleep(200)
#return player.urlplayed
#done = time.time()
done = time.time()
elapsed = done - start
if player.urlplayed and elapsed>=3:
... | link=getUrl('http://www.livetv.tn/index.php',cookieJar)
captcha=None
match =re.findall('<img src=\"(.*?)\" alt=\"CAPT', link)
if len(match)>0:
captcha="http://www.livetv.tn"+match[0]
else:
captcha=None
solution=None
if captcha:
local_captcha = os.path.join(profile_path, "captchaC.img" )
localFile = op... |
Chasego/codirit | jiuzhang/Nine Chapters/3 Binary Tree & Divide Conquer/py/BalancedBinaryTree_rec.py | Python | mit | 873 | 0.001145 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# ... | if root is None:
return True, 0
l, r = root.left, root.right
l_balanced, l_h = | self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0
|
scribusproject/scribus-tools | resource-checker/scribus-services-check.py | Python | gpl-3.0 | 408 | 0.009804 | # This script will check http://services.scribus.net for broken assets
import lxml.html
url = "http://services.scribus.net"
doc = lxml.ht | ml.parse(url)
# pattern matching for relative urls: <a href="scribus_fonts.xml">
content_parsed = doc.xpath('href')
# also ignore scribusversions.xml
# Create a scraper class to feed .xml page results to
# Create a function that mails an admin when a r | esult 404s
|
jreback/pandas | pandas/tests/indexing/test_datetime.py | Python | bsd-3-clause | 7,714 | 0.001037 | import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Index, Series, Timestamp, date_range
import pandas._testing as tm
class TestDatetimeIndex:
def test_indexing_with_datetime_tz(self):
# GH#8260
# support datetime64 with tz
idx = Index(date_range("20130101... | tamp("2011-01-02"),
Timestamp( | "2011-01-02"),
Timestamp("2011-01-01"),
]
if to_period:
keys = [x.to_period("D") for x in keys]
exp = Series(
[0.2, 0.2, 0.1], index=Index(keys, name="idx", dtype=idx.dtype), name="s"
)
result = ser.loc[keys]
tm.assert_series_equal(resu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.