content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import os
import hy
from models import test
#from pyswip.prolog import Prolog
class Answers:
def __init__(self):
self._list_answer = []
self._limit_questions = 0
self._root = ''
# Files,NOTA !!!!! cambiar las rutas de los archivos, si es necesario .... !!!... |
from django.apps import AppConfig
class SdConfig(AppConfig):
name = 'sd'
|
# SPDX-FileCopyrightText: 2021 Computer Assisted Medical Interventions Group, DKFZ
# SPDX-FileCopyrightText: 2021 Janek Groehl
# SPDX-License-Identifier: MIT
from simpa import Tags
import simpa as sp
import numpy as np
import matplotlib.pyplot as plt
from utils.save_directory import get_save_path
import os
os.environ[... |
# Refer Readme file for setup instruction
from selenium import webdriver
from selenium.webdriver.support.select import Select
import pandas as pd
auton = webdriver.ChromeOptions()
auton.add_argument("headless")
############### Change chromedriver.exe path here #############
driver = webdriver.Chrome(opti... |
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com>
# License: BSD 3 clause
def run_playground_decision():
import os
import onelearn
filename = onelearn.__file__.replace(
"/onelearn/__init__.py", "/examples/playground_classification.py"
)
os.system("streamlit run %s" % filename)
de... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('calculator/index.html')
context =... |
import streamlit as st
import altair as alt
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import pandasdmx as pdmx
import pandas_datareader.data as web
# Plot settings
plt.style.use(
"https://github.com/aeturrell/coding-for-economists/raw/main/plot_style.txt"
)
# Page set... |
# Copyright 2020-2022 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
#
# Unless required by applicable law or agree... |
"stats template"
# For computation of weighted variance, see
# http://en.wikipedia.org/wiki/Weighted_sample_variance#Weighted_sample_variance
from copy import deepcopy
import bottlechest as bn
__all__ = ["stats"]
FLOAT_DTYPES = [x for x in bn.dtypes if 'float' in x]
INT_DTYPES = [x for x in bn.dtypes if 'int' in x]... |
from __future__ import absolute_import
from jhu_primitives.monomial.monomial import MonomialPrimitive
__all__ = ['MonomialPrimitive', "AdjacencySpectralEmbedding"]
from .ase import AdjacencySpectralEmbedding
"""
from .lse import LaplacianSpectralEmbedding
from .dimselect import DimensionSelection
from .gclust import... |
from django.urls import path
from nameservice import views
#
urlpatterns = [
path("", views.Home.as_view(), name="home"),
path("create", views.SkyNSCreateView.as_view(), name="nsCreate"),
path("list", views.SkyNSListView.as_view(), name="nsList"),
path("update/<int:pk>", views.SkyNSUpdateView.as_view()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pandas import DataFrame
from Octopus.dataframe.core.abstractDataFrame import AbstractDataFrame
__all__ = ['PandasDataFrame']
class PandasDataFrame(AbstractDataFrame):
def __init__(self, data=None, index=None, columns=None, dtype=None,
copy=Fal... |
# -*- coding: utf-8 -*-
"""
This module is experimental and subject to change.
"""
from simmate.database.base_data_types import (
table_column,
Structure,
Forces,
Thermodynamics,
Calculation,
)
from typing import List
from pymatgen.io.vasp.outputs import Vasprun
class DynamicsRun(Structure, Ca... |
"""Functions for training and running group classification."""
import math
import os
import time
import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.utils.extmath import softmax
from scipy.special import expit
from sklearn.metrics import f1_score, fbeta_score, classif... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! 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... |
# Copyright 2021 The FedLearner 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 applica... |
def minion_game(string):
# your code goes here
kevin = 0
stuart = 0
length = len(string)
for i in range(length):
if string[i] in "AEIOU":
kevin += (length-i)
else:
stuart += (length-i)
if kevin > stuart:
print("Kevin", kevin)
elif kevin < stuar... |
from django import test
from django.urls import reverse
from django.test import client
from indicators.models import LevelTierTemplate
from factories.workflow_models import (
RFProgramFactory,
TolaUserFactory,
grant_program_access,
)
class TestSaveCustomTemplateView(test.TestCase):
@classmethod
d... |
from django.db import models
from apps.usuario.models import EstadoModel
from django.urls import reverse
from apps.usuario.templatetags.utils import PROCESO
class Ubicacion(EstadoModel):
latitudubicacion = models.CharField(max_length=30, blank=True, null=True,
verbose_... |
"""
===================================
Merging two instances in the design
===================================
This example demonstrate how to merge two instance in the design to create a new
merged definition
.. hdl-diagram:: ../../../examples/basic/_initial_design_merge.v
:type: netlistsvg
:align: center
... |
from typing import TYPE_CHECKING, Callable, Tuple
from .exceptions import get_status_code_error
from .specs.openapi.checks import content_type_conformance, response_schema_conformance, status_code_conformance
from .utils import GenericResponse
if TYPE_CHECKING:
from .models import Case
def not_a_server_error(re... |
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
class AppTestNumSupport(BaseNumpyAppTest):
def test_zeros(self):
from numpy import zeros
a = zeros(3)
assert len(a) == 3
assert a[0] == a[1] == a[2] == 0
def test_empty(self):
from numpy import empty
... |
import pytest
from pyloan.loan import Loan
testdata = [
(
"loan1",
"r0",
[
{
"annualRate": 2.115,
"insurance": 1.2,
"periods": 120,
"principal": 10000,
"startDate": "2010-09-15",
}
... |
"""Tests for sqlalchemy orm session."""
from unittest import TestCase
import astroid
from sqlalchemy.orm.scoping import scoped_session
class PluginTest(TestCase):
"""PluginTest test case."""
def setUp(self):
"""Init setup."""
self.node = astroid.MANAGER.ast_from_class(
scoped_ses... |
import requests
from .objects import TYPES_TO_COLLECTION_NAMES, Container, Sample
from .utils import url_path_join
class Client:
"""
This connects to an amostra HTTP server for sample management.
For each collection, we have a traitlets-based object to represent
documents from that collection and au... |
import unittest
import os
import json
import datetime
from processes.insert_movies import Main
from processes.postgres import Postgres
try:
DB_SERVER = os.environ['DB_SERVER']
DB_PORT = os.environ['DB_PORT']
DB_DATABASE = os.environ['DB_DATABASE']
DB_USER = os.environ['DB_USER']
DB_PASSWORD = os.e... |
import asyncio
class OnHold:
def __init__(self, bot, gif, mention):
self.bot = bot
self.gif = gif
self.mention = mention
async def create_hold(self):
await self.gif.add_reaction("🔁")
def check(react, user):
return (user == self.mention
... |
input = """
% Most of this example is due to Francesco Scarcello.
% It shows the necessity to check whether a partial interpretation, which is
% about to be totalised, still contains "not false" (or "must be true")
% atoms. If it does, this represents an inconsistency.
a :- not g, not h.
b :- not g, not h.
c :- not g... |
##ppg
import numpy as np
import torch
import torch.nn as nn
from torch import distributions as td
from torch.optim import Adam
from torch.utils.data import Dataset, DataLoader
from collections import deque, namedtuple
import gym
import time
import scipy.signal
from core_lstm import *
from env import *
from spinup.util... |
import json
import pickle as pkl
import pathlib
#paths = ["/srv/local1/estengel/blocks_data_for_release/good_robot_sim/stacks/",
# "/srv/local1/estengel/blocks_data_for_release/good_robot_sim/rows/",
# "/srv/local1/estengel/blocks_data_for_release/good_robot_real/rows/1/",
# "/srv/local1/est... |
import logging
import random
import re
import tempfile
import uuid
from enum import Enum, auto
from importlib import import_module
from pathlib import Path
from typing import List, Callable, Any, Dict, Union, Optional
import attr
from configuror import Config
from fake_useragent import UserAgent, FakeUserAgentError
f... |
import urllib
tickers = ['YHOO', 'AVP', 'BIIB', 'BP', 'CL', 'CVX',
'DNA', 'EXPE', 'GOOG', 'PG', 'XOM', 'AMGN']
shortest = 300
prices = {}
dates = None
for t in tickers:
url = 'http://ichart.finance.yahoo.com/table.csv?' + \
's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996' % t + \
'&ign... |
import gym
import robo_gym
import math
import numpy as np
import pytest
ur_models = [pytest.param('ur3', marks=pytest.mark.nightly), \
pytest.param('ur3e', marks=pytest.mark.nightly), \
pytest.param('ur5', marks=pytest.mark.commit), \
pytest.param('ur5e', marks=pytest.mark.night... |
import sys
import os
import copy
from yaku.context \
import \
get_bld, get_cfg
from yaku.scheduler \
import \
run_tasks
def configure(ctx):
ctx.use_tools(["ctasks"])
def build(ctx):
# To *override* options, you should clone a builder + replacing
# options there
builder = ctx.b... |
import ConfigSpace as CS
import multiprocessing as mp
from .bayesopt.autogluon.searcher_factory import gp_fifo_searcher_factory, gp_multifidelity_searcher_factory, gp_fifo_searcher_defaults, gp_multifidelity_searcher_defaults
from .searcher import BaseSearcher
from ..utils.default_arguments import check_and_merge_defa... |
# 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
# 每行中的整数从左到右按升序排列。
# 每行的第一个整数大于前一行的最后一个整数。
# 示例 1:
# 输入:matrix = [[1,3,5,7],
# [10,11,16,20],
# [23,30,34,50]], target = 3
# 输出:true
# 示例 2:
# 输入:matrix = [[1,3,5,7],
# [10,11,16,20],
# [23,30,34,50]], targe... |
import logging
from pandas import Categorical
from core import prepare
from core import draw
BENCH_NAME = 'parsec_var_input'
EXP_NAME = BENCH_NAME
BENCHMARK_ORDER = (
"blackscholes",
"streamcluster",
"swaptions",
"canneal",
)
OVERFLOWS = {
"perf": (
(-1.87, 8.25, "~12",),
),
"mem... |
##
## Artificial Intelligence Final Project
##
## ####
##
## James Clisham
##
##
## Ant Colony Optimization implemented in a variety of ways to solve the graph coloring problem.
## Primary focus on manipulating the various different components of ACO and pitting them against
## each other in trials.
##
import os, sy... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import *
def deconv(out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Create a transposed-convolutional layer with optional batch normalization """
# create a sequence of transpose + optional batch norm layers... |
'''
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finish... |
#Feature engineering functions for Bike sharing project
import pandas as pd
import numpy as np
import math
from sklearn.preprocessing import MinMaxScaler, StandardScaler, FunctionTransformer
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.... |
import discord, datetime, parsing as tool, pytz, asyncio
from discord.ext import tasks, commands
def status():
print(f"now running {asyncio.get_running_loop()}")
class MyCog(commands.Cog):
def __init__(self):
self.channels = dict()
self.info = [dict() for _ in range(4)]
self.prev_date ... |
import logging
import requests
from .api_endpoints import API_ENDPOINTS
LOG = logging.getLogger(__name__)
# TODO: create nice docs
def requests_url(request, url):
access_token = request.session.get("access_token")
authorization_header = {"Authorization": "Bearer {}".format(access_token)}
resp = request... |
import os
from datetime import datetime
from app import db
from app import filesystem
from app.utils import get_random_string
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
dropbox_id = db.Column(db.Integer)
name = db.Column(db.String(80))
email = db.Col... |
from typing import List, Optional
from fastapi import Path, Depends, APIRouter
from starlette.responses import Response, RedirectResponse
from sqlalchemy.ext.asyncio import AsyncSession
from pol import sa, res, wiki
from pol.res import ErrorDetail, not_found_exception
from pol.utils import subject_images
from pol.con... |
import argparse
import copy
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
from cogdl.data import Dataset
from cogdl.models.supervised_model import (
SupervisedHomogeneousNodeClassificationModel,
)
from cogdl.trainers.supervised_model_trainer import SupervisedHomogeneousNode... |
# Time complexity: O(len(n)!)
# Approach: Sort the initial array and run the nextPermute algorithm till it is completely converted in non-increasing.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
n = len(nums)
if n==1:
return [nums]
... |
import re
from dataclasses import dataclass
from datetime import timedelta
from typing import Optional
HHHMMSS = r"(?P<hours>[0-9]+([,.][0-9]+)?)"
def parse_isoformatDuration(durationString: str) -> timedelta:
pass
def parse_HHMMSS(
duration_string: str, hm_separator: str = ":", ms_separator: str = ":"
) -... |
import asyncio
from aiohttp import web
from aiohttp_basicauth_middleware import basic_auth_middleware
def hello(request):
return web.Response(text='Hello')
def get_app(loop, auth_dict=None, strategy=lambda x: x):
if auth_dict is None:
auth_dict = {}
app = web.Application(loop=loop)
app.rou... |
#!/usr/bin/env python
"""
TODO: Modify unittest doc.
"""
from __future__ import division
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Virtual Lab"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__date__ = "4/10/14"
import unittest2 as unittest
impo... |
class IContentHost:
""" This interface is implemented by layouts which host System.Windows.ContentElement. """
def GetRectangles(self,child):
"""
GetRectangles(self: IContentHost,child: ContentElement) -> ReadOnlyCollection[Rect]
Returns a collection of bounding rectangles for a child element.
... |
import logging
logger = logging.getLogger('Handler')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
class Handler:
def does_supports(self,... |
from .knowledge import *
class HebbianKnowledge(Knowledge):
def __init__(self):
pass
def store_all_knowledge(self):
pass
|
"""Function to work on a population in dynamic mode."""
import sys
from redis import StrictRedis
import cloudpickle as pickle
from time import sleep, time
import logging
from ..util import any_particle_preliminary
from .cmd import (
N_EVAL, N_ACC, N_REQ, N_FAIL, ALL_ACCEPTED, N_WORKER, N_LOOKAHEAD_EVAL,
SSA, ... |
consumer_key = 'YOUR CONSUMER KEY'
consumer_secret = 'YOUR CONSUMER SECRET'
access_token = 'YOUR ACCESS TOKEN'
access_token_secret = 'YOUR ACCESS TOKEN SECRET'
|
#################################
# --- Day 23: Safe Cracking --- #
#################################
import AOCUtils
from math import factorial
class VM:
def __init__(self, program):
self.program = program[:]
self.pc = 0
self.registers = {"a": 0, "b": 0, "c": 0, "d": 0}
self.togg... |
'''
Created on Sep 9, 2011
@author: Ankhazam & Piotr & OpenCV team
'''
from algorithms.AlgorithmBase import AlgorithmBase
import classification.SURFFlannMatcher as SFM
import classification.TrainedObject as TO
import image.ImageDescriptionReader as IDR
import image.ImageDescriptionWriter as IDW
import common.Utils as ... |
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
import logging
import warnings
class NetworkAddresses(APIClassTemplate):
"""
The NetworkAddresses Object in the FMC.
"""
URL_SUFFIX = "/object/networkaddresses"
def __init__(self, fmc, **kwargs):
super().__init__(fmc, **kwa... |
from dynet import *
train_sentence = [('the','D'), ('dog','N'), ('walks','V')]
i2w = dict(enumerate(set(w for w,t in train_sentence)))
w2i = dict((w,i) for i,w in i2w.items())
t2i = dict((t,i) for i,t in enumerate(set(t for w,t in train_sentence)))
num_words = len(w2i)
num_tags = len(t2i)
model = Model()
sgd = Simpl... |
#encoding=utf-8
from whoosh.analysis import RegexAnalyzer,LowercaseFilter,StopFilter,StemFilter
from whoosh.analysis import Tokenizer,Token
from whoosh.lang.porter import stem
import jieba
import re
STOP_WORDS = frozenset(('a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'can',
'for', 'from',... |
from Microsoft.Scripting.Silverlight import DynamicApplication
engine = DynamicApplication.Current.Runtime.GetEngine('IronRuby')
scope = engine.CreateScope()
def execute(str, type = 'file'):
global engine, scope
return engine.Execute(str, scope)
|
#!/usr/bin/env python3
"""
****************************************************************************
Copyright (C) 2018 Datirium. LLC.
All rights reserved.
Contact: Datirium, LLC (datirium@datirium.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in complia... |
"""The official genshin map
Gets data from the official genshin map such as categories, points and similar.
"""
import json
from typing import Any, Dict, List
from urllib.parse import urljoin
from .caching import permanent_cache
from .genshinstats import fetch_endpoint
OS_MAP_URL = "https://api-os-takumi-static.hoyo... |
# 終了コマンド実装
import sys
# discordのAPI
import discord
# Google検索
from googlesearch import search
# discordに接続
client = discord.Client()
# モード切替
ModeFlag = 0
# 起動時のメッセージ
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('-----... |
from dcsolve import dcsolver
word_pairs = [('line', 'cake'), ('kit', 'zap'),('ask', 'why'), ('face',
'pill'), ('oozy', 'aqua'), ('icky', 'poop'), ('quiz',
'kook')]
costs = ['steps', 'scrabble', 'frequency']
for w1, w2 in word_pairs:
for cost in costs:
dcsolver(w1, w2, cost)
... |
'''
Created on Mar 30, 2021
@author: jpannizzo
'''
from core.utilities.experiment_utils import hcl_mix, update_dispense_action_set, update_lsr_edoc
from core.models.view_tables import Edocument
import numpy as np
def liquid_solid_extraction(data, q3,experiment_copy_uuid,exp_name, exp_template):
'''
# logic fo... |
import torch
from torch import nn
from ..builder import RECOGNIZERS
from .base import BaseRecognizer
@RECOGNIZERS.register_module()
class Recognizer2D(BaseRecognizer):
"""2D recognizer model framework."""
def forward_train(self, imgs, labels, **kwargs):
"""Defines the computation performed at every ... |
# -*- coding: utf-8 -*-
from __future__ import annotations
__all__ = ["Transform", "Linear", "Cholesky", "Subspace"]
from functools import partial
from typing import Any, Callable, Sequence, Union
import jax.numpy as jnp
from jax.scipy import linalg
from .kernels import Kernel
from .types import JAXArray
class T... |
import os
import argparse
import tarfile
import re
import json
import logging
from collections import defaultdict
from bgcore import tsv
from bgcore.re import ReContext
from fannsdb.utils import RatedProgress
__CB = {
"A" : "T",
"T" : "A",
"G" : "C",
"C" : "G"
}
def complementary_sequence(seq):
return "".join(... |
import pytest
from alchemtest.gmx import load_benzene
from alchemlyb.parsing import gmx
from alchemlyb.convergence import forward_backward_convergence
@pytest.fixture()
def gmx_benzene():
dataset = load_benzene()
return [gmx.extract_dHdl(dhdl, T=300) for dhdl in dataset['data']['Coulomb']], \
[gmx.... |
import pytest
def test_createTask():
pass |
from django.db import migrations, models
import django.db.models.deletion
import morphodict.lexicon.models
class Migration(migrations.Migration):
replaces = [
("lexicon", "0001_initial"),
("lexicon", "0002_alter_wordform_linguist_info"),
("lexicon", "0003_remove_unused_dictionarysource_fi... |
import logging
from peewee import *
from ..db import db, BarbotModel, ModelError, addModel
from ..bus import bus
_logger = logging.getLogger('Models.Glass')
class Glass(BarbotModel):
type = CharField()
size = IntegerField()
units = CharField()
description = TextField(null = True)
@staticm... |
"""Tests for Erisoglu 2011 algorithm"""
import unittest
import numpy as np
import sklearn.datasets as skdatasets
from initialisations.erisoglu import Erisoglu
# pylint: disable=R0201
class ErisogluTestSuite(unittest.TestCase):
"""Tests for Erisoglu 2011 algorithm"""
def setUp(self):
self._e = Eri... |
from .coil_agent import CoILAgent
|
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post , personal_details , details
def projects(request):
all_post = Post.objects.all()
return render(request,'pro.html',{'posts':all_post})
# Create your views here.
|
#! /usr/bin/env python
from os import makedirs
from os.path import join, dirname, exists
from sys import path
path.insert(0, '.')
from time import time
from argparse import ArgumentParser
parser = ArgumentParser(description="Train MNIST generator with DP-WGAN-GP")
parser.add_argument('--capacity', type=int, default=6... |
# Copyright 2018 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 to in writing, ... |
from __future__ import annotations
import dataclasses
import functools
import operator
import random
import timeit
from typing import Optional
import fire
from pipe import select
from tqdm import tqdm
COSTS = {
"A": 1,
"B": 10,
"C": 100,
"D": 1000,
}
def check_move_from_home(source: Node, target: N... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
This module implements fMRI Design Matrix creation.
Design matrices are represented by Pandas DataFrames
Computations of the different parts of the design matrix are confined
to the make_first_level_de... |
import discord
from discord.ext import commands
from main import *
import asyncio
import datetime
import cogs.utils.slash as slash
class Bot(commands.Cog):
"""Commands and events related to the bot."""
def __init__(self, bot):
self.bot = bot
display_emoji = "👾"
@commands.Cog.listener... |
"""Utility functions for tf-based Reinforcement learning algorithms."""
import numpy as np
from metarl.misc import tensor_utils as np_tensor_utils
from metarl.tf.misc import tensor_utils
def paths_to_tensors(paths, max_path_length, baseline_predictions, discount,
gae_lambda):
"""Return proce... |
"""Some utilities that may help.
"""
from .iterables import (flatten, group, take, subsets,
variations, numbered_symbols, cartes, capture, dict_merge,
postorder_traversal, preorder_traversal, interactive_traversal,
prefixes, postfixes, sift, topological_sort)
from .lambdify import lambdify
from .source imp... |
#!/usr/bin/env python
# coding: utf-8
# DO NOT EDIT
# Autogenerated from the notebook copula.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
# # Copula - Multivariate joint distribution
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sc... |
# Generated by Django 2.1.2 on 2018-10-29 18:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0014_auto_20171227_1530'),
]
operations = [
migrations.AddField(
model_name='profile',
name='api_key_id'... |
'''
Version: 0419
Utility Maximizing Learning Plan Simulations
# Brute force, Greedy, ILP Solver
# Support Additive cost function
'''
import networkx as nx
import numpy as np
import random,copy, time, json, os, argparse, csv, datetime
from gurobipy import *
from UMLP_solver import *
import utils
# INPUT desc... |
import os
import threading
from castero import helpers
from castero.config import Config
from castero.datafile import DataFile
class Episode:
"""The Episode class.
This class represents a single episode from a podcast feed.
"""
def __init__(self, feed, title=None, description=None, link=None,
... |
#
# Copyright 2018-2022 Elyra 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 or agreed to in writ... |
"""insert new fields in user table
Revision ID: 948eefcc2e28
Revises: a9c4c250382f
Create Date: 2020-02-05 11:00:03.687495
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '948eefcc2e28'
down_revision = 'a9c4c250382f'
branch_labels = None
depends_on = None
def... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from nncf.common.graph.patterns import GraphPattern
from nncf.common.graph.patterns import HWFusedPatterns
from nncf.torch.graph.pattern_operations import ARITHMETIC_OPERATIONS
from nncf.torch.graph.pattern_operations import ATOMIC_ACTIVATIONS_OPERATIONS
from nncf.torch.graph.pattern_operations import BATCH_NORMALIZATI... |
# coding: utf-8
class Node:
def __init__(self, *_, key=None, value=None, p=None, s=None):
self.key = key
self.value = value
self.precursor = p
self.successor = s
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.cap... |
import datetime
import json
import logging
import os
import random
from collections import defaultdict
from dict_recursive_update import recursive_update
from tuw_nlp.common.utils import ensure_dir
from tuw_nlp.grammar.alto import get_rule_string, run_alto
from tuw_nlp.grammar.utils import get_dummy_input
class IRT... |
from .VerificationModel import VerificationModel |
# Generated by Django 3.2.4 on 2021-06-13 07:11
from django.db import migrations, models
import user.models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
... |
from bs4 import BeautifulSoup
class Kata:
def __init__(self, soup):
self.soup = soup
@property
def source_codes(self):
codes = self.soup.find_all('div', {'class': 'markdown'})
return [''.join(code.findAll(text=True)) for code in codes]
@property
def languages(self):
... |
from typing import List
from unicodedata import normalize
from tokenizer.base import BaseTokenizer
class JamoTokenizer(BaseTokenizer):
def __init__(self):
pass
def tokenize(self, text: str) -> List[str]:
return list("▁".join([normalize("NFKD", token) for token in text.strip().split(" ")]))
... |
_base_ = [
'../_base_/models/setr_convfuse_pup.py',
'../_base_/datasets/ade20k.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_240k.py'
]
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
backbone=dict(img_size=512,align_corners=False, pos_embed_interp=True,drop_rate=0.... |
'''Aggregates item files in data/libs/items'''
import json
import os
import re
def pack_folder(folder="./dat"):
'''
Takes a string containing a relative path to a folder containing multiple .json files,
combines them into one array, returns that array. Uses the containing folder to apply
a category to ... |
import numpy as np
import matplotlib,pylab as plt
import scipy.io
matfile_name = "C:\\dataset\\mpii_human_pose_v1_u12_2\\mpii_human_pose_v1_u12_1.mat"
matfile = scipy.io.loadmat(matfile_name, struct_as_record=False)
print(matfile.get('RELEASE')[0, 0].get('annolist'))
# print(matfile['re'])
# # print(type(matfi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.