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 |
|---|---|---|---|---|---|---|---|---|
DoubleNegativeVisualEffects/cortex | test/IECoreHoudini/FromHoudiniPointsConverter.py | Python | bsd-3-clause | 39,834 | 0.052945 | ##########################################################################
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary ... | .parm("class").set(3)
vert_f3.parm("size").set(3)
vert_f3.parm("value1").setExpression("$VTX*0.1")
vert_f3.parm("value2").setExpression("$VTX*0.1")
vert_f3.parm("value3").setExpression("$VTX*0.1")
vert_f3.setInput( 0, vert_f2 )
vert_i1 = geo.createN | ode( "attribcreate", node_name = "vert_i1", exact_type_name=True )
vert_i1.parm("name").set("vert_i1")
vert_i1.parm("class").set(3)
vert_i1.parm("type").set(1)
vert_i1.parm("value1").setExpression("$VTX*0.1")
vert_i1.setInput( 0, vert_f3 )
vert_i2 = geo.createNode( "attribcreate", node_name = "vert_i2", ex... |
ovnicraft/openerp-restaurant | website_sale/models/product_characteristics.py | Python | agpl-3.0 | 3,642 | 0.006315 |
from openerp.osv import osv, fields
class attributes(osv.Model):
_name = "product.attribute"
def _get_float_max(self, cr, uid, ids, field_name, arg, context=None):
result = dict.fromkeys(ids, 0)
if ids:
cr.execute("""
SELECT attribute_id, MAX(value)
... | _name = "product.attribute.line"
_order = 'attribute_id, value_id, value'
_columns = {
'value': fields.float('Numeric Value'),
'value_id': fields.many2one('product.attribute.value', 'Textual Value'),
'attribute_id': fields.many2one('product.attribute', 'attribute', required=True),
... | any2one('product.template', 'Product', required=True),
'type': fields.related('attribute_id', 'type', type='selection',
selection=[('distinct', 'Distinct'), ('float', 'Float')], string='Type'),
}
def onchange_attribute_id(self, cr, uid, ids, attribute_id, context=None):
attribute =... |
nathawes/swift | utils/build_swift/tests/build_swift/test_shell.py | Python | apache-2.0 | 26,680 | 0.000037 | # This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list o... | m, '-rf', '/Applications/Xcode.app']
self.assertEqual(
shell._normalize_args(command),
['sudo', 'rm', '-rf', '/Applications/Xcode.app'])
def test_normalize_args_converts_complex_wrapper_commands(self):
sudo_rm_rf = shell.wraps('sudo rm -rf')
command = [sudo_rm_rf, ... | ormalize_args(command),
['sudo', 'rm', '-rf', '/Applications/Xcode.app'])
@utils.requires_module('pathlib')
def test_normalize_args_accepts_single_wrapper_arg(self):
rm_xcode = shell.wraps(['rm', '-rf', Path('/Applications/Xcode.app')])
self.assertEqual(
shell._normaliz... |
ptroja/spark2014 | testsuite/gnatprove/tests/intro/test.py | Python | gpl-3.0 | 65 | 0.030769 | from test_support impo | rt *
prove_all(no_fail=True, st | eps = 400)
|
awni/tensorflow | tensorflow/python/kernel_tests/softmax_op_test.py | Python | apache-2.0 | 4,506 | 0.006214 | # 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... | ===================
"""Tests for SoftmaxOp and LogSoftmaxOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import numpy as np
import tensorflow as tf
class SoftmaxTest(tf.test.Te | stCase):
def _npSoftmax(self, features, log=False):
batch_dim = 0
class_dim = 1
batch_size = features.shape[batch_dim]
e = np.exp(features -
np.reshape(np.amax(features, axis=class_dim), [batch_size, 1]))
softmax = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])
if l... |
hecanjog/pattern.studies | orc/hat.py | Python | cc0-1.0 | 364 | 0.013736 | from pippi import dsp
from hcj import snds, fx
hat = snds.load('mc303/hat2.wav') |
def make(length, i):
#h = dsp.bln(length / 4, dsp.rand(6000, 8000), dsp.rand(9000, 16000))
#h = dsp.amp(h, dsp.rand(0.5, 1))
#h = d | sp.env(h, 'phasor')
h = hat
h = dsp.fill(h, length, silence=True)
if dsp.rand() > 0.5:
h = fx.penv(h)
return h
|
weahwww/python | bytes_to_str.py | Python | gpl-2.0 | 351 | 0.008547 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def python3xByte | sToStr():
f = open("BytesToStr.txt", "wb")
zhcnBytes = b'\x63\x68\x61\x72\x43\x6f\x64\x65\x41\x74'
zhcnUnicodeStr = zhcnBytes.decode('gbk')
print(zhcnUnicodeStr)
f.write(zhcnUnicodeStr.encode('utf-8'))
f.close()
if __name__ == "__main__":
pytho | n3xBytesToStr() |
milki/morph | morph/tests/test_patternchain.py | Python | bsd-2-clause | 3,569 | 0.001121 | # test_patternchain.py -- Tests for Pattern Chains
"""Tests for Pattern Chain objects"""
from morph import (
pattern,
patternchain
)
from morph.pattern import (
LiteralPattern,
NumericCounterPattern,
)
from morph.patternchain import (
generateFullReplaceChain,
PatternChain,
FilePatternCh... | ['file0', 'file1', 'file2', 'file3', 'file4'])
)
def testStr(self):
chain = FilePatternChain()
chain.insert_file('file5', 4)
chain.insert_file('file | 1.5', 2)
chain.delete_file(0)
chain.move_file(0, 2)
chain.delete_file(2)
self.assertEqual("\t('insert', 'file5', 4)\n"
"\t('insert', 'file1.5', 2)\n"
"\t('delete', 0)\n"
"\t('move', 0, 2)\n"
... |
kanishka-linux/kawaii-player | kawaii_player/hls_webkit/netmon_webkit.py | Python | gpl-3.0 | 3,417 | 0.009072 | """
Copyright (C) 2017 kanishka-linux kanishka.linux@gmail.com
This file is part of hlspy.
hlspy 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 ver... | nk = (request.url().toString())
except UnicodeEncodeError:
urlLnk = (request.url().path())
if self.get_link:
if self.get_link in urlLnk:
self.netS.emit(urlLnk)
lower_case = urlLnk.lower()
lst = []
if self.d | efault_block:
lst = [
"doubleclick.net", 'adnxs', r"||youtube-nocookie.com/gen_204?",
r"youtube.com###watch-branded-actions", "imagemapurl",
"b.scorecardresearch.com", "rightstuff.com", "scarywater.net",
"popup.js", "banner.htm", "_tribalf... |
sih4sing5hong5/hue7jip8 | 試驗/test教育部臺灣閩南語字詞頻調查工作.py | Python | mit | 539 | 0 | import io
from django.core.management import call_command
from django.test.testcases import TestCase
from 臺灣言語服務.models import 訓練過渡格式
class KIPsu試驗(TestCase):
@classmethod
def setUpClass(cls):
with io.StringIO() as tshogoo:
call_command('教育部臺灣閩南語字詞頻調查工作', stderr=tshogoo)
prin... | 00])
return super().setUpClass()
def test數量(self | ):
self.assertGreater(訓練過渡格式.資料數量(), 50000)
|
konradko/cnav-bot | cnavbot/services/pi2go.py | Python | mit | 4,857 | 0 | import time
import logging
from cnavbot import settings
logger = logging.getLogger()
class Driver(object):
def __init__(self, *args, **kwargs):
self.driver = kwargs.pop('driver', settings.BOT_DRIVER)
class Motors(Driver):
def __init__(self, speed=None, *args, **kwargs):
super(Motors, se... | )
logger.info('Max dista | nce set to {}'.format(self.max_distance))
def left(self):
"""Returns true if there is an obstacle to the left"""
obstacle = self.driver.irLeft()
logger.debug('Left obstacle: {}'.format(obstacle))
return obstacle
def right(self):
"""Returns true if there is an obstacle t... |
Paul-Ezell/cinder-1 | cinder/volume/drivers/glusterfs.py | Python | apache-2.0 | 17,430 | 0 | # Copyright (c) 2013 Red Hat, 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 require... | rovisioning_support'] = not thin_enabled
self._stats = data
@remotefs_drv.locked_volume_id_operation
def create_volume(self, volume):
"""Creates a volume."""
self._ensure_shares_mounted()
volume['provider_location'] = self._find_share(volume['size'])
LOG.info(_LI('ca... | n']}
def _copy_volume_from_snapshot(self, snapshot, volume, volume_size):
"""Copy data from snapshot to destination volume.
This is done with a qemu-img convert to raw/qcow2 from the snapshot
qcow2.
"""
LOG.debug("snapshot: %(snap)s, volume: %(vol)s, "
"v... |
rafallo/p2c | settings.py | Python | mit | 760 | 0.003947 | # -*- coding: utf-8 -*-
import os, tempfile
PROJECT_ROOT = os.path.dirname(__file__)
TMP_DIR = tempfile.mkdtemp()
DOWNLOAD_DIR = os.path.join(TMP_DIR, "download")
LOG_DIR = os.path.join(TMP_DIR, "logs")
try:
os.makedirs(DOWNLOAD_DIR)
except OSError:
pass
try:
os.makedirs(LOG_DIR)
except OSError:
p... | ation.json")
START_PORT = 6841
END_PORT = 6851
SUPPORTED_MOVIE_EXTENSIONS = (
"mp4", "avi", "mkv", "ogv", "ogg", "mpeg", "flv", "wmv")
SUPPORTED_SUBTITLE_EXTENSIONS = ("txt", "srt")
DOWNLOAD_PIECE_SIZE = 1024 * 1024 * | 5
# for 1MB piece length
PRIORITY_INTERVAL = 2 |
asommer70/photolandia | photolandia/urls.py | Python | mit | 678 | 0.00295 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('albums/', include('albums.urls')),
path('photos/', include('photos.url... | t/', auth_views.logout, {'template_name': 'account/logout.html'}, name='logout'),
path('api/login', views.api_login, name="api_login"),
pa | th('', views.IndexView.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
codingforentrepreneurs/digital-marketplace | src/products/migrations/0012_auto_20151120_0434.py | Python | mit | 630 | 0.001587 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.core.files.storage
import products.models
class Migration(migrations.Migration):
dependencies = [
('prod | ucts', '0011_auto_20151120_0137'),
]
operations = [
migrations.AlterField(
model_name='product',
name='media',
field=models.FileField(storage=djang | o.core.files.storage.FileSystemStorage(location=b'/Users/jmitch/Desktop/dm/static_cdn/protected'), null=True, upload_to=products.models.download_media_location, blank=True),
),
]
|
laterpay/rubberjack-cli | tests/test_cli.py | Python | mit | 6,380 | 0.003135 | import boto
import mock
import moto
import tempfile
import unittest
from click.testing import CliRunner
from rubberjackcli.click import rubberjack
class CLITests(unittest.TestCase):
@moto.mock_s3_deprecated
@mock.patch('boto.beanstalk.layer1.Layer1.create_application_version')
@mock.patch('boto.beansta... | # FIXME Remove hardcoded EnvName
'VersionLabel': 'same',
},
],
},
},
}
CliRunner().invoke(rubberjack, ['promote'], catch_exceptions=False)
self.assertTrue(se.called)
@moto.mock_s3_deprecat... | foo', 'deploy'], catch_exceptions=False)
@moto.mock_s3_deprecated
@mock.patch('boto.beanstalk.layer1.Layer1.create_application_version')
@mock.patch('boto.beanstalk.layer1.Layer1.update_environment')
def test_deploy_to_custom_environment(self, ue, cav):
s3 = boto.connect_s3()
s3.create_... |
bhupennewalkar1337/erpnext | erpnext/buying/doctype/request_for_quotation/request_for_quotation.py | Python | gpl-3.0 | 8,686 | 0.023947 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe import _
from frappe.model.mapper import get_mapped_doc
from frappe.utils import get_url, random_string,... | rmissions=True)
def create_user(self, rfq_supplier, link):
user = frappe.get_doc({
'doctype': 'User',
'send_welcome_email': 0,
'email': rfq_supplier.email_id,
'first_name': rfq_supplier.supplier_name or rfq_supplier.supplier,
'user_type': 'Website User',
'redirect_url': link
})
user.save(ignor... | ll_name = get_user_fullname(frappe.session['user'])
if full_name == "Guest":
full_name = "Administrator"
args = {
'update_password_link': update_password_link,
'message': frappe.render_template(self.message_for_supplier, data.as_dict()),
'rfq_link': rfq_link,
'user_fullname': full_name
}
subjec... |
gwpy/gwsumm | gwsumm/triggers.py | Python | gpl-3.0 | 14,721 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013)
#
# This file is part of GWSumm.
#
# GWSumm 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) ... | e)
# override with user options
if format:
read_kw['format'] = format
elif not read_kw.get('format', None):
read_kw['format'] = etg.lower()
if timecolumn: |
read_kw['timecolumn'] = timecolumn
elif columns is not None and 'time' in columns:
read_kw['timecolumn'] = 'time'
# replace columns keyword
if read_kw['format'].startswith('ascii.'):
read_kw['include_names'] = columns
else:
read_kw['columns'] = columns
# parse filt... |
JWDebelius/scikit-bio | skbio/parse/sequences/tests/__init__.py | Python | bsd-3-clause | 378 | 0 | #!/usr/bin/env python
# -----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified | BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------- | ------------------------------------------------------------
|
jeetsukumaran/pstrudel | test/scripts/calc-tree-unlabeled-symmetric-difference.py | Python | gpl-2.0 | 1,420 | 0.003521 | #! /usr/bin/env python
import sys
import math
import collections
import dendropy
def count_set_size_difference(v1, v2):
c1 = collections.Counter(v1)
c2 = collections.Counter(v2)
| counted_matched = c1 & c2
matched = sorted(list(counted_matched.elements()))
counted_diffs = (c1 - c2) + (c2 - c1)
unmatched = sorted(list(counted_diffs.elements()))
diff = len(unmatched)
return diff
def count_subtree_leaf_set_sizes(tree):
internal_nodes = tree.internal_nodes()
subtree_... | = {}
for nd in internal_nodes:
leaf_count = 0
for leaf in nd.leaf_iter():
leaf_count += 1
if nd.taxon is not None:
label = nd.taxon.label
else:
label = nd.label
subtree_leaf_set_sizes[label] = leaf_count
return sorted(subtree_leaf_set_s... |
burito/PyUI | pyui/themeBase.py | Python | lgpl-2.1 | 7,045 | 0.013343 | # PyUI
# Copyright (C) 2001-2002 Sean C. Riley
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but... | #####################################################################
###
### Widgets specific drawing functions.
### These are the methods for actual themes to implement.
###
#####################################################################
def drawButton(self, rect, title, hasFocus, ... | t
def drawLabel(self, rect, title, color = None, font = None, shadow=0, align=0 ):
return rect
def drawCheckBox(self, rect, text, checkState):
return rect
def drawSliderBar(self, rect, range, position, BARWIDTH=8):
return rect
def drawEdit(self, rect, text, ha... |
sile16/python-isilon-api | isilon/__init__.py | Python | mit | 500 | 0.018 | import session
import namespace
import platform
from . | exceptions import ObjectNotFound, APIError, ConnectionError, IsilonLibraryError
class API(object):
'''Implements higher level functionality to interface with an Isilon cluster'''
def __init__(self, *args, **kwargs):
self.session = session.Session(*args, **kwargs)
self.namespace = nam... | platform.Platform(self.session)
|
regionbibliotekhalland/digitalasagor | progressdlg.py | Python | gpl-3.0 | 4,102 | 0.015115 | # Copyright 2013 Regionbibliotek Halland
#
# This file is part of Digitala sagor.
#
# Digitala sagor 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
# ... | Y or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. |
#
# You should have received a copy of the GNU General Public License
# along with Digitala sagor. If not, see <http://www.gnu.org/licenses/>.
import Tkinter as tki
import ttk
from language import lang
import language as lng
import dialog
import thread
class _ProgressDialog(tki.Frame):
"""A F... |
mhbu50/frappe | frappe/core/doctype/log_settings/test_log_settings.py | Python | mit | 182 | 0.010989 | # -*- coding: utf-8 -*-
# Copyright (c) 202 | 0, Frappe Technologies and Contribut | ors
# See license.txt
# import frappe
import unittest
class TestLogSettings(unittest.TestCase):
pass
|
jdmonaco/vmo-feedback-model | src/spike_reset.py | Python | mit | 3,535 | 0.040181 | #!/usr/bin/env python
#encoding: utf-8
import numpy as np
from pylab import *
dt=0.01 # msec
tau=40.0 # msec
tmax=1000 # msec
V_spk=-20
V_thres=-50.0
V_reset=-70.0
E_leak=V_reset
R_m=10.0 # MΩ
tt=np.arange(0, tmax, dt) #0:dt:tmax
Nt=len(tt) #length(tt)
V=np.zeros((Nt,))
V2=np.zeros((Nt,))
S=np.zeros((Nt,))
S2=np.zero... | newphase
subplot(nrows,1,2)
plot([k*dt]*2, [V_reset,V_spk], 'k-',lw=LW,zorder=-50)
xlim(tlim)
ylim(Vlim)
ylabel('V')
subplot(nrows,1,3)
xlim(tlim)
ylim(-25, 25)
ylabel(r'$I_e$ (pA)')
# plot(timeList/T, phaseList,'o-')
# xlabel('Pulse timing (Period)')
# ylabel('Phase reset (degree)')
# grid(True)
subplot(nrows,2,7)... | jump_ix:]-2, X[:jump_ix]]
Y = r_[Y[jump_ix:], Y[:jump_ix]]
colors = colors[jump_ix:] + colors[:jump_ix]
midX = X[int(Nsuper/2)+1]
for i_super in xrange(Nsuper):
plot(X[i_super],Y[i_super],'o',mec='k',
mfc=colors[i_super],ms=6,mew=1,zorder=i_super)
print X[i_super],Y[i_super]
# p=np.polyfit(x,y,1)
# yp=... |
gengwg/leetcode | 142_linked_list_cycle_ii.py | Python | apache-2.0 | 976 | 0 | # 142. Linked List Cycle II
# Given a linked list, return the node where the cycle begins. |
# If there is no cycle, return null.
#
# Note: Do not modify the linked list.
#
# Follow up:
# Can you solve it without using extra space?
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycl... | return None
slow = head.next
fast = head.next.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if fast is None or fast.next is None:
return None
slow = head
... |
anryko/ansible | lib/ansible/modules/cloud/google/gcpubsub_info.py | Python | gpl-3.0 | 4,597 | 0.00261 | #!/usr/bin/python
# Copyright 2016 Google 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | json_output['topics'] = list_func(pubsub_client.list_topics())
elif mod_params['view'] == 'subscriptions':
if mod_params['topic']:
t = p | ubsub_client.topic(mod_params['topic'])
json_output['subscriptions'] = list_func(t.list_subscriptions())
else:
json_output['subscriptions'] = list_func(pubsub_client.list_subscriptions())
json_output['changed'] = False
json_output.update(mod_params)
module.exit_json(**json_o... |
lmr/autotest | client/shared/base_packages.py | Python | gpl-2.0 | 45,844 | 0.000284 | """
This module defines the BasePackageManager Class which provides an
implementation of the packaging system API providing methods to fetch,
upload and remove packages. Site specific extensions to any of these methods
should inherit this class.
"""
import fcntl
import logging
import os
import re
import shutil
from au... | fetch_dir = os.path.join(fetch_dir, re.sub("/", "_", name))
return (name, fetch_dir)
def fetch_pkg_file(self, filename, dest_path):
"""
Fetch a package file from a package repository.
:type filename: string
:param filename: The filename of the package file to fetch.
... | lementedError()
def install_pkg_post(self, filename, fetch_dir,
install_dir, preserve_install_dir=False):
"""
Fetcher specific post install
:type filename: string
:param filename: The filename of the package to install
:type fetch_dir: string
... |
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/f2py/tests/test_callback.py | Python | bsd-2-clause | 3,040 | 0 | from __future__ import division, absolute_import, print_function
import math
import textwrap
from numpy import array
from numpy.testing import run_module_suite, assert_, assert_equal, dec
import util
class TestF77Callback(util.F2PyTest):
code = """
subroutine t(fun,a)
integer a
cf2py intent(out) ... | t = getattr(self.module, name)
| r = t(lambda: 4)
assert_(r == 4, repr(r))
r = t(lambda a: 5, fun_extra_args=(6,))
assert_(r == 5, repr(r))
r = t(lambda a: a, fun_extra_args=(6,))
assert_(r == 6, repr(r))
r = t(lambda a: 5 + a, fun_extra_args=(7,))
assert_(r == 12, repr(r))
r = t(la... |
gdsfactory/gdsfactory | gdsfactory/tests/test_port_from_csv.py | Python | mit | 241 | 0 | from gdsfactory.port import csv2port
def test_csv2port(data_regression):
import gdsfactory as gf
name = "straight" |
csvpath = gf.CONFIG["gdsdir"] / f"{name}.ports"
ports = csv2port(csvpath)
data_reg | ression.check(ports)
|
dnjohnstone/hyperspy | hyperspy/tests/learn/test_mlpca.py | Python | gpl-3.0 | 2,332 | 0.000429 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | U = rng.uniform(0, 1, size=(m, r))
V = rng.uniform(0, 10, size=(n, r))
| varX = U @ V.T
X = rng.poisson(varX)
rank = r
# Test tolerance
tol = 300
U, S, V, Sobj = mlpca(X, varX, output_dimension=rank, tol=tol, max_iter=max_iter)
X = U @ np.diag(S) @ V.T
# Check the low-rank component MSE
normX = np.linalg.norm(X - X)
assert normX < tol
# Check s... |
NoMoKeTo/lircpy | lircpy/__init__.py | Python | apache-2.0 | 142 | 0 | from .lircpy import LircPy
from .exceptions import Invali | dResponseError, LircError
__all__ = ['LircPy', 'InvalidResponseError', ' | LircError']
|
aykut/django-oscar | oscar/apps/order/abstract_models.py | Python | bsd-3-clause | 19,620 | 0.007594 | from itertools import chain
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.db.models import Sum
from django.template import Template, Context
class AbstractOrder(models.Mod... | _template = models.CharField(max_length=170, blank=True)
def save(self, *args, **kwargs):
if not self.code:
self.code = slugify(self.name)
super(AbstractCommunicationEventType, self).save(*args, **kwargs)
class Meta:
abstract = True
verbose_name_plural = _("... | self.email_subject_template and self.email_body_template
def get_email_subject_for_order(self, order, **kwargs):
return self._merge_template_with_context(self.email_subject_template, order, **kwargs)
def get_email_body_for_order(self, order, **kwargs):
return self._merge_template_with... |
Yukarumya/Yukarum-Redfoxes | taskcluster/taskgraph/task/test.py | Python | mpl-2.0 | 5,066 | 0.000987 | # 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/.
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
from . import tran... | logger.debug("Generating tasks for test {} on platform {}".format(
test_name, test['test-platform']))
yield test
@classmethod
def get_builds_by_platform(cls, dep_kind, loaded_tasks):
"""Find the build tasks on which tests will depend, keyed by
platform... | ns a dictionary mapping build platform to task."""
builds_by_platform = {}
for task in loaded_tasks:
if task.kind != dep_kind:
continue
build_platform = task.attributes.get('build_platform')
build_type = task.attributes.get('build_type')
i... |
fhcrc/taxtastic | tests/test_taxonomy.py | Python | gpl-3.0 | 10,512 | 0 | #!/usr/bin/env python
import os
from os import path
import logging
import shutil
from sqlalchemy import create_engine
from . import config
from .config import TestBase
import taxtastic
from taxtastic.taxonomy import Taxonomy, TaxonIntegrityError
import taxtastic.ncbi
import taxtastic.utils
log = logging
datadir =... | 1',
parent_id='1280',
rank='subspecies',
names=[{'tax_name': 'foo'}],
source_name='ncbi'
)
lineage = self.tax.lineage('1280_1')
self.assertEqual(lineage['ta | x_id'], '1280_1')
self.assertEqual(lineage['tax_name'], 'foo')
def test02(self):
new_taxid = '1279_1'
new_taxname = 'between genus and species'
children = ['1280', '1281']
self.tax.add_node(
tax_id=new_taxid,
parent_id='1279',
rank='spec... |
lferr/charm | charm/toolbox/policytree.py | Python | lgpl-3.0 | 6,070 | 0.014333 | #!/usr/bin/python
from pyparsing import *
from charm.toolbox.node import *
import string
objStack = []
def createAttribute(s, loc, toks):
if toks[0] == '!':
newtoks = ""
for i in toks:
newtoks += i
return BinNode(newtoks)
return BinNode(toks[0]) # create
# convert 'attr <... | == False: return (False, sendThis)
return (True, sendThis)
if(tree.getNodeType() == OpType.AND):
if resultLeft and resultRight: sendThis = leftAttr + rightAttr
elif resultLeft: sendThis = leftAttr
elif resultRight: sendThis = rightAttr
els... | if result == False: return (False, sendThis)
return (True, sendThis)
elif(tree.getNodeType() == OpType.ATTR):
if(tree.getAttribute() in attrList):
return (True, [tree])
else:
return (False, None)
retur... |
csengstock/tcpserv | tcpserv.py | Python | lgpl-3.0 | 5,176 | 0.000773 | # tcpserv
#
# Copyright (c) 2015 Christian Sengstock, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU | Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR... | or more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
"""
Simple python socket helper library to implement
stateless tcp-servers.
Usage:
# Interface
>>> from tcpserv import listen, request
# Define server logic by a handler function:
# Gets a request... |
binary-signal/mass-apk-installer | mass_apk/__main__.py | Python | bsd-3-clause | 154 | 0 | """Main entry for mass apk when invoked as python module.
>>> python -m massapk
"""
from mass_apk import cli
if __name__ == | "__main__":
cli.mai | n()
|
kikocorreoso/brython | www/src/Lib/importlib/_bootstrap.py | Python | bsd-3-clause | 39,424 | 0.00038 | """Core implementation of import.
This module is NOT meant to be directly imported! It has been designed such
that it can be bootstrapped into Python as the implementation of import. As
such it requires the injection of specific modules and attributes in order to
work. One should use importlib as the public-facing ver... | self.wakeup.acquire()
self.wakeup.release()
finally:
del _blocking_on[tid]
def release(self):
tid = _thread.get_ident()
with self.lock:
if self.owner != tid:
raise RuntimeError('cannot release un-acquired lock')
assert sel... | if self.count == 0:
self.owner = None
if self.waiters:
self.waiters -= 1
self.wakeup.release()
def __repr__(self):
return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
class _DummyModuleLock:
"""A simple _ModuleLo... |
Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-cognitiveservices-search-customsearch/azure/cognitiveservices/search/customsearch/models/_models_py3.py | Python | mit | 29,187 | 0.000171 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | red when
sending a request.
All required parameters must be populated in | order to send to Azure.
:param _type: Required. Constant filled by server.
:type _type: str
:ivar id: A String identifier.
:vartype id: str
:ivar web_search_url: The URL To Bing's search result for this item.
:vartype web_search_url: str
:ivar name: The name of the thing represented by thi... |
bpeck/tumblr-display | src/Drawable.py | Python | apache-2.0 | 76 | 0.013158 | class Drawable( | objec | t):
def draw(self, display_screen, dT):
pass |
mmanhertz/elopic | tests/test_db.py | Python | bsd-2-clause | 3,055 | 0.001309 | from __future__ import unicode_literals
import os
import shutil
import tempfile
import unittest
from elopic.data.elopicdb import EloPicDB, EloPicDBError
from elopic.logic.elo import INITIAL_ELO_SCORE
from tests.utils import copy_all_files, delete_files_matching_pattern
class TestDatabase(unittest.TestCase):
"""... | [r[0] for r in result],
expected,
'Paths do not match'
)
for r in result:
self.assertEqual(r[1], 0)
self.assertEqual(r[2], INITIAL_ELO_SCORE)
| self.assertEqual(r[3], 0)
def _get_imagepaths_in_dir(self, dir):
return [os.path.join(self.tempdir, e) for e in os.listdir(dir) if e.endswith('.jpg')]
def test_load_from_disk_new_folder(self):
self._assert_db_matches_dir(self.tempdir)
def test_load_additional_files(self):
se... |
the-invoice/nab | nwaddrbook/icmp/util.py | Python | gpl-3.0 | 701 | 0 | import os
import pwd
import grp
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
if os.getuid() != 0:
# We're not root so, like, whatever dude
return
# Get the uid/gid from the name
sudo_user = os.getenv("SUDO_USER")
if sudo_user:
pwnam = pwd.getpwnam(sudo_user)
... | m.pw_gid
else:
running_uid = pwd.getpwnam(uid_name).pw_uid
running_gid = grp.getgrnam(gid_name).gr_gid
# | Remove group privileges
os.setgroups([])
# Try setting the new uid/gid
os.setgid(running_gid)
os.setuid(running_uid)
# Ensure a very conservative umask
os.umask(0o22)
|
DMRookie/RoomAI | roomai/doudizhu/DouDiZhuPokerAction.py | Python | mit | 7,614 | 0.010901 | #!/bin/python
import os
import roomai.common
import copy
#
#0, 1, 2, 3, ..., 7, 8, 9, 10, 11, 12, 13, 14
#^ ^ ^ ^ ^
#| | | | |
#3, 10, J, Q, K, A, 2, r, R
#
class DouDiZhuActionElement:
str_to_rank = {'3':0, '4':1, '5':2... | None
self.__action2pattern__()
self.__key__ = DouDiZhuPokerAction.__master_slave_cards_to_key__(masterCards, slaveCards)
def __get_key__(self): return sel | f.__key__
key = property(__get_key__, doc="The key of DouDiZhu Action")
def __get_masterCards__(self): return self.__masterCards__
masterCards = property(__get_masterCards__, doc="The cards act as the master cards")
def __get_slaveCards__(self): return self.__slaveCards__
slaveCards = property(_... |
denismakogon/tosca-vcloud-plugin | vcloud_plugin_common/__init__.py | Python | apache-2.0 | 17,925 | 0.000167 | # Copyright (c) 2014 GigaSpaces Technologies 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.0
#
# Unless required ... | t(SESSION_TOKEN)
org_url = cfg.get(ORG_URL)
if not (all([url, token]) or all([url, username, password]) or session_token):
raise cfy_exc.NonRecoverableError(
"Login credentials must be specified.")
if (service_type == SUBSCRIPTION_SERVICE_TYPE and not (
s | ervice and org_name
)):
raise cfy_exc.NonRecoverableError(
"vCloud service and vDC must be specified")
if service_type == SUBSCRIPTION_SERVICE_TYPE:
vcloud_air = self._subscription_login(
url, username, password, token, service, org_name,
... |
nglrt/virtual_energy_sensor | virtual_energy_sensor/loadtrain.py | Python | mit | 3,264 | 0.016544 | import numpy as np
import fnmatch, os
import h5py
class Hdf5Loader():
def loadDirectory(self, dirname):
"""
Loads all hdf5 files in the directory dirname
@param dirname: The directory which contains the files to load
@returns: list of h5py File objects
""... | files in a given directory. It extracts all datasets
|
which are specified in :dataset_list and merges the datasets from
all files.
Finally it returns a numpy array for each dataset in the :dataset_list
@param dirname: The directory containing the hdf5 files
@param dataset_list: List of datasets t... |
75py/Download-Confirm | work/generate_extentions_res.py | Python | apache-2.0 | 1,723 | 0.004643 | from jinja2 import Environment, FileSystemLoader
data = {
"extensionInfoList": [
{"ext": "apk", "mimeTypes": ["application/vnd.android.package-archive"]}
, {"ext": "zip", "mimeTypes": []}
, {"ext": "tgz", "mimeTypes": []}
, {"ext": "gz", "mimeTypes": []}
, {"ext": "pdf", "mi... | roid/downloadconfirm/extension/{}HookTest.java"
},
]
env = Environment(loader=FileSystemLoader('.'))
for xmlTemplate in xmlTemplates:
template = env.get_template(xmlTemplate['template'])
rendered = template.render(data)
with open(xmlTemplate['output'], 'w') as f:
f.write(rendered)
f.c... | e = env.get_template(javaTemplate['template'])
rendered = template.render({'extInfo': extInfo})
with open(javaTemplate['output'].format(extInfo['ext'].capitalize()), 'w') as f:
f.write(rendered)
f.close()
|
weberwang/WeRoBot | travis/terryfy/travisparse.py | Python | mit | 1,763 | 0.001134 | """ Parse travis.yml file, partly
"""
import sys
if sys.version_info[0] > 2:
basestring = str
class TravisError(Exception):
pass
def get_yaml_entry(yaml_dict, name):
""" Get entry `name` from dict `yaml_dict`
Parameters
----------
yaml_dict : dict
dict or subdict from parsing .trav... | if not globals is None:
if matrix is None:
raise TravisError('global section needs matrix section')
lines += globals
if not matrix is None:
lines.append(matrix[0])
return '\n'.join(lines) + '\n'
| |
zamonia500/PythonTeacherMythenmetz | 300문제/96.py | Python | gpl-3.0 | 106 | 0 | pet = ['dog', 'cat', 'parrot', 'squirrel', 'goldfish']
fo | r anima | l in pet:
print(animal, len(animal))
|
dsweet04/rekall | rekall-core/rekall/plugins/common/__init__.py | Python | gpl-2.0 | 471 | 0 | """Plugins that are not OS-specific"""
# pylint: disable=unused-import
from rekall.plugins.common import address_resolver
from rekall.plugins.common import api
from rekall.plugins.common import bovine
from rekall.plugins.common import efilter_plugins
from rekall.plugins.common import inspection
from rekall.plugins.com... |
from rekall.plugin | s.common import scanners
from rekall.plugins.common import sigscan
|
mbrukman/cloud-launcher | apps/cloudera/director/py/rhel6.py | Python | apache-2.0 | 1,057 | 0 | #!/usr/bin/python
#
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Licens | e 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 WA | RRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##########################################################################
#
# Deployment for Cloudera Director using a RHEL 6 image.
#
################... |
abulte/Flask-Bootstrap-Fanstatic | application/__init__.py | Python | mpl-2.0 | 730 | 0.005487 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2013 Alexandre Bulté <alexandre[at]bulte[dot]net>
#
# 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/.
from fl... | = Fanstatic(app)
# define your own ressources this way
fanstatic.resource('js/app.js', name=' | app_js', bottom=True)
@app.route('/')
def index():
return render_template('index.html') |
natasasdj/OpenWPM | analysis/12_images_third-domains2.py | Python | gpl-3.0 | 19,012 | 0.016148 | import os
import sqlite3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.distributions.empirical_distribution import ECDF
from matplotlib.ticker import FuncFormatter
def thousands(x, pos):
if x>=1e9:
return '%.1fB' % (x*1e-9)
elif x>=1e6:
return '%.1fM' %... | _index(name='img_perc').sort_values('img_perc',ascending=False)
domcom['img_perc']=domcom['img_perc']/float(df2.shape[0])*100
table_dir = '/home/nsarafij/project/OpenWPM/analysis/tables_10k'
fhand = open(os.path.join(table_dir,'third-domain2company_perc_top30.txt'),'w+')
### table domains - companies
for i in range(0,n... | s = s.encode('UTF-8')
print s
fhand.write(s + '\n')
fhand.close()
### companies
# counts
fig_dir = '/home/nsarafij/project/OpenWPM/analysis/figs_10k_domains/'
fig, ax = plt.subplots()
plt.plot(range(1,com.shape[0]+1),com,marker='.')
plt.xscale('log')
plt.xlabel('company rank')
plt.ylabel('... |
lucventurini/mikado | Mikado/loci/excluded.py | Python | lgpl-3.0 | 3,468 | 0.003172 | # coding: utf-8
"""
This module defines a containers that hold transcripts excluded from further consideration.
It is invoked when all transcripts in a locus have a score of 0 and the "purge"
option has been enabled.
"""
from .abstractlocus import Abstractlocus
from ..transcripts import Transcript
class Excluded(Ab... | args: optional arguments are completely ignored by this method.
"""
# Notice that check_in_locus is always set to False.
| _ = kwargs
Abstractlocus.add_transcript_to_locus(self, transcript, check_in_locus=False)
def add_monosublocus(self, monosublocus_instance):
"""Wrapper to extract the transcript from the monosubloci and pass it
to the constructor.
:param monosublocus_instance
:type mon... |
nioinnovation/safepickle | safepickle/types/tests/test_timedelta.py | Python | apache-2.0 | 509 | 0 | from unittest import TestCase
from datetime import timedelta
from safepickle.types.timedelta import TimedeltaType |
from safepickle.encoding import encode, decode
class TestTimedelta(TestCase):
def test_timedelta(self):
""" Asserts timedelta type is handled as expected
"""
obj = t | imedelta(days=1, seconds=2, microseconds=3)
type_ = TimedeltaType()
encoding = type_.encode(obj, encode)
decoding = decode(encoding)
self.assertEqual(obj, decoding)
|
PytLab/catplot | tests/edge_3d_test.py | Python | mit | 2,499 | 0.001601 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test case for Edge3D.
"""
import unittest
from catplot.grid_components.nodes import Node2D, Node3D
from catplot.grid_components.edges import Edge2D, Edge3D
class Edge3DTest(unittest.TestCase):
def setUp(self):
self.maxDiff = True
def test_construc... | t 3D edge from a 2D edge.
"""
node1 = Node2D([1.0, 1.0])
node2 = Node2D([1.0, 2.0])
edge2d = Edge2D(node1, node2)
edge3d = Edge3D.from2d(edge2d)
self.assertTrue(isinstance(edge3d, Edge3D))
def test_move(self):
""" Test the edge can be moved correctly.
... | 3D([1.0, 1.0, 1.0], color="#595959", width=1)
node2 = Node3D([0.5, 0.5, 0.5], color="#595959", width=1)
edge = Edge3D(node1, node2, n=10)
edge.move([0.5, 0.5, 0.5])
ref_x = [1.5,
1.4545454545454546,
1.4090909090909092,
1.36363636363636... |
mvaled/sentry | tests/sentry/similarity/backends/base.py | Python | bsd-3-clause | 8,478 | 0.003185 | from __future__ import absolute_import
import abc
class MinHashIndexBackendTestMixin(object):
__meta__ = abc.ABCMeta
@abc.abstractproperty
def index(self):
pass
def test_basic(self):
self.index.record("example", "1", [("index", "hello world")])
self.index.record("example", "... | sults = self.index.classify("example", [("index", 0, "hello world")])
assert results[0:2] == [("1", [1.0]), ("2", | [1.0])]
assert results[2][0] in ("3", "4") # equidistant pairs, order doesn't really matter
assert results[3][0] in ("3", "4")
assert results[4][0] == "5"
# classification, low threshold
results = self.index.classify("example", [("index", 6, "hello world")])
assert len... |
piotroxp/scibibscan | scib/lib/python3.5/site-packages/astropy/utils/compat/fractions.py | Python | mit | 568 | 0 | # Licensed un | der a 3-clause BSD style license - see LICENSE.rst
"""
Handles backports of the standard library's `fractions.py`.
The fractions module in 2.6 does not handle being instantiated using a
float and then calculating an approximate fraction based on that.
This functionality is required by the FITS unit format generator,
s... | _ import absolute_import
import sys
if sys.version_info[:2] == (2, 6):
from ._fractions_py2 import *
else:
from fractions import *
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/spyderlib/cli_options.py | Python | gpl-3.0 | 2,217 | 0.000903 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 The Spyder development team
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
import optparse
def get_options():
"""
Convert options into commands
return commands, message
"""
parser = optparse.OptionParser(usage="s... | lp="Run a new instance of Spyder, even if the single "
"instance mode has been turned on (default)")
parser.add_option('--session', dest="startup_session", default='',
| help="Startup session")
parser.add_option('--defaults', dest="reset_to_defaults",
action='store_true', default=False,
help="Reset configuration settings to defaults")
parser.add_option('--reset', dest="reset_session",
action='store_... |
praveen-pal/edx-platform | common/lib/xmodule/xmodule/util/date_utils.py | Python | agpl-3.0 | 1,275 | 0.000784 | """
Convenience methods for working with datetime objects
"""
from datetime import timedelta
from django.utils.translation import ugettext as _
def get_default_time_display(dt, show_timezone=True):
"""
Co | nverts a datetime to a string representation. This is the default
representation used in Studio and LMS.
It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC",
depending on the value of show_timezone.
If None is passed in for dt, an empty string will be returned.
The default valu... | try:
timezone = u" " + dt.tzinfo.tzname(dt)
except NotImplementedError:
timezone = dt.strftime('%z')
else:
timezone = u" UTC"
return unicode(dt.strftime(u"%b %d, %Y {at} %H:%M{tz}")).format(
at=_(u"at"), tz=timezone).strip()
def almo... |
srluge/SickRage | sickbeard/clients/download_station_client.py | Python | gpl-3.0 | 2,731 | 0.001465 | # coding=utf-8
# Authors:
# Pedro Jose Pereira Vieito <pvieito@gmail.com> (Twitter: @pvieito)
#
# URL: https://github.com/mr-orange/Sick-Beard
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... | a=data)
return self.response.json()['success']
def _add_torrent_file(self, result):
data = {
'api': 'SYNO.DownloadStation.Task',
'version': '1',
'method': 'create',
' | session': 'DownloadStation',
'_sid': self.auth
}
if sickbeard.TORRENT_PATH:
data['destination'] = sickbeard.TORRENT_PATH
files = {'file': (result.name + '.torrent', result.content)}
self._request(method='post', data=data, files=files)
return self.respons... |
krkeegan/lib-py-insteon | insteon/rest_server.py | Python | gpl-2.0 | 1,792 | 0.001116 | import threading
import pprint
import json
from bottle import route, run, Bottle
class Rest_Server(Bottle):
'''The REST front end'''
def __init__(self, core):
super(Rest_Server, self).__init__()
self._core = core
self.route('/plms', callback=self.list_plms)
def st... | d/usb-FTDI_FT232R_USB_UART_A403KDV3-if00-port0",
"port_active": true,
"sub_cat": 21
}
}
:statuscode 200: no | error
'''
plms = self._core.get_all_plms()
ret = {}
for plm in plms:
ret[plm.dev_addr_str] = {
'dev_cat': plm.dev_cat,
'sub_cat': plm.sub_cat,
'firmware': plm.firmware,
'port': plm.port,
... |
codex-bot/github | github/data_types/commit.py | Python | mit | 1,228 | 0.001629 | from data_types.user import User
class Commit:
"""
Commit object
https://developer.github.com/v3/repos/commits/
Attributes:
url: Commit URL in repo
author: Commit author
committer: Commit sender
message: Commit messagee
tree: Example {
"url": "https:... | author = User(data['author'])
self.committer = None
if 'committer' in data:
self.committer = User(data['committ | er'])
self.message = data.get('message', '')
self.tree = data.get('tree', None)
self.comment_count = data.get('comment_count', 0)
self.added = data.get('added', [])
self.removed = data.get('removed', [])
self.modified = data.get('modified', [])
|
kennethreitz/pipenv | pipenv/vendor/tomlkit/container.py | Python | mit | 24,835 | 0.000322 | from __future__ import unicode_literals
import copy
from ._compat import decode
from ._utils import merge_dicts
from .exceptions import KeyAlreadyPresent
from .exceptions import NonExistentKey
from .exceptions import ParseError
from .exceptions import TOMLKitError
from .items import AoT
from .items impor | t Comment
from .items import Item
from .items import K | ey
from .items import Null
from .items import Table
from .items import Whitespace
from .items import item as _item
_NOT_SET = object()
class Container(dict):
"""
A container for items within a TOMLDocument.
"""
def __init__(self, parsed=False): # type: (bool) -> None
self._map = {} # type... |
diegocepedaw/oncall | src/oncall/user_sync/ldap_sync.py | Python | bsd-2-clause | 17,821 | 0.002188 | from gevent import monkey, sleep, spawn
monkey.patch_all() # NOQA
import sys
import time
import yaml
import logging
import ldap
from oncall import metrics
from ldap.controls import SimplePagedResultsControl
from datetime import datetime
from pytz import timezone
from sqlalchemy import create_engine
from sqlalchemy.o... | mobile = mobile.decode("utf-8")
mobile = normalize_phone_number(mobile)
except NumberParseException:
mobile = None
except UnicodeEncodeError:
mobile = None
if mail:
mail = mail[0]
... | else:
slack = None
contacts = {'call': mobile, 'sms': mobile, 'email': mail, 'slack': slack, 'name': name}
dn_map[dn] = username
users[username] = contacts
pctrls = [
c for c in serverctrls if c.controlType == SimplePagedResultsControl.c... |
andela/codango | codango/resources/migrations/0001_initial.py | Python | mit | 1,494 | 0.002677 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import cloudinary.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... | source_file_name', models.CharField(max_length=100, null=True)),
('resource_file_size', models.IntegerField(default=0)),
('snippet_text', models.TextField(null=True, blank=True)),
('date_added', models.DateTimeField(auto_now_add=True)) | ,
('date_modified', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
]
|
nparley/mylatitude | lib/attr/_make.py | Python | mit | 49,291 | 0.00002 | from __future__ import absolute_import, division, print_function
import hashlib
import linecache
import sys
import warnings
from operator import itemgetter
from . import _config
from ._compat import PY2, isclass, iteritems, metadata_proxy, set_closure_cell
from .exceptions import (
DefaultAlreadySetError, Frozen... | he value is an instance of :class:`Factory`, its callable will be
used to construct a new value (useful for mutable data types like lists
or dicts).
If a default is not set (or set manually to ``attr | .NOTHING``), a value
*must* be supplied when instantiating; otherwise a :exc:`TypeError`
will be raised.
The default can also be set using decorator notation as shown below.
:type default: Any value.
:param validator: :func:`callable` that is called by ``attrs``-generated
``__... |
unioslo/cerebrum | testsuite/docker/test-config/cereconf_local.py | Python | gpl-2.0 | 1,350 | 0.000741 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2003-2018 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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... | General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
impo | rt os
from Cerebrum.default_config import *
CEREBRUM_DATABASE_NAME = os.getenv('DB_NAME')
CEREBRUM_DATABASE_CONNECT_DATA['user'] = os.getenv('DB_USER')
CEREBRUM_DATABASE_CONNECT_DATA['table_owner'] = os.getenv('DB_USER')
CEREBRUM_DATABASE_CONNECT_DATA['host'] = os.getenv('DB_HOST')
CEREBRUM_DATABASE_CONNECT_DATA['tabl... |
marcoconstancio/yanta | plugins/viewers/html_editor/html_editor.py | Python | gpl-2.0 | 16,041 | 0.004239 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os.path
import string
import webbrowser
import shutil
import json
import base64
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5.QtCore import QFile
from PyQt5.QtCore import QUrl
from PyQt5.QtWebKit import QWebSettings
from ... | ##### TO IMPLEMENT ##########
#self.note_editor.execute_js(self.functions.get_javascript_plugins())
#self.load_functions = []
#self.settings().setAttribute(QWebSettings.AutoLoadImages, False)
#QWebSettings.globalSettings()->setAttribute(QWebSettings | ::DeveloperExtrasEnabled, true);
#QWebSettings.globalSettings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True)
def get_config(self):
return self.config
def set_context_menu_append_actions(self, context_menu_actions):
self.context_menu_actions = context_menu... |
braams/shtoom | shtoom/__init__.py | Python | lgpl-2.1 | 121 | 0 | # Copyright (C) 2004 | Anthony Baxter
# This file is necessary to make this directory a pack | age
__version__ = '0.3alpha0'
|
Hexadorsimal/pynes | nes/processors/ppu/name_table.py | Python | mit | 106 | 0 | class NameTable:
def __init__(self, start, size):
self.s | tart = start
self.s | ize = size
|
TomHeatwole/osf.io | admin/base/settings/defaults.py | Python | apache-2.0 | 5,822 | 0.001546 | """
Django settings for the admin project.
"""
import os
from urlparse import urlparse
from website import settings as osf_settings
from django.contrib import messages
# import local # Build own local.py (used with postgres)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Q... | 'api.base.middleware.CeleryTaskMiddleware',
'api.base.middleware.TokuTransactionMiddleware',
'django.contrib.sessions.mi | ddleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
... |
Hernanarce/pelisalacarta | python/version-mediaserver/platformcode/launcher.py | Python | gpl-3.0 | 24,841 | 0.017736 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta 4
# Copyright 2015 tvalacarta@gmail.com
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# --... | earch, para mostrar el teclado y lanzar la busqueda con el texto indicado.
elif item.action=="search":
logger.info("pelisalacar | ta.platformcode.launcher search")
tecleado = platformtools.dialog_input()
if not tecleado is None:
itemlist = channelmodule.search(item,tecleado)
else:
itemlist = []
elif item.channel == "channelselector":
import channelselector
if item.action =="mainlist":
... |
uwcirg/true_nth_usa_portal | portal/migrations/versions/424f18f4c1df_.py | Python | bsd-3-clause | 1,316 | 0.006079 | """empty message
Revision ID: 424f18f4c1df
Revises: 106e3631fe9
Create Date: 2015-06-23 11:31:08.548661
"""
# revision identifiers, used by Alembic.
revision = '424f18f4c1df'
down_revision = '106e3631fe9'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.diale... | create_type=False)
def upgrade():
### commands auto generated by Alembic - please adjust! ###
providers_list.create(op.get_bind(), checkfirst=False)
op.create_table('auth_providers',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('provider', providers_l... | id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('auth... |
ltucker/giblets | giblets/__init__.py | Python | bsd-3-clause | 287 | 0.003484 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Luke Tucker
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of t | his distribution.
#
# Author: Luke T | ucker <voxluci@gmail.com>
#
from giblets.core import * |
meganbkratz/acq4 | acq4/devices/DAQGeneric/InputChannelTemplate.py | Python | mit | 3,321 | 0.001807 | # -*- coding: utf-8 -*-
from __future__ import print_function
# Form implementation generated from reading ui file 'InputChannelTemplate.ui'
#
# Created: Sun Feb 22 13:29:16 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
... | t.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.groupBox = GroupBox(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setCheckable(False)
self.groupBox.setObjectNam... | groupBox)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(5, 0, 0, 0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.recordCheck = QtGui.QCheckBox(self.groupBox)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self... |
Entropy512/libsigrokdecode | decoders/rgb_led_ws281x/pd.py | Python | gpl-3.0 | 4,320 | 0.003472 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2016 Vladimir Ermakov <vooon341@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of t... | self.samplerate = value
def handle_bits(self, samplen | um):
if len(self.bits) == 24:
grb = reduce(lambda a, b: (a << 1) | b, self.bits)
rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0x0000ff)
self.put(self.ss_packet, samplenum, self.out_ann,
[2, ['#%06x' % rgb]])
self.bits = []
... |
kcii/numpy-pyqt-multiproc-problem | fork.py | Python | mit | 868 | 0.009217 | #!/usr/bin/env python
import PyQt4.QtCore # <- this line causes the error
from multiprocessing import Process
class PTask(Process):
def __init__(self, func):
Process.__init__(self)
self._func = func
def run(self):
self._func()
def f():
try:
import numpy as np
im... | for i in range(1000):
print "i: ", i
n = npl.pinv(np | .random.rand(100,100))
# Sometimes the segfault or malloc error doesn't occur
# on the first use of pinv.
print "pinv success"
except:
# This just means the random matrix was not invertible
# but that pinv executed correctly.
print "exception success"
if __name__ ... |
tellesnobrega/storm_plugin | sahara/service/trusts.py | Python | apache-2.0 | 1,897 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | if cluster.trust_id:
ctx = context.current()
ctx.username = CONF.keystone_authtoken.admin_user
ctx.tenant_id = cluster.tenant_id
client = keystone.client_for_trusts(cluster.trust_id)
ctx.token = client.auth_token
ctx.service_catalog = json.dumps(
client.se... | trusts(cluster.trust_id)
keystone_client.trusts.delete(cluster.trust_id)
|
jieter/django-localflavor | localflavor/is_/forms.py | Python | bsd-3-clause | 2,973 | 0.002018 | """Iceland specific form helpers."""
from __future__ import unicode_literals
from django.forms import ValidationError
from django.forms.fields import RegexField
from django.forms.widgets import Select
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from localflavo... | t IS_POSTALCODES
class ISIdNumberField(EmptyValueCompatMixin, RegexField):
"""
Icelandic identification number (kennitala).
This is a number every citizen of Iceland has.
"""
default_error_messages = {
'invalid': _('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX... | gth=11, min_length=10, *args, **kwargs):
super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$',
max_length, min_length, *args, **kwargs)
def clean(self, value):
value = super(ISIdNumberField, self).clean(value)
if value in self.empty_valu... |
pipermerriam/web3.py | web3/utils/six/__init__.py | Python | mit | 245 | 0 | impor | t sys
if sys.version_info.major == 2:
from .six_py2 import (
urlparse,
urlunparse,
Generator,
)
else:
from .six_py3 impor | t ( # noqa: #401
urlparse,
urlunparse,
Generator,
)
|
PayloadSecurity/VxAPI | cli/wrappers/cli_caller.py | Python | gpl-3.0 | 6,741 | 0.003265 | from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJ... | n path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
... | for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file... |
BirkbeckCTP/janeway | src/security/templatetags/securitytags.py | Python | agpl-3.0 | 2,227 | 0.001347 | from django import template
from security import logic
register = template.Library()
# General role-based checks
@register.simple_tag(takes_context=True)
def is_author(context):
request = context['request']
return request.user.is_author(request)
@register.simple_tag(takes_context=True)
def is_editor(conte... | t):
request = context['request']
if request.user.is_anonymous():
return False
return request.user.is_editor(request)
@register.simple_tag(takes_context=True)
def is_section_editor(context):
request = context['request']
| if request.user.is_anonymous():
return False
return request.user.is_section_editor(request)
@register.simple_tag(takes_context=True)
def is_production(context):
request = context['request']
return request.user.is_production(request)
@register.simple_tag(takes_context=True)
def is_reviewer(cont... |
suokko/python-apt | tests/test_cache_invocation.py | Python | gpl-2.0 | 863 | 0.001159 | #!/usr/bin/python
import unittest
import apt_pkg
import apt.pr | ogress.base
class TestCache(unittest.TestCase):
"""Test invocation of apt_pkg.Cache()"""
def setUp(self):
apt_pkg.init_config()
apt_pkg.init_system()
def test_wrong_in | vocation(self):
"""cache_invocation: Test wrong invocation."""
apt_cache = apt_pkg.Cache(progress=None)
self.assertRaises(ValueError, apt_pkg.Cache, apt_cache)
self.assertRaises(ValueError, apt_pkg.Cache,
apt.progress.base.AcquireProgress())
self.assert... |
DShokes/ArcREST | samples/update_largethumbnail.py | Python | apache-2.0 | 2,476 | 0.008078 | """
This sample shows how to update the
large thumbnail of an item
Python 2.x
ArcREST 3.0.1
"""
import arcrest
from arcresthelper import securityhandlerhelper
from arcresthelper import common
def trace():
"""
trace finds the line, the filename
and error message and returns it
to ... | hh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
if shh.valid == False:
print shh.message
else:
admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
content = admin.content
item = content.getIte | m(itemId)
itemParams = arcrest.manageorg.ItemParameter()
itemParams.largeThumbnail = pathToImage
print item.userItem.updateItem(itemParameters=itemParams)
except (common.ArcRestHelperError),e:
print "error in function: %s" % e[0]['function']
print "error on line... |
pythonpopayan/bermoto | backend/handlers/transactional_messaging.py | Python | mit | 3,778 | 0.002649 | """
handlers for transactional messaging service
"""
import json
# tornado imports
from tornado.queues import Queue
from tornado import websocket, gen, web
#local imports
from settings import DEBUG
#===============================================================================
# WEBSOCKETS SERVER
#================... | def create_user(self, message):
# IMPLEMETAR LOGICA DEL SERVICIO AQUI
# 1. vaidar si la informacion esta completa
# se necesita al menos: name, password
# se pide tambien el correo, | (trabajar en el modelo de bd de usuario)
# 2. validar si usuario no existe
# ir a la base de datos y ver si existe el user_name que llego
# mandar mensaje de ya existente
# 3. validar si esta bien la contraseña
# minimo 8 caracteres, letras y numeros al menos
# mandar u... |
reingart/gui2py | gui/tools/propeditor.py | Python | lgpl-3.0 | 12,658 | 0.006241 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"Visual Property Editor (using wx PropertyGrid) of gui2py's components"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart"
__license__ = "LGPL 3.0"
# some parts where inspired or borrowed from wxFormBuilders & wxPython... | value=spec.mapping[value])
else:
try:
prop = prop(name, value=value)
except Exception, e:
print "CANNOT LOAD PROPERTY", name, value, e
... |
if spec.group is None:
pg.Append(prop)
if readonly:
pg.SetPropertyReadOnly(prop)
else:
# create a group hierachy (wxpg uses dot notation)
... |
IncidentNormal/TestApps | ALE/HF_Sim_Book.py | Python | gpl-2.0 | 17,239 | 0.019375 | '''
Created on Sep 15, 2010
@author: duncantait
'''
from SimPy.Simulation import *
import numpy as np
import random
import math
class G():
#Settings for HF Stations
num_channels = 18
num_stations = 10
class Network():
stations = []
class Medium():
def __init__(self):
self.channel... | tionSettings for N in Network.stations if N.ID==self.ID][0]
def sendMessage(self):
while True:
#every so often operator wants to send a message: adds to queue.
yield hold, self, random.uniform(0,1200)
#Create a Message of type 'CALL'
frameInfo = frameDetails(s... | = self.ChannelOrder(frameInfo.destination)
yield put,self,self.Tx.sendQ,[frameInfo]
yield hold, self, random.uniform(0,1200)
def decideDestination(self):
while True:
dest = random.randint(0,G.num_channels-1)
if dest != self.ID:
return dest
... |
Tijndagamer/bin | validate_ip.py | Python | mit | 609 | 0.00821 | #!/usr/bin/python3
# Small script to validate a given IP address
import socket
import sys
def validate_ip(ip):
try:
socket.inet_p | ton(socket.AF_INET, ip)
return (True,"IPv4")
except socket.error:
try:
socket.inet_pton(socket.AF_INET6, ip)
return(True,"IPv6")
except socket.error:
return(False,"")
if __name__ == "__ma | in__":
try:
ip = sys.argv[1]
state, version = validate_ip(ip)
if state:
print(ip + " is a valid " + version + " address")
except IndexError:
print("No IP given")
|
lsgunth/nvme-cli | tests/nvme_writeuncor_test.py | Python | gpl-2.0 | 2,752 | 0 | # Copyright (c) 2015-2016 Western Digital Corporation or its affiliates.
#
# 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 versio... | block_count)
return self.exec_cmd(write_uncor_cmd)
def test_write_uncor(self):
""" Testcase ma | in """
assert_equal(self.nvme_read(), 0)
assert_equal(self.write_uncor(), 0)
assert_not_equal(self.nvme_read(), 0)
assert_equal(self.nvme_write(), 0)
assert_equal(self.nvme_read(), 0)
|
MapofLife/MOL | app/tile_handler.py | Python | bsd-3-clause | 3,335 | 0.009595 | """This module contains a tile cache handler."""
__author__ = 'Aaron Steele'
# MOL imports
import cache
# Standard Python imports
import hashlib
import logging
import os
import urllib
import webapp2
# Google App Engine imports
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from ... | # gc means Grid Cache
grid_json = memcache.get(grid_key)
if not grid_json:
grid_json = cache.get(grid_key)
if not grid_json:
result = urlfetch.fetch(grid_url, deadline=60)
if result.status_code == 200 or result.status_code == 304: ... | grid_json = result.content
cache.add(grid_key, grid_json)
memcache.add(grid_key, grid_json)
else:
memcache.add(grid_key, grid_json)
if not grid_json:
self.error(404)
else:
self.response.headers["Content... |
edisonlz/fruit | web_project/base/site-packages/django/contrib/formtools/tests/wizard/test_cookiestorage.py | Python | apache-2.0 | 1,813 | 0.003309 | from django.test import TestCase
from django.core import signing
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formtools.wizard.storage.cookie import CookieStorage
from django.contrib.formtool... | nipulated'
self.assertRaises(SuspiciousOperation, storage.load_data)
def test_reset_cookie(self):
request = get_request()
storage = self.get_storage()('wizard1', request, None)
storage.data = {'key1': 'value1'}
response = HttpResponse()
storage.update_response(resp... | ie_data = cookie_signer.sign(storage.encoder.encode(storage.data))
self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data)
storage.init_data()
storage.update_response(response)
unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value)
... |
ain7/www.ain7.org | ain7/annuaire/__init__.py | Python | lgpl-2.1 | 55 | 0 | default_app_co | nfig = 'ain7.annuaire.management.FillDb'
| |
dmlc/xgboost | python-package/xgboost/sklearn.py | Python | apache-2.0 | 71,896 | 0.002031 | # pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme, too-many-lines
"""Scikit-Learn Wrapper interface for XGBoost."""
import copy
import warnings
import json
import os
from typing import Union, Optional, List, Dict, Callable, Tuple, Any, TypeVar, Type, cast
from typing import Sequence
import nump... | mator_type usually defined in scikit-learn base
classes."""
_estimator_type = "ranker"
def _check_rf_callback(
early_stopping_rounds: Optional[int],
callbacks: Optional[Sequence[TrainingCallback]],
) -> None:
| if early_stopping_rounds is not None or callbacks is not None:
raise NotImplementedError(
"`early_stopping_rounds` and `callbacks` are not implemented for"
" random forest."
)
_SklObjective = Optional[
Union[
str, Callable[[np.ndarray, np.ndarray], Tuple[np.ndarray... |
CianDuffy/nodecopter-security | python/pedestrian_detect.py | Python | mit | 1,228 | 0.004886 | import os
import cv2
import time
drone_output_path_string = "./images/intruder-detection/drone-output/drone-output.png"
detected_image_path_string = "./images/intruder-detection/detected/intruder-detected.png"
full_body_haar_cascade_path_string = "./node_modules/opencv/data/haarcascade_fullbody.xml"
def clear_direct... | _path_string)
intruders = intruder_classifier.detectMultiScale(drone_output_image)
if len(intruders) > 0:
for (x, y, w, h) in intruders:
cv2.rectangle(drone_output_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imwrite(detected_image_path_string, drone_output_image)
os.... |
if __name__ == '__main__':
main()
|
sklam/numba | numba/cuda/cudadrv/nvvm.py | Python | bsd-2-clause | 24,855 | 0.000523 | """
This is a direct translation of nvvm.h
"""
import logging
import re
import sys
from ctypes import (c_void_p, c_int, POINTER, c_char_p, c_size_t, byref,
c_char)
import threading
from llvmlite import ir
from .error import NvvmError, NvvmSupportError
from .libs import get_libdevice, open_libdevi... | opts.append('-opt=%d' % options.pop('opt'))
if options.get('arch'):
opts.append('-arch=%s' % options.pop('arch'))
other_options = (
'ftz',
'prec_sqrt',
'prec_div',
'fma',
)
for k in other_options:
if k in options... | v = int(bool(options.pop(k)))
opts.append('-%s=%d' % (k.replace('_', '-'), v))
# If there are any option left
if options:
optstr = ', '.join(map(repr, options.keys()))
raise NvvmError("unsupported option {0}".format(optstr))
# compile
c_opts ... |
edisonlz/fruit | web_project/base/site-packages/django/conf/locale/mk/formats.py | Python | apache-2.0 | 1,758 | 0.001138 | # -*- 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 = 'd F Y'
TIME_FORMAT = 'H:i:s'
DATE... | '
'%d.%m.%y.', # '25.10 | .06.'
'%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59'
'%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200'
'%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30'
'%d. %m. %Y.', # '25. 10. 2006.'
'%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59'
'%d. %m. %y. %H:%M:%S.%f', # '2... |
parthea/datalab | tools/cli/commands/create.py | Python | apache-2.0 | 37,422 | 0 | # Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | `datalab` and `logger` users exist with their
# home directories setup correctly.
useradd datalab -u 2000 || useradd datalab
useradd logger -u 2001 || useradd logger
# In case the instance has started before, the `/home/datalab` directory
# may already exist, but with the incorrect user ID (since `/etc/passwd`
# is sa... | ld force the file ownership under `/home/datalab` to match
# the current UID for the `datalab` user.
chown -R datalab /home/datalab
chown -R logger /home/logger
PERSISTENT_DISK_DEV="/dev/disk/by-id/google-datalab-pd"
MOUNT_DIR="/mnt/disks/datalab-pd"
MOUNT_CMD="mount -o discard,defaults ${{PERSISTENT_DISK_DEV}} ${{MOU... |
anthraxx/pwndbg | pwndbg/chain.py | Python | mit | 4,555 | 0.003305 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dere... | chain = get(value, limit, offset, hard_stop, hard_end)
arrow_left = C.arrow(' %s ' % config_arrow_left)
arrow_right = C.arrow( | ' %s ' % config_arrow_right)
# Colorize the chain
rest = []
for link in chain:
symbol = pwndbg.symbol.get(link) or None
if symbol:
symbol = '%#x (%s)' % (link, symbol)
rest.append(M.get(link, symbol))
# If the dereference limit is zero, skip any enhancements.
if... |
jmuhlich/indra | indra/reach/reach_reader.py | Python | bsd-2-clause | 1,451 | 0.000689 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import logging
from indra.java_vm import autoclass, JavaException
logger = logging.getLogger('reach_reader')
class ReachReader(object):
"""The ReachReader wraps a singleton instance of the REACH reader.
Th... | ----------
| api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.