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 |
|---|---|---|---|---|---|---|---|---|
MangoMangoDevelopment/neptune | lib/ros_comm-1.12.0/utilities/roswtf/src/roswtf/graph.py | Python | bsd-3-clause | 14,968 | 0.008485 | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above... | rule that in particular seems useful is the timestamp drift. It may be too
#expensive otherwise to run, though it would be interesting to attempt to receive a
#message from every single topic.
#TODO: parameter audit?
service_errors = [
]
service_warnings = [
]
topic_errors = [
(topic_timestamp_drif... | ]
## cache sim_time calculation sot that multiple rules can use
def _compute_sim_time(ctx):
param_server = rosgraph.Master('/roswtf')
ctx.use_sim_time = False
try:
val = simtime = param_server.getParam('/use_sim_time')
if val:
ctx.use_sim_time = True
except:
... |
The-OpenROAD-Project/OpenROAD | src/odb/test/unitTestsPython/TestWireCodec.py | Python | bsd-3-clause | 5,470 | 0.005484 | import opendbpy as odb
import helper
import odbUnitTest
class TestWireCodec(odbUnitTest.TestCase):
#This Function | is called before each of the test cases defined below
def setUp(self):
self.db, self.tech, self.m1, self.m2, self.m3, self.v1 | 2, self.v23 = helper.createMultiLayerDB()
self.chip = odb.dbChip_create(self.db)
self.block = odb.dbBlock_create(self.chip, "chip")
self.net = odb.dbNet_create(self.block, "net")
self.wire = odb.dbWire_create(self.net)
self.pathsEnums = ["PATH", "JUNCTION", "SHORT", "VWIRE", ... |
TE-ToshiakiTanaka/bantorra.old | script/testcase_base.py | Python | mit | 1,751 | 0.001142 | import os
import sys
import argparse
import ConfigParser
import testcase_service
from bantorra.util import define
from bantorra.util.log import LOG as L
class TestCase_Base(testcase_service.TestCaseUnit):
config = {}
"""
TestCase_Base.
- Parse Command Line Argument.
- Create Se... | Parse Command Line Arguments.
"""
return None
@classmethod
def get_servic | e(cls):
"""
Get Service.
in the wifi branch, Used service is there.
"""
cls.core = cls.service["core"].get()
cls.picture = cls.service["picture"].get()
@classmethod
def get_config(cls, conf=""):
"""
Get Config File.
:arg st... |
kylon/pacman-fakeroot | test/pacman/tests/sync701.py | Python | gpl-2.0 | 504 | 0 | self.description = "incoming package replaces symlink with directory (order | 1)"
lp = pmpkg("pkg1")
lp.files = ["usr/lib/foo",
"lib -> usr/lib"]
self.addpkg2db("local", lp)
p1 = pmpkg("pkg1", "1.0-2")
p1.files = ["usr/lib/foo"]
self.addpkg2db("sync", p1)
p2 = pmpkg("pkg2")
p2.files = ["lib/bar"]
self.addpkg2db("sync", p2)
self.args = "-S pkg1 pkg2"
self.addrule("PACMAN_RETCODE... | ("PKG_VERSION=pkg1|1.0-2")
self.addrule("PKG_EXIST=pkg2")
self.addrule("FILE_TYPE=lib|dir")
|
pniedzielski/fb-hackathon-2013-11-21 | src/py/level3.py | Python | agpl-3.0 | 1,260 | 0.001587 | # Learn Python -- level 2 logic
# Copyright (C) 2013 Cornell FB Hackathon Team.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) an... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero 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/>.
player1._position = [5, 6]
_world.grid[player1._posit... | [14, 6]
_world.grid[player2._position[1]][player2._position[0]] = player2
items = [Item("bread", [0, 2]),
Item("mushroom", [11, 9]),
Item("scepter", [5, 4]),
Item("banana", [17, 3]),
Item("bread", [10, 1]),
Item("sword", [8, 9])]
def at_end():
if (player1.inventory.co... |
jokey2k/sentry | src/sentry/testutils/helpers/auth_header.py | Python | bsd-3-clause | 431 | 0 | from __future__ import absolute_import
__all__ = ('get_auth_header',)
def get_auth_header(client, api_key=None, secret_key=No | ne):
header = [
('sentry_client', client),
('sentry_version', '5'),
]
if api_key:
header.append(('sentry_key', api_key))
if secret_key:
header.append(('sentry_secret', secret_key))
return 'Sentry %s' % ', '.join('%s=%s' % (k, v | ) for k, v in header)
|
therewillbecode/ichnaea | ichnaea/api/locate/query.py | Python | apache-2.0 | 10,806 | 0 | """Code representing a query."""
import six
from ichnaea.api.locate.constants import (
DataAccuracy,
MIN_WIFIS_IN_QUERY,
)
from ichnaea.api.locate.schema import (
CellAreaLookup,
CellLookup,
FallbackLookup,
WifiLookup,
)
try:
from collections import OrderedDict
except ImportError: # prag... | oip_db: A geoip database.
:type geoip_db: :class:`~ichnaea.geoip.GeoIPWrapper`
:param stats_client: A stats client.
:type stats_client: :class:`~ichnaea.log.StatsClient`
"""
self.geoip_db = geoip_db
self.http_session = http_session
self.session = session
... | .wifi = wifi
self.api_key = api_key
if api_type not in (None, 'country', 'locate'):
raise ValueError('Invalid api_type.')
self.api_type = api_type
@property
def fallback(self):
"""
A validated
:class:`~ichnaea.api.locate.schema.FallbackLookup` instanc... |
solashirai/edx-platform | lms/djangoapps/teams/serializers.py | Python | agpl-3.0 | 7,981 | 0.00213 | """Defines serializers used by the Team API."""
from copy import deepcopy
from django.contrib.auth.models import User
from django.db.models import Count
from django.conf import settings
from django_countries import countries
from rest_framework import serializers
from openedx.core.lib.api.serializers import Collapsed... | ready present in the topic data, and if not, querying the CourseTeam
model to get the count. Requires that `context` is provided with a valid course_id
in order to filter teams within the course.
"""
team_count = serializers.SerializerMethodField()
def get_team_count(self, topic):
"""Get th... | topic:
return topic['team_count']
else:
return CourseTeam.objects.filter(course_id=self.context['course_id'], topic_id=topic['id']).count()
class BulkTeamCountTopicListSerializer(serializers.ListSerializer): # pylint: disable=abstract-method
"""
List serializer for efficientl... |
lablup/sorna-repl | python-tensorflow/test_run.py | Python | lgpl-3.0 | 2,665 | 0.001876 | import argparse
from getpass import getpass
import json
import sys
import textwrap
import zmq
import colorama
from colorama import Fore
def execute(code):
ctx = zmq.Context.instance()
ctx.setsockopt(zmq.LINGER, 50)
repl_in = ctx.socket(zmq.PUSH)
repl_in.connect('tcp://127.0.0.1:2000')
rep | l_out = | ctx.socket(zmq.PULL)
repl_out.connect('tcp://127.0.0.1:2001')
with repl_in, repl_out:
msg = (b'xcode1', code.encode('utf8'))
repl_in.send_multipart(msg)
while True:
data = repl_out.recv_multipart()
msg_type = data[0].decode('ascii')
msg_data = data[1]... |
Gorbeh/sf | src/WindowManager.py | Python | agpl-3.0 | 16,966 | 0.0234 |
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, ... | leAction == ROW_EDIT):
CurrentRow = self.Ui.tableWidgetTable.currentRow()
ValuesList = self.ReadTableRow(CurrentRow)
self.InputUi.lineEditParamName.setText(ValuesList[PARAM_NAME_COL])
self.InputUi.comboBoxType.setCurrentIndex(Para | mTypeList.index(ValuesList[PARAM_TYPE_COL]))
if (ValuesList[PARAM_MDLINIT] == "Yes"):
self.InputUi.checkBoxmdlInitializeSizes.setCheckState(QtCore.Qt.Checked)
else:
self.InputUi.checkBoxmdlInitializeSizes.setCheckState(QtCore.Qt.Unchecked)
if (ValuesList[PARAM_MDLSTART] == "Yes"):
self.InputU... |
ferrine/gelato | gelato/tests/conftest.py | Python | mit | 130 | 0 | import numpy as | np
import gelato
import pytest
@pytest.fixture()
def seeded():
gelato.set_tt_rng(42)
np.random.seed | (42)
|
frontendphil/analyzr | parsr/checkers.py | Python | mit | 15,240 | 0.001247 | import subprocess
import json
import math
import re
import lizard
from jinja2 import Environment, FileSystemLoader
from xml.dom import minidom
from decimal import Decimal
from analyzr.settings import CONFIG_PATH, PROJECT_PATH, LAMBDA
XML_ILLEGAL = u'([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][... | template | = self.env.get_template("%s.xml" % self.name)
file_count = len(files)
chunks = int(math.ceil(file_count / self.FILE_BATCH_SIZE))
if not file_count % self.FILE_BATCH_SIZE == 0:
chunks = chunks + 1
for i in range(chunks):
start = i * self.FILE_BATCH_SIZE
... |
ryepdx/scale_proxy_server | header_decorators.py | Python | agpl-3.0 | 376 | 0.005319 | def json_headers(f):
def wrappe | d(*args, **kwargs):
resp = f(*args, **kwargs)
resp.headers['Content-Type'] = 'application/json'
return resp
return wrapped
def max_age_headers(f):
def wrapped(*args, **kwargs):
resp = f(*args, **kwargs)
resp.headers['Access-Co | ntrol-Max-Age'] = 9999999
return resp
return wrapped
|
pombredanne/django-custard | custard/tests/test.py | Python | mit | 17,657 | 0.003908 | from __future__ import unicode_literals
from datetime import date, time, datetime
import django
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, Client
from django.test.clien... | cf.full_clean()
| cf = CustomFieldsUniqueModel.objects.create(content_type=self.simple_unique,
name='name',
label="Field already present in model",
data_type=CUSTOM_TYPE_INTEGER)
... |
QuLogic/burnman | burnman/data/input_raw_endmember_datasets/HHPH2013data_to_burnman.py | Python | gpl-2.0 | 3,130 | 0.01246 | # BurnMan - a lower mantle toolkit
# Copyright (C) 2012-2014, Myhill, R., Heister, T., Unterborn, C., Rose, I. and Cottaar, S.
# Released under GPL v2 or later.
# This is a standalone program that converts a tabulated version of the Stixrude and Lithgow-Bertelloni data format into the standard burnman format (printed ... | or b
1.e-5, # table conversion
1.e8, # kbar -> Pa
1.0, # no scale for K'0
1.e-8] #GPa -> Pa # no scale for eta_s
formula='0'
for idx, m in enumerate(ds):
if idx == 0:
param_names=m
else:
print 'class', | m[0].lower(), '(Mineral):'
print ' def __init__(self):'
print ''.join([' formula=\'',m[1],'\''])
print ' formula = dictionarize_formula(formula)'
print ' self.params = {'
print ''.join([' \'name\': \'', m[0], '\','])
print ' \... |
tencrance/cool-config | python_tricks/call_str_repr.py | Python | mit | 510 | 0.018595 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/7 17:13
# @Author : Zhiwei Yang
# @File : call_str_repr.py.py
class print_name(object):
def __init__(self,name):
self.name = name
class print_name_pro(object):
def __int__(self,name):
self.name = name
def __str__(self)... | print_name("yang")
print (a) # 这样打印不好看,所以请看类B
b = print_name_pro("zhi" | )
print (b) |
cidadania/e-cidadania | src/core/spaces/models.py | Python | apache-2.0 | 8,796 | 0.003183 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Clione Software
# Copyright (c) 2010-2013 Cidadania S. Coop. Galega
#
# 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.or... | datetime import datetime
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from core.spaces.file_validation import ContentTypeRestrictedFileFie... | del. This model stores a "space" or "place" also known as a
participative process in reality. Every place has a minimum set of
settings for customization.
There are three main permission roles in every space: administrator
(admins), moderators (mods) and regular users (users).
"""
name = models... |
yosshy/osclient2 | osclient2/cinder/v2/volume_backup.py | Python | apache-2.0 | 4,420 | 0 | # Copyright 2014-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
# 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... | volume=volume.get_id(),
name=transfer_name))
def delete(self, force=False):
"""
Delete a volume backup
@keyword force: Whether the deletion is forced
@type force: bool
@rtype: None
"""
if ... | _http.post(self._url_resource_path, self._id, 'action',
data=utils.get_json_body("os-force_delete"))
class Manager(base.Manager):
"""manager class for volume backups on Block Storage V2 API"""
resource_class = Resource
service_type = 'volume'
_attr_mapping = ATTRIBUTE_MAPPING
... |
JaDogg/__py_playground | reference/peglet/examples/json.py | Python | mit | 2,243 | 0.012929 | """
Example: parse JSON.
"""
from peglet import Parser, hug, join, attempt
literals = dict(true=True,
false=False,
null=None)
mk_literal = literals.get
mk_object = lambda *pairs: dict(pairs)
escape = lambda s: s.decode('unicode-escape')
mk_number = float
# Following http://www.... | e('0')
#. (0.0,)
## json_parse('0.125e-2')
#. (0.00125,)
## attempt(json_parse, '0377')
## attempt(json_parse, '{"hi"]')
# Udacity CS212 problem 3.1:
## json_parse('["testing", 1, 2, 3]')
#. (('testing', 1.0, 2.0, 3.0),)
## json_parse('-123.456e+789')
#. (-inf,)
## json_parse('{"age": 21, "state":"CO","occupation"... | 21.0, 'state': 'CO', 'occupation': 'rides the rodeo'},)
|
bbsan2k/nzbToMedia | core/transmissionrpc/torrent.py | Python | gpl-3.0 | 16,349 | 0.001529 | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import sys
import datetime
from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT
from core.transmissionrpc.utils import Field, format_timedelta
from six import integer_types... | pending',
6: 'seeding',
}
return mapping[code]
class Torrent(object):
"""
Torrent is a class holding the data received from Transmission regarding a bittorrent transfer.
All fetched torrent fields are accessible through this class using attributes.
This class has a few convenience pro... | raise ValueError('Torrent requires an id')
self._fields = {}
self._update_fields(fields)
self._incoming_pending = False
self._outgoing_pending = False
self._client = client
def _get_name_string(self, codec=None):
"""Get the name"""
if codec is Non... |
charanpald/sandbox | sandbox/recommendation/MaxLocalAUC.py | Python | gpl-3.0 | 37,126 | 0.016134 | import array
import itertools
import logging
import multiprocessing
import numpy
import scipy.sparse
import sharedmem
import sppy
import time
from sandbox.misc.RandomisedSVD import RandomisedSVD
from sandbox.recommendation.AbstractRecommender import AbstractRecommender
from sandbox.recommendation.IterativeSoftImput... | recommendation.MaxAUCSigmoid import MaxAUCSigmoid
from sandbox.recommendation.Recommender | Utils import computeTestMRR, computeTestF1
from sandbox.recommendation.WeightedMf import WeightedMf
from sandbox.util.MCEvaluatorCython import MCEvaluatorCython
from sandbox.util.MCEvaluator import MCEvaluator
from sandbox.util.Sampling import Sampling
from sandbox.util.SparseUtilsCython import SparseUtilsCython
fro... |
KAMI911/lactransformer | lactransformer/lasdiff.py | Python | mpl-2.0 | 6,565 | 0.003656 | try:
import traceback
import argparse
import textwrap
import glob
import os
import logging
import datetime
import multiprocessing
from libs import LasPyConverter
except ImportError as err:
print('Error {0} import module: {1}'.format(__name__, err))
traceback.print_exc()
e... | os.path.join(outputpath, os.path.basename(workfile))])
| else:
logging.info('The %s is not file, or pair of comparable files. Skipping.' % (workfile))
elif os.path.isfile(inputfiles):
inputisdir = False
workfile = inputfiles
if os.path.basename(outputfiles) is not "":
doing.append([workfile, outputfiles])
else... |
faneshion/MatchZoo | matchzoo/layers/matching_layer.py | Python | apache-2.0 | 5,753 | 0 | """An implementation of Matching Layer."""
import typing
import tensorflow as tf
from keras.engine import Layer
class MatchingLayer(Layer):
"""
Layer that computes a matching matrix between samples in two tensors.
:param normalize: Whether to L2-normalize samples along the
dot product axis befor... | yer should be called '
'on 2 inputs with same 0,2 dimensions.')
if self._matching_type in ['mul', 'plus', 'minus']:
return shape1[0], shape1[1], shape2[1], shape1[2]
elif self._matching_type == 'dot':
return shape1[0], shape1[1], shape2[1], 1
... | return shape1[0], shape1[1], shape2[1], shape1[2] + shape2[2]
else:
raise ValueError(f"Invalid `matching_type`."
f"{self._matching_type} received."
f"Must be in `mul`, `plus`, `minus` "
f"`dot` and `concat... |
AZQ1994/s4compiler | sr_mult.py | Python | gpl-3.0 | 5,281 | 0.065897 | from list_node import ListNode
from instruction import Instruction, Subneg4Instruction
def sr_mult(WM, LM):
namespace_bak = WM.getNamespace(string=False)
WM.setNamespace(["sr","mult"])
c_0 = WM.const(0)
c_1 = WM.const(1)
c_m1 = WM.const(-1)
c_32 = WM.const(32)
a = WM.addDataWord(0, "arg1")
b = W... | ListNode(Subneg4Instruction(
| c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
ret_addr
)))
)
WM.setNamespace(namespace_bak)
return LNs, a, b, ret_addr, lo |
openstack/horizon | openstack_dashboard/dashboards/project/networks/ports/urls.py | Python | apache-2.0 | 1,111 | 0 | # Copyright 2012 NEC Corporation
#
# 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... | issions and limitations
# under the License.
from django.conf.urls import url
from openstack_dashboard.dashboards.project.networks.ports import views
from openstack_dashboard.dashboards.project.networks.ports.extensions. \
allowed_address_pairs import views as addr_pairs_views
PORTS = r'^(?P<port_id>[^/]+)/%... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_04_01/models/_models.py | Python | mit | 674,347 | 0.003676 | # 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 ... | cationCertificate]
:param trusted_root_certificates: Trusted Root certificates of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limit | s#application-gateway-limits>`_.
:type trusted_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayTrustedRootCertificate]
:param ssl_certificates: SSL certificates of the application gateway resource. For default
limits, see `Application Gateway limits
<https://docs.... |
ohaz/Colours | main.py | Python | apache-2.0 | 1,269 | 0.002364 | # -*- coding: utf-8 -*-
# Main kivy import
import kivy
# Additional kivy imports
from kivy.app import App
from kivy.config import Config
# Screens
from screens import screenmanager
from screens.mainscreen import MainScreen
from screens.ingamescreen import IngameScreen
# Cause program to end if the required kivy ver... | ---------------
# Multitouch emulation creates red dots on the screen. We don't need multitouch, so we disable it
Config.set('input', 'mouse', 'mouse,disable_multitouch')
# ---------------------
# Local initialisations
# ---------------------
# Initialise the screen manager (screens/screenmanager.py)
screenmanager.... | en(name='ingame')])
# Start with the main menu screen
screenmanager.change_to('main_menu')
class ColoursApp(App):
"""
The main Class.
Only needed for the build function.
"""
def build(self):
"""
Method to build the app.
:return: the screenmanager
"""
return... |
nachandr/cfme_tests | cfme/tests/containers/test_containers_smartstate_analysis.py | Python | gpl-2.0 | 5,838 | 0.002398 | import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui impor... | olarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
if test_item.is_openscap:
random_image_instance.assign_policy_profiles('OpenSCAP profile')
else:
random_image_instance.unassign_policy_profiles('OpenSCAP profi... | random_image_instance.last_scan_attempt_on
random_image_instance.scan()
task = provider.appliance.collections.tasks.instantiate(
name=f"Container Image Analysis: '{random_image_instance.name}'", tab='AllTasks')
task.wait_for_finished()
soft_assert(original_scan != random_image_instance.last... |
jendap/tensorflow | tensorflow/python/compiler/tensorrt/test/quantization_mnist_test.py | Python | apache-2.0 | 10,917 | 0.005954 | # 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... | , use_trt, batch_size, num_epochs, model_dir):
"""Train or evaluate the model.
Args:
is_training: whether to train or evaluate the model. In training mode,
quantization will | be simulated where the quantize_and_dequantize_v2 are
placed.
use_trt: if true, use TRT INT8 mode for evaluation, which will perform
real quantization. Otherwise use native TensorFlow which will perform
simulated quantization. Ignored if is_training is True.
batch_size: batch size.
... |
lizardsystem/lizard-box | lizard_box/migrations/0008_auto__add_portaltab__add_layoutportaltab__chg_field_box_url.py | Python | gpl-3.0 | 5,651 | 0.007963 | # 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 model 'PortalTab'
db.create_table('lizard_box_portaltab', (
('id', self.gf('django.db... | b.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Box']"}),
'column': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Column']"}),
'height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.mo... | eld', [], {'default': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'})
},
'lizard_box.layout': {
'Meta': {'object_name': 'Layout'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}... |
gotgenes/BiologicalProcessNetworks | bpn/mcmc/sabpn.py | Python | mit | 3,485 | 0.003156 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing. |
"""
import collections
import itertools
import sys
from convutils import convutils
import bpn.cli
import bpn.structures
from defaults import (
SUPERDEBUG,
SUPERDEBUG_MODE,
LINKS_FIELDNAMES,
PARAMETERS_FIELDNAMES,
TRANSITIONS_FIELDNAMES,
DETAILED_TRANSITIONS_FIELDNAM... | ger = logging.getLogger('bpn.sabpn')
if SUPERDEBUG_MODE:
# A logging level below logging.DEBUG
logging.addLevelName(SUPERDEBUG, 'SUPERDEBUG')
logger.setLevel(SUPERDEBUG)
#stream_handler.setLevel(SUPERDEBUG)
import simulatedannealing
import states
import recorders
def main(argv=None):
cli_parser =... |
jimmycallin/master-thesis | architectures/svm_baseline/resources.py | Python | mit | 5,218 | 0.002108 | from misc_utils import get_config, get_logger, tokenize
from discourse_relation import DiscourseRelation
from collections import Counter, defaultdict
import json
import abc
import numpy as np
from os.path import join
import os
logger = get_logger(__name__)
class Resource(metaclass=abc.ABCMeta):
def __init__(self,... | else:
rel_type = 'Implicit'
predicted_rels.append(rel.to_output_f | ormat(text_result, rel_type)) # turn string representation into list instance first
# Store test file
if not os.path.exists(store_path):
os.makedirs(store_path)
with open(join(store_path, 'output.json'), 'w') as w:
for rel in predicted_rels:
w.write(json... |
txdywy/wiki20 | wiki20/tests/models/test_auth.py | Python | gpl-2.0 | 1,523 | 0.009849 | # -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest
class TestGroup(ModelTest):
"""Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(... | = "Test Group"
)
class TestUser(ModelTest):
"""Unit test case for the ``User`` model."""
klass = model.User
attrs = dict(
user_name = "ignucius",
email_address = "ignucius@example.org"
)
def test_obj_creation_username(self):
"""The obj constructor must se... | ation_email(self):
"""The obj constructor must set the email right"""
eq_(self.obj.email_address, "ignucius@example.org")
def test_no_permissions_by_default(self):
"""User objects should have no permission by default."""
eq_(len(self.obj.permissions), 0)
def test_getting_by_ema... |
nicksergeant/snipt | views.py | Python | mit | 1,815 | 0.000551 | from annoying.decorators import ajax_request, render_to
from blogs.views import blog_list
from django.db.models import Count
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from snipts.utils import get_lexers_list
from taggit.models import Tag
@render_to('homepage.html')
def homepage(request):
... | rue)
popular_tags = popular_tags.annotate(
count=Count('taggit_taggeditem_items__id'))
popular_tags = popular_tags.order_by('-count')[:20]
popular_tags = sorted(popular_tags, key=lambda tag: tag.name)
return {
'all_tags | ': all_tags,
'tags': popular_tags
}
@ajax_request
def user_api_key(request):
if not request.user.is_authenticated():
return HttpResponseBadRequest()
return {
'api_key': request.user.api_key.key
}
|
jennirinker/PyFAST | setup.py | Python | gpl-3.0 | 395 | 0.002532 | """ Set-up script to in | stall PyFAST locally
"""
from setuptools import setup
setup(name='pyfast',
version='0.1',
description='Tools for working with wind turbine simulator FAST',
| url='https://github.com/jennirinker/PyFAST.git',
author='Jenni Rinker',
author_email='jennifer.m.rinker@gmail.com',
license='GPL',
packages=['pyfast'],
zip_safe=False) |
abw333/dominoes | dominoes/__init__.py | Python | mit | 675 | 0 | from dominoes import players
from dominoes import search
from dominoes.board import Board
from dominoes.domino import Domino
from dominoes.exceptions import EmptyBoardException
from dominoes.exceptions import EndsMismatchException
from dominoes.exceptions import GameInProgressException
from dominoes.exce | ptions import GameOverException
from dominoes.exceptions import NoSuchDominoException
from dominoes.exceptions import NoSuchPlayerException
from dominoes.exceptions import SeriesOverException
from dominoes.game import Game
from dominoes.hand impo | rt Hand
from dominoes.result import Result
from dominoes.series import Series
from dominoes.skinny_board import SkinnyBoard
|
PrincetonUniversity/pywsse | wsse/client/requests/tests/test_auth.py | Python | lgpl-3.0 | 2,780 | 0.026278 | # wsse/client/requests/tests/test_auth.py
# coding=utf-8
# pywsse
# Authors: Rushy Panchal, Naphat Sanguansin, Adam Libresco, Jérémie Lumbroso
# Date: September 1st, 2016
# Description: Test the requests authentication implementation
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.c... | settings.NONCE_STORE_ARGS = []
def tearDownModule():
'''
Tear down the module after running tests.
'''
# R | estore the nonce settings.
settings.NONCE_STORE, settings.NONCE_STORE_ARGS = __old_nonce_settings
class TestWSSEAuth(StaticLiveServerTestCase):
'''
Test authenticating through the `WSSEAuth` handler.
'''
endpoint = reverse_lazy('api-test')
def setUp(self):
'''
Set up the test cases.
'''
self.user = User... |
novapost/django-email-change | src/email_change/__init__.py | Python | apache-2.0 | 1,088 | 0.001838 | # -*- coding: utf-8 -*-
#
# This file is part of django-email-change.
#
# django-email-change adds support for email address change and confirmation.
#
# Development Web Site:
# - http://www.codetrax.org/projects/django-email-change
# Public Source Code Repository:
# - https://source.codetrax.org/hgroot/djang... | IES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
VERSION = (0, 2, 3, 'final', 0)
def get_version():
version = | '%d.%d.%d' % (VERSION[0], VERSION[1], VERSION[2])
return version
|
obutkalyuk/Python_15 | fixture/session.py | Python | apache-2.0 | 1,157 | 0.002593 | class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, user, password):
wd = self.app.wd
self.app.open_home_page()
self.app.type_text("user", user)
self.app.type_text("pass", password)
wd.find_element_by_css_selec | tor("input[value='Login']").click()
def ensure_login(self, user, password):
wd = self.app.wd
if self.is_logged_in():
if self.is_logged_in_as(user):
return
else:
self.logout()
self.login( | user,password)
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Logout").click()
def ensure_logout(self):
wd = self.app.wd
if self.is_logged_in():
self.logout()
def is_logged_in(self):
wd = self.app.wd
return len(wd.find_elements... |
ysasaki6023/NeuralNetworkStudy | cifar02/analysis_DropTest.py | Python | mit | 925 | 0.028108 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm
fig = plt.figure()
ax = {}
ax["DropOut"] = fig.add_subplot(121)
ax["NoDropOut"] = fig.add_subplot(122)
dList = {}
dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"]
dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"]
d... |
for i,dfile in enumerate(dName):
print dfile
d = pd.read_csv("Output_DropTest/%s/output.dat"%dfile)
dTrain = d[d["mode"]=="Train"]
dTest = d[d["mode"]=="Test" ]
ax.plot(dTrain.epoch, dTrain.accuracy*100., lineStyle="-" , color=cList[i], label=dfile)
ax.plot(dTest .e... | end(loc=4,fontsize=8)
ax.grid()
for k in dList:
myPlot(ax[k],dList[k])
plt.show()
|
mpearmain/BayesBoost | examples/usage.py | Python | apache-2.0 | 1,604 | 0.00187 | from bayes_opt import BayesianOptimization
'''
Example of how to use this bayesian optimization package.
'''
# Lets find the maximum of a simple quadratic function of two variables
# We create the bayes_opt object and pass the function to be maximized
# together with the paraters names and their bounds.
bo = BayesianO... | y with target values as keys of another
# dictionary with parameters names and their corresponding value.
bo.initialize({-2: {'x': 1, 'y': 0}, -1.251: {'x': 1, 'y': 1.5}})
# Once we are satisfied with the initialization conditions
# we let the algorithm do its magic by calling the maximize()
# method.
bo.maximize(n_it... | lf.res
print(bo.res['max'])
# If we are not satisfied with the current results we can pickup from
# where we left, maybe pass some more exploration points to the algorithm
# change any parameters we may choose, and the let it run again.
bo.explore({'x': [0.6], 'y': [-0.23]})
bo.maximize(n_iter=5, acq='pi')
# Finally... |
bjodah/pysym | pysym/util.py | Python | bsd-2-clause | 2,569 | 0 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return... | prefix, '_'.join(map(str, index))))
return arr
def lambdify(args, exprs):
"""
lambdify mimics sympy.lambdify
"""
try:
nargs = len(args)
except TypeError:
| args = (args,)
nargs = 1
try:
nexprs = len(exprs)
except TypeError:
exprs = (exprs,)
nexprs = 1
@_wrap_numbers
def f(*inp):
if len(inp) != nargs:
raise TypeError("Incorrect number of arguments")
try:
len(inp)
except Type... |
tommyip/zulip | zerver/webhooks/trello/view/card_actions.py | Python | apache-2.0 | 10,437 | 0.004791 | from typing import Any, Dict, Mapping, Optional, Tuple
from .exceptions import UnknownUpdateCardAction
SUPPORTED_CARD_ACTIONS = [
u'updateCard',
u'createCard',
u'addLabelToCard',
u'removeLabelFromCard',
u'addMemberToCard',
u'removeMemberFromCard',
u'addAttachmentToCard',
u'addChecklist... | e'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_added_attachment_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'attachment_url': get_action_data(payload)['attachment'].get('url'),
'attachment_name': get_action_data(payload)['attachmen... | tr, Any], action_type: str) -> str:
data = {
'card_name': get_card_name(payload),
'old_list': get_action_data(payload)['listBefore'].get('name'),
'new_list': get_action_data(payload)['listAfter'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def ... |
cydcowley/Imperial-Visualizations | visuals_EM/Waves and Dielectrics/plotly_arrows.py | Python | mit | 2,137 | 0.003745 | import numpy as np
import plotly.graph_objs as go
def p2c(r, theta, phi):
"""Convert polar unit vector to cartesians"""
return [r * np.sin(theta) * np.cos(phi),
r * np.sin(theta) * np.sin(phi),
r * np.cos(theta)]
# return [-r * np.cos(theta),
# r * np.sin(theta) * np.sin(... | ans [0, π]
out (bool) - True if outgoing, False if incoming (to the origin)
width (int) - line thickness
color (hex/rgb) - line color
"""
self.theta = theta
self.out = out
self.width = width
self.color = color
wing_length, wing_angle =... | _xyz = p2c(1., self.theta, 0)
wings_xyz = [p2c(wing_length, self.theta + wing_angle, 0),
p2c(wing_length, self.theta - wing_angle, 0)]
self.shaft = go.Scatter3d(
x=[0, shaft_xyz[0]],
y=[0, shaft_xyz[1]],
z=[0, shaft_xyz[2]],
showlegen... |
mcanaves/django-tenant-schemas | examples/tenant_tutorial/tenant_tutorial/views.py | Python | mit | 1,030 | 0.000971 | from customers.models import Client
from django.conf import settings
from django.db import utils
from django.views.generic import TemplateView
from tenant_schemas.utils import remove_www
class HomeView(TemplateView):
template_name = "index_public.html"
def get_context_data(self, **kw | args):
context = super(HomeView, self).get_context_data(**kwargs)
hostname_without_port = remove_www(self.request.get_host().split(':')[0])
try:
Client.objects.get(schema_name='public')
except utils.DatabaseError:
context['need_sync'] = True
context[... | S
context['tenants_list'] = []
return context
except Client.DoesNotExist:
context['no_public_tenant'] = True
context['hostname'] = hostname_without_port
if Client.objects.count() == 1:
context['only_public_tenant'] = True
context['ten... |
hastexo/django-oscar-vat_moss | oscar_vat_moss/order/models.py | Python | bsd-3-clause | 375 | 0 | from oscar_vat_moss import fields
from oscar.apps.address.abstract_models import AbstractShippingAddress
from oscar.apps.address.abstract_models import AbstractBilli | ngAddress
class ShippingAddress(AbstractShippingAddress):
| vatin = fields.vatin()
class BillingAddress(AbstractBillingAddress):
vatin = fields.vatin()
from oscar.apps.order.models import * # noqa
|
konradxyz/cloudify-manager | rest-service/manager_rest/workflow_client.py | Python | apache-2.0 | 1,585 | 0 | #########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | = workflow['operation']
task_queue = '{}_workflows'.format(deployment_id)
execution_parameters['__cloudify_context'] = {
'workflow_id': name,
'blueprint_id': blueprint_id,
| 'deployment_id': deployment_id,
'execution_id': execution_id
}
client().execute_task(task_name=task_name,
task_queue=task_queue,
task_id=execution_id,
kwargs=execution_parameters)
def workf... |
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | tests/python/proper.py | Python | gpl-3.0 | 11,408 | 0.006837 | #! /usr/bin/env python
import vcsn
from test import *
algos = ['distance', 'inplace', 'separate']
# check INPUT EXP ALGORITHM
# -------------------------
def check_algo(i, o, algo):
i = vcsn.automaton(i)
o = vcsn.automaton(o)
print("using algorithm: ", algo)
print("checking proper")
# We call sort().stri... | "]
1 -> 2 [label = "a"]
2 -> 0 [label = "a"]
2 -> 1 [label = "\\e"]
}''', '''digraph
{
vcsn_context = "wordset<char_letters(ab)>, b"
rankdir = LR
edge [arrowhead = vee, arrows | ize = .6]
{
node [shape = point, width = 0]
I0
F0
F1
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0
0 -> F0
0 -> 0 [label = "a"]
0 -> 1 [label = "a"]
0 -> 2 [label = "a"]
1 -> F1
1 -> 0 [label = "a"]
1 -> 1 [label = "a"]
1 -> 2 [l... |
rocky/python3-trepan | trepan/processor/parse/tok.py | Python | gpl-3.0 | 1,426 | 0 | class Token:
"""
Class representing a token.
kind: the kind of token, e.g. filename, number, other
value: specific instance value, e.g. "/tmp/foo.c", or 5
offset: byte offset from start of p | arse string
"""
def __init__(self, kind, value=None, offset=None):
self.offset = offset
self.kind = kind
self.value = value
def __eq__(self, o):
""" '==', but it's okay if offset is different"""
if isinstance(o, Token):
# Both are tokens: compare kind | and value
# It's okay if offsets are different
return (self.kind == o.kind)
else:
return self.kind == o
def __repr__(self):
return str(self.kind)
def __repr1__(self, indent, sib_num=''):
return self.format(line_prefix=indent, sib_num=sib_num)
d... |
rdmilligan/SaltwashAR | scripts/features/base/speaking.py | Python | gpl-3.0 | 476 | 0.006303 | # Copyright (C) 2015 Ross D Milligan
# GNU GENERAL PUBLIC LICENSE Version 3 | (full notice can be found at https://github.com/rdmilligan/SaltwashAR)
class Speaking:
# initialize speaking
def __init__(self, text_to_speech):
self.is_speaking = False
self.text_to_speech = text_to_speech
# text to speech
def _text_to_speech(self, text):
s | elf.is_speaking = True
self.text_to_speech.convert(text)
self.is_speaking = False |
Dev-Cloud-Platform/Dev-Cloud | dev_cloud/cc1/src/ec2/helpers/query.py | Python | apache-2.0 | 3,363 | 0.000595 | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except i | n 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, eit... | se.
#
# @COPYRIGHT_end
"""@package src.ec2.helpers.query
@copyright Copyright (c) 2012 Institute of Nuclear Physics PAS <http://www.ifj.edu.pl/>
@author Oleksandr Gituliar <gituliar@gmail.com>
"""
from datetime import datetime
import urllib
from ec2.base.auth import _sign_parameters_ver2
def query(parameters, aws... |
Eyepea/aiohttp | aiohttp/client.py | Python | apache-2.0 | 26,125 | 0.000153 | """HTTP Client for asyncio."""
import asyncio
import base64
import hashlib
import json
import os
import sys
import traceback
import warnings
from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
from yarl import URL
from . import connector as connector_mod
from . import client_exceptions, client_reqrep,... | out)
handle = tm.start()
| timer = tm.timer()
try:
with timer:
while True:
url = URL(url).with_fragment(None)
cookies = self._cookie_jar.filter_cookies(url)
req = self._request_class(
method, url, params=params, headers=header... |
m-weigand/ccd_tools | src/ddplot/ddplot.py | Python | gpl-3.0 | 16,512 | 0.000666 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ddplot.py can create plots from plot results created using dd_single.py and
dd_time.py
Copyright 2014,2015 Maximilian Weigand
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 ... | U General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# from memory_profiler import *
from optp | arse import OptionParser
import os
import numpy as np
from NDimInv.plot_helper import *
import NDimInv.elem as elem
# import dd_single
import NDimInv
# import lib_dd.plot as lDDp
import sip_formats.convert as SC
import matplotlib.pylab as plt
import matplotlib as mpl
def handle_cmd_options():
parser = OptionParse... |
softlayer/softlayer-python | SoftLayer/CLI/subnet/__init__.py | Python | mit | 23 | 0 | "" | "Network subnets. | """
|
SeeSpotRun/rmlint | tests/test_options/test_match_without_extension.py | Python | gpl-3.0 | 718 | 0.001393 | #!/usr/bin/env python3
# encoding: utf-8
from nose import with_setup
from tests.utils import *
@with_setup(usual_setup_f | unc, usual_teardown_func)
def test_negative():
create_file('xxx', 'b.png')
create_file('xxx', 'a.png')
create_file('xxx', 'a')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 3
assert footer['total_lint_size'] == 0
assert footer['duplicates'] == 0
@with_setup(usual_s... | ')
create_file('xxx', 'a.jpg')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 2
assert footer['total_lint_size'] == 3
assert footer['duplicates'] == 1
|
ericlee0803/surrogate-GCP | gp/GPhelpers.py | Python | bsd-3-clause | 2,253 | 0.030626 | import GPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# ~~~~WARNING: ONLY SUPPORT FOR 1D RIGHT NOW~~~~ #
# TODO
def batch():
pass
# Calculates GP from input and output vectors X and Y respectively
def calcGP(X, Y, kernel='rbf', variance=1., lengthscale=1.):
# Reshape in 1D Cas... | thscale)
m = GPy.models.GPRegression(X,Y,kernel)
return m
else:
print('Kernel is not supported, please use one that is supported or use the default RBF Kernel')
return None
# Updates GP with a set of new function evaluations Y at points X
def updateGP(model, kernel, Xnew, Ynew):
# Reshape in 1D Case
if(len(... | pend(model.Y, Ynew, 0)
m = GPy.models.GPRegression(X,Y,kernel)
return m
# Using Expected Improvement, send out a number of further evaluations
# -batchsize = number of new evals
# -fidelity = number of points used to estimate EI
# -bounds = determines how new evals points are spaced
def batchNewEvals_EI(model, bou... |
RPGOne/Skynet | scikit-learn-c604ac39ad0e5b066d964df3e8f31ba7ebda1e0e/examples/mixture/plot_gmm.py | Python | bsd-3-clause | 2,817 | 0 | """
=================================
Gaussian Mixture Model Ellipsoids
=================================
Plot the confidence ellipsoids of a mixture of two Gaussians with EM
and variational Dirichlet process.
Both models have access to five components with which to fit the
data. Note that the EM model will necessari... |
u = w[0] / linalg.norm(w[0])
# as the | DP will not use every component it has access to
# unless it needs it, we shouldn't plot the redundant
# components.
if not np.any(Y_ == i):
continue
plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color)
# Plot an ellipse to show the Gaussian component
a... |
jeremymcrae/mupit | mupit/mutation_rates.py | Python | mit | 8,652 | 0.007397 | """
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distr... | r all genes can be obtained from the supplementary material of
Samocha et al. Nature Genetics 2014 doi:10.1038/ng.3050
Args:
rates_url: url to supplementary mutation rates table
gencode_url: url to gencode, or local path. This is requ | ired to identify
chromosomes for the genes in the rates data, since we need to know
the chromosome in order to corrrect rates on chromosome X.
Returns:
dataframe of mutation rates, with an extra column for summed lof rate
"""
rates = pandas.read_excel(rates_url, she... |
Yelp/elastalert | elastalert/kibana_discover.py | Python | apache-2.0 | 5,644 | 0.003189 | # -*- coding: utf-8 -*-
# flake8: noqa
import datetime
import logging
import json
import os.path
import prison
import urllib.parse
from .util import EAException
from .util import lookup_es_key
from .util import ts_add
kibana_default_timedelta = datetime.timedelta(minutes=10)
kibana5_kibana6_versions = frozenset(['5.... | discover_app_url:
logging.warning(
'Missing kibana_discover_app_url for rule %s' % (
rule.get('name', '<MIS | SING NAME>')
)
)
return None
kibana_version = rule.get('kibana_discover_version')
if not kibana_version:
logging.warning(
'Missing kibana_discover_version for rule %s' % (
rule.get('name', '<MISSING NAME>')
)
)
return N... |
testmana2/test | Plugins/VcsPlugins/vcsPySvn/SvnStatusMonitorThread.py | Python | gpl-3.0 | 6,360 | 0.00173 | # -*- coding: utf-8 -*-
# Copyright (c) 2006 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the VCS status monitor thread class for Subversion.
"""
from __future__ import unicode_literals
import os
import pysvn
from VCS.StatusMonitorThread import VcsStatusMonitorThread
import Prefer... | elif file.text_status == pysvn.wc_status_kind.modified or \
file.prop_status == pysvn.wc_status_kind.modified:
status = "M"
elif file.text_status == pysvn.wc_status_kind.added or \
file.prop_status == pysvn.wc_status_kind.added:... | le.text_status == pysvn.wc_status_kind.replaced or \
file.prop_status == pysvn.wc_status_kind.replaced:
status = "R"
if status:
states[file.path] = status
try:
if self.reportedStates[file.path] !=... |
ubiquill/Potluck | src/view/Changes.py | Python | gpl-2.0 | 2,296 | 0.003486 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2011 Thomas Schreiber
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any l... | 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, write to the Fr | ee Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# by Thomas Schreiber <ubiquill@gmail.com>
#
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from view.changesUi import Ui_changeSummary
import string
class ChangeWin(QDialog):
"""A QDialog that lists changes befo... |
scrapinghub/dateparser | dateparser/data/date_translation_data/sw.py | Python | bsd-3-clause | 4,155 | 0 | info = {
"name": "sw",
"date_order": "DMY",
"january": [
"jan",
"januari"
],
"february": [
"feb",
"februari"
],
"march": [
"mac",
"machi"
],
"april": [
"apr",
"aprili"
],
"may": [
"mei"
],
"june":... | our ago": [
"saa hii"
],
"0 minute ago": [
"dakika hii"
],
"0 month ago": [
"mwezi huu"
],
"0 second ago": [
"sasa hivi"
],
"0 week ago": [
"wiki hii"
],
"0 year ago": [
... | week ago": [
"wiki iliyopita"
],
"1 year ago": [
"mwaka uliopita"
],
"in 1 day": [
"kesho"
],
"in 1 month": [
"mwezi ujao"
],
"in 1 week": [
"wiki ijayo"
],
"in 1 year": [
... |
jackkiej/SickRage | tests/notifier_tests.py | Python | gpl-3.0 | 10,384 | 0.003371 | # coding=UTF-8
# URL: https://github.com/SickRage/SickRage
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... | ef test_growl(self):
"""
Test growl notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_kodi(self):
"""
Test kodi notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_libnotify(self):
"""
... | """
Test nma notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_nmj(self):
"""
Test nmj notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_nmjv2(self):
"""
Test nmjv2 notifications
... |
cshallue/models | research/differential_privacy/multiple_teachers/analysis.py | Python | apache-2.0 | 10,988 | 0.012013 | # 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 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 spec... | ds on the privacy cost of training the
student model from noisy aggregation of labels predicted by teachers.
It should be used only after training the student (and therefore the
teachers as well). We however include the label files required to
reproduce key results from our paper (https://arxiv.org/abs/1610.05755):
the... |
k3idii/pykpyk | datatools.py | Python | mit | 955 | 0.034555 | import itertools
import struct
def ip4_to_int32(str_ip, order='>'):
return struct.unpack(order+"I",struct.pack("BBBB",*map(int,str_ip.split("."))))[0]
def int32_to_ip4(big_int, order='>'):
return '.'.join(map(str, struct.unpack("BBBB",struct.pack(order+"I",big_int))))
def gen_get_n_bit(data, bit=1):
mask = 1 <... | urn list(gen_get_n_bit(data, bit))
def byte_to_bin_str(byte):
return "{0:0>b}".format(byte)
def byte_to_bin_arr(byte):
return [int(x) for x in byte_to_bin_str(byte)]
def gen_chunks(data, size):
for i in range(1+len(data)/size):
yield data[i*size:(i+1)*size]
def chunks(data, size):
return list(gen_chunks... |
def gen_pairs(col,):
return itertools.combinations(col,2);
|
swtp1v07/Savu | savu/data/structures.py | Python | apache-2.0 | 17,375 | 0 | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | if self.backing_file is None:
raise IOError("Failed to open the hdf5 file")
logging.debug("Creating file '%s' '%s'", self.base_path,
self.backing_file.filename)
self.base_path = group_name
if not isinstance(data, RawTimeseriesData):
raise Value... | Data")
self.core_directions[CD_PROJECTION] = (1, 2)
self.core_directions[CD_SINOGRAM] = (0, 2)
self.core_directions[CD_ROTATION_AXIS] = 0
data_shape = new_shape
if data_shape is None:
data_shape = data.data.shape
data_type = np.double
image_key_shape... |
adrn/gala | gala/integrate/setup_package.py | Python | mit | 1,672 | 0 | from distutils.core import Extension
from collections import defaultdict
def get_extensions():
import numpy as np
exts = []
# malloc
mac_incl_path = "/usr/include/malloc"
cfg = defaultdict(list)
cfg['include_dirs'].append(np.get_include())
cfg['include_dirs'].append(mac_incl_path)
c... | ['extra_compile_args'].append('--std=gnu99')
cfg['sources'].append('gala/integrate/cyintegrators/ruth4.pyx')
cfg['sources'].append('gala/potential/potential/src/cpotential.c')
exts.append(Extension('gala.integrate.cyintegrators.ruth4', | **cfg))
return exts
|
google/fuzzbench | analysis/coverage_data_utils.py | Python | apache-2.0 | 9,404 | 0.000638 | # 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 agreed to in writing, ... | """Returns the key representing |fuzzer| and |benchmark|."""
return fuzzer + ' ' + benchmark
def key_to_fuzzer_and_benchmark(key: str) -> Tuple[str, str]:
"""Returns a tuple containing the fuzzer and the benchmark represented by
|key|."""
return tuple(key.split(' '))
def get_experiment_filestore_p... | path for |fuzzer| and |benchmark| in
|df|. Returns an arbitrary filestore path if there are multiple."""
df = df[df['fuzzer'] == fuzzer]
df = df[df['benchmark'] == benchmark]
experiment_filestore_paths = get_experiment_filestore_paths(df)
fuzzer_benchmark_filestore_path = experiment_filestore_paths[... |
brodie/cram | cram/_test.py | Python | gpl-2.0 | 7,518 | 0.000532 | """Utilities for running individual tests"""
import itertools
import os
import re
import time
from cram._diff import esc, glob, regex, unified_diff
from cram._process import PIPE, STDOUT, execute
__all__ = ['test', 'testfile']
_needescape = re.compile(br'[\x00-\x09\x0b-\x1f\x7f-\xff]').search
_escapesub = re.compil... | diffpath + b'.err'
else:
diffpath = errpath = b''
diff = unified_diff(refout, postout, diffpath, errpath,
matchers=[esc, glob, regex])
for firstline in diff:
return refout, postout, itertools.chain | ([firstline], diff)
return refout, postout, []
def testfile(path, shell='/bin/sh', indent=2, env=None, cleanenv=True,
debug=False, testname=None):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same lis... |
Serpens/small_bioinfo | blast_fasta.py | Python | gpl-3.0 | 1,496 | 0.007353 | #!/usr/bin/env python
import os, sys
from Bio import SeqIO
from Bio.Blast import NCBIWWW
from time import sleep
from helpers import parse_fasta, get_opts
def usage():
print """Usage: blast_fasta.py [OPTIONS] seqs.fasta
Options:
-t blast_type blastn, blastp, blastx, tblastn, tblastx, default: blastn... | sleep(delay)
return result
except urllib2.HTTPError: # something went wrong, increase delay and try again
delay *= 2
if __name__=='__main__':
t | ry:
opts = get_opts(sys.argv[1:], 't:o:p:')
fasta_path = opts[1][0]
opts = dict(opts[0])
except:
usage()
exit(1)
blast_type = opts.get('-t', 'blastn')
out_dir = opts.get('-o', os.getcwd())
out_prefix = opts.get('-p', 'blast_')
seqs = parse_fasta(fasta_path)
... |
GreenVars/diary | tests/logdb_test.py | Python | mit | 2,455 | 0.002037 | from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_ | dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb = DiaryDB(self.TEMP_DB_PATH)
| self.logdb_default = DiaryDB()
@classmethod
def tearDownClass(cls):
import os
os.remove(cls.TEMP_DB_PATH)
def constructs_correctly(self):
self.assertIsInstance(self.logdb.conn, sqlite3.Connection)
self.assertIsInstance(self.logdb.cursor, sqlite3.Cursor)
def test_c... |
jlafon/django-rest-framework-oauth | tests/test_oauth.py | Python | mit | 19,202 | 0.003854 | import time
import datetime
import oauth2 as oauth
from provider import scope as oauth2_provider_scope
from rest_framework.test import APIClient
from rest_framework_oauth.authentication import (
oauth2_provider,
OAuthAuthentication,
OAuth2Authentication
)
from rest_framework import status, permissions
from ... | token_type=OAuthToken.ACCESS, key=self.TOKEN_KEY, secret=self.TOKEN_SECRET,
is_approved=True
)
def _create_authorization_header(self):
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time... | ", parameters=params)
signature_method = oauth.SignatureMethod_PLAINTEXT()
req.sign_request(signature_method, self.consumer, self.token)
return req.to_header()["Authorization"]
def _create_authorization_url_parameters(self):
params = {
'oauth_version': "1.0",
... |
daneoshiga/gpodder | src/gpodder/gtkui/interface/__init__.py | Python | gpl-3.0 | 764 | 0.001309 | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2015 Thomas Perl and the gPodder Team
#
# gPodder 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... | ion.
#
# gPodder 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 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/>.
#
|
blasterbug/doc2md.py | doc2md.py | Python | gpl-2.0 | 7,823 | 0.005497 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
doc2md.py generates Python documentation in the Markdown (md) format. It was
written to automatically generate documentation that can be put on Github
or Bitbucket wiki pages. It is initially based on Ferry Boender's pydocmd.
It is as of yet not very complete and is more... |
functions = inspect.getmembers(mod_inst, inspect.i | sfunction)
if functions:
for func_name, func_inst in functions:
if func_inst.__module__ == mod_name :
info['functions'].append(insp_method(func_name, func_inst))
# Get module classes
classes = inspect.getmembers(mod_inst, inspect.isclass)
if classes:
for clas... |
talapus/Ophidian | Academia/Modules/list_all_installed_modules.py | Python | bsd-3-clause | 147 | 0 | #!/usr/bin/env python
import sys
import textwrap
names = | sorted(sys.modules.keys())
name_text = ', '.join(name | s)
print textwrap.fill(name_text)
|
manene/SAE_Sampling | spark/genGraph.py | Python | mit | 715 | 0 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Created Time: Fri Jul 17 00:58:20 2015
# Purpose: generate a bidirected graph
# Mail: hewr2010@gmail.com
__author__ = "Wayne Ho"
import sys
import random
if __name__ == "__main__":
if len(sys.argv) < 3:
print("./%s [#vertices] [#edges]" % sys.argv[0])
exi... | int(sys.argv[1]), int(sys.argv[2])
print n, m
pool = {}
for i in xrange(m):
while True:
x, y = int(n * random.random()), int(n * random.rand | om())
if x > y:
x, y = y, x
if x == y:
continue
if (x, y) not in pool:
break
pool[(x, y)] = True
print x, y
|
mwbetrg/skripbatak | createlp2016table.py | Python | bsd-3-clause | 2,171 | 0.004606 | import site
import sys, os
from peewee import *
import datetime
import time
import calendar
import sqlite3
import gzip
import shutil
#-----------------------------------------------------------------------
if os.path.exists('/storage/extSdCard'):
database = SqliteDatabase('/storage/extSdCard/mydb/lessonplan20... | _table = 'lessonplanbank'
|
class Lessonplan2016(BaseModel):
activity1 = CharField(null=True)
activity2 = CharField(null=True)
assimilation = CharField(null=True)
content = CharField(null=True)
date = IntegerField(null=True)
duration = CharField(null=True)
exercise = TextField(null=True)
handout = TextField(null=T... |
Pistachitos/Sick-Beard | sickbeard/notifiers/growl.py | Python | gpl-3.0 | 6,111 | 0.014237 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | me'])
notice.add_header('Notification-Title',options['title'])
if options['password']:
notice.set_password(options['password'])
#Optional
if options['sticky']:
notice.add_header('Notification-Sticky',options['sticky'])
if options['priority']:
... | ification-Icon', 'https://raw.github.com/midgetspy/Sick-Beard/master/data/images/sickbeard.png')
if message:
notice.add_header('Notification-Text',message)
response = self._send(options['host'],options['port'],notice.encode(),options['debug'])
if isinstance(response,gntp.GNTPOK... |
candlepin/virt-who | virtwho/virt/kubevirt/client.py | Python | gpl-2.0 | 4,273 | 0.000468 | #
# Copyright 2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | mport Timeout
from virtwho.virt.kubevirt import config
_TIMEOUT = 60
class KubeClient:
def __init__(self, path, version, insecure):
cfg = config.Configuration()
cl = config._get_kube_config_loader_for_yaml_file(path)
cl.load_and_set(cfg)
if insecure:
self._pool_mana... | assert_hostname=False
)
else:
cert_reqs = ssl.CERT_REQUIRED
ca_certs = cfg.ssl_ca_cert
cert_file = cfg.cert_file
key_file = cfg.key_file
self._pool_manager = urllib3.PoolManager(
num_pools=4,
maxsize=4... |
weaver-viii/h2o-3 | h2o-py/tests/testdir_algos/glm/pyunit_covtype_get_future_model.py | Python | apache-2.0 | 1,261 | 0.014274 | import sys
sys.path.insert(1, "../../../")
import h2o
import random
def test_get_future_model(ip,port):
covtype=h2o.upload_file(h2o.locate("smalldata/covtype/covtype.altered.gz"))
myY=54
myX=list(set(range(54)) - set([20,28])) # Cols 21 and 29 are constant, so must be explicitly ignored
... | # L1: alpha=1, lambda=1e-4
covtype_h2o3 = h2o.start_glm_job(y=covtype[myY], x=covtype[myX], family=" | binomial", alpha=[1], Lambda=[1e-4])
covtype_h2o1 = h2o.get_future_model(covtype_h2o1)
print(covtype_h2o1)
covtype_h2o2 = h2o.get_future_model(covtype_h2o2)
print(covtype_h2o2)
covtype_h2o3 = h2o.get_future_model(covtype_h2o3)
print(covtype_h2o3)
if __name__ == "__main__":
h2o.run_test(sys... |
FeiZhan/Algo-Collection | answers/hackerrank/Check Subset.py | Python | mit | 423 | 0.016627 | #@result Submitted a few seconds ago • Score: 10.00 Status: Accepted Test Case #0: 0s Test Case #1: 0.01s Test Case #2: 0s Test Case #3: 0s Test Case #4: 0.01s Test Case #5: 0s
for i in range(int(raw_input())): #More than 4 lines will result in | 0 scor | e. Blank lines won't be counted.
a = int(raw_input()); A = set(raw_input().split())
b = int(raw_input()); B = set(raw_input().split())
print B == B.union(A)
|
cynapse/cynin | src/ubify.cyninv2theme/ubify/cyninv2theme/browser/addcontentselector.py | Python | gpl-3.0 | 3,531 | 0.016709 | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distrib... | program. If not, see <http://www.gnu.org/licenses/>.
#
#You can contact Cynapse at support@cynapse.com with any problems with cyn.in.
#For any queries regarding the licensing, please send your mails to
# legal@cynapse.com
#
#You can also contact Cynapse at:
#802, Building No. 1,
#Dheeraj Sagar, Malad(W)
#M... | ################################
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ubify.policy.config import spacesdefaultaddablenonfolderishtypes
from zope.component import getUtility
from zope.app.publisher.interfaces.browser import IBrowserMenu
... |
asedunov/intellij-community | python/helpers/pydev/_pydevd_bundle/pydevd_utils.py | Python | apache-2.0 | 7,871 | 0.004447 | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):... | )
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among | the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(n... |
icyflame/batman | pywikibot/userinterfaces/gui.py | Python | mit | 21,774 | 0.000413 | # -*- coding: utf-8 -*-
"""
A window with a unicode textfield where the user can edit.
Useful for editing the contents of an article.
"""
from __future__ import absolute_import, unicode_literals
#
# (C) Rob W.W. Hooft, 2003
# (C) Daniel Herding, 2004
# Wikiwichtel
# (C) Pywikibot team, 2008-2014
#
# Distributed ... | e = idleConf.CurrentTheme()
textcf = dict(padx=5, wrap='word', undo='True',
foreground=idleConf.GetHighlight(currentTheme,
'normal', fgBg='fg'),
| background=idleConf.GetHighlight(currentTheme,
'normal', fgBg='bg'),
highlightcolor=idleConf.GetHighlight(currentTheme,
'hilite', fgBg='fg'),
hig... |
Robpol86/Flask-Statics-Helper | flask_statics/helpers.py | Python | mit | 1,406 | 0.004979 | """Helper functions for Flask-Statics."""
from flask_statics | import resource_base
from flask_statics import resource_definitions
| def priority(var):
"""Prioritizes resource position in the final HTML. To be fed into sorted(key=).
Javascript consoles throw errors if Bootstrap's js file is mentioned before jQuery. Using this function such errors
can be avoided. Used internally.
Positional arguments:
var -- value sent by list.s... |
tswicegood/seeder | seeder/tests.py | Python | gpl-3.0 | 11,995 | 0.009587 | from django.test import TestCase as DjangoTestCase
from django.conf import settings
from seeder.models import *
from seeder.posters import TwitterPoster
from random import randint as random
from datetime import datetime
import time
import mox
import re
def generate_random_authorized_account():
u = User(username = ... | r(random(10000, 99999)))
u.save()
return AuthorizedAccount.objects.create(user = u)
def generate_random_seeder(account = None):
if account is None:
account = generate_random_authorized_account()
return Seeder.objects.create(
twitter_id = random(1000, 9999),
authorized_for = acco... | ne):
if seeder is None:
seeder = generate_random_seeder()
return Token.objects.create(
seeder = seeder,
oauth_token = "some token" + str(random(10, 100)),
oauth_token_secret = "some token secret" + str(random(10, 100))
)
def generate_random_update(account = None):
if acc... |
rvanlaar/easy-transifex | src/transifex/transifex/teams/tests/models.py | Python | bsd-2-clause | 1,066 | 0.005629 | fr | om transifex.projects.models import Project
from transi | fex.teams.models import Team
from transifex.txcommon.tests import base
class TestTeamModels(base.BaseTestCase):
def test_available_teams(self):
"""
Test whether monkey-patch of Project class with a 'available_teams'
instance method returns the desired result.
"""
# There mu... |
tomaszkax86/Colobot-Model-Converter | colobotformat.py | Python | bsd-2-clause | 11,044 | 0.006249 | #-*- coding: utf-8 -*-
# Implements Colobot model formats
# Copyright (c) 2014 Tomasz Kapuściński
import modelformat
import geometry
import struct
class ColobotNewTextFormat(modelformat.ModelFormat):
def __init__(self):
self.description = 'Colobot New Text format'
def get_extension(self):
... | mat = triangle.material
for i in range(4):
mat.diffuse[i] = floats[0 + i]
mat.ambient[i] = floats[4 + i]
mat.specular[i] = floats[8 + i]
# texture name
chars = input_file.read(20)
for i in range(20):
... | mat.texture = struct.unpack('={}s'.format(i), chars[:i])[0]
break
values = struct.unpack('=ffiHHHH', input_file.read(20))
mat.state = values[2]
dirt = values[3]
if dirt != 0:
mat.texture2 = 'dirty{:02d}.png'.format(dirt)
... |
gjlawran/ckanext-bcgov | ckanext/bcgov/scripts/save_orgs.py | Python | agpl-3.0 | 1,656 | 0.010266 | # Copyright 2015, Province of British Columbia
# License: https://github.com/bcgov/ckanext-bcgov/blob/master/license
import json
import urllib2
import urllib
import pprint
from base import (site_url, api_key)
org_filename = './data/orgs_list.json'
data_string = json.dumps({'all_fields' : True})
org_list = [... | .pprint(user_list)
except Exception, e:
pass
org_dict = {'id' : org['id'], 'members' : members}
orgs_dict[org['name']] = org_dict
with open(or | g_filename, 'w') as org_file :
org_file.write(json.dumps(orgs_dict))
|
peckhams/topoflow | topoflow/gui/Input_Dialog.py | Python | mit | 21,814 | 0.011094 |
# Add ability to pass TF_Input_Dialog a data structure
# instead of an XML filename. XML file is only for
# initial creation, but for updates or showing user-
# modified settings, need this other option.
#---------------------------------------------------------
#!/usr/bin/env python
# August 8 & 11, 2008
# Febru... | ame
self.parent = parent
self.title = title
self.vgap = 10
self.hgap = 6
#-------------------------------------------------
# Later move these into Variable_Box() or remove
#----------------- | --------------------------------
self.type_code = {'Scalar':0, 'Time series':1, \
'Grid':2, 'Grid sequence':3}
self.type_name = {0:'Scalar', 1:'Time series', \
2:'Grid', 3:'Grid sequence'}
#-----------------------------------------
... |
ctu-osgeorel-proj/bp-pesek-2016 | src/position_correction.py | Python | gpl-2.0 | 7,629 | 0.003016 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
SuroLeveling
A QGIS plugin
todo
-------------------
begin : 2016-02-12
git sha : $Format:%H$
copyr... | dow())
#--------------------------------------------------------------------------
#def onClosePlugin(self): CAUSE OF ENABLE SECOND OPENING
# """Cleanup necessary items here when plugin dockwidget is closed"""
# pr | int "** CLOSING SuroLeveling"
# disconnects
# self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docke... |
HanWenfang/syncless | test/wsgi_test.py | Python | apache-2.0 | 9,998 | 0.005501 | #! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Sat Apr 24 00:25:31 CEST 2010
import errno
import logging
import socket
import sys
import unittest
from syncless import coio
from syncless import wsgi
def TestApplication(env, start_response):
if env['PATH_INFO'] == '/answer':
start_response('200 OK', [('Co... | max_nonblocking_pipe_write_size, 33333)
request = 'GET / HTTP/1.0\r\n'
request += 'Xy: Z\r\n' * ((max_size - len(request)) / 7)
assert len(request) <= max_size
b.sendall(request)
b.shutdown(1)
CallWsgiWorker(a)
try:
response = b.recv(8192)
except IOError, e:
if e.errno != err... | stems raise ECONNRESET if the peer is very fast
# to close the connection. The exact reasons why we get ECONNRESET
# instead of just an EOF sometimes is unclear to me.
response = ''
self.assertEqual('', response)
def testSinglePolicyFileRequest(self):
a, b = coio.socketpair(socket.AF_UNIX,... |
Locu/djredis | djredis/__init__.py | Python | mit | 38 | 0 | # | coding: utf-8
__version__ = '0.1.0'
| |
doyubkim/fluid-engine-dev | src/tests/python_tests/test_cell_centered_scalar_grid.py | Python | mit | 12,197 | 0 | """
Copyright (c) 2018 Doyub Kim
I am making my contributions/submissions to this project solely in my personal
capacity and am not conveying any rights to any intellectual property of any
third parties.
"""
import numpy as np
import pyjet
from pytest import approx
from pytest_utils import *
cnt = 0
def test_grid... | placianAtDataPoint(i, j) == a.laplacian(pt)
def func(i, j):
global cnt
assert i >= 0 and i < a.resolution.x
assert j >= 0 and j < a.resolution.y
cnt += 1
cnt = 0
a.forEachDataPointIndex(func)
assert cnt == a.resolution.x * a.resolution.y
blob = a.serialize()
b =... | 12, 7)
assert_vector_similar(b.origin, (9, 2))
assert_vector_similar(b.gridSpacing, (3, 4))
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == b[i, j]
def test_cell_centered_scalar_grid2():
# CTOR
a = pyjet.CellCenteredScalarGrid2()
assert a.r... |
jeremiahyan/odoo | addons/l10n_be_edi/tests/test_ubl.py | Python | gpl-3.0 | 8,636 | 0.002432 | # -*- coding: utf-8 -*-
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon
from odoo.tests import tagged
from odoo import Command
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestL10nBeEdi(AccountEdiTestCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n... | </Party>
</AccountingCustomerParty>
<PaymentMeans>
<PaymentMeansCode listID="UN/ECE 4461">31</PaymentMeansCode>
<PaymentDueDate>2017-01-01</PaymentDueDate>
<InstructionID>INV/2017/00001</InstructionID>
</Payment... | currencyID="Gol">220.000</TaxAmount>
</TaxTotal>
<LegalMonetaryTotal>
<LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount>
<TaxExclusiveAmount currencyID="Gol">1100.000</TaxExclusiveAmount>
<TaxInclusiveAmount c... |
Cisco-Talos/pyrebox | volatility/volatility/plugins/overlays/windows/vista_sp12_x64_syscalls.py | Python | gpl-2.0 | 43,395 | 0.053693 | # Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your o... | 25
'NtAccessCheckAndAuditAlarm', # 0x26
'NtUnmapViewOfSection', # 0x27
'NtReplyWaitReceivePortEx', # 0x28
'NtTerminateProcess', # 0x29
'NtSetEventBoostPriority', # 0x2a
'NtReadFileScatter', # 0x2b
'NtOpenThread | TokenEx', # 0x2c
'NtOpenProcessTokenEx', # 0x2d
'NtQueryPerformanceCounter', # 0x2e
'NtEnumerateKey', # 0x2f
'NtOpenFile', # 0x30
'NtDelayExecution', # 0x31
'NtQueryDirectoryFile', # 0x32
'NtQuerySystemInformation', # 0x33
'NtOpenSection', # 0x34
'NtQueryTimer', # 0x35
'NtFsContr... |
TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/xdis/opcodes/opcode_30.py | Python | mit | 1,967 | 0.004067 | # (C) Copyright 2017, 2019-2020 by Rocky Bernstein
"""
CPython 3.0 bytecode opcodes
This is a like Python 3.0's opcode.py with some classification
of stack usage.
"""
from xdis.opcodes.base import (
def_op,
extended_format_ATTR,
extended_format_CALL_FUNCTION,
finalize_opcodes,
format_MAKE_FUNCTION... | OP NAME OPCODE POP PUSH
#--------------------------------------------
def_op(l, 'SET_ADD', 17, 2, 0) # Calls set.add(TOS1[-i], TOS).
| # Used to implement set comprehensions.
def_op(l, 'LIST_APPEND', 18, 2, 0) # Calls list.append(TOS1, TOS).
# Used to implement list comprehensions.
jrel_op(l, 'JUMP_IF_FALSE', 111, 1, 1)
jrel_op(l, 'JUMP_IF_TRUE', 112, 1, 1)
# Yes, pj2 not pj3 - Py... |
WimpyAnalytics/django-readonly-schema | readonly/readonly/settings/local.py | Python | mit | 1,156 | 0.00519 | """ Local dev settings and globals. """
from base import *
""" DEBUG CONFIGURATION """
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
""" LOGGING """
for logger_key in LOGGING['loggers'].ke... | as soon as possible in the order
MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware',) + MIDDLEWARE_CLASSES
# See: https://github.com/django-debug-toolbar/django | -debug-toolbar#installation
DEBUG_TOOLBAR_PATCH_SETTINGS = False
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TEMPLATE_CONTEXT': True,
} |
aacebedo/build-utilities | setup.py | Python | lgpl-3.0 | 2,674 | 0.008975 | #!/usr/bin/env python3
#
# build-utilities
# Copyright (c) 2015, Alexandre ACEBEDO, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the Lice... | ail="Alexandre ACEBEDO",
description="Build utilities for pyt | hon and go projects.",
license="LGPLv3",
keywords="build go python",
url="http://github.com/aacebedo/build-utilities",
entry_points={'console_scripts':
['build-utilities = buildutilities.__main__:BuildUtilities.main']}
)
if __name__ == "__main__":
pro... |
ZeitOnline/zeit.content.cp | src/zeit/content/cp/blocks/teaser.py | Python | bsd-3-clause | 7,905 | 0 | from zeit.cms.i18n import MessageFactory as _
import copy
import grokcore.component as grok
import lxml.objectify
import zeit.cms.content.property
import zeit.cms.interfaces
import zeit.cms.syndication.feed
import zeit.cms.syndication.interfaces
import zeit.content.cp.blocks.block
import zeit.content.cp.interfaces
impo... | rst)) > 0:
previously_first.layout = area.default_teaser_layout
@grok.adapter(zeit.content.cp.interfaces.ITeaserBlock)
@grok.implementer(zeit.content.cp.interfaces.IRenderedXML)
d | ef rendered_xml_teaserblock(context):
container = getattr(
lxml.objectify.E, context.xml.tag)(**context.xml.attrib)
# Render non-content items like topiclinks.
for child in context.xml.getchildren():
# BBB: xinclude is not generated anymore, but some might still exist.
if child.tag ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.