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
ufieeehw/IEEE2015
ros/dynamixel_motor/dynamixel_driver/scripts/set_servo_config.py
Python
gpl-2.0
7,282
0.006866
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Software License Agreement (BSD License) # # Copyright (c) 2010-2011, Antons Rebguns. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Red...
NGLE', dest='cw_
angle_limit', help='set servo motor CW angle limit') parser.add_option('--ccw-angle-limit', type='int', metavar='CCW_ANGLE', dest='ccw_angle_limit', help='set servo motor CCW angle limit') parser.add_option('--min-voltage-limit', type='int', metavar='MIN_VOLTAGE', des...
ToontownUprising/src
otp/distributed/DistributedTestObject.py
Python
mit
717
0.001395
from direct.distributed import DistributedObject class Distribu
tedTestObject(DistributedObject.DistributedObject): def setRequiredField(self, r): self.requiredField = r def setB(self, B): self.B = B def setBA(self, BA): self.BA = BA def setBO(self, BO): self.BO = BO def setBR(self, BR): self.BR = BR def setBRA(s...
): for field in ('B', 'BA', 'BO', 'BR', 'BRA', 'BRO', 'BROA'): if hasattr(self, field): return True return False
consideratecode/csrf_example
manage.py
Python
mit
810
0
#!/usr/bin/env python import os import sys if __nam
e__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csrf_example.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missin...
try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" )...
GDGLima/contentbox
third_party/filetransfers/backends/url.py
Python
apache-2.0
405
0.004938
from django.http import HttpResponseRedirect from django.utils.encoding
import smart_str def serve_file(request, file, **kwargs): """Serves files by redirecting to file.url (e.g., useful for Amazon S3)""" return HttpResponseRedirect(smart_str(file.url)) def public_download_url(file, **kwargs): """Directs downloads to file.url (useful for
normal file system storage)""" return file.url
GabrielBrascher/cloudstack
plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmNetworkModule.py
Python
apache-2.0
15,306
0.008363
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
@param pattern: search pattern @param result: Parser line execution result @return : list of search find result of Parser which has same pattern findall Parser find all pattern in a string """ result = [] for line in samples: items = re.findall(pat...
for item in items: result.append(item) return result def checkPattern(self, pattern, cmd_result): """ @param pattern: search pattern @param cmd_result: Parser line execution result @return : True (if pattern is occurred) """ for line in c...
MithileshCParab/HackerRank-10DaysOfStatistics
Problem Solving/Algorithms/Implementation/migratory_birds.py
Python
apache-2.0
925
0.007568
#!/bin/python3 import math import os import random import re import sys # Complete the migratoryBirds function below. # {1:2, 2:4, 3:3, 4:4} def migratoryBirds(arr): frequentBird, frequency = 1, 0 birdsDict = {} for i in arr: if i not in birdsDict.keys(): birdsDict[i] = 1 else...
frequency: frequency = birdsDict[bird] frequentBir
d = bird if birdsDict[bird] == frequency: if bird < frequentBird: frequentBird = bird return frequentBird if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr_count = int(input().strip()) arr = list(map(int, input().rstrip().split()))...
bohlian/frappe
frappe/commands/__init__.py
Python
mit
1,535
0.024756
# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, absolute_import, print_function import sys import click impor
t cProfile import
pstats import frappe import frappe.utils from functools import wraps from six import StringIO click.disable_unicode_literals_warning = True def pass_context(f): @wraps(f) def _func(ctx, *args, **kwargs): profile = ctx.obj['profile'] if profile: pr = cProfile.Profile() pr.enable() ret = f(frappe._dict(c...
tchitchikov/goulash
python/pullData/src/pull.py
Python
apache-2.0
2,524
0.004358
import csv import numpy import pandas import pymongo import requests from datetime import datetime from io import StringIO mongo_client = pymongo.MongoClient("localhost", 27017) financial_db = mongo_client.financial_data
financial_collection = financial_db.data class Pull: def __call__(self, source, tickers, start_date, end_date): if source=='Google': results = self.google_call(tickers, start_date, end_date) return results elif source=='Database': results = self.database_call(t...
_call(self, tickers, start_date, end_date): """ google_call makes a call to the google finance api for historical data Args: None (uses the class variables) Returns: None (sets self.results) """ results = {} for ticker in tickers: ...
mldbai/mldb
testing/MLDB-2126-export-structured.py
Python
apache-2.0
1,480
0.001351
# # MLDB-2126-export-structured.py # Mathieu Marquis Bolduc, 2017-01-25 # This file is part of MLDB. Copyright 20
17 mldb.ai inc. All rights reserved. # import tempfile import codecs import os from mldb import mldb, MldbUnitTest, ResponseException t
mp_dir = os.getenv('TMP') class MLDB2126exportstructuredTest(MldbUnitTest): # noqa def assert_file_content(self, filename, lines_expect): f = codecs.open(filename, 'rb', 'utf8') for index, expect in enumerate(lines_expect): line = f.readline()[:-1] self.assertEqual(line, e...
astrobin/astrobin
astrobin_apps_platesolving/migrations/0012_platesolvingadvancedtask.py
Python
agpl-3.0
824
0.002427
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-03-17 20:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('astrobin_apps_platesolving', '0011_update_platesolvingadvanced_settings_sample_raw_frame_file_verbose_name'), ] operations...
ds=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('serial_number', models.CharField(max_lengt
h=32)), ('created', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=True)), ('task_params', models.TextField()), ], ), ]
polyaxon/polyaxon-api
polyaxon_lib/__init__.py
Python
mit
572
0.001748
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function f
rom .modes import Modes from . import models from . import bridges from . import layers from . import processing from .libs import * # noqa from . import activations from . import initializations from . import losses from . import metrics from . import optimizers from . import regularizations from .rl import explorat...
as envs, memories, stats, utils as rl_utils from . import variables from . import datasets from . import estimators from . import experiments
danlrobertson/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/manifestupdate.py
Python
mpl-2.0
25,973
0.001617
import itertools import os import urlparse from collections import namedtuple, defaultdict from wptmanifest.node import (DataNode, ConditionalNode, BinaryExpressionNode, BinaryOperatorNode, VariableNode, StringNode, NumberNode, UnaryExpressionNode, UnaryOpera...
is None, a new AST is created to associate with this manifest. :param test_path: Path of the test file associated with this manifest.
:param url_base: Base url for serving the tests in this manifest. :param property_order: List of properties to use in expectation metadata from most to least significant. :param boolean_properties: Set of properties in property_order that should ...
jgmanzanas/CMNT_004_15
project-addons/vt_flask_middleware/config.py
Python
agpl-3.0
705
0.004255
import os class Config(object): DE
BUG = False TESTING = False SECRET_KEY = 'A0Zr18h/3yX R~XHH!jmN]LWX/,?RT' DATABASE = { 'engine': 'playhouse.pool.PooledPostgresqlExtDatabase', 'name': 'middleware
', 'user': 'comunitea', 'port': '5434', 'host': 'localhost', 'max_connections': None, 'autocommit': True, 'autorollback': True, 'stale_timeout': 600} NOTIFY_URL = "https://www.visiotechsecurity.com/?...
ismail-s/warehouse
tests/unit/packaging/test_services.py
Python
apache-2.0
9,105
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may o
btain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr
eed 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 io import os.path import boto3.sessio...
jobiols/management-system
mgmtsystem_hazard_risk/__openerp__.py
Python
agpl-3.0
1,727
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this pr...
not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Hazard Risk", "version": "8.0.1.1.0", "author": "Savoir-faire Linux, Odoo Community Association (OCA)", "website": "http://www.savoirfairelinux.com", "license": "AGPL-...
mzdaniel/oh-mainline
vendor/packages/celery/celery/events/dumper.py
Python
agpl-3.0
2,533
0.001974
# -*- coding: utf-8 -*- """ celery.events.dumper ~~~~~~~~~~~~~~~~~~~~ THis is a simple program that dumps events to the console as they happen. Think of it like a `tcpdump` for Celery events. :copyright: (c) 2009 - 2011 by Ask Solem. :license: BSD, see LICENSE for more details. """ from __fu...
humanize_type(type), sep, task, fields)) def evdump(app=None): sys.stderr.write("-> evdump: starting capture...\n") app = app_or_default(app) dumper = Dumper() conn = app.broker_connection() recv = app.events.Receiver(conn, handlers={"*": dumper.on_event}) try: re...
conn and conn.close() if __name__ == "__main__": evdump()
partofthething/home-assistant
homeassistant/components/ovo_energy/config_flow.py
Python
apache-2.0
3,440
0.000291
"""Config flow to configure the OVO Energy integration.""" import aiohttp from ovoenergy.ovoenergy import OVOEnergy import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigFlow from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from .const import DOMA...
self.username, user_input[CONF_PASSWORD] ) except aiohttp.ClientError: errors["base"] = "connection_error" else: if authenticated: await self.async_set_unique_id(self.username) for entry in self._async_cu...
c_update_entry( entry, data={ CONF_USERNAME: self.username, CONF_PASSWORD: user_input[CONF_PASSWORD], }, ) ...
V11/volcano
server/sqlmap/plugins/dbms/sybase/connector.py
Python
mit
2,499
0.002401
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.da...
g: raise SqlmapConnectionException(msg) return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() try: self.connector.commit() except pymssql.Opera
tionalError: pass return retVal
boundlessgeo/geogig-py
src/geogigpy/diff.py
Python
bsd-3-clause
2,681
0.001119
# -*- coding: utf-8 -*- """ *************************************************************************** diff.py --------------------- Date : November 2013 Copyright : (C) 2013-2016 Boundless, http://boundlessgeo.com ************************************************************...
elif self.newref == NULL_ID: return TYPE_REMOVED else: return TYPE_MODIFIED def __str__(self): if self.o
ldref == NULL_ID: return "%s %s (%s)" % (TYPE_ADDED, self.path, self.newref) elif self.newref == NULL_ID: return TYPE_REMOVED + " " + self.path else: return "%s %s (%s --> %s)" % (TYPE_MODIFIED, self.path, self.oldref, self.newref)
ties/py-sonic
libsonic/connection.py
Python
gpl-3.0
100,484
0.001513
""" This file is part of py-sonic. py-sonic 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. py-sonic is distributed in the hope that it wil...
able. This is useful if you are connecting to an older version of Subsonic. insecure:bool This will allow you to use self signed certificates when connecting if set to True. useNetrc:str|bool You can either speci...
netrc file ($HOME/.netrc). """ self._baseUrl = baseUrl self._hostname = baseUrl.split('://')[1].strip() self._username = username self._rawPass = password self._netrc = None if useNetrc is not None: self._process_netrc(useNetrc) ...
MCRSoftwares/AcadSocial
universidades/migrations/0002_auto_20150118_1319.py
Python
gpl-2.0
640
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('universidades', '0001_initial'), ] operations = [ migrations.AlterField( model_name='universidademodel',
name='nome', field=models.CharField(max_length=256), preserve_default=True, ), migrations.AlterField( model_name='uni
versidademodel', name='sigla', field=models.CharField(max_length=32), preserve_default=True, ), ]
spacedogXYZ/sms_checkin
sms_checkin/settings/development.py
Python
agpl-3.0
883
0.001133
from .common import * INTERNAL_IPS = ['127.0.0.1', ] CORS_ORIGIN_WHITELIST = ( 'localhost:8000', ) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } Q_CLUSTER = { 'name': 'DjangORM', 'workers': 2, 'timeout': 90, 'retry': 120, 'queue_limit': 5...
ch_up': False # do not replay missed schedules past } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'reminders': { 'handlers': ['console'], 'le...
.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'messages': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, }
lrq3000/pyFileFixity
pyFileFixity/lib/gooey/gui/windows/views.py
Python
mit
111
0.036036
CONFIG_SCR
EEN = 'config' RUNNING_SCREEN = 'running' SUCCESS_SCREEN = 'success' ERROR_SCREEN = 'error
'
tosmun/AdventOfCode
solutions/day21/p2/main.py
Python
apache-2.0
1,368
0.067982
from itertools import combinations START_P_HP = 100 START_P_DMG = 0 START_P_A = 0 START_B_HP = 100 START_B_DMG = 8 START_B_A = 2 WEAPONS = [ [8,4,0], [10,5,0], [25,6,0], [40,7,0], [74,8,0] ] ARMOR = [ [13,0,1], [31,0,2], [53,0,3], [75,0,4], [102,0,5] ] #Include 'no armor' option ARMOR.append([0,0,0]) RINGS = [ [25,1...
_cost > cost): cost = p_cost print cost def is_win(b_hp, b_dmg, b_a, p_hp, p_dmg, p_a): b_dmg = max(b_dmg - p_a, 1) p_dmg = max(p_dmg - b_a, 1) #<= because we start first return (b_hp / p_dmg) <= (p_hp / b_dmg) def calc_bonuses(w,a,r): ret = [0, 0, 0] for i in [w,a,r]: for j in i: ret[0] += j[0] re...
return ret if __name__ == "__main__": main()
rlowrance/re-local-linear
Logger.py
Python
mit
886
0.003386
import datetime import sys import pdb from directory import directory if False: pdb.set_trace() # avoid warning message from pyflakes class Logger(object): # from stack overflow: how do i duplicat sys stdout to a log file in
python def __init__(self, logfile_path=None, logfile_mode='w', base_name=
None): def path(s): return directory('log') + s + datetime.datetime.now().isoformat('T') + '.log' self.terminal = sys.stdout clean_path = logfile_path.replace(':', '-') if base_name is None else path(base_name) self.log = open(clean_path, logfile_mode) def write(self, me...
spiceqa/virt-test
virttest/lvsb.py
Python
gpl-2.0
4,505
0
""" Higher order classes and functions for Libvirt Sandbox (lxc) container testing :copyright: 2013 Red Hat Inc. """ import datetime import time import logging import lvsb_base # This utility function lets test-modules quickly create a list of all # sandbox aggregate types, themselves containing a list of individual...
except TypeError: # Symbol wasn't a class, just ignore it pass # Return a list of instantiated sandbox_testsandboxes's classes return [namespace[type_name](params, env) for type_name in pobs] # TestSa
ndboxes subclasses defined below, or inside other namespaces like # a test module. They simply help the test-module iterate over many # aggregate manager classes and the sandboxes they contain. class TestSimpleSandboxes(lvsb_base.TestSandboxes): """ Simplistic sandbox aggregate manager that just executes a c...
botify-labs/moto
tests/test_swf/responses/test_domains.py
Python
apache-2.0
3,834
0
import boto from boto.swf.exceptions import SWFResponseError import sure # noqa from moto import mock_swf_deprecated # RegisterDomain endpoint @mock_swf_deprecated def test_register_domain(): conn = boto.connect_swf("the_key", "the_secret") conn.register_domain("test-domain", "60", description="A test domai...
t_swf("the_key", "the_secret") conn.register_domain("b-test-domain", "60") conn.register_domain("a-test-domain", "60") conn.register_domain("c-test-domain", "60") all_domains = conn.list_d
omains("REGISTERED") names = [domain["name"] for domain in all_domains["domainInfos"]] names.should.equal(["a-test-domain", "b-test-domain", "c-test-domain"]) @mock_swf_deprecated def test_list_domains_reverse_order(): conn = boto.connect_swf("the_key", "the_secret") conn.register_domain("b-test-domai...
techiaith/seilwaith
srdk/htk/SRDK_Train.py
Python
apache-2.0
1,957
0.036791
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys import traceback f
rom argparse import
ArgumentParser class SRDKRunError(Exception): def __init__(self, message): self.msg = message def run_commands(cmds): for cmd in cmds: cmd = u" ".join(cmd) print("Rhedeg %s" % cmd) returncode = os.system(cmd) try: if returncode != 0: ...
n4hy/gnuradio
gr-uhd/apps/uhd_rx_cfile.py
Python
gpl-3.0
5,974
0.005524
#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) ...
e_sink(gr.sizeof_short*2, filename) else: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) self._sink = gr.file_sink(gr.sizeof_gr_complex, filename) # Set receiver sample rate self._u.set_samp_rate(options.samp_rate) # Set...
if options.gain is None: g = self._u.get_gain_range() options.gain = float(g.start()+g.stop())/2 print "Using mid-point gain of", options.gain, "(", g.start(), "-", g.stop(), ")" self._u.set_gain(options.gain) # Set the subdevice spec if(options.spec): ...
dylanseago/LeagueOfLadders
leagueofladders/urls.py
Python
apache-2.0
420
0.004762
from django.conf.urls import patterns, include, url from django.contrib im
port admin from leagueofladders import settings urlpatterns = patterns('', url(r'^l/', include('leagueofladders.app
s.myleague.urls', namespace='myleague')), url(r'^admin/', include(admin.site.urls)), url(r'^%s$' % settings.LOGIN_URL[1:], 'django.contrib.auth.views.login'))
Azure/azure-sdk-for-python
sdk/storage/azure-mgmt-storage/azure/mgmt/storage/_storage_management_client.py
Python
mit
63,288
0.006652
# 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 ...
nt from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin from msrest import Deserializer, Serializer from ._configuration import StorageManagementClientConfiguration if T
YPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential class _SDKClient(object): def __init__(self, *args, **kwargs): """This is a fake class to support current implemetation of MultiApiClientMixin." ...
jdowner/uuid64
uuid64/__init__.py
Python
mit
23
0
from . uu
id64 impo
rt *
dleecefft/pcapstats
pbin/parseL4Info.py
Python
apache-2.0
5,615
0.018878
#!/usr/bin/env python # take a large pcap and dump the data into a CSV so it can be analysed by something like R. # # This version we want to know what the source IP is, what the protocol is and based on those # peices of info run a function to grab that data and write a line to a CSV file # # Ignore all traffic sourc...
estamp(float(tsstr)) rowlist[0]=
dtobj.strftime("%Y-%m-%d") rowlist[1]= dtobj.strftime("%H:%M:%S.%f") rowlist[2]= tsstr return def parseIPother(ipopkt): print "running parseIP Other " rowlist[3]= int(ipopkt.ip.proto) rowlist[4]= str(ipopkt.ip.src).strip() tsstr=str(ipopkt.frame_info.time_epoch) dtobj=datetime.fromtimes...
kiyukuta/chainer
chainer/functions/activation/leaky_relu.py
Python
mit
2,382
0
from chainer import cuda from chainer i
mport function from chainer.utils imp
ort type_check def _kern(): return cuda.elementwise( 'T cond, T x, T slope', 'T y', 'y = cond >= 0 ? x : (T)(slope * x)', 'lrelu') class LeakyReLU(function.Function): """Leaky rectifier unit.""" def __init__(self, slope=0.2): self.slope = slope def check_type_forward(self,...
endlessm/chromium-browser
third_party/angle/third_party/vulkan-validation-layers/src/scripts/layer_chassis_dispatch_generator.py
Python
bsd-3-clause
99,103
0.005711
#!/usr/bin/python3 -i # # Copyright (c) 2015-2020 The Khronos Group Inc. # Copyright (c) 2015-2020 Valve Corporation # Copyright (c) 2015-2020 LunarG, Inc. # Copyright (c) 2015-2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
in_chain<VkPipelineCreationFeedbackCreateInfoEXT>(src_chain); if (!src_feedback_struct) return; auto dst_feedback_struct = const_cast<VkPipelineCreationFeedbackCreateInfoEXT *>( lvl_find_in_chain<VkPipelineCreationFeedbackCreateInfoEXT>(
dst_chain)); *dst_feedback_struct->pPipelineCreationFeedback = *src_feedback_struct->pPipelineCreationFeedback; for (uint32_t i = 0; i < src_feedback_struct->pipelineStageCreationFeedbackCount; i++) { dst_feedback_struct->pPipelineStageCreationFeedbacks[i] = src_feedback_struct->pPipelineStageCreationFe...
joshuahoman/vivisect
envi/tests/msp430/iswpb.py
Python
apache-2.0
341
0.017595
from envi.archs.msp430.regs import *
checks = [ # SWPB ( 'DEC r15', { 'regs': [(REG_R15, 0xaabb)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f10", 'data': "" }, { 'regs': [(REG_R15, 0xbbaa)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f10", 'data': "" }
), ]
jeffw16/elephant
nlp/nlpserver.py
Python
mit
849
0.042403
import socket import nlp class NLPServer(object): def __init__(self, ip, port):
self.sock = socket.socket() self.sock.bind((ip, port)) self.processor = nlp.NLPProcessor() print "Established Server" def listen(self): import thread self.sock.listen(5) prin
t "Started listening at port." while True: c = self.sock.accept() cli_sock, cli_addr = c try: print 'Got connection from', cli_addr thread.start_new_thread(self.manageRequest, (cli_sock,)) except Exception, Argument: print Argument self.sock.close() quit() def manageRequest(sel...
NSLS-II-XPD/ipython_ophyd
archived/profile_collection-dev/startup/42-energy-calib.py
Python
bsd-2-clause
4,842
0.001239
from __future__ import division, print_function import numpy as np from lmfit.models import VoigtModel from scipy.signal import argrelmax import matplotlib.pyplot as plt def lamda_from_bragg(th, d, n): return 2 * d * np.sin(th / 2.) / n def find_peaks(chi, sides=6, intensity_threshold=0): # Find all potenti...
fit_centers < 0.] r_peaks = lmfit_centers[lmfit_centers > 0.] for peak_set in [r_peaks, l_peak
s[::-1]]: for peak_center, d, n in zip(peak_set, d_spacings, ns): tth = np.deg2rad(np.abs(peak_center)) wavelengths.append(lamda_from_bragg(tth, d, n)) return np.average(wavelengths), np.std(wavelengths) from bluesky.callbacks import CollectThenCompute class ComputeWavelength(Col...
feilongfl/micropython
tests/wipy/pin.py
Python
mit
4,685
0.007044
""" This test need a set of pins which can be set as inputs and have no external pull up or pull down connected. """ from machine import Pin import os mch = os.uname().machine if 'LaunchPad' in mch: pin_map = ['GP24', 'GP12', 'GP14', 'GP15', 'GP16', 'GP17', 'GP28', 'GP8', 'GP6', 'GP30', 'GP31', 'GP3', 'GP0', ...
ode=Pin.OUT) # mode print(pin.mode() == Pin.OUT) pin.mode(Pin.IN) print(pin.mode() == Pin.IN) # pull pin.pull(None) print(pin.pull() == None) pin.pull(Pin.PULL_DOWN) print(pin.pull() == Pin.PULL_DOWN) # drive pin.drive(Pin.MED_POWER) print(pin.drive() == Pin.MED_POWER) pin.drive(Pin.HIGH_POWER) print(pin.drive() == Pin
.HIGH_POWER) # id print(pin.id() == pin_map[0]) # all the next ones MUST raise try: pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value except Exception: print('Exception') try: pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value excep...
bronycub/sugarcub
sugarcub/celery.py
Python
gpl-3.0
576
0
from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sugarcub.settings') from django.conf import settings # noqa app = Celery('sugarcub')
# Using a string here means the worker will not have to # pickle the object
when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
kustodian/ansible
lib/ansible/modules/cloud/amazon/kinesis_stream.py
Python
gpl-3.0
46,551
0.001547
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
ards: description: - The number of shards you want to have with this stream. - This is required when I(state=present) type: int retention_period: description: - The length of time (in hours) data records are accessible after they are added to the stream. - The default reten...
time. type: int state: description: - Create or Delete the Kinesis Stream. default: present choices: [ 'present', 'absent' ] type: str wait: description: - Wait for operation to complete before returning. default: true type: bool wait_timeout: description: - H...
IlyaDjurin/django-shop
shop/migrations/0018_auto_20170327_1937.py
Python
mit
3,554
0.0039
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-27 16:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0017_auto_20170327_1934'), ] operations = [ migrations.AlterField( ...
), migrations.AlterField( model_name='tovar_img', name='tovar_image8', field=models.ImageField(blank=True, upload_to='media/products/%Y/%m/%d/', verbose_name='Изображение товара8'), ),
migrations.AlterField( model_name='tovar_img', name='tovar_image9', field=models.ImageField(blank=True, upload_to='media/products/%Y/%m/%d/', verbose_name='Изображение товара9'), ), ]
DavidJohnGee/clicrud
clicrud/crud/__init__.py
Python
apache-2.0
3,616
0.000553
""" Co
pyright 2015 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in w...
D, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging import time import json import sys from clicrud.device.generic import generic def read(queue, finq, ranonceq, **kwargs): _cli_input = "['command', 'commands', 'list...
iDigBio/idb-backend
idb/data_api/v1.py
Python
gpl-3.0
4,235
0.012043
from __future__ import division, absolute_import, print_function from flask import current_app, Blueprint, jsonify, url_for, request from idb.helpers.cors import crossdomain from .common import json_error, idbmodel, logger this_version = Blueprint(__name__,__name__) def format_list_item(t,uuid,etag,modified,versio...
return jsonify(r) else: return json_error(404) else: return json_error(404) @this_version.route('/<string:t>', methods=['GET','OPTIONS']) @crossdomain(origin="*") def list(t): if t not in current_app.config["SUPPORTED_TYPES"]: return json_error(404) limit =...
t is not None: offset = int(offset) else: offset = 0 r = {} l = [ format_list_item( t, v["uuid"], v["etag"], v["modified"], v["version"], v["parent"], ) for v in idbmodel.get_type_list("".join(t[:-1]),li...
tensorflow/tensorflow
tensorflow/python/client/timeline.py
Python
apache-2.0
28,612
0.005033
# 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...
erating this event as an integer. tid: Identifier of the thread generating this event as an integer. flow_id: Identifier of the flow a
s an integer. """ event = self._create_event('s', 'DataFlow', name, pid, tid, timestamp) event['id'] = flow_id self._events.append(event) def emit_flow_end(self, name, timestamp, pid, tid, flow_id): """Adds a flow end event to the trace. When matched with a flow start event (with the same 'f...
piotrlewalski/birdstorm
game/apps/core/models/buildings.py
Python
mit
2,036
0.002947
import blinker from concurrency.fields import IntegerVersionField from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver from game.apps.core.models.planet.models import Planet from game.utils.models i...
ted']: Citadel.objects.create(user=kwargs['instance'], planet_id=1) # TODO don't hard-code planet id Warehouse.objects.create(user=kwargs['instance'], planet_id=1) # TODO don't hard-code planet id def get_base(self): #TODO cache return self.buildings.get(type="Base") User.base = pr...
t_base)
MSHallOpenSoft/plotter
Thesidetab/sliderder.py
Python
gpl-2.0
2,815
0.001421
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'slidersd.ui' # # Created: Tue Mar 17 23:31:52 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attri...
nslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.label.setText(_translate("Form", "a = ", None)) self.label_3.setText(_translate("Form", "-10", None)) self.label_4.setText(_translate("Form", "10", None))
PetePriority/home-assistant
homeassistant/components/modbus/climate.py
Python
apache-2.0
5,304
0
""" Platform for a Generic Modbus Thermostat. This uses a setpoint and process value within the controller, so both the current temperature register and the target temperature register need to be configured. For more details about this platform, please refer to the documentation at https://home-assistant.io/component...
[self._count]) @property def supported_features(self): """Return the list of supported fea
tures.""" return SUPPORT_FLAGS def update(self): """Update Target & Current Temperature.""" self._target_temperature = self.read_register( self._target_temperature_register) self._current_temperature = self.read_register( self._current_temperature_register) ...
kpech21/Greek-Stemmer
tests/closets/test_word_exceptions.py
Python
lgpl-3.0
157
0
#
-*- coding: utf-8 -*- from greek_stemmer.closets.word_exceptions import exceptions def test_word_exceptions(): assert isinstance(except
ions, dict)
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
Python
apache-2.0
16,836
0.00689
from pypif.obj import Property, Scalar from .base import DFTParser, Value_if_true, InvalidIngesterException import os import re from ase.io.vasp import read_vasp_out from pypif.obj import Value, FileReference from dftparse.vasp.outcar_parser import OutcarParser from dftparse.vasp.eigenval_parser import EigenvalParser ...
# Error handling: ENCUT not found raise Exception('ENCUT not found') @Value_if_true def uses_SOC(self): # Open up the OUTCAR with open(self.outcar) a
s fp: #look for LSORBIT for line in fp: if "LSORBIT" in line: words = line.split() return words[2] == 'T' # Error handling: LSORBIT not found raise Exception('LSORBIT not found') @Value_if_true...
bj7/pwndbg
pwndbg/memory.py
Python
mit
5,918
0.010308
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Reading, writing, and describing memory. """ import gdb import pwndbg.compat import pwndbg.typeinfo PAGE_SIZE = 0x1000 PAGE_MASK = ~(PAGE_SIZE-1) MMAP_MIN_ADDR = 0x8000 def read(addr, count, partial=False): result = '' try: result = gdb.selected_infer...
def page_align(address): return round_down(address, PAGE_SIZE) def page_size_align(address): return round_up(address, PAGE_SIZE) def page_offset(address): return
(address & (PAGE_SIZE-1)) assert round_down(0xdeadbeef, 0x1000) == 0xdeadb000 assert round_up(0xdeadbeef, 0x1000) == 0xdeadc000 def find_upper_boundary(addr, max_pages=1024): addr = pwndbg.memory.page_align(int(addr)) try: for i in range(max_pages): pwndbg.memory.read(addr, 1) ...
kparal/anaconda
pyanaconda/anaconda.py
Python
gpl-2.0
9,570
0.001463
# anaconda: The Red Hat Linux Installation program # # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 # Red Hat, Inc. All rights reserved. # # 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 Softw...
led = False self.id = None self._instClass = None self._intf = None self.isHeadless = False self.ksdata = None self.mediaDevice = None self.methodstr = None
self.opts = None self._payload = None self.proxy = None self.proxyUsername = None self.proxyPassword = None self.reIPLMessage = None self.rescue_mount = True self.rootParts = None self.stage2 = None self._storage = None self.updateSrc...
mihow/footer
config/wsgi.py
Python
mit
1,706
0
""" WSGI config for Footer project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` s...
try # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode wi
th each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development serve...
junhuac/MQUIC
src/mojo/tools/mopy/config.py
Python
mit
4,103
0.014136
# Copyright 2014 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. import ast import os.path import platform import re import sys class Config(object): '''A Config contains a dictionary that species a build configuratio...
NS.ge
t(value, value)) # Getters for standard fields ------------------------------------------------ @property def build_dir(self): '''Build directory path.''' return self.values['build_dir'] @property def target_os(self): '''OS of the build/test target.''' return self.values['target_os'] @pr...
pzread/sdup
pg.py
Python
mit
8,196
0.0194
import random import datetime import psycopg2 from collections import deque from tornado.stack_context import wrap from tornado.ioloop import IOLoop from tornado.concurrent import return_future class WrapCursor: def __init__(self,db,cur): self._db = db self._cur = cur self._oldcur = None ...
ACK;',callback = _cb) def _init_member(self): self.fetchone = self._cur.fetchone self.fet
chmany = self._cur.fetchmany self.fetchall = self._cur.fetchall self.scroll = self._cur.scroll self.cast = self._cur.cast self.tzinfo_factory = self._cur.tzinfo_factory self.arraysize = 0 self.itersize = 0 self.rowcount = 0 self.rownumber = 0 self...
mozilla/iacomus-alerts
python/poster.py
Python
epl-1.0
2,563
0.006633
import simplejson as json import urllib import urllib2 import time server = "" def GET(uri, params): params = urllib.urlencode(params) req = urllib2.Request(server + uri + "?" + params , headers={'Accept': 'application/json'}) return json.loads(urllib2.urlopen(req).read()) def POST(uri, params): para...
response = json.loads(urllib2.urlopen(req).read()) return response["id"] def set_server_url(url): global server server = url class Detector: def __init__(self, name, url): self.name = name self.url = url def get_id(self): try: return self.id except At...
except urllib2.HTTPError as e: self.id = POST("/detectors/", {'name': self.name, 'url': self.url}) return self.id def realize(self): self.get_id() class Metric: def __init__(self, name, descr, detector): self.name = name self.descr = descr self.det...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/hplip/ui4/readonlyradiobutton.py
Python
gpl-3.0
1,657
0.004225
# -*- coding: utf-8 -*- # # (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P. # # 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 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...
blajoie/vcf2fasta
scripts/vcf2fasta.py
Python
apache-2.0
8,351
0.025626
from __future__ import print_function from __future__ import division import numpy as np import sys import argparse import time import re import gzip import os import logging from collections import defaultdict from operator import itemgetter __version__ = "1.0" def main(): parser=argparse.ArgumentParser(descr...
le('>') if regexp.search(line): if line.startswith(">"): chrom=line.lstrip(">") pos=1 print(line,"-",name,file=out_fh,sep="") continue else: # random > found in
line - issue with cat ? sys.exit('error with fasta file'+'\n'+str(line)) if(chrom != last_chrom): tmp_pos_list=[] if(last_chrom != None): verboseprint(" ... ",placed_snps," / ",possible_snps,sep="") ...
keeprocking/pygelf
tests/test_common_fields.py
Python
mit
2,884
0.001387
import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception SYSLOG_LEVE
L_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(host='127.0.0.1', port=12201), GelfUdpHandler(host='127.0.0.1', port=12202), GelfUdpHandler(host='127.0.0.1', port=12202, compress=False), GelfHttpHandler(host='127.0.0.1', port=12203), GelfHttpHandler(host='127.0.
0.1', port=12203, compress=False), GelfTlsHandler(host='127.0.0.1', port=12204), GelfHttpsHandler(host='127.0.0.1', port=12205, validate=False), GelfHttpsHandler(host='localhost', port=12205, validate=True, ca_certs='tests/config/cert.pem'), GelfTlsHandler(host='127.0.0.1', port=12204, validate=True, ca...
nmakhotkin/mistral-extra
examples/webhooks/api/controllers/resource.py
Python
apache-2.0
1,470
0
# -*- coding: utf-8 -*- # # Copyright 2013 - Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
obj, key): setattr(obj, key, val) return obj def __str__(self): """WSME based implementation
of __str__.""" res = "%s [" % type(self).__name__ first = True for attr in self._wsme_attributes: if not first: res += ', ' else: first = False res += "%s='%s'" % (attr.name, getattr(self, attr.name)) return res + "...
chromakode/karmabot
karmabot/extensions/lmgtfy.py
Python
bsd-3-clause
2,423
0.000413
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. # dedicated to LC from json import JSONDecoder from urllib import urlencode from urllib2 import urlopen from karmabot.co...
rt Facet import re import htmlentitydefs ## # Function Placed in public domain by Fredrik Lundh # http://effbot.org/zone/copyright.htm # http://effbot.org/zone/re-sub.htm#unesc
ape-html # Removes HTML or XML character references and entities from a text string. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode string, if necessary. def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character referenc...
witcxc/scipy
scipy/linalg/_decomp_qz.py
Python
bsd-3-clause
8,764
0.004792
from __future__ import division, print_function, absolute_import import warnings import numpy as np from numpy import asarray_chkfinite from .misc import LinAlgError, _datacopied from .lapack import get_lapack_funcs from scipy._lib.six import callable __all__ = ['qz'] _double_precision = ['i','l','d'] def _sele...
not in Schur " "form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be correct " "for J=%d,...,N" % info-1, UserWarning) elif info == a_n+1: raise LinAlgError("Something other than QZ iteration failed") elif info == a_n+2: raise LinAlgError("After reordering,
roundoff changed values of some " "complex eigenvalues s
cloudbase/nova-virtualbox
nova/openstack/common/versionutils.py
Python
apache-2.0
8,784
0
# Copyright (c) 2013 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 ...
s): report_deprecated_feature(LOG, msg, details) return func_or_cls(*args, **kwargs) return wrappe
d elif inspect.isclass(func_or_cls): orig_init = func_or_cls.__init__ # TODO(tsufiev): change `functools` module to `six` as # soon as six 1.7.4 (with fix for passing `assigned` # argument to underlying `functools.wraps`) is released # and added to th...
Humantrashcan/prices
exchanges/opportunity_kraken.py
Python
mit
658
0.024316
from exchanges import helpers from exchanges import kraken from decimal import Decimal ### Kraken opportunities #### ARBITRAGE
OPPORTUNITY 1 def opportunity_1(): sellLTCbuyEUR = kraken.get_current_bid_LTCEUR() sellEURbuyXBT = kraken.get_current_ask_XBTEUR() sellXBTbuyLTC = kraken.get_current_ask_XBTLTC() opport = 1-((sellLTCbuyEUR/sellEURbuyBTX)*sellXBTbuyLTC) return Decimal(opport) def opportunity_2(): sellEURbuyLTC = kraken.ge...
llLTCbuyXBT = kraken.get_current_ask_XBTLTC() sellXBTbuyEUR = kraken.get_current_bid_XBTEUR() opport = 1-(((1/sellEURbuyLTC)/sellLTCbuyXBT)*sellXBTbuyEUR) return Decimal(opport)
PyFilesystem/pyfilesystem2
tests/test_enums.py
Python
mit
335
0
import os from fs
import enums import unittest class T
estEnums(unittest.TestCase): def test_enums(self): self.assertEqual(enums.Seek.current, os.SEEK_CUR) self.assertEqual(enums.Seek.end, os.SEEK_END) self.assertEqual(enums.Seek.set, os.SEEK_SET) self.assertEqual(enums.ResourceType.unknown, 0)
sureshbvn/nlpProject
nGramModel/test.py
Python
mit
2,837
0.004582
#!/usr/bin/env python from __future__ import print_function # Use the srilm module from srilm import * # Initialize a trigram LM variable (1 = unigram, 2 = bigram and so on) n = initLM(5) # Read 'sam
ple.lm' into the LM variable readLM(n, "corpu.lm") # How many n-grams of different order are there ? print("1. Number of n-grams:") print(" There are {} unigrams in this LM"
.format(howManyNgrams(n, 1))) print(" There are {} bigrams in this LM".format(howManyNgrams(n, 2))) print(" There are {} trigrams in this LM".format(howManyNgrams(n, 3))) print(" There are {} 4-grams in this LM".format(howManyNgrams(n, 4))) print(" There are {} 5-grams in this LM".format(howManyNgrams(n, 5))) p...
rootio/rootio_telephony
sms_utils/sms_server.py
Python
agpl-3.0
3,873
0.018848
from flask import Flask from flask import request from flask.ext.sqlalchemy import SQLAlchemy import datetime import uuid as uid import sys import requests import urllib2 GOIP_SERVER_IP = '127.0.0.1' #'172.248.114.178' TELEPHONY_SERVER_IP = '127.0.0.1:5000/sms/in' sys.path.append('/home/csik/public_python/sms_...
uuid, 'edt': edt, 'fr': fr, 'to': to, 'from_number': from_number, 'body': body, } r= requests.get(TELEPHONY_SERVER_IP,params=payload) print r.text return "looks alright " + str(uuid) #return str(str(e...
_name__ == "__main__": app.run(debug=True) r = requests.get('http://'+GOIP_SERVER_IP+'/init_goip')
isc-projects/forge
tests/softwaresupport/bind9_server/bind_configs.py
Python
isc
54,716
0.009668
# Copyright (C) 2013-2020 Internet Systems Consortium. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET ...
nf, rndc.conf, fwd.db, rev.db ] 1: [""" options { directory "${data_path}"; // Working directory listen-on-v6 port ${dns_port} { ${dns_addr}; }; allow-query-cache {
none; }; // Do not allow access to cache allow-update { any; }; // This is the default allow-query { any; }; // This is the default recursion no; // Do not provide recursive service }; zone "1.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa" { type master; file...
jaybutera/tetrisRL
run_model.py
Python
mit
1,627
0.009834
impor
t sys import os import torch import time from engine import TetrisEngine from dqn_agent import DQN, ReplayMemory, Transition from torch.autograd import Variable use_cuda = torch.cuda.is_available() FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor LongTensor = torch.cuda.LongTensor if use_cuda e...
ngine(width, height) def load_model(filename): model = DQN() if use_cuda: model.cuda() checkpoint = torch.load(filename) model.load_state_dict(checkpoint['state_dict']) return model def run(model): state = FloatTensor(engine.clear()[None,None,:,:]) score = 0 while True: ...
VikParuchuri/evolve-music2
extract_features.py
Python
mit
6,422
0.001557
import pandas as pd import logging import settings import os from scikits.audiolab import oggwrite, play, oggread from scipy.fftpack import dct from itertools import chain import numpy as np import math log = logging.getLogger(__name__) def read_sound(fpath, limit=settings.MUSIC_TIME_LIMIT): try: data, f...
continue log.debug("On file {0}".format(p)) filepath = os.path.join(settings.OGG_DIR, p) try: data, fs, enc = read_sound(filepath) except Exception:
continue try: features = process_song(data, fs) except Exception: log.error("Could not get features for file {0}".format(p)) continue d.append(features) fss.append(fs) encs.append(enc) fnames...
srottem/indy-sdk
samples/python/src/anoncreds.py
Python
apache-2.0
7,929
0.005171
import time from indy import anoncreds, wallet import json import logging from indy import pool from src.utils import run_coroutine, PROTOCOL_VERSION logger = logging.getLogger(__name__) async def demo(): logger.info("Anoncreds sample -> started") issuer = { 'did': 'NcYxiDXkpYi6ov5FcYDi1e', ...
erifier = {} store = {} # Set protocol version 2 to work with Indy Node 1.4 await pool.set_protocol_version(PROTOCOL_VERSION) # 1. Create Issuer Wallet and Get Wallet Handle await wallet.create_wallet(issuer['wallet_config'], issuer['wallet_credentials']) issuer['wallet'] = await wallet.open_w...
credentials']) # 2. Create Prover Wallet and Get Wallet Handle await wallet.create_wallet(prover['wallet_config'], prover['wallet_credentials']) prover['wallet'] = await wallet.open_wallet(prover['wallet_config'], prover['wallet_credentials']) # 3. Issuer create Credential Schema schema = { ...
sajuptpm/contrail-controller
src/config/svc-monitor/svc_monitor/rabbit.py
Python
apache-2.0
4,079
0.001226
import gevent import socket from vnc_api.vnc_api import * from cfgm_common.vnc_kombu import VncKombuClient from config_db import * from cfgm_common.dependency_tracker import DependencyTracker from reaction_map import REACTION_MAP import svc_monitor class RabbitConnection(object): _REACTION_MAP = REACTION_MAP ...
be_actions(self, oper_info): msg = "Notification Message: %s" % (pformat(oper_info)) self.logger.log_debug(msg) obj_type = oper_info['type'].replace('-', '_') obj_class = DBBaseSM.get_obj_type_map().get(obj_type) if obj_class is None: return if oper_info['ope...
te(obj_id) dependency_tracker = DependencyTracker( DBBaseSM.get_obj_type_map(), self._REACTION_MAP) dependency_tracker.evaluate(obj_type, obj) elif oper_info['oper'] == 'UPDATE': obj_id = oper_info['uuid'] obj = obj_class.get(obj_id) ol...
vipmike007/avocado-vt
virttest/iscsi.py
Python
gpl-2.0
29,173
0.001165
""" Basic iscsi support for Linux host with the help of commands iscsiadm and tgtadm. This include the basic operates such as login and get device name by target name. And it can support the real iscsi access and emulated iscsi in localhost then access it. """ import re import os import logging from avocado.core imp...
s" % portal_ip output = process.system_output(cmd, ignore_status=True) session = "" if "Invalid" in output: logging.debug(output) else: session = output return session class _Is
csiComm(object): """ Provide an interface to complete the similar initialization """ def __init__(self, params, root_dir): """ common __init__ function used to initialize iSCSI service :param params: parameters dict for iSCSI :param root_dir: path for image ...
v-iam/azure-sdk-for-python
azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/error.py
Python
mit
1,252
0.000799
# 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 ...
------------------------------------------------------------------ from msrest.serialization import Model from msrest.exceptions import HttpOperationError class Error(Model): """Cognitive Services error object. :param error: The error body. :type error: :class:`ErrorBody <azure.mgmt.cognitiveservic...
elf.error = error class ErrorException(HttpOperationError): """Server responsed with exception of type: 'Error'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ def __init__(self, deserialize, response, *args): super(ErrorException, self).__in...
dsiddharth/access-keys
keystone/common/sql/migrate_repo/versions/001_add_initial_tables.py
Python
apache-2.0
5,811
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
tell it to and there is no DDL to alter a column to drop # an unnamed unique constraint, so this code creates a named unique # constraint on the name column rather than an unnamed one. # (This is used in migration 16.) user_table = sql.Table( 'user', meta, ...
.Column('id', sql.String(64), primary_key=True), sql.Column('name', sql.String(64), nullable=False), sql.Column('extra', sql.Text()), sql.UniqueConstraint('name', name='user_name_key')) else: user_table = sql.Table( 'user', meta, sql.Co...
steventimberman/masterDebater
venv/lib/python2.7/site-packages/rest_framework/compat.py
Python
mit
10,280
0.000486
""" The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ # flake8: noqa from __future__ import unicode_literals import inspect import django from django.apps import apps from django.conf import settings from dj...
ment to `json.dumps()` differs between 2.x and 3.x # See: http://bugs.python.org/issue22767 if six.PY3: SHORT_SEPARATORS = (',', ':') LONG_SEPARATORS = (', ', ': ') IND
ENT_SEPARATORS = (',', ': ') else: SHORT_SEPARATORS = (
NixaSoftware/CVis
venv/lib/python2.7/site-packages/pandas/tests/indexes/datetimes/test_datetimelike.py
Python
apache-2.0
2,661
0
""" generic tests from the Datetimelike class """ import numpy as np import pandas as pd from pandas.util import testing as tm from pandas import Series, Index, DatetimeIndex, date_range from ..datetimelike import DatetimeLike class TestDatetimeIndex(DatetimeLike): _holder = DatetimeIndex def setup_method(...
expected = DatetimeIndex(['2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'], freq='D') tm.assert_index_equal(result, expected) result = drange.shift(-1) expected = DatetimeIndex(['2012-12-31', '2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04'], ...
mareuter/lct-python
lct/utils/observing_info.py
Python
mit
1,166
0.008576
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # Copyright (c) 2012-2014, Michael Reuter # Distributed under the MI
T License. See LICENSE.txt for more information. #------------------------------------------------------------------------------ from .moon_info import MoonInfo from .observing_site import ObservingSite class ObservingInfo(object): ''' This class is responsible for keeping the observing site information and ...
ation object together. It will be responsible for updating any of the observing site information that then affects the moon information. ''' __shared_state = {"obs_site": ObservingSite(), "moon_info": MoonInfo()} def __init__(self): ''' Constructor ''...
kashishm/gauge-python
start.py
Python
mit
2,076
0.000482
import os import platform import sys import threading from concurrent.futures import ThreadPoolExecutor from os import environ, path from threading import Timer import grpc import ptvsd from getgauge import handlers, logger, processor from getgauge.impl_loader import copy_skel_files from getgauge.messages import runne...
oad implementations from {}. {} does not exist.'.format( impl_dir, impl_dir)) load_files(d) def _handle_detached():
logger.info("No debugger attached. Stopping the execution.") os._exit(1) def start(): if environ.get('DEBUGGING'): ptvsd.enable_attach(address=( '127.0.0.1', int(environ.get('DEBUG_PORT')))) print(ATTACH_DEBUGGER_EVENT) t = Timer(int(environ.get("debugger_wait_time", 30)...
antoinecarme/pyaf
tests/model_control/detailed/transf_Logit/model_control_one_enabled_Logit_MovingAverage_Seasonal_WeekOfYear_NoAR.py
Python
bsd-3-clause
163
0.04908
import tests.mod
el_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Logit'] , ['MovingAverage'] , ['Seasonal_WeekOfYear'] , ['NoAR'
] );
yuanming-hu/taichi
tests/python/examples/simulation/test_ad_gravity.py
Python
mit
1,137
0
import argparse import taichi as ti FRAMES = 100 def test_ad_gravity(): from taichi.examples.simulation.ad_gravity import init, substep init() for _ in range(FRAMES): for _ in range(50): substep() def video_ad_gravity(result_dir): import numpy as np from taichi.examples.si...
framerate=24, automatic_build=False) gui = ti.GUI('Autodiff gravity', show_gui=False) init() for _ in range(FRAMES): for _ in range(50): substep() gui.circles(x.to_numpy(), radius=3) video_manager.write_frame(g...
__name__ == '__main__': parser = argparse.ArgumentParser(description='Generate ad_gravity video') parser.add_argument('output_directory', help='output directory of generated video') video_ad_gravity(parser.parse_args().output_directory)
kmtoki/qmk_firmware
lib/python/qmk/cli/new/keymap.py
Python
gpl-2.0
1,884
0.004246
"""This script automates the copying of the default keymap into your own keymap. """ import shutil from pathlib import Path import qmk.path from qmk.decorators import automagic_keyboard, automagic_keymap from milc import cli @cli.argument('-kb', '--keyboard', help='Specify keyboard name. Example: 1upkeyboards/1up60h...
ard else input("Keyboard Name: ") keymap = cli.config.new_keymap.keymap if cli.config.new_keymap.keymap else input("Keymap Name: ") # generate keymap paths kb_path = Path('keyboards') / keyboard keymap_path = qmk.path.keymap(keyboard) keymap_path_default = keymap_path / 'default' keymap_path_ne...
cli.log.error('Keyboard %s does not exist!', kb_path) return False if not keymap_path_default.exists(): cli.log.error('Keyboard default %s does not exist!', keymap_path_default) return False if keymap_path_new.exists(): cli.log.error('Keymap %s already exists!', keymap_path...
ddinsight/dd-streamworks
stream_worker/devmodule/production/networklog/__init__.py
Python
apache-2.0
12,862
0.003424
# -*- coding: utf-8 -*- # # Copyright 2015 AirPlug Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
ect): OW_TASK_SUBSCRIBE_EVENT
S = ['evtPlayerLog', 'evtNetworkLog'] OW_TASK_PUBLISH_EVENTS = [] OW_USE_HASHING = False OW_HASH_KEY = None OW_NUM_WORKER = 8 def publishEvent(self, event, params): # THIS METHOD WILL BE OVERRIDE # DO NOT EDIT THIS METHOD pass def __makeCellId(self, plmnid, cid, lac): ...
ffsdmad/af-web
cgi-bin/plugins2/report/fond_search_report1.py
Python
gpl-3.0
547
0.006085
# -*- coding: utf8 -*- SQL = ( ('list_fonds_report1', """ select F.FKOD,F.FNAME, (F.A16+if(F.A22,A22,0)) as
A16 FROM `af3_fond` F WHERE FNAME like ('%%%(qr)s%%') or A1 like ('%%%(qr)s%%') ORDER BY FKOD;"""), ) FOUND_ROWS = True ROOT = "fonds" ROOT_PREFIX = None ROOT_POSTFIX= None XSL_TEMPLATE = "data/af-web.xsl" EVENT = None WHERE = () PARAM = ("qr",) TITLE="Поиск фондов" MESSAGE="Нет результ
атов по вашему запросу, вернитесь назад" ORDER = None
hforge/itools
itools/database/backends/git.py
Python
gpl-3.0
14,062
0.00313
# -*- coding: UTF-8 -*- # Copyright (C) 2007, 2009, 2011-2012 J. David Ibáñez <jdavid.ibp@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at y...
g('{0}/catalog'.format(path), fields) @classmethod def init_backend_static(cls, path): # Static database lfs.make_folder('{0}/database_static'.format(path)) lfs.make_folder('{0}/database_static/.history'.format(path)) ##############################################################...
############################################################## def normalize_key(self, path, __root=None): # Performance is critical so assume the path is already relative to # the repository. key = __root.resolve(path) if key and key[0] == '.git': err = "bad '{0}' path, ...
ray-project/ray
release/ray_release/tests/test_cluster_manager.py
Python
apache-2.0
24,218
0.000991
import os import time import unittest from typing import Callable from unittest.mock import patch from uuid import uuid4 from freezegun import freeze_time from ray_release.exception import ( ClusterCreationError, ClusterStartupError, ClusterStartupTimeout, ClusterStartupFailed, ClusterEnvBuildErro...
l_counter["search_cluster_computes"], 1) self.assertEqual(self.sdk.call_counter["create_cluster_compute"], 1) self.assertEqual(len(self.sdk.call_counter), 2) @patch("time.sleep", lambda *a, **kw
: None) def testFindCreateClusterEnvExisting(self): # Find existing env and succeed self.cluster_manager.set_cluster_env(self.cluster_env) self.assertTrue(self.cluster_manager.cluster_env_name) self.assertFalse(self.cluster_manager.cluster_env_id) self.sdk.returns["search_cl...
sdispater/pendulum
pendulum/time.py
Python
mit
7,783
0.001156
from datetime import time from datetime import timedelta import pendulum from .constants import SECS_PER_HOUR from .constants import SECS_PER_MIN from .constants import USECS_PER_SEC from .duration import AbsoluteDuration from .duration import Duration from .mixins.default import FormattableMixin class Time(Formatt...
utes=0, seconds=0, microseconds=0): """ Add duration to the instance. :param hours: The number of hours :type hours: int :param minutes: The number of minutes :type minutes: int :param seconds: The number of seconds :type seconds: int :param mi...
econds: int :rtype: Time """ from .datetime import DateTime return ( DateTime.EPOCH.at(self.hour, self.minute, self.second, self.microsecond) .add( hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds ) ...
luotao1/Paddle
python/paddle/distributed/fleet/utils/log_util.py
Python
apache-2.0
1,685
0.00178
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
_logger.addHandler(handler) return _logger logger = LoggerFactory.build_logger(name="HybridParallel", level=logging.INFO) def layer_to_str(base, *args, **kwargs): name = base + "(" if args: name += ", ".join(str(arg) for arg in args) if kwargs: name += ", " if kwar...
("{}={}".format(key, str(value)) for key, value in kwargs.items()) name += ")" return name
markuz/Christine
libchristine/Share.py
Python
gpl-2.0
5,045
0.004559
# -*- coding: utf-8 -*- # # This file is part of the Christine project # # Copyright (c) 2006-2007 Marco Antonio Islas Cruz # # Christine 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...
nager().getLogger('Share') self.__PathTemplate = os.path.join(SHARE_PATH, 'gui') self.__PathPixmap = os.path.join(self.__PathTemplate, 'pixmaps') #self.__Pixmaps, used to store a pixmap. if it is here then reuse it #instead of creating another one from the same faile self.__Pix...
de template @param string file: file to load @param string root: root widget to return instead the main window """ if file: file = ''.join([file, '.glade']) if isFile(os.path.join(self.__PathTemplate, file)): return glade_xml(os.path.join(self.__Pa...
AravindK95/ee106b
project1/src/lab1/src/exp_quat_func.py
Python
mit
7,708
0.018422
#!/usr/bin/env python """Exponential and Quaternion code for Lab 6. Course: EE 106, Fall 2015 Author: Victor Shia, 9/24/15 This Python file is a code skeleton Lab 6 which calculates the rigid body transform given a rotation / translation and computes the twist from rigid body transform. When you think you have the me...
create_rbt() arg1 = np.array([1.0, 2, 3]) arg2 = 2 arg3 = np.array([0.5,-0.5,1]) func_args = (arg1,arg2,arg3) ret_desired = np.array( [[ 0.4078, -0.6562, 0.6349, 0.5 ], [
0.8384, 0.5445, 0.0242, -0.5 ], [-0.3616, 0.5224, 0.7722, 1. ], [ 0. , 0. , 0. , 1. ]]) array_func_test(create_rbt, func_args, ret_desired) #Test compute_gab(g0a,g0b) g0a = np.array( [[ 0.4078, -0.6562, 0.6349, 0.5 ], [ 0.8384, 0.5445, 0.0242, -...
reminisce/mxnet
python/mxnet/symbol/numpy_extension/__init__.py
Python
apache-2.0
996
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
y 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...
governing permissions and limitations # under the License. """Module for the ops not belonging to the official numpy package.""" from . import _op from . import image from . import _register from ._op import * # pylint: disable=wildcard-import __all__ = _op.__all__
kboyd/scons_r
test/basic.py
Python
bsd-2-clause
596
0.001678
# A SCons tool for R scripts # # Copyright (c) 2014 Kendrick Boyd. This is free software. See LICENSE # for details. """ Basic test of producing output using save. """ import TestSCons test = TestSCons.TestSCons() # Add scons_r tool to test figure. test.file_fixture('../__init__.py', 'site_sco
ns/site_tools/scons_r/__init__.py') test.write(['SConstruct'], """\ import os env = Environment(TOOLS = ['scons_r']) e
nv.R('basic.r') """) test.write(['basic.r'], """\ x=rnorm(100) save(x, file='x.rdata') """) test.run(arguments='.', stderr=None) test.must_exist('x.rdata') test.pass_test()
thoslin/django-markitup
markitup/views.py
Python
bsd-3-clause
527
0.00759
from django.shortcuts import render_to_response from django.template import RequestContext from markitup import settings from markitup.markup import filter_func from
markitup.sanitize import sanitize_html def apply_filter(request): cleaned_data = sanitize_html(request.POST.get('data', ''), strip=True) markup = filter_func(cleaned_data) return render_to_response( 'markitup/preview.html', {'preview': markup}, co...
nce=RequestContext(request))
aldian/tensorflow
tensorflow/python/keras/applications/xception.py
Python
apache-2.0
13,084
0.006649
# 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...
the Xception architecture. Reference: - [Xception: Deep Learning with Depthwise Separable Convolutions]( https://arxiv.org/ab
s/1610.02357) (CVPR 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at `~/.keras/keras.json`. Note that the default input image size for this model is 299x299. Caution: Be sure to properly pre-process yo...
mrocklin/blaze
blaze/expr/utils.py
Python
bsd-3-clause
1,782
0.001684
from __future__ import absolute_import, division, print_function class _slice(object): """ A hashable slice object >>> _slice(0, 10, None) 0:10 """ def __init__(self, start, stop, step): self.start = start self.stop = stop self.step = step def __hash__(self): r...
__str__(self): return str(list(self)) def hashable_index(index): """ Convert slice-thing into something hashable >>> hashable_index(1) 1 >>> isinstance(hash(hashable_index((1, slice(10)))), int) True """ if type(index) is tuple: # can't do isinstance due to hashable_list ...
(index.start, index.stop, index.step) return index def replace_slices(index): if isinstance(index, hashable_list): return list(index) elif isinstance(index, _slice): return index.as_slice() elif isinstance(index, tuple): return tuple(map(replace_slices, index)) return inde...
scionrep/scioncc
src/pyon/ion/process.py
Python
bsd-2-clause
27,034
0.005401
#!/usr/bin/env python __author__ = 'Adam R. Smith, Michael Meisinger, Dave Foster <dfoster@asascience.com>' import threading import traceback import gevent from gevent import greenlet, Timeout from gevent.event import Event, AsyncResult from gevent.queue import Queue from pyon.core import MSG_HEADER_ACTOR from pyon....
r.timeout.heartbeat_proc_time_threshold', 30) * 1000: heartbeat_ok = False else: # it's made some progress self._heartbeat_count = 1 self._heartbeat_stack = st self._heartbeat_time = get_ion_ts() ...
time = get_ion_ts() self._heartbeat_stack = st else: self._heartbeat_op = None self._heartbeat_count = 0 #log.debug("%s %s %s", listeners_ok, ctrl_thread_ok, heartbeat_ok) return (listeners_ok, ctrl_thread_ok, heartbeat_ok) @property ...
joedeller/pymine
whereamiV2.py
Python
mit
3,643
0.000549
#! /usr/bin/python # Joe Deller 2014 # Finding out where we are in minecraft # Level : Beginner # Uses : Libraries, variables, functions # Minecraft worlds on the Raspberry Pi are smaller than # other minecraft worlds, but are still pretty big # So one of the first things we need to learn to do # is find out where w...
about is the spacing # Notice playerPos has four spaces before it # This means that it is "inside" the loop # Python is very fussy about spaces, something we will be seeing again and again # However,comments do not care about spaces while True: myLocation = mc.player.getTilePos() # myLocation is variable that...
se them with postToChat() we need to change them # from numbers, into characters - called a string # There are several ways of doing this, for now we will use a command # called str , which takes a number and hands back a string # of characters. Although to us there isn't any apparent difference # ...
torbjoernk/pySDC
examples/advection_2d_explicit/playground.py
Python
bsd-2-clause
2,543
0.009044
from pySDC import CollocationClasses as collclass import numpy as np from ProblemClass import sharpclaw #from examples.sharpclaw_burgers1d.TransferClass import mesh_to_mesh_1d from pySDC.datatype_classes.mesh import mesh, rhs_imex_mesh from pySDC.sweeper_classes.imex_1st_order import imex_1st_order import pySDC.Meth...
g.norm( # uex.values,
np.inf))) fig = plt.figure(figsize=(8,8)) plt.imshow(uend.values[0,:,:]) # plt.plot(P.state.grid.x.centers,uend.values, color='b', label='SDC') # plt.plot(P.state.grid.x.centers,uex.values, color='r', label='Exact') # plt.legend() # plt.xlim([0, 1]) # plt.ylim([-1, 1]) plt.show()
owenmorris/pylucene
test/test_PositionIncrement.py
Python
apache-2.0
11,319
0.002297
# ==================================================================== # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
g searched term # because there exist another searched terms in the same searched # position. mq = MultiPhraseQuery()
mq.add([Term("field", "3"), Term("field", "9")], 0) hits = searcher.search(mq, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "2")) q.add(Term("field", "4")) hits = searcher.search(q, None, 1000).scoreDocs self.as...
quchunguang/test
testpy/parsetab.py
Python
mit
2,575
0.133592
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x91\x95\xa5\xf7\xe0^bz\xc0\xf4\x04\xf9Z\xebA\xba' _lr_action_items = {'NAME':([0,2,5,7,11,12,13,14,],[1,8,8,8,8,8,8,8,]),')':([3,8,9,10,16,17,18,19,20,],[-9,-10,-7,16,-8,-4,-3,-5,-6,]),'(...
on','statement',3,'p_statement_assign','D:\\repos\\test\\testpy\\testply.py',58), ('statement -> expression','statement',1,'p_statement_expr','D:\\repos\\test\\testpy\\testply.py',63), ('expression -> expression + expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',68), ('express...
sion - expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',69), ('expression -> expression * expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',70), ('expression -> expression / expression','expression',3,'p_expression_binop','D:\\repos\\test\\tes...