text
string
size
int64
token_count
int64
from tkinter import simpledialog from porcupine import actions, get_tab_manager, tabs def gotoline(): tab = get_tab_manager().select() # simpledialog isn't ttk yet, but it's not a huge problem imo lineno = simpledialog.askinteger( "Go to Line", "Type a line number and press Enter:") if linen...
778
239
import os import pickle import sys import warnings from collections import OrderedDict import biosppy.signals.tools as st import numpy as np import wfdb from biosppy.signals.ecg import correct_rpeaks, hamilton_segmenter from hrv.classical import frequency_domain, time_domain from scipy.signal import medfilt...
4,634
1,810
""" Subclass of tiddlywebplugins.openid2 to support tiddlyweb_secondary_user cookie. """ import urlparse from tiddlyweb.web.util import server_host_url, make_cookie from tiddlywebplugins.openid2 import Challenger as OpenID FRAGMENT_PREFIX = 'auth:OpenID:' class Challenger(OpenID): def __init__(self): ...
3,904
1,178
from datetime import datetime import freezegun # Initialize freezegun to avoid freezegun being reinitialized which is expensive initialize_freezegun = freezegun.freeze_time(datetime(2021, 1, 1)) initialize_freezegun.start()
226
69
''' Created on Apr 2, 2015 @author: tmahrt ''' import os from os.path import join import math import copy from pyacoustics.morph.morph_utils import common from pyacoustics.morph.morph_utils import plot_morphed_data from pyacoustics.utilities import utils from pyacoustics.utilities import sequences from pyacoustics....
9,047
2,726
import numpy as np class MetricsController: def __init__(self,metrics=None,algorithm="generic",metrics_path="/home/heitor/recsys/data/metrics",k=10): self.algorithm=algorithm self.metrics_path=metrics_path self.k=k if metrics==None: self.fload_metrics() ...
1,886
675
from typing import TYPE_CHECKING from sqlalchemy import Boolean, Column, Integer, String from sqlalchemy.orm import relationship from app.db.base_class import Base if TYPE_CHECKING: from .pet import Pet # noqa: F401 class User(Base): id = Column(Integer, primary_key=True, index=True, autoincrement=True, nul...
736
236
from django.contrib import admin from django.utils.html import format_html from . import get_user_model @admin.register(get_user_model()) class UserAdmin(admin.ModelAdmin): list_display = ['ext_id', 'username', 'name', 'email', 'active', 'is_bot', 'is_admin', 'get_photo', 'last_seen'] list_filter = ('active'...
930
305
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-04-24 14:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Cre...
1,476
440
#!/usr/bin/env python from flask import Flask, render_template, request, redirect, jsonify, url_for, flash from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker from database_setup import Base, Category, Item, User from flask import session as login_session import random import string impor...
19,691
5,694
class InvalidConfigurationError(Exception): pass class InvalidBotToken(Exception): pass class InvalidBotPlugin(Exception): pass
144
40
import os from setuptools import setup version = os.getenv('VERSION', '1.10.1') setup( name='tensorflow-autodetect', version=version, url='https://github.com/commaai/tensorflow-autodetect', author='comma.ai', author_email='', license='MIT', long_description='Auto-detect tensorflow or tenso...
723
218
from rest_framework import permissions from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from intask_api.projects.models import Project class IsProjectHeader(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.header == requ...
1,639
470
'''3. Write a Python program to split a list into different variables. ''' universalList = [(1, 2, 3), ('w', 'e', 's')] lst1, lst2 = universalList print(lst1) print(lst2)
171
63
# Python3 from solution1 import checkParticipants as f qa = [ ([0, 1, 1, 5, 4, 8], [2]), ([0, 1, 2, 3, 4, 5], []), ([6], []), ([3, 3, 3, 3, 3, 3, 3, 3], [4, 5, 6, 7]), ([0, 0, 1, 5, 5, 4, 5, 4, 10, 8], [1, 2, 5, 6, 7, 9]) ] for *q, a in qa: for i, e in enumerate(q): ...
576
289
from models.base_model import BaseModel from models.classifier import BertClassifier from models.sequence_labeling import BertSequenceLabeling from models.sequence_embedding import BertSequenceEmbedding
202
47
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # python3 -m pip install --force -U --user PlexAPI import json import time import logging import plexapi import plexapi.video import plexapi.myplex import plexapi.server import plexapi.library import plexapi.exceptions PLEX_URL = "" PLEX_TOKEN = "" WATCHED_HISTORY =...
7,563
2,506
import os import sys import time import exceptions import uuid import logging ''' @author: msune,lbergesio,omoya,CarolinaFernandez @organization: i2CAT, OFELIA FP7 PolicyEngine Rule class Encapsulates logic of a simple Rule ''' from django_thermostat.pypelib.Condition import Condition from django_thermo...
3,556
1,246
def test_get_tags(te): r = te.get_tags() assert r == []
64
27
from birds.display_utils import geo_plot from birds.pann import load_pretrained_model, read_audio_fast, get_model_predictions_for_clip, BIRDS def test_prediction_works(): test_bird = 'comrav' model = load_pretrained_model() y = read_audio_fast(f'./data/audio/{test_bird}.mp3') predictions = get_mode...
709
270
#!/bin/python import subprocess import os import sys import maps import time import logging def line(n): print('-'*n) logging.basicConfig(filename = "LetsHPC_Team_CodeRunner.log", level = logging.INFO) logger = logging.getLogger(__name__) #####################################################################...
12,306
3,539
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-24 Last_modify: 2016-03-24 ****************************************** ''' ''' Given two strings s and t, determine if th...
1,236
407
import pymongo ## local 테스트 ## from dotenv import load_dotenv import os import pytz import datetime import itertools from uuid import uuid4 from collections import defaultdict # ObjectId로 쿼리할때 필요 from bson.objectid import ObjectId """ RDBMS Mongo DB Database Database Table Collection Row Document Index...
1,860
629
import numpy as np import cv2 as cv import os import sys class ObjectDetector: """ Object Detector is the class model for using YOLOv2 and gathering results """ def __init__(self): self.network_loading() def network_loading(self): # Loading in the trained darknet models labels self.LABELS =...
1,659
611
# -*- coding: utf-8 from django.apps import AppConfig class ClosuredagConfig(AppConfig): name = 'closuredag'
115
41
class Stack(): def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): return self.stack.pop() def __len__(self): return len(self.stack) def print(self): return print(self.stack) if __name__ == '_...
499
177
from utils.db import connection, print_version import pandas as pd def add_table(csv_file, table_name, engine): df = pd.read_csv(csv_file) df = df.drop('Unnamed: 0') df.to_sql(name=table_name, con=engine, index=False, if_exists='replace') table = 'data/tables/postcode_coordinates.csv' add_table(table, 'P...
484
167
import runpy runpy._run_module_as_main('SeeMee')
48
20
from .name2idx import parameters as C def f_params(): x = [0]*C.len_f_params x[C.Kon_IL13Rec] = 0.00341992 x[C.Rec_phosphorylation] = 999.631 x[C.pRec_intern] = 0.15254 x[C.pRec_degradation] = 0.172928 x[C.Rec_intern] = 0.103346 x[C.Rec_recycle] = 0.00135598 x[C.JAK2_phosphorylation] =...
755
454
import os import datetime import click from flask.cli import with_appcontext from werkzeug.security import generate_password_hash def init_app(app): app.cli.add_command(init_db_command) @click.command('init-db') @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" ...
593
186
with open('./logs/test.log', 'r') as f1: data = f1.readlines() formatted = [x.replace('.pdf', '') for x in data] with open('./logs/test2.log', 'r') as f1: f1.writelines(formatted)
191
79
import argparse import json from pyhmy import ( get_all_validator_addresses, get_validator_information ) def get_block_by_num(block_num, endpoint): params = [ str(hex(block_num)), False, ] payload = { "id": "1", "jsonrpc": "2.0", "method": "hmy_getBlockByNum...
2,206
717
import re valid = ['hcl', 'iyr', 'pid', 'ecl', 'hgt','eyr', 'byr' ] def check_passport_part1(buffer): passport = map(lambda x: x.split(':')[0], buffer.split(' ')) for v in valid: if v not in passport: return False return True def split_passport(buffer): dictionary = {} for fiel...
2,271
754
from django.db import models from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField from utils.model_utils import default_1d_array_of_strings class SeoModel(models.Model): seo_title = models.CharField("SEO title", max_length=100, blank=True, null=True) seo_descri...
535
171
''' symmetrical-synthesis Copyright (c) 2020-present NAVER Corp. MIT license ''' import os import time import glob import cv2 import random import numpy as np import tensorflow as tf import random try: import data_util except ImportError: from dataset import data_util tf.app.flags.DEFINE_boolean('random_resize...
8,314
2,872
# -*- coding: utf-8 -*- """ Created on Sat Jun 17 20:55:53 2019 @author: Parikshith.H """ import sqlite3 conn=sqlite3.connect('music.sqlite') cur=conn.cursor() cur.execute('DROP TABLE IF EXISTS Tracks') cur.execute('CREATE TABLE Tracks(title TEXT,plays INTEGER)') cur.execute('''INSERT INTO Tracks(title,plays) VALUES...
1,678
619
#!/usr/bin/python from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.externalpkg import extmod def main(): module = AnsibleModule(argument_spec={}) module.exit_json(extmod_path=extmod.path()) if __name__ == '__main__': main()
269
89
from ..grammar import * from .Metalanguage import Metalanguage class EBNFTerminal(Terminal): def __init__(self, subject, left_bound='"', right_bound='"'): super().__init__(subject, left_bound=left_bound, right_bound=right_bound) class EBNFDefinitionList(DefinitionList): def __init__(self, definitio...
1,869
564
from sqlalchemy.orm import Session from db.crud.jobs import create_new_job, retrieve_job from schemas.jobs import JobCreate from tests.utils.users import create_random_owner from tests.utils.jobs import create_sample_job def test_retrieve_job_by_id(db_session: Session): """Test retrieving job from db""" owner...
560
180
from __future__ import unicode_literals import pytest import spacy import os try: xrange except NameError: xrange = range @pytest.fixture() def token(doc): return doc[0] @pytest.mark.models def test_load_resources_and_process_text(): from spacy.en import English nlp = English() doc = nlp(u...
5,135
1,755
import os from copy import deepcopy import matplotlib.pyplot as plt import numpy as np from bridge_sim import model, sim, temperature, traffic, plot, util from bridge_sim.model import Config, Point, Bridge from bridge_sim.plot.util import equal_lims from bridge_sim.sim.responses import without from bridge_sim.util im...
35,774
12,370
#%% import json import requests from io import StringIO import pandas as pd # %% with open("../db_pass", "r") as f: token = json.load(f)['token'] # %% data = { 'token': token, 'content': 'record', 'format': 'csv', 'type': 'flat', 'csvDelimiter': '', 'rawOrLabel': 'raw', 'rawOrLabelHead...
936
371
""" Sequence statistics: Count, length, bounding boxes size. """ import os from glob import glob import pickle from tqdm import tqdm def extract_stats(cache_path): # Load sequences from file with open(cache_path, "rb") as fp: # Unpickling seq_list = pickle.load(fp) if len(seq_list) == 0: ...
2,622
901
# Generated by Django 3.0.7 on 2020-07-04 04:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0003_auto_20200704_0400'), ] operations = [ migrations.AlterModelOptions( name='person', options={'verbose_name_plura...
352
134
import datetime from tkapi.util import queries from tkapi.zaak import Zaak, ZaakSoort from tkapi.dossier import Dossier, DossierWetsvoorstel from tkapi.document import Document from .core import TKApiTestCase class TestDossier(TKApiTestCase): def test_get_dossiers(self): dossiers = self.api.get_dossier...
7,735
2,842
""" This library contains several functions designed to help with the illustration of hexagonal grids Functions: plot_hexagaons : plots a specified data vector over a 2-D hexagon grid. create_alpha_mask : creates an alpha shape (a concave hull), which is required for plotting contou...
27,649
8,917
''' self_concepts_test This module serves as the unit test for self_concepts ''' import argparse, sys sys.path.append('../../source/python') from self_concepts import Concept from self_concepts import Property from self_concepts import Relationship from self_concepts import Ontology from self_concepts import Blackb...
58,889
16,207
''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1...
1,042
390
import json from package.query_db import query from package.dictionary_to_list import dictionary_to_list from package.lambda_exception import LambdaException from boto3 import client as boto3_client def verify_admin(event, context): user_id = int(event['user_id']) user_id_dic = {} if user_id == None: #Maki...
2,077
591
#!/usr/bin/env python3 """ Created on September 21 2019 @author: Melchior du Lac @description: Wrap rp2paths into a docker """ import argparse import tempfile import os import logging import shutil import docker import glob def main(rp_pathways, rp2paths_pathways, rp2paths_compounds, timeout=30, max_steps=0, max_pa...
4,821
1,422
import pytest from framework.services.booker_client import BookerClient booker_client = BookerClient() @pytest.fixture() def clear_env(): pass
150
49
spiFile = open('spiflash.bin','wb') # 128KB is reserved for bitstream bitFile = open('../bitstream/mf8a18_rv32i.bin','rb') bitData = bitFile.read(0x20000) riscvFile = open('riscv.bin','rb') riscvData = riscvFile.read(32768) spiFile.write(bitData) spiFile.seek(0x20000) spiFile.write(riscvData) nullData = bytearray...
402
194
"""Options for saving user prefences, etc. """ import json import os import pyvista class RcParams(dict): """Internally used class to manage the rcParams""" filename = os.path.join(pyvista.USER_DATA_PATH, 'rcParams.json') def save(self): with open(self.filename, 'w') as f: json.dump...
753
252
"""This script validates an ArcGIS Enterprise deployment to ensure it is configured properly with all the required components such as Portal for ArcGIS, ArcGIS Server, ArcGIS Data Store and the associated configuration. Designed for ArcGIS Enterprise 10.5 and higher.""" # Author: Philip Heede <pheede@esri.com> # Last...
11,978
3,203
import itertools import re import math from typing import List, Tuple def ints(text: str) -> Tuple[int, ...]: "Return a tuple of all ints in a string" return tuple(map(int, re.findall(r'-?\b\d+\b', text))) def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s ...
4,445
1,926
import math import time from max30105 import MAX30105, HeartRate import smbus from bme280 import BME280 import socket #from matplotlib import pyplot as plt class DataPoint(): def __init__(self,value,time): self.time_stamp = time self.value = value class Device(): def __init__(self...
4,431
1,566
from .client_http import HttpClient from .client_tcp import TcpClient from .client_udp import UdpClient from .client import Client class ClientFactory: """ Client factory for different types of protocols """ def getClient(self, ip, port=None, protocol="http") -> Client: """Creates new client ...
1,417
355
import scrapy ''' 现在您已经知道如何从页面中提取数据,我们来看看如何跟踪它们的链接。 首先是提取我们想要跟踪的页面的链接。检查我们的页面,我们可以看到有一个链接到下一个页面与以下标记: <ul class="pager"> <li class="next"> <a href="/page/2/">Next <span aria-hidden="true">&rarr;</span></a> </li> </ul> 我们可以尝试在shell中提取它: >>> response.css('li.next a').extract_first() '<a href="/page/2/"...
1,569
961
import pytest import numpy as np import pandas as pd from scipy.special import binom import os import sys sys.path.insert(0, "..") from autogenes import objectives as ga_objectives def test_distance(): arr = np.ones((3,3)) assert ga_objectives.distance(arr) == 0 arr = np.identity(3) assert np.isclose(ga_...
909
407
# -*- coding: utf-8 -*- # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. import os import flask from flask_wtf import FlaskForm import wtforms from wtforms import validators from digits.config import config_value from digits.device_query import get_device, get_nvml_info from digits import utils f...
15,563
4,376
# encoding: utf-8 # usando python 3 # Afinação - Alberto toca violão e é programador. # Precisando afinar o violão e sem diapasão por perto, # resolveu fazer um programa para ajudá-lo. # O que ele queria era a nota Lá soando sem parar até que ele conseguisse afinar a # respectiva corda do violão; as demais cordas ...
1,155
422
fav_beer = {'Julian': 'White Rabbit Dark Ale', 'Bob': 'Some sort of light beer I assume', 'Mike': 'Oregano Beer'}
138
46
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Actual WSGI app instantiations used from app.yaml. Extracted to a separate module to avoid calling 'initialize' in unit tests during module loading time....
548
182
"""Layer classes.""" from __future__ import absolute_import import abc import six import tensorflow as tf @six.add_metaclass(abc.ABCMeta) class BaseLayer(object): """Base layer interface.""" @abc.abstractmethod def forward(self): """Layer forward propagation.""" pass @abc.abstractm...
6,298
1,971
import unittest from malcolm.core import call_with_params from malcolm.modules.builtin.parts import GroupPart class TestGroupPart(unittest.TestCase): def setUp(self): self.o = call_with_params( GroupPart, name="things", description="A group of things") self.setter = list(self.o.creat...
835
263
import os from jose import jwt from datetime import datetime, timedelta JWT_SECRET = 'secret' JWT_ALGORITHM = 'HS256' JWT_EXP_DELTA_SECONDS = 31556952 # year def get_token(request): return jwt.decode(request.headers.get('Authorization'), os.environ['JWT_SECRET']) def create_token(user_id): payload = { ...
512
213
import os from django.db import models from ai4all_api.detection_items import DETECTION_ITEMS from ai4all_api.notification_types import NOTIFICATION_TYPES class SubmitCameraItem(models.Model): date_created = models.DateTimeField(auto_now_add=True) tg_chat_id = models.BigIntegerField() name = models.Char...
1,238
397
# # ------------------------------------------------------------------------- # Copyright (c) 2019 AT&T Intellectual Property # # 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 # # ...
1,797
525
import tensorflow as tf x1_data=[73.,93.,89.,96.,73.] x2_data=[80.,88.,91.,98.,66.] x3_data=[75.,93.,90.,100.,70.] y_data=[152.,185.,180.,196.,142.] x1=tf.placeholder(tf.float32) x2=tf.placeholder(tf.float32) x3=tf.placeholder(tf.float32) Y=tf.placeholder(tf.float32) w1=tf.Variable(tf.random_normal([1]),name='weight...
996
461
import pandas as pd import nltk import re from nltk.stem import wordnet from nltk import pos_tag from nltk import word_tokenize from datetime import datetime data = pd.read_csv('traindata.csv', encoding='utf-8') train_counter = 0 def text_normalize(text): global train_counter if train_counter % 10000 == 0: ...
1,759
546
import io import logging import queue from collections import namedtuple import torch import zmq from tensor_twister.status_codes import StatusCode UnpackedMessage = namedtuple("UnpackedMessage", ["tensor", "name", "ip"]) def serve(host: str, port: int): """ Listen for incoming tensor data from clients. P...
1,848
601
#! /usr/bin/env python # Copyright (c) 2014 KU Leuven, ESAT-STADIUS # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notic...
6,744
2,049
""" This problem was asked by Twitter. Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. Hint: Try prep...
622
173
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 09.08.2018 This is basically a python port of of a script by berwinter https://github.com/berwinter/uvr1611/blob/master/lib/backend/blnet-connection.inc.php author: Niels """ import struct from datetime import datetime # Parser constant # 1 bit DIGITAL_ON ...
4,974
1,627
from typing import Optional from typing import List from fastapi import APIRouter, Depends, Body from models import User, Content, Node, Group, ExternalContent from routers import get_current_user, admin_only from schemas import NodeAdd, NodeEdit, NodeFind # router = APIRouter() @router.post("/push_content") async...
3,568
1,118
class vector: def __init__(self, *vals): self.x = list(vals) for val in vals: float(val) self.dimension = len(self.x) def __getitem__(self, key): return self.x[key] def __setitem__(self, key, value): self.x[key] = value return self ...
2,427
794
# https://programmers.co.kr/learn/courses/30/lessons/1845 def solution(nums): if len(set(nums)) <= len(nums)/2: return int(len(set(nums))) else: return int(len(nums)/2) print(solution([3,1,2,3])) print(solution([3,3,3,2,2,4])) print(solution([3,3,3,2,2,2]))
283
131
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
3,903
1,201
from itertools import count from tqdm import tqdm from neodroid.environments.droid_environment import VectorUnityEnvironment def run(self, environment: VectorUnityEnvironment, render: bool = True) -> None: state = environment.reset().observables F = count(1) F = tqdm(F, leave=False, disable=not render)...
992
290
# -*- coding: utf-8 -*- import re import copy import os import string import xlrd import pickle from .get_tokens import * keywords_0 = ('auto', 'typedf', 'const', 'extern', 'register', 'static', 'volatile', 'continue', 'break', 'default', 'return', 'goto', 'else', 'case') keywords_1 = ('catch', 'sizeof...
17,995
5,499
""" Copyright (c) 2020 Flatipie 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, modify, merge...
1,929
631
import os import shutil import xml.dom.minidom def output_pascal_format(mid_data, output_path): # mid_data: # filename # width # height # depth # objects # -- xmin # -- ymin # -- xmax # -- ymax # -- name # -- pose # -- truncated # -- difficult ...
7,035
2,373
""" Contains path planning logic. """ import math import numpy as np from heapq import heappush, heappop def heuristics(a, b): """Heuristics function using the Euclidian Distance.""" weight = 1.0 x1, y1 = a x2, y2 = b distance = np.sqrt(np.square(x2-x1) + np.square(y2-y1)) # distance = math....
4,880
1,528
from libcity.model.traffic_od_prediction.GEML import GEML __all__ = [ "GEML" ]
84
37
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0007_auto_20151202_1434'), ] operations = [ migrations.AddField( model_name='certificationprocess', ...
699
207
import json import logging import sys log = logging.getLogger(__name__) def die(s): log.error(s) sys.exit(-1) def load_json(path): try: fp = open(path) except OSError as err: die("Could not open {}: {}".format(path, str(err))) try: value = json.load(fp) except ValueEr...
628
228
identifier = 'org.vistrails.test.upgrades_layout' name ='test_upgrades_layout' version = '0.3'
95
39
#for all read file code at the end of the code file should closed. f = open('test.txt', 'r') file_contents = f.read() f.close() words = file_contents.split(' ') word_count = len(words) print(word_count) """ OUTPUT: 3 """ #for all the time use a file closing it is became a big job. with open('test.txt', 'r') as f: ...
480
175
import torch from einops import rearrange """ @openai - VD-VAE https://github.com/openai/vdvae/blob/main/vae_helpers.py Nice helper module as calling super.__init__() gets annoying """ class HelperModule(torch.nn.Module): def __init__(self, *args, **kwargs): super().__init__() self.bui...
1,192
477
# coding=utf-8 import sys import numpy as np from p2_mahjong.card import MahjongCard as Card log_head = "utils.py" CARD_USED_TYPE = ['characters', 'green', 'red', 'white', 'east', 'west', 'north', 'south', 'spring', 'summer', 'autumn', 'winter', 'mei', 'lan', 'zhu', 'ju'] card_encoding_dict = {} card...
2,078
797
class Solution: def mySqrt(self, x: int) -> int: # Base cases if (x == 0 or x == 1): return x # Staring from 1, try all numbers until # i*i remains less than to x. i = 1 while (i*i < x):i += 1 return i if i*i == x else i-1 ''' cla...
1,062
385
"""MEG UI Manager """ import pkg_resources from PyQt5 import QtCore, QtWidgets, QtGui, uic from meg_runtime.config import Config from meg_runtime.logger import Logger from meg_runtime.app import App class UIManager(QtWidgets.QMainWindow): """Main UI manager for the MEG system.""" UI_FILE = 'mainwindow.ui' ...
13,517
3,576
"""testing """ from energy_demand.scripts import s_rs_raw_shapes import numpy as np def test_assign_hes_data_to_year(): hes_data = { 'working_day': { 0: np.zeros((24, 2)) + 10, 1: np.zeros((24, 2)) + 20, 2: np.zeros((24, 2)) + 30, 3: np.zeros((24, 2)) + 40, ...
1,459
692
import argparse import logging import yaml from pathlib import Path from script_utils.common import common_setup from release.davis16.compute_flow import link_splits from release.helpers.misc import msg, subprocess_call def check_tracks(track_output, splits): for split in splits: np_dir = track_output /...
1,935
618
# The MIT License (MIT) # Copyright (c) 2021-present foxwhite25 # # 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, ...
4,712
1,740
import tkinter as tk class Kinds: def __init__(self, master, *args, **kwargs): self.master = master self.imethods = tk.PhotoImage(data="""iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAACXBIWXMAAA7DAAAOwwHHb6hk AAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAddJREFUKJGNkjFrk3EQxn/3vt...
6,395
4,509
# Generated by Django 3.0 on 2020-03-29 14:09 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
1,125
344
import struct import sys import math import numpy as np # # TODO 1: (NOW FIXED) Find the first occurrence of magic and start from there # TODO 2: Warn if we cannot parse a specific section and try to recover # TODO 3: Remove error at end of file if we have only fragment of TLV # def tlvHeaderDecode(data): tlvT...
9,686
3,238
from io import StringIO from os import path, listdir, remove from math import radians, tan, cos, pi, atan, sin from pandas import read_csv import sympy as sy import numpy as np # these variables are used to solve symbolic mathematical equations # x is the control variable over the height ... max(x) = H_cross_section ...
11,285
3,609
from __future__ import annotations import json import socket import requests from bunq.sdk.context.api_context import ApiContext, ApiEnvironmentType from bunq.sdk.exception.bunq_exception import BunqException from bunq.sdk.http.api_client import ApiClient from bunq.sdk.model.generated import endpoint from bunq.sdk.m...
1,772
609