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 |
|---|---|---|---|---|---|---|---|---|
rlefevre1/hpp-rbprm-corba | src/hpp/corbaserver/rbprm/rbprmbuilder.py | Python | lgpl-3.0 | 12,303 | 0.017719 | #!/usr/bin/env python
# Copyright (c) 2014 CNRS
# Author: Steve Tonneau
#
# This file is part of hpp-rbprm-corba.
# hpp-rbprm-corba is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either version
# 3 of ... | )
self.name = urdfName
self.displayName = urdfName
self.tf_root = "base_link"
self.rootJointType = rootJointType
self.jointNames = self.client.basic.robot.getJointNames ()
self.allJointNames = self.client.basic.robot.getAllJointNames ()
self.client.basic.robot.meshPackageName = meshPackageName
self.me... | .packageName = packageName
self.urdfName = urdfName
self.urdfSuffix = urdfSuffix
self.srdfSuffix = srdfSuffix
rankInConfiguration = rankInVelocity = 0
for j in self.jointNames:
self.rankInConfiguration [j] = rankInConfiguration
rankInConfiguration += self.client.basic.robot.getJointConfigSize (j)
sel... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_generated_aiplatform_v1_model_service_export_model_sync.py | Python | apache-2.0 | 1,552 | 0.000644 | # -*- coding: utf-8 -*-
# Copyright 2020 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... | oogle-cloud-aiplatform
# [START aiplatform_generated_aiplatform_v1_ModelService_ExportModel_sync]
from google.cloud import aiplatform_v1
def sample_export_model():
# Create a client
client = aiplatform_v1.ModelServiceClient()
# Initialize request argument(s)
request = aiplatform_v1.ExportModelReque... | )
# Make the request
operation = client.export_model(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END aiplatform_generated_aiplatform_v1_ModelService_ExportModel_sync]
|
vbelakov/h2o | py/testdir_single_jvm/test_GLM2_many_cols_libsvm.py | Python | apache-2.0 | 2,663 | 0.009763 | import unittest, random, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm
def write_syn_libsvm_dataset(csvPathname, rowCount, colCount, SEED):
r1 = random.Random(SEED)
dsf = open(csvPathname, "w+")
for i in range(rowCount):
rowDa... |
print "Creating random libsvm:", csvPathname
write_syn_libsvm_dataset(csvPathname, rowCount, colCount, SE | EDPERFILE)
parseResult = h2i.import_parse(path=csvPathname, hex_key=hex_key, schema='put', timeoutSecs=timeoutSecs)
print "Parse result['destination_key']:", parseResult['destination_key']
# We should be able to see the parse result?
inspect = h2o_cmd.runInspect(None, p... |
crunchmail/munch-core | src/munch/apps/campaigns/migrations/0002_permissions.py | Python | agpl-3.0 | 9,257 | 0.001296 | # -*- coding: utf-8 -*-
from django.db import migrations
from django.core.management.sql import emit_post_migrate_signal
PERMISSIONS = {
'mailstatus': [
('add_mailstatus', 'Can add mail status'),
('change_mailstatus', 'Can change mail status'),
('change_mine_mailstatus', 'Can change_mine ma... | ions_messageattachment', ],
'previewmail': [
'change_organizations_previewmail',
'delete_organizations_previewmail',
'view_organizations_previewmail', ],
},
}
def update_content_types(apps, schema_editor):
db_alias = schema_editor.connection.alias
emit_post_migr... | ault', db_alias)
def load_permissions(apps, schema_editor):
Group = apps.get_model('auth', 'group')
Permission = apps.get_model('auth', 'permission')
ContentType = apps.get_model('contenttypes', 'contenttype')
# Delete previous permissions
for model in PERMISSIONS:
content_type = ContentT... |
avsaj/rtpmidi | rtpmidi/test/test_recovery_journal_chapters.py | Python | gpl-3.0 | 22,784 | 0.01207 | from twisted.trial import unittest
from rtpmidi.engines.midi.recovery_journal_chapters import *
class TestNote(unittest.TestCase):
def setUp(self):
self.note = Note()
def test_note_on(self):
#simple
note_to_test = self.note.note_on(100, 90)
#Testing type
assert(type(n... | .append([[176, i, 100],6])
def test_header(self):
"""Test header creation ChapterC"""
#Creating header
header = self.chapter_c.header(10, 1)
#Testing type
assert(type(header)==str), self.fail("Wrong type returned")
#Testing length
assert(len( | header)==1), self.fail("Wrong header size")
def test_parse_header(self):
"""Test header parsing ChapterC"""
#Creating header
header = self.chapter_c.header(10, 1)
#Parsing header
header_parsed = self.chapter_c.parse_header(header)
#Testing type
assert(type(... |
TemplateVoid/mapnik | tests/python_tests/image_filters_test.py | Python | lgpl-2.1 | 2,704 | 0.005547 | #!/usr/bin/env python
from nose.tools import *
from utilities import execution_path, run_all
from utilities import side_by_side_image
import os, mapnik
import re
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))... | fail_im = side_by_side_image(expected_im, im)
fail_im.s | ave('/tmp/mapnik-style-image-filter-' + filename + '.fail.png','png32')
eq_(len(fails), 0, '\n'+'\n'.join(fails))
if __name__ == "__main__":
setup()
exit(run_all(eval(x) for x in dir() if x.startswith("test_")))
|
frreiss/tensorflow-fred | tensorflow/python/ops/numpy_ops/np_array_ops.py | Python | apache-2.0 | 60,984 | 0.010675 | # Copyright 2020 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... | tem in the list. So e.g. when converting [2., 2j]
# to a tensor, i | t will select float32 as the inferred type and not be able
# to convert the list to a float 32 tensor.
# Since we have some information about the final dtype we care about, we
# supply that information so that convert_to_tensor will do best-effort
# conversion to that dtype first.
result_t = np_arra... |
JarronL/pynrc | dev_utils/DMS/nircam2ssb.py | Python | mit | 16,914 | 0.018565 | #! /usr/bin/env python
# This script converts the fits files from the NIRCam CRYO runs
# into ssb-conform fits files.
import sys, os,re,math
import optparse,scipy
from jwst import datamodels as models
from astropy.io import fits as pyfits
import numpy as np
class nircam2ssbclass:
def __init__(self):
... | f.modApartIDs)):
self.part2mod[self.modApartIDs[i]]={}
self.part2mod[self.modBpartIDs[i]]={}
self.part2mod[self.modApartIDs[i]]['module']='A'
self.part2mod[self.modBpartIDs[i]]['module']='B'
if i == 4 or i == 9 or i==14:
self.part2mod[self.modA... | self.modBpartIDs[i]]['channel']='LONG'
self.part2mod[self.modBpartIDs[i]]['detector'] = 'NRCBLONG'
elif i < 4:
self.part2mod[self.modApartIDs[i]]['channel']='SHORT'
self.part2mod[self.modApartIDs[i]]['detector']='NRCA'+str(i+1)
self.part2mod[se... |
drdangersimon/EZgal | examples/convert/convert_basti.py | Python | gpl-2.0 | 3,979 | 0.047751 | #!/usr/bin/python
import glob,re,sys,math,pyfits
import numpy as np
import utils
if len( sys.argv ) < 2:
print '\nconvert basti SSP models to ez_gal fits format'
print 'Run in directory with SED models for one metallicity'
print 'Usage: convert_basti.py ez_gal.ascii\n'
sys.exit(2)
fileout = sys.argv[1]
# try to... | in!
print 'Loadin | g masses from %s' % mass_file[0]
data = utils.rascii( mass_file[0], silent=True )
masses = data[:,10:14].sum( axis=1 )
has_masses = True
files = glob.glob( 'SPEC*agb*' )
nages = len( files )
ages = []
for (i,file) in enumerate(files):
ls = []
this = []
# extract the age from the filename and convert to years
... |
ssarangi/numba | numba/cuda/tests/cudapy/test_sync.py | Python | bsd-2-clause | 3,582 | 0 | from __future__ import print_function, absolute_import
import numpy as np
from numba import cuda, int32, float32
from numba.cuda.testing import unittest
from numba.config import ENABLE_CUDASIM
def useless_sync(ary):
i = cuda.grid(1)
cuda.syncthreads()
ary[i] = i
def simple_smem(ary):
N = 100
sm ... | y):
i = cuda.grid(1)
sm = cuda.shared.array(0, float32)
sm[i] = i * 2
cuda.syncthreads()
ary[i] = sm[i]
def use_threadfence(ary):
ary[0] += 123
cuda.thre | adfence()
ary[0] += 321
def use_threadfence_block(ary):
ary[0] += 123
cuda.threadfence_block()
ary[0] += 321
def use_threadfence_system(ary):
ary[0] += 123
cuda.threadfence_system()
ary[0] += 321
class TestCudaSync(unittest.TestCase):
def test_useless_sync(self):
compiled =... |
thilbern/scikit-learn | sklearn/manifold/spectral_embedding_.py | Python | bsd-3-clause | 19,492 | 0.000103 | """Spectral Embedding"""
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Wei LI <kuantkid@gmail.com>
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse
from scipy.linalg import eigh
from scipy.sparse.linalg import lobpcg
from ..base import BaseEstimator
from ..ext... | start from node 0
return _graph_connected_component(graph, 0).sum() == graph.shape[0]
def _set_diag(laplacian, value):
"""Set the diagonal of the l | aplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition
Parameters
----------
laplacian : array or sparse matrix
The graph laplacian
value : float
The value of the diagonal
Returns
-------
laplacian : array or sparse matrix
An ... |
natetrue/ReplicatorG | skein_engines/skeinforge-0006/skeinforge_tools/oozebane.py | Python | gpl-2.0 | 29,728 | 0.038415 | """
Oozebane is a script to turn off the extruder before the end of a thread and turn it on before the beginning.
The default 'Activate Oozebane' checkbox is on. When it is on, the functions described below will work, when it is off, the functions
will not be called.
The important value for the oozebane preferences ... | nd of the
line will be thinner.
When oozebane turns the extruder off, it slows the feedrate down in steps so in theory the thread will remain at roughly the same
thickness until the end. The "Turn Off Steps" preference is the number of steps, the more steps the smaller the size of the step that
the feedrate will be d... | Maximum Distance" preference is the
maximum distance before the thread starts that the extruder will be turned off, the default is 1.2. The longer the extruder has been
off, the earlier the extruder will turn back on, the ratio is one minus one over e to the power of the distance the extruder has been
off over the "Ea... |
JulyKikuAkita/PythonPrac | cs15211/BinaryTreeTilt.py | Python | apache-2.0 | 2,991 | 0.003009 | __source__ = 'https://leetcode.com/problems/binary-tree-tilt/'
# Time: O(n)
# Space: O(n)
#
# Description: 563. Binary Tree Tilt
#
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values
# and the sum of... | a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* } |
*/
# 3ms 100%
class Solution {
int res = 0;
public int findTilt(TreeNode root) {
postOrder(root);
return res;
}
private int postOrder(TreeNode root) {
if (root == null) return 0;
int left = postOrder(root.left);
int right = postOrder(root.right);
res +... |
rjw57/rbc | rbc/parser.py | Python | mit | 24,773 | 0.000121 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# CAVEAT UTILITOR
#
# This file was automatically generated by Grako.
#
# https://pypi.python.org/pypi/grako/
#
# Any changes you make to it will be overwritten the next time
# the file is generated.
from __future__ import print_function, division, absolute_import, un... | self.ast._define(
['name', 'maxidx'],
[]
)
@graken()
def _extrnstatement_(self):
self._token('extrn')
self._cut()
self._namelist_()
self.ast['@'] = self.last_node
self._token(';')
@graken()
def _compoundstatement_(self):
... | atement_()
self._cut()
self._closure(block1)
self.ast['@'] = self.last_node
self._token('}')
@graken()
def _ifstatement_(self):
self._token('if')
self._cut()
self._token('(')
self._expr_()
self.ast['cond'] = self.last_node
self... |
lmazuel/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/vault_secret_group_py3.py | Python | mit | 1,468 | 0.001362 | # 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 ... | ificates': {'key': 'vaultCertificates', 'type': '[VaultCertificate]'},
}
def __init__(self, *, source_vault=None, vault_certificates=None, **kwargs) -> None:
super(VaultSecretGroup, self).__init__(**kwargs)
| self.source_vault = source_vault
self.vault_certificates = vault_certificates
|
timokoola/mjuna | mjuna/mjuna/wsgi.py | Python | apache-2.0 | 385 | 0.002597 | """
WSGI config for mjuna project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.dj | angoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mjuna.settings")
from django.core.wsgi import get_wsgi_application
application = get_w | sgi_application()
|
mdsol/flask-mauth | tests/test_authenticators.py | Python | mit | 42,880 | 0.002705 | # -*- coding: utf-8 -*-
import datetime
import json
import time
from unittest import TestCase
import requests_mauth
import mock
from mock import patch
from six import assertRegex
from flask_mauth.mauth.authenticators import LocalAuthenticator, AbstractMAuthAuthenticator, RemoteAuthenticator, \
mws_attr
from flas... | )
def test_time_valid_empty_header(self):
"""With | an empty header, we get an exception"""
request = mock.Mock(headers={settings.x_mws_time: ''})
with self.assertRaises(InauthenticError) as exc:
self.authenticator.time_valid(request=request)
self.assertEqual(str(exc.exception),
"Time verification failed for M... |
mrunge/openstack_horizon | openstack_horizon/dashboards/identity/groups/tables.py | Python | apache-2.0 | 8,157 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | : getattr(obj, 'description', None),
verbose_name=_('Description'))
id = tables.Column('id', verbose_name=_('Group ID'))
class Meta:
name = "groups"
| verbose_name = _("Groups")
row_actions = (ManageUsersLink, EditGroupLink, DeleteGroupsAction)
table_actions = (GroupFilterAction, CreateGroupLink,
DeleteGroupsAction)
class UserFilterAction(tables.FilterAction):
def filter(self, table, users, filter_string):
"""Na... |
matthias-k/pysaliency | tests/test_numba_utils.py | Python | mit | 762 | 0.001312 | from hypothesis import given, strategies as st
import numpy as np
from pysaliency.numba_utils import auc_for_one_positive
from pysaliency.roc import general_roc
def test_auc_for_one_positive | ():
assert auc_for_one_positive(1, [0, 2]) == 0.5
assert auc_for_one_positive(1, [1]) == 0.5
assert auc_for_one_positive(3, [0]) == 1.0
assert auc_for_one_positive(0, [3]) == 0.0
@given(st.lists( | st.floats(allow_nan=False, allow_infinity=False), min_size=1), st.floats(allow_nan=False, allow_infinity=False))
def test_simple_auc_hypothesis(negatives, positive):
old_auc, _, _ = general_roc(np.array([positive]), np.array(negatives))
new_auc = auc_for_one_positive(positive, np.array(negatives))
np.testin... |
mogoweb/chromium-crosswalk | tools/licenses.py | Python | bsd-3-clause | 16,956 | 0.002359 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility for checking and processing licensing information in third_party
directories.
Usage: licenses.py <command>
Commands:
... | scan third_party directories, verifying that we have licensing info
credits generate about:credits on stdout
(You can also import this as a module.)
"""
import cgi
import os
import sys
# Paths from the root of the tree to directories to skip.
PRUNE_PATHS = set([
# Same module occurs | in crypto/third_party/nss and net/third_party/nss, so
# skip this one.
os.path.join('third_party','nss'),
# Placeholder directory only, not third-party code.
os.path.join('third_party','adobe'),
# Build files only, not third-party code.
os.path.join('third_party','widevine'),
# Only bina... |
noroutine/ansible | lib/ansible/modules/cloud/amazon/s3_lifecycle.py | Python | gpl-3.0 | 15,265 | 0.002489 | #!/usr/bin/python
# Copyright: Ansible Project
# 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': ['stableinterf... | import Lifecycle, Rule, Expiration, Transition
from boto.exception import BotoServerError, S3Respo | nseError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, ec2_argument_spec, get_aws_connection_info
def create_lifecycle_rule(connection, module):
name = module.params.get("name")
expirati... |
ethronsoft/stor | bindings/python/setup.py | Python | bsd-2-clause | 737 | 0.004071 | from setuptools import setup
setup(
name="pystor",
version="0.9.1",
author="Ethronsoft",
author_email='dev@ethronsoft.com',
zip_safe=False,
packages=["ethronsoft", "ethronsoft.pystor"],
license=open( | "LICENSE.txt").read(),
include_package_data=True,
| keywords="nosql document store serverless embedded",
url="https://github.com/ethronsoft/stor",
description="Python bindings to esft::stor, a C++ NoSQL serverless document store",
install_requires=[
'enum34'
],
setup_requires=[
'pytest-runner'
],
tests_require=[
'pyte... |
opennode/nodeconductor-openstack | src/waldur_openstack/openstack/urls.py | Python | mit | 928 | 0.009698 | from . import views
def register_in(router):
router.register(r'openstack', views.OpenStackServiceViewSet, base_name='openstack')
router.register(r'openstack-images', views.ImageViewSe | t, base_name='openstack-image')
router.register(r'openstack-flavors', views.FlavorViewSet, base_name='openstack-flavor')
router.register(r'openstack-tenants', views | .TenantViewSet, base_name='openstack-tenant')
router.register(r'openstack-service-project-link', views.OpenStackServiceProjectLinkViewSet, base_name='openstack-spl')
router.register(r'openstack-security-groups', views.SecurityGroupViewSet, base_name='openstack-sgp')
router.register(r'openstack-floating-ips'... |
PreppyLLC-opensource/django-advanced-filters | advanced_filters/migrations/0001_initial.py | Python | mit | 1,420 | 0.003521 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-07 23:02
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', ... | ank=True, max_length=64, null=True)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='created_advanced_filters', to=settings.AUTH_USER_MODEL)),
('groups', models.ManyToManyField(blank=True, to='auth.Group')),
('users', models.Ma... | s={
'verbose_name_plural': 'Advanced Filters',
'verbose_name': 'Advanced Filter',
},
),
]
|
henrymp/coursebuilder | controllers/utils.py | Python | apache-2.0 | 17,556 | 0.000627 | # Copyright 2012 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 ... | etloc, base, None, None, None))
return base
def __init__(self, *args, **kwargs):
super(ApplicationHandler, self).__init__(*args, **kwargs)
self.template_value = {}
| def get_template(self, template_file, additional_dirs=None):
"""Computes location of template files for the current namespace."""
self.template_value[COURSE_INFO_KEY] = self.app_context.get_environ()
self.template_value['is_course_admin'] = Roles.is_course_admin(
self.app_context)... |
shashank971/edx-platform | common/test/acceptance/tests/helpers.py | Python | agpl-3.0 | 24,524 | 0.003058 | """
Test helper functions and base classes.
"""
import inspect
import json
import unittest
import functools
import operator
import pprint
import requests
import os
import urlparse
from contextlib import contextmanager
from datetime import datetime
from path import Path as path
from bok_choy.javascript import js_defined... |
"""
if os.path.exists(filename):
os.remove(filename)
def disable_animations(page):
"""
Disable jQuery and CSS3 animations.
" | ""
disable_jquery_animations(page)
disable_css_animations(page)
def enable_animations(page):
"""
Enable jQuery and CSS3 animations.
"""
enable_jquery_animations(page)
enable_css_animations(page)
@js_defined('window.jQuery')
def disable_jquery_animations(page):
"""
Disable jQuery ... |
TeluguOCR/banti_telugu_ocr | tests/linegraph_test.py | Python | apache-2.0 | 691 | 0.002894 | from random import random
from banti.linegraph import LineGraph
cl | ass Weight():
def __init__(self, val):
self.val = val
def combine(self, other):
return random() < .3, Weight(int(100*random())+(self.val+other.val)//2)
def strength(self):
return self.val
def __repr__(self):
return "{}".format(self.val)
weights = [Weight(val) for val ... | ths = lgraph.get_paths()
for path in paths:
print(path, lgraph.path_strength(path))
print("Strongest Path: ", lgraph.strongest_path()) |
juergenz/pie | src/pie/chat_commands.py | Python | mit | 3,649 | 0.004111 | __all__ = ['chatcommand', 'execute_chat_command', 'save_matchsettings', '_register_chat_command']
import functools
import inspect
from .events import eventhandler, send_event
from .log import logger
from .asyncio_loop import loop
_registered_chat_commands = {} # dict of all registered chat commands
async def exe... | f _registered_chat_commands[cmd].__doc__ is None:
docstr = 'no description set'
else:
docstr = _registered_chat_commands[cmd].__doc__
server.chat_send(cmd + ' - ' + docstr, player)
async def save_matchsettings(server, filename = None):
| await server.rpc.SaveMatchSettings('MatchSettings\\' + server.config.matchsettings)
@chatcommand('/savematchsettings')
async def cmd_savematchsettings(server, player):
await save_matchsettings(server)
server.chat_send('matchsettings saved: ' + server.config.matchsettings)
@chatcommand('/shutdown')
asyn... |
applitools/eyes.selenium.python | applitools/selenium/capture/eyes_webdriver_screenshot.py | Python | apache-2.0 | 9,401 | 0.004148 | from __future__ import absolute_import
import base64
import typing as tp
from selenium.common.exceptions import WebDriverException
from applitools.core import EyesScreenshot, EyesError, Point, Region, OutOfBoundsError
from applitools.utils import image_utils
from applitools.selenium import eyes_selenium_utils
from a... | webdriver for the session.
"""
return EyesWebDriverScreenshot(driver, screenshot=screenshot)
def __init__(self, driver, screenshot=None, screenshot64=None,
is_viewport_scr | eenshot=None, frame_location_in_screenshot=None):
# type: (EyesWebDriver, Image.Image, None, tp.Optional[bool], tp.Optional[Point]) -> None
"""
Initializes a Screenshot instance. Either screenshot or screenshot64 must NOT be None.
Should not be used directly. Use create_from_image/create... |
kotfic/reddit_elfeed_wrapper | reddit_elfeed_wrapper/app.py | Python | gpl-2.0 | 2,387 | 0.001676 | from functools import wraps
from flask import Flask, make_response
from werkzeug.contrib.atom import AtomFeed
from datetime import datetime as dt
from HTMLParser import HTMLParser
from bs4 import BeautifulSoup
import praw
app = Flask(__name__)
def get_api():
USER_AGENT = "reddit_wrapper for personalized rss see: ... | t
@app.route('/r/python.atom')
@reddit("Python Subreddit", "python")
def python(article):
try:
return HTMLParser().unescape(article.self | text_html)
except TypeError:
return ''
@app.route('/r/funny.atom')
@reddit("Funny Subreddit", "funny")
def funny(article):
try:
soup = BeautifulSoup("<img src=\"{}\" />".format(article.url))
return str(soup)
except TypeError:
return ''
@app.route('/r/emacs.atom')
@reddit("... |
tsdmgz/ansible | lib/ansible/modules/storage/netapp/sf_account_manager.py | Python | gpl-3.0 | 8,755 | 0.002284 | #!/usr/bin/python
# (c) 2017, NetApp, 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'],
... | except Exception as e:
self.module.fail_json(msg='Error creating account %s: %s)' % (self.name, to_native(e)),
exception=traceback.format_exc())
def delete_account(self):
try:
self.sfe.remove_account(account_id=self.account_id)
excep... | ())
def update_account(self):
try:
self.sfe.modify_account(account_id=self.account_id,
username=self.new_name,
status=self.status,
initiator_secret=self.initiator_secret,
... |
marc0uk/twit | twit.py | Python | mit | 1,468 | 0.008174 | import sys, os
import tweepy
# File with colon-separaten consumer/access token and secret
consumer_file='twitter.consumer'
access_file='twitter.access'
def __load_auth(file):
if os.path.exists(file):
with open(file) as f:
| tokens = f.readline().replace('\n','').replace('\r','').split(':')
if len(tokens) == 2:
return tokens[0],tokens[1]
else:
raise ValueError("Expecting two colon-separated tokens")
else:
raise IOError("File not found: %s" % file)
def twit(message, secret_dir='/secret')... | nsumer and access tokens and secrets
consumer_token, consumer_secret = __load_auth(os.path.join(secret_dir, consumer_file))
access_token, access_secret = __load_auth(os.path.join(secret_dir, access_file))
#
# Perform OAuth authentication
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
... |
sarumont/py-trello | trello/util.py | Python | bsd-3-clause | 3,964 | 0.002018 | # -*- coding: utf-8 -*-
from __future__ import with_statement, print_function, absolute_import
import os
from requests_oauthlib import OAuth1Session
def create_oauth_token(expiration=None, scope=None, key=None, secret=None, name=None, output=True):
"""
Script to obtain an OAuth token from Trello.
Must ha... | -from-a-user
"""
request_token_url = 'https://trello.com/1/OAuthGetRequestToken'
authorize_url = 'https://trello.com/1/OAuthAuthorizeToken'
access_tok | en_url = 'https://trello.com/1/OAuthGetAccessToken'
expiration = expiration or os.environ.get('TRELLO_EXPIRATION', "30days")
scope = scope or os.environ.get('TRELLO_SCOPE', 'read,write')
trello_key = key or os.environ['TRELLO_API_KEY']
trello_secret = secret or os.environ['TRELLO_API_SECRET']
name ... |
ellmo/rogue-python-engine | rpe/rendering/__init__.py | Python | gpl-3.0 | 15 | 0.066667 | import ren | derer | |
HowAU/python-training | generator/contact.py | Python | apache-2.0 | 2,357 | 0.017288 | from model.contact import Contact #создаем скрипт для генерации групп с последующим сохранением в файл
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try: #почитай про трай
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts","file"]) #опция n задает кол-во... | maxlen))]) #случайным образом выбирает символы из заданной строки
testdata = [Contact(firstname="", middlename="", lastname="")] + [
Contact(firstname="John", middlename="Jay", lastname="Johnson", home="123", mobile="456", work="789",
email= | "a@mail.com", email2="b@mail.com", email3="c@mail.com", phone2="456")
for i in range(random.randrange(n))
]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as out: #открываем файл с флагом w - write (запись) и что-то туда записываем
jsonpickle.set_encoder_optio... |
Tiduszk/CS-100 | Chapter 2/Practice Exam/Practice Exam.py | Python | gpl-3.0 | 1,064 | 0.032895 | #Made by Zachary C. on 9/21/16 last edited on 9/21/16
#CONSTANTS
HOURS_DAY | = 24
MINUTES_HOUR = 60
SECONDS_MINUTE = 60
#1. Greet the user and explain the program
#2. Ask the user to input the number of days
#3. save the number | of days
days = float(input('This program converts days into hours, minutes, and seconds.\nPlease enter the number of days: '))
#4. Calculate the number of hours (days * hours in day)
#5. Save the number of hours
hours = days * HOURS_DAY
#6. Calculate the number of minutes (hours * minutes in hour)
#7. Save the numbe... |
ChunggiLee/ChunggiLee.github.io | Heatmap/newData.py | Python | bsd-3-clause | 22,372 | 0.013767 | # -*- coding: utf-8 -*-
import sys, numpy, scipy
import scipy.cluster.hierarchy as hier
import scipy.spatial.distance as dist
import csv
import scipy.stats as stats
import json
import networkx as nx
from networkx.readwrite import json_graph
def makeNestedJson(leaf) :
leaf=json.loads(leaf)
#A tree is ... | ntNum]-3), int(data[parentNum]))
elif data[parentNum-3] < length and data[parentNum-4] > length:
#print (parentNum-4 , data[parentNum-4])
hier += str(int(data[parentNum-3])) + "."
if (typeRC == "row"):
rowLeafNum = rowLeafNum + 1
if in... | global content
content['label'] = rowNameArr[int(data[parentNum-3])][0]
global content
content['parent'] = int(int(data[parentNum]))
global content
content['id'] = int(data[parentNum-3])
global leafData
... |
stadelmanma/netl-AP_MAP_FLOW | apmapflow/scripts/apm_process_paraview_data.py | Python | gpl-3.0 | 6,758 | 0.000148 | r"""
Description: Generates 2-D data maps from OpenFoam data saved by paraview
as a CSV file. The data has to be saved as point data and the following fields
are expected p, points:0->2, u:0->2. An aperture map is the second main input
and is used to generate the interpolation coordinates as well as convert
the flow ve... |
aper_map = DataField(map_file)
#
# reading first line of paraview file to get column names
logger.info('reading paraview data file')
with open(para_file, 'r') as file:
cols = file.readline()
cols = cols.strip().replace('"', '').lower()
cols = cols.split(',')
#
# rea... | aset and splitting into column vectors
data = sp.loadtxt(para_file, delimiter=',', dtype=float, skiprows=1)
data_dict = {}
for i, col in enumerate(cols):
data_dict[col] = data[:, i]
#
return aper_map, data_dict
def generate_coordinate_arrays(aper_map, para_data_dict):
r"""
Generate... |
dmgawel/helios-server | helios/south_migrations/0007_auto__add_field_voterfile_voter_file_content__chg_field_voterfile_vote.py | Python | apache-2.0 | 11,336 | 0.00891 | # 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 'VoterFile.voter_file_content'
db.add_column('helios_voterfile', 'voter_file_content', self... | {'default': 'None', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '2... | bjectField', [], {'null': 'True'}),
'private_p': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'public_key': ('helios.datatypes.djangofield.LDObjectField', [], {'null': 'True'}),
'questions': ('helios.datatypes.djangofield.LDObjectField', [], {'null': 'True'}),
... |
msullivan/advent-of-code | 2018/8a.py | Python | mit | 712 | 0.007022 | #!/usr/bin/env pyt | hon3
import sys
from collections import defaultdict, deque
from dataclasses import dataclass
@dataclass
class Nobe:
children: object
metadata: object
argh = 0
def parse(data):
global argh
children = data.popleft()
metadata = data.popleft()
print(children, metadata)
nobe = Nobe([], [])
... | sys.stdin][0]
data = deque([int(x) for x in data.split(' ')])
print(data)
print(len(data))
parse(data)
print(argh)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
DarkmatterVale/ChatterBot | chatterbot/adapters/io/io.py | Python | bsd-3-clause | 594 | 0 | from chatterbot.adapters import Adapter
from chatterbot.adapters.exceptions import AdapterNotImplementedError
class IOAdapter(Adapter):
"""
This is an abstract class that represents the interfac | e
that all input-output adapters should implement.
"""
def process_input(self):
"""
Returns data retrieved from the input source.
"""
raise AdapterNotImplementedError()
def process_response(self, input_value):
""" |
Takes an input value.
Returns an output value.
"""
raise AdapterNotImplementedError()
|
gregdp/segger | Segger/iseg_dialog.py | Python | mit | 43,661 | 0.0366 |
# Copyright (c) 2020 Greg Pintilie - pintilie@mit.edu
# 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, me... | ute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is |
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARR... |
metasmile/strsync | strsync/strsync.py | Python | gpl-3.0 | 26,146 | 0.004169 | # -*- coding: utf-8 -*-
# strsync - Automatically translate and synchronize .strings files from defined base language.
# Copyright (c) 2015 metasmile cyrano905@gmail.com (github.com/metasmile)
from __future__ import print_function
import strparser, strparser_intentdefinition, strlocale, strtrans
import time, os, sys, ... | nts
__LOCALE_XCODE_BASE_LOWERCASE__ = 'base'
__DIR_SUFFIX__ = ".lproj"
__FILE_SUFFIX__ = ".strings"
__FILE_INTENT_SUFFIX__ = ".intentdefinition"
__FILE_DICT_SUFFIX__ = ".stringsdict"
__RESOURCE_PATH__ = expanduser(args['target path'])
__ONLY_FOR_KEYS__ = args['only for keys']
__BASE_LAN... | __KEYS_FORCE_TRANSLATE_ALL__ = ('--force-translate-keys' in sys.argv or '-f' in sys.argv) and not __KEYS_FORCE_TRANSLATE__
__KEYS_FOLLOW_BASE__ = args['following_base_keys']
__CUTTING_LENGTH_RATIO__ = (args['cutting_length_ratio_with_base'] or [0])[0]
__FOLLOWING_ALL_KEYS_IFNOT_EXIST__ = args['following_b... |
DemocracyClub/yournextrepresentative | ynr/apps/candidates/management/commands/candidates_create_csv.py | Python | agpl-3.0 | 3,846 | 0.00026 | from collections import defaultdict
from django.core.files.storage import DefaultStorage
from django.core.management.base import BaseCommand, CommandError
from candidates.csv_helpers import list_to_csv, memberships_dicts_for_csv
from elections.models import Election
def safely_write(output_filename, memberships_lis... | have a half written file.
If not using S3, there will be a short time where the file is empty
during write.
"""
csv = list_to_csv(memberships_list)
file_store = DefaultStorage()
with file_store.open(output_filename, "wb") as out_file:
out_file.write(csv.encode("utf-8"))
class Comm... | t(
"--site-base-url",
help="The base URL of the site (for full image URLs)",
)
parser.add_argument(
"--election",
metavar="ELECTION-SLUG",
help="Only output CSV for the election with this slug",
)
def slug_to_file_name(self, slug):... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/effective_network_security_rule_py3.py | Python | mit | 5,742 | 0.003657 | # 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 ... | port or range.
:type source_port_range: str
:pa | ram destination_port_range: The destination port or range.
:type destination_port_range: str
:param source_port_ranges: The source port ranges. Expected values include
a single integer between 0 and 65535, a range using '-' as seperator (e.g.
100-400), or an asterix (*)
:type source_port_ranges: l... |
wolfv/SilverFlask | silverflask/controllers/security_controller.py | Python | bsd-2-clause | 1,824 | 0.002193 | from flask import render_template, jsonify, url_for, abort, request, redirect, current_app
from flask_wtf import Form
from flask_user import current_user
from silverflask import db
from | silverflask.models import User
from silv | erflask.fields import GridField
from silverflask.core import Controller
from silverflask.controllers.cms_controller import CMSController
class SecurityController(CMSController):
url_prefix = CMSController.url_prefix + '/security'
urls = {
'/edit/<int:record_id>': 'edit_user',
'/gridfield': 'get... |
icarito/sugar | extensions/cpsection/webaccount/view.py | Python | gpl-3.0 | 4,477 | 0 | # Copyright (C) 2013, Walter Bender - Raul Gutierrez Segales
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This ... | pacing(style.DEFAULT_SPACING * 4)
grid.set_border_width(style.DEFAULT_SPACING * 2)
grid.set_column_homogeneous(True)
width = Gdk.Screen.width() - 2 * style.GRID_CELL_SIZE
nx = int(width / (style.GRID_CELL_SIZE + style.DEFAULT_SPACING * 4))
self._servic | e_config_box = Gtk.VBox()
x = 0
y = 0
for service in services:
service_grid = Gtk.Grid()
icon = CanvasIcon(icon_name=service.get_icon_name())
icon.show()
service_grid.attach(icon, x, y, 1, 1)
icon.connect('activate', service.config_se... |
lsaffre/atelier | atelier/invlib/utils.py | Python | bsd-2-clause | 8,921 | 0.000897 | # -*- coding: UTF-8 -*-
# Copyright 2017-2021 Rumma & Ko Ltd
# License: BSD, see LICENSE for more details.
"""Utilities for atelier.invlib
"""
from invoke.exceptions import Exit
from atelier.utils import confirm, cd
def must_confirm(*args, **kwargs):
if not confirm(''.join(args)):
raise Exit("User fai... | l = ctx.docs_rsync_dest % name
if "%" in ctx.docs_rsync_dest:
name = '%s_%s' % (ctx.project_name, docs_dir.name)
dest_url = ctx.docs_rsync_dest % name
else:
dest_url = ctx.docs_rsync_dest.format(
prj=ctx.project_name, docs=docs_... | c_tree(ctx, build_dir, dest_url)
def publish_doc_tree(self, ctx, build_dir, dest_url):
print("Publish to ", dest_url)
with cd(build_dir):
args = ['rsync', '-e', 'ssh', '-r']
args += ['--verbose']
args += ['--progress'] # show progress
args += ['--del... |
tylertian/Openstack | openstack F/cinder/cinder/api/sizelimit.py | Python | apache-2.0 | 1,789 | 0.001118 | # vim: tabstop=4 | shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack, 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under... |
googleapis/python-dns | tests/unit/test_changes.py | Python | apache-2.0 | 12,894 | 0.000388 | # Copyright 2015 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 agreed to in writing, s... | etUpConstants(self):
from google.cloud._helpers import UTC
from google.cloud._helpers import _NOW
self.WHEN = _NOW().replace(tzinfo=UTC)
def _make_resource(se | lf):
from google.cloud._helpers import _datetime_to_rfc3339
when_str = _datetime_to_rfc3339(self.WHEN)
return {
"kind": "dns#change",
"id": self.CHANGES_NAME,
"startTime": when_str,
"status": "done",
"additions": [
{
... |
tuck182/syslog-ng-mod-lumberjack-py | src/lumberjack/client/process.py | Python | gpl-2.0 | 3,727 | 0.015562 | from lumberjack.client.file_descriptor import FileDescriptorEndpoint
from lumberjack.client.message_receiver import MessageReceiverFactory
from lumberjack.client.message_forwarder import RetryingMessageForwarder
from lumberjack.client.protocol import LumberjackProtocolFactory
from lumberjack.util.object_pipe import Obj... | , f | orwarder):
factory = MessageReceiverFactory(forwarder, shutdown_params = ShutdownParams(
message = self._shutdown_message,
deferred = self._on_shutdown
))
endpoint = FileDescriptorEndpoint(reactor, self._pipe.get_reader().fileno())
endpoint.listen(factory)
return endpoint
def create_m... |
viktorTarasov/PyKMIP | kmip/services/server/crypto/api.py | Python | apache-2.0 | 2,580 | 0 | # Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... | Create an asymmetric key pair.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created keys will be compliant.
length(int): The length of the keys to be created. This value must
be compliant with the cons... | dict: A dictionary containing the public key data, with the
following key/value fields:
* value - the bytes of the key
* format - a KeyFormatType enumeration for the bytes format
dict: A dictionary containing the private key data, identical in
... |
Azulinho/flocker | flocker/provision/_install.py | Python | apache-2.0 | 36,812 | 0 | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.provision.test.test_install -*-
"""
Install flocker on a remote node.
"""
import posixpath
from textwrap import dedent
from urlparse import urljoin, urlparse
from effect import Func, Effect
import yaml
from zope.interface impo... | rted.
"""
distribution_to_url = {
# TODO instead of hardcoding keys, use the _to_Distribution map
# and then choose the name
'centos-7': "https://{archive_bucket}.s3.amazonaws.com/"
"{key}/clusterhq-release$(rpm -E %dist).noarch.rpm".format(
ar... | f using
# ``lsb_release`` but that allows instructions to be shared between
# versions, and for earlier error reporting if you try to install on a
# separate version. The $(ARCH) part must be left unevaluated, hence
# the backslash escapes (one to make shell ignore the $ as a
# s... |
RedHatQE/python-moncov | test/code/while_some_while_some.py | Python | gpl-3.0 | 48 | 0.104167 | i | = 0
while i <3:
while i <2:
i += 1
i + | = 1
|
reuk/waveguide | scripts/python/boundary_modelling.py | Python | gpl-2.0 | 3,922 | 0.001785 | from math import pi, sin, cos, tan, sqrt
from recordclass import recordclass
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
from functools import reduce
def db2a(db):
return np.power(10, (db / 20.0))
def a2db(a):
return 20 * np.log10(a)
def series_coeffs(c):
return redu... | alpha * A) / a0]
a = [1, (-2 * cw0) / a0, (1 - alpha / A) / a0]
return b, a
BiquadMemory = recordclass('BiquadMemory', ['z1', 'z2'])
BiquadCoefficients = recordclass(
'BiquadCoeff | icients', [
'b0', 'b1', 'b2', 'a1', 'a2'])
def biquad_step(i, bm, bc):
out = i * bc.b0 + bm.z1
bm.z1 = i * bc.b1 - bc.a1 * out + bm.z2
bm.z2 = i * bc.b2 - bc.a2 * out
return out
def biquad_cascade(i, bm, bc):
for m, c in zip(bm, bc):
i = biquad_step(i, m, c)
return i
def im... |
if1live/marika | server/sample.py | Python | mit | 6,943 | 0.004609 | ################################################################################
# Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. #
# Leap Motion proprietary and confidential. Not for distribution. #
# Use subject to the terms of the Leap Motion SDK Agreement available at ... | ft hand" if hand.is_left else "Right hand"
print " %s, id %d, position: %s" % (
handType, hand.id, hand.palm_position)
# Get the hand's normal vector and direction
normal = hand.palm_normal
direction = hand.direction
# Calculate the hand's ... | s, roll: %f degrees, yaw: %f degrees" % (
direction.pitch * Leap.RAD_TO_DEG,
normal.roll * Leap.RAD_TO_DEG,
direction.yaw * Leap.RAD_TO_DEG)
# Get arm bone
arm = hand.arm
print " Arm direction: %s, wrist position: %s, elbow position: ... |
radez/packstack | packstack/plugins/cinder_250.py | Python | apache-2.0 | 16,938 | 0.010922 | """
Installs and configures Cinder
"""
import os
import re
import uuid
import logging
from packstack.installer import exceptions
from packstack.installer import processors
from packstack.installer import validators
from packstack.installer import basedefs
from packstack.installer import utils
from packstack.modules... | ,
"VALIDATORS" : [validators.validate_options],
"DEFAULT_VALUE" : "lvm",
"MASK_INPUT" : False,
"LOOSE_VALIDATION": False | ,
"CONF_NAME" : "CONFIG_CINDER_BACKEND",
"USE_DEFAULT" : False,
"NEED_CONFIRM" : False,
"CONDITION" : False },
]
groupDict = { "GROUP_NAME" : "CINDER",
"DESCRIPTION" ... |
shaypal5/ezenum | tests/test_string_enum.py | Python | mit | 408 | 0 | """Testing the StringEnum class."""
import ezenum as eze
def test_basic():
"""Just check it o | ut."""
rgb = eze.StringEnum(['Red', 'Green', 'Blue'])
assert rgb.Red == 'Red'
assert rgb.Green == 'Green'
assert rgb.Blue == 'Blue'
assert rgb[ | 0] == 'Red'
assert rgb[1] == 'Green'
assert rgb[2] == 'Blue'
assert len(rgb) == 3
assert repr(rgb) == "['Red', 'Green', 'Blue']"
|
sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/bandit/plugins/insecure_ssl_tls.py | Python | apache-2.0 | 9,646 | 0 | # -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# SPDX-License-Identifier: Apache-2.0
import bandit
from bandit.core import test_properties as test
def get_bad_proto_versions(config):
return config['bad_protocol_versions']
def gen_config(name):
if name == 'ssl_with_bad... | /poodlebleed.com/
- https://security.openstack.org/
- https://sec | urity.openstack.org/guidelines/dg_move-data-securely.html
.. versionadded:: 0.9.0
"""
bad_ssl_versions = get_bad_proto_versions(config)
for default in context.function_def_defaults_qual:
val = default.split(".")[-1]
if val in bad_ssl_versions:
return bandit.Issue(
... |
gamechanger/kafka-python | kafka/protocol/legacy.py | Python | apache-2.0 | 14,397 | 0.002084 | from __future__ import absolute_import
import logging
import struct
import six
from six.moves import xrange
import kafka.common
import kafka.protocol.commit
import kafka.protocol.fetch
import kafka.protocol.message
import kafka.protocol.metadata
import kafka.protocol.offset
import kafka.protocol.produce
from kafka... | oad(topic, partition, error, tuple(offsets))
for topic, partitions in response.topics
for partition, error, offsets in partitions
]
@classmethod
def encode_metadata_request(cls, topics=(), payloads=None):
"""
Encode a MetadataRequest
Arguments:
... | s not None:
topics = payloads
return |
lmr/autotest | cli/user.py | Python | gpl-2.0 | 2,827 | 0 | #
# Copyright 2008 Google Inc. All Rights Reserved.
"""
The user module contains the objects and methods used to
manage users in Autotest.
The valid action is:
list: lists user(s)
The common options are:
--ulist / -U: file containing a list of USERs
See topic_common.py for a High Level Design and Algorithm.
"""
... | st user list <options>"""
usage_action = 'list'
topic = msg_topic = 'user'
msg_items = '<users>'
def __init__(self):
"""Add to the parser the options common to all the
user actions"""
super(user, self).__init__()
self.p | arser.add_option('-U', '--ulist',
help='File listing the users',
type='string',
default=None,
metavar='USER_FLIST')
self.topic_parse_info = topic_common.item_parse_info(
attri... |
lo-windigo/fragdev | images/urls.py | Python | agpl-3.0 | 801 | 0.004994 | # This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# th | e Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General... | agDev Website. If not, see <http://www.gnu.org/licenses/>.
# Placeholder urlpatterns list, in case views are added
app_name = 'images'
urlpatterns = []
|
J-Adrian-Zimmer/GraphIsomorphism | TestGraphs.py | Python | mit | 5,052 | 0.047902 | from Graph import Graph
def mkTestGraph4():
return Graph(
['a','b','c','d'],
[ ('a','b'),
('b','c'),
('c','a'),
('a','d')
]
)
def mkTestGraph4b(): ## isomorphic with 4
return Graph(
['a','c','b','d'],
... | ges[i+1:]),
Graph(me.numNodes, edges[0:j] + edges[j+1:]).
| relabelledClone()
)
|
macronucleus/chromagnon | Chromagnon/ndviewer/main.py | Python | mit | 43,167 | 0.011328 | #!/usr/bin/env priithon
import os, sys
import six
import wx, wx.lib.scrolledpanel as scrolled
import wx.lib.agw.aui as aui # from wxpython4.0, wx.aui does not work well, use this instead
try:
from ..Priithon import histogram, useful as U
from ..PriCommon import guiFuncs as G ,microscope, imgResample
... | ## each dimension is assgined a number: 0 -- z; 1 -- y; 2 -- x
## each view has two dimensions (x-y view: (1,2); see below viewer2.GLViewer() calls) and
## an axis normal to it (x-y view: 0)
self.viewers = [] # XY, XZ, ZY
self.viewers.append(viewer2.GLViewer(self, dims=(1,2),
... | ))
self._mgr.AddPane(self.viewers[0], aui.AuiPaneInfo().Floatable(False).Name('XY').Caption("XY").BestSize((self.doc.nx, self.doc.ny)).CenterPane().Position(0))
self.viewers[-1].setMyDoc(self.doc, self)
self.viewers[-1].setAspectRatio(self.doc.pxlsiz[-2]/se... |
valentin-krasontovitsch/ansible | lib/ansible/modules/system/firewalld.py | Python | gpl-3.0 | 29,694 | 0.001886 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, Adam Miller <maxamillion@fedoraproject.org>
# 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 = {'metadat... | Rule
from firewall.client import FirewallClientZoneSettings
except ImportError:
# The import errors are handled via FirewallTransaction, don't need to
# duplicate that here
| pass
class IcmpBlockTransaction(FirewallTransaction):
"""
IcmpBlockTransaction
"""
def __init__(self, module, action_args=None, zone=None, desired_state=None, permanent=False, immediate=False):
super(IcmpBlockTransaction, self).__init__(
module, action_args=action_args, desired_st... |
mark-adams/django-waffle | waffle/south_migrations/0004_auto__add_field_flag_testing.py | Python | bsd-3-clause | 5,923 | 0.008779 | # 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 'Flag.testing'
db.add_column('waffle_flag', 'testing', self.gf('django.db.models.fields.Boo... | model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], ... | ,
'authenticated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'everyone': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symme... |
texttochange/vusion-backend | vusion/persist/model_manager.py | Python | bsd-3-clause | 2,407 | 0.001662 | from datetime import datetime
class ModelManager(object):
def __init__(self, db, collection_name, has_stats=False, **kwargs):
self.property_helper = None
self.log_helper = None
s | elf.collection_name = collection_name
self.db = db
if 'logger' in kwargs:
self.log_helper = kwargs['logger']
if collection_name in self.db.collection_names():
self.collection = self.db[collection_name]
| else:
self.collection = self.db.create_collection(collection_name)
if has_stats:
self.add_stats_collection()
def add_stats_collection(self):
self.stats_collection_name = '%s_stats' % self.collection_name
if self.stats_collection_name in self.db.collection_names():
... |
DeepSOIC/Lattice | latticeShapeString.py | Python | lgpl-2.1 | 12,398 | 0.014518 | #***************************************************************************
#* *
#* Copyright (c) 2015 - Victor Titov (DeepSOIC) *
#* <vv.titov@gmail.com> *
#* ... | nt of individual strings")
obj.YAlign = ['None','Top','Bottom','Middle']
obj.addProperty("App::PropertyBool","AlignPrecisionBoundBox","Lattice ShapeString","Use precision bounding box for alignment. Warning: slow!")
obj.addProperty("App::PropertyFile","FullPathToFont","Lattice ShapeStr... | FullPathToFont", 1) # set read-only
obj.Proxy = self
self.setDefaults(obj)
def makeFoolObj(self,obj):
'''Makes an object that mimics a Part::FeaturePython, and makes a Draft
ShapeString object on top of it. Both are added as attributes to self.
... |
Eigenlabs/EigenD | plg_macosx/caprobe.py | Python | gpl-3.0 | 794 | 0.002519 |
#
# Copyright 2009 Eigenlabs Ltd. htt | p://www.eigenlabs.com
#
# This file is part of EigenD.
#
# EigenD is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# EigenD is distrib... | at it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EigenD. If not, see <http://www.gnu.or... |
lowitty/zacademy | bin/trap_snmp_v2_v3.py | Python | mit | 6,374 | 0.004864 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import time
import logging.config
dir_cur = os.path.normpath(os.path.dirname(os.path.abspath(__file__)).split('bin')[0])
if dir_cur not in sys.path:
sys.path.insert(0, dir_cur)
log_dir = os.path.normpath(dir_cur + os.path.sep + 'logs' ... | == options.mode:
if 1 < len(options.list.split(',')):
msg = "We can only send one alarm in Clear mode, you have feed more than one alarm " \
"IDs for the '--list' option."
logging.crit | ical(msg)
else:
t = SnmpTrapUtils.SendTrapNormal(options, traps_map, list_engine[0], list_engine[1], list_engine[2],
list_engine[3], id_file, False)
try:
t.start()
while not t.b_stop:
... |
voutilad/courtlistener | cl/api/urls.py | Python | agpl-3.0 | 2,240 | 0 | from cl.api import views
from cl.audio import api_views as audio_views
from cl.people_db import api_views as judge_views
from cl.search import api_views as search_views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# Search & Audio
router.register(... | /rest-info/(?P<version>v[123])?/?$',
views.rest_docs,
name='rest_docs'),
url(r'^api/bulk-info/$', |
views.bulk_data_index,
name='bulk_data_index'),
url(r'^api/rest/v(?P<version>[123])/coverage/(?P<court>.+)/$',
views.coverage_data,
name='coverage_data'),
# Pagerank file
url(r'^api/bulk/external_pagerank/$',
views.serve_pagerank_file,
name='pagerank_file'),... |
rvrheenen/OpenKattis | Python/judgingmoose/judgingmoose.py | Python | mit | 176 | 0.017045 | l, r = [int(x) for x in input() | .split()]
if max(l,r) == 0:
print("Not a moose")
elif l == r:
print("Even {}".format(l+r))
else | :
print("Odd {}".format(max(l,r)*2))
|
neosinha/automationengine | AutomationEngine/QueryTool/Main.py | Python | mit | 1,129 | 0.009743 | """
Created on April 14, 2017
@author Miguel Contreras Morales
"""
import QueryTool
import datetime
import cherrypy as QueryServer
import os
if __name__ == "__main__":
"""
This initializes CherryPy services
+ self - no input required
"""
print "Intializing!"
portn... | rver.socket_port': portnum,
'server.socket_timeout': 600,
'server.thread_pool' : 8,
'server.max_request_body_size': 0
})
wwwPath = os.path.join(os.getcwd(),'www')
print wwwPath
static... | 'tools.sessions.on': True,
'tools.staticdir.on': True,
'tools.staticdir.dir': wwwPath
}
}
QueryServer.quickstart(QueryTool.QueryTool(dbaddress="10.30.5.203:27017", path= wwwPath), '/', conf)
|
phobson/bokeh | bokeh/properties.py | Python | bsd-3-clause | 195 | 0.010256 | from | bokeh.util.deprecate import deprecated_module
deprecated_module('bokeh.properties', '0.11', 'use bokeh.core.properties instead')
del deprecated_module
fro | m .core.properties import * # NOQA
|
open-synergy/opnsynid-l10n-indonesia | l10n_id_taxform_bukti_potong_pph_f113309/__openerp__.py | Python | agpl-3.0 | 719 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 OpenSynergy Indonesia
# License AGPL-3.0 o | r later (http://www.gnu.org/licenses/agpl).
{
"name": "Indonesia - Bukti Potong PPh 4 Aya | t 2 (F.1.1.33.09)",
"version": "8.0.1.1.0",
"category": "localization",
"website": "https://opensynergy-indonesia.com/",
"author": "OpenSynergy Indonesia",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"l10n_id_taxform_bukti_potong_pph_common",
... |
ruohoruotsi/Wavelet-Tree-Synth | nnet/keeper_LSTMVRAE-JayHack-RyotaKatoh-chainer/dataset.py | Python | gpl-2.0 | 7,469 | 0.002946 | import gzip
import os
import numpy as np
import cPickle as pickle
import six
from six.moves.urllib import request
import scipy
from scipy import io
# from sklearn import decomposition
'''
BVH
'''
def load_bvh_data(file_path):
frames = 0
frame_time = 0.0
with open(file_path, "rb") as f:
lines... | f_images.read(16)
f_labels.read(8)
for i in six.moves.range(num):
target[i] = ord(f_labels.read(1))
for j in six.moves.range(dim):
data[i, j] = ord(f_images.read(1))
return data, target
def download_mnist_data(data_dir):
parent = 'http://yann.l... | t_labels = 't10k-labels-idx1-ubyte.gz'
num_train = 60000
num_test = 10000
print('Downloading {:s}...'.format(train_images))
request.urlretrieve('{:s}/{:s}'.format(parent, train_images), train_images)
print('Done')
print('Downloading {:s}...'.format(train_labels))
request.urlretrieve('{:s}/{... |
daschwa/typing-test | server.py | Python | mit | 395 | 0 | #!/usr/bin/env python
from livereload import Server, shell
server | = Server()
style = ("style.scss", "style.css")
script = ("typing-test.js", "typing-test-compiled.js")
server.watch(style[0], shell(["sass", style[0]], output=style[1]))
server.watch(script[0], shell(["babel", script[0]], output=script[1]))
server.watch("index.html")
server.serve(po | rt=8080, host="localhost", open_url=True)
|
ryanarnold/complaints_categorizer | categorizer/feature_selection.py | Python | mit | 2,179 | 0.005048 | from collections import Counter
def TFIDF(TF, complaints, term):
if TF >= 1:
n = len(complaints)
x = sum([1 for complaint in complaints if term in complaint['body']])
return log(TF + 1) * log(n / x)
else:
return 0
def DF(vocab, complaints):
term_DF = dict()
for term in ... | complaint['body'] and complaint['category'] != category:
B += 1
if term not in complaint['body'] and complaint['category'] == category:
C += 1
if term not in complaint['body'] and complaint['category'] != category:
D += 1
... | erm][category]['freq'] = A + C
except ZeroDivisionError:
print(term)
print(category)
print(A)
print(B)
print(C)
print(D)
input()
pass
chi_table[term]['chi_average'] = float... |
Vauxoo/stock-logistics-warehouse | stock_inventory_revaluation/wizards/stock_change_standard_price.py | Python | agpl-3.0 | 974 | 0 | # Copyright 2016-17 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import a | pi, models
class StockChangeStandardPrice(models.TransientModel):
_inherit = "stock.change.standard.price"
@api.model
def default_get(self, fields):
res = super(StockChangeStandardPrice, self).default_get(fields)
product_or_template = self.env[self._context['active_model']].browse(
... | '])
if 'counterpart_account_id' in fields:
# We can only use one account here, so we use the decrease
# account. It will be ignored anyway, because we'll use the
# increase/decrease accounts defined in the product category.
res['counterpart_account_id'] = product_... |
gf712/PyML | tests/nearest_neighbours_tests.py | Python | mit | 2,186 | 0.004575 | import unittest
from pyml.nearest_neighbours import KNNClassifier, KNNRegressor
from pyml.datasets import gaussian, regression
from pyml.preprocessing import train_test_split
class TestKNNClassifier(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.datapoints, cls.labels = gaussian(n=100, d=2... | ls.y_train)
def test_train(self):
self.assertEqual(self.classifier.X, self.X_train)
def test_predict(self):
predictions = self.classifier.predict(X=self.X_test)
self.assertEqual(predictions, [2, 2, 0, 0, 2, 0, 2, 2, 1, 1, 2, 0, 2, 2, 0])
def test_score(self):
ac | curacy = self.classifier.score(X=self.X_test, y_true=self.y_test)
self.assertEqual(accuracy, 1.0)
class TestKNNRegressor(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.X, cls.y = regression(100, seed=1970)
cls.X_train, cls.y_train, cls.X_test, cls.y_test = train_test_split(... |
itsMagondu/IoTNeuralNetworks | noisefilter/noisefilter/urls.py | Python | mit | 1,603 | 0.001871 | """ Default urlconf for noisefilter """
from django.conf import settings
from django.conf.urls import | include, url
from django.conf.urls.static import static
from django.contrib import admin
from | django.contrib.sitemaps.views import index, sitemap
from django.views.generic.base import TemplateView
from django.views.defaults import (permission_denied,
page_not_found,
server_error)
sitemaps = {
# Fill me with sitemaps
}
admin.autodiscov... |
jmcguire/rpg-toolkit-website | rpgtoolkit.py | Python | mit | 4,134 | 0.012821 | #!/usr/bin/env python
"""
rpgtoolkit.py
Generate a random webpage from a config file.
Lots of gaming resources are simple variations on a theme. Here's a big list, choose a random thing from the list, and interpolate a bit using data from some other lists.
Here's how this program works: given a config file, figure o... | t's a
# recursive function that doesn't know when its time is over
self.saved_tags = {}
if not self.norepeats:
self.config = self.backup_config
return select
def get_random_item_from(self, listn | ame):
"""remove a random item from one of the lists in the config, and return it"""
pick = random.randint(0, len(self.config[listname]) - 1)
return self.config[listname].pop(pick)
def interpolate(self, string):
"""replace references in string with other items from hash, recursive"""
# look for ... |
kubernetes-client/python | kubernetes/client/models/v1_ingress_class_spec.py | Python | apache-2.0 | 5,087 | 0 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | ler of this V1IngressClassSpec. # noqa: E501
Controll | er refers to the name of the controller that should handle this class. This allows for different \"flavors\" that are controlled by the same controller. For example, you may have different Parameters for the same implementing controller. This should be specified as a domain-prefixed path no more than 250 characters in ... |
morreene/tradenews | tradenews/newscluster/models.py | Python | bsd-3-clause | 533 | 0.001876 | # -*- coding: utf-8 -*-
import datetime as dt
from tradenews.database import (
Col | umn,
db,
Model,
SurrogatePK,
)
class NewsCluster(SurrogatePK, Model):
__tablename__ = 'newscluster'
# id = Column(db.Integer(), nullable=False, primary_key=True)
date = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
title = Column(db.Text(), nullable=True)
text = Col | umn(db.Text(), nullable=True)
cluster = Column(db.Integer(), nullable=True)
def __init__(self):
db.Model.__init__(self) |
burnpanck/traits | examples/tutorials/traits_4.0/interfaces/interfaces.py | Python | bsd-3-clause | 4,275 | 0.011696 | # Copyright (c) 2007, Enthought, Inc.
# License: BSD Style.
#--(Interfaces)-----------------------------------------------------------------
"""
Interfaces
==========
In Traits 3.0, the ability to define, implement and use *interfaces* has been
added to | the package.
Defining Interfaces
-------------------
Interfaces are defined by subclassing from the **Interface** class, as shown
in the example below::
from traits.api import Interface
class IName ( Interface ):
def get_name ( self ):
" Returns the name of an object. "
This same code ... | tab of the code.
Interface classes are intended mainly as documentation of the methods and
traits that the interface defines, and should not contain any actual
implementation code, although no check is performed to enforce this currently.
Implementing Interfaces
-----------------------
A class declares that it imple... |
chemelnucfin/tensorflow | tensorflow/python/data/kernel_tests/multi_device_iterator_test.py | Python | apache-2.0 | 19,062 | 0.00724 | # Copyright 2018 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... | assertRaises(errors.InvalidArgumentError):
self.evaluate(elem_on_1_t)
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(elem_on_2_t)
@combinations.generate(skip_v2_tes | t_combinations())
def testUneven(self):
dataset = dataset_ops.Dataset.range(10)
multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
dataset, ["/cpu:1", "/cpu:2"], max_buffer_size=4)
config = config_pb2.ConfigProto(device_count={"CPU": 3})
with self.test_session( |
webcomics/dosage | dosagelib/plugins/projectfuture.py | Python | mit | 2,118 | 0 | # SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
from .common import _ParserScraper
class ProjectFuture(_ParserScraper):
imageSearch = '//td[@class="tamid"]/img'
prevSearch = '//a[./img[@alt="Previous"]]'
def __init__(self, name, comic, fi... | return (
cls('AWalkInTheWoods', 'simeon', '1', last='12'),
cls('BenjaminBuranAndTheArkOfUr', 'ben', '00', last='23'),
cls('BookOfTenets', 'tenets', '01', last='45'),
cls('CriticalMass', 'criticalmass', 'cover', last='26'),
cls('DarkLordRising', 'darklord',... | 01-00'),
cls('HeadsYouLose', 'heads', '00-01', last='07-12'),
cls('NiallsStory', 'niall', '00'),
cls('ProjectFuture', 'strip', '0'),
cls('RedValentine', 'redvalentine', '1', last='6'),
cls('ShortStories', 'shorts', '01-00'),
cls('StrangeBedfellows'... |
mPowering/django-orb | orb/management/commands/load_orb_languages.py | Python | gpl-3.0 | 2,656 | 0.002259 | """
Management command to load language fixtures as tags
"""
from __future__ import unicode_literals
import csv
import os
import re
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from orb.models import Category, Tag
def has_data(input):
"""Identify... | dest="image",
default="tag/language_default.png",
help="Default image (static image path)",
)
parser.add_ar | gument(
"--user",
dest="user",
type=int,
default=1,
help="Default user to mark as creating",
)
parser.add_argument(
"--iso6392",
action="store_true",
dest="iso6392",
default=False,
hel... |
Chasego/codirit | leetcode/034-Search-for-a-Range/SearchForaRange_001.py | Python | mit | 654 | 0.010703 | class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def searchRange(self, nums, targe | t):
res = []
l, r = 0, len(nums) - 1
while l <= r:
m = (l + r) /2
if nums[m] < target:
l = m + 1
else:
r = m - 1
res.append(l)
l, r = 0, len(nums) - 1
while l <= r:
m = (l + r) /2
| if nums[m] <= target:
l = m + 1
else:
r = m - 1
res.append(r)
res = [-1, -1] if res[0] > res[1] else res
return res
|
kubeflow/kfserving-lts | test/e2e/predictor/test_torchserve.py | Python | apache-2.0 | 2,082 | 0.000961 | # Copyright 2019 kubeflow.org. |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl | e law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from kubernetes import ... |
Colstuwjx/scit-sys | openstack_api.py | Python | gpl-2.0 | 7,352 | 0.005849 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
from creds import get_nova_obj
from scit_config import *
from scit_db import *
#get authed nova obj
nova = get_nova_obj()
def create_nova_vm(logger, server_name, usr_dst):
conf = getScitConfig()
retry = int(conf["scit"]["scit_clean_retry"])
... | r_name, None)
time.sleep(10)
retry = retry - 1
| ret = create_vm_min(logger, server_name, usr_dst)
if ret:
break
#write into db
addVm(ret["vm_name"], ret["vm_fixip"], "READY")
return True
#minimal create vm
def create_vm_min(logger, server_name, usr_dst):
ret = {}
ret["vm_name"] = server_name
try... |
Dangetsu/vnr | Frameworks/Sakura/py/libs/scripts/cabocha.py | Python | gpl-3.0 | 307 | 0.026059 | # codi | ng: utf8
# jmdict.py
# 2/14/2014 jichi
if __name__ == '__main__':
import sys
sys.path.append('..')
def get(dic):
"""
@param dic str such as ipadic or unidic
@return bool
"""
import rc
ret | urn rc.runscript('getcabocha.py', (dic,))
if __name__ == "__main__":
get('unidic')
# EOF
|
gzqichang/wa | qevent/qevent/models.py | Python | mit | 5,215 | 0.001778 | from django.db import models
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.translation import ugettext_lazy as _
from django.conf import settings... | bj)
return obj.relative_actions.public(**kwargs)
def _object_actions(self, obj):
check(obj)
ct = get_contenttype(obj)
return models.Q(
actor_type_id=ct.pk,
actor_obj | ect_id=obj.pk,
) | models.Q(
target_type_id=ct.pk,
target_object_id=obj.pk,
) | models.Q(
relative_type_id=ct.pk,
relative_object_id=obj.pk,
)
@stream
def any(self, obj, **kwargs):
"""
指定 object 的所有 actions
"""
... |
algorhythms/LeetCode | 324 Wiggle Sort II py3.py | Python | mit | 2,047 | 0.000489 | #!/usr/bin/python3
"""
Given an unsorted array nums, reorder it such | that nums[0] < nums[1] > nums[2]
< nums[3]....
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow U | p:
Can you do it in O(n) time and/or in-place with O(1) extra space?
"""
from typing import List
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
Median + 3-way partitioning
"""
n = len(nums)
#... |
edx/edx-platform | cms/djangoapps/contentstore/views/tests/test_item.py | Python | agpl-3.0 | 160,015 | 0.003406 | """Tests for items views."""
import json
import re
from datetime import datetime, timedelta
from unittest.mock import Mock, PropertyMock, patch
import ddt
from django.conf import settings
from django.http import Http404
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls i... | resp = sel | f.create_xblock(category='vertical', parent_usage_key=parent_usage_key)
self.assertEqual(resp.status_code, 200)
return self.response_usage_key(resp)
@ddt.ddt
class GetItemTest(ItemTest):
"""Tests for '/xblock' GET url."""
def _get_preview(self, usage_key, data=None):
""" Makes a reque... |
SKIRT/PTS | modeling/fitting/component.py | Python | agpl-3.0 | 4,328 | 0.000693 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | ure__ i | mport absolute_import, division, print_function
# Import standard modules
from abc import ABCMeta
# Import astronomical modules
from astropy.table import Table
# Import the relevant PTS classes and modules
from ..component.component import ModelingComponent
from .tables import RunsTable
from .run import FittingRun
f... |
Grumbel/scatterbackup | tests/test_fileinfo.py | Python | gpl-3.0 | 1,443 | 0.000693 | #!/usr/bin/env python3
# ScatterBackup - A chaotic backup solution
# Copyright (C) 2015 Ingo Ruhnke <grumbel@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 the... | thout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
from scat | terbackup.fileinfo import FileInfo
class FileInfoTestCase(unittest.TestCase):
def test_from_file(self):
fileinfo = FileInfo.from_file("tests/data/test.txt")
self.assertEqual(11, fileinfo.size)
self.assertEqual("6df4d50a41a5d20bc4faad8a6f09aa8f", fileinfo.blob.md5)
self.assertEqual... |
mahmoud/wapiti | wapiti/operations/test_basic.py | Python | bsd-3-clause | 1,717 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base
from misc import GetPageInfo
from models import PageIdentifier
from category import GetSubcategoryInfos
from revisions import GetCurrentContent, GetPageRevisionInfos
from meta import GetSourceInfo
def test_unicode_title():
get_beyonce ... |
# This tests whether the client object given to the initial operation |
# is passed to its sub-operations.
# Use just enough titles to force multiplexing so that we can get
# sub ops to test.
titles = ['a'] * (base.DEFAULT_QUERY_LIMIT.get_limit() + 1)
client = base.MockClient()
op = GetPageInfo(titles, client=client)
assert id(op.subop_queues[0].peek().client... |
Yas3r/OWASP-ZSC | lib/generator/linux_x86/dir_create.py | Python | gpl-3.0 | 378 | 0.026455 | #!/usr/bin/env python
'''
OWASP ZSC | ZCR Shellcoder
ZeroDay Cyber Research
Z3r0D4y.Com
Ali Razmjoo
shellcode template used : http://shell-storm.org/shellcode/files/shellcode-57.php
'''
| from core import stack
from core import tem | plate
def run(dirname):
command = 'mkdir %s' %(str(dirname))
return template.sys(stack.generate(command.replace('[space]',' '),'%ecx','string'))
|
boyska/pyFsdb | fsdb/Fsdb.py | Python | lgpl-3.0 | 9,607 | 0.001353 | # -*- coding: utf-8 -*-
import os
import errno
import stat
import unicodedata
import hashlib
import shutil
import logging
import config
class Fsdb(object):
"""File system database
expose a simple api (add,get,remove)
to menage the saving of files on disk.
files are placed under specified fs... | ithm == "sha2"):
algFunct = hashlib.sha512
else:
raise ValueError('"' + algorithm + '" it is not a supported algorithm function')
hashM = algFunct()
with open(filepath, 'r') as f:
data = f.read(block_size)
hashM.update(data)
return hashM.h... | aticmethod
def generateDirTreePath(fileDigest, deep):
"""Generate a relative path from the given fileDigest
relative path has a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.