content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- from .primaries import MSDS_DISPLAY_PRIMARIES_CRT __all__ = [ 'MSDS_DISPLAY_PRIMARIES_CRT', ]
from googleads import ad_manager from dfp.client import get_client def create_line_items(line_items): """ Creates line items in DFP. Args: line_items (arr): an array of objects, each a line item configuration Returns: an array: an array of created line item IDs """ dfp_client = get_client() l...
from server import app, DBSession from flask import Blueprint, request, session, send_file, make_response, jsonify from utils import captcha, cmparePswd, invalid, invalidate from flask_jwt_extended import jwt_required, jwt_optional, create_access_token, get_jwt_identity, get_raw_jwt import io from model import Storehou...
import unittest from probrnn import graphs import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' params = { "LEARNING_RATE": 0.0001, "N_HIDDEN": 64, "N_BINS": 2, "BATCH_SIZE": 30, "WINDOW_LENGTH": 23, } class TestNADE(unittest.TestCase): def test_initialize(self): gr...
S = input() T = input() a = [] for i in range(len(S)): if S[i] != T[i]: a.append(i) if len(a) == 0 or (len(a) == 2 and a[0] + 1 == a[1] and S[a[0]] == T[a[1]] and S[a[1]] == T[a[0]]): print('Yes') else: print('No')
# -*- coding: utf-8 -*- import attr import typing from attrs_mate import AttrsClass # --- SQS @attr.s class SQSRecord(AttrsClass): messageId: str = attr.ib() receiptHandle: str = attr.ib() body: str = attr.ib() attributes: dict = attr.ib() messageAttributes: dict = attr.ib() md5OfBody: str = ...
import socket # socket 만들기 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("192.168.99.1", 9999)) #ip 주소, port 번호(사용중인 번호만 아니면 모든 int 가능) # message 작성 test_msg = "abcd" # 판단 1 sock.send(test_msg.encode()) # message 받기 data_size = 1024 data = sock.recv(data_size) # print(data.decode()) # 연결 종...
from flask import request from flask_restful import Resource from werkzeug.exceptions import NotFound from bookshelf.books.model import Book from bookshelf.books.repository import BookRepository class BookResource(Resource): def __init__(self, book_repository: BookRepository): self._book_repository = bo...
import graphene from ..core.fields import FilterInputConnectionField from ..translations.mutations import PageTranslate from .bulk_mutations import PageBulkDelete, PageBulkPublish, PageTypeBulkDelete from .filters import PageFilterInput, PageTypeFilterInput from .mutations.attributes import ( PageAttributeAssign, ...
import difflib as dl def generateHTMLDiff(srcname, mutantname): with open("../src/" + srcname) as f: original_file = f.read() with open("../mutants/" + mutantname + "/src/" + srcname.replace(".cpp", "_" + mutantname + ".cpp")) as f: mutated_file = f.read() hd = dl.HtmlDiff() diffs = ...
import json import numpy as np import cv2 import io from django.core import serializers from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect, get_object_or_404 import base64 import os import dlib from imutils import face_utils import math from .detection import * from .geome...
#%% import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import phd.viz colors, palette = phd.viz.phd_style() # Load in the datasets data_a = pd.read_csv('../../data/ch6_induction_si/figS1_partA.csv') data_b = pd.read_csv('../../data/ch6_induction_si/figs1_partB.csv') data_O2 = ...
# faça um programa que leia a LARGURA (larg) e a ALTURA (altu) dde uma parede em metros, calcule sua área [ LARGURA x ALTURA] {area), # e a quantidade necessárioa de tinta, sabendo que um galao de tinta pinta dois metros. larg = float(input("qual a largura da parede? ")) altu = float(input("qual a altura da parede? ")...
import pytest from ephios.core.signup import SignupStats @pytest.mark.django_db def test_signup_stats_addition(django_app): a = SignupStats(4, 2, 3, None) b = SignupStats(5, 2, 3, 5) c = SignupStats(3, 2, None, 2) assert a + b == SignupStats(9, 4, 6, None) assert b + c == SignupStats(8, 4, 3, 7) ...
from typing import Dict, List from icolos.core.containers.perturbation_map import Edge from icolos.core.workflow_steps.pmx.base import StepPMXBase from pydantic import BaseModel from icolos.core.workflow_steps.step import _LE from icolos.utils.enums.program_parameters import StepPMXEnum from icolos.utils.execute_extern...
import sys from django.db import connections from django.db.utils import ConnectionDoesNotExist, IntegrityError from django.core.management.base import BaseCommand from django_comments.models import Comment from django_comments_xtd.models import XtdComment __all__ = ['Command'] class Command(BaseCommand): he...
# -*- coding:utf-8 -*- import logging from logging import Formatter from colorlog import ColoredFormatter from mongolog.handlers import MongoHandler logger = None def get_logger(app, name, log_level=None, log_file=None, mongo_host=None, mo...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import (QTimer, QCoreApplication, Qt, qsrand, QTime, QRectF, QPointF, pyqtSignal, QSize, QPoint, QSettings, QVariant) from PyQt5.QtGui import (QBrush, QColor, QPainter, QPixmap, QFont, QPalette) from PyQt5.QtWidgets import (QWidget, QApplication, QGraphicsSce...
#!/usr/bin/python import sys, os, string ROOT = os.path.dirname(os.path.abspath(__file__)) #sys.path.insert(0, os.path.join(ROOT, '..')) #sys.path.append(ROOT+"/lib") import markup, datetime def get_classify_stats(ocf,cf,ck,out_dir,outf,outfo,taxa_level): contigs_by_class = { } origContigsByClass = { } o...
from django.db import models from datetime import datetime from django.core.validators import MaxValueValidator, MinValueValidator from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Project(models.Model): name = models.CharField(max_length=100) added = models.Date...
# -*- coding: utf-8 -*- """ Author : Jacques Flores Created : October 17th,2019 About: Script for creating datasets in Dataverse. An Empty JSON file with Dataverse structure is imported and converted into a JSON dict Metadata is imported from an excel file into a pandas dataframe and written into the ...
from bluesky.plans import count ct = count([]) #ct.flyers = [topoff_inj, diag6_flyer5, diag6_flyer1] ct.flyers = [diag6_flyer5, diag6_flyer1] uid, = RE(ct) assert len(db[uid].descriptors) == 3 # one event stream per flyer
# datanectar data science chains should live here
## Usando o Native Baise vamos fazer um programa que preveja a probabilidade de acidentes de veiculos import pandas as pd ## Essa é a biblioteca que vamos usar para manipulação de dados from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import ...
from flask import Flask app = Flask(__name__) app.config.from_object('config.config') from app import views
import logging from terra import api from terra import msg from terra import utils from terra.account import Account __all__ = ["api", "msg", "utils", "Account"] __version__ = "0.8.0" logging.getLogger(__name__).setLevel(logging.INFO)
from enum import Enum class NodeState(Enum): ROOT = 1 CHILD = 2 TERMINAL = 3 class Node(): def __init__(self, segment, pos, #remaining, nb_remaining, level=0, duplicates=1, parent=None, ...
import sys sys.path.append('../') import pandas as pd from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import normalize, MinMaxScaler import re from math import sqrt, pow import os import joblib from keras.layers import TimeDistributed from sklearn....
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str use a array to track the vowels position, then do the swap at these positions as string is immutable, convert string to list, then join back """ vowels = 'aeiouAEIOU' vowe...
def left_ind(P): M = 0 for i in range(1,len(P)): if P[i][0] < P[M][0]: M = i elif P[i][0] == P[M][0]: if P[i][1] > P[M][1]: M = i return M def pos(p, q, r): val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) if val == 0: return 0 elif val > 0: return 1 else: ret...
# Generated by Django 3.1.3 on 2020-12-10 06:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0021_auto_20201209_1613'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ...
import ujson as json class SimpleJsonRpc(object): def __init__(self, data): if (isinstance(data, str)): data = json.loads(data) self._id = data['id'] self._method = data['method'] self._params = data.get('params', dict()) @property def method(self): ret...
import numpy as np from .state_space_model import StateSpaceModel class Kalman(StateSpaceModel): """ A class to perform kalman filtering or smoothing """ def __init__( self, transition, observation, process_noise, measurement_noise, init_state_mean, ...
# Adapted from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py import gzip import numpy as np import tensorflow as tf # added this to see tf.compat.v1.disable_eager_execution() #from tensorflow.contrib.learn.python.learn.datasets import base from influence.d...
#presently we support manual adding: import json with open("listening_files.json","r") as f: list_file = json.load(f) total_lessons = list_file['total_lessons'] with open("listening_files.json","w+") as f: #list_file['Lesson_2'] = ["Flag Football","01:16","Medium"] list_file['Lesson_1'] = ["How to look inside Br...
from tortoise import fields, models from subject.models import Subject as Subject class Trial(models.Model): id = fields.IntField(pk=True) subject_id: fields.ForeignKeyRelation[Subject] = fields.ForeignKeyField("models.Subject", related_name="trials") created_at = fields.DatetimeField(auto_now=False, au...
import os import numpy as np import pandas as pd def save(df, fname): dname = os.path.dirname(fname) if not os.path.isdir(dname): os.makedirs(dname) records = df.to_records(index=False) records.dtype.names = [str(i) for i in records.dtype.names] np.save(fname, records)
import time from pageobjects.environments import DiscardChangesPopup from pageobjects.nodes import Nodes, RolesPanel, DeleteNodePopup from tests import preconditions from tests.base import BaseTestCase class TestDiscardEnvironmentChanges(BaseTestCase): @classmethod def setUpClass(cls): BaseTestCase.s...
from os import chdir as cd from os.path import abspath, dirname, join, pardir, realpath import platform from subprocess import CalledProcessError, check_output as execute from sys import exit # Introduce ourselves. print('Initializing pwman...') # Get root directory of this repository. REPO_DIR = abspath(join(dirname...
import tfidf def transfer(word, no): li = [] for i in range(no): li.append(word) return li sport = [] f = open("sport.txt", "r") for x in f: g = x.split(" ") li = transfer(g[0], int(g[1][:-1])) sport.extend(li) print(sport) food = [] f = open("food.txt", "r") for x in f: g...
import gym import numpy as np """Data generation for the case of a single block pick and place in Fetch Env""" actions = [] observations = [] infos = [] vectorize_observation = False def main(): env = gym.make('FetchDrawTriangle-v1') numItr = 100 initStateSpace = "random" env.reset() print("Rese...
import compiler_gym # imports the CompilerGym environments import gym from transformers import ( DataCollatorWithPadding, PreTrainedTokenizerFast, RobertaForSequenceClassification, RobertaTokenizerFast, TrainingArguments, ) from datasets import load_dataset from o4.data import prepare_cost_datase...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import numpy as np import os n_sigma=2. def return_stuff(Mach_number,mode='Fiducial'): if Mach_number==2 : dir='Mach2' Mid_point=106 fit_low_bnd=Mid_point#-n_sigma*sigma_s/0.05+30 #0.05 is spacing in x fit_up_bnd=176#Mid_point+n_sigma*sigma_s/0.05+15 if Mach_number==3 : ...
from bokeh.models import HoverTool, ColumnDataSource from bokeh.plotting import figure, output_file, show import bokeh.layouts import datetime import numpy as np import DownloadData def yw2datetime(yw): if isinstance(yw, (list, np.ndarray)): return [yw2datetime(i) for i in yw] yw_int = [int(i) for i i...
#!/usr/bin/python # import from modules directory import sys import os.path sys.path.append(os.path.abspath(os.path.dirname(__file__)) + "/modules") import threading import time import copy import DynamicObjectV2 Obj = DynamicObjectV2.Class MsgLock = threading.RLock() IOLock = threading.RLock() version = open('REA...
from django.urls import path from . import views urlpatterns = [ path('change_pass',views.change_pass,name='change_pass'), path('dash', views.dashboard, name='dash'), path('login',views.login,name ='login'), path('logout',views.logout,name='logout'), path('prescriptions',views.prescriptions,name='prescriptions'), ...
#Basic Operations in a Binary Search Tree(BST) in Python #Creating a class to create a node class Node: def __init__(self, key): self.key = key self.left = None self.right = None # Inserting a node def insert(node, key): # Return a new node if the tree is empty if node is None: ...
import csv import re FUNDING_YEAR_RE = re.compile(r'(Funding Year) (\d+)') FISCAL_YEAR_RE = re.compile(r'(FY) (\d+)') CONGRESS_NUMBER = re.compile(r'\((\d+)TH\)') def format_csv(source_doc, csv_file='senate_data.csv', cleaned_file='senate_data_cleaned.csv'): unclean_data_reader = csv.reader(open(csv_file, 'r')) ...
"""A test class for the ZipfMandelbrot distribution helper """ import unittest from PiCN.Simulations.MobilitySimulations.Helper.ConsumerDistributionHelper import ZipfMandelbrotDistribution class TestConsumerZipfMandelbrotDistributionHelper(unittest.TestCase): """test class for testing the behavior and results of...
import logging from asyncio import get_event_loop LOGGER = logging.getLogger('pulsar.events') class AbortEvent(Exception): """Use this exception to abort events""" pass class Event: __slots__ = ('name', '_onetime', '_handlers', '_waiter', '_self') def __init__(self, name, o, onetime): sel...
# -*- coding: utf-8 -*- """ 【简介】 加载QSS文件 """ import sys from PyQt5.QtWidgets import QMainWindow , QApplication, QVBoxLayout , QPushButton from CommonHelper import CommonHelper class MainWindow(QMainWindow): def __init__(self,parent=None): super(MainWindow,self).__init__(parent) self.resize(477, 258) ...
import matplotlib from matplotlib import pyplot as plt matplotlib.use('Agg') from matplotlib.collections import BrokenBarHCollection from itertools import cycle from collections import defaultdict import pandas import numpy as np asms = snakemake.params["asms"] print(asms) alist = snakemake.input["asms"] print(alist)...
import pymysql import os class Connection: mode = os.environ.get('ENVIRONMENT') def __init__(self): self.connection = pymysql.connect(host=os.environ.get('DB_HOST'), port=int(os.environ.get('DB_PORT')), user=os.environ....
# coding : utf8 from Node import * class Syntaxe(Node): def setCrochet(self): structure = '{noeud}[{var}]' if self.type == "VAR": self.crochet = strcture.format( noeud=self.type, val=self.value, var=self.leaf ) else: self.crochet = strcture.format( noeud=self.type, val=self.value, ...
import json import typer from pathlib import Path from spacy.tokens import Span, DocBin, Doc from spacy.vocab import Vocab from wasabi import Printer msg = Printer() SYMM_LABELS = ["Binds"] MAP_LABELS = { "Pos-Reg": "Regulates", "Neg-Reg": "Regulates", "Reg": "Regulates", "No-rel": "Regulates", ...
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2017 Anler Hernández ...
import shopify from kss.customer import Customer shipping = { 'group_0': tuple(sorted([ 'Asendia', 'Åland Islands', 'Albania', 'Andorra', 'Armenia', 'Austria', 'Belarus', 'Belgium', 'Bosnia & Herzegovina', 'Bouvet Island', 'Bulgaria', 'Croatia', 'Cyprus', 'Czechia', 'Denmark', 'Estonia', '...
from database.conn import execute def insertDVDB(lpn,vtype,video_ref,time): if vtype=='Car': vtype='Car / Taxi' elif vtype=='Motorcycle': vtype='Motorcycle / Scooter' print(vtype) inserted=execute("INSERT INTO vehicles values('"+lpn+"','"+vtype+"','"+video_ref+"',"+str(time)+")") re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020-2021 OpenDR European Project # # 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...
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, 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 ...
from goopylib.objects.GraphicsObject import GraphicsObject from goopylib.styles import * from goopylib.constants import _root, ALL_CHARACTERS, ALIGN_OPTIONS from tkinter import StringVar as tkStringVar from tkinter import Entry as tkEntry from tkinter import Frame as tkFrame from tkinter import END as tkEND class Ent...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2018-09-26 10:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('forum', '0013_board_locked'), ] operations = [ migrations.AddField( ...
from ISO19115Creator import gdalreader from ISO19115Creator import functions import gdal import osr import sridentify rootDir = r'D:\test\dem.tif' test = gdalreader.GdalData(rootDir) print(test.getBoundingBox()) test = gdal.Open(rootDir) print(test.GetProjection()) print(test) print(test.getBoundingBox()) spatialRe...
#!/usr/bin/env python3 from hashlib import md5 secret = "bgvyzdsv" i = 1 done = [False, False] while True: key = secret + str(i) if not done[0] and md5(key.encode()).hexdigest()[0:5] == "00000": print("Part 1: " + str(i)) done[0] = True if not done[1] and md5(key.encode()).hexdigest()[0:6...
"""Manager utility implementations of grading managers.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods # Number of methods are defined in specification # pylint: disable=too-many-ancestors # Inheritance defined in specification from ..osid...
import numpy as np import pytest from sklearn.utils._weight_vector import ( WeightVector32, WeightVector64, ) @pytest.mark.parametrize( "dtype, WeightVector", [ (np.float32, WeightVector32), (np.float64, WeightVector64), ], ) def test_type_invariance(dtype, WeightVector): """Ch...
import argparse args = argparse.ArgumentParser(description='MolGAN model for molecular.') args.add_argument('--device', default=1) args.add_argument("--mode", default="train", help='mode for model, default is true') args.add_argument('--learning_rate', default=1e-3, help='learning rate') args.add_argument('--batch_dim...
"""Parse arguments in python-style NOTE: 1. You should acknownledge the usage of argparse module of python first. 2. Shell var '$' symbol can be used in 'default', if the order of arguments are right. e.g. in the following example: in the default of --output, '$input' will be replaced by <inpu...
import json import glob, os import dash import datetime import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.express as px from django_plotly_dash import DjangoDash from django.apps import apps import plotly.graph_objects as go from Lab_Misc.Ge...
import csv import main diseaseCode=[] diseaseName=[] symptomCode=[] symptomName=[] tempCode=[] tempName=[] # including diseaseName and diseaseCode to the database disease,occurances,symptoms = main.funct() for i in range(len(disease)): diseaseCode.append(disease[i][5:13]) diseaseName.append(disease[i][14:]) for j ...
from repos.models import Repo from rest_framework import viewsets, permissions from .serializers import RepoSerializer # Repo Viewset class RepoViewSet(viewsets.ModelViewSet): queryset = Repo.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = RepoSerializer
# python_version >= '3.7' #: Okay async with expr as Γ: pass #: N816 async with expr as γΓ: pass #: Okay async for Γ1 in iterator: pass #: N816 async for γΓ1 in iterator: pass
from minitf import kernel as K class Tensor(object): def __init__(self, value): # TODO: cast to numpy array self._value = get_val(value) def __neg__(self): return K.negative(self) def __add__(self, other): return K.add(self, other) def __sub__(self, other): return K.subtract(self, o...
import enum import inspect import pycspr def _has_class(mod, cls): """Asserts that a container exposes a class. """ _has_member(mod, cls) assert inspect.isclass(getattr(mod, cls)), '{} is not a class'.format(cls) def _has_constant(mod, constant): """Asserts that a container exposes a constant...
#Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua media. #nota1=float(input('digite sua primeira nota: ')) #nota2=float(input('digite sua segunda nota: ')) #media=(nota1+nota2)/2 #print('sua media é igual a: {}'.format(media)) #opcional: desenvolba um programa que leia as quatro notas de...
def closest_row(dataframe, column, value): """ Function which takes a dataframe and returns the row that is closest to the specified value of the specified column. :param dataframe: Dataframe object :param column: String which matches to a column in the dataframe in which you would like to find the cl...
#! /usr/bin/env python3 # std imports import logging import typing as T import pathlib import functools import glob import fnmatch from pyscooper.tex_utils import sanitize_tex from pyscooper import deps from pyscooper.cli_utils import debug, info, warning, error class TOCFile: def __init__(self, filepath: path...
#dependencies import pandas as pd import os import requests from bs4 import BeautifulSoup as bs from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager def scrape_all(): executable_path = {"executable_path": "/Users/nallu/.wdm/drivers/chromedriver/win32/92.0.4515.107/chromedrive...
"""Create a new book template.""" import sys import os import os.path as op import shutil as sh from ruamel.yaml import YAML import tempfile from pathlib import Path from .utils import print_message_box, _error from .toc import build_toc from . import __version__ TEMPLATE_PATH = op.join(op.dirname(__file__), 'book_te...
from setuptools import setup setup( name='capture', version='0.0.2', description='tool for visualization', #author='shiannn', #author_email='foomail@foo.com', packages=['visualizer'], #same as name #install_requires=['wheel', 'bar', 'greek'], #external packages as dependencies )
""" Test boto3 client ovverride """ import unittest import os import sys from moto import mock_ssm import boto3 import placebo from . import TestBase from ssm_cache import SSMParameter, SSMParameterGroup class TestClientOverride(unittest.TestCase): """ Refreshable.set_ssm_client tests """ PARAM_VALUE = "abc1...
import pymysql import psycopg2 import logging from airflow.hooks.base_hook import BaseHook from dateutil.parser import parse from datetime import timezone, timedelta from exceptions import ErrorMySqlParameters, ErrorStartDateParser, ErrorPostgreParameters from full_incidents.replication_otrs_to_dwh.postgresql.upload ...
from pycoingecko import CoinGeckoAPI import csv import time import sys filter_file = 'filter.csv' if len(sys.argv) > 1: filter_file = sys.argv[1] cg = CoinGeckoAPI() filter = [] with open(filter_file, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) for entry in csv_reader.fieldnames: ...
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import dataent no_cache = True def get_context(context): token = dataent.local.form_dict.token doc = dataent.get_doc(dataent.local.form_dict.doctype, dataent.local.form_dict.docname...
# -*- coding: utf-8 -*- # # Copyright 2016 Google Inc. 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 requ...
import numpy as np def Sigmoid(z): #return 1.0/(1.0 + np.exp(-z)) return np.exp(-np.logaddexp(0,-z)) def SigmoidGradient(z): return Sigmoid(z)*(1.0-Sigmoid(z)); def InverseSigmoid(a): z = - np.log(1/np.float64(a) - 1) return z def InverseSigmoidGradient(a): z = InverseSigmoid(a) return SigmoidGradient(z)
# Copyright 2021 MosaicML. All Rights Reserved. from composer.algorithms.curriculum_learning.curriculum_learning import CurriculumLearning as CurriculumLearning from composer.algorithms.curriculum_learning.curriculum_learning import \ CurriculumLearningHparams as CurriculumLearningHparams _name = 'Curriculum Lear...
from time import sleep for c in range(10, 0, -1): print(c) sleep(1) print('FELIZ ANO NOVO!!') print('\U0001F386') print('\U0001F386') print('\U0001F386')
# split into train and test set from os import listdir from xml.etree import ElementTree from numpy import zeros from numpy import asarray from mrcnn.utils import Dataset # class that defines and loads the kangaroo dataset from constant import classes from util.xml_parser import extract_boxes class ImageDataset(Data...
import string import math # Positional inverted index, postings in form: # <document id, term frequency in document, term positions in document> class InvertedIndex: num_documents = 0 inverted_index = {} # Cached indices of positions last returned by prev/next calls for a term. prev_cache = {} next_cache = {} ...
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- from .base import hash, hash_next from typing import List, Set, Mapping from task.util import utils from tqdm import tqdm import gzip def make_hash(emb_path): vocab = {} max_tok_len = 0 max_word = None with gzip.open(emb_path, mode='rt', compresslevel=6)...
from opportunities.api.serializers.opportunity_serializers import ( OpportunitySerializer, ) from opportunities.models import Opportunity from rest_framework import generics from rest_framework.permissions import IsAuthenticated class OpportunityAPIView(generics.ListAPIView): ''' ♻API endpoint that allows...
'''------------------------------------------------------------------------------- Tool Name: CreateInflowFileFromHighResECMWFRunoff Source Name: CreateInflowFileFromHighResECMWFRunoff.py Version: ArcGIS 10.3 Author: Alan Snow (adapted from CreateInflowFileFromECMWFRunoff.py) Description: Creates R...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
"""Add snapshot model Revision ID: 2191c871434 Revises: 19168fe64c41 Create Date: 2014-07-17 17:21:42.915797 """ # revision identifiers, used by Alembic. revision = '2191c871434' down_revision = '19168fe64c41' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'snapshot', ...
""" Title: Projet IPT - Diffraction DI Description: Ce programme permet de calculer la valeur (couleur) de chaque point de l'écran. On utlise une méthode de somme discrète. """ #pylint: disable=invalid-name #=== Importation des modules === import numpy as np def diffraction(Fente): """...
""" Provide implementation of the atomic swap interfaces. """ class AtomicSwapInterface: """ Implements atomic swap interface. """ def get_public_key(self): """ Get the public key of atomic swap. """ pass def get(self, swap_id): """ Get information...
import pandas as pd import pytest from pandas.testing import assert_frame_equal from powersimdata.design.generation.clean_capacity_scaling import ( add_new_capacities_collaborative, add_new_capacities_independent, add_shortfall_to_targets, ) def test_independent_new_capacity(): area_names = ["Pacific...
from ml.getDemand import current_day def retrain_model(array_input): day = current_day() import numpy as np import pandas as pd import pickle df = pd.read_csv("ml/inventory.csv") df = pd.DataFrame(df) df = df[['ProductID', 'PriceReg', 'DayoftheYear', 'ItemCount']] # array_input = [[1,...