text
string
size
int64
token_count
int64
#! /usr/bin/env python3 from sh import git, ErrorReturnCode import argparse import sys import os import atexit import re def exit_handler(repo): """ Rollback the repo to the branch passed as an argument. Parameters: repo: An sh.Command baked for git on the working repository. """ print('...
7,651
2,285
# -*- coding: utf-8 -*- from __future__ import absolute_import import json from kubernetes.client import models as k8s_models from kubernetes.client import apis as k8s_apis from kubernetes.client.rest import ApiException from urllib3.exceptions import MaxRetryError from . import VERSION_RX from .. import config from...
2,455
712
"""Unit test package for nhdpy."""
35
12
"""Temporal VAE with gaussian margial and laplacian transition prior""" import torch import numpy as np import ipdb as pdb import torch.nn as nn import pytorch_lightning as pl import torch.distributions as D from torch.nn import functional as F from .components.beta import BetaVAE_MLP from .metrics.correla...
10,423
3,914
import arcade from cargame.globals import conf from cargame import util # This math is for getting the ratio from zoom. I honestly # don't know what it is called, i just constructed it by hand # Long form is 1 - (x - 1) / 2 zoom_multiplexer = lambda x : (3 - x)/2 # TODO: Implement anchor class Camera: def __init...
7,196
2,295
_base_ = [ '../_base_/models/tsm_r50-d8.py', '../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py' ]
168
86
from itertools import combinations def exclude_combi_idx(combis, scores): a = [score[1] for score in combis] v = [] for score in scores: if score[1] in a: continue v.append(score) return v def set_all_solve(combi): current = 0 num = 0 for item in combi: ...
1,883
615
############################################################################### # Copyright (c) 2019, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by the Merlin dev team, listed in the CONTRIBUTORS file. # <merlin@llnl.gov> # # LLNL-CODE-797170 # All righ...
4,418
1,504
import random import pandas as pd import json def get_random_name(): names = ["Miguel", "Susana", " Pedro", "Mateus", "Ângelo", "Beatriz", "Ana", " Maria", "Carlos", "José"] return names[random.randint(0, len(names) - 1)] def add_random_names(data): for x in data: x["name"] = get_random_name() ...
648
235
"""empty message Revision ID: e91e2508f055 Revises: a064e677a1f1 Create Date: 2019-11-04 22:59:00.701304 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e91e2508f055' down_revision = 'a064e677a1f1' branch_labels = None depends_on = None def upgrade(): # ...
1,332
491
from menu import Menu, MenuEntry from logic.cloudformation import CloudFormation class CloudFormationCli: """ Menu for the AWS CloudFormation operations """ def __init__(self): """ Run the menu """ # Init the logic handler self.cloudformation = CloudFormation()...
758
199
from datetime import datetime, timedelta from peewee import SqliteDatabase, Model, PrimaryKeyField, IntegerField, CharField, BooleanField, DateTimeField from bot.data.config import STATIC_DIR from bot.utils.logging import logger db = SqliteDatabase(f"{STATIC_DIR}/db.sqlite3") class User(Model): """ Клас оп...
3,107
983
# /usr/bin/env python3.5 # -*- mode: python -*- # ============================================================================= # @@-COPYRIGHT-START-@@ # # Copyright (c) 2019-2020, Qualcomm Innovation Center, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modifica...
40,373
12,717
import os from flask import Flask, Response, render_template, redirect from flask_restful import reqparse,request, abort, Api, Resource, fields, marshal_with from flask_sqlalchemy import SQLAlchemy import sqlite3 app = Flask(__name__) p_dir = os.path.dirname(os.path.abspath(__file__)) db_file = "sqlite:///{}".forma...
4,878
1,661
import sys import os import json import csv from time import strftime from datetime import timedelta, date, datetime from flask import Blueprint, render_template, redirect, request, url_for, flash import server.configuration as cfg from server.postalservice import checkTemp from server.helpers import LoginRequired, p...
6,203
2,013
from functools import partial from gdsfactory.cell import cell from gdsfactory.component import Component from gdsfactory.components.compass import compass from gdsfactory.components.via_stack import via_stack_slab_npp_m3 from gdsfactory.types import ComponentSpec, Floats, LayerSpecs, Optional pad_via_stack_slab_npp ...
2,507
899
from abc import abstractmethod import argparse import copy import numpy as np import torch from tqdm import tqdm from cogdl.data import Dataset from cogdl.data.sampler import ( SAINTSampler, NeighborSampler, ClusteredLoader, ) from cogdl.models.supervised_model import SupervisedModel from cogdl.trainers.b...
17,008
5,442
import openmoc import openmc.openmoc_compatible import openmc.mgxs import numpy as np import matplotlib # Enable Matplotib to work for headless nodes matplotlib.use('Agg') import matplotlib.pyplot as plt plt.ioff() opts = openmoc.options.Options() openmoc.log.set_log_level('NORMAL') ##############################...
7,448
2,711
#!/usr/bin/env python import os import urllib2, json from urlparse import urlparse def ParseURL(agsURL): ags = [] print agsURL ags = urlparse(agsURL) return ags def GetFolders(agsURL): f = urllib2.urlopen(agsURL) j = json.loads(f.read()) for item in j["folders"]: print item ...
494
178
import plyfile from config import SparseModel, project_path from colmap_scripts.read_model import Image import numpy as np project = SparseModel("/home/felix/pointclouds/_working/2019_11_07_Muenchen_26_10_2018", model_path="/home/felix/pointclouds/_working/2019_11_07_Muenchen_26_10_2018/sparse/1...
809
334
#!/usr/bin/env python # # Create filter taps to use for interpolation filter in # clock recovery algorithm. These taps are copied from # GNU Radio at gnuradio/filter/interpolator_taps.h. # # This file includes them in natural order and I want # them stored in reversed order such that they can be # used directly. # fil...
15,815
14,010
import os import bpy import openpype.api class ExtractBlendAnimation(openpype.api.Extractor): """Extract a blend file.""" label = "Extract Blend" hosts = ["blender"] families = ["animation"] optional = True def process(self, instance): # Define extract output file path sta...
1,688
470
# SPDX-License-Identifier: MIT # Copyright 2022 hirmiura (https://github.com/hirmiura) # # TamaTouを生成するスクリプト # # 使い方 # 1. fontforgeでコンソールを出す(fontforge-console.bat) # 2. ディレクトリ移動 # 3. ffpython TamaTou.py # 4. 待つ # # Orbitron → オービトロン → オーブ → 玉 → Tamaやな! # Noto → No Toufu → 豆腐だらけだし → Touやな! # →→ TamaTou # import font...
2,772
1,375
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function """ bambu ------ pandas RDF functionality Installation -------------- :: # pip install pandas pip install rdflib """ import sys import pandas as pd import rdflib def bambu(): """ mainfunc """ pass def to...
2,623
878
# Generates the following data files from MIMIC: # adult_icu.gz: data from adult ICUs # n_icu.gz: data from neonatal ICUs # adult_notes.gz: clinical notes from adult ICUs # Import libraries import numpy as np import pandas as pd import psycopg2 from scipy.stats import ks_2samp import os import random # Ouput direct...
19,637
8,466
import argparse from collections import defaultdict, Counter from typing import Any, List, Tuple, Mapping, Optional import datetime import hashlib import json import logging import os import requests import sys import boto3 from e2e import GLOBAL_CONFIG from alerts.default import handle_result as default_handle_resu...
14,098
4,315
import os import argparse def _create_parser(): parser = argparse.ArgumentParser(description='Welcome to Universal Systems Manager' 'Bios Token Change') parser.add_argument('--verbose', help='Turn on verbose logging', ...
2,176
724
import brainrender brainrender.SHADER_STYLE = 'cartoon' from brainrender.scene import Scene sharptrack_file = 'Examples/example_files/sharptrack_probe_points.mat' scene = Scene(use_default_key_bindings=True) scene.add_brain_regions('TH', alpha=.2, wireframe=True) scene.add_probe_from_sharptrack(sharptrack_file) s...
333
130
"""Support for UK Met Office weather service.""" from __future__ import annotations from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.const import ( ATTR_ATTRIBUTION, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, LENGTH_KILOMETERS, PERCENTAGE, ...
7,910
2,514
# -*- coding: utf-8 -*- # # Copyright © 2009 Pierre Raybaut # Licensed under the terms of the MIT License # (see formlayout.py for details) """ Simple formlayout example Please take a look at formlayout.py for more examples (at the end of the script, after the 'if __name__ == "__main__":' line) """ import datetime #...
3,513
1,098
# Import Modules import os import csv # Set the path filepath = os.path.join("Resources","budget_data.csv") # Open the CSV file with open(filepath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Skip the header row next(csvreader) # Set up some numbers month = 0 total = 0 max...
1,527
523
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import hashlib import json from odoo import api, models from odoo.http import request from odoo.tools import ustr from odoo.addons.web.controllers.main import module_boot, HomeStaticTemplateHelpers import odoo class ...
4,103
1,210
#!/usr/bin/python import sys import argparse sys.path.append('./') from src.utils.list_to_dict import list_to_dict from src.utils.read_csv import read_csv from src.utils.map_to_list_csv import map_to_list_csv from src.gephi.write_csv import write_csv print("") print("-----------------------------") print("Anonymiz...
1,500
459
# -*- coding: utf-8 -*- # Copyright (c) 2020, Duk Panhavad and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import getdate, cstr from datetime import timedelta cla...
5,487
2,102
from sklearn.cluster import KMeans import cv2 import PIL import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from matplotlib import image as img1 import pandas as pd from scipy.cluster.vq import whiten import os class DominantColors: CLUSTERS = None IMAGEPATH = None I...
4,445
1,528
from .base import * DEBUG = False SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', SECRET_KEY)
97
43
""" lsprofcalltree.py - lsprof output which is readable by kcachegrind Authors: * David Allouche <david <at> allouche.net> * Jp Calderone & Itamar Shtull-Trauring * Johan Dahlin This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by refer...
2,807
954
# Copyright 2016-2018 The NATS 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 writi...
2,328
713
import os import psycopg2 import sqlite3 from psycopg2.extras import DictCursor from dotenv import load_dotenv DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "rpg.db") connection = sqlite3.connect(DB_FILEPATH) load_dotenv() DB_NAME = os.getenv("DB_NAME", default="OOPS") DB_USER = os.getenv("DB_U...
1,912
712
import torch from torch import nn import numpy as np from models.AttentionLayer import AttentionLayer from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch,\ BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP,\ BertMultiAttentionScoresP, BertAttentionClsQuery fr...
12,852
4,161
############################################################################### # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
8,227
2,803
#Input #Xcode logs output by autogenerated method invocations #Requirements #Infer which invocation numbers failed/succeeded #Infer apparent entitlement requirements based on error message from completion handlers #Detect which invocation numbers should have had completion handlers #Map new information to mach-port a...
4,381
1,265
import unittest, os import pandas as pd import numpy as np import pdb from .. import design_response_translation from .. import utils my_dir = os.path.dirname(__file__) class TestDR(unittest.TestCase): """ Superclass for common methods """ def calculate_design_and_response(self): #drd = design...
10,298
3,677
from django.urls import path from flights import views urlpatterns = [path("", views.index)]
94
28
# -*- coding: utf-8 -*- # # Copyright (C) 2019-2020 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """BorrowingRequest schema for marshmallow loader.""" from invenio_records_rest.schemas import RecordMetadat...
835
273
""" Users app config References: https://docs.djangoproject.com/en/3.1/ref/applications/ """ from django.apps import AppConfig class UsersConfig(AppConfig): name = "systemtest.users" verbose_name = "Users" def ready(self): try: import systemtest.users.signals # noqa F401...
366
115
import sys from setuptools import setup, find_packages def get_version(fname): import re verstrline = open(fname, "rt").read() mo = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", verstrline, re.M) if mo: return mo.group(1) else: raise RuntimeError("Unable to find version string in...
1,675
525
# Copyright The OpenTelemetry 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 ...
2,755
862
# -*- coding: utf-8 -*- """Usage: acli ec2 (ls | list | summary) [options] [--region=<region>] acli ec2 (start | stop | reboot | terminate | info | cpu | vols | net) <instance_id> [options] -f, --filter=<term> filter results by term -s, --start=<start_date> metrics start-date -e,...
2,417
839
""" A Basic GUI based on napari """ import logging import multiprocessing as mp import sys from multiprocessing import Process from pathlib import Path from typing import Optional import matplotlib import napari import numpy as np import xarray as xr from napari.qt.threading import thread_worker from PyQt5.QtCore impo...
7,630
2,370
import numpy as np import paddle.v2 as paddle import paddle.v2.fluid.core as core import paddle.v2.fluid.evaluator as evaluator import paddle.v2.fluid.framework as framework import paddle.v2.fluid.layers as layers import paddle.v2.fluid.nets as nets from paddle.v2.fluid.executor import Executor from paddle.v2.fluid.opt...
3,290
1,161
#!/usr/bin/env python3 # # sem.py # # An implementation of the concrete semantics, including an # interpreter # # Author: Sreepathi Pai # # Written for CSC2/455 Spring 2020 # # To the extent possible under law, Sreepathi Pai has waived all # copyright and related or neighboring rights to sem.py. This work # is publishe...
6,847
2,429
import json from requests import ConnectionError from config import * from utils import * from get_auth import TOKEN # Create network create_network_url = "http://{}:9696/v2.0/networks".format(IP) token_headers = { 'X-Auth-Token': TOKEN, 'Content-Type': 'application/json' } # Create router create_router_url ...
4,925
1,443
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, FileField from wtforms.validators import DataRequired from app.view import errormessage class LoginForm(FlaskForm): username = StringField(label='username', validators=[DataRequired(errormessage.LOGIN002)]) password = ...
1,406
442
from setuptools import find_namespace_packages, find_packages, setup # type: ignore from setuptools.command.test import test as TestCommand # type: ignore class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True ...
2,519
814
import os import sys import signal import asyncio import json import time import traceback import typing import socket import re import select import websockets if sys.platform != "win32": import termios import tty else: import msvcrt import win32api from .. import api from ..shared import constants, ...
13,534
3,837
""" Functions for ionospheric modelling: see SDP memo 97 """ import astropy.units as u import numpy from astropy.coordinates import SkyCoord from data_models.memory_data_models import BlockVisibility from processing_components.calibration.operations import create_gaintable_from_blockvisibility, \ create_gaintabl...
8,772
2,949
''' This file is part of Narval : an opensource and free rights static blog generator. ''' #!/usr/bin/python3 #-*- coding: utf-8 -*- import os, filecmp, random, webbrowser from shutil import copyfile params = __import__('config') helpers = __import__('helpers') tmps = __import__('template') def build(params, help...
7,311
2,977
from src import ( RunMode, setup ) __run_mode__ = RunMode.PARALLEL @setup def my_setup(logger): assert False, "FAILING SETUP ON PURPOSE" def test_skipped(logger): assert False, "THIS TEST SHOULD NOT RUN BECAUSE SETUP FAILED"
247
98
class Node: def __init__(self, val: int): self.val = val self.prev = None self.next = None class DoublyLinkedList: def takeinput(self) -> Node: inputlist = [int(x) for x in input().split()] head = None temp = None for curr in inputlist: if c...
1,276
354
# -*- coding: utf-8 -*- """ USED una tantum to refactor the journal_references collection. Note that the old collection references (monograph reference lists) is discarded: monographs are going to ba parsed again. this script: 1- copies the journal_references collection to another collection: sand, test and production...
9,297
2,791
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections from simpysql.Util.Expression import expression as expr, Expression from simpysql.Util.Response import Response from .BaseBuilder import BaseBuilder from simpysql.Util.Dynamic import Dynamic class SqlServerBuilder(BaseBuilder): operators = [ ...
20,534
5,751
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from openBMC.smbpbi import smbpbi_read import smbus from openBMC.fan_control import set_dbus_data,get_dbus_data,pwm_reqest_set,TMP451_7bit_ADDR,GPU0_7bit_ADDR,GPU1_7bit_ADDR import dbus import argparse import socket import sys import os def show(string,seria...
18,955
5,843
from __future__ import print_function import numpy as np import astropy.io.fits import gal_data import config import argparse import os import sys from collections import defaultdict from pdb import set_trace _WORK_DIR = '/Users/lewis.1590/research/galbase' _GALDATA_DIR = '/Users/lewis.1590/python/galbase/gal_data' _...
5,436
1,882
import json import logging from pathlib import Path from hermes.common.lex_utils import success, error logger = logging.getLogger(__name__) script_path = Path.cwd().joinpath('hermes/help/script.json') with script_path.open() as f: script = json.load(f) def handler(event, context): help_text = '\n'.join(script['...
478
161
from ryu.base import app_manager from ryu.ofproto import ofproto_v1_3 from ryu.controller import ofp_event from ryu.controller.handler import set_ev_cls, MAIN_DISPATCHER, CONFIG_DISPATCHER from ryu.lib.packet.packet import packet, ether_types from ryu.lib.packet.ethernet import ethernet from ryu.lib.packet.ethernet imp...
4,733
1,622
""" Investigate the body of the last API response received by the Actor. """ from json.decoder import JSONDecodeError from typing import Union from screenpy import Actor from screenpy.abilities import MakeAPIRequests from screenpy.exceptions import UnableToAnswer from screenpy.pacing import beat class BodyOfTheLast...
1,355
378
from typing import Optional, Sequence import torch from ...gpu import Device from ...models.encoders import EncoderFactory from ...models.optimizers import OptimizerFactory from ...models.q_functions import QFunctionFactory from ...preprocessing import ActionScaler, RewardScaler, Scaler from ...torch_utility import T...
2,973
879
# -*- coding: utf-8 -*- import json import os import threading import urllib import urllib2 import BigWorld import ResMgr from gui.Scaleform.daapi.view.dialogs import DIALOG_BUTTON_ID, ConfirmDialogButtons, SimpleDialogMeta from gui.Scaleform.daapi.view.lobby.LobbyView import LobbyView from gui import DialogsInterface...
9,086
2,715
from time import sleep from igata.predictors import PredictorBase class DummyPredictorNoInputNoOutput(PredictorBase): def predict(self, inputs, meta): result = {"result": 0.222, "class": "car", "is_valid": True} return result class DummyPredictorNoInputNoOutputVariableOutput(PredictorBase): ...
1,978
649
#Encapsulates all models #Caches the models and uses the preexisting model instead of reloading it from .OCR import get_text from .ptt import get_pdf import pytesseract from .question import secondary_pipeline from transformers import pipeline class customwrapper(): def __init__(self): self.questionmodel ...
2,134
546
from .urlutils import any_path_re def patch_djangocms_urls(): import cms.utils.urlutils as cms_urlutils cms_urlutils.any_path_re = any_path_re
154
61
# This is a collection of very short demo-plugins to illustrate how # to create and register hooks into the various parts of Mailpile # # To start creating a new plugin, it may make sense to copy this file, # globally search/replace the word "Demo" with your preferred plugin # name and then go delete sections you aren'...
4,242
1,174
import argparse import gym import math from qtree_wrapper import PyBox as Box from qtree_wrapper import PyDiscrete as Discrete from qtree_wrapper import PyQTree as QTree from qtree_wrapper import PyVector as Vector from train import Train from utils import convert_to_pybox env = gym.make('CartPole-v0') def truncat...
2,523
941
# Yea, there is probably some good framework waiting for me, # but I just want to have fun. Sometimes reinventing the wheel will serve you. # But...don't do that in professional work :) import config import time from Controller import Controller print("Hello!") root = Controller() # try: if True: lastLoopExecution...
621
192
import concurrent.futures import logging from logging import StreamHandler import time import timeit logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) logger = logging.getLogger(__name__) def do_something(wait_time): logger.info("Waiting for %d sec...
803
276
class Combo(): def combine(self,n, k): A = list(range(1,n + 1)) res = self.comb(A, k) return res def comb(self, A, n): if n == 0: return [[]] l = [] for i in range(0, len(A)): m = A[i] remLst = A[i + 1:] for p in se...
1,249
435
# -*- coding: utf-8 -*- from pytest import raises from django.contrib import admin from django.core.urlresolvers import reverse from django.core.urlresolvers import resolve from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import Resolver404 from django.http import HttpResponse import ur...
1,257
407
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # # All rights reserved. #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are # #met: # ...
7,845
2,519
import random from .api import put_change_grade # grades[id] = grade for user #{id}. # grades[0] is not used. Since user id starts from 1. def change_grade_randomshuffle(grades): changed_users_id = set(range(len(grades))) changed_users_id.remove(0) grades = list(range(len(grades))) random.shuffle(g...
3,629
1,333
import numpy as np import matplotlib.pyplot as plt N = 4 ind = np.arange(N) # the x locations for the groups width = 0.4 # the width of the bars fig, ax = plt.subplots() ax.set_ylim(0,11) # outliers only #ax2.set_ylim(0,35) # most of the data #ax.spines['bottom'].set_visible(False) #ax2.spines['top'].set_vi...
2,188
923
from datetime import timedelta from random import sample, randint import talktracker as tt def time_diff(time1, time2): """calculate the time different""" time1_info = timedelta(hours=time1[0], minutes=time1[1], seconds=time1[2]) time2_info = timedelta(hours=time2[0], minutes=time2[1], seconds=time2[2]) ...
3,829
1,312
import asyncio from dataclasses import dataclass, field from typing import Any from .encode import encoder from .database import database from ..logger import logger @dataclass(order=True) class QueueItem: """ キューアイテム """ priority: int item: Any = field(compare=False) queue = None encode_tasks...
2,692
824
import os from dyson import constants from abc import abstractmethod import sys from dyson.constants import to_boolean class DysonModule: def __init__(self): pass @abstractmethod def run(self, webdriver, params): pass def fail(self, msg): print(msg, file=sys.stderr) ...
476
155
"""A simple text editor made in Python 2.7.""" from os import path, chdir workingdir = path.join(path.dirname(__file__), 'texts') chdir(workingdir) from Tkinter import Tk, Text, Button import tkFileDialog root = Tk("Text Editor") text = Text(root) text.grid() def saveas(): """Save file.""" tr...
1,136
392
import sys n, k= map(int, sys.stdin.readline().split()) def power(a, b): if b == 0: return 1 if b % 2: return (power(a, b//2) ** 2 * a) % P else: return (power(a, b//2) ** 2) % P P = 1000000007 f = [1 for _ in range(n + 1)] for i in range(2, n + 1): f[i] = (f[i - 1] * i) % P A = f[n] B = (f[n-k]*f[k])%P p...
397
245
# Quicksilver.py - Agnostic project analyzer that generates resourceful diagrams. WIP # Copyright (C) 2018 Logan Campos - @binaryflesh
135
46
#!/usr/bin/env python3 """ MIT License Copyright (c) 2020 rootadminWalker 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,830
1,393
# Copyright: Wentao Shi, 2021 import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence from torch.nn.functional import softmax class RNN(torch.nn.Module): def __init__(self, rnn_config): super(RNN, self).__init__() self.embedding_layer = nn.Embedding( num...
5,174
1,672
f = open('./day4.py') for chunk in iter(lambda :f.read(10),''): print(chunk)
86
36
from contextlib import contextmanager from .file import H5File @contextmanager def open_h5file(filename, mode='r+', **kwargs): """Context manager for reading an HDF5 file as an H5File object. Parameters ---------- filename : str HDF5 file name. mode : str Mode to open the file: ...
701
211
import pytest import success_backup_check def test_project_defines_author_and_version(): assert hasattr(success_backup_check, '__author__') assert hasattr(success_backup_check, '__version__')
202
66
from modem_base import Modem from network import LTE import logging class ModemSequans(Modem): def __init__(self): self.lte = LTE() def power_on(self): self.lte.init() def power_off(self): self.lte.deinit(dettach=True, reset=True) def init(self): return True def...
1,816
585
from ravendb.exceptions.exceptions import NonUniqueObjectException, InvalidOperationException from ravendb.tests.test_base import UserWithId, TestBase class TestTrackEntity(TestBase): def setUp(self): super(TestTrackEntity, self).setUp() def test_storing_document_with_the_same_id_in_the_same_session_...
1,824
525
from openpyxl import Workbook from openpyxl.utils import get_column_letter import numbers wb = Workbook() def XL_Location(row, column): return get_column_letter(column) + str(row) def Save_Column_Title(file_dir, features, row_index, column_start): ws = wb.active keys = [x[0] for x in features.items()] ...
1,781
573
import colorsys import itertools import numpy as np import torch def sliding_window(top, step=10, window_size=(20, 20)): """ Slide a window_shape window across the image with a stride of step """ for x in range(0, top.shape[1], step): if x + window_size[0] > top.shape[1]: x = top.shape[1]...
1,971
692
class WebsiteBaseError(Exception): pass class TreeTraversal(WebsiteBaseError): def __init__(self, tree, request, segment, req=None): super().__init__() self.tree, self.request, self.segment, self.req = tree, request, segment, req def __str__(self) -> str: return f"{self.tree} > {s...
578
182
from abc import ABC, abstractmethod from datetime import datetime from typing import Any, List, Literal, Optional from contaxy.schema import Job, JobInput, ResourceAction, Service, ServiceInput from contaxy.schema.deployment import DeploymentType # TODO: update_service functionality class ServiceOperations(ABC): ...
8,498
2,238
# Copyright 2015 PerfKitBenchmarker 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 appli...
15,604
4,895
## Self-driven car project based on nvidia's CNN model ## Package #torch = 0.4.1.post2 #torchvision = 0.2.1 #numpy = 1.15.2 #opencv-python =3.4.3 # -*- coding: utf-8 -*- # Import the Stuff import torch import torch.nn as nn import torch.optim as optim from torch.utils import data from torch.utils.data import DataLoa...
5,933
1,926