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 |
|---|---|---|---|---|---|---|---|---|
skurmedel/wordsalad | tests/test_matrix.py | Python | mit | 1,110 | 0.004505 | from wordsalad import WordSaladMatrixBuilder
import unittest
class TestWordSaladMatrixBuilder(unittest.TestCase):
def setUp(self):
self.builder = WordSaladMatrixBuilder()
def test_count_followers_in_sequence_no_endmarker(self):
seq = [1, 2, 3]
self.builder.count_followers_in_sequence(... | _matrix()
self.assertEqual(mat.probability(1, 2), 1)
self.assertEqual(mat.probability(2, 3), 1)
probs3 = mat.probabilities(3)
self.assertEqual(probs3.sum(), 0)
def test_count_followers_in_sequence_endmarker(self):
marker = "end"
seq = [1, 2, 3]
... | llowers_in_sequence(seq, endmarker=marker)
mat = self.builder.build_matrix()
self.assertEqual(mat.probability(1, 2), 1)
self.assertEqual(mat.probability(2, 3), 1)
self.assertEqual(mat.probability(3, "end"), 1)
def test_count_followers_in_sequence_throws_on_type(self):
w... |
fofix/fofix | fofix/game/Main.py | Python | gpl-2.0 | 5,400 | 0.000926 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################################################
# Frets on Fire X (FoFiX) #
# Copyright (C) 2006 Sami Kyöstilä #
# 2008 evilynux <evilynux@gmail.com> ... | ", self.theme)
self.engine = GameEngine(self.config)
self.videoLayer = False
self.restartRequested = False
@staticmethod
def load_config(configPath):
''' Load the configuration file. '''
if configPath is not None:
if configPath.lower() == "reset":
... | VFS.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
os.remove(fileName)
# Recreate it
config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault=True)
else:
# Load specified config file
conf... |
GuessWhoSamFoo/pandas | pandas/tests/arrays/test_datetimes.py | Python | bsd-3-clause | 10,666 | 0 | # -*- coding: utf-8 -*-
"""
Tests for DatetimeArray
"""
import operator
import numpy as np
import pytest
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
from pandas.core.arrays import DatetimeArray
from pandas.core.arrays.datetimes import sequence_to_dt64ns
import pandas.util.testing as tm
... | eArray(pd.date_range('2017', periods=2, tz=tz))
result = np.asarray(data)
expected = np.array([pd.Timestamp('2017-01-01T00:00:00', tz=tz),
pd.Timestamp('2017-01- | 02T00:00:00', tz=tz)],
dtype=object)
tm.assert_numpy_array_equal(result, expected)
result = np.asarray(data, dtype=object)
tm.ass |
QuantumTechDevStudio/RUDNEVGAUSS | archive/solver/DifferentialEvolutionAbstract.py | Python | gpl-3.0 | 1,558 | 0.000666 | import numpy
class DifferentialEvolutionAbstract:
amount_of_individuals = None
f = None
p = None
end_method = None
def __init__(self, min_element=-1, max_element=1):
self.min_element = min_element
self.max_element = max_element
self.f = 0.5
self.p = 0.9
se... | population = []
for _ in range(self.amount_of_individuals):
population.append(numpy.random.uniform(self.min_element, self.max_element, self.dim))
return numpy.array(population)
def choose_best_individual(self):
# Данная функция находит лучшую особь в популяции
func_l... | ):
return []
def optimize(self, func, dim, end_cond, debug_pop_print=-1):
return []
def return_cost_list(self):
return self.cost_list
|
chfw/Flask-Excel | tests/testapp.py | Python | bsd-3-clause | 4,610 | 0 | import platform
from datetime import datetime
import pyexcel as pe
from flask import Flask, abort, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import flask_excel as excel
app = Flask(__name__)
data = [[1, 2, 3], [4, 5, 6]]
if platform.python_implementation() == "PyPy":
app.config["SQLALCHEMY_DATAB... | array, "xls", sheet_name="test_array"
)
elif struct_type == "dict":
adict = request.get_dict(field_name="file")
return excel.make_response_from_dict(
adict, "xls", sheet_name="test_array"
)
elif struct_type == "records":
records = request.get_records( | field_name="file")
return excel.make_response_from_records(
records, "xls", sheet_name="test_array"
)
elif struct_type == "book":
book = request.get_book(field_name="file")
return excel.make_response(book, "xls")
elif struct_type == "book_dict":
book_dict = re... |
KRHS-GameProgramming-2015/Adlez | Adlez.py | Python | bsd-2-clause | 6,657 | 0.011417 | import sys, pygame, math, random, time
from Level import *
from Player import *
from Enemy import *
from NPC import *
from Menu import *
from Item import *
pygame.init()
clock = pygame.time.Clock()
width = 1000
height = 700
size = width, height
bgColor = r,b,g = 255,255,255
screen = pygame.display.set_mode(size)
m... | ct = bg.get_rect(center = [width/2,height/1.9])
screen.fill(bgColor)
screen.blit(bg, bgrect)
pygame.display.flip()
clock.tick(60)
while mode == "quit":
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
... | er) + str(levy) + str(levx)
level=Level(levFile)
player = Player([5,5], [900,500])
while mode == "test":
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
i... |
AleCandido/Lab3.2 | 4_Ottica1/cadmio.py | Python | gpl-2.0 | 2,784 | 0.019044 | from lab import *
from pylab import *
from uncertainties import *
from uncertainties import unumpy
from statistics import *
from scipy.constants import *
import getpass
users={"candi": "C:\\Users\\candi\\Documents\\GitHub\\Lab3.2\\",
"silvanamorreale":"C:\\Users\\silvanamorreale\\Documents\\GitHub\\Lab3.2\\" ,
"Studen... | int("Sodio:\n")
giallor = [59+10/60,59+6/60,59+6/60]
giallos = ufloat(mean(giallor), stdev(giallor))
giallo = giallos - alpha0
verder = [59+18/60,59+20/60,59+16/60]
verdes = ufloat(mean(verder), stdev(verder))
verde = verdes - alpha0
verdescuror = [59+55/60,59+55/60,59+55/60]
verdescuros = ufloat(mean(verdesc | uror), stdev(verdescuror)+0.1)
verdescuro = verdescuros - alpha0
azzurror = [60+8/60, 60+10/60, 60+6/60]
azzurros = ufloat(mean(azzurror), stdev(azzurror))
azzurro = azzurros - alpha0
rossor = [58+55/60,58+53/60,58+56/60]
rossos = ufloat(mean(rossor), stdev(rossor))
rosso = rossos - alpha0
violar = [60+39/60]*3
viol... |
ronniedada/litmus | collectors/cbagent/collectors/libstats/systemstats.py | Python | apache-2.0 | 869 | 0 | from fabric.api import run
from cbagent.collectors.libstats.decorators import multi_node_task
class SystemStats(object):
def __init__(self, hosts, user, password):
self.hosts = hosts
self.user = user
self.password = p | assword
@multi_node_task
def swap_usage(ip):
output = run("free | grep -i swap")
swap_usage = {}
for i, metric in enumerate(("swap_total", "swap_free", "swap_used")):
swap_usage["swap_" + metric] = output.split()[i + 1]
return swap_usage
@multi_node_task
def... | rep -i mem")
mem_usage = {}
for i, metric in enumerate(("total", "used", "free", "shared",
"buffers", "cached")):
mem_usage["mem_" + metric] = output.split()[i + 1]
return mem_usage
|
jeffzheng1/tensorflow | tensorflow/contrib/layers/python/layers/feature_column_ops.py | Python | apache-2.0 | 36,030 | 0.004496 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 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.
# ==============================================================================
"""Util... | ort
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework.python.framework import checkpoint_utils
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.... |
kikocorreoso/brython | www/src/Lib/test/test_glob.py | Python | bsd-3-clause | 13,345 | 0.000225 | import glob
import os
import shutil
import sys
import unittest
from test.support import (TESTFN, skip_unless_symlink,
can_symlink, create_empty_file, change_cwd)
class GlobTests(unittest.TestCase):
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *part... | unless_symlink
def test_glob_broken_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2'),
self.norm('sym3')])
eq(self.glob('sym1'), [self.norm('sym1')])
eq(self.glob('sym2'), [self.norm('sym2... | = "win32", "Win32 specific test")
def test_glob_magic_in_drive(self):
eq = self.assertSequencesEqual_noorder
eq(glob.glob('*:'), [])
eq(glob.glob(b'*:'), [])
eq(glob.glob('?:'), [])
eq(glob.glob(b'?:'), [])
eq(glob.glob('\\\\?\\c:\\'), ['\\\\?\\c:\\'])
eq(glob... |
tommorris/mf2py | test/test_suite.py | Python | mit | 886 | 0.001129 | from __future__ import unicode_literals, print_function
from nose.tools import assert_equal
import glob
import json
import mf2py
import os.path
import sys
from test_parser import check_unicode
assert_equal.__self__.maxDiff = None
def test_mf2tests():
allfiles = glob.glob(
os.path.join('.', 'testsuite', ... | (doc=f, url='http://example.com')
yield check_unicode, htmlfile, p
with open(jsonfile) as jsonf:
try:
s = json.load(jsonf)
except:
s = "bad file: " + jsonfile + sy | s.exc_info()[0]
yield check_mf2, htmlfile, p, s
def check_mf2(htmlfile, p, s):
# TODO ignore extra keys in p that are not in s
assert_equal(p, s)
|
SurfasJones/djcmsrc3 | venv/lib/python2.7/site-packages/cms/models/permissionmodels.py | Python | mit | 5,696 | 0.002282 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.utils import importlib
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth.models import Group
from django.contrib.sites.models import Si... | nicode, python_2_unicode_comp | atible
# To avoid circular dependencies, don't use cms.compat.get_user_model, and
# don't depend on the app registry, to get the custom user model if used
if is_user_swapped:
user_app_name, user_model_name = user_model_label.rsplit('.', 1)
User = None
for app in settings.INSTALLED_APPS:
if app.ends... |
sgraham/nope | tools/perf/profile_creators/small_profile_creator.py | Python | bsd-3-clause | 2,596 | 0.00963 | # Copyright 2013 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.
from telemetry.page i | mport profile_creator
import logging
import page_sets
from telemetry import benchmark
from telemetry.page import page_test
from telemetry.page import test_expectations
from telemetry.results import results_options
from telemetry.user_story import user_story_runner
class SmallPr | ofileCreator(profile_creator.ProfileCreator):
"""
Runs a browser through a series of operations to fill in a small test profile.
This consists of performing a single navigation to each of the top 25 pages.
"""
class PageTest(page_test.PageTest):
def __init__(self):
super(SmallProfileCreator.PageTes... |
mahmoud/womp | womp/inputs/__init__.py | Python | gpl-3.0 | 1,255 | 0.001594 | #from feedback import FeedbackV4 # removed from WP API
#from feedback import FeedbackV5 # removed from WP API
from article_history import ArticleHistory
from assessment import Assessment
from backlinks import Backlinks
from dom import DOM
from google import GoogleNews
from go | ogle import GoogleSearch
from grokse import PageViews
from interwikilin | ks import InterWikiLinks
from langlinks import LangLinks
from nineteen_dom import NineteenDOM
from protection import Protection
from revisions import Revisions
from templates import ParsedTemplates
from watchers import Watchers
from wikitrust import Wikitrust
ALL_INPUTS = [ArticleHistory,
Assessment,
... |
google-research/disentanglement_lib | disentanglement_lib/evaluation/metrics/fairness.py | Python | apache-2.0 | 8,341 | 0.007553 | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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 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 the License.
"""... | ntation. This procedure is described in Section 4 of the paper "On the
Fairness of Disentangled Representations", Francesco Locatello, Gabriele Abbati,
Tom Rainforth, Stefan Bauer, Bernhard Schoelkopf, Olivier Bachem, NeurIPS 2019,
https://arxiv.org/abs/1905.13662.
The unfairness of a classifier is computed as the tota... |
jbzdak/edx-platform | openedx/core/djangoapps/user_api/views.py | Python | agpl-3.0 | 33,442 | 0.001615 | """HTTP end-points for the User API. """
import copy
from opaque_keys import InvalidKeyError
from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured, NON_FIELD_E... | pe="password",
restrictions={
"min_length": PASSWORD_MIN_LENGTH,
"max_length": PASSWORD_MAX_LENGTH,
}
)
form_desc.add_field(
"remember",
field_type="checkbox",
label=_("Remember me"),
default=False,
... | json(), content_type="application/json")
@method_decorator(require_post_params(["email", "password"]))
@method_decorator(csrf_protect)
def post(self, request):
"""Log in a user.
You must send all required form fields with the request.
You can optionally send an `analytics` param w... |
tax/pywhatsapp | whatsapp.py | Python | bsd-3-clause | 6,224 | 0.003213 | import os
import threading
import logging
from yowsup import env
from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS, YOWSUP_PROTOCOL_LAYERS_FULL
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.net... | openwhatsapp.yowsup.prop.sendclient.queue"
def __in | it__(self):
super(SendLayer, self).__init__()
self.ackQueue = []
self.lock = threading.Condition()
def get_upload_entity(self, path):
filename, extension = os.path.splitext(path)
if extension in EXT_IMAGE:
return RequestUploadIqProtocolEntity(
Req... |
eltonkevani/tempest_el_env | tempest/api/compute/volumes/test_volumes_list.py | Python | apache-2.0 | 4,824 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | v for v in self.volume_list if v not in fetched_list
]
self.assertFalse(missing_volumes,
"Failed to find volume %s in fetched list" %
', '.join(m_vol['displayName']
for m_vol in missing_volumes))
class Volu... | tXML(VolumesTestJSON):
_interface = 'xml'
|
bearstech/ansible | lib/ansible/modules/cloud/google/gce_instance_template.py | Python | gpl-3.0 | 19,122 | 0.00068 | #!/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.0',
'status': ['preview'],
... | _instance_template:
name: foo
size: n1-standard-1
image_family: ubuntu-1604-lts
state: present
project_id: "your-project-name"
credentials_file: "/path/to/your-key.json"
service_account_email: "your-sa@your-project-name.iam.gserviceaccount.com"
# Example Playbook
- name: Compute Engine Inst... | ount.com"
credentials_file: "/path/to/your-key.json"
project_id: "your-project-name"
tasks:
- name: create instance template
gce_instance_template:
name: my-test-instance-template
size: n1-standard-1
image_family: ubuntu-1604-lts
state: present
project_id: "{{... |
polysquare/polysquare-generic-file-linter | test/test_linter_acceptance.py | Python | mit | 11,503 | 0 | # /test/test_linter_acceptance.py
#
# Acceptance tests for polysquarelinter.linter, actually runs
# main() and checks results of various functions.
#
# Disable no-self-use in tests as all test methods must be
# instance methods and we don't necessarily have to use a matcher
# with them.
# pylint:disable=no-self-use
#
#... | ."""
def __init__(self, matchee):
"""Forward matchee to parent class."""
super(Equals, self).__init__(matchee)
def comparator(self, expected, other):
"""Check that expected == other."""
| return other == expected
class LinterFailure(Exception):
"""Exception raised when the linter reports a message."""
def __init__(self, message, repl):
"""Initialize exception with mesh and replacement."""
super(LinterFailure, self).__init__()
self.message = message
self... |
plivo/plivo-python | tests/xml/test_sayAsElement.py | Python | mit | 789 | 0.002535 | from unittest import TestCase
from plivo import plivoxml
from tests import PlivoXmlTestCase
class SayAsElementTest(TestCase, PlivoXmlTestCase):
def test_set_methods(self):
expected_response = '<Response><Speak><say-as format="application/ssml+xml" interpret-as="spell-out">' \
... | format = "application/ssml+xml"
content = 'This is Test'
element = plivoxml.ResponseElement()
response = element.add(
plivoxml.SpeakElement("").add(
plivoxml.SayAsElement(content).set_interpret_as(interpret_as).set_format(format)
)
). | to_string(False)
self.assertXmlEqual(response, expected_response)
|
Winand/pandas | pandas/tests/reshape/test_merge.py | Python | bsd-3-clause | 64,631 | 0.000031 | # pylint: disable=E1103
import pytest
from datetime import datetime, date
from numpy.random import randn
from numpy import nan
import numpy as np
import random
import pandas as pd
from pandas.compat import lrange, lzip
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge, MergeErr... | {'key1': | get_test_data(),
'key2': get_test_data(),
'data1': np.random.randn(N),
'data2': np.random.randn(N)})
# exclude a couple keys for fun
self.df = self.df[self.df['key2'] > 1]
self.df2 = DataFrame({'key1': get_t... |
flavour/porto | controllers/admin.py | Python | mit | 53,568 | 0.006907 | # -*- coding: utf-8 -*-
"""
Admin Controllers
"""
module = "admin"
resourcename = request.function
# Options Menu (available in all Functions' Views)
# - can Insert/Delete items from default menus within a function, if required.
s3_menu(module)
# S3 framework functions
# ----------------------------------------... | r = s3base | .S3RoleManager()
modules = deployment_settings.modules
handler.controllers = Storage([(m, modules[m])
for m in modules
if modules[m].restricted])
# Configure REST methods
r.set_handler("users", handler)
... |
dezede/dezede | libretto/models/individu.py | Python | bsd-3-clause | 12,969 | 0.000233 | from django.core.exceptions import ValidationError
from django.db import connection
from django.db.models import (
CharField, ForeignKey, ManyToManyField, PROTECT, BooleanField)
from django.urls import reverse
from django.utils.html import strip_tags
from django.utils.safestring import mark_safe
from django.utils.t... | demoiselle') |
elif titre == 'F':
return hlp(ugettext('M<sup>me</sup>'), 'Madame')
if titre == 'M':
return ugettext('Monsieur')
elif titre == 'J':
return ugettext('Mademoisel |
noironetworks/neutron | neutron/tests/unit/services/logapi/common/test_db_api.py | Python | apache-2.0 | 14,273 | 0 | # Copyright (c) 2017 Fujitsu Limited
# 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 requi... | orts_being_logged_not_supported_log_type(self):
log = _create_log(tenant_id=self.tenant_id)
with mock.patch.object(
| validators, 'validate_log_type_for_port', return_value=False):
ports_log = db_api._get_ports_being_logged(self.context, log)
self.assertEqual([], ports_log)
class LoggingRpcCallbackTestCase(test_sg.SecurityGroupDBTestCase):
def setUp(self):
super(LoggingRpcCallbackTestCase, self).set... |
martinbede/second-sight | tensorflow/examples/tutorials/word2vec/word2vec_basic.py | Python | apache-2.0 | 8,770 | 0.011403 | # 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... | mitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import print_function
import collections
import math
import os
import random
import zipfile
import numpy as np
from six.moves import urllib
from six.mov... | builtin
import tensorflow as tf
# Step 1: Download the data.
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urllib.request.urlretrieve(url + filename, filen... |
USGSDenverPychron/pychron | pychron/mv/degas/degasser.py | Python | apache-2.0 | 12,798 | 0.000391 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# 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/licens... |
pid = Instance(PID)
stream_graph = Instance(StreamStackedGraph, ())
img_graph = Instance(Graph, ())
plot_container = Instance(HPlotContainer, () | )
threshold = Range(0, 100, 25)
test = Button
edit_pid_button = Button
save_button = Button
_lum_thread = None
_lum_evt = None
_luminosity_value = 0
_testing = False
_info = None
def stop(self):
self.debug("stop")
self.dump()
if self._lum_evt:
... |
wfarn/scratchpad | django/django_db/django_db/wsgi.py | Python | apache-2.0 | 393 | 0.002545 | """
WSGI config for django_db project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_db | .settings")
|
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
xzturn/tensorflow | tensorflow/tools/gcs_test/python/gcs_smoke.py | Python | apache-2.0 | 10,461 | 0.013765 | # Copyright 2016 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... | nt(round(time.time() * 1000)) - starttime_ms
print("Created directory in: %d milliseconds" % elapsed_ms)
# Check that the directory exists.
dir_exists = file_io.is_directory(dir_name)
assert dir_exists
print("%s directory exists: %s" % (d | ir_name, dir_exists))
# Test recursive directory creation.
starttime_ms = int(round(time.time() * 1000))
recursive_dir_name = "%s/%s/%s" % (dir_name,
"nested_dir1",
"nested_dir2")
print("Creating recursive dir %s" % recursive_dir_name)
... |
humanoid-path-planner/hpp-corbaserver | src/hpp/__init__.py | Python | lgpl-3.0 | 1,269 | 0.002364 | # Copyright (c) 2012 CNRS
# Author: Florent Lamiraux
#
# This file is part of hpp-corbaserver.
# hpp-corbaserver 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 the License, or (at... | http://www.gnu.org/licenses/>.
from .quaternion import Quaternion
from .transform import Transform
def retrieveRosResource(path):
import os
ros_package_paths = os.environ["ROS_PACKAGE_PATH"].split(':')
if path.startswith("package://"):
relpath = path[len("package://"):]
for dir in ros_pac... | source " + path)
else:
return path
|
theawless/Dict-O-nator | dictonator/setlog.py | Python | gpl-3.0 | 1,573 | 0.000636 | # Dict'O'nator - A dictation plugin for gedit.
# Copyright (C) <2016> <Abhinav Singh>
#
# This file is part of Dict'O'nator.
#
# Dict'O'nator 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 o... | treamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
# adding | handler for file logs
fh = logging.FileHandler(debug_log)
fh.setFormatter(formatter)
logger.addHandler(fh)
setup_logger()
|
henriquemiranda/yambo-py | yambopy/recipes.py | Python | bsd-3-clause | 20,837 | 0.022172 | # Copyright (C) 2018 Henrique Pereira Coutada Miranda, Alejandro Molina Sanchez, Alexandre Morlet, Fulvio Paleari
#
# All rights reserved.
#
# This file is part of yambopy
#
#
import os
from operator import itemgetter
from collections import OrderedDict
from yambopy import *
#
# by Henrique Miranda.
#
def pack_files_i... | k into folders starting with var or reference
if any( [basename.startswith(v) for v | in [var,'reference']] ):
for filename in files:
if filename != 'ndb.QP': continue
#get ndb.QP file in folder
io[basename] = ( YamboIn.from_file(folder=folder,filename="%s.in"%basename),
YamboQPDB.from_db(folder=root,filename=f... |
repotvsupertuga/tvsupertuga.repository | script.module.streamtvsupertuga/lib/resources/lib/sources/en/moviesleak.py | Python | gpl-2.0 | 6,709 | 0.015502 | # -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... | item, hostDict))
[i.start() for i in threads]
[i.join() for i in threads]
return self._sources
except Exception:
return self._sources
def _get_sources(self, item, hostDict):
try:
quality, info = source_utils.get_release_quality(item[0],... | ]
div = 1 if size.endswith(('GB', 'GiB')) else 1024
size = float(re.sub('[^0-9|/.|/,]', '', size.replace(',', '.'))) / div
size = '%.2f GB' % size
info.append(size)
except Exception:
pass
data = client.request(item... |
yuanming-hu/taichi | tests/python/test_arg_alignment.py | Python | mit | 418 | 0 | import taichi as ti
from tests import test_utils
@test_utils.test(exclude=[ti.opengl])
def test_ret_write():
@ti.kernel
| def func(a: ti.i16) -> ti.f32:
return 3.0
assert func(255) == 3.0
@test_utils.test(exclude=[ti.opengl])
def test_arg_rea | d():
x = ti.field(ti.i32, shape=())
@ti.kernel
def func(a: ti.i8, b: ti.i32):
x[None] = b
func(255, 2)
assert x[None] == 2
|
wdecoster/nanoget | nanoget/extraction_functions.py | Python | gpl-3.0 | 18,527 | 0.003023 | import logging
from functools import reduce
import nanoget.utils as ut
import pandas as pd
import sys
import pysam
import re
from Bio import SeqIO
import concurrent.futures as cfutures
from itertools import repeat
def process_summary(summaryfile, **kwargs):
"""Extracting information from an albacore summary file.... | e"]
else:
datadf.columns = ["channelIDs", "time", "duration", "lengths", "quals"]
logging.info("Nanoget: Finished collecting statistics from summary file {}".format(summaryfile))
return ut.reduce_memory_usage(datadf.loc[datadf["lengths"] != 0].copy())
def check_bam(ba | m, samtype="bam"):
"""Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
"""
ut.check_existance(bam)
samfile = pysam.AlignmentFile(bam, "rb")
if not samfile.has_index():
pysa... |
qxcv/joint-regressor | keras/vggnet/vgg16_keras.py | Python | apache-2.0 | 2,604 | 0.014209 | from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
import numpy as np
def VGG_16(weights_path=None):
model = Sequential()
model.add(ZeroPadding2D((1,1),input... | (Dropout(0.5))
model.add(Den | se(1000, activation='softmax'))
if weights_path:
model.load_weights(weights_path)
return model
if __name__ == "__main__":
import cv2
im = cv2.resize(cv2.imread('cat.jpg'), (224, 224)).astype(np.float32)
im[:,:,0] -= 103.939
im[:,:,1] -= 116.779
im[:,:,2] -= 123.68
im = im.tran... |
naveensan1/nuage-openstack-neutron | nuage_neutron/plugins/common/trunk_db.py | Python | apache-2.0 | 3,135 | 0 | # Copyright 2017 Nokia
#
# 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... | d(models_v2.Port, name='cur_parent_port')
cur_parent_network = aliased(models_v2.Network, name='cur_parent_network')
cur_parent_network_segment = aliased(segments_db.NetworkSegment,
name='cur_parent_network_segment')
other_parent_port = aliased(models_v2.Port, name='... | session.query(models_v2.Port)
.options(
noload('*'),
joinedload(models_v2.Port.sub_port),
joinedload(models_v2.Port.fixed_ips))
.join(
(models.SubPort, models.SubPort.port_id == models_v2.Port.id),
(models.Trunk, models.SubPort.trunk_id == m... |
szepeviktor/fail2ban | fail2ban/tests/samplestestcase.py | Python | gpl-2.0 | 5,376 | 0.023251 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban 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;... | eLocal.microsecond / 1000000
self.assertEqual(fail2banTime, jsonTime,
| "UTC Time mismatch fail2ban %s (%s) != failJson %s (%s) (diff %.3f seconds) on: %s:%i %r:" %
(fail2banTime, time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(fail2banTime)),
jsonTime, time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(jsonTime)),
fail2banTime - jsonTime, logFile.filename(), logFile.fileline... |
hugosenari/dbus_async | example/low_api_client.py | Python | isc | 1,198 | 0.010017 | import dbus_async
@asyncio.coroutine
def dbus_hello_client(bus):
# create message
helloWorld = Method("HelloWorld",
path="/remote/object/path",
iface="com.example.Sample",
bus=bus)
# wait reply
result = yield from helloWorld("Anon... |
pass
con.close()
loop.run_until_complete(con.wait_closed())
loo | p.close() |
agold/svgchart | lib/input/FileInput.py | Python | apache-2.0 | 333 | 0.042042 | class FileInput | :
"""Retrieves the contents of a file and passes them to InputSets."""
def __init__(self,inputSets,filename):
"""
@param inputSets: List of target InputSets
@param filename: Name of file to be scanned for input
"""
with open(filename,'rU') as f:
text = f.read()
for i in inputSets:
i.inp | ut(text) |
supercheetah/diceroller | pyinstaller/PyInstaller/hooks/hook-_tkinter.py | Python | artistic-2.0 | 5,503 | 0.001272 | #
# Copyright (C) 2012, Martin Zibricky
# Copyright (C) 2011, Hartmut Goebel
# Copyright (C) 2005, Giovanni Bajo
#
# 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 Licen... | ameworks.
path_to_tcl = bins[0][1]
if 'Library/Frameworks' in path_to_tcl:
tcl_tk = _find_tk_darwin_frameworks(bins)
# Tcl/Tk compiled as on Linux other Unices.
# For example this is the case of Tcl/Tk from macports.
else:
tcl_tk = _find_tk_tclshell()
... | # Workaround for broken Tcl/Tk detection in virtualenv on Windows.
_handle_broken_tk()
tcl_root, tk_root = _find_tk(mod)
tcldir = "tcl"
tkdir = "tk"
tcltree = Tree(tcl_root, os.path.join('_MEI', tcldir),
excludes=['demos', 'encoding', '*.lib', 'tclConfig.sh'])
tktree = Tr... |
climbus/RPiRobot | tests/test_robot.py | Python | mit | 10,802 | 0.000833 | import sys
import os
import unittest
import time
from mock import Mock, patch
sys.path.append(os.path.abspath("."))
sys.path.append(os.path.abspath("rpirobot"))
from rpirobot.robot import Robot
class TestRobot(unittest.TestCase):
"""Tests for Robot class."""
def setUp(self):
self.robot = Robot()
... | )
self.robot.change_status(-1)
self.assertTrue(self.robot._stop_motors.called)
def test_could_toggle_status(self):
self._set_motors()
self.robot.set_led(Mock())
self.robot.status = -1
self.robot.toggle_status()
self.assertEqual(self.robot.status, 1)
s... | elf._set_motors()
self.robot.set_led(Mock())
self.robot._stop_motors = Mock()
self.robot.stop()
self.assertTrue(self.robot._stop_motors.called)
def test_left(self):
self.robot.set_led(Mock())
self._set_motors()
self.robot._stop_motors = Mock()
self.ro... |
great-expectations/great_expectations | great_expectations/validator/metric_configuration.py | Python | apache-2.0 | 2,379 | 0 | import json
from typing i | mport Tuple
from great_expectations.core.id_dict import IDDict
class MetricConfiguration:
def __init__(
self,
metric_name: str,
metric_domain_kwargs: dict,
metri | c_value_kwargs: dict = None,
metric_dependencies: dict = None,
):
self._metric_name = metric_name
if not isinstance(metric_domain_kwargs, IDDict):
metric_domain_kwargs = IDDict(metric_domain_kwargs)
self._metric_domain_kwargs = metric_domain_kwargs
if not isinstan... |
borevitzlab/timestreamlib | scripts/tscli/playTimestream.py | Python | gpl-3.0 | 2,769 | 0.009029 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 28 17:49:08 2014
@author: chuong nguyen, chuong.v.nguyen@gmail.com
"""
from __future__ import absolute_import, division, print_function
import cv2
import logging
import timestream
import numpy as np
from timestream.parse import ts_parse_date
import docopt
import datetime... | ream.parse.ts_format_date(img.datetime)
cv2.putText(imgResized, timestamp, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), thickness = 1)
cv2.imshow(windowName, imgResized[:,:,::-1])
k = cv2.waitKey(delay)
if k = | = 1048603:
# escape key is pressed
break
cv2.destroyAllWindows() |
monkeypants/MAVProxy | MAVProxy/modules/mavproxy_wp.py | Python | gpl-3.0 | 33,902 | 0.003186 | #!/usr/bin/env python
'''waypoint command handling'''
import time, os, fnmatch, copy, platform
from pymavlink import mavutil, mavwp
from MAVProxy.modules.lib import mp_module
from MAVProxy.modules.lib import mp_util
if mp_util.has_wxpython:
from MAVProxy.modules.lib.mp_menu import *
class WPModule(mp_module.MPMod... | ed and tnow - self.wp_requested[seq] < 2:
continue
ret.append(seq)
return ret
def send_wp_requests(self, wps=None):
'''send some more WP requests'''
if wps is None:
wps = self.missing_wps_to_request()
tnow = time.time()
for seq in wps:... | = tnow
self.master.waypoint_request_send(seq)
def wp_status(self):
'''show status of wp download'''
try:
print("Have %u of %u waypoints" % (self.wploader.count()+len(self.wp_received), self.wploader.expected_count))
except Exception:
print("Have %u waypo... |
BansheeMediaPlayer/bockbuild | packages/libicu.py | Python | mit | 156 | 0.070513 | Package ('libicu', '55.1',
source_dir | _name = 'icu/source',
sources = [
'http://download.icu-project.org/files | /icu4c/%{version}/icu4c-55_1-src.tgz'
]
)
|
QuantumElephant/horton | scripts/horton-convert.py | Python | gpl-3.0 | 2,641 | 0.009087 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licens... | s published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warr | anty 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 sys, argparse, os, numpy as np
from horton i... |
rogerscristo/BotFWD | env/lib/python3.6/site-packages/telegram/contrib/__init__.py | Python | mit | 49 | 0 | f | rom .botan import Botan
__all__ = ['Bot | an']
|
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_peering.py | Python | mit | 4,677 | 0.00171 | # coding=utf-8
# --------------------------------------------------------------------- | -----
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code | is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class VirtualNetworkPeering(SubResource):
"""Peerings in a virtual network resource.
:param id: Resource ID.
:type id: str
:param allow_virtual_network_access: Whethe... |
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/agw/fmresources.py | Python | mit | 13,594 | 0.008092 | import wx
# Overall menu styles
StyleDefault = 0
StyleXP = 1
Style2007 = 2
StyleVista = 3
# Menu shadows
RightShadow = 1 # Right side shadow
BottomShadow = 2 # Not full bottom shadow
BottomShadowFull = 4 # Full bottom shadow
# Button styles
BU_EXT_XP_STYLE = 1
B... |
"mmmmmmmmmmmmmmmm",
"mmmmmmmmmmmmmmmm"]
menu_right_arrow_xpm | = [
" 16 16 8 1",
"` c #ffffff",
". c #000000",
"# c #000000",
"a c #000000",
"b c #000000",
"c c #000000",
"d c #000000",
"e c #000000",
"````````````````",
"````````````````",
"````````````````",
"````````````````",
"```````... |
Antonio-Team/enigma2 | lib/python/Screens/FactoryReset.py | Python | gpl-2.0 | 1,088 | 0.020221 | from Screens.MessageBox import MessageBox
from Screens.ParentalControlSetup import ProtectedScreen
from Components.config import config
class FactoryReset(MessageBox, ProtectedScreen):
def __init__(self, session):
MessageBox.__init__(self, session, _("Factory reset will restore your receiver to its default configur... | O, default=False)
self.skinName = "MessageBox"
ProtectedScreen.__init__(self)
def isProtected(self):
return config.ParentalControl.setuppinactive.value and\
(not config.ParentalControl.config_sections.main_menu.value and not config.ParentalControl.config_sections.configuration.value or hasattr(self.session,... | entalControl.config_sections.manufacturer_reset.value
|
liquidinstruments/pymoku | pymoku/_frequency_response_analyzer.py | Python | mit | 22,648 | 0 | import math
import logging
from pymoku._instrument import MokuInstrument
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument import to_reg_signed
from pymoku._instrument import from_reg_signed
from pymoku._instrument import to_reg_bool
from pymoku._in... | = logging.getLogger(__name__)
REG_FRA_SWEEP_FREQ_MIN_L = 64
REG_FRA_SWEEP_FREQ_MIN_H = 65
REG_FRA_SWEEP_FREQ_DELTA_L = 66
REG_FRA_SWEEP_FREQ_DELTA_H = 67
REG_FRA_LOG_EN = 68
REG_FRA_HOLD_OFF_L = 69
REG_FRA_SWEEP_LENGTH = 71
REG_FRA_AVERAGE_TIME = 72
REG_FRA_ENABLES = 73
REG_FRA_SWEEP_AMP_MULT = 74
REG_FRA_SETTLE_CYCLE... | = 79
REG_FRA_PHASE_OFF_CH1_MSB = 80
REG_FRA_HARMONIC_MULT_CH1 = 81
REG_FRA_PHASE_OFF_CH2_LSB = 82
REG_FRA_PHASE_OFF_CH2_MSB = 83
REG_FRA_HARMONIC_MULT_CH2 = 84
_FRA_FPGA_CLOCK = 125e6
_FRA_DAC_SMPS = 1e9
_FRA_DAC_VRANGE = 1
_FRA_DAC_BITDEPTH = 2**16
_FRA_DAC_BITS2V = _FRA_DAC_BITDEPTH / _FRA_DAC_VRANGE
_FRA_SCREEN_WID... |
iulian787/spack | var/spack/repos/builtin/packages/r-dynamictreecut/package.py | Python | lgpl-2.1 | 744 | 0.005376 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDynamictreecut(RPackage):
"""dynamicTreeCut: Methods for Detection of Clusters in Hierarc... | Cut/"
version('1.63-1', sha256='831307f64eddd68dcf01bbe2963be99e5cde65a636a13ce9de229777285e4db9')
| depends_on('r@2.3.0:', type=('build', 'run'))
|
mayson/viperpeers | viperpeers.py | Python | gpl-2.0 | 45,342 | 0.047087 | #!/usr/bin/env python
# vim:fileencoding=utf-8
# Find the best reactor
reactorchoices = ["epollreactor", "kqreactor", "cfreactor", "pollreactor", "selectreactor", "posixbase", "default"]
for choice in reactorchoices:
try:
exec("from twisted.internet import %s as bestreactor" % choice)
break
except:
pass
bestre... | CR( 'New max hubs' )] )
self.usercommands['Set'] += self.UC( self._('Settings\\Limits\\Set min slots'), ['Set core min_slots', self.tUCR( 'New m | in slots' )] )
# -- User control
self.usercommands['AddReg'] = ''
self.usercommands['SetLevel'] = ''
for i in self.settings['privlist'].keys():
self.usercommands['AddReg'] += self.UC( self._( 'Users\\Selected\\Register selected nick as\\%s' ) % i, ['AddReg %[nick]', i, self.tUCR( 'Password' )] )
se... |
henzk/ape | ape/container_mode/tasks.py | Python | mit | 12,347 | 0.002349 | from __future__ import unicode_literals, print_function
import os
import sys
import subprocess
import json
from ape import feaquencer
from ape import tasks
from .exceptions import ContainerError, ContainerNotFound, ProductNotFound
class Config(object):
APE_ROOT = os.environ['APE_ROOT_DIR']
SOURCE_HEADER = '#... | ommands may be available
that are relevant to sdox:dev
:param poi: product of interest, string: <container_name>:<product_name> or <product_name>.
"""
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'... | duct name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
container_name = os.environ.get('CONTAINER_NAME')
product_name = parts[0]
else:
print('unable to find poi: ', poi)
sys.exit(1)
if container_name not in tasks.... |
pmaunz/pyqtgraph | examples/optics/pyoptic.py | Python | mit | 18,598 | 0.008229 | # -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import csv, gzip, os
from pyqtgraph import Point
class GlassDB:
"""
Database of dispersion coefficients for Schott glasses
+ Corning 7980
"""
def __init__(self, fileName='schott_glasses.csv'):
... | : 25.4, ## diameter of lens
'r1': 50., ## positive means convex, use 0 for planar
'r2': 0, ## negative means convex
'd': 4.0,
'glass': 'N-BK7',
'refl | ect': False,
}
defaults.update(params)
d = defaults.pop('d')
defaults['x1'] = -d/2.
defaults['x2'] = d/2.
gitem = CircularSolid(brush=(100, 100, 130, 100), **defaults)
Optic.__init__(self, gitem, **defaults)
def propagateRay(self, ray):
... |
osspeak/osspeak | osspeak/recognition/actions/library/general.py | Python | mit | 247 | 0.016194 | def python_evaluate(text):
return | eval(str(text))
def python_print(*values, sep=' '):
joined = sep.join((str(v) for v in values))
print(joined)
def python_list(*args):
re | turn args
def error(text=''):
raise RuntimeError(text) |
ptphp/PyLib | src/webpy1/webpy1.1/post/post_anju.py | Python | apache-2.0 | 4,425 | 0.018079 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2,urllib,sys,time
import cookielib,mechanize
import re
DEBUG =0
reload(sys)
sys.setdefaultencoding('utf8') #@UndefinedVariable
register_openers()
headers = {
... | om',
'User-Agent' : 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
#'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
| #'Accept-Language':'zh-cn,zh;q=0.5',
#'Accept-Encoding':'gzip, deflate',
#'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
'Keep-Alive':'115',
'Connection':'keep-alive',
}
#datagen11, headers = multipart_encode({"fileUploadInput": ... |
Jumpscale/jumpscale6_core | lib/JumpScale/grid/zdaemon/__init__.py | Python | bsd-2-clause | 330 | 0 | from JumpScale import j
import JumpScale.grid.gevent
import JumpScale.baselib.key_value_store
import JumpScale.baselib.serializers
from .ZDa | emonFactory import ZDaemonFactory
j.base.loader.makeAvailable(j, 'core')
j.core.zdaemon = ZDaemonFactory()
j.base.loa | der.makeAvailable(j, 'servers')
j.servers.zdaemon = ZDaemonFactory()
|
KernelAnalysisPlatform/kvalgrind | qemu/panda_plugins/syscalls/syscall_parser.py | Python | gpl-3.0 | 16,902 | 0.007159 |
# /* PANDABEGINCOMMENT
# *
# * Authors:
# * Tim Leek tleek@ll.mit.edu
# * Ryan Whelan rwhelan@ll.mit.edu
# * Joshua Hodosh josh.hodosh@ll.mit.edu
# * Michael Zhivich mzhivich@ll.mit.edu
# * Brendan Dolan-Gavitt brendandg@gatech.edu
# *
# * This work is licensed under t... | : {\n"
alltext += "record_syscall(\"%s\") | ;\n" % callname
argno = 0
for i, val in enumerate(arg_types):
arg_type = val.type
arg_name = val.name
if argno >= len(ARGS):
alltext += "// out of registers. Use the stack!"+'\n'
break
if arg_type == CHAR_STAR:
... |
sebdelsol/pyload | module/plugins/accounts/DebridItaliaCom.py | Python | gpl-3.0 | 1,321 | 0.006813 | # -*- coding: utf-8 -*-
import re
from time import mktime, strptime
from module.plugins.Account import Account
class DebridItaliaCom(Account):
__name__ = "DebridItaliaCom"
__type__ = "account"
__version__ = "0.11"
| __description__ = """Debriditalia.com account plugin"""
__lice | nse__ = "GPLv3"
__authors__ = [("stickell", "l.stickell@yahoo.it"),
("Walter Purcaro", "vuolter@gmail.com")]
WALID_UNTIL_PATTERN = r'Premium valid till: (.+?) \|'
def loadAccountInfo(self, user, req):
info = {"premium": False, "validuntil": None, "trafficleft": Non... |
buck06191/BayesCMD | bparser/ast.py | Python | gpl-2.0 | 36,960 | 0.011986 | # functions for processing the parsed syntax tree
import sys
import decimal
import string
import logger
# list of standard functions (from <math.h>) that are
# already known to be included in the destination
# NB: this list is fairly minimal -- the actual math.h
# for a contemporary C compiler is likely to include
# m... | 'outputs' : [],
'inputs' : [],
'docs' | : [],
'docstack' : [],
'modeldocs' : [],
'tags' : {},
'sources' : sources,
'extern' : [],
}
# independent variable is always at index 0
declare_symbol(find_independent(merged, independent), work)
for item i... |
skarphed/skarphed | admin/src/skarphedadmin/gui/ServerPropertyPage.py | Python | agpl-3.0 | 10,902 | 0.013212 | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as ... | x.pack_start(self.buttons,False)
self.add(self.vbox)
if server is not None:
self.ipFrame_IPEntry.set_text(server.getIp())
self.ipFrame_NameEntry.set_text(server.getRawName())
self.sshFrame_NameEntry.set_text(server.getSSHName())
self.sshF... | self.render()
def render(self):
def search(model, path, rowiter, target):
text = model.get_value(rowiter,0)
if text == target.getName():
self.ipFrame_Target.set_active_iter(rowiter)
server = None
try:
server = self.getApplicati... |
plotly/python-api | packages/python/plotly/plotly/validators/ohlc/hoverlabel/_bordercolor.py | Python | mit | 526 | 0.001901 | import _plotly_utils.basevalidators
clas | s BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bordercolor", parent_name="ohlc.hoverlabel", **kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_o... | ,
**kwargs
)
|
ScottWales/mosrs-setup | mosrs/setup.py | Python | apache-2.0 | 7,573 | 0.009375 | #!/usr/bin/env python
"""
Copyright 2016 ARC Centre of Excellence for Climate Systems Science
author: Scott Wales <scott.wales@unimelb.edu.au>
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
h... | """
Ask a yes/no question
Returns: true/false answer
"""
raw_value = raw_input(prompt + ' [yes/no] ')
try:
return strtobool(raw_value)
except ValueError:
return ask_bool(prompt)
def prompt_or_default(prompt, default):
"""
Ask a question with a default answer
Ret... | if response == '':
response = default
return response
def gpg_startup():
agent = dedent("""
[ -f ~/.gpg-agent-info ] && source ~/.gpg-agent-info
if [ -S "${GPG_AGENT_INFO%%:*}" ]; then
export GPG_AGENT_INFO
else
eval $( gpg-agent --daemon --allow-pres... |
ballouche/navitia | source/jormungandr/jormungandr/scenarios/journey_filter.py | Python | agpl-3.0 | 15,470 | 0.00362 | # Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | o General Public License for more | details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_imp... |
dpmurphy/HSPI | docs/source/conf.py | Python | mit | 5,577 | 0.001614 | # -*- coding: utf-8 -*-
#
# HSPI documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 26 17:22:42 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | te the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'HSPIdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
#... | size': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own ... |
mozillazg/redis-py-doc | redis/commands/timeseries/utils.py | Python | mit | 1,309 | 0.002292 | from ..helpers import nativestr
def list_to_dict(aList):
return {nativest | r(aList[i][0]): nativestr(aList[i][1]) for i in range(len(aList))}
def parse_range(response):
"""Parse range response. Used by TS.RANGE | and TS.REVRANGE."""
return [tuple((r[0], float(r[1]))) for r in response]
def parse_m_range(response):
"""Parse multi range response. Used by TS.MRANGE and TS.MREVRANGE."""
res = []
for item in response:
res.append({nativestr(item[0]): [list_to_dict(item[1]), parse_range(item[2])]})
retur... |
Danielhiversen/home-assistant | homeassistant/components/dhcp/__init__.py | Python | apache-2.0 | 13,216 | 0.001059 | """The dhcp integration."""
from abc import abstractmethod
from datetime import timedelta
import fnmatch
from ipaddress import ip_address as make_ip_address
import logging
import os
import threading
from aiodiscover import DiscoverHosts
from aiodiscover.discovery import (
HOSTNAME as DISCOVERY_HOSTNAME,
IP_AD... | self.hass = hass
self._integration_matchers = integration_matchers
self._address_data = address_data
def process_client(self, ip_address, hostname, mac_address):
"""Process a client."""
made_ip_address = make_ip_address(ip_address)
if (
| is_link_local(made_ip_address)
or is_loopback(made_ip_address)
or is_invalid(made_ip_address)
):
# Ignore self assigned addresses, loopback, invalid
return
data = self._address_data.get(ip_address)
if (
data
and data... |
nrz/ylikuutio | external/bullet3/examples/pybullet/gym/pybullet_envs/minitaur/robots/robot_base.py | Python | agpl-3.0 | 4,709 | 0.007008 | # Lint as: python3
"""The abstract robot class."""
import abc
from typing import Optional, Sequence
# Action names for robots operating kinematically.
LINEAR_VELOCITY = "linear_velocity"
ANGULAR_VELOCITY = "angular_velocity"
class RobotBase(metaclass=abc.ABCMeta):
"""The base class for all robots used in the mobi... | pass
@abc.abstractmethod
def post_control_step(self):
"""Updates some internal variables such as | step counters."""
pass
@property
def action_space(self):
"""The action spec of the robot."""
raise NotImplementedError("action_space is not implemented")
@property
@abc.abstractmethod
def action_names(self):
"""Name of each action in the action_space.
This is a structure of strings with... |
HandsomeYingyan/rpi-speech-recognition-car | contror/BACK.py | Python | agpl-3.0 | 331 | 0.036254 | import RPi.GPIO as GPIO
import time
INT1=11
INT2=12
INT3=13
INT4=15
GPIO.setmode(GPIO.BOARD) |
GPIO.setup(INT1,GPIO.OUT)
GPIO.setup(INT2,GPIO.OUT)
GPIO.setup(INT3,GPIO.OUT | )
GPIO.setup(INT4,GPIO.OUT)
GPIO.output(INT1,GPIO.LOW)
GPIO.output(INT2,GPIO.HIGH)
GPIO.output(INT3,False)
GPIO.output(INT4,False)
time.sleep(0.8)
GPIO.cleanup()
|
grengojbo/st2 | st2auth/st2auth/backends/__init__.py | Python | apache-2.0 | 1,972 | 0.001014 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | ense 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 the License.
import json
import importlib
from osl... |
gloryofrobots/obin | arza/types/plist.py | Python | gpl-2.0 | 11,988 | 0.000167 | from arza.types.root import W_Root
from arza.types import space
from arza.types import api
from arza.runtime import error
class W_PList(W_Root):
def __init__(self, head, tail):
self.head = head
self.tail = tail
def __iter__(self):
cur = self
while not is_empty(cur):
... | type(pl, space.islist)
def tail(pl):
type_check(pl)
return pl.tail
def split(pl):
type_check(pl)
return head(pl), tail(pl)
def _length_foldl(el, acc):
return acc + 1
def length(pl):
type_chec | k(pl)
return foldl(_length_foldl, 0, pl)
def cons(v, pl):
error.affirm_any(v)
type_check(pl)
return W_PList(v, pl)
def cons_n_list(items, pl):
type_check(pl)
head = pl
for item in reversed(items):
head = cons(item, head)
return head
def append(pl, v):
type_check(pl)
... |
catapult-project/catapult | common/py_vulcanize/py_vulcanize/html_generation_controller.py | Python | bsd-3-clause | 934 | 0.008565 | # Copyright 2013 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.
from __future__ import absolute_import
import os
import re
from py_vulcanize import style_sheet
class HTMLGenerationController(object):
def __init__(sel... | s)
return ss.contents_with_inli | ned_images
|
davy39/eric | Plugins/VcsPlugins/vcsMercurial/Ui_HgBundleDialog.py | Python | gpl-3.0 | 9,093 | 0.002969 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './Plugins/VcsPlugins/vcsMercurial/HgBundleDialog.ui'
#
# Created: Tue Nov 18 17:53:57 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class U... | self.multipleButton.setText(_translate("HgBundleDialog", "Revision | s:"))
self.multipleEdit.setToolTip(_translate("HgBundleDialog", "Enter revisions by number, id, range or revset expression one per line"))
self.tagButton.setToolTip(_translate("HgBundleDialog", "Select to specify a revision by a tag"))
self.tagButton.setText(_translate("HgBundleDialog", "Tag:"))... |
gdassori/python | python-twisted/tests/unit-test-full.py | Python | mit | 7,584 | 0.006337 | ## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
## TODO Tests
##
## - wait 20 minutes, send a message, receive and success.
## -
## -
##
##
## -------------------------... | 0MDRkLTllYTItNDhiZGE0N2JlYzBl',
## Cipher Key
'YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr' +
'WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi' + |
'jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa' +
'V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX' +
'U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz' +
'c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX' +
'RSblJWYlRGcFVqQmFlRmRyYUU0... |
hsoft/dupeguru | qt/results_model.py | Python | gpl-3.0 | 3,932 | 0.000763 | # Created By: Virgil Dupras
# Created On: 2009-04-23
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... | # --- Events
def appWillSavePrefs(self):
self.model.columns.save_columns()
# --- model --> view
def invalidate_markings(self):
# redraw view
# HACK. this is the only way I found to update the widget without reseting everything
self.view.scroll(0, 1)
self.view.scroll(... | s ResultsView(QTableView):
# --- Override
def keyPressEvent(self, event):
if event.text() == " ":
self.spacePressed.emit()
return
super().keyPressEvent(event)
def mouseDoubleClickEvent(self, event):
self.doubleClicked.emit(QModelIndex())
# We don't ca... |
ndparker/tdi | tdi/tools/htmlform/_adapters.py | Python | apache-2.0 | 4,395 | 0 | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2007 - 2015
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | ``list``.
"""
self.param = param
def getfirst(self, name, default=None):
""" :See: ``tdi.tools.htmlform.ParameterAd | apterInterface`` """
try:
result = self.param[name]
except KeyError:
pass
else:
if result:
return result[0]
return default
def getlist(self, name):
""" :See: ``tdi.tools.htmlform.ParameterAdapterInterface`` """
try:... |
suziesparkle/wagtail | wagtail/wagtailadmin/views/home.py | Python | bsd-3-clause | 2,933 | 0.003069 | from django.shortcuts import render
from django.contrib.auth.decorators import permission_required
from django.conf import settings
from django.template import RequestContext
from django.template.loader import render_to_string
from wagtail.wagtailadmin import hooks
from wagtail.wagtailcore.models import Page, PageRev... | ROM wagtailcore_pagerevision group by page_id
) as max_rev on max_rev.max_created_at = wp.created_at and wp.user_id = %s order by wp.created_at desc
""", [request.user.id])[:5]
def render(self):
return render_to_string('wagtailadmin/home/recent_edits.html', {
'last_e... |
@permission_required('wagtailadmin.access_admin')
def home(request):
panels = [
SiteSummaryPanel(request),
PagesForModerationPanel(request),
RecentEditsPanel(request),
]
for fn in hooks.get_hooks('construct_homepage_panels'):
fn(request, panels)
return render(request,... |
KirillMysnik/ArcJail | srcds/addons/source-python/plugins/arcjail/modules/arcjail/arcjail_user.py | Python | gpl-3.0 | 9,070 | 0.001985 | # This file is part of ArcJail.
#
# ArcJail 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.
#
# ArcJail is distributed in the hope that... | layer.name
self.last_online_reward = time()
self.account = 0
self.slot_data = []
self._loaded = False
@property
def loaded(self):
return self._loaded
def load_from_database(self):
if self._steamid == "BOT":
return
db_sessi | on = Session()
db_arcjail_user = db_session.query(DB_ArcjailUser).filter_by(
steamid=self._steamid).first()
if db_arcjail_user is not None:
self.account = db_arcjail_user.account
self.last_online_reward = db_arcjail_user.last_online_reward
self.slot_data... |
n2o/dpb | links/admin.py | Python | mit | 339 | 0 | from django.contrib import adm | in
from .models import Link, LinkCategory
from dpb.admin import PageDownAdmin
class LinkAdmin(PageDownAdmin):
list_display = ('title', ' | state', 'category', 'website')
list_filter = ('category',)
search_fields = ['title']
admin.site.register(Link, LinkAdmin)
admin.site.register(LinkCategory)
|
ntymtsiv/tempest | tempest/api/identity/admin/test_users.py | Python | apache-2.0 | 9,689 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | st_tenant)
# Re-auth
resp, body = self.token_client.auth(self.data.test_user,
| self.data.test_password,
self.data.test_tenant)
self.assertEqual('200', resp['status'])
@attr(type='gate')
def test_authentication_request_without_token(self):
# Request for token authentication with a valid token in h... |
asimonov-im/boinc | py/Boinc/tools.py | Python | gpl-3.0 | 2,065 | 0.00678 | ## $Id: tools.py 23525 2011-05-12 04:11:40Z davea $
import configxml
try:
# use new hashlib if available
from hashlib import md5
except:
import md5
import os, shutil, binascii, | filecmp
# from http://www.plope.com/software/uuidgen/view
_urandomfd = None
def urandom(n):
"""urandom(n) -> str
Return a string of n random bytes suitable for cryptographic use.
"""
global _urandomfd
if _urandomfd is None:
try:
_urandomfd = os.open("/dev/urandom", os.O | _RDONLY)
except:
_urandomfd = NotImplementedError
if _urandomfd is NotImplementedError:
raise NotImplementedError("/dev/urandom (or equivalent) not found")
bytes = ""
while len(bytes) < n:
bytes += os.read(_urandomfd, n - len(bytes))
return bytes
def make_uuid():
... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.3/Lib/test/test_urllibnet.py | Python | mit | 5,447 | 0.001652 | #!/usr/bin/env python
import unittest
from test import test_support
import socket
import urllib
import sys
import os
import mimetools
class URLTimeoutTest(unittest.TestCase):
TIMEOUT = 10.0
def setUp(self):
socket.setdefaulttimeout(self.TIMEOUT)
def tearDown(self):
socket.setdefaulttim... | :
FILE.close()
os.unlink(file_location)
def test_specified_path(self):
# Make sure that specifying the location of the fil | e to write to works.
file_location,info = urllib.urlretrieve("http://www.python.org/",
test_support.TESTFN)
self.assertEqual(file_location, test_support.TESTFN)
self.assert_(os.path.exists(file_location))
FILE = file(file_location)
... |
danellecline/stoqs | stoqs/loaders/CANON/loadCANON_september2018.py | Python | gpl-3.0 | 20,474 | 0.006936 | #!/usr/bin/env python
__author__ = 'Mike McCann,Duane Edgington,Danelle Cline'
__copyright__ = '2018'
__license__ = 'GPL v3'
__contact__ = 'duane at mbari.org'
__doc__ = '''
Master loader for all CANON May-June Campaign 2018
Mike McCann, Duane Edgington, Danelle Cline
MBARI 15 May 2018
@var __date__: Date of last s... | te
# NPS_34a updated paramete | r names in netCDF file
## The following loads decimated subset of data telemetered during deployment
cl.nps34a_base = 'http://legacy.cencoos.org/thredds/dodsC/gliders/Line66/'
cl.nps34a_files = [ 'OS_Glider_NPS_G34_20180514_TS.nc' ]
cl.nps34a_parms = ['temperature', 'salinity','fluorescence']
cl.nps34a_startDatetime = ... |
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_pulldom.py | Python | gpl-2.0 | 12,628 | 0.000634 | import io
import unittest
import xml.sax
from xml.sax.xmlreader import AttributesImpl
from xml.sax.handler import feature_external_ges
from xml.dom import pulldom
from test.support import findfile
tstfile = findfile("test.xml", subdir="xmltestdata")
# A handy XML snippet, containing attributes, a namespace prefix,... | node = next(items)
self.assertEqual(node.tagName, "html")
with self.assertRaises(StopIteration):
next(ite | ms)
items.clear()
self.assertIsNone(items.parser)
self.assertIsNone(items.stream)
@unittest.expectedFailure
def test_comment(self):
"""PullDOM does not receive "comment" events."""
items = pulldom.parseString(SMALL_SAMPLE)
for evt, _ in items:
if evt ... |
martomo/SublimeTextXdebug | xdebug/helper/helper_26.py | Python | mit | 1,428 | 0.001401 | """
Helper module for Python version 2.6 and below
- Ordered dictionaries
- Encoding/decoding urls
- Unicode
- Exception handling (except Exception, e)
"""
import base64
from urllib import unquote, quote
try:
from ordereddict import OrderedDict
except:
pass
def modulename():
return 'Helper module for Pyt... | return unichr(code) # noqa: F821
def unicode_string(string):
if isinstance(string, unicode): # noqa: F821
return string
return string.decode('utf8', 'replace')
def is_digit(string):
# Check if basestring (str, unicode) is digit
return isinstance(string, basestring) and string.isdigit() # ... | 21
|
gtaylor/btmux_template_io | btmux_template_io/parsers/ssw/populators/equipment.py | Python | bsd-3-clause | 2,429 | 0 | from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def populate_equipment(xml_root, unit_obj):
"""
Equipm... | ng like a SearchLight, which has no crit in BTMux.
return
data_dict = ITEM_TABLE[btmux_name]
if 'tons_per_crit' in data_dict:
crits_per_item = int(round(
float(unit_ob | j.weight) / data_dict['tons_per_crit'], 0))
else:
crits_per_item = data_dict.get('crits', 1)
add_special = data_dict.get('add_special')
if add_special:
unit_obj.specials.add(add_special)
add_crits_from_locations(
equip_e,
btmux_name,
unit_obj,
crits_per_... |
sysuccc/QiuDaBao | qiudabao/models.py | Python | gpl-2.0 | 617 | 0.025932 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
f | rom django.contrib.auth.models import User
# Create your models here.
class AccountInfo(models.Model):
user = models.ForeignKey(User)
balance = models.IntegerField()
DISH_NAME_MAX_LENGTH = 20
class Order(models.Model):
offerer = models.ForeignKe | y(User, related_name='offerer_order')
submiter = models.ForeignKey(User, related_name='submiter_order', null=True, blank=True)
dish = models.CharField(max_length=DISH_NAME_MAX_LENGTH)
description = models.TextField(blank=True)
place = models.TextField()
|
facebookexperimental/eden | eden/scm/edenscm/mercurial/annotate.py | Python | gpl-2.0 | 4,963 | 0.000403 | # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Copyright Mercurial Contributors
#
# This software may be used and distributed according to the terms of the
# GNU General Public License v... | ing the last line.
remaining = [(parent, []) for parent, _blocks in pblocks]
for idx, (parent, blocks) in enumerate(pblocks):
for (a1, a2, b1, b2), _t in blocks:
if a2 - a1 >= b2 - b1:
for bk in range(b1, b2):
if child[0][bk].fctx =... | (bk - b1), a2 - 1)
child[0][bk] = attr.evolve(parent[0][ak], skip=True)
else:
remaining[idx][1].append((a1, a2, b1, b2))
# Then, look at anything left, which might involve repeating the last
# line.
for parent, blocks in remaining:... |
annndrey/npui-unik | netprofile/netprofile/common/auth.py | Python | agpl-3.0 | 6,265 | 0.025064 | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General ... | for required in ('username', 'realm', 'nonce', 'uri', 'response' | , 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
_add_www_authenticate(request, secret, realm)
return None
return params
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback,... |
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/subversion/tests/cmdline/special_tests.py | Python | gpl-2.0 | 22,957 | 0.015943 | #!/usr/bin/env python
#
# special_tests.py: testing special and reserved file handling
#
# Subversion is a tool for revision control.
# See http://subversion.tigris.org for more information.
#
# ====================================================================
# Copyright (c) 2000-2007 CollabNet. All rights res... | = svntest.actions.get_virginal_state(wc_dir, 2)
expected_status.add({
'newfile' : Item(status=' ', wc_rev=3),
'linktarget' : Item(status=' ', wc_rev=2),
})
svntest.actions.run_and_verify_commit(wc_dir, expected_output,
| expected_status, None, wc_dir)
def replace_file_with_symlink(sbox):
"replace a normal file with a special file"
sbox.build()
wc_dir = sbox.wc_dir
# First replace a normal file with a symlink and make sure we get an
# error
iota_path = os.path.join(wc_dir, 'iota')
os.remove(i... |
ArtemVavilov88/test2-Se-Python-14 | test_search_negative.py | Python | apache-2.0 | 1,089 | 0.003673 | import unittest
from selenium impo | rt webdriver
from selenium.webdriver.common.keys import Keys
class php4dvd_search_film_negative(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(20)
def test_search_negative(self):
driver = self.driver
drive | r.get("http://localhost/php4dvd/")
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("admin")
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("admin")
driver.find_element_by_name("submi... |
kreczko/l1t_cli | l1t_cli/commands/dqm/offline/setup/__init__.py | Python | apache-2.0 | 2,339 | 0.002138 | """
dqm offline setup:
Sets up CMSSW and the latest code to preduce OfflineDQM plots
Usage:
dqm offline setup
"""
import logging
import os
import string
import hepshell
from hepshell.interpreter import time_function
from l1t_cli.setup import WORKSPACE, INTEGRATION_TAG
LOG = logging.ge... | uccess: # stop at first error
| return False
# now activate the working area:
from l1t_cli.commands.update.active_cmssw import Command as UpdateCMSSW
c = UpdateCMSSW()
new_cmssw = os.path.join(WORKSPACE, RECIPE['alias'])
c.run([new_cmssw], {})
return True
|
josiah-wolf-oberholtzer/uqbar | tests/fake_package/multi/two.py | Python | mit | 130 | 0 | class PublicClass:
pass
class _PrivateClass:
pass
de | f public_function():
| pass
def _private_function():
pass
|
ypid/series60-remote | pc/widget/ContactCanvas.py | Python | gpl-2.0 | 1,696 | 0.019458 | # -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Matplotlib
try:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as Navig... | Figure
except ImportError:
USE_MATPLOTLIB = False
else:
USE_MATPLOTLIB= True
if USE_MATPLOTLIB:
class ContactCanvas(FigureCanvas):
def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = Non | e):
self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey)
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
... |
srct/bookshare | bookshare/lookouts/admin.py | Python | gpl-3.0 | 290 | 0 | # core django imports
fro | m django.contrib import admin
# imports from your apps
from .models import Lookout
@admin.register(Lookout)
class LookoutAdmin(admin.ModelAdm | in):
list_display = ('id', 'created', 'modified', 'owner', 'isbn')
list_filter = ('created', 'modified', 'owner')
|
ncbray/pystream | bin/tests/test_tvl.py | Python | apache-2.0 | 3,771 | 0.024397 | # Copyright 2011 Nicholas Bray
#
# 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... | )
self.assertRaises(TypeError, bool, tvl.TVLFalse)
def testTVLMaybe(self):
self.assertEqual(tvl.TVLMaybe.mustBeTrue(), False)
self.assertEqual(tvl.TVLMaybe.maybeTrue(), True)
self.assertEqual(tvl.TVLMaybe.maybeFalse(), True)
self.assertEqual(tvl.TVLMaybe.mustBeFalse(), False)
self.assertRaises(TypeE... | vert(unittest.TestCase):
def testTVLTrue(self):
self.assertEqual(~tvl.TVLTrue, tvl.TVLFalse)
def testTVLFalse(self):
self.assertEqual(~tvl.TVLFalse, tvl.TVLTrue)
def testTVLMaybe(self):
self.assertEqual(~tvl.TVLMaybe, tvl.TVLMaybe)
class TestTVLAnd(unittest.TestCase):
def testTVLTrue(self):
self.assertEq... |
renanalencar/hermes | agency/migrations/0014_auto_20150726_1411.py | Python | mit | 468 | 0.002137 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('agency', '0013_auto_20150726_0001'),
]
operations = [
migrations.AlterField(
| model_name='feedinfo',
name='feed_publisher_name',
field=models.CharField(max_length=5 | 0, verbose_name='Name', choices=[(b'EPTTC', 'EPTTC')]),
),
]
|
opennode/nodeconductor | waldur_core/core/migrations/0002_remove_organization.py | Python | mit | 398 | 0 | # -*- coding: utf-8 -*-
# Generated | by Django 1.11.7 on 2018-04-10 07:17
from __future__ import unicode_literals
from django.db import migrations
class Migra | tion(migrations.Migration):
dependencies = [
('core', '0001_squashed_0008'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='organization_approved',
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.