code stringlengths 1 199k |
|---|
import networkx
from Game import myStream, myNote
from mylibs.incDijksra import incDijkstra
from mylibs.myDict import MyDict
from Game.myKey import mykey
from Game.myJumpChordsAndSpeedTols import MyJumpChordsAndSpeedTols
import logging
from Game.myNoteMap import KnownChordPos
logger = logging.getLogger(__name__)
hdlr =... |
"""Provides an apt backend to PackageKit
Copyright (C) 2007 Ali Sabil <ali.sabil@gmail.com>
Copyright (C) 2007 Tom Parker <palfrey@tevp.net>
Copyright (C) 2008-2009 Sebastian Heinlein <glatzor@ubuntu.com>
Copyright (C) 2012 Martin Pitt <martin.pitt@ubuntu.com>
Licensed under the GNU General Public License Version 2
Thi... |
from collections import OrderedDict
from rest_framework.generics import ListAPIView
from rest_framework.serializers import ModelSerializer
from rest_framework.serializers import SerializerMethodField
from patchwork.api.embedded import CheckSerializer
from patchwork.api.embedded import CoverLetterSerializer
from patchwo... |
"""
***************************************************************************
slope.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
********************************************... |
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should load the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.
"""
def init(): pass
def l... |
import fnmatch
import logging
import optparse
import os.path
import re
import six
import sys
import traceback
from io import BytesIO
from translate import __version__
from translate.misc import progressbar
class ManPageOption(optparse.Option, object):
ACTIONS = optparse.Option.ACTIONS + ("manpage",)
def take_ac... |
a=['999','1']
max_length=len(max(a,key=len))
tem=0
carry=0
for i in xrange(len(a)):
while len(a[i])<max_length:
a[i]='0'+a[i]
for x in xrange(len(a)):
a[x]=a[x][::-1]
out=''
for x in xrange(max_length):
for i in a:
tem+=int(i[x])
print(i[x],carry)
tem+=carry
carry=0
print(tem)
if tem>9:
carry=tem/10
out... |
import urllib
import os
import re
from time import sleep
from datetime import date
def welcome(modulename):
print """
|==========================================================|
|====================== [ 404 ] ========================|
|==============[ lordnotfound404@gmail.com ]===... |
from django import forms
from django.contrib.auth.models import Group
from common.forms import ModelFormWithHelper
from common.helpers import SubmitCancelFormHelper
from community.constants import COMMUNITY_ADMIN
from community.models import Community, CommunityPage
from community.utils import get_groups
from users.mod... |
import os, Queue
import sys
from time import sleep
from threading import Thread
from libs.qemu import QemuInstance, UARTLineParser
if len(sys.argv) > 1:
print "ARGS:", str(sys.argv)
sys.path.append(os.path.dirname( sys.argv[1] ))
print("=== Starting RPiEmu v0.5 ===")
rpi = QemuInstance()
rpi.start()
from models... |
import fauxfactory
import pytest
from widgetastic.utils import partial_match
from cfme import test_requirements
from cfme.infrastructure.provider import InfraProvider
from cfme.infrastructure.provider.rhevm import RHEVMProvider
from cfme.infrastructure.pxe import get_pxe_server_from_config, get_template_from_config
fro... |
import apt_pkg
import logging
import os
import mock
import sys
import tempfile
import unittest
sys.path.insert(0, "..")
from unattended_upgrade import _setup_logging
class MockOptions:
dry_run = False
debug = False
class TestLogdir(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp... |
import os
import re
import mimetypes
from collections import namedtuple
from aiohttp import web
from app.lib.helpers import (
http400,
http404,
)
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
FILENAME_PARSER = re.compile(r"(?P<id>\d+)_(?P<name>.+)\.(?P<format>.+)")
ParsedFile = namedtuple('ParsedFile', [
... |
from gui.dwidgets import DMenu
class SettingsMenu(DMenu):
"""docstring for SettingsMenu"""
def __init__(self, parent=None):
super(SettingsMenu, self).__init__(parent)
self.parent = parent
self.menuItems = [
{
'name': self.tr('Login'),
'icon': u... |
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
******************************************... |
"""
Basic iscsi support for Linux host with the help of commands
iscsiadm and tgtadm.
This include the basic operates such as login and get device name by
target name. And it can support the real iscsi access and emulated
iscsi in localhost then access it.
"""
import re
import os
import logging
from avocado.core import... |
from __future__ import print_function
from socket import socket
import sys, os, re, stat, math, time, datetime
import importlib
try: # unicode monkeypatch for windoze
import win_unicode_console
win_unicode_console.enable()
except:
msg = "Please install the 'win_unicode_console' module."
if os.name == 'nt': prin... |
import math
import sys
est_file = sys.argv[1]
ref_file = sys.argv[2]
def read_mapping(f):
m = {}
for line in open(f):
s = line.split(',')
ins = int(s[0], base=16)
id = int(s[1])
if id != -1:
m[ins] = id
return m
def make_grouping(m):
cs = {}
for ins, id in m.iteritems():
if id in cs:... |
import os
import shutil
from xml.etree.ElementTree import Element, SubElement, tostring, parse
from os import environ, makedirs, chmod
from os.path import join, basename, isdir, split, normpath, exists
import logging
import random
from gi.repository import GObject
import zipfile
import tempfile
from sugar3.activity.act... |
import argparse
import os
from star import *
def parse_args():
parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.")
parser.add_argument('--input', metavar='f1', type=str, nargs=1, required=True, help="particle file whose ctf values will b... |
from brian2 import *
import brian2genn
set_device('genn', directory='simple_example_synapses')
N = 100
tau = 10*ms
eqs = '''
dV/dt = -V/tau + Iin/tau : 1
Iin : 1
'''
G = NeuronGroup(N, eqs, threshold='V>1', reset='V=0', name='PN')
G.V = rand()
G2 = NeuronGroup(N, eqs, threshold='V>1', reset='V=0', name='LN')
G2.V = 2 *... |
import gtk
import pango
import math
from core.world import TheWorld
class TextEditor(object):
def __init__(self, text):
self.__text = text
self.cursorindex = 0
self.padding = 10.0
self.width = 0.0
self.height = 0.0
self.pixel_width = 0.0
self.pixel_height = 0.0
# create text layout
... |
"""
Django settings for SimpleChat project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY... |
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',#'django.db.backends.postgresql_psycopg2',
'NAME': 'bauth',
'USER': 'postgres',
'ADMINUSER':'postgres',
'PASSWORD': 'C7TS*+dp~-9JHwb*7rzP',
... |
from pymoistcontrol.util import *
import os
class SerialOpenDialog(QDialog):
"""Serial port connection dialog."""
def __init__(self, parent):
"""Class constructor."""
QDialog.__init__(self, parent)
self.setLayout(QGridLayout(self))
self.setWindowTitle("Select serial port")
self.portCombo = QComboBox(self)
... |
from scrapy.item import Item, Field
class PopularArticlesItem(Item):
# define the fields for your item here like:
# name = Field()
pass |
from django.shortcuts import render,render_to_response,redirect
from django.core.urlresolvers import reverse
from block.models import Blocks
from models import Article
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def article_lis... |
from rest_framework import serializers
class MailTestSerializer(serializers.Serializer):
EMAIL_HOST = serializers.CharField(max_length=1024, required=True)
EMAIL_PORT = serializers.IntegerField(default=25)
EMAIL_HOST_USER = serializers.CharField(max_length=1024)
EMAIL_HOST_PASSWORD = serializers.CharFie... |
import os,sys,socket,select
from time import strftime
variables = ['name','tripcode']
servercommands = ["/pm", "/peoplecount"]
def date():
return strftime(".%Y-%m-%d")
def chat_client(inputsocket,data,location):
#initialize radchat client files
if not os.path.exists(location+'/resources/programparts/radchat'): os... |
from flask import Blueprint, request, render_template, jsonify
from housesGenerator import House
from holdings import Holdings
houses = Blueprint('houses', __name__, url_prefix='/houses')
@houses.route('/')
def index():
return render_template('houses.html')
@houses.route('/houseGenerator', methods=['GET', 'POST'])
... |
import unittest, sys, findbits
class TestFindBits(unittest.TestCase):
def setUp(self):
self.old_stdout = sys.stdout
sys.stdout = OutputBuffer()
def tearDown(self):
sys.stdout = self.old_stdout
INVERT_CASES = [
('10', '01'),
('', ''),
]
def test... |
import os
APP_NAME = "SLog"
VERSION = "0.9.4"
WEBSITE = "http://vialinx.org"
LICENSE = """
SLog is a PyGTK-based GUI for the LightLang SL dictionary.
Copyright 2007 Nasyrov Renat <renatn@gmail.com>
This file is part of SLog.
SLog is free software; you can redistribute it and/or modify
it under the terms of the GNU Gene... |
import sys
import csv
from pprint import pprint
"""2018.10.28 John Dey
consume CSV output from pwalk and reassemble directory data.
File system data from pwalk is flattened and out of order.
Rewalk the tree data and create two new fields for each directory.
Create a tree sum of file count and bytes at each directory (n... |
from http.server import SimpleHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import threading
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
if __name__ == '__main__':
server = ThreadedHTTPServer(('localhost', 8000), SimpleHTTPRequestHan... |
from ventana import Ventana
from formularios import utils
import pygtk
pygtk.require('2.0')
import gtk
from framework import pclases
from utils import _float as float
import mx.DateTime
class Confirmings(Ventana):
def __init__(self, objeto = None, usuario = None):
"""
Constructor. objeto puede ser u... |
from gvsbuild.utils.base_builders import CmakeProject
from gvsbuild.utils.base_expanders import GitRepo
from gvsbuild.utils.base_project import Project, project_add
@project_add
class Grpc(GitRepo, CmakeProject):
def __init__(self):
Project.__init__(
self,
"grpc",
repo_ur... |
from .validator import Validator
from ..util import register_as_validator
class ExactLength(Validator):
__validator_name__ = 'exact_length'
def __init__(self, exact_length):
super(ExactLength, self).__init__()
self.exact_length = exact_length
def validate(self, data, request=None, session=No... |
import jmri.jmrit.jython.Jynstrument as Jynstrument
import jmri.jmrit.catalog.NamedIcon as NamedIcon
import jmri.jmrit.symbolicprog.tabbedframe.PaneOpsProgAction as PaneOpsProgAction
import javax.swing.JButton as JButton
class DecoderPro(Jynstrument):
def getExpectedContextClassName(self):
return "javax.swi... |
import time
__author__ = 'ASU'
class ContextLock():
def __init__(self, lock):
"""
:param lock:
:type lock: thread.LockType
"""
self.__lock = lock
def __enter__(self):
self.__lock.acquire()
def __exit__(self, exc_type, exc_value, traceback):
self.__lock... |
'''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
W... |
from Tools.Profile import profile
from Tools.BoundFunction import boundFunction
import Screens.MovieSelection
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDescriptor
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.Label import Label
from Com... |
"""
/***************************************************************************
Client for streaming based WPS.
It exploits asynchronous capabilities of WPS and QGIS for visualizing
intermediate results from a WPS
-------------------
copyright : (C) 2012 by Germán Carrillo (Ge... |
import json
import logging
from typing import List, Optional
from uuid import uuid4
from django import http
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.db.utils import OperationalError
from django.views.decorators.http import requi... |
from pymongo import MongoClient
import json
import requests
import time
from datetime import datetime
def subredditInfo(sr, limit=100, sorting="top", period="day",
user_agent="ChicagoSchool's scraper", **kwargs):
"""retrieves X (max 100) amount of stories in a subreddit
'sorting' is whether or... |
import sys
import os, os.path
import errno
import logging
import time
import random
import signal
import daemon
import datetime
import pkg_resources
import subprocess
import xmlrpclib
from daemon import pidfile
from optparse import OptionParser
import gevent, gevent.hub, gevent.socket, gevent.event, gevent.monkey
from ... |
from MaKaC.webinterface.rh import conferenceDisplay
def index(req,**params):
return conferenceDisplay.RHAbstractBook(req).process(params)
def test(req,**params):
return conferenceDisplay.RHAbstractBook(req).process(params) |
__author__ = 'duarte'
import sys
from preset import *
import numpy as np
"""
spike_noise_input
- standard network setup, driven with noisy, Poissonian input
- quantify and set population state
- run with noise_driven_dynamics in computations
- debug with noise_driven_dynamics script
"""
run = 'local'
data_label = 'exam... |
my_ip = "192.168.1.100"
my_subnet = "255.255.255.0"
ip = my_ip.split(".")
print ip
while True:
#my_ip = input("Enter a ip address:")
if int(ip[0]) <= 223 and (int(ip[1]) != 169 or int(ip[2]) != 254) and (int(ip[1]) <= 254 and int(ip[2]) <= 254 and int(ip[3]) <= 254):
print "You entered a valid ip"
break
else:
... |
import multiprocessing
import gen_templates
import subprocess
import argparse
import json
import copy
import re
import os
def which(program):
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['which', program], stdout = FNULL,
stderr = subprocess.STDOUT)
if retcode != 0:... |
__author__ = "Antonio Hernández <ahernandez@emergya.com>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <devmaster@guadalinex.org>"
__license__ = "GPL-2"
import firstboot.serverconf
from ChefConf import ChefConf
from GCCConf import GCCConf
from AuthConf import AuthConf
from DateSyncConf import DateSyncConf
fr... |
__copyright__ = """
Copyright (C) 2006, Catalin Marinas <catalin.marinas@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be us... |
import os
import sys
import unittest
from unittest.test.testmock import support
from unittest.test.testmock.support import SomeClass, is_instance
from test.test_importlib.util import uncache
from unittest.mock import (
NonCallableMock, CallableMixin, sentinel,
MagicMock, Mock, NonCallableMagicMock, patch, _patc... |
from PyQt4 import QtGui
from collector.ui.gen.im_export import Ui_Dialog
from collector.ui.views import Dialog
from collector.ui.helpers.customtoolbar import CustomToolbar
from collector.core.controller import get_manager
from collector.core.plugin import PluginExporter, PluginImporter
import logging
class BaseDialog(Q... |
import xmlrpc.client
from time import sleep
def remoteCall(func, *args):
try:
ret = func(*args)
return ret
except xmlrpc.client.Fault as e:
print(e)
server = xmlrpc.client.ServerProxy("https://localhost:8080", allow_none=True)
sid = remoteCall(server.login, "dj", "abc123")
print(remoteCa... |
"""
This tutorial introduces denoising auto-encoders (dA) using Theano.
Denoising autoencoders are the building blocks for SdA.
They are based on auto-encoders as the ones used in Bengio et al. 2007.
An autoencoder takes an input x and first maps it to a hidden representation
y = f_{\theta}(x) = s(Wx+b), parameter... |
from Screen import Screen
from Components.ActionMap import NumberActionMap
from Components.config import config, ConfigNothing, ConfigBoolean, ConfigSelection
from Components.Label import Label
from Components.SystemInfo import SystemInfo
from Components.ConfigList import ConfigListScreen
from Components.Pixmap import ... |
'''
A set of (smooth) loss functions.
Created on Oct 2, 2014
@author: jiayu.zhou
'''
import numpy as np;
def least_squares(w, X, y):
'''
least squares loss.
MATLAB verified function.
f(x) = 1/2 * ||X * w - y||_F^2.
Parameters
----------
w: np.matrix
X: np.matrix
y: np.matrix
Retu... |
import sys
from spalloc import (
config, ProtocolClient, ProtocolError, ProtocolTimeoutError,
SpallocServerException)
VERSION_RANGE_START = (0, 1, 0)
VERSION_RANGE_STOP = (5, 0, 1)
class Terminate(Exception):
def __init__(self, code, *args):
super().__init__()
self._code = code
args ... |
from graphics import *
from editor import *
from FileDialog import *
from console import *
import math
import sys
import re
import stack
import pickle
logger=None
class parser(viewbox):
"Draws a string specified in our little language"
def autocomplete(self):
"Completes fractal components that are unspe... |
import os
from enigma import eConsoleAppContainer
from Components.Harddisk import harddiskmanager
opkgDestinations = []
opkgStatusPath = ''
def opkgExtraDestinations():
global opkgDestinations
return ''.join([" --dest %s:%s" % (i,i) for i in opkgDestinations])
def opkgAddDestination(mountpoint):
pass
#global opkgDe... |
"""Unit tests for the parser engine."""
__revision__ = \
"$Id$"
import tempfile
from flask.ext.registry import PkgResourcesDirDiscoveryRegistry, \
ImportPathRegistry, RegistryProxy
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
Field_... |
from __future__ import unicode_literals
from django.db import models
class Urls(models.Model):
longurl = models.CharField(max_length=256)
shorturl = models.CharField(max_length=128) |
__author__ = 'mkaplenko'
import httplib
import time
class MobilMoneySms(object):
def __init__(self, phone_to, message):
self.phone_to = phone_to
self.message = message
self.sync = int(time.time()*100)
class MobilMoneySmsClient(object):
connection_host = 'gate.mobilmoney.ru'
response ... |
import binascii
import hashlib
from reversecoin.bitcoin.key import CKey as Key
from reversecoin.bitcoin.base58 import encode, decode
def myhash(s):
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
def myhash160(s):
h = hashlib.new('ripemd160')
h.update(hashlib.sha256(s).digest())
return h.dige... |
"""
MUSE -- A Multi-algorithm-collaborative Universal Structure-prediction Environment
Copyright (C) 2010-2017 by Zhong-Li Liu
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
version 2 of the... |
'''
Copyright (C) 2017 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
W... |
import pytest
from conftest import assert_bash_exec
@pytest.mark.bashcomp(cmd=None, ignore_env=r"^\+COMPREPLY=")
class TestUnitTilde:
def test_1(self, bash):
assert_bash_exec(bash, "_tilde >/dev/null")
def test_2(self, bash):
"""Test environment non-pollution, detected at teardown."""
as... |
from pwn import *
sh = ssh(host='192.168.1.104', user='root',
password='godmode', port=22)
cmd = sh.set_working_directory('/opt/protostar/bin')
e = ELF("./heap1")
puts_add = p32(e.got["puts"])
winner = pack(0x8048494)
print "puts: ", puts_add
arg1 = "A"*20
arg1 += puts_add
arg2 = winner
print sh.run(['.... |
import sys,time
from sys import path
import datetime
from time import sleep
import re
import redis
time_to_live = 3600
multiplier = 1
sys.path.append("/usr/local/lib/python2.7/site-packages/Adafruit-Raspberry-Pi-Python-Code/Adafruit_I2C/")
from Adafruit_I2C import Adafruit_I2C
redthis = redis.StrictRedis(host='433host'... |
"""
This is a example of a unittest module
"""
import unittest
class TestExample(unittest.TestCase):
"""
Test of test
"""
def test_one(self):
"""
This is a example of a unittest
"""
self.assertFalse(False)
def test_two(self):
"""
This is a example of a... |
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __init__(self):
self.pr... |
import tkinter
window = tkinter.Tk()
window.mainloop()
print('Anybody home?') |
"""API for manipulating organisation."""
from functools import partial
from elasticsearch.exceptions import NotFoundError
from .models import OrganisationIdentifier, OrganisationMetadata
from ..api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
from ..fetchers import id_fetcher
from ..item_types.api import ItemT... |
from setuptools import setup, find_packages
setup(
name='pulp_ostree_common',
version='1.0.0a1',
packages=find_packages(),
url='http://www.pulpproject.org',
license='GPLv2+',
author='Pulp Team',
author_email='pulp-list@redhat.com',
description='common code for pulp\'s ostree support',
) |
from ventana import Ventana
import utils
import pygtk
pygtk.require('2.0')
import gtk, gtk.glade, time, sqlobject
import sys, os
try:
import pclases
except ImportError:
sys.path.append(os.path.join('..', 'framework'))
import pclases
import mx, mx.DateTime
sys.path.append(os.path.join('..', 'informes'))
from... |
from twisted.internet import defer
from nav.smidumps import get_mib
from nav.mibs.mibretriever import MibRetriever
class HPHTTPManageableMib(MibRetriever):
"""HP-httpManageable-MIB (SEMI-MIB) MibRetriever"""
mib = get_mib('SEMI-MIB')
@defer.inlineCallbacks
def get_serial_number(self):
"""Tries t... |
"""
Django settings for central_service project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJE... |
import chanutils.torrent
from chanutils import get_json, movie_title_year
from playitem import TorrentPlayItem, PlayItemList
_SEARCH_URL = 'https://yts.mx/api/v2/list_movies.json'
_FEEDLIST = [
{'title':'Latest', 'url':'https://yts.mx/api/v2/list_movies.json?limit=50'},
{'title':'Highest Rated', 'url':'https://yts.... |
from phamerator import *
from phamerator.phamerator_manage_db import *
from phamerator.db_conf import db_conf
import sys, getpass
GeneID = sys.argv[1]
password = getpass.getpass()
db = raw_input('database: ')
c = db_conf(username='root', password=password, server='134.126.132.72', db=db).get_cursor()
print get_relative... |
"""
nrburst_pickle_preserve.py
Crunch together pickles from nrburst_match.py
"""
import sys
import glob
import cPickle as pickle
import numpy as np
pickle_files = glob.glob(sys.argv[1]+'*pickle')
user_tag = sys.argv[2]
delta_samp=100
sample_pairs=zip(range(0,1000,delta_samp), range(delta_samp-1,1000,delta_samp))
sim_in... |
import re
import os
import sys
def read_file(path):
lines = []
if (path.endswith('.cpp') or path.endswith('.h')):
if(os.path.isfile(path)):
handle = open(path, 'r')
for line in handle:
lines.append(line.strip())
handle.close()
return lines
def find... |
print "You enter a dark room with three doors. Do you go through door #1, door #2 or door #3?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "... |
import minecraft as minecraft
import random
import time
x = 128
y = 2
z = 128
mc = minecraft.Minecraft.create()
while y < 63:
j = mc.getBlock(x,y,z)
if j == 0:
mc.setBlock(x,y,z,8)
z = z - 1
if z <= -128:
z = 128
x = x - 1
if x<= -128:
x = 128
y = ... |
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in"
" the directory containing %r. It appears you've customized "
"things.\nYou'll have to run dja... |
import itertools
from typing import List, Any, Optional, TYPE_CHECKING
import networkx as nx
import numpy as np
import tqdm
from knossos_utils.skeleton import Skeleton, SkeletonAnnotation, SkeletonNode
from scipy import spatial
if TYPE_CHECKING:
from ..reps.super_segmentation import SuperSegmentationObject
from .. ... |
import xmltodict
def parseData(data):
try:
return xmltodict.parse(data)
except:
if len(data.split()) is 0:
return None
else:
raise Exception('Invalid XML data', data) |
"""
LAMP
"""
import numpy as np
tol = 1.e-6 # zero tolerance
def pdist(x):
"""
Pairwise distance between pairs of objects
TODO: find a fast function
"""
n, d = x.shape
dist = np.zeros((n, n))
for i in range(n):
for j in range(n):
dist[i][j] = np.linalg.norm(x[i] - x[j]... |
import os
from lutris import settings
from lutris.runners.runner import Runner
class mupen64plus(Runner):
"""Nintendo 64 emulator"""
human_name = "Mupen64Plus"
platform = "Nintendo 64"
game_options = [{
'option': 'main_file',
'type': 'file',
'label': 'ROM file',
'help': (... |
d, n = list(map(int, input().split()))
answer = 0
while n%10:
if n%10 == d:
answer += 1
n //= 10
print(answer) |
"""
<This library provides a Python interface for the Telegram Bot API>
Copyright (C) <2015> <Jacopo De Luca>
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 th... |
import os
DOWNLOAD_TMP_DIR = '/tmp'
REPOSITORY_PUBLIC_KEY = '/root/keys/cloud_key.pub'
LOCAL_REPOSITORY_DIR = '/pkgs'
HTML_DIR = '/usr/share/mod-pacmanager/html/'
IHM_RESET_SCRIPT = '/root/reset.py'
if os.path.exists("/root/repository"):
fh = open("/root/repository")
REPOSITORY_ADDRESS = fh.read().strip()
f... |
'''
* The MIT License (MIT)
*
* Copyright (c) 2016 Jorge Aranda Moro
*
* 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
* t... |
import datetime
import xml.etree.ElementTree as et
import pony.orm as orm
import sys
import os
pjoin = os.path.join
__dir__ = os.path.abspath(os.path.dirname(__file__))
sys.path.append(__dir__)
from server import *
dat = dict(
code = 'concefly',
last_login = datetime.datetime.now(),
user_type = 'admi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_flavor_facts
short_description: Retrieve facts about one or ... |
import glob
import gettext
__trans = gettext.translation('pisilinux', fallback=True)
_ = __trans.ugettext
import pisilinux.context as ctx
import pisilinux.actionsapi
from pisilinux.actionsapi import get
from pisilinux.actionsapi import cmaketools
from pisilinux.actionsapi import shelltools
basename = "qt4"
prefix = "/%... |
from __future__ import print_function
"""A replacement for the ``time.clock()`` function.
From the clock man page::
Note that the time can wrap around. On a 32bit system
where CLOCKS_PER_SEC equals 1000000 this function will
return the same value approximately every 72 minutes.
The ``clock()`` func... |
class IDatabase:
def enter_coin(coin):
raise Exception('NotImplementedError') |
import astra
import numpy as np
vol_geom = astra.create_vol_geom(256, 256)
proj_geom = astra.create_proj_geom('parallel', 1.0, 384, np.linspace(0,np.pi,180,False))
proj_id = astra.create_projector('strip', proj_geom, vol_geom)
import scipy.io
P = scipy.io.loadmat('phantom.mat')['phantom256']
sinogram_id, sinogram = ast... |
from matplotlib import pyplot as plt, colorbar
from lib2.VNATimeResolvedDispersiveMeasurement2D import *
class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D):
def __init__(self, name, sample_name, **devs_aliases_map):
devs_aliases_map["q_z_awg"] = None
super().__init__(name, sample_... |
import src
import random
class Shocker(src.items.Item):
"""
ingame item used as ressource to build bombs and stuff
should have the habit to explode at inconvienent times
"""
type = "Shocker"
def __init__(self):
"""
set up internal state
"""
super().__init__(displa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.