text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- """ Created on Sun Mar 21 11:55:27 2021 Snow-Hydrology Repo for Evaluation, Analysis, and Decision-making Dashboard (shread_dash.py) Database Initialization This is part of dashboard loading database and other data into memory. The data for the database relies on a series of retrieval scripts ...
9,018
3,831
import cloudscraper import json from bs4 import BeautifulSoup from dotenv import load_dotenv import os scraper = cloudscraper.create_scraper() load_dotenv('lang_code') language = os.getenv("lang_code") def simsimi(question): ''' Function to make the HTTP request to the Simsimi API already with the message typed b...
730
253
import sys def write(): print('Creating new text file') name = 'test.txt' # Name of text file coerced with +.txt try: file = open(name,'a') # Trying to create a new file or open one file.close() except: print('Something went wrong! Can\'t tell what?') ...
357
122
from rest_framework import serializers from .models import Bid, Item, User class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name', 'product_code', 'description', 'sold') class UserSerializer(serializers.ModelSerializer): class Meta: model =...
523
147
import requests from a01.auth import A01Auth session = requests.Session() # pylint: disable=invalid-name session.auth = A01Auth()
133
46
""" Construct, train neural-SDE models and simulate trajectories from the learnt models. """ # Copyright 2021 Sheng Wang. # Affiliation: Mathematical Institute, University of Oxford # Email: sheng.wang@maths.ox.ac.uk import numpy as np import os import pandas as pd import tensorflow as tf import tensorflow_probabilit...
27,025
9,166
import random pedra = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' papel = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' tesoura = ''' _______ ---' ____)____ ______) __________) (____) -...
2,641
1,157
def even_square_sum(list): even = [x * x for x in list if x % 2 == 0] return sum(even) print(even_square_sum([1, 2, 3, 4, 5]))
133
63
import json file_content = [] with open('vaccine_data.ndjson', 'r', encoding="UTF-8") as f: for row in f.readlines(): rowJson = json.loads(row.replace('\n','')) if rowJson['prefecture'] == '08': del rowJson['prefecture'] if not rowJson['medical_worker']: del rowJson['medical_worker'] ...
1,304
488
from .system import System from logcat import LogCat class Widget(System): def __init__(self): super().__init__() self.on("cmd_render", self._render) # widget.py
187
61
import smtplib user = input('Enter your gmail ') password = input('Enter your password ') receiver = input('Enter the receiver ') msg = input('Enter the message ') #num = input('Enter the number of emails you want to send ') #x = 0 #x = int() #num = int() server = smtplib.SMTP('smtp.gmail.com', 587) server....
461
160
''' Created on Feb 4, 2015 @author: nirmal ''' from scheme import current_timestamp from spire.schema import * from spire.mesh import Surrogate __all__ = ('Notification',) schema = Schema('narrative') class Notification(Model): """A notification.""" class meta: schema = schema ...
820
255
from entity.message import Message from .databaserepo import DatabaseRepo class MessageDbRepo(DatabaseRepo): def __init__(self): super().__init__("Messages") def all(self, cid): query = "SELECT * FROM " + self.table + " WHERE conversation_id = '" + str(cid) + "'" m_results = self.db.s...
1,061
335
from tkinter import * from tkinter import messagebox from database import db from client import client from pprint import * import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import matplotlib.dates as m...
8,896
2,788
import torch import numpy as np import os import sys from fairseq.data.data_utils import collate_tokens from fairseq.models.roberta import RobertaModel import time roberta = RobertaModel.from_pretrained('checkpoints/', checkpoint_file='ck.pt', data_name_or_path='data/processed_RACE/') roberta.eval() def eval_one_e...
4,431
1,490
import soundfile as sf from tqdm import tqdm import src.utils.interface_file_io as io import librosa import wave import multiprocessing import src.utils.interface_multiprocessing as mi import torchaudio import numpy as np import torch.nn.functional as F import torch torchaudio.set_audio_backend("sox_io") def audio_lo...
5,043
1,801
import math from typing import MutableSequence, Optional, TypeVar, Union import torch from torch import nn from torch import Tensor from torch.types import Number from einops import repeat T = TypeVar("T") def exists(val: Optional[T]) -> bool: return val is not None def default(val: Optional[T], d: T) -> T: ...
6,318
2,343
class Blog: def __init__(self, title, photo, name,date,content): self.title = title self.photo = photo self.name = name self.date = date self.content = content blog1= Blog(title='python bisics', photo='https://images.pexels.com/photos/837140/pexels-photo-837140.jpeg', name='Yasser',date='10-06-2...
828
360
import logging from modules.common.GoogleBucketResource import GoogleBucketResource from modules.common.Utils import Utils from modules.common import create_output_dir, remove_output_dir from yapsy.PluginManager import PluginManager from definitions import PIS_OUTPUT_DIR logger = logging.getLogger(__name__) class Re...
4,075
1,148
import importlib import os conf_module = importlib.import_module("conf.%s" % os.environ['CONFIGURATION']) settings = { key: getattr(conf_module, key) for key in dir(conf_module) if key.isupper() }
211
74
from django.db import models # Create your models here. class User(models.Model): SEXS = ((0, '未知'), (1, '男'), (2, '女')) LOCATIONS = (('gz', '广州'), ('sz', '深圳'), ('sh', '上海'), ('bj', '北京'), ('cq', '重庆')) phonenum = models.CharField(max_length=11, unique=True) nickname = models.CharField(max_length=16)...
694
263
from dataclasses import dataclass from scipy.stats import nbinom # type: ignore[import] from probs.discrete.rv import DiscreteRV @dataclass(eq=False) class NegativeBinomial(DiscreteRV): """ The negative binomial distribution is a discrete probability distribution that models the number of failures k in...
1,696
534
#!python3 """ A simple script that uses Baidu Place API to search certain kinds of place in a range of circular space. This API can be called maximum 2000 times per day. """ import requests, json # import psycopg2 class ConvertFailure(Exception): def __str__(self): return "Convertion Failed." mykey = "In...
2,513
948
# -*- coding: utf-8 -*- import logging from pathlib import Path import click import torch from classifier import Classifier from torchvision import datasets, transforms @click.command() @click.argument('data_filepath', type=click.Path(), default='data') @click.argument('trained_model_filepath', type=click.Path(), ...
2,293
692
__author__ = 'luigolas' import numpy as np from scipy.stats import cumfreq class Statistics(): """ Position List: for each element in probe, find its same ids in gallery. Format: np.array([[2,14],[1,2],...]) Mean List: Calculate means of position list by axis 0. Format: np.array([1.52, 4.89]) Mode_li...
4,681
1,553
from rhqmetrics_handler import RHQMetricsHandler
49
16
from tkinter import* #=====importing self created module which will show the registartion form=======# import registrationform #=====importing self created module which will help in deleting student record from data base======# import deletestudent #=============importing selfcreated update student record ========...
3,253
1,117
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Customer, Seller, Product, Order class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_lengt...
3,443
1,035
"""Implementation of AvoidBlastMatches.""" from ..Specification import Specification, SpecEvaluation # from .VoidSpecification import VoidSpecification from ..biotools import blast_sequence from ..Location import Location class AvoidBlastMatches(Specification): """Enforce that the sequence has no BLAST matches ...
4,665
1,336
from aadict import aadict from cachetools import LRUCache import ujson as json import regex from shortuuid import uuid from functools import wraps from glob import glob from time import time import logging import os import shutil import unicodedata _logger = logging.getLogger(__name__) _basepath = None _serialize =...
8,769
2,698
print("x"*25) print("Bem-Vindo a Tabuada v2.0") print("x"*25) n = int(input("Digite um número para a tabuada: ")) for t in range(1, 11): print(f"{n} x {t:2} = {n*t}")
171
88
n1=17 n2=28 if n1>n2: print('n1 bozorgtar az n2') elif n1<n2: print('n2 bozorgtar az n1') elif n1==n2: print('n1 va n2 barabar hastand')
149
80
"""Adds table for scicrunch rrids Revision ID: 39fa67f45cc0 Revises: 3452ca7b13e9 Create Date: 2020-12-15 18:16:03.581479+00:00 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "39fa67f45cc0" down_revision = "3452ca7b13e9" branch_labels = None depends_on = None ...
1,192
421
import pymysql from tkinter import messagebox class Socios(): def abrir(self): bbdd= pymysql.connect( host= "localhost", user= "root", passwd="", db= "ejemplo1") return bbdd def alta(self,datos): ''' datos[0]: id datos[1]: nombre ''' bbdd=self.abrir() ...
2,541
938
import sys import json import das_client def dasFileQuery(dataset): query = 'dataset dataset=%s' % dataset host = 'https://cmsweb.cern.ch' # default idx = 0 # default limit = 0 # unlimited debug = 0 # defaul...
1,420
441
def append_file(password, file_path): password_file = open(file_path, "a+") password_file.write(password + "\r\n") password_file.close()
153
56
import pickle # pickle can serialize python objects data = {1:"hi", 2: "there"} # convert to byte byte_data = pickle.dumps(data) # convert back to python object data2 = pickle.loads(byte_data) # ----------using with files---------- filename = "" # write to a file pickle.dump(data, open(filename, "wb" )) with op...
477
175
from os import sys, path from resolver.models import * sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) sys.path.append('/home/app') from client.lib.cactus_client import CactusClient def run(): Organization.objects.all().delete() Inchi.objects.all().delete() Publisher.objects.all().d...
4,676
1,560
import subprocess def launch_app(path_of_app): try: subprocess.call([path_of_app]) return True except Exception as e: print(e) return False
180
55
from characters.models import Character from characters.serializers import CharacterSerializer from rest_framework import generics class CharacterListView(generics.ListCreateAPIView): queryset = Character.objects.all() serializer_class = CharacterSerializer class CharacterDetailView(generics.RetrieveUpdateD...
418
100
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import DeleteRole, EditRole, NewRole, RolesList, RoleUsers class MisagoAdminExtension(object): def register_urlpatterns(self, urlpatterns): # Permissions section urlpatterns.namespace(r'^permissio...
1,454
450
from base import * import utils.neuralrenderer_render as nr class Visualizer(object): def __init__(self,high_resolution=False): self.high_resolution = high_resolution self.renderer = nr.get_renderer(high_resolution=self.high_resolution).cuda() def visualize_renderer(self,verts,images):...
5,138
1,975
import wsgiref.util import flask from proxy import proxy # pylint: disable=W0212 def test_happy_path(): environ = { "REQUEST_METHOD": "GET", "PATH_INFO": "/locationforecast/1.9/", "QUERY_STRING": "lat=59.31895603;lon=18.0517762", "HTTP_REFERER": "https://walles.github.io/weather...
455
179
import sys def main(): for line in sys.stdin: value, group = line.strip().split(',') print(group, 1, sep='\t') if __name__ == '__main__': main()
186
66
import os import numpy as np import argparse import logging import random import pickle from pprint import pformat from exps.data import ParticleNetDataset from settree.set_data import SetDataset, OPERATIONS, merge_init_datasets import exps.eval_utils as eval from exps.eval_utils import create_logger data_root = '/ho...
6,756
2,187
#!/usr/bin/env python # -*- coding: utf-8 -*- from .blnet_web import BLNETWeb, test_blnet from .blnet_conn import BLNETDirect from .blnet import BLNET
152
61
from psycopg2 import connect import requests import json r = requests.get( "http://localhost:9091/api/getDatabaseContainerByContainerID", params = {"containerID":"Metadatabase"} ) r.json() conn=connect( dbname="metadatabase", user = "postgres", host = r.json()['IpAddress'], password = "postgr...
452
165
from setuptools import setup setup(name='dcgenerator', version='0.1', description='Generate dc events from time series', url='https://github.com/JurgenPalsma/dcgenerator', author='Flying Circus', author_email='jurgen.palsma@gmail.com', license='MIT', packages=['dcgenerator'], ...
395
122
"""Manage Wonk's configuration.""" import pathlib from typing import Any, Dict, List import yaml from pydantic import BaseModel from toposort import toposort_flatten # type: ignore from wonk.exceptions import UnknownParentError class PolicySet(BaseModel): """Describes a policy set.""" name: str manag...
2,801
810
# Copyright 2021 Arm 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 required by applicable law or agree...
5,325
1,697
# Copyright 2017 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
3,192
969
#!/user/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------ @Project : opensourcetest @Time : 2020/11/12 15:01 @Auth : chineseluo @Email : 848257135@qq.com @File : cli_test.py @IDE : PyCharm ------------------------------------ """ import os import sys import unittest from op...
1,578
539
import socket import struct import config import json import threading import random def multicast_handler(client_port: int): # create the datagram socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', client_port)) # set a timeout so the socket does not block indefinitely when...
2,364
727
import numpy as np import torch from collections import defaultdict, deque, OrderedDict import heapq from data_structures import DoublyLinkedList, UndirectedGraph,Fragment import time import sys loss = torch.nn.GaussianNLLLoss() def _compute_stats(track): t,x,y = track['t'],track['x'],track['y'] ct...
18,567
5,753
#Copyright (c) 2010 harkon.kr # # ***** BEGIN MIT LICENSE BLOCK ***** # #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, copy...
4,324
1,355
from enum import Enum class StatusType(Enum): DEFAULT = "dflag updated_at created_at".split() class UnidadesType(Enum): DEFAULT = "dflag updated_at created_at".split() class AssuntoType(Enum): DEFAULT = "dflag updated_at created_at".split() class PersonsType(Enum): DEFAULT = "dflag updated_at create...
5,063
1,489
import os path = os.path.join(os.path.dirname(__file__), 'day01.txt') with open(path) as f: inputdata = f.readlines() def part1(): total = 0 freqlist = {} for line in inputdata: total += int(line) return total def part2(): total = 0 freqlist = set() while True: for lin...
550
201
#! /usr/bin/env python # # Copyright (C) 2018 Mikko Kotila import os DESCRIPTION = "Signs Text Processing for Deep Learning" LONG_DESCRIPTION = """\ Signs is a utility for text preprocessing, vectorizing, and analysis such as semantic similarity, mainly for the purpose of using unstructured data in deep learning mode...
2,259
659
class NotProvided: pass def nullable(value): if isinstance(value, str) and value == 'null': return None return value
139
44
# -*- coding: utf-8 -*- """ Created on Wed Sep 9 08:46:08 2020 @author: Jon """ from numba import jit import numpy as np @jit(nopython=True) def get_adjusted(state, K, W, ms2_coeff): #ms2_coeff_flipped = np.flip(ms2_coeff_flipped, 1) ms2_coeff_flipped = ms2_coeff one_accumulator = 0 zero_ac...
856
334
"""Object name: Resistance Function name: serial_sum(R,nori,nend), performs serial sum of a resistance object list from nori to nend Function name: parallel_sum(R,nori,nend), performs parallel sum of a resistance object list from nori to nend """ ### definition of thermal resistance ### from sympy.interactive ...
5,542
1,770
import csv import MySQLdb from datetime import datetime from tabulate import tabulate #should be changed to sys/argv but this is temporary anyway FILENAME = '/tmp/buttons.csv' NUM_ROWS = 2 def tabulate_dataset(table): headers = ["Mode", "Datetime"] print tabulate(table, headers, tablefmt="grid") + '\n' def...
2,269
721
from flask import session class Session(): @staticmethod def set_session(key: str, value): session[key] = value
133
41
import doctest doctest.testfile("addd.rst")
44
20
from flask import Flask, request, url_for, redirect, session, flash, jsonify, abort import json # from flask_login import LoginManager, UserMixin, login_required, logout_user from flask_login import login_user, logout_user, login_required import os from flask_restful import Resource, Api from passlib.apps import ...
3,040
975
from core_tests_base import CoreTestsBase, FakeTessagon, FakeTileSubClass from tessagon.core.tile_generator import TileGenerator class TestTileGenerator(CoreTestsBase): def test_non_cyclic(self): tessagon = FakeTessagon() tile_generator = TileGenerator(tessagon, ...
4,554
1,691
n = input(); mp = [[int(i) for i in raw_input()] for j in xrange(n)] pnt = [[0 for i in xrange(n)] for j in xrange(n)] x, y = [int(i) for i in raw_input().split()] for i in xrange(1,x): pnt[0][i] = pnt[0][i-1]+mp[0][i]-mp[0][i-1] if mp[0][i]>mp[0][i-1] else pnt[0][i-1] for i in xrange(1,y): pnt[i][0] = pnt[i-1][0]+...
645
390
from . import config as config_module from .resource import resource_config, Resource from .view import ResourceView __all__ = [ "resource_config", "Resource", "ResourceView", ] __version__ = "1.0a2" def includeme(config): for name in config_module.__all__: method = getattr(config_module, n...
368
115
def decryped_data(text, key): char_lower = "" for i in range(97, 123): char_lower += chr(i) char_lower *= 2 char_upper = char_lower.upper() decryped = "" for i in text: if i in char_lower: decryped += char_lower[char_lower.index(i, 26) - key] elif i in char_up...
518
192
#-*- coding: utf-8 -*- from setuptools import setup with open("README.md", "r") as fh: readme = fh.read() setup(name='fala_assis', version='0.0.1', url='https://github.com/OseiasBeu/AssistenteDeFala', license='MIT License', author='Oseias Beu', long_description=readme, long_des...
621
223
num_int = 5 num_dec = 7.3 val_str = "texto qualquer " print("Primeiro número é:", num_int) print("O poder do Kakaroto é mais de %i mil" %num_dec) print("Olá mundo " + val_str + str(num_int)) print("Concatenando decimal:", num_dec) print("Concatenando decimal: %.10f" %num_dec) print("Concatenando decimal: " + str(num...
452
181
#%% #md """ This script downloads the dataset use in the analysis. __It requires 2 inputs to be specified__ repo_directory and email (see first cell block). """ #%% # Where is the main directory of the repo repo_directory = './' # Pubmed requires you to identify with an email addreesss email = '' #%% import os os...
3,603
1,227
# -*- coding: utf-8 -*- from sbdc.preprocessing import ContiguousSegmentSet from sbdc.datasets import bbc_load X = bbc_load() cs = ContiguousSegmentSet( min_segment_length=100, small_segment_vanish_strategy="top") cs.fit(X[:, 2]) text_segments = cs.transform() print text_segments[:2]
297
120
import xml.etree.ElementTree as ET from pathlib import Path from argparse import ArgumentParser import dateutil.parser def main(): parser = ArgumentParser( description="An example script demonstrating how to parse a few " "values out of a FIXM XML file.") parser.add_argument("xml_...
1,586
408
# Base imports from os import environ # Third party imports from graphene import Field, ObjectType, String, Int # Project imports from graphql_api.tenor.schemas.hacker_gif.result import Result from graphql_api.tenor.resolvers.hacker_gif import resolve_hacker_gifs API_KEY = environ.get('TENOR_API_KEY') class Hack...
554
182
# coding: latin-1 # Flask example: https://realpython.com/flask-by-example-part-1-project-setup/ from flask import Flask from waitress import serve app = Flask(__name__) from functions.date import get_date from functions.connect import connect header = '<html>\n\t<header>\n\t\t<title>\n\t\t\tHome control panel\n\t\...
2,367
962
# Handlers import json import logging from aiohttp import web def tape_library_handler_wrapper( request, action_name, required_params=None, optional_params=None, skip_lock_check=False, ): """This wrapper performs error handling for the API calls. Raises ------ Multiple exception...
10,371
2,965
import logging from datetime import datetime, timedelta from robit.core.health import Health class Alert: def __init__( self, **kwargs, ): if 'alert_method' in kwargs: self.method = kwargs['alert_method'] if 'alert_method_kwargs' in kwargs: se...
1,677
469
import datetime import pytz from utils.timezones import time_zones from utils.CalculateHours import calc_hours def validate_schedule(resource, this_tag, customTagName): t = this_tag if t['Key'].lower() == customTagName.lower(): state = resource.state['Name'] stop_instance = False st...
5,823
1,547
class Solution: def isHappy(self, n: int) -> bool: pool = set() pool.add(n) result=n while(result>1): strn = str(result) result = 0 for c in strn: result+=int(c)*int(c) if result in pool: return False ...
365
105
from django.contrib import admin from .models import PreQuestionnaire admin.site.register(PreQuestionnaire)
110
29
import numpy as np from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union def _voc_ap( rec, prec, use_07_metric=False, ): """Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11-point method (default:False). ...
5,014
1,962
import asyncio from callable import Callable from signature import signature import pytest def f1(a: int, b: str = 'x') -> None: pass @asyncio.coroutine def f2(a: int, b: str = 'x') -> None: pass @pytest.mark.parametrize('f,sig', [ (lambda: None, 'lambda'), (lambda a, b: None, 'lambda a, b'), ...
1,418
629
import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
75
27
# coding: utf-8 ########################################################################## # NSAp - Copyright (C) CEA, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for det...
1,293
367
from src.auth.adapter import * from src.auth.domain import * from src.auth.service import *
92
28
class Planning: """ This class represents the Planning phase of a turn """ def __init__(self, game): """ Constructor game: The game under way """ self._game = game def execute(self): """ Run the Planning phase """ ...
569
174
import json import random import re import subprocess import tempfile from datetime import timedelta import cv2 import numpy as np import requests from vidaug import augmentors as va # this is a static build from https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.4.1-i686-static.tar.xz # requires new ffmpeg v...
8,098
2,997
from bingraphvis.base import Content class AflCovInfo(Content): def __init__(self, project): super(AflCovInfo, self).__init__('aflcovinfo', ['text']) self.project = project def gen_render(self, n): node = n.obj n.content[self.name] = { 'data': [{ ...
621
195
from __future__ import absolute_import from __future__ import unicode_literals from corehq.dbaccessors.couchapps.all_docs import \ get_all_doc_ids_for_domain_grouped_by_db, get_doc_count_by_type, \ delete_all_docs_by_doc_type, get_doc_count_by_domain_type from dimagi.utils.couch.database import get_db from djan...
3,418
1,232
#======================================================================= # instruction.py #======================================================================= from pydgin.utils import r_uint class Instruction( object ): def __init__( self, bits, str ): self.bits = r_uint( bits ) self.str = str @prop...
913
348
from autogoal.contrib import find_classes from autogoal.kb import * from autogoal.kb import build_pipelines, build_pipeline_graph from autogoal.contrib.spacy import SpacyNLP from autogoal.contrib._wrappers import FlagsMerger import logging logging.basicConfig(level=logging.INFO) pipeline_space = build_pipeline_gra...
564
189
"""Customizable space module that provides different search spaces implementations. """ from opytimizer.spaces.boolean import BooleanSpace from opytimizer.spaces.grid import GridSpace from opytimizer.spaces.hyper_complex import HyperComplexSpace from opytimizer.spaces.search import SearchSpace from opytimizer.spaces.t...
341
90
# coding: utf-8 # # This code is part of lattpy. # # Copyright (c) 2021, Dylan Jones # # This code is licensed under the MIT License. The copyright notice in the # LICENSE file in the root directory and this permission notice shall # be included in all copies or substantial portions of the Software. """Spatial algorit...
16,913
5,734
# SPDX-License-Identifier: BSD # # This file is part of Pyosmium. # # Copyright (C) 2022 Sarah Hoffmann. import pytest import osmium as o def _run_file(fn): rd = o.io.Reader(fn) try: o.apply(rd, o.SimpleHandler()) finally: rd.close() def test_node_only(test_data): _run_file(test_data(...
1,471
625
def printMatrix(m): for i in range(0, len(m)): print(m[i]) print("\n") def convertInputToReq(data): matrix1 = data width = len(data) terminalStates = [] for i in range(0, width): #are all in the row 0? all0 = True rowSum = sum(data[i]) if (...
6,615
2,456
from typing import TYPE_CHECKING if TYPE_CHECKING: from displayio import Shape, Group, TileGrid, Palette, Bitmap, OnDiskBitmap NativeElement = Group | Shape | TileGrid | Palette | Bitmap | OnDiskBitmap NativeContainer = Group else: NativeElement = object NativeContainer = object
302
90
############################################################################## #copyright 2013, Hamid MEDJAHED (hmedjahed@prologue.fr) Prologue # #Licensed under the Apache License, Version 2.0 (the "License"); # #you may not use this file except in compliance with the License. # #You...
13,279
4,775
from django.contrib import admin from django.http import HttpResponseRedirect from django.urls import path from faker import Faker from .models import ProjectRequest from .utils import create_project_request @admin.register(ProjectRequest) class ProjectRequestAdmin(admin.ModelAdmin): change_list_template = "proj...
1,105
299
import numpy as np from gym import wrappers from reinforcement_learning.utils.utils import decrement_eps, EPS_DEC_LINEAR, pickle_save from reinforcement_learning.tabular_RL.utils import init_v, init_q, init_q1_q2, \ max_action_q, max_action_q1_q2, eps_greedy_q, eps_greedy_q1_q2, print_v class TD0PredictionModel:...
13,477
4,537