code stringlengths 1 199k |
|---|
"""Random functions that don't fit elsewhere."""
from collections import defaultdict
from contextlib import contextmanager
import collections
import functools
import hashlib
import json
import os
import pkg_resources
import socket
import subprocess
import tempfile
import urllib
from kitchen.iterutils import iterate
fro... |
from weightless.core import compose
from meresco.core import Observable
class FieldsListToLuceneDocument(Observable):
def __init__(self, fieldRegistry, untokenizedFieldnames, indexFieldFactory, rewriteIdentifier=None, **kwargs):
Observable.__init__(self, **kwargs)
self._fieldRegistry = fieldRegistry... |
"""
Slovenian-specific definitions of relationships
"""
from __future__ import unicode_literals
from gramps.gen.lib import Person
import gramps.gen.relationship
_ancestors = [ "", "starš", "stari starš", "prastari starš" ]
_fathers = [ "", "oče", "ded", "praded", "prapraded" ]
_mothers = [ "", "mati", "babica", "prabab... |
import pandas as pd
import numpy as np
import cPickle as pickle
from sklearn import preprocessing
from sklearn.feature_extraction import DictVectorizer
from sklearn_pandas import DataFrameMapper
from param import config
def build_features(features, data):
# remove NaNs
data.fillna(0, inplace=True)
data.loc[... |
from functools import wraps
import attr
import asyncio
class Controller(object):
"""
Standard procedure:
1. connect, assign callbacks
2. discover groups/subcontrollers, assign callback (refs to parent cb)
3. children auto-trigger publish cb, reflect initial to properties
"""
... |
from tornado.web import UIModule
class EduCubeTelemetry(UIModule):
def javascript_files(self):
return [
# "bootstrap.min.js",
# "jquery.js"
]
def css_files(self):
return [
# "bootstrap.min.css",
# "portfolio-item.css"
]
def rend... |
from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo
class FilesonicCom(DeadHoster):
__name__ = "FilesonicCom"
__type__ = "hoster"
__version__ = "0.37"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?filesonic\.com/file/\w+'
__config__ = [] #@TODO: Remove in ... |
from .svt import SVT, mixed_noise_model
__all__ = ["mixed_noise_model", "SVT"] |
"""
Copyright 2017 Robin Verschueren
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... |
import json, logging, inspect, functools
class APIError(Exception):
def __init__(self, error, data='', message=''):
super(APIError, self).__init__(message)
self.error = error
self.data = data
self.message = message
class APIValueError(APIError):
"""docstring for APIValueError"""
def __init__(self, field, mes... |
from ..Engine.TestResults import TestResults
from ..Engine.TestSuite import TestSuite
import io
import traceback
import sys
class ConsoleTestRunner:
"""Runs tests and displays minimal output at the console.
This behaves like the simple cosole test runners in JUnit etc,
displaying a dot for a passed test, F ... |
"""Combine all the different protocols into a simple interface."""
import logging
import os
import importlib
from .ssdp import SSDP
from .mdns import MDNS
from .gdm import GDM
from .lms import LMS
from .tellstick import Tellstick
from .daikin import Daikin
from .smartglass import XboxSmartGlass
_LOGGER = logging.getLog... |
from datetime import datetime
from csv import writer as csvwriter
from json import dump
from django.shortcuts import get_object_or_404, redirect, HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.gzip import gzip_page
from django.apps import apps
from django.urls im... |
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from player import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('player.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_... |
from distutils.core import setup
setup(
name='hit',
version='1.0',
packages=['hit', 'hit.serial', 'hit.train', 'hit.process', 'hit.importer', 'app.trainer'],
url='',
license='',
author='Albert Sanso, Eloi Puertas',
author_email='albertsanso@gmail.com, eloipuertas@gmail.com',
description=... |
from nive.utils.path import DvPath
from nive.definitions import *
from nive.portal import Portal
from nive.security import User, Allow, Everyone
from nive.application import Application
from nive.utils.dataPool2.files import File
root = RootConf(
id = "root",
name = "Data root",
default = 1,
context = "... |
'''
This module contains the various objects and methods for representing the
index to an instance of a table, included the underlying ISAM keydesc
representation.
'''
__all__ = ('TableIndex', 'PrimaryIndex', 'DuplicateIndex', 'UniqueIndex',
'AscPrimaryIndex', 'AscDuplicateIndex', 'AscUniqueIndex',
... |
from __future__ import print_function
from openturns import *
{
// First, build two functions from R^3->R
Description inVar(3);
inVar[0] = "x1";
inVar[1] = "x2";
inVar[2] = "x3";
Description outVar(1);
outVar[0] = "y";
Description formula(1);
formula[0] = "x1^3 * sin(x2 + 2.5 * x3)... |
"""Test testprocess.Process."""
import sys
import time
import contextlib
import datetime
import pytest
from PyQt5.QtCore import QProcess
import testprocess
pytestmark = [pytest.mark.not_frozen]
@contextlib.contextmanager
def stopwatch(min_ms=None, max_ms=None):
if min_ms is None and max_ms is None:
raise Va... |
import threading
from queue import Queue
from plasma.lib.utils import unsigned
from plasma.lib.fileformat.binary import T_BIN_PE, T_BIN_ELF
from plasma.lib.consts import *
ALL_SP = {}
class Analyzer(threading.Thread):
def init(self):
self.dis = None
self.msg = Queue()
self.pending = set() # ... |
""" Compiled generator object type.
Another cornerstone of the integration into CPython. Try to behave as well as normal
generator expression objects do or even better.
"""
compiled_genexpr_type_code = """
// *** Nuitka_Genexpr type begin
// TODO: Could optimize it through a compile time determination.
const int MAX_IT... |
import unittest
import Rhino.Geometry as geom
import rhinoscriptsyntax as rs
import transformations as trans
import unfold
import Map
import Net
import meshUtils.meshLoad as meshLoad
import meshUtils.mesh as mesh
reload(meshLoad)
reload(Net)
reload(unfold)
reload(trans)
reload(mesh)
reload(Map)
def setUpModule():
p... |
offset = 0x0C00
rev_code = {
"M": 0xC01, # ఁ
"x": 0xC02, # ం
"X": 0xC03, # ః
"a": 0xC05, # అ
"A": 0xC06, # ఆ
"i": 0xC07, # ఇ
"I": 0xC08, # ఈ
"u": 0xC09, # ఉ
"U": 0xC0A, # ఊ
"WR": 0xC0B, # ఋ
"": 0xC0C, # -
"WA": 0xC0D, # -
"e": 0xC0E, # ఎ
"E": 0xC0F, ... |
import asynctest
import bot # noqa: F401
from asynctest.mock import Mock, patch
from lib.cache import CacheStore
from lib.data.message import Message
from lib.helper import parser
from tests.unittest.mock_class import StrContains
from .. import library
def send(messages):
pass
class TestFeatureLibrary(asynctest.Te... |
from dolfin import *
import numpy as np
import petsc4py
from petsc4py import PETSc
from slepc4py import SLEPc
from meshDS import*
petsc4py.init()
petsc4py.PETSc.Sys.popErrorHandler()
class projectKL(object):
"""Docstring for projectKL. """
def __init__(self,mesh):
"""TODO: to be defined1. """
# ... |
import re
from xml.sax.saxutils import escape
class SodsHtml():
def __init__(self, table, i_max = 30, j_max = 30):
''' init and set default values for spreadsheet elements '''
self.table = table
# set default css table cell border
self.default_border = 'none;'
self.cell_style... |
import os
import subprocess
import logging
import show_message as show
""" AutoPartition class """
MAX_ROOT_SIZE = 30000
MIN_ROOT_SIZE = 6500
def check_output(command):
""" Calls subprocess.check_output, decodes its exit and removes trailing \n """
return subprocess.check_output(command.split()).decode().strip(... |
from re import findall
from cloudbot import hook
from cloudbot.util.formatting import get_text_list
polls = {}
class PollError(Exception):
pass
class PollOption:
def __init__(self, title):
self.title = title
self.votes = 0
class Poll:
def __init__(self, question, creator, options=("Yes", "No... |
from __future__ import absolute_import
import unittest
from solfege.utils import string_get_line_at
class TestStringGetLineAt(unittest.TestCase):
def test1(self):
self.assertEquals(string_get_line_at("abc", 1), "abc")
self.assertEquals(string_get_line_at("\nabc", 1), "abc")
self.assertEquals... |
'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layer... |
import urllib
import urllib2
import os
import re
import sys
import xbmc
import xbmcgui
import xbmcaddon
import time
import datetime
import json
from resources.lib.tvhighlights import TVDScraper
__addon__ = xbmcaddon.Addon()
__addonID__ = __addon__.getAddonInfo('id')
__addonname__ = __addon__.getAddonInfo('name')
__vers... |
import numpy as np
from alis import almsgs
from alis import alfunc_base
msgs=almsgs.msgs()
class PowerLaw(alfunc_base.Base) :
"""
Returns a 1-dimensional gaussian of form:
p[0] = amplitude
p[1] = x offset
p[2] = dispersion (sigma)
"""
def __init__(self, prgname="", getinst=False, atomic=None... |
from .tcpsocket_adapter import TcpSocketDeviceAdapter
from .tcpsocket_server import TcpSocketDeviceServer
__all__ = ['TcpSocketDeviceAdapter', 'TcpSocketDeviceServer'] |
'''
Demo application function to compute a simple vector addition computation
between 2 arrays using OpenCL.
'''
from numpy import *
import opencl
opencl_source = '''
__kernel void
vector_add (__global char *c, __global char *a, __global char *b)
{
// Index of the elements to add
unsigned int n = get_global_id(0);
... |
from __future__ import unicode_literals
from django.db import migrations, models
def fixDinnerClub(apps, schema_editor):
tranModel = apps.get_model('cashier', 'transaction')
trans = tranModel.objects.all()
for tran in trans:
if tran.amount < 0:
tran.amount *= -1
tran.save()
c... |
from django.http import HttpResponse
from django.shortcuts import render
def main(request):
"""docstring for mainscreen"""
return render(request, 'index/index.html') |
from __future__ import absolute_import, division, with_statement
import functools
from tornado.escape import url_escape
from tornado.httpclient import AsyncHTTPClient
from tornado.log import app_log
from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog
from tornado.util import b
from tornado.web impor... |
from __future__ import absolute_import
import json
from datetime import date
from flask import request
from invenio.base.i18n import _
from invenio.config import CFG_DATACITE_DOI_PREFIX
from invenio.config import CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL
from invenio.modules.deposit import fields
from invenio.modules.depos... |
import logging
import shlex
from threading import Timer, current_thread
from types import ModuleType
from typing import Tuple, Callable, Mapping, Sequence
from io import IOBase
import re
from .storage import StoreMixin, StoreNotOpenError
from errbot.backends.base import Message, Presence, Stream, Room, Identifier, ONLI... |
import ase
from ase.utils.geometry import cut, stack
from ase import io
from ase import atoms
substrate = ase.io.read('POSCAR.SnO.vasp',format='vasp')
epilayer = ase.io.read('POSCAR.NiO.vasp',format='vasp')
angle_of_rotation = 0.5 # The increment of rotation
centre_of_mass = epilayer.get_center_of_mass()
epilaye... |
CREAK = 'CREAK'
WITHIT = 'WITHIT'
ROCKITT = 'ROCKITT'
WACKER = 'WACKER'
TAKE = 'TAKE'
ALBERT = 'ALBERT'
TEARAWAY = 'TEARAWAY'
BULLY = 'BULLY'
SWOT = 'SWOT'
HERO = 'HERO'
HEROINE = 'HEROINE'
BOY01 = 'BOY01'
BOY02 = 'BOY02'
BOY03 = 'BOY03'
BOY04 = 'BOY04'
BOY05 = 'BOY05'
BOY06 = 'BOY06'
BOY07 = 'BOY07'
BOY08 = 'BOY08'
BO... |
""" Translate GDAY output file
Match the NCEAS format and while we are at it carry out unit conversion so that
we matched required standard. Data should be comma-delimited
"""
import shutil
import os
import numpy as np
import csv
import sys
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
from ... |
from .GListApp import GListApp |
from safeeyes import utility
def validate(plugin_config, plugin_settings):
command = None
if utility.DESKTOP_ENVIRONMENT == "gnome" and utility.IS_WAYLAND:
command = "dbus-send"
elif utility.DESKTOP_ENVIRONMENT == "sway":
command = "swayidle"
else:
command = "xprintidle"
if n... |
import urllib,re,xbmcgui,xbmcplugin,xbmc,sys,process,requests
def Movie_Main():
process.Menu('Genre','',202,'','','','')
process.Menu('IMDB top 250 Films','http://www.imdb.com/chart/top',206,'','','','')
process.Menu('Movie Channels','',208,'','','','')
process.Menu('Search','',207,'','','','')
xbmc... |
from blindr import create_app
app = create_app('config.heroku')
app.logger.info('[server] init done') |
"""listeria URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
from django.conf.urls import url
from valhalla.sciapplications.views import (
SciApplicationCreateView, SciApplicationUpdateView, SciApplicationIndexView,
SciApplicationDetailView, SciApplicationDeleteView, SciApplicationPDFView
)
app_name = 'sciapplications'
urlpatterns = [
url(r'^$', SciApplicationIndexVi... |
"""Script to post to AutoIrishLitDiscourses.tumblr.com. Really rough sketch of a
script here. Not really meant for public use.
There are multiple scripts that post to this Tumblr account. This particular
script is meant to impersonate Matthew Arnold, based on his book /Celtic
Literature/.
The fact that there isn't real... |
def pi_wallis(n):
""" Producto de Wallis para π """
producto = 1
k = 1
while k <= n:
producto *= (2 * k) ** 2 / (2 * k + 1) / (2 * k - 1)
k += 1
return producto * 2
def main():
print(pi_wallis(500))
print(pi_wallis(500000))
main() |
import traceback, sys, gc, os
import threading
import logging
def setup_logging(level=logging.INFO):
handler = logging.StreamHandler()
handler.setLevel(level)
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s'))
# set handler for base logger
logging.getLogger().... |
from dateutil.parser import parse
tableName = 'MICEX_SBER'
startDateTime = parse('2011-06-01T10:30')
plotTitle = 'Гистограмма исходных данных'
imageName = 'Plot.png'
n = 200 # Size of window
precision = 3
binWidth = 50
from common.get_data import getData
import numpy as np
from scipy.stats import gamma # Gamma distribu... |
import shutil
import subprocess
import tempfile
import unittest
import calypso.config
class CalypsoTestCase(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
calypso.config.set('storage', 'folder', self.tmpdir)
subprocess.call(["git", "init", self.tmpdir])
subproc... |
from server import sql_database, Items, ExpiryEvents, Sellers, DBConnection
import sqlite3 as sql
import datetime
if __name__ == '__main__':
dry_run = True
with DBConnection() as conn:
now = datetime.datetime.now()
items = Items.select(conn, "ExpiryDate < ?", now)
for item in items:
... |
import re
class Feature_getter:
pass
class Single_feature_getter(Feature_getter):
def __init__(self):
self.feature_name = ''
self.feature_type = ''
def get_value(self, review):
# "Abstract" method.
pass
class SentiWS_based_feature_getter(Single_feature_getter):
def __init... |
__author__ = "Raul Perula-Martinez"
__email__ = "raul.perula@uc3m.es"
__date__ = "2014-11"
__license__ = "GPL v3"
__version__ = "1.0.0"
import re
cadena = raw_input("Introduce una cadena: ")
patron = re.compile(r"^([\-\+]?\d+)[,\.](\d+)\Z")
if patron.search(cadena):
print "Es un número decimal";
numero = patron.searc... |
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class RegistroUsuario(forms.ModelForm):
password = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='Repite tu password',widget=forms.PasswordInput)
class Meta:
model = Use... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import unittest
import time
import os
import shutil
import sys
import six
from DIRAC.Core.Base.Script import parseCommandLine, getPositionalArgs
parseCommandLine()
from DIRAC import gLogger
from DIRAC.Resources.... |
'''Bot de Telegram que permanece a la espera de que alguien le envie un comando (texto o un audio) por Telegram. Una vez lo recibe:
- si es texto lo envia al NLP para que procese el texto en busca de lo que se desea hacer.
- si es audio (.wav) lo envia al ASR para que obtenga el texto y este sea enviado al NLP ... |
'''
Abstract classes are defined differently between python 2 and 3.
A syntax error is thrown if you even include the python3 format
in python 2 code (even inside guards that prevent the code from executing).
This is the appropriate definition for python 2.
Copyright 2016 GoodCrypto
Last modifie... |
import gtk
import pango
from ..engine import BadCommandException
from .model import CommandStore
from .common import get_icon_pixbuf
class Entry(gtk.Entry):
def __init__(self, engine):
gtk.Entry.__init__(self)
settings = engine.settings
settings.commands.connect('reset-commands', self.comman... |
import sigrokdecode as srd
from collections import namedtuple
class Ann:
'''Annotation and binary output classes.'''
(
BIT, START, DATA, PARITY_OK, PARITY_ERR,
STOP_OK, STOP_ERR, BREAK,
OPCODE, DATA_PROG, DATA_DEV, PDI_BREAK,
ENABLE, DISABLE, COMMAND,
) = range(15)
(
... |
"""
Get VM instances available in the configured cloud sites
"""
from DIRAC import gLogger, exit as DIRACExit
from DIRAC.Core.Utilities.DIRACScript import DIRACScript as Script
@Script()
def main():
Script.registerArgument("site: Site name")
Script.registerArgument("CE: Cloud Endpoint Name")
Script.regi... |
def is_deficient(n):
devisors = []
for i in range(1, n):
if n % i == 0:
devisors.append(i)
if sum(devisors) <= n:
return True
else:
return False
def main():
try:
a,b = input("Enter two strictly positive numbers: ").split()
if a.isnumeric() and b.isnumeric():
pass
else:
raise ValueError
a,b =... |
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from django.contrib.auth.models import User
def main(request):
logged_in = False
user = ''
if request.user.is_authenticated():
user = request.user.username
logge... |
class customer(object):
"""Deze klasse houdt het klantenbestand bij""" |
from configuration import config
import os.path
import rrdtool
import logging
logger = logging.getLogger('monitor')
def _get_ds_def(src_def):
src_str = 'DS:{}:GAUGE:120:0:32768'
return [src_str.format(a_src) for a_src in src_def]
src_nodes = ['clients', 'wifilinks', 'vpns']
ds_nodes = _get_ds_def(src_nodes)
src... |
import re
import sdf_helper as sh
def parse_name_val(str, delim='=', include_strings=False):
if str.find(delim) == -1:
return None
pair = str.split(delim)
if len(pair) != 2:
return None
val = None
try:
val = int(pair[1].strip())
except:
try:
val = floa... |
"""
Simple FITS astronomy viewer/processor
AUTHOR
----
Mike Tyszka, Ph.D.
DATES
----
2018-10-08 JMT From scratch
LICENSE
----
This file is part of Stellate.
Stellate 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,... |
from scap.model.xs.TokenType import TokenType
class ChoiceGroupIDPattern(TokenType):
# <xsd:pattern value="ocil:[A-Za-z0-9_\-\.]+:choicegroup:[1-9][0-9]*"/>
pass |
try:
import sys
import warnings
import numpy
import os
import time
from classes.misc import misc
from digitemp.master import UART_Adapter
from digitemp.device import AddressableDevice
from digitemp.device import DS18B20
except ImportError as e:
print (e)
raise
if ( sys.version_info[0] < 3 ):
warnings.war... |
"""
Module implementing a class to store task data.
"""
from __future__ import unicode_literals
import os
import time
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTreeWidgetItem
import UI.PixmapCache
import Preferences
class Task(QTreeWidgetItem):
"""
Class implementing the task data structure.
... |
from __future__ import absolute_import, unicode_literals
import logging
import requests
from .base import BaseDiscovery, DiscoveryResult
log = logging.getLogger(__name__)
class KeybaseDiscovery(BaseDiscovery):
"""Discover pgp keys and others contact identities in keybase."""
KEYBASE_DEFAULT_BASE_URL = 'https://... |
__author__ = 'calthorpe_analytics'
from django.contrib.auth import get_user_model
from django.db import models
from footprint.main.managers.geo_inheritance_manager import GeoInheritanceManager
from footprint.main.models.geospatial.feature import PaintingFeature
from footprint.main.models import AnalysisModule
import lo... |
"""Telescope action to park the telescope"""
from warwick.observatory.operations import TelescopeAction, TelescopeActionStatus
from warwick.observatory.operations.actions.onemetre.telescope_helpers import tel_stop, tel_park
class ParkTelescope(TelescopeAction):
"""Telescope action to park the telescope"""
def _... |
import numpy as np
import mirheo as mir
ranks = (1, 1, 1)
domain = (16, 16, 8)
u = mir.Mirheo(ranks, domain, debug_level=3, log_filename='log', no_splash=True)
center=(domain[0]*0.5, domain[1]*0.5)
wall = mir.Walls.Cylinder("cylinder", center=center, radius=domain[1]*0.4, axis="z", inside=True)
u.registerWall(wall, 10... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "droplets.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is rea... |
"""Copyright (C) 2013 COLDWELL AG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that i... |
import textwrap, ftplib, sys, os
def get_notice():
return textwrap.dedent('''\
FTP Client Copyright (C) 2017 Bryan R. Martinez (github.com/bryanrm)
See the GNU General Public License for more details.
''')
def session_loop(ftp):
try:
print(get_notice())
print(str(ftp.getwelcome()).... |
import argparse
import getpass
import re
import sys
from match import match_tracks
from playmusic import PlayMusic
from rdio import Rdio
from report import Report
parser = argparse.ArgumentParser(description='Export playlists and favorites from Rdio to Play Music')
parser.add_argument('rdio_username', help='username on... |
import json
import urllib.parse
import urllib.request
from urllib.error import URLError
import hashlib
import hmac
import time
import logging
import threading
import queue
from ams.sql import DataBase
class Pool():
name = "pool"
def __init__(self, user, worker, key, seckey=None):
self.key = key
... |
from datetime import datetime
import json
import logging
import os
import requests
import traceback
from scout.datasource import DataSource
class Stackoverflow(DataSource):
""" Get events from Stackoverflow using the Stackexchange API """
def create_tables(self):
""" The name of the fields are the same ... |
from .launcher import OpenVPNNotFoundException, VPNLauncherException
from leap.bitmask.vpn.launchers.linux import (
NoPolkitAuthAgentAvailable, NoPkexecAvailable)
from leap.bitmask.vpn.launchers.darwin import NoTunKextLoaded
__all__ = ["OpenVPNNotFoundException", "VPNLauncherException",
"NoPolkitAuthAgen... |
import sys
if sys.version_info < (2, 6):
sys.exit("rootpy only supports python 2.6 and above")
try:
import ROOT
except ImportError:
sys.exit("ROOT cannot be imported. Is ROOT installed with PyROOT enabled?")
ROOT.PyConfig.IgnoreCommandLineOptions = True
if ROOT.gROOT.GetVersionInt() < 52800:
sys.exit("r... |
from setuptools import setup
setup(
name='gedcom-rdf',
version='0.1',
py_modules=['gedcomrdf',],
license='GPLv3+',
test_suite='tests',
description="Convert GEDCOM files to/from RDF",
author="Rory McCann",
author_email="rory@technomancy.org",
classifiers=[
'Programming Languag... |
import re
from flask import jsonify, request
import time
from werkzeug.security import generate_password_hash
from werkzeug.utils import redirect
from apps import config
from apps.blueprint import api
from apps.init_app import mongo
from flask_login import current_user, login_user, logout_user, login_required
from apps... |
'''
Project: strum https://github.com/smh69/strum
Scale names and their compositions
Copyright (C) 2010-2015, Spencer Michael Hanson
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... |
import sqlite3
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
class Quote(object):
def __init__(self, db):
try:
self.connect = sqlite3.connect(db)
self.curs... |
""" Operate on classifiers """
import copy
import numpy
from pySPACE.missions.nodes.base_node import BaseNode
from pySPACE.resources.data_types.prediction_vector import PredictionVector
class SplitClassifierLayerNode(BaseNode):
""" Split the overrepresented class in the training set for multiple training.
The n... |
import random
from base import Plugin
RANDOM_MESSAGES = open('plugins/random_messages.txt').read().splitlines()
class Static(Plugin):
"""
class for testing the new random message functionality
"""
NAME = "Random Messages"
AUTHOR = "kellner@cs.uni-goettingen.de"
VERSION = (0, 0, 1)
ENA... |
import os
import sys
import sdl2.ext
if not sys.path[0] in os.environ["PATH"].split(":"):
print(os.path.abspath(os.curdir + "/src"))
sys.path.append(os.path.abspath(os.curdir + "/src"))
import render
sdl2.ext.init()
my_render = render.Renderer("Muh title", 640, 480)
input() |
import math
import unittest
from .test_core import createSolution
from ..indicators import GenerationalDistance, InvertedGenerationalDistance, \
EpsilonIndicator, Spacing, Hypervolume
from ..core import Solution, Problem, POSITIVE_INFINITY
class TestGenerationalDistance(unittest.TestCase):
def test(self):
... |
@make(inputs=[0, 1, 2, 3], outputs=[4], handler=Output.STORE)
def get_project_resource_availability(ctx, project_id, ingest="true", destination="false", archive="false"):
"""
Get if a project's resource(s) is/are up
Parameters
----------
ctx : Context
Combined type of a callback and rei stru... |
"""Convenience module to spatially and temporally smooth functional data."""
import os
import numpy as np
from nibabel import load, save, Nifti1Image
from scipy.ndimage.filters import gaussian_filter, gaussian_filter1d
strPthIn = '/str/to/nii/'
strPthOut = '/str/to/nii/out/'
if not os.path.exists(strPthOut):
os.mak... |
import os
import subprocess
import sys
def thisdir():
return os.path.dirname(os.path.realpath(__file__))
def execute(command_parts):
try:
subprocess.check_call(command_parts, stderr=subprocess.STDOUT)
return True
except Exception as e:
print("An error occurred during execution of " + ' ... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1099, 601)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self... |
"""
This is the application entry. This is where we create and run the
Application.
"""
from .app import Application
def main():
"""
Application entry point.
"""
app = Application()
ret_code = app.run()
app.close()
return ret_code |
import os, json, logging, pickle
import numpy as np
from collections import defaultdict
from copy import deepcopy
from mapserver.graph.contractor2 import GraphContractor
from mapserver.routing.router2 import Router
from networkx.readwrite import json_graph as imports
from mapserver.graph.update import GraphUpdate
from ... |
"""Handle time series data.
@author : Liangjun Zhu
@changelog:
- 18-10-29 - lj - Extract from other packages.
"""
from __future__ import absolute_import, unicode_literals
import bisect
from collections import OrderedDict
from datetime import datetime
from typing import List, Dict, Optional, Union, AnyStr
... |
"""
ESSArch is an open source archiving and digital preservation system
ESSArch
Copyright (C) 2005-2019 ES Solutions AB
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.