content stringlengths 4 20k |
|---|
__all__ = ["System"]
import sys, os, platform
import errno
from .common import Common
from .config import Config
def System():
return _System.get()
class _System(object):
'''Class which abstracts all system commands in TACTIC. By default,
TACTIC will use standard python libraries for this'''
syst... |
"""
Basic fossils for data export
"""
from hashlib import md5
from indico.modules.attachments.api.util import build_material_legacy_api_data, build_folders_api_data
from indico.modules.events.notes.util import build_note_api_data
from indico.util.fossilize import IFossil
from indico.util.fossilize.conversion import C... |
""" Database helper functions for the indexer.
"""
import logging
import select
import time
import psycopg2
from psycopg2.extras import wait_select
# psycopg2 emits different exceptions pre and post 2.8. Detect if the new error
# module is available and adapt the error handling accordingly.
try:
import psycopg2.e... |
# coding=utf-8
""""
Copyright 2014 Love Löfdahl
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 wri... |
#!/usr/bin/env python
############################################################################
# This is a simple assembler for the EC327 Simplified Intel Assembly code.
#
# At this point, the only minor improvement I think that the assembler
# still needs is to take the name of the assembly source file as a
# comm... |
__author__ = 'Jonathan Brodie'
import ctypes
from hzclient.clientmessage import ClientMessage
from util import util
'''
PUT
'''
def putEncode():
msg=ClientMessage()
msg.optype=0x0201
util.raiseNotDefined()
def putDecode(bytesobject):
servermsg=ClientMessage.decodeMessage(bytesobject)
util.raiseNotD... |
from django.contrib import admin
from .models import *
from django import forms
# Register your models here.
class domaindesc( forms.ModelForm ):
description = forms.CharField(widget=forms.Textarea)
class Meta:
model = domain
fields = "__all__"
class subtopicdesc( forms.ModelForm ):
descri... |
"""
@author: Thomas PERROT
Contains views for cards app
"""
from datetime import date, timedelta
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from rest_framework import viewsets
from rest_framework.decorators import list_route, detail_route
from rest_framework.response import ... |
import time
import json
import os
from datetime import datetime
from .world import world, logged_wait, res_filename
from nose.tools import eq_, assert_less
from bigml.api import HTTP_CREATED
from bigml.api import HTTP_ACCEPTED
from bigml.api import FINISHED
from bigml.api import FAULTY
from bigml.api import get_status... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.utils import translation
from django.test import TestCase
from nose.tools import *
import mock
from utils import test_utils
from utils.factories import *
from videos.models import Video
from subtitles import pipeline
from ... |
import yaml
import os
import subprocess
# docker run -it mysql /usr/bin/mysqldump -h [MYSQL_HOST] -u [MYSQL_USER] --password=[MYSQL_PASSWORD] [MYSQL_DATABASE] > backup.sql
# BIN = "docker run --rm -it mysql:5.7 /usr/bin/mysqldump"
BIN = "mysqldump"
if __name__ == "__main__":
root = os.path.dirname(os.path.abspat... |
from test_framework.test_framework import InfinitumTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolSpendCoinbaseTest(InfinitumTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
Postprocessing.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... |
from django.urls import path, re_path, include
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from core import views as core_views
from feeds import views as feed_views
from plugins import views as plugin_views
from plugininstances import vie... |
from . import fds_postfinance_account_sepa
from . import fds_sepa_upload_history |
"""
test resolved contexts
"""
from rez.tests.util import restore_os_environ, restore_sys_path, TempdirMixin, \
TestBase
from rez.resolved_context import ResolvedContext
from rez.bind import hello_world
from rez.utils.platform_ import platform_
import unittest
import subprocess
import os.path
import os
class Test... |
"""Support for transport.opendata.ch."""
from datetime import timedelta
import logging
from opendata_transport import OpendataTransport
from opendata_transport.exceptions import OpendataTransportError
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ... |
# rain_notifier.py
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documenta... |
import urllib
import re
import hashlib
import lxml
from weboob.tools.browser import BaseBrowser, BrowserHTTPNotFound, BrowserHTTPError, BrowserIncorrectPassword, BrokenPageError
from weboob.capabilities.messages import CantSendMessage
from .pages.index import IndexPage, LoginPage
from .pages.news import ContentPage, ... |
import os
from selenium.common.exceptions import WebDriverException
from keywordgroup import KeywordGroup
class _JavaScriptKeywords(KeywordGroup):
def __init__(self):
self._cancel_on_next_confirmation = False
# Public
def alert_should_be_present(self, text=''):
"""Verifies an alert is pr... |
import json
import logging
import re
from time import time
from urllib.parse import urljoin, urlparse
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
log = logging.getLogger(__name__)
class OlympicChannel(Plugin):
_url_re = re.compile(r"htt... |
import os
from argparse import ArgumentParser
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.analysis.machine import Machine
from pdb import pm
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
parser = ArgumentParser(description="x86 32 ba... |
from openerp.osv import fields, osv
class ple_3_20 (osv.Model):
_name = "l10n_pe.ple_3_20"
_inherit = "l10n_pe.ple"
_columns= {
'lines_ids': fields.one2many ('l10n_pe.ple_line_3_20', 'ple_3_20_id', 'Lines', readonly=True, states={'draft':[('readonly',False)],}),
}
def action_reload (self,... |
"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""
import pytest
from pandas import Interval, Timedelta, Timestamp
@pytest.fixture(params=[
(Timedelta('0 days'), Timedelta('1 day')),
(Timestamp('2018-01-01'), Timedelta('1 day')),
(0, 1)], ids=lambda x: type(x[0]).__name__)
def... |
import os
import sys
from . import utils
(WARNING,
ERROR,
FATAL) = range(3)
class Position(object):
"""Represents a position in the source file which we
want to inform about.
"""
def __init__(self, filename=None, line=None, column=None):
self.filename = filename
self.line = line
... |
""" Caching facility for SymPy """
# TODO: refactor CACHE & friends into class?
# global cache registry:
CACHE = [] # [] of
# (item, {} or tuple of {})
from sympy.core.decorators import wraps
def print_cache():
"""print cache content"""
for item, cache in CACHE:
item = str(item)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
import os
import os.path
import sys
import argparse
import logging
def cartesian_product(dicts):
return list(dict(zip(dicts, x)) for x in itertools.product(*dicts.values()))
def summary(configuration):
kvs = sorted([(k, v) for k, v in configu... |
#!/usr/bin/python
from datetime import datetime
from pprint import pprint
# copied from process.py
import os, sys, subprocess
# os.environ['DJANGO_SETTINGS_MODULE'] = 'dj.settings'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj.settings")
sys.path.insert(0, '..' )
from django.conf import settings
import django... |
from xml.dom.minidom import parse, getDOMImplementation
#import gettext
#_ = gettext.Catalog("DBSetup",'').gettext
from os import system,path,listdir
from Components.GUIComponent import *
from Components.HTMLComponent import *
from Components.Button import Button
from Components.MenuList import MenuList
from Componen... |
"""
Regression test for a bug where, if you were in a IRC channel that had the same
name as your nickname (e.g. user 'foo' in room '#foo'), all private 1:1 messages
to foo would appear to also be coming through room #foo as well (bug #19766)
"""
from idletest import exec_test, BaseIRCServer
from servicetest import Eve... |
"""Deprecation helpers for Home Assistant."""
from __future__ import annotations
import functools
import inspect
import logging
from typing import Any, Callable
from ..helpers.frame import MissingIntegrationFrame, get_integration_frame
def deprecated_substitute(substitute_name: str) -> Callable[..., Callable]:
... |
# from flask import Flask, request
# from flask_webapi.formatters import JsonInputFormatter, JsonOutputFormatter, PickleOutputFormatter, MimeType
# from flask_webapi.negotiators import DefaultContentNegotiator
# from unittest import TestCase
#
# class TestSelectInputFormatter(TestCase):
# def setUp(self):
# ... |
{
'name': 'CRM Project',
'version': '8.0.1.0.0',
'category': 'Project',
'depends': ['project', 'crm', 'sale'],
'author': 'Elico Corp',
'license': 'AGPL-3',
'website': 'https://www.elico-corp.com',
'support': '<EMAIL>',
'data': ['views/sale.xml',
'views/opportunities.xml'... |
import logging
import time
from autotest.client.shared import error
from virttest import utils_test, aexpect
from virttest import env_process
@error.context_aware
def run(test, params, env):
"""
Time manage test:
1) Generate stress in host.
2) Run atleast 15 vms with "driftfix=slew" option
3) Reb... |
"""Tool to validate settings."""
import logging
import os
import sys
SIMIAN_CONFIG_PATH = None
def ErrorExit(msg, *args):
logging.error(msg, *args)
sys.exit(1)
def ValidatePem(arg, dirname, fnames):
"""Validate all fnames found in dirname as PEM files.
Args:
arg: tuple, (settings module to make use ... |
import os
from sys import exit
from botocore.exceptions import ClientError
from .util import AMI_HELP_MSG, get_block_device_map
from os import path
import time
import boto3
from .existing import ExistingCluster
import json
from string import Template
class Ec2Cluster(ExistingCluster):
def __init__(self, config):
... |
from pandac.PandaModules import *
import Playground
from direct.task.Task import Task
import random
from direct.fsm import ClassicFSM, State
from direct.actor import Actor
from toontown.toonbase import ToontownGlobals
from direct.directnotify import DirectNotifyGlobal
from toontown.hood import Place
class DDPlayground... |
#!/usr/bin/env python2
# coding=utf-8
#
##############################################################################
### NZBGET POST-PROCESSING SCRIPT ###
# Post-Process to Mylar.
#
# This script sends the download to your automated media management servers.
#
# NOTE: This sc... |
"""
TileStorage.py
My attempt at abstracting the storage of windows for tiling algorithms.
Namely, the handling of window ordering so that we have a data structure
that closely resembles that which you see on the screen. Additionally, it
will handle the management of masters and slaves. Tiling algorithms need
only be ... |
from functools import wraps
import sys
import requests
from mock import MagicMock, Mock, patch
from appvalidator.zip import ZipPackage
from appvalidator.errorbundle import ErrorBundle
from appvalidator.errorbundle.outputhandlers.shellcolors import OutputHandler
def _do_test(path, test, failure=True, set_type=0,
... |
import os
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachments.models.attachments import Attachment
from indico.modules.files.models.files import File
@celery.task(ignore_result=False)
def generate_materials_package(attachment_ids, event):
from indico.modules.attach... |
import tensorflow as tf
def image_scaling(img, label):
"""
Randomly scales the images between 0.5 to 1.5 times the original size.
Args:
img: Training image to scale.
label: Segmentation mask to scale.
"""
scale = tf.random_uniform([1], minval=0.5, maxval=1.5, dtype=tf.float32, see... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from astropy.time import Time
import astropy.units as u
from astropy.coordinates import SkyCoord, EarthLocation
from ..utils import time_grid_from_range
from ..observer import Observer
from ... |
from telemetry.page import shared_page_state
from telemetry.util import wpr_modes
from page_sets.login_helpers import google_login
from page_sets.login_helpers import linkedin_login
from page_sets.rendering import rendering_story
from page_sets.rendering import story_tags
class TopRealWorldDesktopPage(rendering_stor... |
"""This module is part of Swampy, a suite of programs available from
allendowney.com/swampy.
Copyright 2011 Allen B. Downey
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
"""
import math
import random
import time
from tkinter import END
from World import World, Animal, MyThread
clas... |
import shutil
import pexpect
from os.path import expanduser
from contextlib import contextmanager
from subprocess import check_call, check_output
def adb(device=None):
adb = shutil.which('adb')
if device:
return adb + ' -s %s ' % device
return adb + ' '
def shell(device):
cmd = adb(device) ... |
"""
IpsecConf parser - file ``/etc/ipsec.conf``
===========================================
IpsecConf parser the file /etc/ipsec.conf about
the configuration and control information
for the Libreswan IPsec subsystem.
"""
from collections import defaultdict
from insights.specs import Specs
from insights.core import C... |
"""
Brocade NOS Driver Test
"""
import sys
from quantum.plugins.brocade.nos import nosdriver as nos
def nostest(host, username, password):
# Driver
driver = nos.NOSdriver()
# Quantum operations
vlan = 1001
mac = '0050.56bf.0001'
driver.create_network(host, username, password, vlan)
drive... |
from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
from scipy import misc
from skimage.color import rgb2gray
import numpy as np
import Helper
import Display
def spectral_cluster(filename, compactness_val=30, n=6):
'''
Apply spectral clusteri... |
import json
from urllib import urlopen
import requests
import getpass
from string import Template
import sys
import os
import subprocess
class RunError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def run(command, **kwargs):
fail_hard... |
#!/usr/bin/python
"""
This script generatess various OAuth parameters for Twitter login.
Please run the following command to generate a valid 'config.py':
>>> python config_generate.py --consumer_key=$CONSUMER_KEY --consumer_secret=$CONSUMER_SECRET
... --callback_url=$CALLBACK_URL
where ... |
from . import (
res_partner_attributes_add_NEQ,
) |
#!/usr/bin/python
import pandas as pd
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.cross_validation import train_test_split
from matplotlib import pyplot as plt
def runs_of_ones_count(bits):
# make sure all runs of ones ar... |
import unittest
from janome.progress import SimpleProgressIndicator, logger as p_logger
class TestProgress(unittest.TestCase):
def test_simple_progress_indicator(self):
total = 22
desc = 'Test loop'
# create SimpleProgressIndicator, print once in 10 times update
progress_indicator... |
import random
from typing import List, Any
import numpy as np
from sentences import Sentence
from transition_parser.parallel_util import ParallelParse, SentenceBatch
from transition_parser.performance import measure_performance
class ThreadedTransitionParser:
def __init__(self, transition_system, learner,
... |
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# TODO: Delete this code once this version of pymel has been out for while!
# ok, we recently deleted some files (batch.py and gui.py) from pymel...
# ...however, some users may still have some pesky .pyc's lying around... and if
# they do, th... |
"""
Preprocessing steps to get data in right format so that it can be displayed.
Data should end in the following format: list of:
begin 1494448500
end 1494458543
line "H"
stops [{'s... |
# -*- coding: utf-8 -*-
import datetime
import gzip
import logging
import os
import re
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Max
from okscraper_django.management.base_commands import NoArgsDbLogCommand
from laws.models import Vote, Vo... |
from django.test import TestCase
from casexml.apps.case.models import CommCareCase
from corehq.apps.commtrack.dbaccessors import \
get_supply_point_ids_in_domain_by_location, \
get_supply_points_json_in_domain_by_location, \
get_supply_point_case_by_location_id, get_supply_point_case_by_location
from corehq... |
# coding: utf-8
from __future__ import absolute_import
from strictyaml.ruamel.representer import RoundTripRepresenter
from strictyaml.ruamel.scalarstring import ScalarString
from strictyaml.ruamel.emitter import Emitter
from strictyaml.ruamel.serializer import Serializer
from strictyaml.ruamel.resolver import BaseRes... |
import random
import string
import uuid
from contextlib import closing
import psycopg2
import pytest
from kazoo.client import KazooClient
from pgshovel.administration import initialize_cluster
from pgshovel.cluster import Cluster
DEFAULT_SCHEMA = """\
CREATE TABLE auth_user (
id bigserial PRIMARY KEY NOT NULL,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from specparser import HadoopRuntime
from collections import OrderedDict
import boto
import json
import os
import sys
import subprocess
def cmd(cmd_str):
ret = subprocess.call(cmd_str, shell=True)
return ret
def s3_delete(s3_path, settings):
from urlparse imp... |
"""
Surveilr - Log aggregation, analysis and visualisation
Copyright (C) 2011 Linux2Go
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License
as published by the Free Software Foundation, either version 3 of
the License... |
from bisect import bisect_left, bisect_right
from blending.src.decider.base_decider import BaseDecider
from blending.util.blend_config import BlendConfig
__author__ = 'DongMin Kim'
class DecideBestSTI(BaseDecider):
def __init__(self, a):
super(self.__class__, self).__init__(a)
def __str__(self):
... |
# -*- coding: utf-8 -*-
"""
Functions to read FAAM core processed data
"""
import datetime
import netCDF4 as nc
import numpy as np
from . import FaamFld, ObsData
from . import utils
def read_core_nc(fname, flds=None, time2datetime=False, calc_wspd=True, calc_wdir=True):
"""Read core FAAM data from a NetCDF file.... |
from django.test import TestCase
from django.urls import reverse
from portal.models import Student, Hobby
from portal.tests.constants import VALID_USERNAME
from portal.utils import get_invalid_id_popup, create_families_from_parents, assign_children_to_families
def create_student_and_return(username, child=False, mag... |
from django.core.management.base import NoArgsCommand
from askbot import models
from askbot import const
from askbot.conf import settings as askbot_settings
from django.utils.translation import ungettext
from askbot import mail
from askbot.utils.classes import ReminderSchedule
from askbot.models.question import Thread
... |
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html
"""
try:
import oslo.i18n
# NOTE(dhellmann): This reference to o-s-l-o will be replaced by the
# application name when this module is synced into the separate
# repository. It is OK to have more than one tr... |
import collections
import math
import sys
Statistics = collections.namedtuple("Statistics",
"mean mode median std_dev")
def main():
if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:
print("usage: {0} file1 [file2 [... fileN]]".format(
sys.argv[0])... |
"""
System commands
These are the default commands called by the system commandhandler
when various exceptions occur. If one of these commands are not
implemented and part of the current cmdset, the engine falls back
to a default solution instead.
Some system commands are shown in this module
as a REFERENCE only (the... |
# -*- coding: utf-8 -*-
import os
import sys
import random
def readhumanlines_i(inDir, num):
filename = os.path.join(inDir,str(num),'ivectors_' + str(num), 'spk_ivector.ark')
f = open(filename)
lines = f.readlines()
f.close()
return lines
def readhumanlines_d(inDir, num):
filename = os.path.j... |
import asn1crypto
# Functions that might be useful
def read(filename, binary=True):
"""
Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise
"""
with open(filename, 'rb' if ... |
# coding: utf-8
import os
import unittest
from sqlalchemy.engine.reflection import Inspector
from niamoto.testing import set_test_path
set_test_path()
from niamoto.conf import settings, NIAMOTO_HOME
from niamoto.testing.test_database_manager import TestDatabaseManager
from niamoto.testing.base_tests import BaseTes... |
# -*- coding: utf-8 -*-
'''
script.screensaver.meal - A random meal recipe screensaver for kodi
Copyright (C) 2015 enen92,Zag
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, eith... |
from __future__ import absolute_import
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.models import get_user_profile_by_email, UserMessage
from zerver.views.messages import get_old_messages_... |
"""2D Explosion using textured billboard quads
This example is designed to illustrate how to create 2D effects
using the default pyglet projection. Compare this code to the
3D splode.py
"""
__version__ = '$Id: splode2d.py 203 2009-04-05 03:52:58Z casey.duncan $'
import os
import math
import time
from pyglet import i... |
# ******** Part 2 - code layout **************************
class AClass:
def m1(self):
pass
def m2(self):
pass
def m3(self):
pass
def some_method(a1, a2, a3):
"""
some_method returns the larger of 1 or 2
:param a1: First item to compare
:param a2: Second item t... |
import pynmea2
import datetime
def test_proprietary_1():
# A sample proprietary sentence from a LCJ Capteurs
# anemometer.
data = "$PLCJ,5F01,66FC,AA,9390,6373"
msg = pynmea2.parse(data)
assert msg.manufacturer == "LCJ"
assert msg.data == ['','5F01','66FC','AA','9390','6373']
assert msg.ren... |
class StringNamespacedData:
def __init__(self, state):
self.state = state
def max_args(self):
return 0
def arg_flags(self, i):
return 0
def preparse(self):
pass
def postparse(self):
pass
def long_last_arg(self):
return False
def first_arg_is_na... |
# -*- coding: utf-8 -*-
import httplib as http
import sys
import inspect
import pkgutil
import mock
from nose import SkipTest
from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from tests import factories
from api.base.settings.defaults import API_BASE
from rest_framework.permissions import... |
'''>>> print("""docstring""")'''
async
""">>> print('''docstring''')"""
await
"""\n>>> print('''docstring''')"""
await
""" >>> print('''docstring''')"""
await
""" 1 >>> print('''docstring''')"""
await
''' : punctuation.definition.string.begin.python, source.python, string.quoted.docstring.multi.python
>... |
import abc
from oslo_log import log as logging
import six
from tempest_lib import auth
from tempest import config
from tempest import exceptions
CONF = config.CONF
LOG = logging.getLogger(__name__)
# Type of credentials available from configuration
CREDENTIAL_TYPES = {
'identity_admin': ('identity', 'admin'),
... |
# -*- coding: utf-8 -*-
"""django-confit documentation build configuration file."""
import os
import re
from django.conf import settings
# Minimal Django settings. Required to use sphinx.ext.autodoc, because
# django-confit depends on Django...
settings.configure()
doc_dir = os.path.dirname(os.path.abspath(__file_... |
#!usr/bin/env python
# coding=utf-8
# Created by <EMAIL> on 2016/11/9.
from flask import jsonify, request, current_app, url_for
from . import api
from ..models import User, Post
@api.route('/users/<int:id>')
def get_user(id):
user = User.query.get_or_404(id)
return jsonify(user.to_json())
@api.route('/use... |
# -*- coding: utf8 -*-
"""
.. module:: burpui.models
:platform: Unix
:synopsis: Burp-UI DB models module.
.. moduleauthor:: Ziirish <<EMAIL>>
"""
import datetime
from .ext.sql import db
from flask import current_app, session
from .engines.server import BUIServer # noqa
app = current_app # type: BUIServer
... |
def simulate_one_path(N, x0, p0, M, m):
x = np.zeros(N+1)
p = np.zeros(N+1)
index_set = range(0, N+1)
x[0] = x0
p[0] = p0
for n in index_set[1:]:
x[n] = x[n-1] + p[n-1]/(100.0*12)*x[n-1]
# Update interest rate p
r = random.randint(1, M)
if r == 1:
#... |
from typing import Union, Tuple, List, Iterable, Dict
import collections
import string
import os
import json
from .WordTokenizer import WordTokenizer, ENGLISH_STOP_WORDS
class WhitespaceTokenizer(WordTokenizer):
"""
Simple and fast white-space tokenizer. Splits sentence based on white spaces.
Punctuation a... |
from ipmininet.iptopo import IPTopo
from ipmininet.router.config import RouterConfig, STATIC, StaticRoute
class StaticRoutingNet(IPTopo):
def build(self, *args, **kwargs):
# Change the config object for RouterConfig
# because it does not add by default OSPF or OSPF6
r1 = self.addRouter("... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Category'
db.create_table(u'services_category', (
(u'id', self.gf('django.db.mod... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.template import Template, Context
from multilingual.flatpages.models import MultilingualFlatPage
class TemplateTestCase(TestCase):
fixtures = ['testdata.json']
def test_gll(self):
mfp = MultilingualFlatPage.objects.get(url='/test1/')
... |
{
'name': 'Donation Recurring Tax Receipt',
'version': '8.0.0.1.0',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Manage recurring donations with tax receipts',
'author': 'Barroux Abbey, Akretion, Odoo Community Association (OCA)',
'website': 'http://www.barroux.org',
... |
"""
Examples to show basic use case of python azure-eventhub SDK, including:
- Create EventHubProducerClient
- Create EventHubConsumerClient
- Create EventData
- Create EventDataBatch
- Send EventDataBatch
- Receive EventData
- Close EventHubProducerClient
- Close EventHubConsumerClient
... |
"""This is a self-profiling tool."""
from collections import namedtuple
import inspect
import itertools
import logging
import os
import signal
import sys
import threading
import time
PROFILING_TIMER_DELAY = 0.01
BLACKLIST = [
'copy.py:_deepcopy_dict',
'copy.py:_deepcopy_list',
'__init__.py:query',
'en... |
from __future__ import division, print_function, absolute_import
import os
import subprocess
import datetime as dt
import argparse
def main():
parser = argparse.ArgumentParser(description='This program filters a journal file to on keep certain sites and removes duplicate journals..')
parser.add_argument('--dat... |
'''
Copyright (C) 2021 Gitcoin Core
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This progra... |
from __future__ import print_function
import copy
import errno
import gc
import logging
import os
import pprint
import socket
import sys
import traceback
import eventlet.backdoor
import greenlet
from oslo_config import cfg
from conveyor.common._i18n import _LI
help_for_backdoor_port = (
"Acceptable values are 0... |
import os, logging
import mxnet as mx
def get_movielens_data(data_dir, prefix):
# MovieLens 10M dataset from https://grouplens.org/datasets/movielens/
# This dataset is copy right to GroupLens Research Group at the University of Minnesota,
# and licensed under their usage license.
# For full text of th... |
from setuptools import setup
setup(
name='mir.sqlqs',
version='0.5.0',
description='Relational SQL API (SQL QuerySet)',
long_description='',
keywords='',
url='https://github.com/darkfeline/mir.sqlqs',
author='Allen Li',
author_email='<EMAIL>',
classifiers=[
'Development Stat... |
from asp.jit import mapreduce_support as mr
class ArrayDoublerMRJob(mr.AspMRJob):
def mapper(self, key, value):
try:
yield 1, 2*float(value)
except ValueError:
pass
class ArrayDoubler(object):
def __init__(self):
self.pure_python = True
def double_usin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.