content
stringlengths
5
1.05M
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2011, Eucalyptus Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # withou...
from django.apps import AppConfig class PagesConfig(AppConfig): name = 'estatisticas_facebook.pages' verbose_name = "Pages"
import os, sys, pdb import csv import json import random import math import torch import numpy as np from torch import nn from torch.optim.optimizer import Optimizer from typing import Dict, Union, List, Tuple from transformers import BertTokenizer, RobertaTokenizer, AlbertTokenizer from abcd.components.tools import R...
import util def solve(input_path): f = open(input_path) sorted_numbers = sorted(int(s) for s in f) prev = 0 # The initial adapter is rated 0 diff_histogram = [0] * 4 for n in sorted_numbers: diff_histogram[n - prev] += 1 prev = n diff_histogram[3] += 1 # Special case of the device itself print(...
#program to match the string with pattern using modular algorithm def reGexMatch(s,p): #lookuptable #initalize the 2D array dp with None/null of size length of pattern+1 & string+1. #inorder to tranverse the 2D array two iterative variables required i & j. dp=[[None for j in range(len(s)+1)] for i in ra...
""" Task 3 Write an application that allows you to calculate the cost of a trip. Implement a function called hotel_cost that takes one argument, nights, as input. The hotel costs £70 per night – so return a suitable value. Implement a function called plane_ticket_cost that accepts a string, city, and a float...
from django.core.management.base import BaseCommand, CommandError from django_celery_beat.models import CrontabSchedule, PeriodicTask class Command(BaseCommand): help = 'Setup and Reset the Celery Analytics Tasks schedules' def add_arguments(self, parser): parser.add_argument('--inline', action='store...
from threading import current_thread from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional import queue class Payload(BaseModel): id: str img: str type: int misc: Optional[list] = [] app = FastAPI() origins = [ ...
# Generated by Django 2.1.7 on 2019-09-10 12:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0008_team_teammember'), ] operations = [ migrations.AlterModelOptions( name='teammember', options={'orderi...
""" Module for computing meridional transport of quantities """ import numpy as np import xarray as xr # xarray compatibility try: from xarray.core.pycompat import OrderedDict except ImportError: from collections import OrderedDict from .get_basin import get_basin_mask from .ecco_utils import get_llc_grid fro...
from __future__ import absolute_import, unicode_literals from drf_toolbox.renderers.json import JSONEncoder from functools import wraps import json @wraps(json.dump) def dump(value, fp, *args, **kwargs): kwargs.setdefault('cls', JSONEncoder) return json.dump(value, fp, *args, **kwargs) @wraps(json.dumps) de...
import asyncio from os.path import abspath, dirname, join from types import FunctionType from aiohttp import web from .helpers import (generate_doc_from_each_end_point, load_doc_from_yaml_file, swagger_path) try: import ujson as json except ImportError: import json async def _swagger_...
import rlkit.misc.hyperparameter as hyp from multiworld.envs.mujoco.cameras import sawyer_pusher_camera_upright from multiworld.envs.mujoco.sawyer_xyz.sawyer_push_and_reach_env_reset_full_goal import SawyerPushAndReachXYEnv from rlkit.data_management.obs_dict_replay_buffer import \ ObsDictRelabelingBuffer from rlki...
# FIXME: remove uTensorOpEqualityDelegate import after we have generic op_eq_deleate from utensor_cgen.backend.utensor.code_generator.legacy._operators import \ uTensorOpEqualityDelegate from utensor_cgen.matcher import uTensorGraphMatcher def test_id_match(patrn_ugraph): matcher = uTensorGraphMatcher(patrn_u...
import unittest from api.app import create_app, db from api.models import User from config import Config class TestConfig(Config): SERVER_NAME = 'localhost:5000' TESTING = True DISABLE_AUTH = True ALCHEMICAL_DATABASE_URL = 'sqlite://' class TestConfigWithAuth(TestConfig): DISABLE_AUTH = False ...
from .commands import startapp_command
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class PolylineDecorator(Component): """A PolylineDecorator component. Polyline is a wrapper of Polyline in react-leaflet. It takes similar properties to its react-leaflet counterpart. Keyword arguments: ...
import pygame pygame.init() # Initalise pygame # Create the screen screen = pygame.display.set_mode((800 , 600)) # Title and screen pygame.display.set_caption('Space Invaders (FreePlay)') icon = pygame.image.load(r'assets\heros\6.png') pygame.display.set_icon(icon) # Player playerImg = pygame.image.load(r'assets\he...
from NENV import * import ipaddress class NodeBase(Node): pass class _Collapse_Addresses_Internal_Node(NodeBase): """ Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Netw...
import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.projections import register_projection from matplotlib.projections.polar import PolarAxes from matplotlib.spines import Spine import numpy as np class RadarAxes(PolarAxes): name = 'radar' def __init__( ...
from __future__ import annotations import numpy as np import PIL.Image as Image from arlunio import ast def builtin_x(backend: NumpyBackend, tree: ast.Node): ratio = backend.width / backend.height scale = tree.attributes["scale"] stretch = tree.attributes["stretch"] x0 = tree.attributes["x0"] ...
from operator import attrgetter # Sorry, I was too lazy to actually make this any better. It should be in a 'helper file' in larger projects def are_values_unique(x): """ Asserts values are unique in a list """ seen = set() return not any(i in seen or seen.add(i) for i in x) class Vertex: """ Repres...
import numpy as np class SemiGradDP: def __init__(self, env, pi, b, w_dim, alpha, gamma, vhat, nab_vhat): self.env = env self.pi = pi self.b = b self.a = alpha self.g = gamma self.w_dim = w_dim self.vhat = vhat self.nab_vhat = nab_vhat self.n_st = len(self.env.states) self.re...
# from .pkg_1 import A # a=A() # print(a.t1('xxyy')) from p1.p1_1 import B from p2.p2_2 import t3 b=B() print(b.t2('xxyy')) t3()
#!/usr/bin/env python # Copyright (C) 2018 Hatching B.V. # This file is licensed under the MIT License, see also LICENSE. import gevent.monkey gevent.monkey.patch_all() import argparse import base58 import hashlib import json import logging import os import random import requests import time import uuid from gevent....
""" * Assignment: Protocol Iterator Range * Complexity: medium * Lines of code: 14 lines * Time: 8 min English: 1. Modify class `Range` to write own implementation of a built-in `range(start, stop, step)` function 2. Assume, that user will never give only one argument; it will always be either tw...
"""Git repository management inside Ginpar for themes and quickstart. """ import os import subprocess from ginpar.utils.echo import success, echo, error from ginpar.utils.files import try_remove def clone_repo(repo, path): """Clone the contents of a repository in a custom path Parameters ---------- ...
#list comprehension makes code even shorter but harder to read num_square = [value**3 for value in range(1,10)] print(num_square) #the medium way of doing it num_square = [] for value in range(1,11): num_square.append(value**3) print(num_square) print(min(num_square)) print(max(num_square)) print(sum(num_square))...
"""Unit tests for idlelib.configSectionNameDialog""" import unittest from idlelib.idle_test.mock_tk import Var, Mbox from idlelib import configSectionNameDialog as name_dialog_module name_dialog = name_dialog_module.GetCfgSectionNameDialog class Dummy_name_dialog: # Mock for testing the following methods ...
import numpy as np import mysql.connector as mysqlq import matplotlib.pyplot as pl from prettytable import PrettyTable as pt import math as ma import random as rd g=mysqlq.connect(host="localhost",user="root",passwd="newdelhi96") cur=g.cursor() cur.execute("show databases") dbs=cur.fetchall() value=0 for...
from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app def create(self, contact): wd = self.app.wd self.app.open_main_page() # Add new contact wd.find_element_by_link_text("add new").click() self.fill_contact_f...
##Patterns: E0711 ##Err: E0711 raise NotImplemented raise NotImplementedError
tabuada = 1 while tabuada <= 10: n = 1 print ("Tabuada %d" %tabuada) while n <= 10: print ("%d x %d = %d" %(tabuada, n, tabuada * n)) n = n + 1 tabuada = tabuada + 1
from bank_app import create_app def test_config(): assert not create_app().testing assert create_app({'TESTING': True}).testing def test_hello(client): """ Tests if application is returning a valid response to /hello url :param client: pytest fixture named client, located in conftest.py :re...
#!/usr/bin/env python3.7 # coding: utf-8 import os for data in ["mnist","fashionmnist","kmnist"]: for net in ["shufflenet","resnet","mobilenet"]: os.system(f"python3.7 ./main.py {data} {net}")
""" syntax: | install <パッケージ> install update:<パッケージ> install file:<ファイル> syntax_description: | パッケージ: インストールするパッケージ。update:をつけると、パッケージが更新されます。 ファイル: エクスポートしたファイルのパス。 --- パッケージをインストールします。 """ import os import re import requests import shlex import shutil import subprocess import sys import yaml import zipfile ...
#!/usr/bin/python #coding:utf-8 import logging import mylog import mydecision_tree as ml import sys import os import numpy as np logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def str2num(s): a = ['unacc', 'acc', 'good', 'vgood','vhigh', 'high', 'med', 'low', 'small', 'med', 'big', '2...
from ulauncher.api.client.Extension import Extension from ulauncher.api.shared.event import KeywordQueryEvent from .KeywordQueryEventListener import KeywordQueryEventListener class WiktionaryExtension(Extension): def __init__(self): super(WiktionaryExtension, self).__init__() self.subscribe(Keywor...
import pytest from hashtable import HashTable from left_join import left_join def test_exists(): assert HashTable assert left_join @pytest.fixture() def left_table_synonyms(): ht = HashTable() ht.add('fond', 'enamored') ht.add('wrath', 'anger') ht.add('diligent', 'employed') ht.add('outfit...
import functools def cases(test_cases): def decorator(f): @functools.wraps(f) def wrapper(*args): for case_idx, case in enumerate(test_cases, 1): new_args = args + (case if isinstance(case, tuple) else (case,)) try: f(*new_args) ...
import torch import torch.nn as nn from torch.cuda.amp import custom_fwd class BatchReNorm2D(nn.Module): """Batch Re-Normalization Parameters num_features – C from an expected input of size (N, C, H, W) eps – a value added to the denominator for numerical stability. Default: 1e-5 momen...
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import print_function import os from os.path import join as pjoin, dirname, abspath, commonprefix import sys from sys import version_info import re import subprocess if sys.version_info[0] < 3: import __builtin__ as builtins else: import bui...
from getratings.models.ratings import Ratings class NA_Rakan_Sup_Aatrox(Ratings): pass class NA_Rakan_Sup_Ahri(Ratings): pass class NA_Rakan_Sup_Akali(Ratings): pass class NA_Rakan_Sup_Alistar(Ratings): pass class NA_Rakan_Sup_Amumu(Ratings): pass class NA_Rakan_Sup_Anivia(Ratings): pass ...
import turtle # Ask user for input here. # Now create a graphics window. t = turtle.Pen() # Put the rest of your code can go here # Prevent the graphics window from diappearing too # quickly to see it. stopper = raw_input("Hit <enter> to quit.") # Now remove the graphics window before exiting. turtle.bye()
import json from stix_shifter_utils.modules.base.stix_transmission.base_sync_connector import BaseSyncConnector from .api_client import APIClient from stix_shifter_utils.utils.error_response import ErrorResponder from stix_shifter_utils.utils import logger class Connector(BaseSyncConnector): init_error = None ...
import logging from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from soato import models logger = logging.getLogger(__name__) class CountryCase(TestCase): fixtures = ["soato/fixtures/soato.json"] def setUp(self): self.query = models.Co...
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression from typing import NoReturn import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pio.templates.default = "simple_white" def load_data(filename: st...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Cosmo Tech. # Licensed under the MIT license. import os import sys import argparse from tools_common.git import ( check_head, check_branch_is_main, check_tag_exists, commit_all_changes, create_tag, create_branch, get_top_level_...
import os import shutil import _thread import copy from typing import List from pathlib import Path import concurrent.futures from .images.resize import resize_image from .videos.optimize import video_file_FFMPEG from tempfile import NamedTemporaryFile from fastapi import UploadFile,HTTPException,status from .storage.g...
# puzzle easy // https://www.codingame.com/ide/puzzle/logic-gates # needed values in_val = [] out_val = [] dic = {} end = [] # game values n = int(input()) m = int(input()) _ = int # needed functions def do_it(sol, letter, n): if n == False: sol = sol.replace('0','_').replace('1','-') end.append(...
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # 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...
# MIT 6.034 Lab 3: Games from game_api import ConnectFourBoard from toytree import * # ------- PART I: CONNECTFOUR BOARDS # Note: The tester uses some of these boards, so if you change them, tests may # break. However, feel free to copy these to make new boards of your own. BOARD_UHOH = ConnectFourBoard(board_array...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import os import pytest import hcl from hooks.pre_gen_project import TerragruntGenerator, StackParser from pprint import pprint TEMPLATES_DIR = os.path.join(os.path.dirname(__file__), 'te...
from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def energy_band_alignment_diagram(energies, materials, limit=8., width=1., cols=['#74356C','#efce19'], textsize=22, arrowhead=0...
# coding=utf-8 from .templatelite import *
#!/usr/bin/env python import argparse import hatchet as ht if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-m", "--metric", default="sum", type=str, help="Metric to display" ) args, argv = parser.parse_known_args() files = argv[:] if not files: ...
from django.contrib import admin from .models import Student, Subject, Paper admin.site.register(Student) admin.site.register(Subject) admin.site.register(Paper)
# -*- encoding: utf-8 -*- """ MIT License Copyright (C) PAPAYA EU Project 2021 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use...
import json import copy from sdklib.compat import str, unquote_plus from sdklib import http from sdklib.http import HttpRequestContext from sdklib.http.renderers import get_renderer from sdklib.http.response import Response as HttpResponse from sdklib.util.urls import urlsplit class Cookie(object): def __init__(...
''' Created on Jan 17, 2018 @author: khoi.ngo Implementing test case IssuerCreateClaimDefs with 2 DIDs and the same schema. ''' import json from indy import anoncreds, did, ledger import pytest from test_scripts.functional_tests.anoncreds.anoncreds_test_base \ import AnoncredsTestBase from utilities import utils...
import tornado from tornado.options import define import argparse from tellet import application import logging as log import sys log.basicConfig(level=log.DEBUG, format='%(asctime)s - %(levelname)-8s - %(message)s', datefmt='%d/%m/%Y %Hh%Mm%Ss') console = log.StreamHandler(sys.stderr)...
""" Module to access the Root endpoints """ # pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods from ...models import PushNotification from ..base import ApiBaseClass class RootApi(ApiBaseClass): """ """ def acknowledge_notification( self, ) -> PushNot...
import uuid from typing import Dict, Optional, Tuple, Union from confluent_kafka import Consumer, Producer from streaming_data_types.epics_connection_info_ep00 import serialise_ep00 from streaming_data_types.fbschemas.epics_connection_info_ep00.EventType import ( EventType as ConnectionStatusEventType, ) from for...
#!/usr/bin/env python # # Copyright 2015 BMC Software, 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 applicab...
import sys sys.path.append(".") from main import * from shield import Shield from Environment import Environment from DDPG import * import argparse def cooling (learning_method, number_of_rollouts, simulation_steps, learning_eposides, critic_structure, actor_structure, train_dir,\ nn_test=False, retrain_s...
import os import sys from setuptools import setup, find_packages if sys.version_info < (3, 6): sys.exit("Sorry, Python >= 3.6 is required for kobert-transformers.") with open("requirements.txt") as f: require_packages = [line.strip() for line in f] with open(os.path.join("kobert_transformers", "version.txt...
''' Created on 28 de abr de 2020 @author: leonardo Content: Power Up de aumentar a distancia limite do raio da bomba. ''' from componentes.jogo.powerups import PowerUp import math class DistanciaBomba(PowerUp): def poder(self, personagem): personagem.distancia_bomba+=0.5 personagem.servidor.em...
import json import sys from typing import Dict, Any import time import datetime import hashlib from mysql.connector import connect, Error as MysqlError from mysql.connector.connection import MySQLConnection from mysql.connector.cursor import CursorBase import paho.mqtt.client as mqtt from dotenv import dotenv_values f...
# --------------------------------------------------------------------- # Eltex.LTP.get_lldp_neighbors # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Py...
from time import sleep a = 0 #total de pessoas com idade maior de 18 b = 0 #total de homens cadastrados c = 0 #total de mulheres com idade menor de 20 while True: print('=-' * 20) print('CADASTRE UMA PESSOA') print('=-' * 20) idade = int(input('IDADE: ')) sexo = ' ' while sexo not in 'MF': ...
import io import unittest from unittest.mock import patch from kattis import k_unionfind ############################################################################### class SampleInput(unittest.TestCase): '''Problem statement sample inputs and outputs''' def test_sample_input_1(self): '''Run and as...
""" this is a regional comment lec2 """ #print('hello world') # this is a line comment #print('123') #print(type(123)) #print(type('hedgehog')) #print(type(123.)) #print("hello world") #print('hello world') #print("Abby's hedgehog") #print(2**4) #(2**4) #my_int = 123 #print("123") #my_int = 312 #print ("321"...
"""" Copyright © Krypton 2022 - https://github.com/kkrypt0nn (https://krypton.ninja) Description: This is a template to create your own discord bot in python. Version: 4.1 """ import json import os import platform import random import sys import disnake from disnake import ApplicationCommandInteraction from disnake....
# pylint: disable=missing-docstring, line-too-long, invalid-name, arguments-differ, no-member import math import torch from e3nn import o3, rs class Kernel(torch.nn.Module): def __init__(self, Rs_in, Rs_out, RadialModel, get_l_filters=o3.selection_rule, sh=o3.spherical_harmonics_xyz, normalization='norm'): ...
import numpy as np from luvina.utils.data_utils import get_file file_name = "wikipedia_common_misspellings.txt" origin = ('https://raw.githubusercontent.com/rameshjesswani/Semantic-Textual' + '-Similarity/master/nlp_basics/nltk/dataset/dataset_misspelled.txt') def load_data(): """ i. Data set is d...
k = int(input()) count1 = 0 count2 = 0 for i in range(k): if i % 2 != 0: count1 += 1 else: count2 += 1 print(count1 * count2)
#!/usr/bin/env python # coding: utf-8 from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def obtain_heart(bg_path, image_path): """将给定图像扣为心形""" heart_im = cv2.imread(bg_path) heart_im = cv2.cvtColor(heart_im, cv2.COLOR_BGR2GRAY) im = cv2.imread(image_path...
import unittest import os from testutils import getZserioApi, getApiDir class DbWithRelocationTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "sql_databases.zs").db_with_relocation cls._europeDbFileName = os.path.join(getApiDir(os.path.dirname(__file...
from flask import redirect, render_template, Blueprint, url_for, request, flash # Internal Reminder from to_do_app import db from to_do_app.models import Reminder, Tag from to_do_app.reminder.forms import ReminderForm reminder = Blueprint('reminder', __name__) # Create @reminder.route('/write', methods=['GET', 'POST...
import smtplib from email_config import * import traceback from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email_templates.email_templates_eng import * from email_templates.email_templates_chn import * def send_email(receivers, email_type, msg_content, language='english'): ...
from utils import yaml import logging as log from pprint import pprint import os from pathlib import Path class ConfigMapper(object): def __init__(self, filename, configDir): """ Initlizes the config off a tree of yamls. "/" holds global config "<subsystem>" holds configs for subsys...
import os from collections import defaultdict import plotly.graph_objects as go def plot_trace(results_trace: dict, plot_file: str): utilities = defaultdict(lambda: defaultdict( lambda: {"x": [], "y": [], "bids": []})) accept = {"x": [], "y": [], "bids": []} for index, action in enumerate(results...
"""GCN using DGL nn package References: - Semi-Supervised Classification with Graph Convolutional Networks - Paper: https://arxiv.org/abs/1609.02907 - Code: https://github.com/tkipf/gcn """ from math import trunc from typing_extensions import IntVar import torch import torch.nn as nn from dgl.nn.pytorch import GraphCo...
__author__ = 'Jacco Kulman' import unittest import time class TimeTestCase(unittest.TestCase): def setup(self): self.t = time.time() def test_data_attributes(self): time.altzone time.daylight time.timezone time.tzname def test_clock(self): time.clo...
#! /usr/bin/env python # coding: utf var = "string1" print(var) # Выведет "string1" var = 1 print(var) # Выведет "1" var += 2 print(var) # Выведет "3" # число π PI = 3.14 print(PI) # => 3.14 # случайное изменение значения PI='MAIN' print(PI) type(object) # <class 'type'> type(type) # <class 'type'> type(int) # ...
""" Advent of Code 2020 Day 18 This is... I don't know what this is... """ from typing import Callable def get_data(fname: str) -> list: """ Read the data file into dicts. """ with open(fname) as f: return [line.strip() for line in f] def simple(expr: str) -> int: """Evaluate a simple e...
from typing import List class Solution: def minOperations(self, logs: List[str]) -> int: count: int = 0 for word_command in logs: if word_command == "./": count += 0 elif word_command == "../": if count == 0: count = 0 ...
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import logging as _logging from coremltools.converters.mil.backend.nn.passes.nn_passes import nn_bac...
from django.apps import apps from django.core.exceptions import ViewDoesNotExist from django.http import Http404 from django.urls import ResolverMatch from django.urls.exceptions import Resolver404 try: from django.urls import re_path # Django 2.x from django.urls import URLPattern from django....
""" Moving inlist TCGA images to a folder for upload Created on 1/22/2019 @author: RH """ import os import shutil import csv # Get all images in the root directory def image_ids_in(root_dir, ignore=['.DS_Store', 'dict.csv']): ids = [] for id in os.listdir(root_dir): if id in ignore: pri...
workers = 20 timeout = 120 worker_class = 'gevent' bind = '0.0.0.0:8092'
from setuptools import setup setup( name="fastuot", distname="", version='0.1.0', description="Fast computation of unbalanced OT problems", author='Thibault Sejourne', author_email='thibault.sejourne@ens.fr', url='https://github.com/thibsej/fast_uot', packages=['fastuot'], install_r...
import requests import json import os def main(): response = requests.get( 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US') data = json.loads(response.text) url_to_image = data["images"][0]['url'] file_path = download_file("http://bing.com" + url_to_image) os.system...
import torch import numpy as np from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader class DiabetesDataset(Dataset): def __init__(self): xy = np.loadtxt('./data/diabetes.csv', delimiter=',', dtype=np.float) self.len = xy.shape[0] self.x_data = torch...
import random import spacy import spacy.gold from itertools import chain from tqdm.auto import tqdm class Dataset: """ Wraps Functionality: - Wraps dataset - Keeps all dataset labels, they are set up on dataset initialization - Keeps __len__ - Allows dataset iteration """ pos ...
#!/usr/bin/env python3 import sys from pyArango.connection import * import os import requests from operator import itemgetter from datetime import datetime ARUSR = os.environ['ARUSR'] ARPWD = os.environ['ARPWD'] ARSVR = os.environ['ARSVR'] ARDBN = os.environ['ARDBN'] connection = Connection(arangoURL='http://'+ARSVR+...
import datetime import time import urllib.request import re import threading from pymongo import MongoClient """основной хост для парсинга""" HOST = 'https://referat.ru' """максимально количество потоков""" MAX_THREADS = 5 START_TIME = time.time() client = MongoClient('mongodb://localhost/alumico') db = client.refe...
# Generated by Django 2.1 on 2019-11-09 06:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Announcement', fields=[ ...
from django import template register = template.Library() # This custom Django template filter is to make it easy to take the dots out of # hostnames when rendering the dashboard, which is necessary in order to be # able to use them as class names for the isotope filtering. @register.filter() def stripchar(value, ar...
from database import models import logging from safrs import jsonapi_attr from sqlalchemy.orm import relationship, remote, foreign """ If you wish to drive models from the database schema, you can use this file to customize your schema (add relationships, derived attributes), and preserve customizations over iteration...