code stringlengths 1 199k |
|---|
import metomi.rose.macro
class LogicalTransformer(metomi.rose.macro.MacroBase):
"""Test class to change the value of a boolean environment variable."""
WARNING_CHANGED_VALUE = "{0} -> {1}"
def transform(self, config, meta_config=None):
"""Perform the transform operation on the env switch."""
... |
"""
PyGMI stands for Python Geoscience Modelling and Interpretation.
It is a modelling and interpretation suite aimed at magnetic, gravity and other
datasets. It includes:
* Magnetic and Gravity 3D forward modelling
* Cluster Analysis
* Routines for cutting, reprojecting and doing simple modifications to data
* Con... |
import re
__author__ = 'Chris Ottersen'
exp_template = r"""
^
(?P<SMStext>I\x00P\x00M\x00\.\x00S\x00M\x00S\x00t\x00e\x00x\x00t\x00\x00\x00)
(?P<content>
(?:
\x8B\x41.\x01
(?P<phone_2>(?:..){,20}?\x00\x00)
\x8B\x41.\x01
(... |
from optparse import make_option
import sys
from deluge.ui.console.main import BaseCommand
import deluge.ui.console.colors as colors
from deluge.ui.client import client
import deluge.common as common
import deluge.component as component
status_keys = ["state",
"save_path",
"tracker",
"next_annou... |
"""Tests related to host map and network map
:requirement: SSSD NSS should support host map
:casecomponent: sssd
:subsystemteam: sst_idm_sssd
:upstream: yes
"""
from __future__ import print_function
from sssd.testlib.common.utils import sssdTools
import pytest
@pytest.mark.usefixtures('setup_sssd', 'enable_sssd_hostmap... |
f = open(sys.argv[1], "r")
lines = f.readlines()
f.close()
for line in lines:
print("System.out.println(\"" + line.replace("\\", "\\\\") + "\");") |
"""The TemporalNetwork class in teneto is a way of representing network objects."""
import inspect
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from ..utils import df_to_array, gen_nettype, binarize,\
df_drop_ij_duplicates, get_network_when, set_diagonal
from .. import networkmeasures
from... |
from __future__ import print_function, absolute_import, unicode_literals, division
from builtins import (ascii, bytes, chr, dict, filter, hex, input,
map, next, oct, pow, range, round,
str, super, zip, object)
import unittest
import sys
import forgi.threedee.model.coarse_grai... |
import tornado.web
import requests
import settings
import simplejson as json
import os
import httplib
import logging
class BaseHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
def render(self, template, **kwargs):
kwargs['current_pa... |
import classes.level_controller as lc
import classes.game_driver as gd
import classes.extras as ex
import pygame
import classes.board
import random
from math import pi,cos,sin
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self,mainloop,15... |
""" Page Object Model - Analytics Page """
from .selectors.analytics import PAGE_HEADER, OVERVIEW_STATS, GYM_MAP, \
GYM_LIST_TITLE, GYM_LIST_TABLE, LEVEL_LIST_TABLE, LEVEL_LIST_TITLE, \
DAY_LIST_TABLE, DAY_LIST_TITLE, HOUR_LIST_TABLE, HOUR_LIST_TITLE, \
TABLE_CONTENTS
from .common import BasePage
class Anal... |
from drf_yasg.inspectors import SwaggerAutoSchema
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
class CustomSwaggerAutoSchema(SwaggerAutoSchema):
def get_tags(self, operation_keys):
if len(operation_keys) > 2:
return [operation_key... |
from setuptools import setup
version = "0.8.3"
filename = "0.8.3-20120108"
setup(name="pyscxml",
version=filename,
description="A pure Python SCXML parser/interpreter",
long_description="Use PySCXML to parse and execute an SCXML document. PySCXML aims for full compliance with the W3C standard. Feature... |
"""
It used to create several plots
"""
import time
import copy
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Utilities.Plotting import gDataCache
from DIRAC.Core.Utilities.Plotting.Plots import generateNoDataPlot, generateTimedStackedBarPlot, generateQualityPlot, generateCumulativePlot, generatePiePlot, gen... |
"""Handle communication between python client and PHP backdoor"""
__all__ = ["py2php", "php2py", "Build", "Encode"]
import codecs
import base64
import phpserialize
import core
from core import session
from core import encoding
from datatypes import Path
from .exceptions import BuildError
def _phpserialize_recursive_dic... |
import scrapy
from dotup_scrapy.items import DotupItem
import re
class DotupSpider(scrapy.Spider):
name = 'dotup'
start_urls = ['http://dotup.org']
# This regex extracts the filename from URLs
id_re = re.compile(r'([0-9]+).[a-z0-9]{1,4}')
def parse(self, response):
for href in response.selec... |
'''
Copyright 2013, 2014 Nedim Srndic, University of Tuebingen
This file is part of Mimicus.
Mimicus 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 v... |
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import dateutil
import six
from requests.compat import unquote_plus
from tornado.escape import xhtml_unescape
from trakt import TraktAPI
import sickbeard
import sickchill
from sickbeard import config, db, helper... |
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
def start(bot, update):
keyboard = [[Inline... |
def readline (self):
while 1:
if self:
if __file__:
continue
return
def _parse(a, b, source, state):
while 1:
if b:
while 1:
break
else:
raise
def _parse2(source, state):
while 1:
if a:
if... |
from __future__ import absolute_import
import logging
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from .base import BetterBase, session_scope
from .log import Log
class DropAssociation(BetterBase):
__tablename__ = 'drop_table'
enemy_id = Column(Int... |
__author__ = 'Viktor Kerkez <alefnula@gmail.com>'
__contact__ = 'alefnula@gmail.com'
__date__ = '21 October 2010'
__copyright__ = 'Copyright (c) 2010 Viktor Kerkez'
from distutils.core import setup
setup(
name = 'Panda',
version = '0.0.1',
description = 'Panda is a Scheme... |
import kivy
kivy.require('1.9.1')
from kivy.uix.boxlayout import BoxLayout
from kivy.app import Builder
from kivy.uix.spinner import Spinner
from mappedspinner import MappedSpinner
from utils import *
from valuefield import IntegerValueField, FloatValueField
from autosportlabs.racecapture.views.configuration.baseconfig... |
"""
Code to transform data from Mercator [1] into a common scheme.
[1] https://github.com/fabric8-analytics/mercator-go
"""
import argparse
import json
import sys
from itertools import zip_longest
from os import path
from tempfile import TemporaryDirectory
from urllib.parse import urlparse
from f8a_worker.utils import ... |
'''
view a mission log on a map
'''
import sys, time, os
import re
from math import *
from pymavlink import mavutil, mavwp, mavextra
from MAVProxy.modules.mavproxy_map import mp_slipmap, mp_tile
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.lib import grapher
... |
from __future__ import division
import base64
import random
import re
import sys
import time
from twisted.internet import defer
from twisted.python import log
import bitcoin.getwork as bitcoin_getwork, bitcoin.data as bitcoin_data
from bitcoin import helper, script, worker_interface
from util import forest, jsonrpc, va... |
import time
from functools import partial
from starcluster.logger import log
from starcluster import utils
from starcluster.node import Node
from starcluster.node import NodeRecoveryManager
class StreamingNodeAdd(object):
"""
Class specialized in adding nodes as a stream.
Rather than having to wait at each ... |
class StateLayoutVersionMismatchException(Exception):
def __init__(self, message):
super(StateLayoutVersionMismatchException, self).__init__(message)
class UnknownStateStoreException(Exception):
def __init__(self, message):
super(UnknownStateStoreException, self).__init__(message)
class StateNot... |
"""ORCID util tests."""
from __future__ import absolute_import, division, print_function
import pytest
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from inspire_dojson.utils import get_record_ref
from inspire_schemas.api import validate
from inspirehep.modules.records.api import InspireRecord
from... |
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from astakos.im.models import Project
from astakos.im.quotas import get_project_quota
from synnefo.util import units
from synnefo_admin.admin.exceptions import AdminHttp404
from synnefo_admin.admin.utils import is_resource_useful, crea... |
"""
========
ctang, a map of geba stations in southern africa
========
"""
import math
import pdb
import datetime
import pandas as pd
import numpy as np
import matplotlib as mpl
from textwrap import wrap
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap , addcyclic
from matplotlib.dates import Ye... |
from IGCexpansion.CodonGeneconv import ReCodonGeneconv
import argparse
def main(args):
paralog = [args.paralog1, args.paralog2]
alignment_file = '../MafftAlignment/' + '_'.join(paralog) + '/' + '_'.join(paralog) + '_input.fasta'
newicktree = './YeastTree.newick'
if args.force:
if args.model == '... |
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
BASE_URL = "%s/" % plugin.get_setting("base_nyaa")
HEADERS = {
"Referer": BASE_URL,
}
CATEGORIES = [
("Anime", "1_0"... |
class Config(dict):
def clone_nopasswd(self):
new_copy = self.copy()
new_copy['imap_password'] = '**Password Hidden**'
new_copy['smtp_password'] = '**Password Hidden**'
new_copy['imap_folders_to_exclude'] = '**Folder List Here**'
return new_copy |
"""
Executes gradient magnitude filter over images.
Copyright (C) 2013 Oskar Maier
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 versio... |
from myhdl import *
FX2_OUT_FIFO = int('00', base=2)
FX2_IN_FIFO = int('01', base=2)
class Bus(object): pass
def get_interfaces():
""" Single function to get the buses
"""
clock = Signal(bool(1))
reset = ResetSignal(bool(1), active=0, async=False)
# Get an object that can be used for the "interfaces... |
"""
Copyright (C) 2012 Caio Oliveira <caio.freitaso@gmail.com>
Copyright (C) 2012 Diego Toral <diegotoral@gmail.com>
Copyright (C) 2012 Thiago Abreu <thiagoa7@gmail.com>
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 Sof... |
import argparse
helpString = ""
helpString += "Computes the derivatives of the transition dipole moment of an "
helpString += "electronic one-photon transition with respect to the atomic "
helpString += "coordinates based on a numerical excited-state frequency "
helpString += "calculation"
parser = argparse.ArgumentPar... |
"""
Count related records in a MySQL database.
"""
import argparse
import getpass
import sys
import pymysql.cursors
__author__ = 'Markus Englund'
__license__ = 'GNU GPLv3'
__version__ = '0.2.1'
def get_related_columns(user, host, password, db, table_name):
connection = pymysql.connect(
host=host, user=user,... |
import numpy as np
import cv2
class Video_saver:
def __init__(self,name,size):
self.name= name
self.size = size
def Save_video(self,List_img):
video = cv2.VideoWriter('Videos/'+self.name+'.avi',cv2.cv.CV_FOURCC('D', 'I', 'V', 'X'), 25.0, self.size)
for L_Img in List_img:
... |
import requests
import json
def get_weather(url):
result = requests.get(url)
if result.status_code == 200:
return result.json()
else:
return('Не могу получить данные о погоде!')
def get_names(url='http://api.data.mos.ru/v1/datasets/2009/rows', year=None):
if year in [2015, 2016]:
... |
import unittest
import sys
import os
import errno
import time
from datetime import datetime, timedelta
try:
from urllib.request import HTTPBasicAuthHandler
except:
from urllib2 import HTTPBasicAuthHandler
sys.path.append( os.path.join("..", "src", "bin") )
from syndication import SyndicationModularInput
from sy... |
import sys, os
sys.path.append('./tools/')
import traversal, bfutils, graphkit
import unknownrate as ur
from multiprocessing import Pool,Process, Queue, cpu_count, current_process
import functools
import zickle as zkl
import time, socket
import scipy
import clingo as cg
UMAX = 1
INPNUM = 1 # number of randomized starts... |
__author__ = "David Rusk <drusk@uvic.ca>"
from displayable import DisplayableImageSinglet
def display_hdulist(hdulist):
DisplayableImageSinglet(hdulist).render() |
'''
Created on 19/12/2013
@author: pablo
'''
import csv
import ldap
import ldap.modlist as modlist
import uuid
l = ldap.initialize("ldap://127.0.0.1:3389")
l.protocol_version = ldap.VERSION3
l.simple_bind("cn=admin,dc=econo", "pcucqccp")
with open('/tmp/alumnos-carla.csv') as csvfile:
reader = csv.reader(csvfil... |
import sys, os
sys.path.insert(0, os.path.abspath('..'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
'sphinx.ext.todo', 'sphinx.ext.coverage']
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8-sig'
master_doc = 'index'
project = 'ViTables Users\' Guide'
copyrig... |
import logging
logger = logging.getLogger(__name__)
from .driver import Neo4jDriver |
from .entry_content import sanitize_entry_content |
import numpy as np
import pandas as pd
import scipy.io
import sys
sys.path.append("../")
from functions import *
from pylab import *
from sklearn.decomposition import PCA
import _pickle as cPickle
import neuroseries as nts
import os
from scipy.ndimage import gaussian_filter
data_directory = '/mnt/DataGuillaume/MergedD... |
import datetime
def get_start_of_week(day):
if day.weekday() == 6: return day
weekday = day.weekday() + 1
start_delta = datetime.timedelta(days=weekday)
start_of_week = day - start_delta
return start_of_week |
"""This demo program solves the incompressible Navier-Stokes equations
on an L-shaped domain using Chorin's splitting method."""
from dolfin import *
parameters["std_out_all_processes"] = False;
mesh = Mesh("../lshape.xml.gz")
V = VectorFunctionSpace(mesh, "Lagrange", 2)
Q = FunctionSpace(mesh, "Lagrange", 1)
u = Trial... |
from django import template
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def update_button(id, name):
content = u"""
<div class="ln_solid"></div>
<button id="{0}" class="btn btn-success btn-round">{1}</button>
"""
return format_html(content... |
import sys, time, os
import numpy as np
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
import pycuda.gpuarray as gpuarray
currentDirectory = os.getcwd()
parentDirectory = currentDirectory[:currentDirectory.rfind("/")]
toolsDirectory = parentDirectory + "/tools"
sys.path.extend( [toolsDirectory, v... |
from __future__ import absolute_import
import logging
import hashlib
import re
from core.point import Point
from core.customgcode import CustomGCode
from core.layercontent import Layers, Shapes
from globals.d2gexceptions import VersionMismatchError
import globals.globals as g
from globals.six import text_type
import gl... |
"""
Input form with special options.
"""
__revision__ = "$Rev: 2974 $"
__date__ = "$Date: 2008-08-14 11:26:19 -0400 (Thu, 14 Aug 2008) $"
__author__ = "$Author: johann $"
from django import forms
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
class SpecialForm(forms.Form)... |
from pycds.orm.manual_matviews import (
monthly_total_precipitation_with_total_coverage,
monthly_total_precipitation_with_avg_coverage,
MonthlyTotalPrecipitation,
)
import pytest
def check(results, months, variable):
assert {r.vars_id for r in results} == {variable.id}
assert {r.obs_month.month for ... |
from __future__ import unicode_literals
from django.db import migrations
import wiki.plugins.metadata.models
class Migration(migrations.Migration):
dependencies = [
('metadata', '0033_auto_20180703_1308'),
]
operations = [
migrations.AlterField(
model_name='adpositionrevision',
... |
"""
@author: Gasmi
"""
import matplotlib.pyplot as plt
import volmdlr.core_compiled
import volmdlr
import volmdlr.core
from volmdlr.core_compiled import Matrix33
from itertools import combinations
import numpy as npy
import volmdlr.edges
import volmdlr.wires
import volmdlr.faces
from volmdlr.core_compiled import Matrix... |
import os
from sysproduction.data.directories import (
get_statefile_directory,
get_statefile_backup_directory,
)
from sysdata.data_blob import dataBlob
def backup_state_files():
data = dataBlob(log_name="backup_state_files")
backup_object = backupStateFiles(data)
backup_object.backup_files()
re... |
from modeller import *
from modeller.scripts import complete_pdb
env=environ()
env.libs.topology.read(file='$(LIB)/top_heav.lib')
env.libs.parameters.read(file='$(LIB)/par.lib')
log.verbose()
mdl = complete_pdb(env, '1cuk')
atmsel = selection(mdl)
saxs = saxsdata(env)
saxs.ini_saxs(atmsel=atmsel, s_min= 0.0, s_max=0.5,... |
from models import Conference
from models import ConferenceForm
from models import ConferenceForms
from models import ConferenceQueryForm
from models import ConferenceQueryForms
DEFAULTS = {
"city": "Default City",
"maxAttendees": 0,
"seatsAvailable": 0,
"topics": [ "Default", "Topic" ],
}
OPERATORS = {... |
from PyQt4.QtGui import QDialog, QFormLayout, QLabel, QDialogButtonBox, QComboBox, QCheckBox , QSpinBox , QLineEdit
from PyQt4.QtCore import Qt, SIGNAL
from widgets.util import createSpace
import os
class NewConfigurationDialog(QDialog):
"""A dialog for selecting defaults for a new configuration."""
def __init_... |
from distutils.core import setup
setup(
name='pyroku',
version='0.1',
description='A simple interface to the Roku streaming player.',
author='Alex Philipp',
author_email='alex@snapfiber.com',
url='https://github.com/alex-sf/pyroku',
packages=['pyroku'],
license='GPL',
long_descriptio... |
"""
Construct a bunch of images of the pointy star objects
find . -exec convert {} {}.jpg \;
"""
import Image
from math import atan2, cos, sin, sqrt
from random import random, choice
WIDTH = 600
HEIGHT = 600
WD2 = float(WIDTH/2)
HD2 = float(HEIGHT/2)
PI = 3.14159265358979323
PID2 = PI / 2.0
PIPI = 2.0 * PI
out_dir = ... |
'''
Created on 8 Nov 2012
@author: George
'''
'''
Models a FIFO queue where entities can wait in order to get into a server
'''
import simpy
from CoreObject import CoreObject
class Queue(CoreObject):
family='Buffer'
#===========================================================================
# the __init__ ... |
from . import invoice_topay_report |
"""
tarotclub game python AI
this is a try to make a python AI for the tarotclub game
"""
class Card(object):
"""generic card"""
COLOR_STRENGTH = {'T': 4, 'S': 3, 'H': 2, 'D': 1, 'C': 0}
COLOR = ['C', 'D', 'H', 'S', 'T', ' ']
def __init__(self, value=0, color=''):
self._value = value
try... |
import os
import sys
import cv2
from libraries.background import BackGround
if __name__ == '__main__':
myBackGround = BackGround()
videoAddress = os.getenv('HOME') +'/trafficFlow/trialVideos'
DEFAULT_WEBCAM_ADDRESS = 1
videoInput = DEFAULT_WEBCAM_ADDRESS
for input in sys.argv:
if ('.mp4' in ... |
import cv2
import glob
import datetime
import numpy as np
from ..pathsandnames import PathsAndNames
class PiCameraOperations():
@staticmethod
def _scale():
"""
Scale the input resolution to the ROI resolution
:return: vector two points of a Box
DEPRECATED
"""
scal... |
import re
def isprime(n):
'''
>>> for n in inclusive_range(0, 10):
... print('{0} is prime: {1}'.format(n, isprime(n)))
...
0 is prime: False
1 is prime: False
2 is prime: True
3 is prime: True
4 is prime: False
5 is prime: True
6 is prime: False
7 is prime: True
8... |
"""Webserver
"""
import os
import sys
from engine.page import Page
from engine.conf import PATH_TO_HTML, PATH_TO_TEMPLATE_HTML, PATH_TO_TEMPLATE, PATH_TO_MD
from engine.postprocessing import add_head
from flask import Flask, redirect, url_for, send_from_directory, request
import time
import subprocess
import re
import ... |
from .app import main |
"""Make sure the complex gate sensorgraph works correctly."""
from iotile.sg.sim import SensorGraphSimulator
from iotile.sg import DataStream
def test_complex_gate_basic(complex_gate, complex_gate_opt):
"""Make sure the sg compiled and optimized."""
sg, sg_opt = complex_gate, complex_gate_opt
# Check for re... |
import logging
import re
from .format import BuiltinFormat
class Model(object):
logger = logging.getLogger("pipboy.Model")
server = {
"info": {"lang": "en", "version": "1.1.30.0"},
"run_server": False,
"run_client": False,
}
__startup = {
"Inventory": {},
"Log": [... |
import time
extensions = ['sphinx.ext.imgmath',
'sphinxcontrib.bibtex',
'sphinx.ext.githubpages',
'sphinx_toolbox.collapse']
templates_path = ['_templates']
source_suffix = ['.rst', '.md']
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
master_doc = 'index'
project = u'Ec... |
from os.path import dirname
from os.path import join as path_join
from os import environ
from zlib import compress, decompress
from base64 import b64encode, b64decode
import pickle
if 'TXPLAYA_PLAYLISTS' in environ:
PATH = environ['TXPLAYA_PLAYLISTS']
else:
from os.path import expanduser
PATH = path_join(ex... |
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Line, Rectangle
from kivy.core.text import Label as CoreLabel
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
class Controller(FloatLayout):
"""Create a controller that receives a custo... |
import ROOT
from rootpy.io import open as ropen
from rootpy.tree import Tree
f = ropen("test.root", "recreate")
print ROOT.gDirectory.GetName()
t = Tree()
f2 = ropen("test2.root", "recreate")
f2.Close()
print ROOT.gDirectory.GetName()
t.Write()
f.Close() |
from netaddr import IPNetwork, IPAddress, ZEROFILL
from lib.utils import call_ansible, write_role
def action_set_static_ip(arg):
if arg not in ['yes', 'no']:
print 'error: only "yes" and "no" are allowed'
return 10
arg = "static" if arg == "yes" else "dhcp"
print 'interface mode: %s' % arg
... |
DEFAULT_DOCKER_COMMAND = "docker"
DEFAULT_SUDO = True
DEFAULT_SUDO_COMMAND = "sudo"
DEFAULT_HOST = None
DEFAULT_VOLUME_MOUNT_TYPE = "rw"
DEFAULT_WORKING_DIRECTORY = None
DEFAULT_NET = None
DEFAULT_MEMORY = None
DEFAULT_VOLUMES_FROM = None
class DockerVolume(object):
def __init__(self, path, to_path=None, how=DEFAUL... |
from mock import patch, call
import mock
from .test_helper import patch_open, raises
from collections import namedtuple
from kiwi.partitioner.msdos import PartitionerMsDos
from kiwi.exceptions import KiwiPartitionerMsDosFlagError
class TestPartitionerMsDos(object):
def setup(self):
disk_provider = mock.Mock... |
"""
Copyright (C) 2011 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from traceback import format_exc
from django.http import HttpResponse, HttpResponseServerError... |
def find_outlier(integers):
import operator
# Print arguments
print('integers = {}'.format(integers))
# First, determine the "trend" - is it mostly odd? Or mostly even?
even_tracker = 0 # positive = even; negative = odd
# We only need to look at the first 3 integers, to determine a set's trend
for i in integers... |
"""
Django settings for accounts project.
Generated by 'django-admin startproject' using Django 1.8.7.
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
impor... |
"""Builtin application: rose_prune: suite housekeeping application."""
import os
from random import shuffle
from rose.app_run import BuiltinApp, ConfigValueError
from rose.date import RoseDateTimeOperator
from rose.env import env_var_process, UnboundEnvironmentVariableError
from rose.fs_util import FileSystemEvent
from... |
import argparse
from unittest.mock import MagicMock
import pytest
from randovania.cli import server
def test_server_command_logic(mocker):
# Setup
mock_create_app: MagicMock = mocker.patch("randovania.server.app.create_app")
# Run
server.flask_command_logic(None)
# Assert
mock_create_app.assert_... |
"""web 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-based v... |
from ctypes import *
import os
class Info(Structure):
_fields_ = [
("bd_size", c_uint64),
("bd_block_size", c_uint64),
("bd_major", c_int),
("bd_minor", c_int),
("ch_major", c_int),
("ch_minor", c_int),
("capabilities", c_int)
]
class _ctrlreq_create(Struc... |
"""
Dr. Disco - testing fix-chimeric
[License: GNU General Public License v3 (GPLv3)]
This file is part of Dr. Disco.
FuMa 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
(... |
"""Errors decoding Unicode data.
"""
import codecs
import sys
from codecs_to_hex import to_hex
error_handling = sys.argv[1]
text = u'pi: \u03c0'
print 'Original :', repr(text)
with codecs.open('decode_error.txt', 'w', encoding='utf-16') as f:
f.write(text)
with open('decode_error.txt', 'rb') as f:
print 'Fi... |
import turtles # imports the turtle module
t = turtle.Turtle() # name your turtle 't'
t.forward(50) # move forward by 50 pixels
t.right(90) # rotate right by 90 degrees
t.forward(50)
t.right(90)
t.forward(50)
t.right(90)
t.forward(50)
t.right(90)
turtle.done() # turtle is do... |
"""Registry for FFT averaging methods
"""
from collections import OrderedDict
from ...utils.decorators import deprecated_function
__author__ = "Duncan Macleod <duncan.macleod@ligo.org>"
METHODS = OrderedDict()
def _format_name(name):
return name.lower().replace("-", "_")
def register_method(func, name=None, depreca... |
"""
Copyright 2012, 2013 Driesen Joep
This file is part of Seasoning.
Seasoning 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.
Seasoning is ... |
import argparse
import os
import requests
import sys
GITHUB_API_URL = "https://api.github.com/"
def read_arguments():
#github_update_projectinfo.py file myProjectName -b blacklist.txt https://github.com/grimoirelab
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
parser... |
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Default dimension parameter to evaluate the model
defaultDimension = 1
spatialDimension = 1
# Amplitude values
amplitude = NumericalPoint(defaultDimension, 1.0)
# Scale values
scale... |
import bpy
from mathutils import Vector
from case_utils import draw_wall, delete_all
def draw_lid():
vector = Vector((0, 0, 0.1))
# Let's call one unit in Blender 1cm
bottom_vertices = [
(-0.1, 0, 0),
(5, 0, 0),
(5, -0.1, 0),
(6, -0.1, 0),
(6, 1.1, 0),
(0,... |
"""autogenerated by genpy from RoboCompAGM2ROS/getNodeRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class getNodeRequest(genpy.Message):
_md5sum = "e7293f7ecc241d9e1ca32cffe1cb473b"
_type = "RoboCompAGM2ROS/getNodeRequest"
_has_header =... |
import traceback
from onedrivee.drives import errors
from onedrivee.workers.tasks.task_base import TaskBase
class DeleteItemTask(TaskBase):
def __init__(self, parent_task, rel_parent_path, item_name, is_folder):
"""
:param TaskBase parent_task: Base task.
:param str rel_parent_path: Relative... |
""" This module maintains the parameter specification classes.
These are used for function, lambdas, generators. They are also a factory
for the respective variable objects. One of the difficulty of Python and
its parameter parsing is that they are allowed to be nested like this:
(a,b), c
Much like in assignments, whic... |
""" Navigation display for the QTGL gui."""
try:
from PyQt5.QtCore import qCritical, QTimer
from PyQt5.QtOpenGL import QGLWidget
QT_VERSION = 5
except ImportError:
from PyQt4.QtCore import qCritical, QTimer
from PyQt4.QtOpenGL import QGLWidget
QT_VERSION = 4
import OpenGL.GL as gl
from math impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.