content stringlengths 4 20k |
|---|
from django import http
import commonware
import requests
from rest_framework.exceptions import ParseError
from rest_framework.generics import ListAPIView
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
from rest_framework.views import APIView
import amo
from lib.met... |
import unittest
import os
import shutil
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator
from airflow import AirflowException
from subprocess import check_call
import mock
import json
from airflow.contrib.kubernetes.pod_launcher import PodLauncher
from airflow.contrib.kubernetes.volum... |
test_sub_dir = "test_data/1019436/session_1"
def test_summary_mask():
import os
import pickle
import pkg_resources as p
from qap.spatial_qc import summary_mask
from qap.qap_utils import load_image, load_mask
anat_reorient = p.resource_filename("qap", os.path.join(test_sub_dir, \
... |
import ctypes
from pyglet import com
lib = ctypes.oledll.dinput8
LPVOID = ctypes.c_void_p
WORD = ctypes.c_uint16
DWORD = ctypes.c_uint32
LPDWORD = ctypes.POINTER(DWORD)
BOOL = ctypes.c_int
WCHAR = ctypes.c_wchar
UINT = ctypes.c_uint
HWND = ctypes.c_uint32
HANDLE = LPVOID
MAX_PATH = 260
DIENUM_STOP = 0
DIENUM_CONTIN... |
# -*- coding: utf-8 -*-
import fileinput
import pdb
import traceback
from typing import Dict, List, Tuple
Aunts = Dict[int, Dict[str, int]]
def solve(aunts: Aunts) -> Tuple[int, int]:
ticker_tape: Dict[str, int] = {
"children": 3,
"cats": 7,
"samoyeds": 2,
"pomeranians": 3,
... |
"""More recovery and iterator tests."""
import transaction
from transaction import Transaction
from ZODB.tests.IteratorStorage import IteratorDeepCompare
from ZODB.tests.StorageTestBase import MinPO, snooze
from ZODB import DB
from ZODB.serialize import referencesf
import time
class RecoveryStorage(IteratorDeepComp... |
import pytest
from webdriver.error import NoSuchWindowException
from tests.perform_actions.support.mouse import get_inview_center, get_viewport_rect
from tests.perform_actions.support.refine import filter_dict, get_events
from tests.support.asserts import assert_move_to_coordinates
from tests.support.inline import in... |
"""
===========
NH2D fitter: ortho- and para- in the same file, but not modeled together
===========
Reference for line params:
Shah & Wooten (2001) line frequencies and line strengths.
TODO: Obtaine up-to-date values from CDMS and Splatalogue
Ronak Y. Shah and Alwyn Wootten ApJ 554, 933-947 (2001)
http://adsabs.har... |
"""main entry point for gadfly sql."""
import sqlgen, sqlbind
sql = sqlgen.getSQL()
sql = sqlbind.BindRules(sql)
error = "gadfly_error"
verbosity = 0
class gadfly:
"""as per the DBAPI spec "gadfly" is the connection object."""
closed = 0
verbose = verbosity # debug!
def __init__(self, databasename=N... |
from __future__ import print_function
import lib.bokken_globals as glob
import lib.common as common
import os, sys, platform
def check_all():
python_version()
radare_dependency_check()
cores()
gtkui_dependency_check()
graphviz_dependency_check()
def python_version():
print('\tPython version..... |
""" This script submits a test prodJobuction with filter
"""
# pylint: disable=wrong-import-position, protected-access
from __future__ import print_function
import time
import os
import json
from DIRAC.Core.Base import Script
Script.setUsageMessage('\n'.join([__doc__.split('\n')[1],
... |
import requests
from django.db import models
from django.conf import settings
from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailsearch import index
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class PersonPage(Orderable, Page):
user = models.OneToOneField(settings.AUTH_USER_... |
from ...core import init_module, classes
from ...functions import FunctionRing, DifferentialRing, OperatorRing
from ..algebra import Calculus
init_module.import_heads()
class CalculusFunctionRing(FunctionRing):
"""
Functions ring with Calculus value algebra.
"""
@classmethod
def get_value_algeb... |
# Python script that generates the documentation for script functions.
# This parses the codeblocks for to find all the source files, then parses all the source files for script macros.
# Finally it outputs all the documentation to stdout so it can be stored on disk.
# This script should run in both python2 and python3... |
import MySQLdb
import MySQLdb.cursors
import json
import six
from airflow.hooks.dbapi_hook import DbApiHook
class MySqlHook(DbApiHook):
"""
Interact with MySQL.
You can specify charset in the extra field of your connection
as ``{"charset": "utf8"}``. Also you can choose cursor as
``{"cursor": "S... |
"""Raspberry Pi Face Recognition Treasure Box
Webcam OpenCV Camera Capture Device
Copyright 2013 Tony DiCola
Webcam device capture class using OpenCV. This class allows you to capture a
single image from the webcam, as if it were a snapshot camera.
This isn't used by the treasure box code out of the box, but is ... |
'''
XXX:
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2011-04-09
'''
from sys import path as sys_path
from os.path import join as path_join
from os.path import dirname
from itertools import chain
from liblinear import LibLinearClassifier
sys_path.append(path_join(dirname(__file__), '..'))
from... |
from django.contrib.auth import authenticate, get_user_model
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from . import constants, utils
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = tuple(... |
import time
import unittest
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from django.views.generic import View, TemplateView, RedirectView
class SimpleView(View):
"""
A simple view with a docstring.
"""
d... |
from wptserve.handlers import HTTPException
import urllib
def main(request, response):
if request.method != "GET":
raise HTTPException(400, message="Method was not GET")
if not "id" in request.GET:
raise HTTPException(400, message="No id")
id = request.GET['id']
if "read" in request.... |
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt
#from matplotlib import collections as mc
#from matplotlib import patches as mp
import plotly.offline as pl
import plotly.graph_objs as go
def _plot_polygon(polygon):
if polygon is None or polygon.displayed or polygon.outer_wire.is_roo... |
from stdnet import odm
from stdnet.utils import test, encoders
from .base import StructMixin
class TestList(StructMixin, test.TestCase):
structure = odm.List
name = 'list'
def create_one(self):
l = odm.List()
l.push_back(3)
l.push_back(5.6)
return l
def test_items(se... |
"""
Module responsible for translating reference sequence data into GA4GH native
objects.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import hashlib
import json
import random
import pysam
import ga4gh.server.datamodel as datamodel
import ga4gh.ser... |
import sys,os,shelve
import re,dfxml,fiwalk
from bc_utils import filename_from_path
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
def build_local_wb(ws, fi, row_idx):
ws.cell('%s%s'%('A', row_idx)).value = '%s' % fi.partition()
... |
#!/usr/bin/env python3
import sys
import click
from tabulate import tabulate
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, try_select_columns, try_select_rows, try_sort
from boadata.core import DataObject
def show_table(do: DataObject):
print(tabulate(do.inner_data, do.columns... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.db.models import Count
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy as _lazy
from .models import GlossVideo
class HasGlossFilter(admin.SimpleListFilte... |
import math
import cv2
from matplotlib import pyplot as plt
import numpy as np
orig = cv2.imread('contrast.jpg')
orig = cv2.resize(orig, (0,0), fx=0.3, fy=0.3)
img = cv2.copyMakeBorder(orig,0,0,0,0,cv2.BORDER_REPLICATE)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
height = img.shape[1]
width = img.shape[0]
I = img.me... |
from openerp.osv import orm
from openerp.tools.translate import _
class logistic_requisition_cost_estimate(orm.TransientModel):
"""Add update of agreement price"""
_inherit = "logistic.requisition.cost.estimate"
def _prepare_cost_estimate_line(self, cr, uid, sourcing, context=None):
"""Override... |
# -*- coding: utf-8 -*-
import simplejson
import urllib
import httplib2
from lxml import etree
from datetime import datetime
from linkedtv.model import Enrichment
from linkedtv.api.dimension.DimensionService import DimensionService
class AnefoAPI(DimensionService):
def __init__(self):
DimensionService.__init__(se... |
# -*- coding: utf-8 -*-
"""
Tests for Timestamp timezone-related methods
"""
from datetime import date, datetime, timedelta
from distutils.version import LooseVersion
import dateutil
from dateutil.tz import gettz, tzoffset
import pytest
import pytz
from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
... |
'''
This plugin provides authentication from a database using sqlobject. In
addition to the standard stuff provided by the TurboGears soprovider, it
adds a csrf_token attribute that can be used to protect the server from
csrf attacks.
.. versionadded:: 0.3.14
.. moduleauthor:: Toshio Kuratomi <<EMAIL>>
'''
from dat... |
DEBUG = True
INSTALLED_APPS = [
# These are needed for django-admin to run
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
# Our precious app
'account',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'djang... |
# -*- coding: utf-8 -*-
'''
Configuration management using Augeas
=====================================
.. versionadded:: 0.17.0
This state requires the ``augeas`` Python module.
.. _Augeas: http://augeas.net/
Augeas_ can be used to manage configuration files. Currently only the ``set``
command is supported via thi... |
import lang.gbs_builtins
from lang.gbs_builtins import GbsObject, clone_value
import lang.gbs_constructs
import lang.gbs_runnable
import lang.gbs_io
import common.position
import common.i18n as i18n
import random
from common.utils import *
#### Gobstones virtual machine
## A compiled program consists of a dictionary ... |
from itertools import repeat
def is_immutable(self):
raise TypeError('%r objects are immutable' % self.__class__.__name__)
class ImmutableDict(dict):
_hash_cache = None
@classmethod
def fromkeys(cls, keys, value=None):
return cls(zip(keys, repeat(value)))
def __reduce_ex__(self, protoc... |
'''outgoing_tuple_helper.py: module to provide a helper class for preparing and pushing tuples'''
import sys
from heron.common.src.python.utils.log import Log
from heron.proto import tuple_pb2, topology_pb2, ckptmgr_pb2
import heron.instance.src.python.utils.system_constants as constants
from heron.instance.src.pytho... |
# matplotlib without any blocking GUI
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import ifft, fftshift
from scipy.signal import triang, blackmanharris
from smst.utils import audio, peaks, synth
from smst.models import dft
(fs, x) = audio.read_wav('..... |
# encoding: utf8
import base64, json, urllib
# extension identifier and name
EXTENSION_ID = 'com.pilotmoon.popclip.extension.trello'
EXTENSION_NAME = 'Trello';
# app name for display to user
APP_NAME = 'PopClip Extension “' + EXTENSION_NAME + '”';
# our callback url & params
EXPECT_PARAMS = base64.urlsafe_b64encode... |
from enum import Enum
class SkuName(Enum):
basic = "Basic"
standard = "Standard"
premium = "Premium"
class SkuTier(Enum):
basic = "Basic"
standard = "Standard"
premium = "Premium"
class NamespaceState(Enum):
unknown = "Unknown"
creating = "Creating"
created = "Created"
a... |
"""Benchmark mixed PSO and FollowBest Particles."""
from __future__ import absolute_import, unicode_literals
import logging
import json
import sys
from logging import config
from numpy import random, matrix
from pylocating.utils import distance
from pylocating.benchmarks.mix_pso_followbest import builder
from pyloca... |
#!/usr/bin/env python
"""
Takes cluster.yaml and writes out an Ansible inventory file for the cluster.
"""
import argparse
import jinja2
import os
import sys
import yaml
import re
INVENTORY_TEMPLATE = """[localhost]
127.0.0.1 ansible_connection=local
[{{ cluster_name }}:vars]
ansible_ssh_user={{ cluster_ssh_user }... |
import os
import time
import urllib
import xbmc
import xbmcgui
import xbmcvfs
from systemtools import Python_Version
#----------------------------------------------------------------
# TUTORIAL #
def Cleanup_URL(url):
"""
Clean a url, removes whitespaces and common buggy formatting when pulling from websites
C... |
"""Implementation of :class:`RealDomain` class. """
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.groundtypes import SymPyReal
from sympy.polys.polyerrors import DomainError, CoercionFailed
import math
class ... |
#!/usr/bin/env python
# encoding: utf-8
import os
from types import NoneType
from xmlrpclib import DateTime
import mock
from nose.tools import * # noqa: F403
from tests.base import OsfTestCase
from osf_tests.factories import (UserFactory, ProjectFactory, NodeFactory,
AuthFactory, Regist... |
# coding:utf-8
'''
Unitest for CTC_Log
Created : 11, 13, 2018
Revised : 11, 13, 2018
All rights reserved
'''
# ------------------------------------------------------------------------------------------------
__author__ = 'dawei.leng'
import os
os.environ['THEANO_FLAGS'] = "floatX=float32, mode=FAST_RUN, warn_fl... |
"""
Django settings for Jarbas project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
#!/usr/bin/env py.test
"""Unit tests for the solve interface"""
# Copyright (C) 2011 Garth N. Wells
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either v... |
from uuid import uuid4
import functools
def task(_func=None, *, every=None, schedule=None, schedule_name=None, use_app_context=False, **kwargs):
from .app import celery_app
if _func is None:
return functools.partial(task, every=every, schedule=schedule, schedule_name=schedule_name, use_app_context=u... |
import plotly.graph_objs as go
import plotly.io as pio
import pytest
import plotly
import json
import os
import tempfile
from unittest.mock import MagicMock
from pathlib import Path
# fixtures
# --------
@pytest.fixture
def fig1(request):
return go.Figure(
data=[
{"type": "scattergl", "marker"... |
import numpy as np
from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import widget
import orangecanvas.resources as resources
import sys, os
from crystalpy.util.PolarizedPhotonBunch import Polariz... |
"""The Multinomial distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops impor... |
"""
This is the template for extracting the solution for the computation problem of computing
a Groebner basis of an ideal in a commutative polynomial ring over QQ from the output of the computer
algebra system Singular.
.. moduleauthor:: Albert Heinle <<EMAIL>>
"""
import xml.dom.minidom as dom
import re
#---------... |
import pytest
from plenum.test.helper import sdk_send_random_and_check, perf_monitor_disabled
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.view_change_with_delays.helper import do_view_change_with_pending_request_and_one_fast_node
# This is needed only with current view... |
import random
from flask import Blueprint, render_template, session, request
from flask.ext.socketio import emit, join_room, leave_room
from board_games import TicTacToe
from app import socketio
tic_tac_toe = Blueprint(
'tic_tac_toe',
__name__,
template_folder='templates/tic_tac_toe',
url_prefix='/tic-... |
"""
Django settings for vanessaschill project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... |
#coding=utf-8
'''
Created on 2016��10��19��
@author: huangning
'''
from flask import render_template
from . import main
from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField,TextAreaField,SelectField
from wtforms.validators import Required, Length, Email, Regexp... |
"""Module for handling x509 subjects."""
from collections import abc
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast
from cryptography im... |
# Original source of reaction-based menu idea from
# https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py
#
# Ported to Red V3 by Palm\_\_ (https://github.com/palmtree5)
import asyncio
import contextlib
import functools
from typing import Iterable, List, Union
import discord
from .. import commands
from .... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
@author: actlea
@file: feature_builder.py
@time: 16-3-22 上午10:29
@description:
"""
import math
class FeaturBuilder(object):
def __init__(self, logs=False):
self.logs = logs
def construct_features(self,graph, node):
pass
def get_number_... |
"""
Utilities and helper functions
"""
import logging
import re
import sys
LOG = logging.getLogger(__name__)
def agi_send(data):
sys.stdout.write("%s\n" % data)
sys.stdout.flush()
LOG.debug("agi_send: '%s'", data)
code, result, args = _agi_read()
return code, result, args
def _agi_read():
... |
from __future__ import unicode_literals
import frappe, sys
import erpnext
import frappe.utils
from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts, projects, fixed_asset, schools
from erpnext.demo.setup import education, manufacture, setup_data, healthcare
"""
Make a demo
1. Start with a ... |
import mock
import os
import tempfile
from django.conf import settings
from waffle.testutils import override_switch
from olympia import amo
from olympia.addons.models import AddonCategory, MigratedLWT
from olympia.addons.tasks import (
add_static_theme_from_lwt, create_persona_preview_images,
migrate_lwts_to... |
import urllib
import httplib
import json
import time
from ambari_commons.ambari_metrics_helper import select_metric_collector_hosts_from_hostnames
from ambari_commons.ambari_metrics_helper import load_properties_from_file
RESULT_STATE_OK = 'OK'
RESULT_STATE_CRITICAL = 'CRITICAL'
RESULT_STATE_WARNING = 'WARNING'
RESUL... |
from pyflink.java_gateway import get_gateway
__all__ = ['JobStatus']
class JobStatus(object):
"""
Possible states of a job once it has been accepted by the job manager.
:data:`CREATED`:
Job is newly created, no task has started to run.
:data:`RUNNING`:
Some tasks are scheduled or running,... |
import openerp.tests.common as common
from openerp.modules.module import get_module_resource
from openerp import fields, exceptions
class TestInventoryLineImport(common.TransactionCase):
def get_file(self, filename):
"""Retrieve file from test data, encode it as base64 """
path = get_module_resou... |
from ui_youtube_option import Ui_YoutubeDlOption
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class YoutubeDlOptionWidget(QWidget):
def __init__(self, kconfig):
QWidget.__init__(self)
self.ui = Ui_YoutubeDlOption()
self.ui.setupUi(self)
self.parser = kconfig
self.cfg... |
"""
Django settings for elpolitico 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/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... |
"""Test Object API library module"""
import mock
from openstackclient.object.v1.lib import container as lib_container
from openstackclient.tests.common import test_restapi as restapi
from openstackclient.tests.object.v1 import fakes as object_fakes
fake_account = 'q12we34r'
fake_auth = '11223344556677889900'
fake_u... |
"""Logic for Host Model.
"""
from soc.models.host import Host
from soc.models.program import Program
from soc.models.user import User
def getHostForUser(user_entity):
"""Returns the host entity for the given user.
Args:
user_entity: the user for whom the Host entity must be fetched.
returns:
The hos... |
# -*- coding: utf-8 -*-
import os
import mimetypes
import shutil
import zipfile
from django.conf import settings
from django.core.cache import cache
from django import forms
from mock import Mock, patch
from nose.tools import eq_
import amo.tests
from amo.urlresolvers import reverse
from files.helpers import FileVie... |
class NotificationType(object):
"""
Constants regarding the different types of notification we can send to a device
See https://docs.google.com/document/d/1SV-hNCtgAn2hSMZaC973UdLHCFXCNpvq_RKq0UoY4yg/edit#
"""
# DO NOT CHANGE THESE CONSTANTS
UPCOMING_MATCH = 0
MATCH_SCORE = 1
LEVEL_STAR... |
"""The old popup color changers wrapped as new-style Adjusters"""
## Imports
from __future__ import division, print_function
from lib.gibindings import GdkPixbuf
from lib.gibindings import Gdk
import lib.color
import gui.colors
import gui.colors.adjbases
from lib.gettext import C_
from lib import mypaintlib
from li... |
"""
Name class for Gramps.
"""
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .secondaryobj import SecondaryObject
from .privacybase import PrivacyBase
from .citationbase import CitationBase... |
import logging
import warnings
from contextlib import contextmanager
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from shuup.apps.provides import (
get_identifier_to_object_map, get_provide_objects
)
from shuup.core import cache
from shuup.utils.deprecation... |
from direct.task.Task import Task
from pandac.PandaModules import VBase4, PandaNode
from direct.distributed.ClockDelta import globalClockDelta
from toontown.margins.MarginVisible import MarginVisible
from toontown.nametag import NametagGlobals
from toontown.nametag.Nametag2d import Nametag2d
from toontown.nametag.Name... |
"""
Traceback standard module plus some additional APIs.
"""
from traceback import format_exception
import logging
import inspect
def tb_info(exc_info):
"""
Prepare traceback info.
:param exc_info: Exception info produced by sys.exc_info()
"""
exc_type, exc_value, exc_traceback = exc_info
ret... |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Script for some utility functions.
It imports
-os
-time
-json
It defines
-opj
-string_to_tuple
-change_config
-sanitize_string
-file_size
-write_downloads
-write_history
''''''''''''''''''''''''''''''''... |
"""Tests for RNN cells."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
import tensorflow as tf
class RNNCellTest(tf.test.TestCase):
def testLinear(self):
with self.test_session() as sess:
with tf.variab... |
"""
Error classes.
Includes two main exceptions: ClientException, when something goes
wrong on our end, and APIExeception for when something goes wrong on the
server side. A number of classes extend these two main exceptions for more
specific exceptions.
"""
from __future__ import print_function, unicode_literals
im... |
import qctests.CSIRO_depth
import util.testingProfile
import numpy
##### CSIRO_depth_test ---------------------------------------------------
def test_CSIRO_depth():
'''
Spot-check the nominal behavior of the CSIRO depth test.
'''
# too shallow for an xbt
p = util.testingProfile.fakeProfile([0,0,... |
'''
- Leetcode problem: 141
- Difficulty: Easy
- Brief problem description:
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the
linked list where tail connects to. If pos is -1, then there is no... |
"""
Django settings for Visualizacion project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
impo... |
import os, signal, tempfile, subprocess, shutil, time
import debug, machines
from machines import ARMSimulatorBase
GEM5_PATH = '/home/netos/tools/gem5/gem5-stable'
# gem5 takes quite a while to come up. If we return right away,
# telnet will be opened too early and fails to connect
GEM5_START_TIMEOUT = 5 # in seconds
... |
"""Generate XML and HTML test reports."""
try:
from mako.runtime import Context
from mako.template import Template
from mako import exceptions
except (ImportError):
pass # Mako not installed but it is ok.
import datetime
import os
import string
import xml.etree.cElementTree as ET
import six
def _fil... |
"""
This is the target module which is the super class
of all of the scons targets.
"""
import os
import string
import configparse
import console
from blade_util import var_to_list
class Target(object):
"""Abstract target class.
This class should be derived by subclass like CcLibrary CcBinary
targe... |
import datetime
import urlparse
from webob import exc
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.compute import api
from nova.compute import flavors
from nova import exception
from nova.openstack.common.gettextutils import _
from nova... |
""" Base Storage Class provides the base interface for all storage plug-ins
exists()
These are the methods for manipulating files:
isFile()
getFile()
putFile()
removeFile()
getFileMetadata()
getFileSize()
prestageFile()
getTransportURL()
These are the methods for... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains code to convert discourse graphs into rooted, ordered
trees.
"""
from collections import defaultdict, deque
import StringIO
import textwrap
from nltk.tree import Tree, ParentedTree
from discoursegraphs import (
EdgeTypes, istoken, select_nei... |
import re
from app.utils.file_utils import FileUtils
class RequireFileParser:
moduleNamePattern = 'a-zA-Z@/-_#$!\+#0-9\-\.'
defineSeparators = ' \t\r\n,'
exceptions = []
def parse(self, path, moduleId):
fileUtils = FileUtils()
content = fileUtils.getContent(path)
defineStartIndex, defineEndIndex... |
import xbmcgui
dialog = xbmcgui.Dialog()
dialog.ok('', 'This is a console-only addon - v0.5.4-alpha') |
from setuptools import setup, find_packages, Command
import glob
import os
import sys
import unittest
# Get version from pkg index
from trigger import release as __version__
# Names of required packages
requires = [
'IPy>=0.73',
'Twisted',
'pyasn1', # Twisted conch needs this, but doesn't say so
'pycr... |
import types
from openerp import release
from openerp.osv.orm import TransientModel
from openerp.osv import fields
from openerp.openupgrade.openupgrade import table_exists
from openerp.tools import config, safe_eval
# A collection of functions used in
# openerp/modules/loading.py
def add_module_dependencies(cr, modu... |
from dolfin import *
# Source term
class Source(Expression):
def eval(self, values, x):
dx = x[0] - 0.5
dy = x[1] - 0.5
values[0] = x[0]*sin(5.0*DOLFIN_PI*x[1]) + 1.0*exp(-(dx*dx + dy*dy)/0.02)
# Sub domain for Dirichlet boundary condition
class DirichletBoundary(SubDomain):
def inside... |
import os.path as op
import warnings
from nose.tools import assert_true, assert_equal
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
from scipy import fftpack
from mne import io, read_events, Epochs, pick_types
from mne.time_frequency._stockwell import (tfr_stockwell, _st,
... |
"""Utils for Zenodo Pages."""
from __future__ import absolute_import, print_function
from flask import current_app, request
from flask_mail import Message
from ua_parser import user_agent_parser
def render_template_to_string(template, context):
"""Render a template from the template folder with the given contex... |
"""
Production Configurations
- Use WhiteNoise for serving static files
- Use Amazon's S3 for storing uploaded media
- Use mailgun to send emails
- Use Redis for cache
- Use sentry for error logging
- Use opbeat for error reporting
"""
import logging
from .base import * # noqa
# SECRET CONFIGURATION
# ------... |
"""
Calculates transitions for the Moran process and generalizations.
"""
from ..utils.math_helpers import (
simplex_generator, one_step_indicies_generator, logsumexp,
log_factorial, log_inc_factorial, factorial, inc_factorial)
from ..utils.edges import (
edge_func_to_edges, states_from_edges, power_transi... |
"""COCO-style evaluation metrics.
Implements the interface of COCO API and metric_fn in tf.TPUEstimator.
COCO API: github.com/cocodataset/cocoapi/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import atexit
import copy
from absl import flags
import n... |
from __future__ import absolute_import, division, print_function
import numpy as np
from skbeam.core.constants import XrfElement
from skbeam.core.fitting import gaussian
def get_line(ax, name, incident_energy):
"""
Plot emission lines for a given element.
Parameters
----------
name : str or int
... |
"""
Convert a sync map from a format to another.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
from aeneas.tools.convert_syncmap import ConvertSyncMapCLI
__author__ = "Alberto Pettarin"
__email__ = "<EMAIL>"
__copyright__ = """
Copyright 2012-2013, Alberto Pettarin (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.