code stringlengths 1 199k |
|---|
PLUGIN_NAME = 'Feat. Artists in Titles'
PLUGIN_AUTHOR = 'Lukas Lalinsky, Michael Wiencek'
PLUGIN_DESCRIPTION = 'Move "feat." from artist names to album and track titles.'
PLUGIN_VERSION = "0.1"
PLUGIN_API_VERSIONS = ["0.9.0", "0.10", "0.15"]
from picard.metadata import register_album_metadata_processor, register_track_... |
import json
import urllib2
import unittest
import argparse
import unittest
import sys
import os
sys.path.insert(1, '/home/kevin/google_appengine')
sys.path.insert(1, '/home/kevin/google_appengine/lib/yaml/lib')
sys.path.insert(1, os.getcwd() + '/../app')
from google.appengine.ext import testbed
from google.appengine.ap... |
from django.utils.encoding import smart_str
from datetime import date, datetime
from django.conf import settings
def capitalize(string):
return string[0].upper()+string[1:]
def many_to_many_display(list):
display = ""
for i, item in enumerate(list):
display += smart_str(item)
if i != len(lis... |
"""In which a mixin that allows attached metadata on a model to be
accessed in a common manner is described.
"""
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
from metadata.models.key import MetadataKey
class MetadataSubjectMixin(object):
"""Mixin granting the ability to ac... |
from flask import session
from invenio_base.globals import cfg
from invenio.ext.template import render_template_to_string
"""
Template context function - Display links (previous, next, back-to-search)
to navigate through the records.
"""
def template_context_function(recID):
"""
Displays next-hit/previous-hit/b... |
import urlparse, urllib, time
from zope.interface import Interface
from twisted.web import html, resource
from buildbot.status import builder
from buildbot.status.builder import SUCCESS, WARNINGS, FAILURE, SKIPPED, EXCEPTION
from buildbot import version, util
class ITopBox(Interface):
"""I represent a box in the to... |
from pyramid.view import view_config
from model.models import (
DBSession,
Settings,
)
@view_config(route_name='home', renderer='home.mako')
def home(request):
return configuration_get(request)
@view_config(route_name='configuration', renderer='configuration.mako')
def configuration(request):
return (co... |
"""A report of recently modified cinemas and films
"""
from DateTime import DateTime
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import ... |
import Catche
import os
def countSort(xe):
names = []
Xes = os.listdir(r'.\Gene Expressions\CurrentCel')
out = [[0]]
for x in Xes:
if x[-7:] == r'.CEL.gz':
names.append(x[:-7])
arrayX = Catche.opickle(r'.\Gene Expressions\CurrentCel/BAIntense'+names[xe]+r'.pickle')
counter = ... |
import config
import addonHandler
confspec = {
"announcement": "integer(default=0)",
"cleanDicts": "boolean(default=False)",
}
config.conf.spec["emoticons"] = confspec
addonHandler.initTranslation()
def onInstall():
import speechDictHandler
import globalVars
import os
import shutil
import gui
import wx
ADDON_D... |
"""NAV subsystem for IP device polling.
Packages:
plugins -- polling plugin system
"""
from nav.models import manage
from .log import ContextLogger, ContextFormatter
class Plugin(object):
"""Abstract class providing common functionality for all polling plugins.
Do *NOT* create instances of the base class.
... |
import unittest
from tests.baseclass import *
from pykickstart.errors import *
from pykickstart.commands.autostep import *
class FC3_TestCase(CommandTest):
command = "autostep"
def runTest(self):
# pass
self.assert_parse("autostep", "autostep\n")
self.assert_parse("autostep --autoscreens... |
"""Provide access to Python's configuration information. The specific
configuration variables available depend heavily on the platform and
configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys(). Additional convenience functions are a... |
from functools import wraps
from os import path
import os
import sys
import json
import hashlib
import urlparse
import stat
import zipfile
import subprocess
from module_dynamic.lib import PopenWithoutNewConsole
import build
def task(function):
build.Build.tasks[function.func_name] = function
@wraps(function)
def wra... |
"""
Module for check_snmp_eps_plus.py
"""
from __future__ import absolute_import, division, print_function
from pynag.Plugins import critical, unknown
DEVICE_NAME_OID = ".1.3.6.1.4.1.24734.16.2.1.1.3"
OUTLET_NAME_OID = ".1.3.6.1.4.1.24734.16.8.1.1.4"
OUTLET_STATUS_OID = ".1.3.6.1.4.1.24734.16.8.1.1.5"
SENSOR_ID_OID = "... |
from PyQt4 import QtCore
from collections import defaultdict
from functools import partial
import imp
import json
import os.path
import shutil
import picard.plugins
import tempfile
import traceback
import zipimport
from picard import (config,
log,
version_from_string,
... |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from caluny_api.chat_messages import views
router = DefaultRouter()
router.register(r'messages', views.MessagesViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^send_subject_message/$', views.SendMessageToS... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import gdb
import sys
from crash.infra import CrashBaseClass, export
from crash.types.klist import klist_for_each_entry
if sys.version_info.major >= 3:
long = int
class ClassDeviceClass(CrashBaseClass):
... |
import logging
from lxml import etree
import os
import pytrainer
from pytrainer.upgrade.context import UpgradeContext
from pytrainer.upgrade.migratedb import MigratableDb
def initialize_data(ddbb, conf_dir):
"""Initializes the installation's data."""
db_url = ddbb.get_connection_url()
migratable_db = Migrat... |
"""autogenerated by genpy from bebop_msgs/CommonFlightPlanStateAvailabilityStateChanged.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class CommonFlightPlanStateAvailabilityStateChanged(genpy.Message):
_md5sum = "b47d28069682887... |
import os
import glob
try:
from ifupdown2.lib.io import IO
from ifupdown2.lib.base_objects import Requirements
from ifupdown2.ifupdown.utils import utils
from ifupdown2.nlmanager.nlpacket import Link
except (ImportError, ModuleNotFoundError):
from lib.io import IO
from lib.base_objects import Re... |
"""This module represents the Cornish language.
.. seealso:: http://en.wikipedia.org/wiki/Cornish_language
"""
from translate.lang import common
class kw(common.Common):
"""This class represents Cornish."""
mozilla_nplurals = 2
mozilla_pluralequation = "n!=1 ? 1 : 0" |
"""solve 15"""
def row_end_node(x):
if (x + 1) % DELTA_DOWN == 0:
return True
return False
GRID_SIZE = 20
END_NODE = ((GRID_SIZE + 1) ** 2) - 1
DELTA_DOWN = GRID_SIZE + 1
FIRST_NODE_OF_BOTTOM_ROW = DELTA_DOWN * GRID_SIZE
print(GRID_SIZE, END_NODE, DELTA_DOWN, FIRST_NODE_OF_BOTTOM_ROW)
path_count_from_no... |
import sys
import os
import re
class PtestParser(object):
def __init__(self):
self.results = {}
self.sections = {}
def parse(self, logfile):
test_regex = {}
test_regex['PASSED'] = re.compile(r"^PASS:(.+)")
test_regex['FAILED'] = re.compile(r"^FAIL:([^(]+)")
test_r... |
import email.mime.text
import errno
import httplib
import logging
import os
from os.path import join
import shutil
import smtplib
import stat
import subprocess
import sys
import time
import urllib2
from xml.etree import ElementTree
from synthesepy.third_party.ordered_dict import OrderedDict
log = logging.getLogger(__na... |
"""
Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Funda... |
from django.conf.urls import patterns, include, url
from main.feeds import LastFeed, PopularFeed
urlpatterns = patterns('',
url(r'^$', 'main.views.index'),
url(r'^baslik/(?P<title>[\w\W]+)', 'main.views.TitlePage'),
url(r'^entry/(?P<entry_id>[\w\W]+)/$', 'main.views.EntryPage'),
url(r'^arama/', 'main.vi... |
import os
import subprocess
from setuptools import setup
from exe.engine import version
from exe.engine.path import Path
Path('exe/webui/templates/mimetex.cgi').chmod(0755)
Path('exe/webui/templates/mimetex.64.cgi').chmod(0755)
files = { '/usr/share/exe': ["README",
... |
import bpy
fbx_elem_nil = None
from .parse_fbx import data_types, FBXElem
def tuple_deg_to_rad(eul):
return (eul[0] / 57.295779513,
eul[1] / 57.295779513,
eul[2] / 57.295779513)
def elem_find_first(elem, id_search, default=None):
for fbx_item in elem.elems:
if fbx_item.id == id_s... |
"""
Script to create a template easyblock Python module, for a given software package.
:author: Kenneth Hoste (Ghent University)
"""
import datetime
import os
import sys
from optparse import OptionParser, OptionGroup
from easybuild.tools.filetools import encode_class_name
parser = OptionParser()
parser.usage = "%prog <... |
from ciscoconfparse import CiscoConfParse
import re
from pprint import pprint
import markdown
def read_in_file(filename):
return CiscoConfParse(filename)
def generate_pointee_markdown(parsed_config, pointee_objects):
pointee_types = ['access-list', 'ip access-list', 'interface',
'route-map'... |
from __future__ import print_function
"""
Invenio garbage collector.
"""
__revision__ = "$Id$"
import sys
import datetime
import time
import os
from invenio.legacy.dbquery import run_sql, wash_table_column_name
from invenio.config import CFG_LOGDIR, CFG_TMPDIR, CFG_CACHEDIR, \
CFG_TMPSHAREDDIR, CFG_WEBSEARCH_RS... |
from os.path import join
from django.conf import settings
UPLOAD_DIR = join(settings.MEDIA_ROOT, 'secure_storage')
MB = 1024 * 1024
UPLOAD_FILE_SIZE_LIMIT = 100 * MB
UPLOAD_DOMAIN = 'http://localhost:8000'
ONE_TIME, ONE_MINUTE, ONE_HOUR, ONE_DAY, ONE_WEEK, ONE_MONTH, ONE_YEAR = (
0, 60, 3600, 86400, 604800, 2592000... |
import os
import time
import random
import unittest
import logging
import subprocess
from pwd import getpwnam
class SimpleSetup(object):
def __init__(self, distro, infrastructure):
self.distro = distro
self.username = 'pcloud_tester'
self.infrastructure = infrastructure
self.arch = '... |
class mask():
def __init__(self):
self.name="Color mask view"
self.description="Generates an image with a color filter based on a bitmask"
self.inputdata="image"
self.parameters = {
'mr': 'Red mask',
'mg':'Green mask',
'mb':'Blue mask',... |
import jmri.jmrit.jython.Jynstrument as Jynstrument
import java.awt.CardLayout as CardLayout
import jmri.util.swing.ResizableImagePanel as ResizableImagePanel
import sys
class Test(Jynstrument):
def getExpectedContextClassName(self):
return "java.lang.Object"
def init(self):
print "In init"
... |
from pisi.actionsapi import shelltools, get, autotools, pisitools
def setup():
autotools.configure("--with-default-accel=sna \
--enable-uxa \
--disable-dri3 ")
def build():
autotools.make()
def install():
autotools.rawInstall("DESTDIR=%s" % get.installDIR())... |
"""
WSGI config for bison project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bison.settings")
from django.core.wsgi impo... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ladder.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from ropperapp.common.enum import Enum
from sys import version_info
import ropperapp
class Color(Enum):
RED = '0;31'
CYAN = '0;36'
BLUE = '0;34'
GREEN = '0;32'
PURPLE = '0;35'
LIGHT_RED = '1;31'
LIGHT_CYAN = '1;36'
LIGHT_BLUE = '1;34'
LIGHT_GREEN = '1;32'
LIGHT_PURPLE = '1;35'
LIGHT_YELLOW = '1;33'
YELLOW =... |
import os
from PyQt4 import QtGui
from Code import AperturasStd
from Code import Partida
from Code.QT import Colocacion
from Code.QT import Columnas
from Code.QT import Controles
from Code.QT import Delegados
from Code.QT import FormLayout
from Code.QT import Grid
from Code.QT import Iconos
from Code.QT import QTUtil
f... |
"""
Thermal simulator Ver .04
** Works on Xplane 10.30 and above only **
The plugin then reads the lift value of the plane current position and
sets the lift & roll values.
Author: Alex Ferrer
License: GPL
"""
import world
from XPLMDefs import *
from EasyDref import EasyDref
from thermal_model import calc_th... |
import unittest
import calc
POINTS_FOUR = (
dict(points=20, fine=8, whists=(10, 10, 10)),
dict(points=20, fine=9, whists=(20, 20, 20)),
dict(points=20, fine=10, whists=(30, 30, 30)),
dict(points=20, fine=11, whists=(40, 40, 40)),
)
RESULTS_FOUR = (-45, -15, 15, 45)
POINTS_THREE = (
dict(points=20, f... |
"""
Simple Cython example
"""
import cython_example
area = cython_example.area(37, 48)
print('Cython returned', area) |
"""
This is the main Javascript page.
"""
import copy
import os
import json
import sys
import logging
import traceback
import shutil
import tempfile
import base64
from exe.engine.version import release, revision
from twisted.internet import threads, reactor, defer
from exe.webui.livepage im... |
"""
Avocado application command line parsing.
"""
import argparse
import logging
from . import exit_codes
from . import tree
from . import settings
from .output import BUILTIN_STREAMS, BUILTIN_STREAM_SETS
from .version import VERSION
PROG = 'avocado'
DESCRIPTION = 'Avocado Test Runner'
class ArgumentParser(argparse.Arg... |
import urllib,urllib2
import re
import cookielib
import sys
class AutoAD():
url = 'http://www.example.cn/public/Default.aspx'
posturl = 'http://www.example.cn/StaticPage/subject/comments.aspx '
agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'
headers = {'User-Agent': ag... |
"""
Remove obsolete source and binary associations from suites.
@contact: Debian FTP Master <ftpmaster@debian.org>
@copyright: 2009 Torsten Werner <twerner@debian.org>
@license: GNU General Public License version 2 or later
"""
from daklib.dbconn import *
from daklib.config import Config
from daklib import daklog, uti... |
from __future__ import absolute_import
from django.contrib import auth, messages
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse_lazy
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template import loader, Reque... |
__doc__ = \
"""
pyparsing module - Classes and methods to define and execute parsing grammars
The pyparsing module is an alternative approach to creating and executing simple grammars,
vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
don't need to learn a new syntax for def... |
def menuselect2kconfig(menuselectFilename):
from xml.dom import minidom
import re
missingDependencies = {
"res_rtp_asterisk": ["WITH_PJPROJECT"]
}
dependencyMap = {
"CRYPTO": ["FREETZ_LIB_libcrypto"],
"OPENSSL": ["FREETZ_LIB_libcrypto", "FREETZ_LIB_libssl"],
"CURL": ["FREETZ_LIB_libcurl"],
"GSM": ["FREET... |
from PySide2.QtGui import QColor
palette_trbg = {
'Inchworm': QColor(0xa1,0xe4,0x4d,128),
'CornFlowerBlue': QColor(0x7b,0x8c,0xde,128),
'SuperPink': QColor(0xdc,0x6b,0xad,128),
'YellowOrange': QColor(0xff,0xb1,0x40,128),
'MintGreen': QColor(0xa2,0xfa,0xa3,128),
'Chartreus... |
{
"name" : "Manage the amount of progress in parallel",
"version" : "1.0",
"depends" : ["project","project_issue"],
"author" : "Vauxoo",
"description" : """Manage the amount of progress in parallel, among other related fields.
""",
"website" : "http://vauxoo.com",
"category" : "Generic M... |
import sys, os, time, json
if "TANGO_HOST" not in os.environ:
raise RuntimeError("No TANGO_HOST defined")
import PyTango
dahu = PyTango.DeviceProxy("DAU/dahu/1")
plugin = "id02.SingleDetector"
data = {"DetectorName": 'Rayonix',
"image_file": "/nobackup/lid02gpu11/FRELON/test_laurent_saxs_0000.h5",
#... |
"""
Gets or sets options defined by a given configuration file path.
STATE:complete/untested
TODO:
set up some testing
provide borderline config cases
test
review considerations
CONSIDERATIONS:
Should I include functions to lock the configuration file? This can't
be done with the normal master lock, as the ... |
from cantrips.types.arguments import Arguments
class _Exception(Arguments, Exception):
def __init__(self, message, code, *args, **kwargs):
Arguments.__init__(self, message=message, code=code, *args, **kwargs)
Exception.__init__(self, message)
def factory(codes, base=_Exception):
"""
Creates ... |
from __future__ import unicode_literals
from django.test import TestCase
from common.settings import SKIP_ONLINE_TESTS
from knowledge.models import KnowledgeBuilder
from knowledge.models import KnowledgeGraph, GlobalKnowledge
from knowledge.namespaces import TERM
from unittest import skipIf
class GlobalKnowledgeEmptyDB... |
import os
import textwrap, argparse
import pymysql
import time
if __name__ == '__main__':
argument_parser = argparse.ArgumentParser(
prog='statsSynsetsVarariants.py',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
count number of variants for each synset fro... |
import pyinotify
import sys
from mailer import send_sfm_report
wm = pyinotify.WatchManager()
mask = pyinotify.IN_ACCESS | pyinotify.IN_ATTRIB
class EventHandler(pyinotify.ProcessEvent):
#def process_IN_ACCESS(self, event):
#send_sfm_report(event.pathname)
def process_default(self, event):
send_s... |
import numpy as np
import mcmcGP
import GPy
from multiclassLikelihood_GPy import Multiclass
from ahmc import HMC, AHMC
import sys
from time import time
np.random.seed(1)
ndata = None # none for all data
vb_filename = 'mnist_467M_scg.pickle'
ahmc_num_steps = 50
ahmc_s_per_step = 20
hmc_num_samples = 300
thin = 2
data = ... |
from routersploit.modules.exploits.routers.cisco.ios_http_authorization_bypass import Exploit
def test_check_success(target):
""" Test scenario - successful check """
route_mock = target.get_route_mock("/level/44/exec/-/show startup-config", methods=["GET"])
route_mock.return_value = (
"test"
... |
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as ... |
# -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.choiceboxext import ChoiceBoxExt
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
import Queue
impo... |
'''
Squish: The stupid bug tracker.
'''
import traceback
def _getCaller(backsteps=1):
'''
Quick method to get the previous caller's method information.
Returns:
A tuple of the form (filename, lineno, funcname, text).
'''
trace = traceback.extract_stack(limit=backsteps+2)
return trace[0]
class Debuggable(o... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from common.utils import get_logger
from ..utils import (
set_current_org, get_current_org, current_org,
filter_org_queryset, get_org_by_id, get_org_name_by_id
)
from ..models ... |
import cStringIO
import os
from mercurial import hg, util, patch, commands
from hgext import record
from tortoisehg.util import hglib
from tortoisehg.util.patchctx import patchctx
from tortoisehg.hgqt.i18n import _
from tortoisehg.hgqt import qtlib, qscilib, lexers
from PyQt4.QtCore import *
from PyQt4.QtGui import *
f... |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask_jsonrpc import JSONRPC
import logging
from config import ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, API_URL, basedir
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(ap... |
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
from orgs.mixins import OrgModelMixin
from .hands import LoginLog
__all__ = [
'FTPLog', 'OperateLog', 'PasswordChangeLog', 'UserLoginLog',
]
class FTPLog(OrgModelMixin):
id = models.UUIDField(default=uuid.uuid4, pri... |
a=60000
b=[]
for i in range(1,a):
if a % i ==0:
b.append(i)
c=sum(b)
print(b,c)
if c==a:
print('perfect')
elif c>a :
print('a')
else :
print('d') |
import pygtk
pygtk.require('2.0')
import cairo
import gtk
import gobject
import cairo_drawing
class PanelTopWindow():
def __init__(self):
self.aux_window = gtk.Window()
self.scale = 1
self.aux_window.set_skip_taskbar_hint(1)
self.aux_window.set_skip_pager_hint(1)
self.aux_window.set_app_paintable(True)
sel... |
"""
Module containing classes with common behaviour for consoles of both VMs and Instances of all types.
"""
import base64
import re
import tempfile
import time
from cfme.exceptions import ItemNotFound
from PIL import Image, ImageFilter
from pytesseract import image_to_string
from selenium.webdriver.common.keys import ... |
class Message(object):
message = ''
message_args = ()
def __init__(self, filename, lineno):
self.filename = filename
self.lineno = lineno
def __str__(self):
return '%s:%s: %s' % (self.filename, self.lineno, self.message % self.message_args)
def msg(self):
return self.... |
"""readers module of the nc2map python module
This script contains the basic data danagement utilities in the nc2map
module.
It contains the following reader classes
- The ReaderBase class defines the main methods for all readers,
such as data extraction, the merging method and the arithmetics.
- The NCRea... |
from __future__ import with_statement
import __future__
FUTURE_DIVISION = __future__.division.compiler_flag
from math import *
import locale
import imp
import os
from PIL import Image, ImageDraw
import OpenGL.GL as gl
from fretwork import log
from fofix.core.LinedConfigParser import LinedConfigParser
from fofix.core.Th... |
'''
Covenant Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the h... |
"""CLI for Zenodo fixtures."""
from __future__ import absolute_import, print_function
from invenio_db import db
from invenio_openaire.minters import grant_minter
from invenio_records.api import Record
from .utils import read_json
def loadfp6grants(force=False):
"""Load default file store location."""
data = rea... |
"""
Relationship View
"""
from html import escape
import pickle
import logging
_LOG = logging.getLogger("plugin.relview")
from gi.repository import Gdk
from gi.repository import Gtk
from gi.repository import Pango
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
ngettext = glocale.... |
from pathfinding.core.diagonal_movement import DiagonalMovement
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
matrix = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
def path_find(matrix, start_cell, end_cell):
"""
example from https://pypi.org/project/pathfinding/
"""
... |
"""
Django settings for mecafactures project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
i... |
import re
from karl.utilities.converters.entities2uc import entitydefs
entity_reg = re.compile('&(.*?);')
def handler(x):
""" Callback to convert entity to UC """
v = x.group(1)
return entitydefs.get(v, '')
def convert_entities(text):
""" replace all entities inside a unicode string """
assert isins... |
'''
This is a Python rip from cipher-aead.c.
Some useful info following:
We are using libc's ioctl and fcnt instead of fcntl's because sometimes addressof()
returns really big numbers. This causes problems to fcntl's ioctl (for more follow the link below):
http://hg.python.org/cpython/file/bc6d28e726d8/Python/getargs.c... |
def read_puzzle_input(path):
puzzle_input = ''
with open(path, 'r') as file:
puzzle_input = file.read().strip()
return puzzle_input |
from __future__ import absolute_import
from testutil.dott import feature, sh, testtmp # noqa: F401
sh % "setconfig 'experimental.evolution='"
(
sh % "cat"
<< r"""
[extensions]
rebase=
[phases]
publish=False
"""
>> "$HGRCPATH"
)
sh % "hg init a"
sh % "cd a"
sh % "echo c1" > "c1"
sh % "hg ci -Am c1" == "addi... |
'''
Created on 2016. 10. 16.
@author: jongyeob
'''
import os
import swpy
from swpy.utils2 import filepath
from swpy import dscovr
TEST_MAG_FILE = swpy.RESOURCE_DIR +'/test/dscovr-mag-sample.json'
TEST_PLASMA_FILE = swpy.RESOURCE_DIR +'/test/dscovr-plasma-sample.json'
dscovr.clients.PATH_PATTERN = swpy.TEMP_DIR + dscovr... |
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from gaegraph.model import Node, Arc, to_node_key
class Searchable(Node):
pass
class Site(Searchable):
domain = ndb.StringProperty(required=True)
token = ndb.StringProperty(required=True)
@classmethod
def f... |
import argparse
import sys
from argparse import FileType
def parse_header(spec_lines):
# M I L O A
# aag 25 6 0 1 19
# 0 1 2 3 4 5
header_tokens = spec_lines[0].strip().split()
nof_inputs = int(header_tokens[2])
nof_outputs = int(header_tokens[4])
return nof_inputs, nof_outputs
def g... |
import logging
import click
from helmetico.commons import shared_cmd_options
from .create.cli import create
from .delete.cli import delete
from .update.cli import update
log = logging.getLogger('helmetico')
@shared_cmd_options.global_options()
@click.pass_context
def cli(ctx, **kwargs):
ctx.obj = kwargs
cli.add_com... |
import unittest
from main import validator, main
class ValidatorTestCase(unittest.TestCase):
def test_string1(self):
self.assertFalse(validator("hijklmmn"))
def test_string2(self):
self.assertFalse(validator("abbceffg"))
def test_string3(self):
self.assertFalse(validator("abbcegjk"))... |
import socket
import os
import re
import sys
import time
import urllib2
class Dropbox:
def __init__(self):
self.connected = False
def connect(self, cmd_socket="~/.dropbox/command_socket", iface_socket="~/.dropbox/iface_socket"):
"Connects to the Dropbox command_socket, returns True if it was successful."
self.i... |
"""
WSGI config for gesiesweb 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``... |
import scanconfig
import scansupport as sws
if (scanconfig.cte_disable_motors_first):
sws.disableMotors()
if (scanconfig.cte_enable_motors_first):
sws.enableMotors()
print("Check motor positions")
if not scanconfig.cte_use_motorsim:
# TODO: INCORPORATE 'OST' COMMAND HANDLING TO MOTORSIM
sws.stepFinished... |
import test_global_data_files
from collections import Counter
from rdflib.term import URIRef, Variable, _XSD_PFX, _is_valid_uri
from rdflib.namespace import RDF, RDFS
import classgenerator
from ontology import Ontology
import pprint
import astunparse
import pprint
import ast
from ast import *
import re
def rebind(g):
... |
import pytest
import numpy as np
from scipy.ndimage.filters import gaussian_filter
from matplotlib import pyplot as plt
from pyFAI.detectors import Detector
from pyxem.utils.expt_utils import (
_index_coords,
_cart2polar,
_polar2cart,
remove_dead,
find_beam_offset_cross_correlation,
peaks_as_gve... |
import sys
import numpy as np
from colormap import rgb2hex # which also needs easydev (pip install easydev)
import ast
RGB_min = 0
RGB_max = 255
steps = ast.literal_eval(sys.argv[1]) # EXPECTS numeric parameter as only parameter to script!
c = 0
h = 0
graysRGB = []
descending_RGB_val = np.linspace(RGB_max, RGB_min, num... |
import argparse
from helpers import read_strings
from snp import FindLongestRepeat
import sys
import time
if __name__=='__main__':
sys.setrecursionlimit(1500)
start = time.time()
parser = argparse.ArgumentParser('BA9D Find the Longest Repeat in a String')
parser.add_argument('--sample', default=False... |
from datetime import datetime
from builder import Builder, ObjectBuilder, SetAttrBuilder, Parser
class Base(object):
def __init__(self, **attrs):
for key, value in attrs.items():
setattr(self, key, value)
class Creator(Base):
def __init__(self, **attrs):
self.name = None
self... |
from setuptools import setup
import re
import os
import ConfigParser
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_require_version(name):
if minor_version % 2:
require = '%s >= %s.%s.dev0, < %s.%s'
else:
require = '%s >= %s.%s, < %s.%s'
requi... |
import snap,datetime, sys, time, json, os, os.path, time
import calc
reload(sys)
sys.setdefaultencoding('utf-8')
def prepare_communities(community_file,n_nodes):
i=0
communities = {} # Dicionário com uma chave (id da community): e uma lista de ids dos membros da comunidade
alters_set = set()
size = [] ... |
__author__ = "David Rusk <drusk@uvic.ca>"
from src.validate.downloads.cutouts.focus import (SingletFocusCalculator,
TripletFocusCalculator)
from ...downloads.async import DownloadRequest
from ...downloads.cutouts.grid import CutoutGrid
from ...gui import events, logger
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('inventory', '0013_auto_20161019_1830'),
]
operations = [
migrations.AlterField(
model_name='supply',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.