code stringlengths 1 199k |
|---|
from __future__ import print_function
import elapsedtimer
from elapsedtimer import *
import pytest
import time
import datetime
from sys import platform, version_info
def within(x, y, r):
print("within(%f, %f, %f)" % (x, y, r))
return abs(x - y) < r
def calibrate():
startTime = time.time()
for i in range... |
"""
Calculate travel-times of seismic waves in 2D.
* :func:`~fatiando.seismic.ttime2d.straight`: Calculate the travel-time of a
straight ray through a mesh of square cells
----
"""
import multiprocessing
import math
import numpy
try:
from fatiando.seismic import _ttime2d
except ImportError:
_ttime2d = None
de... |
from setuptools import setup, find_packages
from os import path, walk
author = 'Tomasz Hemperek, Jens Janssen, David-Leon Pohl'
author_email = 'hemperek@uni-bonn.de, janssen@physik.uni-bonn.de, pohl@physik.uni-bonn.de'
with open('VERSION') as version_file:
version = version_file.read().strip()
with open('requiremen... |
from django.conf import settings
from django.core.mail import send_mail, send_mass_mail
from django.core.mail import EmailMultiAlternatives
import html2text
class MailSender(object):
def __init__(self, server, username, password, ssl=False):
settings.EMAIL_HOST = server
settings.EMAIL_HOST_USER = us... |
WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
OPENID_PROVIDERS = [
{'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},
{'name': 'Yahoo', 'url': 'https://me.yahoo.com'},
{'name': 'AOL', 'url': 'http://openid.aol.com/<username>'},
{'name': 'Flickr', 'url': 'http://www.flickr.... |
from datetime import datetime
from datetime import timedelta
from todoman.cli import cli
from todoman.model import Database
from todoman.model import Todo
def test_priority(tmpdir, runner, create):
result = runner.invoke(cli, ["list"], catch_exceptions=False)
assert not result.exception
assert not result.ou... |
"""
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical
and the nodes have the same value.
https://oj.leetcode.com/problems/same-tree/
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = ... |
from .server import APIServer
__all__ = ['APIServer'] |
class G(object):
"""main class"""
pass |
from __future__ import division, unicode_literals
import itertools
from pymatgen.core.lattice import Lattice
import numpy as np
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.operations import SymmOp
class LatticeTestCase(PymatgenTest):
def setUp(self):
self.lattice = Lattice.cubic(10.0)
... |
import sys
class Backup(Exception): pass
class watch(object):
def __init__(self, name, gen, *gen_args):
self.name = name
print "%s.__init__()" % self.name
self.iterator = gen(*gen_args)
def __iter__(self):
print "%s.__iter__()" % self.name
self.iterator_iter = iter(self.i... |
import contextlib
import mock
import sqlite3
import packaging.version
import pytest
import sqlalchemy
import fauxdbi
sqlalchemy_version = packaging.version.parse(sqlalchemy.__version__)
sqlalchemy_1_3_or_higher = pytest.mark.skipif(
sqlalchemy_version < packaging.version.parse("1.3"),
reason="requires sqlalchem... |
from .source import Source # isort:skip
from .config import Config, load_config
from .group import Group |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
import string
import sys
test = TestSCons.TestSCons()
test.pass_test() #XXX Short-circuit until then.
test.write('SConstruct', "")
test.run(arguments = '--warn-undefined-variables',
stderr = "Warning: the --warn-undefined-var... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import sys
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.subdir('work1', 'work2')
test.write('succeed.py', r"""
import sys
file = open(sys.argv[1], 'wb')
file.write("succeed.py: %s\n" % sys.argv[1])
file.clos... |
import sys, os, fcntl, termios, struct, select, errno
from serialutil import *
VERSION = "$Revision: 1.27 $".split()[1] #extract CVS version
if (sys.hexversion < 0x020100f0):
import TERMIOS
else:
TERMIOS = termios
if (sys.hexversion < 0x020200f0):
import FCNTL
else:
FCNTL = fcntl
plat = sys.platform... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('autoemails', '0003_rqjob'),
('workshops', '0210_auto_20200124_1939'),
]
operations = [
migrations.AddField(
model_name='task',
name='rq_jobs',
field=... |
__author__ = 'Danyang'
class Solution:
def solve(self, cipher, lst):
"""
dp
"""
N, K= cipher
N = int(N)
K = int(K)
N = len(lst)
dp = [[1<<32 for _ in xrange(N+1)] for _ in xrange(N+1)]
for i in xrange(N):
dp[i][i] = 1
fo... |
from .path import SubPathAnnotation, PathAttribute
class SubAnnotation(SubPathAnnotation):
non_optional = False
subquery_match_template = '({def_collection_alias})-[:annotates]->({anchor_node_alias})'
def __repr__(self):
return '<SubAnnotation of {} under {}'.format(str(self.collected_node), str(sel... |
from . import api
class StudentEvents():
# StudentEvents.StudentEvents
def student_events(self, titleOnly=False, auth=True):
params = {'TitleOnly': titleOnly}
return api.call('StudentEvents', params, auth)
# StudentEvents.StudentEvents_Categories
def student_events_categories(self, inclu... |
from lib import Ctlr_Base_RSS_2_0
class Ctlr(Ctlr_Base_RSS_2_0):
_created_on = '2013-07-25T16:33:26Z'
_my_feeds = [
{"title": "即時社會", "url": "http://www.appledaily.com.tw/rss/newcreate/kind/rnews/type/102"},
{"title": "即時生活", "url": "http://www.appledaily.com.tw/rss/create/kind/rnews/type/105"},
{"title... |
import random
import datetime
import os
words = open('/usr/share/dict/words').readlines()
names = open('/usr/share/dict/words').readlines()
connectives = open('/usr/share/dict/words').readlines()
severities = [0, 1, 2, 3, 4, 5, 6, 7]
short_desc = "%s %s %s %s %s" % (
random.choice(names).strip(),
random... |
from flatland.util.signals import (
ANY,
ANY_ID,
NamedSignal,
Namespace,
Signal,
receiver_connected,
)
from tests._util import eq_, assert_raises
def test_meta_connect():
sentinel = []
def meta_received(**kw):
sentinel.append(kw)
assert not receiver_connected.receivers
... |
"""
Sphinx/docutils extension to create links to a Trac site using a
RestructuredText interpreted text role that looks like this::
:trac:`trac_link_text`
for example::
:trac:`#2015`
creates a link to ticket number 2015.
adapted from recipe U{here <http://stackoverflow.com/a/2111327/13564>}
"""
import urllib
fro... |
import time
import json
from zope import interface
from twisted.web import client
from twisted.internet import defer
from piped.plugins.status_testing import statustest, processors
from piped import processing
client.HTTPClientFactory.noisy = False
class TestRPCProcessor(processors.StatusTestProcessor):
interface.c... |
"""Download data from database."""
from os.path import join
from ugali.analysis.pipeline import Pipeline
from ugali.preprocess.database import databaseFactory
from ugali.utils.shell import mkdir
components = ['data']
def run(self):
#db = databaseFactory(self.config)
#db.run(outdir=self.config['data']['dirname']... |
"""
This module implements VideoClip (base class for video clips) and its
main subclasses:
- Animated clips: VideofileClip, DirectoryClip
- Static image clips: ImageClip, ColorClip, TextClip,
"""
import os
import subprocess as sp
import multiprocessing
import tempfile
from copy import copy
from tqdm import tqdm
imp... |
from imlib.basic import *
from imlib.dtype import *
from imlib.transform import * |
"""
This module contains functions for writing of Chemkin input files.
"""
import shutil
import math
import re
import logging
import textwrap
import os.path
import numpy
import rmgpy.kinetics as _kinetics
from rmgpy.reaction import Reaction
from rmgpy.rmg.model import Species
from rmgpy.rmg.pdep import PDepReaction
fro... |
"""setup the python package.py"""
from shatter.helpers import read_file
import os
import re
from subprocess import call
__author__ = 'juan pablo isaza'
def has_code(line):
return re.match(r'`.+`', line) or re.match(r'^ .+', line)
def get_code_pieces(line):
code_line = re.match(r'^\s{4,}.+', line)
if code... |
import demistomock as demisto
action = demisto.getArg('action')
if action not in ['link', 'unlink']:
action = 'link'
demisto.results(demisto.executeCommand("linkIncidents", {"linkedIncidentIDs": demisto.getArg("linkedIncidentIDs"),
"action": action})) |
from __future__ import print_function
import email.utils
import fcntl
import io
import os
import pkg_resources
import pwd
import random
import resource
import socket
import sys
import textwrap
import time
import traceback
import inspect
import errno
import warnings
import cgi
import logging
from gunicorn.errors import ... |
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_dathomir_singingmtnclanpatrol_medium1.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="textfont", parent_name="scattergeo.selected", **kwargs
):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent... |
import re
from django.core.exceptions import ValidationError
def validate_name(value):
if not re.match(r'^[А-Я][а-я]*(\-[а-я]*)*$', value):
raise ValidationError('Поддерживаются только русские буквы\
и тире. Перая буква Должна быть заглавной')
def validate_profession(value):
... |
import sys
import os
filepath = ' '.join(sys.argv[1:])
os.system("libreoffice -show \"" + filepath + "\"") |
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
def return_formatted_time(
specificity='second',
small_separator='-',
big_separator='_'):
import time
a = time.localtime()
args = a.tm_year, a.tm_mon, a.tm_mday, a.tm_... |
"""Handles database interaction."""
import logging
from flask import current_app
import pymongo
from pymongo.collation import Collation, CollationStrength
from pymongo.errors import PyMongoError
from api import PicoException
log = logging.getLogger(__name__)
__connection = None
__client = None
def get_conn():
"""
... |
""" Blueprints for oauthclient. """
from __future__ import absolute_import
from .client import blueprint as client_blueprint
from .settings import blueprint as settings_blueprint
blueprints = [
client_blueprint,
settings_blueprint,
] |
from docgen import DocGen |
import json
import pytest
from wrapanapi.exceptions import MultipleItemsError
from wrapanapi.exceptions import NotFoundError
from cfme import test_requirements
from cfme.infrastructure.provider import InfraProvider
from cfme.markers.env_markers.provider import ONE
from cfme.rest.gen_data import mark_vm_as_template
from... |
class Listener:
listenTo = 'noObject' |
import dbus as _dbus
from openrazer.client.devices import RazerDevice as __RazerDevice
from openrazer.client.macro import RazerMacro as _RazerMacro
from openrazer.client import constants as _c
class RazerMouse(__RazerDevice):
_MACRO_CLASS = _RazerMacro
@property
def max_dpi(self) -> int:
"""
... |
from __future__ import unicode_literals
from django.views.generic import DetailView, ListView, TemplateView
from parler.views import TranslatableSlugMixin
from .models import Simple, Untranslated
class SimpleRootView(TemplateView):
template = 'test_addon/empty.html'
class SimpleListView(ListView):
model = Simpl... |
"""
Emotion Calculational controller to folllow beam trajectory
real motors : Sx Sy Sz
Calc motors : Bx By Bz
ID16A (ni)
"""
from emotion import CalcController
from emotion import log as elog
from emotion.controller import add_axis_method
import math
class id16beam(CalcController):
def __init__(self, *args, **kwarg... |
"""
High-level tools for interacting with the LDAP for users.
@author: Andy Georges
The LdapUser class will bind to the LDAP server using LdapQuery, so
there is no need to do this manually.
If this code is extended, it should be Python 2.4 compatible until such time
as all machines where we might require LDAP accesss.
... |
"""
KeepNote
extended plist module
Apple's property list xml serialization
- added null type
"""
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.elementtree.ElementTree as ET
from StringIO import StringIO
from xml.sax.saxutils import escape
import base64, datetime, ... |
import ige.ospace.Const as Const
from ige import NoSuchObjectException
import client, types, string, res, gdata
from ige import log
from ige.ospace import Rules
def techID2Name(techID):
if techID >= 1000:
return _(client.getTechInfo(techID).name.encode())
else:
return client.getPlayer().shipDesi... |
"""
***************************************************************************
dinfdistup.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************... |
import matplotlib.pyplot as plt
def trace_complexes(x,y,fichier,xlabel='Frequence $f$', title='', style='ro'):
plt.figure(0,figsize=(9,5))
plt.clf()
plt.grid(True)
p0 = plt.subplot(3,1,1)
p0.set_title(title)
p0.grid()
p0.plot(x,[yy.real for yy in y],style,linewidth=2.0)
p0.set_ylabel('Partie reelle', fo... |
import pytest
from rpmlint.checks.SysVInitOnSystemdCheck import SysVInitOnSystemdCheck
from rpmlint.filter import Filter
from Testing import CONFIG, get_tested_package
@pytest.fixture(scope='function', autouse=True)
def sysvcheck():
CONFIG.info = True
output = Filter(CONFIG)
test = SysVInitOnSystemdCheck(CO... |
class Muro:
cor = color(150,70,0)
s = 10
def __init__(self, w, h):
self.estrutura = []
cols = w/self.s
lista = range(cols/3, 2*cols/3)
for i in range(cols):
if not i in lista:
x = i * self.s
y = 0
self.estrutura.appe... |
import moose
import pylab
import numpy as np
from matplotlib import pyplot as plt
def setupSteadyState(simdt,plotDt):
ksolve = moose.Ksolve( '/model/kinetics/ksolve' )
stoich = moose.Stoich( '/model/kinetics/stoich' )
stoich.compartment = moose.element('/model/kinetics')
stoich.ksolve = ksolve
#ksol... |
from ctypes import c_int
__all__ = ["SDL_BLENDMODE_NONE", "SDL_BLENDMODE_BLEND", "SDL_BLENDMODE_ADD",
"SDL_BLENDMODE_MOD", "SDL_BlendMode"
]
SDL_BLENDMODE_NONE = 0x00000000
SDL_BLENDMODE_BLEND = 0x00000001
SDL_BLENDMODE_ADD = 0x00000002
SDL_BLENDMODE_MOD = 0x00000004
SDL_BlendMode = c_int |
"""
***************************************************************************
GetScriptsAndModels.py
---------------------
Date : June 2014
Copyright : (C) 2014 by Victor Olaya
Email : volayaf at gmail dot com
**********************************************... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('audits', '0008_auto_20200508_2105'),
]
operations = [
migrations.AlterField(
model_name='ftplog',
name='operate',
field=models.CharField(choices=[('Delete', ... |
"""
urlresolver plugin
Copyright (c) 2018 gujal
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 t... |
from __future__ import absolute_import
from flask_login import login_user
from realms.modules.auth.models import BaseUser
users = {}
class User(BaseUser):
type = 'proxy'
def __init__(self, username, email='null@localhost.local', password="dummypassword"):
self.id = username
self.username = usern... |
from datetime import datetime
from listenbrainz.model import db
from listenbrainz.webserver.admin import AdminModelView
class Spotify(db.Model):
__tablename__ = 'spotify_auth'
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), primary_key=True)
user_token = db.Column(db.String, nu... |
from Pyblio import Fields, Autoload
from Pyblio.Style import Utils
import sys
db = bibopen (sys.argv [2])
keys = db.keys ()
keys.sort ()
url = Fields.URL (sys.argv [3])
Utils.generate (url, Autoload.get_by_name ('output', sys.argv [4]).data,
db, keys, sys.stdout) |
import logging
import os
import shutil
import tempfile
import unittest
from unattended_upgrade import update_kept_pkgs_file
class MotdTestCase(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmpdir)
self.addCleanup(logging.shutdown)
... |
"""This module contains tests that exercise the canned VMware Automate stuff."""
import fauxfactory
import pytest
from textwrap import dedent
from cfme.automate.buttons import ButtonGroup, Button
from cfme.automate.explorer import Namespace, Class, Instance, Domain, Method
from cfme.automate.service_dialogs import Serv... |
from pyx import *
c = canvas.canvas()
c.fill(path.rect(0, 0, 7, 3), [color.gray(0.8)])
c.fill(path.rect(1, 1, 1, 1), [color.rgb.red])
c.fill(path.rect(3, 1, 1, 1), [color.rgb.green])
c.fill(path.rect(5, 1, 1, 1), [color.rgb.blue])
c.writePDFfile() |
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', 'default_set.news.views.index', name='news_index'),
url(r'^(?P<slug>[\w-]+)/$', 'default_set.news.views.detail',
name='news_detail'),
) |
from converter import *
class IRQVector:
def __init__(self, xml, n):
path="INTERRUPT_VECTOR/VECTOR%d/" % (n+1)
self.addr=navnum(xml, path+"PROGRAM_ADDRESS")
self.src=navtxt(xml, path+"SOURCE") # source of interrupt
# the EEPROM ready interrupt seems to be named different for each dev... |
import os
from persistent import Persistent
import tempfile
from indico.util.json import loads
from MaKaC.common.Counter import Counter
from indico.core.config import Config
class BadgeTemplateManager(Persistent):
""" This class is used to manage the badge templates
of a given conference.
An instanc... |
from setuptools import setup
setup(name='cyautomation',
version='0.1',
description='Library for internal automation at City Year',
url='https://github.com/mrklees/cy-automation-library',
author='Alex Perusse',
license='MIT',
packages=['cyautomation.cyschoolhouse'],
zip_safe=Fal... |
from whipper.common import path
from whipper.test import common
class FilterTestCase(common.TestCase):
def setUp(self):
self._filter = path.PathFilter(special=True)
def testSlash(self):
part = 'A Charm/A Blade'
self.assertEqual(self._filter.filter(part), 'A Charm-A Blade')
def testFa... |
'''
Driver method to run the Altens module
'''
import sys
sys.path.append('./')
import altens
import sassie.interface.input_filter as input_filter
import multiprocessing
svariables = {}
runname = 'run_0'
rdc_input_file = "RDC_D_K63.txt"
pdbfile='1D3Z_mod1_new.pdb'
residue_list_file = "reslist.txt"
use_monte_carlo_flag ... |
import os
from typing import TypeVar, Type
from paramiko import RSAKey
from snapcraft.internal.build_providers import errors
SSHKeyT = TypeVar("SSHKeyT", bound="SSHKey")
class SSHKey:
"""SSHKey provides primitives to create and use RSA keys with SSH.
The general use case is that if an instance of SSHKey returns... |
import aiofiles
from .base import BaseResult
class FileResult(BaseResult):
def __init__(self, url, **kwargs):
super().__init__(url)
if self.schema != 'file':
raise ValueError('scheme error')
self.path = self.database
def prepare(self):
"""
check file exist
... |
"""
Classes used to provide grouping leaves mechanism.
"""
import copy
import itertools
import time
import weakref
from kupfer.objects import Leaf, Source
from kupfer import utils
__author__ = ("Karol Będkowski <karol.bedkowsk+gh@gmail.com>, "
"Ulrik Sverdrup <ulrik.sverdrup@gmail.com>" )
class GroupingLe... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
def deepnn(x):
"""deepnn builds the graph for a deep net for classifying digits.
Args:
x: an input tensor with the dimensions (N_examples, 784), where 784 is the
number of pixels in ... |
"""
hackish file to crreate deb from setup.py
"""
import subprocess
from email.utils import formatdate
import aravis
DEBVERSION =aravis.__version__
branch = subprocess.check_output("git rev-parse --abbrev-ref HEAD", shell=True)
branch = branch.decode()
branch = branch.strip()
branch = str(branch).replace("'","")
rev = ... |
'''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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.
T... |
'''
This file is part of eogMetaEdit.
eogMetaEdit 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.
eogMetaEdit is distributed in the hope that... |
"""Copyright 2015 Rafal Kowalski"""
from sqlalchemy.event import listens_for
from .event import Event
from .version import Version
@listens_for(Event, "after_insert")
def after_insert(mapper, connection, target):
"""Update Version after insert to db"""
link_table = Version.__table__
version = Version.query.... |
'ci_verified' not in self.actions['newlabel'] and 'ci_verified' not in self.actions['unlabel'] |
""" SLURM.py is a DIRAC independent class representing SLURM batch system.
SLURM objects are used as backend batch system representation for
LocalComputingElement and SSHComputingElement classes
"""
__RCSID__ = "$Id$"
import commands, os, re
class SLURM( object ):
def submitJob( self, **kwargs ):
""" Subm... |
"""
Implementation of umath.py, with internals.
"""
from __future__ import division # Many analytical derivatives depend on this
import math
import sys
import itertools
import inspect
import uncertainties.core as uncert_core
from uncertainties.core import (to_affine_scalar, AffineScalarFunc,
... |
type = "passive"
def handler(fit, src, context):
fit.fighters.filteredItemBoost(lambda mod: mod.item.requiresSkill("Fighters"), "maxVelocity",
src.getModifiedItemAttr("shipBonusCarrierM3"), skill="Minmatar Carrier") |
"""Extensions over the Telegram Bot API to facilitate bot making"""
from .dispatcher import Dispatcher, DispatcherHandlerStop, run_async
from .jobqueue import JobQueue, Job
from .updater import Updater
from .callbackqueryhandler import CallbackQueryHandler
from .choseninlineresulthandler import ChosenInlineResultHandle... |
"""
This script demonstrates how to use moogli to carry out a simulation and
simultaneously update the visualizer.
The visualizer remains active while the simulation is running.
"""
try:
import moogli
except ImportError as e:
print( "[INFO ] Could not import moogli. Quitting..." )
quit()
import moose
from m... |
import e3
from e3.base import status
import papyon
STATUS_PAPY_TO_E3 = { \
papyon.Presence.ONLINE : status.ONLINE,
papyon.Presence.BUSY : status.BUSY,
papyon.Presence.IDLE : status.IDLE,
papyon.Presence.AWAY : status.AWAY,
papyon.Presence.BE_RIGHT_BACK : status.AWAY,
papyon.Presence.ON_THE_PHONE... |
from ImageScripter import *
from elan import *
Android.getResolution() |
import logging
from random import choice
logger = logging.getLogger(__name__)
class AI(object):
""" Base class for an AI model object.
"""
def make_decision(self, npc, opponents):
""" Given a npc, and list of opponents, decide an action to take
:param npc: The monster whose decision is being... |
from dolfin import *
from numpy import ones
series = TimeSeries("primal")
mesh = UnitSquareMesh(2, 2)
x = Vector()
t = 0.0
while t < 1.0:
# Refine mesh
mesh = refine(mesh);
# Set some vector values
x = Vector(mesh.mpi_comm(), mesh.num_vertices());
x[:] = ones(x.size())
# Append to series
ser... |
import logging
import os
import io
import time
from zipfile import ZipFile
from guessit import guessit
from requests import Session
from subliminal import Episode, Movie
from subliminal.score import get_equivalent_release_groups
from subliminal.utils import sanitize_release_group, sanitize
from subliminal_patch.provide... |
from datetime import timedelta
import numpy as np
import pytz
class SunCycles(object):
SETTING = "sunset"
RISING = "sunrise"
@classmethod
def cycles(cls, **kwargs):
"""
Classmethod for convenience in returning both the sunrise and sunset
based on a location and date. Always calc... |
import pygame;
def color_surface(surface, red, green, blue):
arr = pygame.surfarray.pixels3d(surface)
arr[:,:,0] = red
arr[:,:,1] = green
arr[:,:,2] = blue |
import sys
import os
import unittest
import random
import numpy as np
try:
import openglider
except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
import openglider
import openglider.graphics
import openglider.plots.marks as marks
class TestMarks(unittest.TestCa... |
import random
import sys
import os
import unittest
from visual_test_glider import GliderTestClass
try:
import openglider
except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
import openglider
from openglider.glider.cell import DiagonalRib, Panel, TensionStrap
i... |
import time
import logs
from json import loads, dumps
import mutagen
from mutagen import File
from os import walk, remove
from os.path import join
from whoosh import qparser
from whoosh.analysis import NgramWordAnalyzer
from whoosh.collectors import TimeLimitCollector, TimeLimit
from whoosh.fields import Schema, TEXT, ... |
from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, Pango
from sonata.misc import escape_html
songlabel = None
lyricslabel = None
def on_enable(state):
global songlabel, lyricslabel
if state:
songlabel = Gtk.Label("No song info received yet.")
songlabel.props.ellipsize = Pango.ELLIPSIZE_END
... |
from .JSONSerializator import JSONSerializator |
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils import timezone
class TestView(models.Model):
"""
Represents a views that should be tested. It expects 'GET' or 'POST'
as method, a URL and optionally a data dictionary.
"""
method = models.CharField(... |
import unittest as ut
import importlib_wrapper
import numpy as np
try:
import MDAnalysis # pylint: disable=unused-import
except ImportError:
sample = importlib_wrapper.MagicMock()
skipIfMissingFeatures = ut.skip(
"Python module MDAnalysis not available, skipping test!")
else:
sample, skipIfMiss... |
from __future__ import unicode_literals
from functools import wraps
from indico.core.db import db
from indico.core.settings import SettingsProxyBase
from indico.core.settings.models.base import JSONSettingsBase
from indico.core.settings.util import get_all_settings, get_setting
from indico.util.string import return_asc... |
import os
from setuptools import setup, find_packages
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='elastic',
version='0.0.1',
packages=find_packages(),
package_data={'elastic': ['tests/data/*gz',
... |
__version__ = '3.0.0b2'
if __name__ != '__main__':
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.