content
stringlengths
5
1.05M
import os LOG_DIR = "home/ubuntu/job-miner/logs/" AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"] AWS_SECRET_ACCESS_KEY = os.environ["AWS_SECRET_ACCESS_KEY"] XML_PATH = 's3a://jd-scrapped/dice_xml/*.xml' PARQUET_PATH = 's3a://jd-parquet/jd_raw.parquet' ES_HOST = '10.0.0.13' ES_PORT = '9200' PARQUET_BUCKET = 'jd-...
# -*- coding: utf-8 -*- """ Created on Thu Apr 23 21:32:15 2020 @author: user """ # python David_5_5_train_recognizer.py --selfies output/faces --classifier output/classifier --sample-size 100 # python David_5_5_train_recognizer.py # import the necessary packages from __future__ import print_function from pyimagese...
# *** WARNING: this file was generated by the Kulado Kubernetes codegen tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import kulado import kulado.runtime import warnings from ... import tables, version class Binding(kulado.CustomResource): """ Binding ties one ob...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^experiments/$', views.experiment_list, name='experiment_list'), url(r'^experiments/new$', views.experiment_create, name='experiment_new'), url(r'^experiments/edit/(?P<pk>\...
# -*- coding: utf-8 -*- """ Created on Wed Nov 11 22:31:13 2020 @author: trohit """ from collections import deque """ A +-^-+ B C | +-+-+ D E F G bfs: abcdefg dfs: abdcefg """ def bfs(graph:dict, v:set, n:str): if n not in v: print(n) print("(+) v add " + n) v.add(n)...
# coding: utf8 """ weasyprint.tests.w3_test_suite.web ---------------------------------- A simple web application to run and inspect the results of the W3C CSS 2.1 Test Suite. See http://test.csswg.org/suites/css2.1/20110323/ :copyright: Copyright 2011-2012 Simon Sapin and contributors, see A...
#!/usr/bin/env python import cv2 import numpy as np import matplotlib.pyplot as plt import scipy.signal import os, sys import cv2 import xml.etree.ElementTree as et import math DEBUG=True def get_names(fname): names = [] with open(sys.argv[1]) as fp: while 1: n = fp.readline().strip() ...
from django.core.exceptions import ValidationError ''' RowHandler objects An object inheriting from RowHandler() should be created for each different 'type' of row (the 'type' being determined by a unique combination of columns) process_row (input): row data obtained from the Importer object...
""" Tests for the genetic species interface. """ import unittest import math import msprime import stdpopsim class TestSpecies(unittest.TestCase): """ Tests for basic methods for the species. """ def test_str(self): for species in stdpopsim.all_species(): s = str(species) ...
import argparse import json from typing import List def dict_inc(d, key): if key in d: d[key] += 1 else: d[key] = 1 def read_lines(input_file: str) -> List[str]: lines = [] with open(input_file, "rb") as f: for l in f: lines.append(l.decode().strip()) return l...
#!/usr/bin/env python import sys ########################################################### # # Error aggregation by heuristics # # Each error function has the same structure. They take 4 arguments: # - ungrouped, a list of errors (tuple of error type and a node in a tree) # - grouped, a list of Error_Groups # ...
''' pgm_utils.py : Python utilties for PGM files Copyright (C) 2014 Simon D. Levy This code 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 version 3 of the License, or (at your opti...
import json import datetime import shutil from os import listdir from os.path import isfile, join, basename, dirname from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, timeline def format_time(date_time_str): date_time_obj = datetime.datetime.strptime(date_time_str...
#!/usr/bin/python import sys import random import math import operator from sklearn.metrics import roc_auc_score from sklearn.metrics import mean_squared_error bufferCaseNum = 1000000 eta = 0.01 lamb = 1E-6 featWeight = {} trainRounds = 10 random.seed(10) initWeight = 0.05 def nextInitWeight(): return (random.ra...
import os from docxUtils import DOCXReport class ReporterTest(DOCXReport): def create_content(self): self.doc.add_heading('Hello {}'.format(self.context['name']), level=1) def test_reporter(): root_path = os.path.expanduser('~/Desktop/report.docx') report = ReporterTest(None, {'name': 'Moto'}) ...
'''initialize''' from .diceloss import DiceLoss from .lovaszloss import LovaszLoss from .focalloss import SigmoidFocalLoss from .celoss import CrossEntropyLoss, BinaryCrossEntropyLoss
l = float(input('Digite a largura de sua parede: ')) a = float(input('Digite a altura da sua parede: ')) ar = (l*a) t = (ar/2) print('sua parede tem dimenção de {} x {} m\nA sua parede tem {} m²\nVocê precisa de {} L de tinta para pitar a sua parede'.format(l, a, ar, t))
from jinja2 import (nodes, BaseLoader, ChoiceLoader, PrefixLoader, FileSystemLoader,\ PackageLoader, TemplateNotFound) from jinja2.ext import Extension import re import os def configure_environment(env, wrap_loader=True, with_jinja_tags=True, with_html_tags=False): if wrap_loader: env....
#!/usr/bin/env python """Tests for the reliable_executor module""" import functools import random import unittest import reliable_executor class ReliablyExecuteTest(unittest.TestCase): """Test Case for reliable_executor.reliably_execute()""" def setUp(self): """Sets up a function with a random numbe...
from math import * import proteus.MeshTools from proteus import Domain from proteus.default_n import * from proteus.Profiling import logEvent from proteus.ctransportCoefficients import smoothedHeaviside from proteus.ctransportCoefficients import smoothedHeaviside_integral from proteus.Gauges import PointGauges,LineGaug...
from typing import Any, Dict, Iterable, List, Optional, Tuple import pandas as pd import pyarrow as pa from fugue.dataframe.dataframe import ( DataFrame, LocalBoundedDataFrame, _input_schema, ) from fugue.exceptions import FugueDataFrameInitError, FugueDataFrameOperationError from triad.collections.schema ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import typing from enum import IntEnum from typing import Any, Callable, Iterable, Sized, Tuple, TypeVar, Union from decorator import decorator T = TypeVar("T") class Dim(IntEnum): BATCH = 0 CHANNEL = 1 DEPTH = -3 HEIGHT = -2 WIDTH = -1 def arg_f...
import logging from logging.handlers import RotatingFileHandler import application as app # logging level LEVEL = logging.DEBUG # a filename to append log messages to LOG_FILENAME = '/var/log/apache2/myApp.log' # max size in bytes before a new log file is created MAX_SIZE = 2000 # max amount of log files before i...
from __future__ import absolute_import from django.core import mail from django.core.urlresolvers import reverse from mock import patch from sentry.models import ( AuthProvider, OrganizationMember, OrganizationMemberTeam) from sentry.testutils import APITestCase class UpdateOrganizationMemberTest(APITestCase): ...
import json import time import os import subprocess import threading import uuid from assemblyline.al.common import forge, queue, remote_datatypes from assemblyline.al.common.error_template import ERROR_MAP TYPE_BACKUP = 0 TYPE_RESTORE = 1 DATABASE_NUM = 3 RETRY_PRINT_THRESHOLD = 1000 COUNT_INCREMENT = 1000 LOW_THR...
# -*- encoding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.urls import reverse from django.http import HttpRes...
import io import zipfile from datetime import datetime, timedelta, timezone from urllib.request import Request, urlopen import pandas as pd import numpy as np import requests from my_project.utils import code_timer from pvlib import solarposition from pythermalcomfort.models import utci from pythermalcomfort.models im...
# Generated by Django 2.0 on 2018-02-08 16:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("spectator_events", "0032_recreate_work_slugs"), ] operations = [ migrations.RemoveField(model_name="classicalwork", name="creators",), ...
#!/usr/bin/env python3 """ Miguel F. Romero, 2021 github.com/miferg cgv_build.py formats genomic mapping information to be read by the CGView software. Requires R >= 3 Usage: cgv_build.py genomic.fna annotation.gff mapping.sam prefix """ import sys import subprocess try: genom_name = sys.argv[1] annot_name =...
# =================================================================== # # Copyright (c) 2014, Legrandin <helderijs@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributio...
#!/usr/bin/env python3 from itertools import combinations useds = {} avails = {} with open("input.txt") as f: for i, line in enumerate(f): if i < 2: continue splt = line.strip().split() useds[splt[0]] = int(splt[2][:-1]) avails[splt[0]] = int(splt[3][:-1]) nodes = lis...
import csv import json import logging import multiprocessing as mp import os import sys import daisy import numpy as np import pandas as pd import pymaid import scipy from synful import database, synapse, evaluation logger = logging.getLogger(__name__) def csv_to_list(csvfilename, column): with open(csvfilenam...
#!/usr/bin/env python3 import os from lib.file_actions import list_from_lines #Current file directory lib_dir = os.path.dirname(os.path.realpath(__file__)) main_dir = os.path.dirname(os.path.dirname(__file__)) log_dir = "%s/log" % (main_dir) list_dir = "%s/list" % (main_dir) bucket_dir = "%s/bucket" % (main_dir) #Ge...
from copy import deepcopy from .field import * from .database import * from .query import * import re from datetime import datetime # __all__ = [ # 'IntegerField', 'BigIntegerField', 'PrimaryKeyField', 'FloatField', 'DoubleField', # 'DateTimeField','BooleanField', 'Model', 'DoesNotExist', 'Field','SmallInteger...
import cdms2 import MV2 import os import pkg_resources egg_path = pkg_resources.resource_filename(pkg_resources.Requirement.parse("cdutil"), "share/cdutil") def create_surrounds(data): sh = list(data.shape) L = data.getAxis(1) bL = L.getBounds() if L.isCircular() and bL[-1][1] - bL[0][0] % L.modulo =...
#!/usr/bin/env python3 import os import json # print('Content-Type: text/plain') # print() # print(os.environ) # print('Content-Type: application/json') # print() # print(json.dumps(dict(os.environ.items()))) # print('Content-Type: text/plain') # print() # print(os.getenv('QUERY_STRING')) print('Content-Type: text/...
""" Script that contains the model used. Can be updated to any model within the Pytorch library. """ import re from torch import nn from torchvision import models # ******************************************************************************************************************** # class Model(nn.Module): ...
from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponse from .models import Greeting import numpy as np import pandas as pd from .utilities import distance # Create your views here. def index(request): # return HttpResponse('Hello from Python!') return r...
# -*- coding: utf-8 -*- import random from hashcode20.helpers import Input, Output def main(i: Input) -> Output: """naive: take order as the order of appearance""" library_order = list(map(lambda l: l.library_id, i.libraries)) book_order_per_library = [list(l.books) for l in i.libraries] return Outpu...
import numpy as np from skimage.filters import prewitt_h, prewitt_v, laplace class Feature: # create new Feature object storing 4 images def __init__(self, no_flash1, no_flash2, flash, lst_flash, n=5, boxsize=3, r=3): self.n = n self.boxsize = boxsize self.r = r self.locs...
input = open("inputs/2") ### 1st half # count horizontal and depth moves horizontal = 0 depth = 0 for line in input.readlines(): move, dist = line.split() if move == "forward": horizontal += int(dist) elif move == "down": depth += int(dist) elif move == "up": depth -= int(dist) ...
from urllib.parse import urlparse import redis from typing import List from redis.sentinel import Sentinel from csw.LocationService import ConnectionInfo, ComponentType, ConnectionType, LocationService from csw.Prefix import Prefix from csw.Subsystem import Subsystems class RedisConnector: def __init__(self):...
import urllib.request import os import pickle from html.parser import HTMLParser class ChordieParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) def valid_chords_line(self, line): """ check if the line describes chords :param line: :return: """ ...
from itertools import chain import torch import torch.nn as nn import torch.nn.functional as F class ConvBlock(nn.Module): def __init__(self, ndim, in_channels, out_channels, middle_channels=None): Conv = (None, nn.Conv1d, nn.Conv2d, nn.Conv3d)[ndim] BatchNorm = (None, nn.BatchNorm1d, nn.BatchNor...
import random from dataset.base_dataset import BaseDataset class ConcatDataset(BaseDataset): def __init__(self, source, target): assert( len(source) == len(target)) self.source = source self.target = target def __getitem__(self, i): index = i % len(self.source) return ...
from spacy.tokens import Span class EntityRelationExtractor(object): def __init__(self, entities, model, noun_phrases=False): self.entities = entities self.model = model self.noun_phrases = noun_phrases if not Span.has_extension('entity_relation_subj'): Span.set_extens...
# -*- codeing = utf-8 -*- # @Time : 2022/3/30 10:25 # @Author : linyaxuan # @File : utils.py # @Software : PyCharm import json
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError from .models import Team # Extend built-in User form to include email, first name, and last name fields class ExtendedUserCreationForm(UserCrea...
import h5py import os.path import numpy as np import matplotlib.pyplot as plt import time from sklearn.metrics import mean_absolute_error from typing import List, Tuple from adaptiveleak.utils.data_utils import array_to_fp_shifted, array_to_float_shifted, select_range_shifts_array, to_fixed_point, to_float from adapti...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 11:21:39 2020 @author: zhantao """ import torch import torch.nn as nn class downsampleLayer(nn.Module): ''' A downsample layer of UNet. LeakyReLU is used as the activation func. ''' def __init__(self, infeature, outfeature, ke...
from time import time import torch import numpy as np import matplotlib.pyplot as plt import plotly.graph_objects as go import random from model import AttentionModel from data import generate_data, data_from_txt from baseline import load_model from config import test_parser from plot import get_clean_path from utils ...
import sys from benchmark.testsystems import dhfr_constrained, dhfr_unconstrained, \ waterbox_constrained, flexible_waterbox, t4_constrained, t4_unconstrained, \ alanine_constrained, alanine_unconstrained, src_constrained from benchmark.testsystems.alanine_dipeptide import solvated_alanine_constrained, solvate...
""" Read-me: Call functions in this order: problem = gen_matrix(v,c) constrain(problem, string) obj(problem, string) maxz(problem) gen_matrix() produces a matrix to be given constraints and an objective function to maximize or minimize. It takes var (variable number) and cons (constraint number) as ...
from roundface import execute execute()
import json import os import requests def get_email(slack_user_id): """ Given a slack user id (which is not username!), return the related user email. Args: slack_user_id (string): slack user id, which is not the slack username! Returns: (True, string): If the user can be found from sl...
from typing import List class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res = [] #Nested helper function def dfs(partial, index): print("On entry partial=",partial,"index=",index) if len(partial) == k: print("Appended ",pa...
import asyncio from typing import List, Optional from services.lib.date_utils import MINUTE, parse_timespan_to_seconds from services.lib.depcont import DepContainer from services.lib.utils import class_logger from services.models.node_info import NodeEvent, NodeEventType, EventDataSlash from services.models.thormon im...
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _IBM class _Devtools(_IBM): _type = "devtools" _icon_dir = "resources/ibm/devtools" class CollaborativeDevelopment(_Devtools): _icon = "collaborative-development.png" class ConfigurationManagement(_Devtools): _icon...
#!/usr/bin/env python from decimal import Decimal from pyplus.common import * from pyplus.path import LazyPath DECIMAL = Decimal(1.5) DICT = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5} FLOAT = 1.5 INT = 1 LIST = [1, 2, 3, 4, 5] MAPPABLE = [("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5)] OBJECT = object() SET = {1, 2, ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import numpy as np from numpy.testing import assert_array_equal from abel.transform import get_basis_dir, set_basis_dir def test_basis_dir(): """ Te...
""" First Reverse Have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order. For example: if the input string is "Hello World and Coders" then your program should return the string "sredoC dna dlroW olleH". Examples Input: "Hello World and Coders" Output: etybredo...
from sys import stderr from time import sleep from traceback import format_exc import requests from helpers import chunker, show_progress def safe_request(request, api_location, **kwargs): """Encapsulates a request like request.post or request.get into a retry block. Requires the request to be a object in t...
# Copyright 2018 Capital One Services, 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 to in...
# Generated by Django 3.1.8 on 2021-05-25 20:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('timewebapp', '0035_settingsmodel_lowest_priority_color'), ] operations = [ migrations.RemoveField( model_name='settingsmodel', ...
""" Module for jenkinsapi Views """ import logging import json from jenkinsapi.view import View from jenkinsapi.custom_exceptions import JenkinsAPIException log = logging.getLogger(__name__) class Views(object): """ An abstraction on a Jenkins object's views """ LIST_VIEW = 'hudson.model.ListView' ...
from src.runner.trainers.base_trainer import BaseTrainer class KitsSegTrainer(BaseTrainer): """The KiTS trainer for segmentation task. """ def __init__(self, **kwargs): super().__init__(**kwargs) def _get_inputs_targets(self, batch): """Specify the data input and target. Args:...
from datetime import timedelta import pytest from django.utils.timezone import now from pretalx.event.stages import STAGE_ORDER, in_stage @pytest.mark.django_db @pytest.mark.parametrize( 'target,is_public,from_delta,to_delta,deadline_delta,has_submissions', ( ('PREPARATION', False, 2, 3, 1, False), ...
import tkinter as tk from tkinter import ttk def save_entry(filename): text = text_entry.get(1.0, tk.END) save_to_file(text, filename) def save_to_file(text, filename): if ".txt" in filename: print("file ready") pass else: filename = filename + ".txt" f = open(filename, "w+...
import json import unittest from unittest.mock import MagicMock, patch, call, mock_open import snyk import snyk_access class TestFindOrg(unittest.TestCase): def test_find_org(self): snyk_client = MagicMock(spec=snyk.Snyk) http_client = MagicMock(spec=snyk.HTTPClient) group = MagicMock(sp...
import pytest from server import app @pytest.fixture def client(): with app.test_client() as client: yield client def test_pico_recipes_page_successfully(client): """Retrieve /pico_recipes page successfully.""" rv = client.get('/pico_recipes') assert '200' in rv.status def test_zymatic_r...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/70 - vision.metrics.ipynb (unless otherwise specified). __all__ = ['KNNProxyMetric'] # Cell from fastai.vision.all import * # Cell class KNNProxyMetric(Callback): "A metric which calculates knn-1 accuracy. Use with a labeled validation set." order,run_train,run...
# Copyright (C) 2019 Alibaba Group Holding Limited. # All Rights Reserved. # ============================================================================== from __future__ import division from __future__ import print_function import tensorflow as tf from flags import FLAGS class LoggingTensorHook(tf.train.SessionRun...
from __future__ import annotations import argparse import logging import tempfile from pathlib import Path from typing import Any, Collection, Optional, Sequence import bokeh import numpy import pandas from bokeh.models import HoverTool, Title from bokeh.plotting import ColumnDataSource, figure import annofabcli imp...
from imutils.video import VideoStream import numpy as np import imutils import cv2 def detect_person(frame): ''' this functions test if there is any person in the supplied video frame. If there is any person in the frame, it also crops the region where the person is and returns that region. ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-24 17:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0006_auto_20160420_1812'), ] operations = [ migrations.DeleteModel( ...
"""helper functions used by the tests""" import os import glob import time from contextlib import contextmanager @contextmanager def clean_job(jenkins_job, disable=False): """Helper context manager that deletes a Jenkins job even when tests fail Args: jenkins_job (pyjen.job.Job): Jenkins ...
class Node: def __init__( self, val: int = 0, left: "Node" = None, right: "Node" = None, next: "Node" = None, ): self.val = val self.left = left self.right = right self.next = next class Solution: def connect(self, root: Node) -> Node...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: from .certifi import * from .dns import * from .get_dns import * from .get_hosts import * f...
import numpy as np # left --> -1 # right --> 1 #(current_state, current_value) --> #(write, move, next_state) test_rules = { ('A',0): (1, 1, 'B'), ('A',1): (0, -1, 'B'), ('B',0): (1, -1, 'A'), ('B',1): (1, 1, 'A') } real_rules={ ('A',0):(1, 1,'B'), ('A',1):(0,-1,'B'), ('B',0):(0, 1...
#!/usr/bin/env python # Align text and annotations to a different version of the same text. # Note: not comprehensively tested, use with caution. import codecs import sys DEFAULT_ENCODING = 'UTF-8' TEST_ARG = '--test' DEBUG = False WARN_LENGTH_PRODUCT = 1000000 options = None def argparser(): import argp...
# -*- coding: utf-8 -*- from __future__ import print_function, division import mxnet as mx import numpy as np from mxnet import gluon, nd from mxnet.gluon import nn from mxnet.gluon.data.vision import transforms from networks import resnet18, resnet34, resnet50 from gluoncv.data.market1501.data_read import ImageTxtDa...
#standard import os from string import split,join from operator import itemgetter import unittest class TCA_Output: def __init__(self, CF, Event_titles): self.SSoutfile = CF.Control["PDMTransFile"] self.Alloutfile = CF.Control["PDMAllFile"] self.BSMoutfile = CF.Control["BSMTransFile"] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the corpus module.""" import logging from unittest import TestCase from dphon.corpus import PlaintextCorpusLoader class TestPlaintextCorpusLoader(TestCase): """Test the PlaintextCorpusLoader.""" def setUp(self) -> None: """Create a loader f...
[ { 'date': '2019-01-01', 'description': 'Újév', 'locale': 'hu-HU', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2019-03-15', 'description': 'Az 1848-as forradalom ünnepe', 'locale': 'hu-HU', 'notes': '', 'regio...
import itertools from mau.lexers.base_lexer import Token, TokenTypes, Literal from mau.lexers.text_lexer import TextLexer from mau.parsers.base_parser import BaseParser, ParserError from mau.parsers.arguments_parser import ArgumentsParser from mau.parsers.nodes import ( WordNode, SentenceNode, TextNode, ...
#!/usr/bin/env python from ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter, PipelineGlobalSinkFilter from ATK.Delay import DoubleDualMultipleUniversalFixedDelayLineFilter sample_rate = 96000 def filter(inputl, inputr, blend_ch1=0, blend_ch2=0, feedback_ch1_ch1=0, feedback_ch1_ch2=0, feedback_ch2_ch...
# This file is initialized with a code version of this # question's sample test case. Feel free to add, edit, # or remove test cases in this file as you see fit! import program import unittest class TestProgram(unittest.TestCase): def test_case_1(self): competitions = [["HTML", "C#"], ["C#", "P...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2016 Bogdan Cordier <ooctogene@gmail.com> # and Matteo Cypriani <mcy@lm7.fr> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # ...
from distutils.core import setup setup(name='nlcd', packages=['nlcd'], version='0.2', description='This library provides some helpers related to the National Land Cover Database (NLCD). The NLCD is created by the Multi-Resolution Land Characteristics Consortium (MRLC) and is available at: https://ww...
#! /usr/bin/env python2 """ [2017-07-08 SAT 11:58] Petonic Modified from: https://www.alfredforum.com/topic/1756-eject-specific-drivesvolumesmounts/ Look for the tinyupload link there. Goal is to modify the behavior to look at all disks, not the ones in /Volumes. """ import os import re import glob from Feedback im...
#!/usr/bin/env python3 from copy import deepcopy import cartopy.crs as ccrs import datetime as dt import logging from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import matplotlib matplotlib.use('AGG') import matplotlib.axes as maxes import matplotlib.cm as cm import matplotl...
#!/usr/bin/env python # coding: utf-8 import os import sys import random import math import re import time import numpy as np import tensorflow as tf import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import cv2 as cv from skimage import io # Root directory of the project ROOT_DIR ...
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ myDict = {} myDict['I'] = 1 myDict['V'] = 5 myDict['X'] = 10 myDict['L'] = 50 myDict['C'] = 100 myDict['D'] = 500 myDict['M'] = 1000 ...
a = input("First no :") b = input("Second no:") c = int(a)+int(b) print ("sum is :",c)
from rest_framework import viewsets from rest_framework import mixins import json from numpy.random import rand from rest_framework import views, status from rest_framework.response import Response from django.views.generic import CreateView, ListView from django.urls import reverse_lazy from .models import Post, Hom...
"""DAgger for imitation learning""" from typing import Tuple, NoReturn import gym import torch import numpy as np from sacred import SETTINGS from sacred.utils import apply_backspaces_and_linefeeds import tqdm from common.buffers import ImitationBuffer from envs.env import Env from policies.actors import Pi from poli...
from nltk.tokenize.regexp import RegexpTokenizer import random DATA_PATH = "./data/" tokenizer = RegexpTokenizer(r'\w+') def load_data_from_file(file_name): super_dic = {} file_path = DATA_PATH + file_name + ".txt" f = open(file_path, "r") lines_count = sum(1 for line in open(file_path)) print(...
""" This is for testing profiling of the pypesto.Objective. """ import numpy as np import pypesto import unittest import test.test_objective as test_objective import warnings import copy class ProfilerTest(unittest.TestCase): def runTest(self): objective = test_objective.rosen_for_sensi(max_sensi_order=...
from django.conf.urls import url from baserow.contrib.database.views.registries import view_type_registry from .views import ( ViewsView, ViewView, ViewFiltersView, ViewFilterView, ViewSortingsView, ViewSortView ) app_name = 'baserow.contrib.database.api.views' urlpatterns = view_type_registry.api_urls + [...
from unittest import TestCase from api import Deck class TestDeck(TestCase): def test_generate(self): d = Deck.generate(0) stock = d.get_card_states().count("S") self.assertEqual(stock,10,"The value should be 10") player1 = d.get_card_states().count("P1H") self.assertEqua...