content
stringlengths
5
1.05M
from datetime import date, timedelta from fluff import TYPE_DATE, TYPE_INTEGER, TYPE_SMALL_INTEGER from corehq.apps.userreports.indicators.utils import get_values_by_product from corehq.apps.userreports.util import truncate_value class Column(object): def __init__(self, id, datatype, is_nullable=True, is_prima...
''' hotandcold.py Name: Wengel Gemu Collaborators: Date: September 20, 2019 Description: ''' # This program uses MIT card counting information to tell # the user when the current deck is hot (it's time to bet # big!) or cold (leave the table). It gets user input and # then keeps track of the MIT card counting score ...
from ctypes import * from .util import iz_bool from .space import Space class SimpleSearcher: def __init__(self, x): self.variables = x self.size = len(x) VARSTYPE = c_void_p * self.size self.array = VARSTYPE() for i, v in enumerate(self.variables): self.array[...
from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _, ugettext from django.views.generic import FormView, TemplateView, CreateView, UpdateView, View from django.views.gen...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import math # import ipdb; ipdb.set_trace() from .. import sac_utils as utils from . import Agent from . import actor from . import critic class SACAgent(Agent): """SAC algorithm.""" def __init__(self, obs_dim, action_dim, ...
'Automated Valuation Model version 2' import pdb import numpy as np import pandas as pd from pprint import pprint import sklearn import sklearn.ensemble import sklearn.linear_model import sklearn.preprocessing from columns_contain import columns_contain import AVM_elastic_net import AVM_gradient_boosting_regressor i...
#!/usr/bin/env python from os import path, remove from pyinfra import local def generate_api_docs(): this_dir = path.dirname(path.realpath(__file__)) docs_dir = path.abspath(path.join(this_dir, '..', 'docs')) pyinfra_dir = path.abspath(path.join(this_dir, '..', 'pyinfra')) api_doc_command = ( ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import json import tweepy import sys import locale import datetime locale.setlocale(locale.LC_CTYPE, "") def load_json(filename): f = open(filename) result = json.loads(f.read()) f.close() #print filename return result def init_config(consumer_token, ...
#! -*- coding: utf-8 -*- #--------------------------------- # モジュールのインポート #--------------------------------- import os import pickle import pathlib import logging import argparse import time import fcntl #--------------------------------- # 定数定義 #--------------------------------- BASE_DIR = '/tmp/subproc' FIFO_NAME =...
from model.eegnet_pt import EEGNet class ConfigEEGNet: def __init__(self, nb_classes:int, channels: int, samples: int, kernel_length: int, f1: int, d:int, dropout_rate: float): self.nb_classes = nb_classes self.channels = channels self.samples = samples ...
import os import argparse import numpy as np import random import time import logging from torch.utils import data from transformers.optimization import Adafactor from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config from torch.cuda.amp import autocast as autocast from torch.utils.data import (...
from typing import Optional from fastapi.encoders import jsonable_encoder from dispatch.project import service as project_service from .models import TagType, TagTypeCreate, TagTypeUpdate def get(*, db_session, tag_type_id: int) -> Optional[TagType]: """ Gets a tag type by its id. """ return db_sessi...
from django.test import TestCase class RegisterTest(TestCase): def setUp(self): self.user = { 'first_name': 'Bairavan', 'last_name': 'Durairaj', 'email': 'bairavan@alchemdigital.com', 'password1': 'myPass#1996', } def test_register(self): ...
def fun(solutions, map): map[1] = '홍길동' solutions.append(map) solutions = [] fun(solutions, {}) print(solutions)
# coding=utf-8 # *** WARNING: this file was generated by test. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from ... import _enums a...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging try: import colorlog except ImportError: colorlog = False logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) FORMATTER = ( "%(asctime)s " "[%(log_color)s%(levelname)s%(reset)s] " "[%(cyan)s%(name)s:%(linen...
""" API Wrapper for the Exaroton API """ __version__ = "0.0.2" from .exaroton import Exaroton
import os import json script_root = os.getcwd() input = json.load(open(f"{script_root}/data/# in.json", "r")) output = open(f"{script_root}/data/# out.txt", "w") for msg in input["messages"]: fixed_msg = msg["content"].replace("\n", ". ") output.write(f"- {fixed_msg}\n") output.close()
from flask import Flask, jsonify, request import tensorflow as tf import tensorflow_hub as hub import sys import logging from healthcheck import HealthCheck app = Flask(__name__) logging.basicConfig(filename="flask.log", level=logging.DEBUG, format="%(asctime)s %(levelname)s %(name)s %(threadName)s : ...
import util.cached import time import pytest import collections def test_methods_are_illegal(): class Foo(object): @util.cached.disk def fn(): pass with pytest.raises(AssertionError): Foo().fn() def test_disk(): state = {'val': 0} @util.cached.disk def fn(): ...
import basevcstest class TestVCSBg(basevcstest.VCSBaseTest): def __init__(self, *a, **k): k["geometry"] = {"width": 500, "height": 500} super(TestVCSBg, self).__init__(*a, **k) def testBgUpdate(self): self.x.backgroundcolor = (232, 25, 28) self.x.open() self.checkImage...
#!/usr/bin/env python """Create a Cohesity NFS View Using python""" # import pyhesity wrapper module from pyhesity import * # command line arguments import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--vip', type=str, required=True) # Cohesity cluster name or IP parser.add_argument('-u', '...
# -*- coding=utf-8 -*- import unittest import jionlp as jio class TestMoneyParser(unittest.TestCase): """ 测试金额解析工具 """ def test_money_parser(self): """ test jio.parse_money """ money_string_list = [ # 纯数金额 ['82,225.00元', {'num': '82225.00', 'case': '元', 'definition...
# -------------------------------------------------- ML 02/10/2019 ----------------------------------------------------# # # This is the class for poisson process # # -------------------------------------------------------------------------------------------------------------------- # import numpy as np import pandas ...
"""Get .csv data file of historical FX prices.""" import argparse from os.path import exists import oandapyV20.endpoints.instruments as instruments import pandas as pd from oandapyV20 import API from config import get_config def get_args(): """Get arguments from command line. Returns ---------- arg...
import pandas as pd from point import Point # orientation # read coordinates df = pd.read_csv('coo.csv') pnts = {} # new dictionary for points # convert data to dictionary of Point objects for i in range(df.shape[0]): pnts[df['id'][i]] = Point(df['x'][i], df['y'][i]) # read station target and mea...
from typing import Tuple from optuna import create_study from optuna.study._multi_objective import _get_pareto_front_trials_2d from optuna.study._multi_objective import _get_pareto_front_trials_nd from optuna.trial import FrozenTrial def _trial_to_values(t: FrozenTrial) -> Tuple[float, ...]: assert t.values is n...
import os import sys proj_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.insert(0,proj_dir) from model.Resource_Rational_Subgoal_Planning_Agent import * import utils.blockworld as bw import utils.blockworld_library as bl import pandas as pd a = Resource_Rational_Subgoal_Planning_Agent...
# Copyright 2017--2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" f...
#!/usr/bin/env python r''' https://www.hackerrank.com/challenges/service-lane/problem ''' import math import os import random import re import sys def gmin(n, s, e): min_val = sys.maxsize for i in range(s, e+1): if n[i] < min_val: min_val = n[i] return min_val # Complete the serviceL...
from abc import ABC, abstractmethod from datetime import datetime, timezone from enum import Enum from functools import cached_property import heapq import os from pathlib import Path, PurePosixPath import re from shutil import rmtree import tempfile from time import sleep from typing import Any, Dict, Iterator, List, ...
#!/usr/bin/env python # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 2 # of the License, or (at your option) any later version. # # This program is distrib...
# -*- coding: utf-8 -*- """Check Markdown Links. This module will run on all files to try markdown links. """ # Add Native Libraries from pathlib import Path import subprocess import shlex def check_markdown_links(): """Function will check all markdown files to see if there are any broken links. Args: ...
import json import datetime import tornado.web from status.util import SafeHandler class PricingBaseHandler(SafeHandler): """Base class that other pricing handlers should inherit from. Implements most of the logic of the pricing that other classes should reuse """ # _____________________________ HEL...
import argparse import fnmatch import logging import os import re import sys from smoke_test.main import smoke_test from smoke_test.utils import get_test_stats __version__ = '1.0.0' COMPUTER_RE = re.compile(r's\d{3}$') DEFAULT_EXTRACT_DIR = 'extracted' STUDENT_DIR_INFO_SEPARATOR = '_' def va...
""" Test Data is from part of https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data """ from pandas import DataFrame adults01 = DataFrame([ [39, 'Bachelors', 'Not-in-family', '<=50K', '06/26/1980'], [50, 'Bachelors', 'Husband', '<=50K', '06/18/1969'], [38, 'HS-grad', 'Not-in-family', '...
import sys sys.path.append('./test/tests') from driver import driver, Keys driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source #import test_exam...
from django.contrib import admin from .models import Discipline, DisciplineFront class DisciplineFrontInline(admin.StackedInline): model = DisciplineFront fk_name = 'containing_discipline' fields = ( 'name', ) @admin.register(Discipline) class DisciplineAdmin(admin.ModelAdmin): fiel...
# -*- coding: utf-8 -*- import os import re import time import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from PIL import Image def get_touch_point(): mobile_info = os.popen('cd adb && adb shell wm size') resolution = re.findall(r'Physical size: (\d+?)x(\d+)', mobile_...
import carla import numpy as np import Vehicle from numpy import random import logging from carla import VehicleLightState as vls class Controller: globalController = None def __init__(self, uiroot): self.client = None self.world = None self.uiroot = uiroot self.vehicle_bluep...
import torch from torch import nn import torch.nn.functional as F from torch.nn.parameter import Parameter class AdaptiveConcatPool2d(nn.Module): def __init__(self, sz=None): super().__init__() sz = sz or (1, 1) self.ap = nn.AdaptiveAvgPool2d(sz) self.mp = nn.AdaptiveMaxPool2d(sz) ...
from django.db import models # Create your models here. # class ContMonWebsite(models.Model): # pass from jsonfield import JSONField from model_utils.models import TimeStampedModel import reversion class CrawlUrl(TimeStampedModel): url = models.CharField(max_length=500, db_index=True) domain = models.Ch...
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2020-11-23 13:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('activities', '0032_auto_20201120_1304'), ] operat...
#!/usr/bin/env python # coding: utf8 import sys def get_check_code(id_code): s = 0 weight = lambda i: (1 << (17 - i)) % 11 for i, a in enumerate(id_code[:-1]): s += int(a) * weight(i) n = (12 - s % 11) % 11 return 'X' if n == 10 else str(n) def convert_id_code(id_code): if isinstan...
def minion_game(string): vowels = {"A": True, "E": True, "I": True, "O": True, "U": True} kevin = stuart = 0 for key, value in enumerate(string): if value in vowels: kevin += len(string) - key else: stuart += len(string) - key if kevin > stuart: print(f"K...
import os import datetime SKRIPTPFAD = os.path.abspath(os.path.dirname(__file__)) class JoltManager: def __init__(self): self.number_jolts_one_different = 0 self.number_jolts_three_different = 0 def increase_one_different(self): self.number_jolts_one_different += 1 def increase_...
try: unicode except NameError: raise ImportError from pybench import Test class ConcatUnicode(Test): version = 2.0 operations = 10 * 5 rounds = 60000 def test(self): # Make sure the strings are *not* interned s = unicode(u''.join(map(str,range(100)))) t = unicode(u''...
from lib import action class ConsulAgentChecksAction(action.ConsulBaseAction): def run(self, consul_profile=None): self._create_client(consul_profile) return (True, self.consul.agent.checks())
from datautil.jsonservices import DatasetAPIInfoJSONMaker, OcalAPIRequestJSONMaker, JSONExporter, SetupGridPointsMaker, \ MinMax, OcalAPICommunicationService from datautil.jsonservices import OcalApiService from datautil.visualizationservices import Visualizer class Facade: @staticmethod def validate_fea...
"""Constants for the DroneMobile python library.""" AWSCLIENTID = "3l3gtebtua7qft45b4splbeuiu" BASE_API_URL = "https://api.dronemobile.com/api/" HOST = "api.dronemobile.com" API_VERSION = "v1" URLS = { "auth": "https://cognito-idp.us-east-1.amazonaws.com/", "user_info": f"{BASE_API_URL}{API_VERSION}/user",...
import os import argparse import json import datetime import sys from PyQt5 import QtGui, QtWidgets, uic from google.cloud import pubsub_v1 qtUiFile = "gcp_qt.ui" class Ui(QtWidgets.QMainWindow): """Basic Message Visualizer gui""" def __init__(self, project_id, subscription_id): super(Ui, self).__init...
import sys, os, re, io, threading, copy, getopt import unittest from logging import getLogger from lib import logger, wk8 logger.enable() L = getLogger("test") class Wenku8TestCase(unittest.TestCase): def setUp(self): self.w = wk8.Wenku8() def test_login(self): L.info("测试: 登陆") self.assertTrue(self.w...
import sys, screed d = {} for record in screed.open(sys.argv[1]): ncbi_id = record.name.split(' ')[0].rsplit('|',2)[1] seq = record.sequence d[ncbi_id] = seq for line in open(sys.argv[2]): assay, ncbi, start, end = line.rstrip().split('\t') start = int(start) end = int(end) target = d[ncbi...
# Copyright The PyTorch Lightning team. # # 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 i...
import sys,os target_prefix = sys.prefix for i in range(len(sys.argv)): a = sys.argv[i] if a=='--prefix': target_prefix=sys.argv[i+1] sp = a.split("--prefix=") if len(sp)==2: target_prefix=sp[1] sys.path.insert(0,os.path.join(target_prefix,'lib','python%i.%i' % sys.version_info[:2],'site...
# Generated by Django 3.0 on 2020-07-31 06:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AuthorItem', fields=[ ...
from osf import confirm import time if __name__ == '__main__': start_time = time.time() confirm.confirm_user() print("--- %s seconds ---" % (time.time() - start_time))
import sys from i2cdriver import I2CDriver, EDS # Using a TCA9548A Low-Voltage 8-Channel I2C Switch # Three LM75B temperature sensors are connected to # channels 0,1 and 2. All are at address 0x48. class Mux: def __init__(self, i2, a = 0x70): self.i2 = i2 self.a = a def select(self, n): ...
# Introduction to Markov chain Monte Carlo — with examples ... # https://www.researchgate.net/file.PostFileLoader.html?id=515196a8d039b13015000002&assetKey=AS%3A271835466272768%401441822033782 from pylab import * import pymc from pymc import Matplot import numpy as np from scipy.misc import factorial import spacepy.p...
# -*- coding: utf-8 -*- # This test is supposed to be ignored in `setup.cfg` import nose.tools as ns from os.path import abspath, dirname, join, exists from ConfigParser import SafeConfigParser from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.istream.tweet import Tweet def test_tweet_usage...
import argparse import json import os from glob import glob from pathlib import Path import cv2 from tqdm import tqdm from test_model.temporal.results_generation import calculate_distance from utils.data_funcs import bb_intersection_over_union parser = argparse.ArgumentParser( description="Generate annotation fi...
#There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. # #You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. # #Return the starting gas s...
# -*- coding: utf-8 -*- while True: senha = input() if senha == '2002': print('Acesso Permitido') break print('Senha Invalida')
''' Just like the balloon with multiple ribbons, if we change the attribute of an object through one reference variable, it immediately reflects in other reference variable as there is only one balloon ultimately! ''' class Mobile: def __init__(self, price, brand): self.price = price self.brand =...
import re import numpy as np import xarray as xr from scipy.spatial import Delaunay, Voronoi from ...core.utils import as_id_array from ...utils import jaggedarray from ..sort.intpair import pair_isin from ..sort.sort import reverse_one_to_one class VoronoiDelaunay(object): def __init__(self, xy_of_node): ...
#!/usr/bin/python """Sets and unsets a lock on the local pysal repository.""" import os, sys #check lock if os.path.exists('/tmp/pysal.lock'): print "LOCK IN PLACE, another process is running perhaps?" sys.exit(1) else: lck = open('/tmp/pysal.lock','w') lck.write('%d'%os.getpid()) lck.close() l...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-13 17:23 from __future__ import unicode_literals import dashboard.app_helpers from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0001_initial'), ] operations = [ ...
import scraper def collect_urls(products_url, prefix = ''): products_html = scraper.content(products_url) products_hrefs = scraper.get_attrs(products_html, 'div.product-item a', 'href') product_urls = [(prefix + href) for href in products_hrefs] return product_urls def collect_info(product_url): p...
import os from collections import OrderedDict from django.apps import apps from django.conf import settings from django.contrib.staticfiles import utils from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import ( FileSystemStorage, Storage, default_storage, ) from django.utils i...
from django.core.management.base import BaseCommand from bots.helpers.twitter_bot_utils.conversation_utils import ( get_full_conversation_as_json, ) from bots.management.commands._helpers import ( get_username_pairs_from_arguments, add_username_pairs_argument_to_parser, ) class Command(BaseCommand): h...
#-*- coding: utf-8 -*- from django.http import HttpResponse from django.conf import settings import mimetypes import os class NginxXAccelRedirectServer(object): def serve(self, request, path): response = HttpResponse() fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path) response['X-...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Arima.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui import arima import basic_exponential import trend_exponential import seasoning_exponential im...
#! -*- codign: utf-8 -*- import argparse import contextlib import os.path import re import shutil import signal import subprocess import sys import tempfile import traceback import yaml from . import utils """ Main code, runner """ class Runner(object): BASEDIR_TEMP = 'TEMP' signals = [ signal.S...
import theano from theano import tensor as T import numpy as np from inputFormat import * from layers import * import cPickle class network: def __init__(self, batch_size = None, rng = None, load_file = None, params = None): if(not rng): rng = np.random.RandomState(None) self.input = T.tensor4('input') #position...
from aoc_1 import read_data def parse_data(data): coords = [] max_x = 0 max_y = 0 for row in data: start, end = row.split(' -> ') sx, sy = start.split(',') sx, sy = int(sx), int(sy) ex, ey = end.split(',') ex, ey = int(ex), int(ey) coords.append( (sx, sy...
from django.core.files.uploadedfile import SimpleUploadedFile from admin_smoke import tests from testproject.testapp import admin, models class ProjectAdminTestCase(tests.AdminTests, tests.AdminBaseTestCase): model_admin = admin.ProjectAdmin model = models.Project object_name = 'project' excluded_fie...
import matplotlib.pyplot as plt from scipy.io import wavfile # get the api from scipy.fftpack import fft from pylab import * from pydub import AudioSegment from ragas import * from frequencyAnalysis import * from window import window ################################################################### ############...
from datetime import datetime, timedelta from django.test import TestCase try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User else: User = get_user_model() from .. import models class AsOfTest(TestCase): model = models.Document def ...
# coding=utf-8 # Copyright 2019 Google LLC. # # 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 ...
# # Pyserini: Python interface to the Anserini IR toolkit built on Lucene # # 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...
from mpi4py import MPI from osim.env import ProstheticsEnv from pros_ai import get_policy_observation comm = MPI.Comm.Get_parent() size = comm.Get_size() rank = comm.Get_rank() env = ProstheticsEnv(visualize=False) trajectory_length = None trajectory_length = comm.bcast(trajectory_length, root=0) finished = False ...
#### # EEA Pollutant Enumerator. DO NOT EDIT. #### POLLUTANT_TYPE = { 'As in PM10': 5018, 'BaP in PM10': 5029, 'C6H6': 20, 'Cd in PM10': 5014, 'CO': 10, 'Ni in PM10': 5015, 'NO2': 8, 'NOX as NO2': 9, 'O3': 7, 'Pb in PM10': 5012, 'PM10': 5, 'PM2.5': 6001, 'SO2': 1 } #...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
# -*- coding: utf-8 -*- import os from pydeps.cli import error from pydeps.pydeps import pydeps from tests.filemaker import create_files from tests.simpledeps import simpledeps, empty def test_output(tmpdir): files = """ unrelated: [] foo: - __init__.py - a.py: | ...
import numpy as np from rasterio.features import geometry_mask from ..raster import BandSample def rasterize(feature_collection, transform, out_shape, name='mask'): """Transform vector geometries to raster form, return band sample where raster is np.array of bool dtype (`True` value correspond to objects a...
# Copyright 2014 Cloudera Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
"""Tools for working with geometric primitives and randomising aspects of geometry (shape, pose, etc.).""" import math import warnings from collections.abc import Iterable, Sequence import numpy as np import pymunk as pm from pymunk.vec2d import Vec2d def regular_poly_circumrad(n_sides, side_length): """Circumr...
from functools import partial import torch __all__ = ['CaptureOutput'] class CaptureOutput(object): def __init__(self, module, layers): self.module = module self.layers = layers def __enter__(self): self.outputs = {} self._hooks = [] for name, layer in self.layers....
# Copyright 2018 The Oppia Authors. All Rights Reserved. # # 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 ...
class Validation: @staticmethod def is_number(number): try: int(number) except ValueError: return False return True @staticmethod def is_float(number): try: float(number) except ValueError: return False retu...
#!/usr/bin/env python import itertools from egcg_core.config import cfg from openpyxl import load_workbook from EPPs.common import StepEPP class GenerateManifest(StepEPP): # populate the sample manifest with the sample date. Sample manifest template is determined by a step udf. # The starting row and column...
# -*- coding: UTF-8 no BOM -*- # obtained from https://damask.mpie.de # import os,sys import numpy as np # ------------------------------------------------------------------ # python 3 has no unicode object, this ensures that the code works on Python 2&3 try: test=isinstance('test', unicode) except(NameError): u...
import argparse import os import sys from boa.compiler import Compiler parser = argparse.ArgumentParser("simple_example") parser.add_argument("input", help="Input python file.", type=str) parser.add_argument("output", help="Output avm file.", type=str) args = parser.parse_args() path = os.path.dirname(os.path.abspat...
"""The Philosophy Game Clicking on the first non-parenthesized, non-italicized link, in the main text of a Wikipedia article, and then repeating the process for subsequent articles, usually eventually gets one to the Philosophy article. (See https://en.wikipedia.org/wiki/Wikipedia:Getting_to_Philosophy for more inform...
#_*_ coding: UTF-8 _*_ from flask import url_for def url_for_entity(entity, external=False): key = entity.key endpoint = 'view_%s' % key.kind().lower() return url_for(endpoint, db_id=key.urlsafe(), _external=external) def url_for_list(kind, parent, **query_params): endpoint = 'view_%s_list' % kind.lo...
"""test file for terraform_env""" import unittest import yaml from dsi.common import terraform_output_parser as tf_output from dsi.common import whereami from dsi.common.config import ConfigDict from test_lib.fixture_files import FixtureFiles FIXTURE_FILES = FixtureFiles() class TestTerraformOutputParser(unittes...
# -*- coding: utf-8 -*- ''' Read timeline from all configured channels docstring placeholder ''' from snsapi.snspocket import SNSPocket from snsapi.utils import console_input,console_output if __name__ == "__main__": sp = SNSPocket() sp.load_config() sp.auth() sl = sp.home_timeline() print sl
#Generate NV Scores/Noun Scores #Generate line to line similarity scores based on Noun, Verb and Date if NV Scores #Else based on Just Nouns if Noun Scores import pickle, string, nltk import cPickle as pickle import logging from gensim import corpora, models, similarities import re, enchant import string import nltk...
def print_rangoli(size): n = size ans = "" if(n > 26): print('enter valid number') else: lst=[] maxAsci = 97+n for i in range(97, maxAsci ): lst.append(chr(i)) maxLength = 2 * ( 2*n - 1) - 1 def printLine(lst): lstTemp = list(lst[1:...