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
oomlout/oomlout-OOMP
old/OOMPpart_HESH_03_L_STAN_01.py
Python
cc0-1.0
241
0
import OOMP
newPart = OOMP.oompItem(9019) newPart.addTag("oompType", "HESH") newPart.addTag("oompSize", "03") newP
art.addTag("oompColor", "L") newPart.addTag("oompDesc", "STAN") newPart.addTag("oompIndex", "01") OOMP.parts.append(newPart)
braingineer/baal
baal/structures/gist_trees.py
Python
mit
54,149
0.005522
""" Derivation and Elementary Trees live here. """ from __future__ import print_function from baal.structures import Entry, ConstituencyTree, consts from baal.semantics import Predicate, Expression from collections import deque from copy import copy, deepcopy from math import floor, ceil try: input = raw_input ex...
self.frontier[0]) return
self.frontier[0] @property def right_frontier(self): l, r = self.frontier self.frontier = (l, r+self.frontier_increment) assert self.frontier[1] < ceil(self.frontier[1]) return self.frontier[1] def sibling_increment(self, left=True): l, r = self.frontier if ...
qe-team/marmot
marmot/representations/pos_representation_generator.py
Python
isc
2,447
0.002452
from subprocess import Popen import os import time from marmot.representations.representation_generator import RepresentationGenerator from marmot.experiment.import_utils import mk_tmp_dir class POSRepresentationGenerator(RepresentationGenerator): def _get_random_name(self, suffix=''): return 'tmp_'+suf...
random_name('tag')) tmp_tagged = open(tmp_tagged_name, 'wr+') tagger_call = Popen([tagger, '-token', par_file], stdin=tmp_tok, stdout=tmp_tagged) tagger_call.wait() tmp_tagged.seek(0) # remove sentence markers, restore sentence structure output = [] cur_sentence ...
d_tag = line[:-1].decode('utf-8').strip().split('\t') # each string has to be <word>\t<tag> # TODO: if it's not of this format, it could be the end of sequence (empty string) or an error if len(word_tag) != 2: continue if word_tag[0] == 'SentenceEndMarker'...
fanout/pysmartfeed
test.py
Python
mit
542
0.01845
import sys import json import smartfeed.django base = sys.argv[1] command =
sys.argv[2] db = smartfeed.django.get_default_model() if command == 'add': data = json.loads(sys.argv[3]) id = sys.argv[4] if len(sys.argv) >= 5 else None db.add(base, data, id=id) elif command == 'del': id = sys.argv[3] db.delete(base, id) elif command == 'exp': ttl = int(sys.argv[3]) db.clear_expired(base, t...
orted command')
duyuan11/glumpy
examples/transform-pan-zoom.py
Python
bsd-3-clause
1,497
0.007348
#! /usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------...
py.tr
ansforms import PanZoom, Position vertex = """ attribute vec2 position; attribute vec2 texcoord; varying vec2 v_texcoord; void main() { gl_Position = <transform>; v_texcoord = texcoord; } """ fragment = """ uniform sampler2D texture; varying vec2 v_texcoord; void m...
btian/market_correlator
extract_symbols.py
Python
bsd-3-clause
2,097
0.013829
#!/usr/bin/env python # Copyright (c) 2014, Bo Tian <[email protected]> # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, ...
conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of it...
utors may # be used to endorse or promote products derived from this software without specific # prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AN...
steventimberman/masterDebater
venv/lib/python2.7/site-packages/haystack/admin.py
Python
mit
6,567
0.002284
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from django.contrib.admin.options import ModelAdmin, csrf_protect_m from django.contrib.admin.views.main import SEARCH_VAR, ChangeList from django.core.exceptions import PermissionDenied from django.core.paginator imp...
self.action_form(auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) else: action_form = None selection_note = ungettext('0 of %(count)d selected', 'of %(count)d selected', len(changelist.result_list)) selection_note_all = u...
'module_name': force_text(self.model._meta.verbose_name_plural), 'selection_note': selection_note % {'count': len(changelist.result_list)}, 'selection_note_all': selection_note_all % {'total_count': changelist.result_count}, 'title': changelist.title, 'is_pop...
yelongyu/chihu
app/main/__init__.py
Python
gpl-3.0
338
0.002959
# -*- coding:
utf-8 -*- from flask import Blueprint from ..models import Permission main = Blueprint('main', __name__) from . import views, errors, my_test # app_context_processor # let the variable Permission can ac
cessed by all templates @main.app_context_processor def inject_permissions(): return dict(Permission=Permission)
sileht/python-gnocchiclient
gnocchiclient/osc.py
Python
apache-2.0
1,874
0
# Copyright 2014 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 # # Unless required by applicable law or agreed to in writ...
ermissions and limitations # under the License. from osc_lib import utils DEFAULT_METRICS_API_VERSION = '1' API_VERSION_OPTION = 'os_metrics_api_version' API_NAME = "metric" API_VERSIONS = { "1": "gnocchiclient.v1.client.Client", } def make_client(instance): """Returns a metrics service client.""" vers...
nt = utils.get_client_class( API_NAME, version, API_VERSIONS) # NOTE(sileht): ensure setup of the session is done instance.setup_auth() return gnocchi_client(session=instance.session, adapter_options={ 'interface': instance.inte...
georgecpr/openthread
tests/scripts/thread-cert/Cert_9_2_13_EnergyScan.py
Python
bsd-3-clause
4,676
0.001283
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
get_addr64()) self.nodes[ED1].enable_whitelist() def tearDown(self): for node in list(self.nodes.values()): node.stop() del self.nodes del self.simulator def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.no...
'router') self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') self.nodes[ED1].start() self.simulator.go(5) self.assertEqual(self....
eri-trabiccolo/exaile
plugins/screensaverpause/__init__.py
Python
gpl-2.0
3,410
0.005279
# screensaverpause - pauses Exaile playback on screensaver activation # Copyright (C) 2009-2011 Johannes Sasongko <[email protected]> # # 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 v...
r_changes=True) except dbus.DBusException: continue break else: return None assert proxy interface = dbus.Interface(proxy, service['dbus_interface']) mainloop = glib.MainLoop() def active_changed(new_value): if not new_value: mainloop.quit() ...
ce.connect_to_signal('ActiveChanged', screensaver_active_changed) # For some reason Lock never returns. interface.Lock(ignore_reply=True) mainloop.run() if __name__ == '__main__': test() # vi: et sts=4 sw=4 tw=80
DavidLi2010/ramcloud
scripts/objectsize_scale.py
Python
isc
2,086
0
#!/usr/bin/env python # Copyright (c) 2011 Stanford University # # Permission to use, copy, modify, and distri
bute 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 THE AUTHOR(S) DISCLAIM ALL WARRANTIES # WITH REGAR
D TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOU...
XDSETeamA/XD_SE_TeamA
team9/1/Sharing/manage.py
Python
mit
250
0
#!/usr/bin/env python import os
import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sharing.settings") from django.core.management import execute_from_command_line execute_from_command_l
ine(sys.argv)
cloudbase/maas
src/maasserver/tests/test_preseed.py
Python
agpl-3.0
25,940
0.000578
# Copyright 2012, 2013 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Test `maasserver.preseed` and related bits and bobs.""" from __future__ import ( absolute_import, print_function, unicode_literals, ) str = None __metac...
If content is not provid
ed, a random content # will be put inside the template. path = os.path.join(sel
eggplantbren/Oscillations
StateSpace/Python/Oscillator.py
Python
gpl-3.0
2,171
0.03731
import numpy as np import numpy.random as rng class Oscillator: """ A point in phase space for an oscillator. """ def __init__(self, state, omega=1., tau=1., beta=1.): """ Constructor: takes initial yition and velocity as argument. Sets the time to zero """ self.state = state self.omega, self.tau, self...
, dt) self.state += dt/6.*(f1 + 2*f2 + 2*f3 + f4) self.time += dt if __name__ == '__main__': import matplotlib.pyplot as plt # Initial conditions oscillator = Oscillator(np.array([0., 0.])) # Timestep dt = 0.01 steps = 100000 # Take this many steps skip = 100 # Store and plot results this often keep...
mpty((steps/skip, 3)) # Store results in here # Columns: time, yition, vocity plt.ion() # Turn "interactive mode" for plotting on, so plots # can update without the user having to close the window plt.hold(False) # Clear the plot every time we plot something new # Main loop for i in xrange(0, steps): #...
bearstech/ansible
lib/ansible/modules/cloud/rackspace/rax_mon_notification.py
Python
gpl-3.0
5,164
0.001356
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], ...
description: - Dictionary of key-value pairs used to initialize the notification. Required keys and meanings vary with notification type. See http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/ service-notification-types-crud.html for details. required: true author: Ash Wilson extends...
tasks: - name: Email me when something goes wrong. rax_mon_entity: credentials: ~/.rax_pub label: omg type: email details: address: [email protected] register: the_notification ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False from ansi...
LLNL/spack
var/spack/repos/builtin/packages/r-circstats/package.py
Python
lgpl-2.1
898
0.002227
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See t
he top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import * class RCircstats(RPackage): """Circular Statistics, from "Topics in Circular Statistics" (2001) Circular Statistics, from "Topics in Circular Statistics" (2001) S. Rao Jammalamadaka and A. SenGupta, World Scientific.""" homepage = "https://cloud.r-project.org/package=CircStats" ...
ibc/MediaSoup
worker/deps/gyp/test/variables/filelist/gyptest-filelist.py
Python
isc
697
0.004304
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test variable expansion of '<|(list.txt ...)' syntax commands. """ import os import sys import TestGyp test = TestGyp.TestGyp() CHDI...
'src' test.run_gyp('filelist2.gyp', chdir=CHDIR) test.build('filelist2.gyp', 'foo', chdir=CHDIR) contents = test.read('src/dummy_foo').replace('\r', '') expect = '
John\nJacob\nJingleheimer\nSchmidt\n' if not test.match(contents, expect): print("Unexpected contents of `src/dummy_foo'") test.diff(expect, contents, 'src/dummy_foo') test.fail_test() test.pass_test()
kytos/kytos
kytos/core/napps/base.py
Python
mit
9,959
0
"""Kytos Napps Module.""" import json import os import re import sys import tarfile import urllib from abc import ABCMeta, abstractmethod from pathlib import Path from random import randint from threading import Event, Thread from kytos.core.events import KytosEvent from kytos.core.logs import NAppLog __all__ = ('Kyt...
n.dumps(self.__dict__) d
ef match(self, pattern): """Whether a pattern is present on NApp id, description and tags.""" try: pattern = '.*{}.*'.format(pattern) pattern = re.compile(pattern, re.IGNORECASE) strings = [self.id, self.description] + self.tags return any(pattern.match(st...
IntegratedAlarmSystem-Group/ias-webserver
tickets/migrations/0009_auto_20181105_2039.py
Python
lgpl-3.0
383
0.002611
# Generated by Django 2.0.8 on 2018
-11-05 20:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tickets', '0008_auto_20180730_2035'), ] operations = [ migrations.AlterM
odelOptions( name='ticket', options={'default_permissions': ('add', 'change', 'delete', 'view')}, ), ]
kura-pl/fast_polls
polls/urls.py
Python
mit
583
0.001715
from django.conf.urls imp
ort url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)$', views.vote, name='vote'), url(r'^(?P<question_id>[0-9]+)/results$', views.results, name='results'), url(r'^add$', views.add, name='add'), url(r'^check$', views.ch...
get_random'), url(r'^faq$', views.get_faq, name='get_faq'), ]
tonyseek/python-stdnum
stdnum/hr/__init__.py
Python
lgpl-2.1
870
0
# __init__.py - collection of Croatian numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This
library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser Gen
eral Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICUL...
wiheto/teneto
test/plot/test_plot.py
Python
gpl-3.0
640
0
import teneto import matplotlib.pyplot as plt def test_sliceplot(): G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wu') fig, ax = plt.subplots(1) ax = teneto.plot.slice_plot(G, ax) plt.close(fig) def test_circleplot(): G = teneto.generatenetwork.rand_binomial([4, 2], 0.5,
'graphlet', 'wd') fig, ax = plt.subplots(1) ax = teneto.plot.circle_plot(G.mean(axis=-1), ax) plt.close(fig) def test_stackplot(
): G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'contact', 'wd') fig, ax = plt.subplots(1) ax = teneto.plot.graphlet_stack_plot(G, ax, q=1) plt.close(fig)
kbase/narrative
kbase-extension/ipython/profile_default/ipython_config.py
Python
mit
20,674
0.000532
# Configuration file for ipython. c = get_config() # noqa: F821 c.Completer.use_jedi = False # ------------------------------------------------------------------------------ # InteractiveShellApp configuration # ------------------------------------------------------------------------------ # A Mixin for application...
e matplotlib for interactive use with the default matplotlib backend. # c.TerminalIPythonApp.matplotlib = None # If a command or file is given via the command-line, e.g. 'ipython foo.py', # start an interactive shell after executing the file or command. # c.TerminalIPythonApp.force_interact = False # If true, IPython...
o the user namespace. # c.TerminalIPythonApp.pylab_import_all = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This option can also be specified through the environment # variable IPYTHONDIR...
hatbot-team/hatbot_resources
preparation/lang_utils/__init__.py
Python
mit
74
0.013514
__author__ = 'moskupols'
__all__ = ['morphology', 'cognates', 'pymys
tem']
JianmingXia/StudyTest
KnowledgeQuizTool/MillionHeroes/baiduSearch/get.py
Python
mit
277
0
import requests __url = 'http://www.baidu.com/s?wd=' # 搜索请求网址 def page(word): r = requests.get(__url + word) if r.status_code == 200: # 请求错误(不是200)
处理 return r.text else: print(r.status_code)
return False
calandryll/transcriptome
scripts/old/quality_control3.py
Python
gpl-2.0
1,659
0.011453
#!/usr/bin/python -tt # Updated version of clipping adapters from sequences # Used cutadapt on combined sequences and removes first 13 bases with fastx_clipper # Website: https://code.google.com/p/cutadapt/ # Updated on: 09/26/2013 # Import OS features to run external programs import os import glob # Directories for ...
ple_name = os.path.splitext(os.path.basename(fastq_orig[files]))[0] # Remove adapters from sequences and keep score above 30, with a min length of 51 # Any other sequences will be discarded. This may be modified in future to see what the impact # of removal of lower sequences yields. fastq_tmp = output_dir + fast...
me + "_filtered.fastq" print "Running quality filter of 20 score, 100%..." os.system("fastq_quality_filter -v -Q 32 -q 20 -p 100 -i %s -o %s >> %s" % (fastqfile_in, fastq_tmp, log_out)) print "Removing artifacts..." os.system("fastx_artifacts_filter -v -Q 32 -i %s -o %s >> %s" % (fastq_tmp, fastq_out, log_out)) os...
VectorBlox/PYNQ
python/pynq/iop/tests/test__iop.py
Python
bsd-3-clause
3,522
0.012493
# Copyright (c) 2016, Xilinx, 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of ...
ARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHER...
flacjacket/qtile
libqtile/scripts/qtile_cmd.py
Python
mit
6,464
0.000464
#!/usr/bin/env python # # Copyright (c) 2017, Piotr Przymus # # 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, modi...
exit() for cmd in cmds: doc_
args = get_formated_info(obj, cmd) pcmd = prefix + cmd max_cmd = max(len(pcmd), max_cmd) output.append([pcmd, doc_args]) # Print formatted output formating = "{:<%d}\t{}" % (max_cmd + 1) for line in output: print(formating.format(line[0], line[1])) def get_object(argv): ...
daniestevez/gr-satellites
python/ccsds/telemetry_packet_reconstruction.py
Python
gpl-3.0
2,817
0.00284
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Athanasios Theocharis <[email protected]> # This was made under ESA Summer of Code in Space 2019 # by Athanasios Theocharis, mentored by Daniel Estevez # # This file is part of gr-satellites # # SPDX-License-Identifier: GPL-3.0-or-later # from gnuradio...
(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = bytearray(pmt.u8vector_elements(msg)) size = len(packet) - 6 try: header = telemetry.PrimaryHeader.parse(packet[:])
if header.ocf_flag == 1: size -= 4 except: print("Could not decode telemetry packet") return parsed = telemetry.FullPacket.parse(packet[:], size=size) payload = parsed.payload #The number 6 is used here, because that's the length of the Primary H...
japsu/django-selectreverse
selectreverse/tests/models.py
Python
bsd-2-clause
1,338
0.008969
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from selectreverse.utils import ReverseManager class Building(models.Model): number = models.IntegerField() owners = models.ManyToManyField('Owner') objects = models....
reignKey(ContentType) object_id =
models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class Bookmark(models.Model): url = models.URLField() tags = generic.GenericRelation(TaggedItem) objects = models.Manager() reversemanager = ReverseManager({'gtags': 'tags'})
telefonicaid/fiware-sdc
test/acceptance/e2e/uninstall_product/feature/terrain.py
Python
apache-2.0
3,017
0.002653
# -*- coding: utf-8 -*- # Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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://w...
t ProvisioningSteps from commons.rest_utils import RestUtils from commons.con
figuration import CONFIG_VM_HOSTNAME from commons.fabric_utils import execute_chef_client, execute_puppet_agent, remove_chef_client_cert_file, \ execute_chef_client_stop, execute_puppet_agent_stop, remove_puppet_agent_cert_file, remove_all_generated_test_files, \ remove_puppet_agent_catalog provisioning_steps ...
mediatum/mediatum
core/metatype.py
Python
gpl-3.0
13,830
0.000723
""" mediatum - a multimedia content repository Copyright (C) 2007 Arne Seifert <[email protected]> Copyright (C) 2007 Matthias Kramm <[email protected]> Copyright (C) 2013 Iryna Feuerstein <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Gene...
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/>. """ from warnings import warn class Cont...
user=None, ip=""): if collection is not None: warn("collections argument is deprecated, use container", DeprecationWarning) if container is not None: raise ValueError("container and collection cannot be used together") container = collection self.fiel...
parpg/parpg
parpg/behaviours/npc.py
Python
gpl-3.0
4,169
0.002639
# This file is part of PARPG. # PARPG 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. # PARPG is distributed in the hope ...
e._AGENT_STATE_IDLE self.animate('stand') elif self.state == base._AGENT_STATE_IDLE: if self.wanderCounter > self.wanderRate: self.wanderCounter = 0 self.state = base._AGENT_STATE_WANDER else: self.wanderCounter += 1 ...
E_WANDER: self.wander(self.target_loc) self.state = base._AGENT_STATE_NONE elif self.state == base._AGENT_STATE_TALK: self.animate('stand', self.pc.getLocation()) def wander(self, location): """Nice slow movement for random walking. @type loca...
luosch/leetcode
python/Next Permutation.py
Python
mit
459
0.002179
class Solution(object): def nextPermutation(self, nums): cursor = -1 for i in range(len(nums) - 1, 0, -1): if nums[i - 1] < nums[i]: curso
r = i - 1 break for i in range(len(nums) - 1, -1, -1): if nums[i] > nums[cursor]: nums[i], nums[cursor] = nums[cursor], nums[i]
nums[cursor + 1:] = sorted(nums[cursor + 1:]) break
MakarenaLabs/Orator-Google-App-Engine
orator/schema/grammars/__init__.py
Python
mit
206
0
# -*- coding: utf-8 -*- from .grammar import SchemaGrammar from .sq
lite_grammar import SQLiteSchemaGrammar from .postgres_grammar import PostgresSchemaGrammar from .mysql_grammar import MySql
SchemaGrammar
leftaroundabout/pyunicorn
tests/test_core/TestResitiveNetwork-circuits.py
Python
bsd-3-clause
6,379
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2014 SWIPO Project # # Authors (this file): # Stefan Schinkel <stefan.sch
[email protected]> """ Provides sanity checks for basic for parallel and serial circiuts. """ import numpy as np import networkx as nx from pyunicorn import ResNetwork from .ResistiveNetwork_utils import * debug = 0 """ Test for basic sanity, pa
rallel and serial circiuts """ def testParallelTrivial(): r""" Trivial parallel case: a) 0 --- 1 --- 2 /---- 3 ---\ b) 0 --- 1 --- 2 c) /---- 3 ---\ 0 --- 1 --- 2 \____ 4 ___/ ER(a) = 2*ER(b) = 3*ER(c) """ nws = [] # construct nw1 idI, idJ = [0, 1], [1...
thiagoald/hardmob_information_extractor
sources/generate_sentiments.py
Python
mit
1,731
0.006932
import requests import json NL_KEY = '*' TL_KEY = '*' def translate(text): tmp_payload = {"q": text, "target": "en"} s = requests.post('https://translation.googleapis.com/language/translate/v2?key=' + TL_KEY, json=tmp_payload) data = s.json()['data']['translations'][0] return data['translatedText'] d...
on') as json_data: objs = json.load(json_data) newobjs = [] amt = len(objs) for obj in objs: comments = obj['comments'] scores = [] tot_score = 0 print "for " + obj['hardmob_link'] + ":" try: for comment in com...
iment']['score'] scores.append(score) tot_score += score obj['scores'] = scores obj['avg_score'] = tot_score/int(len(scores)) newobjs.append(obj) except: print "error found" print "remaining: ...
gary-pickens/HouseMonitor
housemonitor/outputs/zigbee/test/zigbeeoutputstep_test.py
Python
mit
1,738
0.021864
''' Created on Mar 8, 2013 @author: Gary ''' import unittest from housemonitor.outputs.zigbee.zigbeecontrol import ZigBeeControl from housemonitor.outputs.zigbee.zigbeeoutputstep import ZigBeeOutputStep from housemonitor.outputs.zigbee.zigbeeoutputthread import ZigBeeOutputThread from housemonitor.lib.hmqueue import H...
k, MagicMock, patch from housemonitor.lib.common import Common import logging.config class Test( unittest.TestCase ): logger = logging.getLogger( 'UnitTest' ) def setUp( self ): logging.config.fileConfig( "unittest_logging.conf" ) def tearDown( self ): pass def test_logger_name( se...
= HMQueue() zig = ZigBeeOutputStep( queue ) self.assertEqual( Constants.LogKeys.outputsZigBee, zig.logger_name ) def test_topic_name( self ): queue = HMQueue() zig = ZigBeeOutputStep( queue ) self.assertEqual( Constants.TopicNames.ZigBeeOutput, zig.topic_name ) def tes...
tallessa/tallessa-backend
tallessa_backend/management/commands/setup.py
Python
agpl-3.0
1,317
0.000759
import logging from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command from
django.core.management.base import BaseCommand from tallessa.utils import log_get_or_create # usually you should getLogger(__name__) but we are not under the tallessa namespace right now logger = logging.getLogger('tallessa') class Command(BaseCommand): def handle(self, *args, **options): management_c...
.append((('setup_default_team',), dict())) for pargs, opts in management_commands: logger.info("** Running: %s", pargs[0]) call_command(*pargs, **opts) if settings.DEBUG: user, created = User.objects.get_or_create( username='mahti', d...
henrikau/metadoc
client/allocations/entries.py
Python
gpl-3.0
2,825
0.004248
# -*- coding: utf-8 -*- # # allocations/entries.py is part of MetaDoc (Client). # # All of MetaDoc 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 opti...
etails. # # You should have received a copy of the GNU General Public License # along with MetaDoc. If not, see <http://www.gnu.org/licenses/>. # import metaelement class AllocationEntry(metaelement.MetaElement): """AllocationEntry - Allocation for specific projects. """ xml_tag_name = "all_entry" def _...
, period): """ Defines attributes for all_entry XML elements. @param account_nmb: Account number for allocation. @type account_nmb: String @param volume: The amount of parameter metric. @type volume: String @param metric: Measurement of parameter volume. ...
daafgo/Edx_bridge
xapi-bridge/__main__.py
Python
apache-2.0
3,433
0.034081
import sys, os, json, requests, threading from urlparse import urljoin from pyinotify import WatchManager, Notifier, EventsCodes, ProcessEvent import converter, settings class QueueManager: ''' Manages the batching and publishing of statements in a thread-safe way. ''' def __init__(self): self.cache = [] self...
for e
in evts: try: evtObj = json.loads(e) except ValueError as err: print 'Could not parse JSON for', e continue xapi = converter.to_xapi(evtObj) if xapi != None: for i in xapi: self.publish_queue.push(i) print '{} - {} {} {}'.format(i['timestamp'], i['actor']['name'], i['ver...
seiji56/rmaze-2016
logic_code/last_ver/sim/herkulex.py
Python
gpl-3.0
23,289
0.004122
#!/usr/bin/env python2.7 """ @package: pyHerkulex @name: herkulex.py @author: Achu Wilson ([email protected]), Akhil Chandran ([email protected]) @version: 0.1 This is a python library for interfacing the Herkulex range of smart servo motors manufactured by Dongbu Robotics. The library was created by ...
nd_data(dat
a): """ Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port """ datalength = len(data) csm1 = checksum1(data, datalength) csm2 = checksum2(csm1) dat...
zguangyu/rts2
python/rts2/target.py
Python
gpl-2.0
1,526
0.026212
# Library for RTS2 JSON calls. # (C) 2012 Petr Kubanek, Institute of Physics # # 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 2.1 of the License, or (at your option) any...
roxy().loadJson('/api/tbyid',{'id':int(name)})['d'] except ValueError: return json.getProxy
().loadJson('/api/tbyname',{'n':name})['d'] def create(name,ra,dec): return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id']
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/skimage/feature/tests/test_peak.py
Python
gpl-3.0
18,709
0.001604
import numpy as np import unittest from skimage._shared.testing import assert_array_almost_equal from skimage._shared.testing import assert_equal from scipy import ndimage as ndi from skimage.feature import peak np.random.seed(21) class TestPeakLocalMax(): def test_trivial_case(self): trivial = np.zeros(...
rt len(peaks) == 4 def test_sorted_peaks(self): image = np.zeros((5, 5), dtype=np.uint8) image[1, 1] = 20 image[3, 3] = 10 peaks = peak.peak_local_max(image, min_distance=1) assert peaks.tolist() == [[3, 3], [1, 1]] image = np.zeros((3, 10)) image[1, (1, 3, ...
1, 3], [1, 1]] def test_num_peaks(self): image = np.zeros((7, 7), dtype=np.uint8) image[1, 1] = 10 image[1, 3] = 11 image[1, 5] = 12 image[3, 5] = 8 image[5, 3] = 7 assert len(peak.peak_local_max(image, min_distance=1, threshold_abs=0)) == 5 peaks_lim...
hsoft/qtlib
radio_box.py
Python
bsd-3-clause
2,903
0.007234
# Created On: 2010-06-02 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCo...
button.setParent(None) del self._buttons[len(self._labels):] to_add = self._labels[len(self._buttons):] for _ in to_add: button = QRadioButton(self) self._buttons.append(button) self._layout.addWidget(button) button.toggled.connect(self
.buttonToggled) if self._spacer is not None: self._layout.addItem(self._spacer) if not self._buttons: return for button, label in zip(self._buttons, self._labels): button.setText(label) self._update_selection() def _update_selection(self): ...
acs-um/gestion-turnos
apps/clientes/migrations/0003_auto_20150605_2119.py
Python
mit
1,158
0.000864
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('clientes', '0002_auto_20150530_1324'), ...
('documento', models.IntegerField()), ('telefono', models.IntegerField()), ('obrasocial', models.CharField(max_length=50)), ('email', models.EmailField(max_length=75)),
('cliente', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.DeleteModel( name='Cliente', ), ]
AdrianRibao/django-users
django_users/templatetags/users.py
Python
bsd-3-clause
422
0.014218
# -*-
coding: utf-8 -*- from django import template from django_users.forms import CreateUserForm #from django.utils.translation import ugettext as _ register = template.Library() @register.inclusion_tag('users/templatetags/registration.html', takes_context = True) def registration_form(context, form=None, *args, **kwargs...
form': form, }
pombredanne/milk
milk/tests/test_nfoldcrossvalidation_regression.py
Python
mit
10,055
0.001392
import numpy as np from milk.measures.nfoldcrossvalidation import nfoldcrossvalidation, foldgenerator # Regression test in 2011-01-31 def test_getfoldgenerator(): labels = np.array([ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7...
35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 3
7, 37, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 42, 4...
Panda3D-google-code-repositories/naith
game/plugins/simpleweapon/simpleweapon.py
Python
apache-2.0
7,962
0.017458
# -*- coding: utf-8 -*- # Copyright Tom SF Haines # # 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 ag...
nd the ray used for shooting track this - allows for gun jitter, kick back etc... parent = xml.find('parent') self.gunView.reparentTo(manager.get(parent.get('plugin')).getNode(parent.get('node')))
# Create a ray cast to detect what the player is looking at... and what will be shot... self.space = manager.get('ode').getSpace() if self.ray!=None: self.ray.destroy() self.ray = OdeRayGeom(100.0) self.ray.setCategoryBits(BitMask32(0xfffffffe)) self.ray.setCollideBits(BitMask32(0xffff...
shivamMg/malvo
teams/migrations/0008_auto_20160305_1811.py
Python
gpl-3.0
546
0.001832
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-03-05 18:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): depen
dencies = [ ('teams', '0007_auto_20160305_1726'), ] operations = [ migrations.AlterField( model_name='team', name='lang_pref', field=models.CharField(choices
=[('C', 'C'), ('J', 'Java')], default='0', max_length=1, verbose_name='programming language preference'), ), ]
cherrishes/weilai
xingxing/common/mqtt_helper.py
Python
apache-2.0
1,402
0.001664
import uuid from paho.mqtt import publish from paho.mqtt.client import MQTTv31 from conf.mqttconf import * def send(msg, user_list, qos=2, retain=False): """ 发布mqtt消息 :param msg:消息内容,可以是字
符串、int、bytearray :param user_list: 用户列表数组(不带前缀的),例如:["zhangsa
n","lilei"] :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一次) :param retain:设置是否保存消息,为True时当订阅者不在线时发送的消息等上线后会得到通知,否则只发送给在线的设备 :return: """ auth = {"username": MOSQUITTO_PUB_USER, "password": MOSQUITTO_PUB_PWD} client_id = MOSQUITTO_PREFIX + str(uuid.uuid1()) msgs = [] for i in user_list: pr...
Andy-Thornton/drupal-security-updates
security-updates.py
Python
gpl-3.0
1,721
0.006973
#!/usr/bin/env python import subprocess, os, sys import colorama from colorama import Fore, Back, Style # Store paths and connection info sourcetree = "/home/flux/Projects/hackday" gitlabapi = "" drupalbootstrap = sourcetree + "/drupal/includes/bootstrap.inc" contrib = sourcetree + "/all/modules/contrib" rpmmodules = ...
yle.RESET_ALL dirs
= os.listdir(modpath) print Fore.GREEN for module in dirs: info = modpath + "/" + module + "/" + module + ".info" try: with open(info, 'r') as searchfile: for line in searchfile: if """version = """ in line: moduleversion ...
MCLConsortium/mcl-site
src/jpl.mcl.site.knowledge/src/jpl/mcl/site/knowledge/organfolder.py
Python
apache-2.0
544
0.001845
# encoding: utf-8 u'''MCL — Organ Folder''' from ._base import IIngestableFolder, Ingestor, IngestableFolderView from .in
terfaces imp
ort IOrgan from five import grok class IOrganFolder(IIngestableFolder): u'''Folder containing body systems, also known as organs.''' class OrganIngestor(Ingestor): u'''RDF ingestor for organs.''' grok.context(IOrganFolder) def getContainedObjectInterface(self): return IOrgan class View(Ing...
p12tic/awn-extras
shared/python/awnmediaplayers.py
Python
gpl-2.0
28,094
0.003132
# !/usr/bin/python # Copyright (c) 2007 Randal Barlow <im.tehk at gmail.com> # # 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 2 of the License, or (at your option) any ...
_name = "XMMS2" elif bus
_obj.NameHasOwner('org.mpris.amarok') == True: player_name = "Amarok" elif bus_obj.NameHasOwner('org.mpris.aeon') == True: player_name = "Aeon" elif bus_obj.NameHasOwner('org.mpris.dragonplayer') == True: player_name = "DragonPlayer" elif bus_obj.NameHasOwner('org.freedesktop.MediaPl...
indexofire/gork
src/gork/application/feedz/processors/__init__.py
Python
mit
91
0
# -*- coding: ut
f-8 -*- from feedz.processors.content_filter import ContentFilterPro
cessor
cchurch/ansible-modules-core
cloud/amazon/rds_param_group.py
Python
gpl-3.0
10,548
0.005973
#!/usr/bin/python # This file is part of Ansible # # Ansible 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
our option) any later version. # # Ansible 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 Gene
ral Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: rds_param_group version_added: "1.5" short_description: manage RDS parameter groups description: - Creates, ...
h-hwang/octodns
tests/test_octodns_provider_dnsimple.py
Python
mit
6,915
0
# # # from __future__ import absolute_import, division, print_function, \ unicode_literals from mock import Mock, call from os.path import dirname, join from requests import HTTPError from requests_mock import ANY, mock as requests_mock from unittest import TestCase from octodns.record import Record from octodns...
equest = Mock(return_value=resp) # non-existant domain, create everything resp.json.side_effect = [ DnsimpleClientNotFound, # no zone in populate DnsimpleClientNotFound,
# no domain during apply ] plan = provider.plan(self.expected) # No root NS, no ignored n = len(self.expected.records) - 2 self.assertEquals(n, len(plan.changes)) self.assertEquals(n, provider.apply(plan)) provider._client._request.assert_has_calls([ ...
archlinux/archweb
public/tests.py
Python
gpl-2.0
1,786
0.00056
from django.test import TestCase class PublicTest(TestCase): fixtures = ['main/fixtures/arches.json', 'main/fixtures/repos.json', 'main/fixtures/package.json', 'main/fixtures/groups.json', 'devel/fixtures/staff_groups.json'] def test_index(self): response = self.client...
.status_code, 200) def test_master_keys_json(self): response = self.client.get('/master-keys/json/') self.assertEqual(response.status_c
ode, 200) def test_feeds(self): response = self.client.get('/feeds/') self.assertEqual(response.status_code, 200) def test_people(self): response = self.client.get('/people/developers/') self.assertEqual(response.status_code, 200) def test_sitemap(self): sitemaps =...
chandler14362/panda3d
direct/src/distributed/DoInterestManager.py
Python
bsd-3-clause
29,162
0.002846
""" The DoInterestManager keeps track of which parent/zones that we currently have interest in. When you want to "look" into a zone you add an interest to that zone. When you want to get rid of, or ignore, the objects in that zone, remove interest in that zone. p.s. A great deal of this code is just code moved from ...
%s, zoneIdList=%s)' % ( self.desc, self.state, self.context, self.events, self.parentId, self.zoneIdList) class InterestHandle: """This class helps to ensure that valid handles get passed in to DoInterestManager funcs""" def __init__(self, id): self._id = id def asInt(self): ret...
lf, other): if type(self) == type(other): return self._id == other._id return self._id == other def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self._id) # context value for interest changes that have no complete event NO_CONTEXT = 0 class DoInterestManager(Dire...
zhreshold/mxnet
tests/python/unittest/test_extensions.py
Python
apache-2.0
7,787
0.010659
# 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...
',['a','b'], 'optimized-0000.params') out5 = sym_block3(a_data, b_data) # check that result matches one exec
uted by MXNet assert_almost_equal(out[0].asnumpy(), out5[0].asnumpy(), rtol=1e-3, atol=1e-3)
manassolanki/erpnext
erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py
Python
gpl-3.0
6,558
0.02516
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart...
ue
for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard if len(...
kiwiheretic/logos-v2
reddit/migrations/0021_redditcredentials_reddit_username.py
Python
apache-2.0
440
0
# -*- coding: utf-8 -
*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reddit', '0020_
pendingsubmissions_submitted'), ] operations = [ migrations.AddField( model_name='redditcredentials', name='reddit_username', field=models.CharField(max_length=50, null=True), ), ]
yubchen/Qlinter
sublimelinter.py
Python
mit
15,716
0.001145
# # sublimelinter.py # Part of SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ryan Hileman and Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter3 # License: MIT # """This module provides the SublimeLinter plugin class and supporting methods.""" import os import...
and not os.path.exists(view.file_name()) ): return True else: return False def view_has_file_only_linter(self, vid): """Return True if any linters for the given view are file-only.""" for lint in persist.view_linters.get(vid, []): if ...
gin.EventListener event handlers def on_modified(self, view): """Called when a view is modified.""" if self.is_scratch(view): return if view.id() not in persist.view_linters: syntax_changed = self.check_syntax(view) if not syntax_changed:
callowayproject/django-cookiesession
example/urls.py
Python
apache-2.0
222
0.004505
from django.conf.urls.defa
ults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^login/', 'django.contrib.auth.views.login'), (r'^admin/', include(admin
.site.urls)), )
shichao-an/adium-sh
adiumsh/settings.py
Python
bsd-2-clause
1,138
0
import os from .utils import get_config PACKAGE_PATH = os.path.abspath(os.path.dirname(__file__)) REPO_PATH = os.path.join(PACKAGE_PATH, os.pardir) LOG_PATH = '~/Library/Application Support/Adium 2.0/Users/Default/Logs' LOG_PATH = os.path.expanduser(LOG_PATH) MOVED_LOG_PATH = os.path.expanduser('~/.adiumshlogs') CONF...
if default_config else None DEFAULT_CHAT = \ default_config.get('chat', None) if default_config else None EVENT_MESSAGE_RECEIVED = 'MESSAGE_RECEIVED' EVENT_MES
SAGE_SENT = 'MESSAGE_SENT' EVENT_STATUS_AWAY = 'STATUS_AWAY' EVENT_STATUS_ONLINE = 'STATUS_ONLINE' EVENT_STATUS_OFFLINE = 'STATUS_OFFLINE' EVENT_STATUS_CONNECTED = 'STATUS_CONNECTED' EVENT_STATUS_DISCONNECTED = 'STATUS_DISCONNECTED'
forestdussault/olc_webportalv2
olc_webportalv2/users/middleware.py
Python
mit
1,413
0
from django.http import HttpResponseRedirect from django.conf import settings from django.utils.deprecation import MiddlewareMixin from re import compile EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMP...
n middleware and template context processors to be loaded. You'll get an error if they aren't. """ def process_request(self, request): assert hasattr(request, 'user'), "The Login Required middleware\ requires authentication middleware to be installed. Edit your\ MIDDLEWARE_CLASSES setting to inse...
\ work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\ 'django.core.context_processors.auth'." if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(settings.LO...
Gentux/etalage
etalage/contexts.py
Python
agpl-3.0
7,875
0.009524
# -*- coding: utf-8 -*- # Etalage -- Open Da
ta POIs portal # By: Emmanuel Raviart <[email protected]> # # Copyright (C) 2011, 2012 Easter-eggs # http://gitorious.org/infos-pratiques/etalage # # This file is part of Etalage. # # Etalage is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as ...
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 program. If not, see <http://www....
alhashash/odoomrp-wip
stock_lock_lot/wizard/__init__.py
Python
agpl-3.0
288
0
# -*- codin
g: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from . import wiz_lock_
lot
candYgene/abg-ld
src/tmp/ontomap_breed.py
Python
apache-2.0
894
0.021253
#!/usr/bin/env python # # This script maps breed names to Livestock Breed Ontology (LBO) IDs. # # Input files: # ONTO.tsv with two columns: id (format: <ontology_acronym>:<term_id>) and name # pigQTLdb.tsv w
ith two columns: qtl_id and breed (comma-separated field of values) # # Output (STDOUT): # thr
ee columns separated by \t: id, name, LBO breed IDs # sep='\t' file1 ='../data/ONTO.tsv' file2 ='../data/pigQTLdb.tsv' lookup = dict() with open(file1) as fin: for ln in fin: ln = ln.rstrip() id, name = ln.split(sep) lookup[name.lower()] = id with open(file2) as fin: for ln in fin: ln =...
skibblenybbles/django-commando
commando/django/core/management/commands/sqlclear.py
Python
mit
50
0
fro
m ..sqlclear import SQLClearCommand as Command
psusloparov/sneeze
pocket/setup.py
Python
apache-2.0
492
0.014228
from setuptools import setup, find_packages setup(name='pocket
', version='0.0.0', packages=find_packages(), install_requires=['sneeze'], entry_points={'nose.plugins.sneeze.plugins.add_models' : ['pocket_models = pocket.database:add_models'], 'nose.plugins.sneeze.plugins.add_options' : ['pocket_options = pocket.log_lib:add_options'], ...
anagers' : ['pocket_manager = pocket.log_lib:TissueHandler']})
codeforamerica/pittsburgh-purchasing-suite
purchasing/conductor/manager/flow_management.py
Python
bsd-3-clause
2,911
0.002061
# -*- coding: utf-8 -*- from flask import render_template, redirect, url_for, flash, abort from purchasing.decorators import requires_roles from purchasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager im...
def flow_detail(flow_id): '''View/edit a flow's details :status 200: Render the flow edit template :status 302: Post changes to the a flow using the submitted :py:class:`~purchasing.conductor.forms.FlowForm`, redirect back to th
e current flow's detail page if successful ''' flow = Flow.query.get(flow_id) if flow: form = FlowForm(obj=flow) if form.validate_on_submit(): flow.update( flow_name=form.data['flow_name'], is_archived=form.data['is_archived'] ) ...
muchu1983/104_cameo
test/unit/test_spiderForPEDAILY.py
Python
bsd-3-clause
1,237
0.00841
# -*- coding: utf-8 -*- """ Copyright (C) 2015, MuChu Hsu Contributed by Muchu Hsu ([email protected]) This file is part of BSD license <https://opensource.org/licenses/BSD-3-Clause> """ import unittest import logging from cameo.spiderForPEDAILY import SpiderForPEDAILY """ 測試 抓取 PEDAILY """ class SpiderForPEDAILYTe...
Case): #準備 def setUp(self): logging.basicConfig(level=logging.INFO) self.spider = SpiderForPEDAILY() self.spider.initDriver() #收尾 def te
arDown(self): self.spider.quitDriver() """ #測試抓取 index page def test_downloadIndexPage(self): logging.info("SpiderForPEDAILYTest.test_downloadIndexPage") self.spider.downloadIndexPage() #測試抓取 category page def test_downloadCategoryPage(self): logging.info("Spider...
javier-ruiz-b/docker-rasppi-images
raspberry-google-home/env/lib/python3.7/site-packages/rsa/util.py
Python
apache-2.0
2,986
0.00067
# Copyright 2011 Sybren A. Stüvel <[email protected]> # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
tionParser import rsa.key def private_to_public() ->
None: """Reads a private key and outputs the corresponding public key.""" # Parse the CLI options parser = OptionParser(usage='usage: %prog [options]', description='Reads a private key and outputs the ' 'corresponding public key. Both private...
yxping/leetcode
solutions/257.Binary_Tree_Paths/AC_dfs_n.py
Python
gpl-2.0
836
0.010766
#!/usr/local/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_dfs_n.py # Create Date: 2015-08-16 10:15:54 # Usage: AC_dfs_n.py # Descripton: # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left ...
r(root.va
l)) if root.left == None and root.right == None: paths.append('->'.join(path)) dfs(root.left) dfs(root.right) path.pop() dfs(root) return paths
idrogeno/IdroMips
lib/python/Components/VfdSymbols.py
Python
gpl-2.0
4,865
0.027955
from twisted.internet import threads from config import config from enigma import eDBoxLCD, eTimer, iPlayableService import NavigationInstance from Tools.Directories import fileExists from Components.ParentalControl import parentalControl from Components.ServiceEventTracker import ServiceEventTracker from Components.Sy...
stance.getRecordings()) self.blink = not self.blink if recordings > 0: if self.blink: open("/proc/stb/lcd/powerled", "w").write("1") self.led = "1" else: open("/proc/stb/lcd/powerled", "w").write("0")
self.led = "0" elif self.led == "1": open("/proc/stb/lcd/powerled", "w").write("0") elif getBoxType() in ('dummy'): recordings = len(NavigationInstance.instance.getRecordings()) self.blink = not self.blink if recordings > 0: if self.blink: open("/proc/stb/lcd/powerled", "w").write("0") ...
mrpau/kolibri
kolibri/core/content/test/test_zipcontent.py
Python
mit
12,256
0.003264
import hashlib import os import tempfile import zipfile from bs4 import BeautifulSoup from django.test import Client from django.test import TestCase from mock import patch from ..models import LocalFile from ..utils.paths import get_content_storage_file_path from kolibri.core.auth.test.helpers import provision_devic...
'<html><head><script async src="url/url.js"></script></head></html>' ) empty_html_name = "empty.html" empty_html_str = "" doctype_name = "doctype.html" doctype = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> """
doctype_str = doctype + "<html><head><script>test</script></head></html>" html5_doctype_name = "html5_doctype.html" html5_doctype = "<!DOCTYPE HTML>" html5_doctype_str = ( html5_doctype + "<html><head><script>test</script></head></html>" ) test_name_1 = "testfile1.txt" test_str_1 = "...
d2jvkpn/bioinformatics_tools
bioparser/gff3extract_v0.9.py
Python
gpl-3.0
1,658
0.019903
import os, gzip, argparse parser = argparse.ArgumentParser(description='Extract transcript records') parser.add_argument("gff3", help="input gff3 file") parser.add_argument("-F", dest="Feature", nargs='+', required=True, help="transcript type(s) and attribution(s), " + "E.g \"-F mRNA ncRNA:ncrna_class=lncRNA\"") p...
tribution(s) of selected transcript(s)") parser.add_argument("-a", dest="attri", nargs='+', default=None, help="output attribution(s) of exon") if len(os.sys.argv) == 1: parser.print_help(); os.sys.exit(0) args = parser.parse_args() MFeature = {} for i in args.Feature: ii = i.split(":") try: MFeat...
f9 = Fx9[8].split(';'); t = Fx9[2] if t in MFeature: k = 1 if MFeature[t] != None and not any(x in MFeature[t] for x in f9): k=0 if t != 'exon' and t not in MFeature: k = 0 if k != 1: return 0 atr = args.Attri if t in MFeature else args.attri F9 = "" if atr != Non...
kasiazubielik/python_training
generator/group.py
Python
apache-2.0
1,257
0.009547
from model.group import Group import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 3 f = "data/groups.json" for o, a in o...
if o == "-n": n = int(a) elif o == "-f": f = a def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + string.punctuation + " "*10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) testdata = [Group(name="", header="", footer="")] + [ Group(name=random_string("name", 10), header=random_string("header", 20), footer=random_string("footer", 20)) for i in range(n) ] file = config_file = os.path.jo...
LAR-UFES/pppoe-plugin
pppoediplugin/CheckConnection.py
Python
gpl-3.0
2,146
0.00794
#!/usr/bin/env python3 from subprocess import getoutput import threading import time import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk as gtk from gi.repository import GLib class CheckConnection(threading.Thread): def __init__(self, pppoedi
): super(CheckConnection,self).__init__() self.pppoedi = pppoedi def run(self): super(CheckConnection,self).run() self.pppoedi.settings.active_status = False #fsyslog = open('/var/log/syslog','r') self.pppoedi.pppoedi_bus_interface.OpenSyslog() while not self...
if self.pppoedi.settings.connect_active: if ppp_status != '': if 'PAP authentication succeeded' in ppp_status and not self.pppoedi.settings.active_status: self.pppoedi.settings.active_status = True self.pppoedi.button_conn_disco...
xuleiboy1234/autoTitle
textsum/seq2seq_attention_model.py
Python
mit
13,425
0.00432
# 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...
ets, self._article_lens: article_lens,
self._abstract_lens: abstract_lens, self._loss_weights: loss_weights}) def run_decode_step(self, sess, article_batch, abstract_batch, targets, article_lens, abstract_lens, loss_weights): to_return = [self._outputs, self.global_st...
cediant/hpcservergridscheduler
CLIENT/client.py
Python
gpl-2.0
7,365
0.057298
#!/home/executor/Ice/python2.4/bin/python # Copyright (C) 2012 CEDIANT <[email protected]> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License v2 # as published by the Free Software Foundation. # # This program is distributed in the hope that it...
_percent = int(sys.argv.pop(1)) if len(sys.argv) > 1 and sys.argv[1] == "--ameba-range" : sys.argv.pop(1) ameba_range = int(sys.argv.pop(1)) if ameba_percent : ameba_range = False if len(sys.argv) > 1 and sys.argv[1] == "--suffix" : sys.argv.pop(1) header = sys.argv.pop(1) outfile = os.path.join
( outfile , header ) os.makedirs( outfile ) app = ExecClientApp() ret = app.main(sys.argv,CONFIG_FILE) sys.exit(ret)
w1ll1am23/simplisafe-python
tests/system/__init__.py
Python
mit
32
0
"""Define tes
ts for sy
stems."""
cdcf/time_tracker
app/main/errors.py
Python
bsd-3-clause
392
0
__author
__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): return render_template(
'405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
AustinRoy7/Pomodoro-timer
venv/Lib/site-packages/setuptools/ssl_support.py
Python
mit
8,130
0.001107
import os import socket import atexit import re from setuptools.extern.six.moves import urllib, http_client, map import pkg_resources from pkg_resources import ResolutionError, ExtractionError try: import ssl except ImportError: ssl = None __all__ = [ 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_avail...
name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a l
abel other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem...
nsalomonis/AltAnalyze
import_scripts/mergeFilesUnique.py
Python
apache-2.0
14,369
0.021992
import sys,string,os sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies import os.path import unique import itertools dirfile = unique ############ File Import Functions ############# def filepath(filename): fn = unique.filepath(filename) return fn def read_di...
return dir_list def returnDirectories(sub_dir): dir_list =
unique.returnDirectories(sub_dir) return dir_list class GrabFiles: def setdirectory(self,value): self.data = value def display(self): print self.data def searchdirectory(self,search_term): #self is an instance while self.data is the value of the instance files = getDirectoryFil...
CanonicalLtd/landscape-client
landscape/sysinfo/tests/test_processes.py
Python
gpl-2.0
2,217
0
import unittest from twisted.internet.defer import Deferred from landscape.lib.testing import ( FSTestCase, TwistedTestCase, ProcessDataBuilder) from landscape.sysinfo.sysinfo import SysInfoPluginRegistry from landscape.sysinfo.processes import Processes class ProcessesTest(FSTestCase, TwistedTestCase, unit...
_of_zombies(self):
"""The number of zombies is added as a note.""" self.builder.create_data(99, self.builder.ZOMBIE, uid=0, gid=0, process_name="ZOMBERS") self.processes.run() self.assertEqual(self.sysinfo.get_notes(), ["There is 1 zombie process."]) ...
nikkitan/bitcoin
test/functional/rpc_scantxoutset.py
Python
mit
13,144
0.008673
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the scantxoutset rpc call.""" from test_framework.test_framework import BitcoinTestFramework from ...
self.nodes[0].scantxoutset("st
art", [ "addr(" + addr_P2SH_SEGWIT + ")", "addr(" + addr_LEGACY + ")", "addr(" + addr_BECH32 + ")"])['total_amount'], Decimal("0.007")) assert_equal(self.nodes[0].scantxoutset("start", [ "addr(" + addr_P2SH_SEGWIT + ")", "addr(" + addr_LEGACY + ")", "combo(" + pubk3 + ")"])['total_amount'], Decimal("0.007")) ...
iandees/all-the-places
locations/spiders/petsmart.py
Python
mit
3,626
0.007722
import datetime import re import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours day_mapping = {'MON': 'Mo','TUE': 'Tu','WED': 'We','THU': 'Th', 'FRI': 'Fr','SAT': 'Sa','SUN': 'Su'} def convert_24hour(time): """ Takes 12 hour time as a string and conver...
ours = OpeningHours() days = elements.xpath('//span[@itemprop="dayOfWeek"]/text()').extract() today = (set(day_mapping) - set(days)).pop() days.remove('TODAY') days.insert(0,today) open_hours = elements.xpath('//div[@class="store-hours"]
/time[@itemprop="opens"]/@content').extract() close_hours = elements.xpath('//div[@class="store-hours"]/time[@itemprop="closes"]/@content').extract() store_hours = dict((z[0],list(z[1:])) for z in zip(days, open_hours, close_hours)) for day, hours in store_hours.items(): if 'CLOSED...
antoinecarme/pyaf
tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_Lag1Trend_Seasonal_Hour_ARX.py
Python
bsd-3-clause
165
0.048485
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['RelativeDifference'] , ['Lag1T
rend']
, ['Seasonal_Hour'] , ['ARX'] );
rbian/tp-libvirt
libvirt/tests/src/numa/numa_capabilities.py
Python
gpl-2.0
1,889
0
import logging from virttest import libvirt_xml from virttest import utils_libvirtd from virttest import utils_misc from autotest.client.shared import error def run(test, params, env): """ Test capabilities with host numa node topology """ libvirtd = utils_libvirtd.Libvirtd() libvirtd.start() ...
l = cell_list[cell_num] cpu_list_from_xml = cell_xml.cpu node_ = numa_info.nodes[cell_num] cpu_list = node_.cpus logging.debug("cell %s cpu list is %s", cell_num, cpu_list) cpu_topo_list = [] for cpu_id in cpu_
list: cpu_dict = node_.get_cpu_topology(cpu_id) cpu_topo_list.append(cpu_dict) logging.debug("cpu topology list from capabilities xml is %s", cpu_list_from_xml) if cpu_list_from_xml != cpu_topo_list: raise error.TestFail("...
xuru/pyvisdk
pyvisdk/enums/host_disk_partition_info_partition_format.py
Python
mit
247
0
#########
############################### # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum H
ostDiskPartitionInfoPartitionFormat = Enum( 'gpt', 'mbr', 'unknown', )
kurdd/Oauth
app/models.py
Python
apache-2.0
1,109
0.012624
# Define a custom User class to work with django-social-auth from django.db import models from django.contrib.auth.models import User class Task(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User) finished = models.BooleanField(default=False) shared ...
ForeignKey(User, related_name="friend_set") class CustomUserManager(models.Manager): def create_user(self, userna
me, email): return self.model._default_manager.create(username=username) class CustomUser(models.Model): username = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) objects = CustomUserManager() def is_authenticated(self): return True
omn0mn0m/JARVIS
jarvis/jarvis.py
Python
mit
3,867
0.006465
import nltk import filemanager import multiprocessing import os import ConfigParser from assistant import Assistant, Messenger from nltk.corpus import wordnet resources_dir = 'resources\\' login_creds = ConfigParser.SafeConfigParser() if os.path.isfile(resources_dir + 'login_creds.cfg'): login_creds.read(resour...
pond', verbs): if "facebook" in proper_nouns: if not login_creds.has_section('Facebook'): login_creds.add_section('Facebook') login_creds.set('Facebook', 'email', raw_input('Enter your FB email: ')) ...
ces_dir + 'login_creds.cfg', 'wb') as configfile: login_creds.write(configfile) fb_process = multiprocessing.Process(target = fb_worker, args = (login_creds.get('Facebook', 'email'), login_creds.get('Facebook', 'passwor...
mancoast/CPythonPyc_test
fail/332_test_codecs.py
Python
gpl-3.0
91,385
0.001609
import _testcapi import codecs import io import locale import sys import unittest import warnings from test import support if sys.platform == 'win32': VISTA_OR_LATER = (sys.getwindowsversion().major >= 6) else: VISTA_OR_LATER = False try: import ctypes except ImportError: ctypes = None SIZEOF_WCH...
# Feeding the previous input may not produce any ou
tput self.assertTrue(not d.decode(state[0])) # The decoder must return to the same state self.assertEqual(state, d.getstate()) # Create a new decoder and set it to the state # we extracted from the old one d = codecs.getincrementaldecod...
Blizzard/s2protocol
s2protocol/diff.py
Python
mit
2,237
0.002235
# # Protocol diffing tool from http://github.com/dsjoerg/s2protocol # # Usage: s2_cli.py --diff 38215,38749 # import sys import argparse import pprint from s2protocol.versions import build def diff_things(typeinfo_index, thing_a, thing_b): if type(thing_a) != type(thing_b): print( "typeinfo {...
_ver) count_a = len(protocol_a.typeinfos) count_b = len(protocol_b.typeinfos) print("C
ount of typeinfos: {} {}".format(count_a, count_b)) for index in range(max(count_a, count_b)): if index >= count_a: print("Protocol {} missing typeinfo {}".format(protocol_a_ver, index)) continue if index >= count_b: print("Protocol {} missing typeinfo {}".format(...
OCA/server-tools
base_report_auto_create_qweb/wizard/report_duplicate.py
Python
agpl-3.0
755
0.001325
# Authors: See README.RST for Contributors # Copyright 2015-2017 # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class IrActionsReportDuplicate(models.TransientModel): _name =
"ir.actions.report.duplicate" _description = "Duplicate Qweb report" suffix = fields.Char( string="Suffix", help="This suffix will be added to the report" ) def duplicate_report(self): self.ensure_one() active_id = self.env.context.get("active_id") model = self.env.cont...
model") if model: record = self.env[model].browse(active_id) record.with_context(suffix=self.suffix, enable_duplication=True).copy() return {}
vivaxy/algorithms
python/problems/construct_the_rectangle.py
Python
mit
598
0.001672
""" https://leetcode.com/problems/construct-the-rectangle/ https://leetcode.com/submissions/detail/107452214/ """ import math class Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ W = int(math.sqrt(area)) while area ...
s Test(unittest.TestCase): def test(self): solution = Solution() self.assertEqual(solution.constructRe
ctangle(4), [2, 2]) if __name__ == '__main__': unittest.main()
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/presets/camera/Nikon_D7000.py
Python
gpl-3.0
150
0
import bpy bpy.context.object
.data.sensor_width = 23.6 bpy.context.object.data.sensor_height = 15.6 bpy.context.object.data.sensor
_fit = 'HORIZONTAL'