text
string
size
int64
token_count
int64
import unittest from model import Cell, Module, OutputType, CellType, Mux import random class CellTests (unittest.TestCase): def setUp(self): self.c = Cell() def tearDown(self): pass def testAsyncOutputFalseWhenBothInputsFalse(self): self.c.driveInputs([False, False]) self.assertFalse(self.c....
12,000
4,648
"""Test the smarttub config flow.""" from unittest.mock import patch from smarttub import LoginFailed from homeassistant import config_entries, data_entry_flow from homeassistant.components.smarttub.const import DOMAIN from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from tests.common import MockConfigEntry...
4,197
1,363
class DefenerVector: def __init__(self, v): self.__v = v def __enter__(self): self.__temp = self.__v[:] return self.__temp def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: self.__v[:] = self.__temp return False v1 = [1, 2, 3] ...
476
178
# Generated by Django 2.2.17 on 2021-01-10 12:35 from django.db import migrations def enable_all_remote_config_feature_states(apps, schema_editor): FeatureState = apps.get_model('features', 'FeatureState') # update all existing remote config feature states to maintain current # functionality when hiding...
785
244
# built in libraries import unittest.mock from tempfile import TemporaryDirectory from os.path import join # tamcolors libraries from tamcolors.utils import identifier class IdentifierTests(unittest.TestCase): def test_globals(self): self.assertIsInstance(identifier.IDENTIFIER_FILE_NAME, str) se...
1,488
436
# start importing some modules # importing OpenCV import cv2 # using this module , we can process images and videos to identify objects, faces, or even handwriting of a human. # importing NumPy import numpy as np # NumPy is usually imported under the np alias. NumPy is a Python library used for working with arrays. I...
2,847
876
__version_info__ = ('0', '1', '1') __version__ = '.'.join(__version_info__) from keyvalues.keyvalues import KeyValues def load_keyvalues(filename): kv = KeyValues() kv.load(filename) return kv
207
71
from collections import deque from itertools import islice from .base import RollingObject class Apply(RollingObject): """ Iterator object that applies a function to a rolling window over a Python iterable. Parameters ---------- iterable : any iterable object window_size : integer, the ...
1,999
648
from typing import List from discord import Role, Color, role from ..bunkbot import BunkBot from ..channel.channel_service import ChannelService from ..core.bunk_user import BunkUser from ..core.service import Service from ..db.database_service import DatabaseService class RoleService(Service): """ ...
7,333
2,159
from __future__ import annotations import abc import enum import pathlib import typing as t class Prediction(enum.Enum): """Represents model prediction.""" def _generate_next_value_(name, start, count, last_values): return name REAL = enum.auto() FAKE = enum.auto() UNCERTAIN = enum.auto...
2,166
590
#python 3 from concurrent.futures import ThreadPoolExecutor import threading import random def view_thread(): print("Executing Thread") print("Accesing thread : {}".format(threading.get_ident())) print("Thread Executed {}".format(threading.current_thread())) def main(): executor = ThreadPoolExecutor(m...
502
156
from buildbot.buildslave import BuildSlave from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.changes import filter from buildbot.config import BuilderConfig from buildbot.schedulers.forcesched import * from poclfactory import createPoclFactory # overrride the 'sample_slave' with a descriptive ...
1,591
478
from flask import Flask, url_for, request, session, abort import os import re import base64 pqr = Flask(__name__) # Determines the destination of the build. Only usefull if you're using # Frozen-Flask pqr.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__)) + '/../build' # Function to easily f...
2,575
822
import json from urllib import request def get_ip(): info = None try: resp = request.urlopen("http://ip-api.com/json/") raw = resp.read() info = json.loads(raw) except Exception as e: print(e) return info
255
83
import collections.abc from typing import Union, Sequence, Optional from .primitives import Number from .units import Unit, UnitTypes _Value = Union[Unit, Number, float, int] class Calc: type: UnitTypes @classmethod def build( cls, values: Union[_Value, Sequence[_Value]], opera...
2,205
655
from .binio import from_dword from .opcodes import Reg, mov_reg_imm, mov_acc_mem, mov_rm_reg, x0f_movups, Prefix def match_mov_reg_imm32(b: bytes, reg: Reg, imm: int) -> bool: assert len(b) == 5, b return b[0] == mov_reg_imm | 8 | int(reg) and from_dword(b[1:]) == imm def get_start(s): i = None if s...
676
304
from tests.testcase import TestCase from edmunds.database.db import db, mapper, relationship, backref from sqlalchemy.orm import mapper as sqlalchemy_mapper, relationship as sqlalchemy_relationship, backref as sqlalchemy_backref from edmunds.database.databasemanager import DatabaseManager from werkzeug.local import Lo...
964
302
import logging pvl_logger = logging.getLogger('pvlib') import datetime import numpy as np import pandas as pd from nose.tools import raises, assert_almost_equals from nose.plugins.skip import SkipTest from pandas.util.testing import assert_frame_equal from pvlib.location import Location from pvlib import solarposit...
6,485
2,150
from MemoryHandler import * from addresses import * from struct import * class carro (object): def __init__(self): self.velocidade=0 self.gasolina=0 self.pontos=0 self.posicao=0 self.rpm=0 self.nitro=0 self.gerenciadorMemoria = MemoryHandler("zsne...
1,396
540
# Copyright (c) 2020 Software AG, # Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, # and/or its subsidiaries and/or its affiliates and/or their licensors. # Use, reproduction, transfer, publication or disclosure is prohibited except # as specifically provided for in your License Agreement with Softwar...
10,483
3,279
# # Copyright (c) 2020, Quantum Espresso Foundation and SISSA. # Internazionale Superiore di Studi Avanzati). All rights reserved. # This file is distributed under the terms of the BSD 3-Clause license. # See the file 'LICENSE' in the root directory of the present distribution, # or https://opensource.org/licenses/BSD-...
866
254
"""Bright general tests""" from unittest import TestCase import nose from nose.tools import assert_equal, assert_not_equal, assert_raises, raises, \ assert_almost_equal, assert_true, assert_false, with_setup import os import warnings import tables as tb import numpy as np from pyne import nucname import bright...
4,135
1,854
from django.apps import AppConfig class DogConfig(AppConfig): name = 'Dog'
81
27
import unittest from pathlib import Path import os import shutil import time from src.bt_utils.handle_sqlite import DatabaseHandler from src.bt_utils.get_content import content_dir from sqlite3 import IntegrityError class TestClass(unittest.TestCase): def testDB(self): if os.path.exists(content_dir): ...
2,568
853
# load model and predicate import mxnet as mx import numpy as np # define test data batch_size = 1 num_batch = 1 filepath = 'frame-1.jpg' DEFAULT_INPUT_SHAPE = 300 # load model sym, arg_params, aux_params = mx.model.load_checkpoint("model/deploy_model_algo_1", 0) # load with net name and epoch num mod = mx.mod.Modul...
1,777
683
class dataMapper: def __init__(self, data): self.__data = data self.__structure = self.getDataStructure() def getDataStructure(self): headings = self.__data[0] structure = {} for key in headings: structure[key.lower()] = '' return structure def m...
577
157
from iconservice import * class SampleInterface(InterfaceScore): @interface def set_value(self, value: int) -> None: pass @interface def get_value(self) -> int: pass @interface def get_db(self) -> IconScoreDatabase: pass @interface def fallback_via_internal_call(self) -> None: pass ...
2,778
916
#!/usr/bin/python from setuptools import setup setup( name = "python-sentry", version = "1.0", author = "Josip Domsic", author_email = "josip.domsic+github@gmail.com", description = ("Pure Python CLI for sentry, as well as client library"), license = "MIT", keywords = "python Sentry CLI", ...
489
170
import json import os def load_config(): PYTHON_ENV = os.getenv("PYTHON_ENV", default="DEV") if PYTHON_ENV == "DEV": with open("./crawler/src/config/config-dev.json") as f: config = json.load(f) host = config["database_host"] name = config["database_name"] ...
790
268
# -*- coding: utf-8 -*- from django.test import SimpleTestCase from core.models import VisibilityMixin class VisibilityMixinTest(SimpleTestCase): def test_is_private(self): visibility = VisibilityMixin() self.assertTrue(visibility.is_private) visibility = VisibilityMixin( vis...
672
200
import datetime import pandas import seaborn as sns import matplotlib.pyplot as plt import os import re import glob amean_err = [] astddev_err = [] amin_err = [] amax_err = [] rmean_err = [] rstddev_err = [] rmin_err = [] rmax_err = [] #loading the true and predicted tec maps for calculating the min/max error, mea...
5,320
2,343
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Challenge Notebook # ## Problem: Sum of Two Integers (Subtraction Variant). # # See the [Lee...
1,969
709
# encoding: utf-8 # Copyright 2011 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. '''Curator: interface''' from zope.interface import Interface from zope import schema from ipdasite.services import ProjectMessageFactory as _ class ICurator(Interface): '''A pe...
1,262
349
from .Results import *
23
7
# Generated by Django 3.0.2 on 2020-01-20 10:43 from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200120_1619'), ] operations = [ migrations.AlterField( model_name='user', nam...
472
168
############################################## # # # Ferdinand 0.40, Ian Thompson, LLNL # # # # gnd,endf,fresco,azure,hyrma # # # ######################################...
350
81
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np from ellalgo.oracles.chol_ext import chol_ext def test_chol1(): """[summary]""" l1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] m1 = np.array(l1) Q1 = chol_ext(len(m1)) assert Q1.factori...
2,707
1,513
#!/usr/bin/env python3 from TelloSDKPy.djitellopy.tello import Tello import cv2 import pygame import numpy as np import time def main(): #Controller Init pygame.init() joysticks = [] for i in range(0,pygame.joystick.get_count()): joysticks.append(pygame.joystick.Joystick(i)) joysticks[...
867
272
import os from copy import deepcopy import tqdm import torch import torch.nn.functional as F import colorful import numpy as np import networkx as nx from tensorboardX import SummaryWriter from .reservoir import reservoir from components import Net from utils import BetaMixture1D class SPR(torch.nn.Module): """ Tr...
11,761
3,690
# Copyright (c) 2020-2022 The PyUnity Team # This file is licensed under the MIT License. # See https://docs.pyunity.x10.bz/en/latest/license.html from pyunity import ( SceneManager, Component, Camera, AudioListener, Light, GameObject, Tag, Transform, GameObjectException, ComponentException, Canvas, PyUnit...
6,602
1,920
import logging import os import alembic.command import alembic.config import cfnresponse from db.session import get_session, get_session_maker from retry import retry from sqlalchemy.exc import OperationalError def log(log_statement: str): """ Gets a Logger for the Lambda function with level logging.INFO and...
1,806
534
from __future__ import unicode_literals import plumber from lxml import etree from datetime import datetime import pipeline class BadArgumentError(Exception): """Raised when a Verb receives wrong args.""" class CannotDisseminateFormatError(Exception): """Raised when metadata format is not supported""" ...
8,988
2,591
from LinkedList import LinkedList def sum_lists(ll_a, ll_b): n1, n2 = ll_a.head, ll_b.head ll = LinkedList() carry = 0 while n1 or n2: result = carry if n1: result += n1.value n1 = n1.next if n2: result += n2.value n2 = n2.next ...
1,229
508
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/5/15 14:44 # @Author : Fred Yangxiaofei # @File : server_common.py # @Role : server公用方法,记录日志,更新资产,推送密钥,主要给手动更新资产使用 from models.server import Server, AssetErrorLog, ServerDetail from libs.db_context import DBContext from libs.web_logs import ins_log...
5,147
1,638
import unittest from src.main.serialization.codec.codec import Codec from src.main.serialization.codec.object.stringCodec import StringCodec from src.main.serialization.codec.primitive.shortCodec import ShortCodec from src.main.serialization.codec.utils.byteIo import ByteIo from src.main.serialization.codec.utils.byte...
1,607
696
# -*- coding: utf-8 -*- """ Created on Wed Jun 7 14:58:44 2017 @author: Jonas Lindemann """ import numpy as np import pyvtk as vtk print("Reading from uvw.dat...") xyzuvw = np.loadtxt('uvw.dat', skiprows=2) print("Converting to points and vectors") points = xyzuvw[:, 0:3].tolist() vectors = xyzuvw[:...
539
246
# Copyright 2014 Florian Ludwig # # 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 writin...
2,237
716
# Import important libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Read the data set dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import t...
1,417
479
# -*- coding: utf-8 -*- """Test for various sources Supported sources - Yahoo Finance - I3Investor - KLSe """ import datetime as dt import string import unittest from source import YahooFinanceSource, GoogleFinanceSource class SourceTest(unittest.TestCase): _TEST_YAHOO_FINANCE_SYMBOL = '6742.KL' _YAHOO_F...
1,853
662
#!/usr/bin/env python3 from collections import namedtuple from itertools import combinations import knapsack def solve_it(input_data, language="rust"): if language == "python": return solve_it_python(input_data) return solve_it_rust(input_data) def solve_it_rust(input_data): return knapsack.so...
2,197
718
from django.conf import settings from api.task.internal import InternalTask from api.task.response import mgmt_task_response from vms.utils import AttrDict from vms.models import Vm from que import TG_DC_UNBOUND, TG_DC_BOUND class MonitoringGraph(AttrDict): """ Monitoring graph configuration. """ def...
3,765
1,128
""" A modular, runtime re-loadable database package! A thin wrapper around the Mongo DB library 'motor' with helper functions to abstract away some more complex database operations. """ import sys as __sys import importlib as __importlib import motor.motor_asyncio import asyncio # names of the python modules/packag...
3,291
798
from helper import unittest, PillowTestCase, hopper from test_imageqt import PillowQtTestCase, PillowQPixmapTestCase from PIL import ImageQt if ImageQt.qt_is_installed: from PIL.ImageQt import QPixmap class TestToQPixmap(PillowQPixmapTestCase, PillowTestCase): def test_sanity(self): PillowQtTestCas...
714
249
from rest_framework import serializers from hood.models import UserProfile class UserProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserProfile fields = ('bio', 'birth_date','picture','email','picture')
255
64
from .lexer import Lexer class ListLexer(Lexer): tokens = Lexer.tokens fingerprints = [ (r'(?P<UL>^\*( +)?)', 'UL'), (r'(?P<OL>^\d+.( +)?)', 'OL'), ] def __init__(self): super().__init__() @_(r'^\*( +)?') def UL(self, t): return t @_(r'^\d+.( +)?') def ...
403
171
# Generated by Django 2.0.2 on 2018-08-20 14:44 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job', '0002_auto_20180820_0901'), ] operations = [ migrations.AlterField( model_name='job'...
879
286
import functools import math import operator class Coordinate: def __init__(self, lat, lng): f_lat = float(lat) if math.fabs(f_lat) > 180: raise ValueError(f'The latitude must be between -180 and 180 degrees, but was {f_lat}!') f_lng = float(lng) if math.fabs(f_lng) > 1...
900
312
from os import environ from requests import post class OdinLogger: @classmethod def log(cls, type, desc, value, id, timestamp): response = post(url="http://localhost:3939/stats/add", data = type + "," + desc + "," + str(value) + "," + id + "," + str(timestamp)) return response.status_code
315
94
# coding=utf-8 import numpy as np from itertools import combinations_with_replacement from my_log import logging def load_transcription(transcription_file_name): """ :return: a list of tuple: [ (word: string, phones: list), (word: string, phones: list), ..., ...
14,673
4,720
""" STAT 656 HW-10 @author:Lee Rainwater @heavy_lifting_by: Dr. Edward Jones @date: 2020-07-29 """ import pandas as pd # Classes provided from AdvancedAnalytics ver 1.25 from AdvancedAnalytics.Text import text_analysis from AdvancedAnalytics.Text import sentiment_analysis from sklearn.feature_extrac...
6,483
2,419
class Timing: def beat_to_seconds(self, beat_number: float) -> float: """ Convert beat number to seconds. :param beat_number: Beat number counted from 0. :return: Time in seconds. """ raise NotImplementedError def seconds_to_beat(self, time: float) -> float: ...
497
136
from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from meditorch.nn.models import UNetResNet from torchsummary import summary import torch.optim as optim from torch.optim import lr_scheduler from meditorch.nn import Trainer from meditorch.utils.plot import plot_image_truem...
2,113
802
"""Query Object for all read-only queries to the Real Property table """ import os import logging from time import time from typing import List import asyncio import aiohttp import aiofiles import databases from PIL import Image import sqlalchemy from sqlalchemy.sql import select, func import geoapi.common.spatial_uti...
10,520
2,923
#!/usr/bin/env python # -*- coding: utf-8 -*- """ API for proxy """ from core import exceptions from core.web import WebHandler from service.proxy.serializers import ProxySerializer from service.proxy.proxy import proxy_srv from utils import log as logger from utils.routes import route def return_developing(): ...
1,685
550
#!/usr/bin/python3 from projects.crawler_for_prodect_category.category_output import output_utils import codecs Logger = output_utils.Logger def output(filename, datas): """ 将爬取的数据导出到html :return: """ Logger.info('Output to html file, please wait ...') # object_serialize('object.pkl',self.dat...
2,058
731
#!/usr/bin/env python # Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
2,947
743
""" Background vs Foreground Image segmentation. The goal is to produce a segmentation map that imitates videocalls tools like the ones implemented in Google Meet, Zoom without using Deep Learning- or Machine Learning- based techniques. This script does the following: - builds a background model using the first 3s ...
5,567
1,684
from entity import Entity class RelativeEntity(Entity): def __init__(self, width, height): Entity.__init__(self, width, height) self.margin = [0, 0, 0, 0] def below(self, entity): self.y = entity.y + entity.height + self.margin[1] def above(self, entity): self.y = entity.y - self.height - self...
1,279
469
#!/opt/conda/envs/rapids/bin/python3 # # Copyright (c) 2020, NVIDIA CORPORATION. # # 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 ...
6,967
2,320
#! /usr/bin/env python ''' This script calculates fractions of SNPs with iHS values above 2.0 over genomic windows of specified size. #Example input: #CHROM POS iHS chr1 14548 -3.32086 chr1 14670 -2.52 chr1 19796 0.977669 chr1 19798 3.604374 chr1 29412 -0.308192 chr1 29813 2.231736 chr1 29847 0.6594 chr1 29873 -2.0...
4,688
1,890
# Import the needed management objects from the libraries. The azure.common library # is installed automatically with the other libraries. from azure.common.client_factory import get_client_from_cli_profile from azure.mgmt.resource import ResourceManagementClient from utils.dbconn import * from utils.logger import * fr...
2,176
555
import numpy from scipy import stats from modules import controler # To compile, us Auto Py to Exe: # Step 1 - install Auto Py to Exe, if not already done # To install the application run this line in cmd: # pip install auto-py-to-exe # To open the application run this line in cmd: # auto-py-to-exe # Step 2 - read the...
1,049
444
# 10000 iterations, just for relative comparison # 2.7.5 3.3.2 # FilesCompleter 75.1109 69.2116 # FastFilesCompleter 0.7383 1.0760 if __name__ == '__main__': import sys import timeit from argcomplete.completers import FilesCompleter from _pytest._argcomplete im...
694
242
from dataclasses import dataclass from bindings.gmd.time_edge_property_type import TimePrimitivePropertyType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class ValidTime(TimePrimitivePropertyType): """ gml:validTime is a convenience property element. """ class Meta: name = "validT...
374
119
import os from compas_assembly.datastructures import Assembly from compas_assembly.geometry import Arch from compas_assembly.rhino import AssemblyArtist from compas.rpc import Proxy proxy = Proxy() proxy.restart_server() try: HERE = os.path.dirname(__file__) except NameError: HERE = os.getcwd() DATA = os.p...
2,020
559
# -*- coding: utf-8 -*- # Copyright (C) 2017-2019 by # David Amos <somacdivad@gmail.com> # Randy Davila <davilar@uhd.edu> # BSD license. # # Authors: David Amos <somacdivad@gmail.com> # Randy Davila <davilar@uhd.edu> """Assorted degree related graph utilities. """ import collections from grinpy i...
8,840
3,014
"""Contain the tests for the handlers of each supported GitHub webhook."""
76
19
# Pytests to test the Polygon domain type in the domain.json schema file import pytest from jsonschema.exceptions import ValidationError pytestmark = pytest.mark.schema("/schemas/domain") @pytest.mark.exhaustive def test_valid_polygon_domain(validator, polygon_domain): ''' Tests an example of a Polygon domain '...
3,860
1,313
from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.utils import timezone from rest_framework.authtoken.models import Token class BerryMan...
1,516
453
import unittest from app.models import Post,User from app import db class PostModelTest(unittest.TestCase): def setUp(self): self.user_Alice=User(username="Alice", password="potato", email="alice@ms.com") self.new_post=Post(id=1,category="All", title="Great Things Take Time", blog="User Tests for b...
1,012
336
import sys, pygame, math, random from Wall import * from Ghost import * from Manpac import * from Norb import * from Score import * pygame.init() clock = pygame.time.Clock() width = 700 height = 700 size = width, height bgColor = r,g,b = 0, 0, 0 screen = pygame.display.set_mode(size) while True: ghosts = [Gh...
8,439
3,230
import logging import multiprocessing import sys from Bio import Entrez from tqdm import tqdm from SNDG import execute, mkdir from SNDG.WebServices import download_file from SNDG.WebServices.NCBI import NCBI Entrez.email = 'A.N.Other@example.com' _log = logging.getLogger(__name__) from collections import defaultdi...
11,871
6,180
"""Cut properly some text.""" import re END_OF_SENTENCE_CHARACTERS = {".", ";", "!", "?"} def properly_cut_text( text: str, start_idx: int, end_idx: int, nbr_before: int = 30, nbr_after: int = 30 ) -> str: """Properly cut a text around some interval.""" str_length = len(text) start_idx = max(0, star...
855
327
# [3차] n진수 게임 import string tmp = string.digits+string.ascii_uppercase[:6] def convert(n, base): q, r = divmod(n, base) if q == 0: return tmp[r] else: return convert(q, base) + tmp[r] def solution(n, t, m, p): answer, nums = '', '' count, cur = 0, 0 while count < t * m: ...
1,307
1,104
from abc import abstractmethod from typing import Any, List import torch def interpolate_vectors(v1: torch.Tensor, v2: torch.Tensor, n: int) -> torch.Tensor: step = (v2 - v1) / (n - 1) return torch.stack([v1 + i * step for i in range(n)], dim=0) def reparameterize(mu: torch.Tensor, log_var: torch.Tensor) -...
1,292
475
# -*- coding: utf-8 -*- import re import pandas as pd import multiprocessing from multiprocessing.dummy import Pool as ThreadPool import logging from .utils import isNull class Triplifier(object): def __init__(self, config): self.config = config self.integer_columns = [] for rule in self.c...
7,293
2,255
from django.urls import path, include from rest_framework import routers from core import views router = routers.DefaultRouter() router.register('coffe_types', views.CoffeTypeViewSet, base_name='coffe_types') router.register('harvests', views.HarvestViewSet, base_name='harvests') router.register( 'storage_repor...
455
146
from django.db import models from core.utils.cnpj_is_valid import cnpj_is_valid class Customer(models.Model): name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=50, null=False, blank=False) cnpj = models.CharField(max_length=14, unique=True, null=False, b...
409
140
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped from styx_msgs.msg import Lane, Waypoint from scipy.spatial import KDTree import numpy as np from std_msgs.msg import Int32 import math ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As men...
5,876
1,971
from typing import Any import cv2 import numpy as np from sigmarsGarden.config import Configuration from sigmarsGarden.parse import circle_coords def configure(img: Any) -> Configuration: cv2.namedWindow("configureDisplay") # def click_and_crop(event, x, y, flags, param) -> None: # print(event, x, ...
1,633
570
import torch from transformers import GPT2Tokenizer, GPT2LMHeadModel from torch.utils.data import TensorDataset, DataLoader # reference: \transformers\generation_utils.py def select_greedy(logits): next_token_logits = logits[:, -1, :] # Greedy decoding next_token = torch.argmax(next_token_logits, dim=-1) ...
4,847
1,781
from cc3d import CompuCellSetup from connectivityTestSteppables import connectivityTestSteppable CompuCellSetup.register_steppable(steppable=connectivityTestSteppable(frequency=1)) CompuCellSetup.run()
205
65
from models.genetic_algorithms.population import Population
59
14
from django.urls import path from . import views app_name = 'campaigns' urlpatterns = [ path('<int:campaign_id>/', views.Campaign.as_view(), name='campaign'), ]
167
61
# -*- coding: iso-8859-15 -*- import spanishconjugator from spanishconjugator.SpanishConjugator import Conjugator # ----------------------------------- Imperfect Indicative ----------------------------------- # def test_imperfect_indicative_yo_ar(): expected = "hablaba" assert Conjugator().conjugate('hablar',...
1,470
495
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 13 17:37:31 2020 @author: robertopitz """ import numpy as np from random import randrange from math import isnan import pygame as pg def get_new_prey_pos(pos, board): while True: c = randrange(1,len(board)-1) r = randrange(1,len...
8,044
3,157
# coding:utf-8 import ConfigParser import sys __author__ = '4ikist' from core.engine import NotificatonIniter, TalkHandler, VKEventHandler def load_config(prop_file): cfg = ConfigParser.RawConfigParser() cfg.read(prop_file) api_name = dict(cfg.items('main'))['api_name'] api_credential...
1,092
381
from utils.yacs_config import CfgNode as CN __C = CN() cfg = __C # cfg.canvas_init=0 cfg.use_vit=0 cfg.use_fast_vit=0 cfg.img_mean=-1 cfg.vit_mlp_dim=2048 cfg.vit_depth=8 cfg.vit_dropout=1 cfg.concat_one_hot=0 cfg.mask_out_prevloc_samples=0 #cfg.input_id_canvas=0 cfg.register_deprecated_key('input_id_canvas') cfg.use_...
1,375
662
#!/usr/bin/env python3 import sys from itertools import repeat, product from operator import mul from functools import reduce inputFile = 'input' if len(sys.argv) >= 2: inputFile = sys.argv[1] heightmap : list[list[int]] = [] with open(inputFile) as fin: for line in fin: heightmap.append([int(c) for ...
1,769
699
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains custom tray balloon """ from __future__ import print_function, division, absolute_import from Qt.QtWidgets import QWidget, QSystemTrayIcon, QMenu class TrayMessage(QWidget, object): def __init__(self, parent=None): super(TrayMessa...
974
327