text
string
size
int64
token_count
int64
''' The MIT License (MIT) Copyright (c) 2014 NTHUOJ team 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,...
6,013
1,690
""" Wrapper to save the training data to different file formats """ class GenericFileWriter(object): """ Write data to different file formats depending on the open_file and write_file functions """ def __init__(self, open_file=None, write_file=None): self.open_file = open_file self.wr...
618
196
# Generated by Django 2.2 on 2020-03-30 14:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20200330_2200'), ] operations = [ migrations.AlterField( model_name='boughtproduct', name='quantity...
772
255
""" Copyright (c) 2017-2020 ABBYY Production LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
8,087
2,249
import time import random import pyson content = """ { "time" : time.time(), random.randint(0, 1) : "a random number", "another_level" : { "test" : 5 }, "main level" : True } """ print(pyson.loads(content, globals(), locals()))
237
99
import pandas as pd import numpy as np def rsi_tradingview(ohlc: pd.DataFrame, period): delta = ohlc["close"].diff() up = delta.copy() up[up < 0] = 0 up = pd.Series.ewm(up, alpha=1/period).mean() down = delta.copy() down[down > 0] = 0 down *= -1 down = pd.Series.ewm(down, alpha=1/per...
716
310
# -*- coding: utf-8 -*- """ This module extends the default output formatting to include HTML. """ import sys import datetime from jinja2 import Template def html_output(source, header, thresholds): source_file_dict = {"filename": source.filename} func_list = [] for source_function in source.function_li...
808
233
#!/usr/bin/env python # -*- coding:utf-8 -*- import NLP def calculate(tags): tmp_str = " ".join(str(val) for val in tags) tmp_tags = NLP.calculate_also_pos(tmp_str) print(tmp_tags) lst_query = ["USD", "KRW"]#๊ธฐ๋ณธ ์›๋‹ฌ๋Ÿฌ ํ™˜์œจ๋กœ ์ดˆ๊ธฐํ™” str_humanize = ["๋‹ฌ๋Ÿฌ", "์›"]#๊ธฐ๋ณธ ์›๋‹ฌ๋Ÿฌ ํ™˜์œจ๋กœ ์ดˆ๊ธฐํ™” indicator = 0 cursor = ...
5,733
2,048
from marshmallow import fields, validate from .base import BaseSchema class PageParamSchema(BaseSchema): page = fields.Integer(required=True, validate=validate.Range(min=1))
181
52
from multiprocessing import Lock from flask import Flask, request, jsonify from constants import HOST, PORT from Database.database import Database from handler.frontendHandler import frontend_handler from handler.iotHandler import iot_handler # Create the flask application app = Flask(__name__) db_name = 'test.db' db...
1,617
522
n = int(input()) result=0 for i in range(1,n+1): result+=i print(result)
76
33
# Exercรญcio Python 055 # Leia o peso de 5 pessoas, mostre o maior e o menor maior = 0 menor = 0 for p in range(1, 6): peso = int(input("Digite o peso:")) if p == 1: #com o contador na primeira posiรงรฃo, o maior e o menor sรฃo iguais maior = peso menor = peso else: if peso > maior: ...
452
162
from bs4 import BeautifulSoup as bs from pathlib import Path import os import glob import time import random import requests pwd = os.getcwd() page_counter = 1 URL = "https://www.example.com/companies/?page=" # Creating 'pages' folder if this one exists deletes it's content try: Path(pwd + '/pages').mkdir(paren...
886
311
import os from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship, backref Base = declarative_base() from app.db_models.accounts import Accounts from app.db_models.association_table import AssociationTable from app.db_models.o...
892
277
import numpy as np from autumn.models.covid_19.detection import create_cdr_function def test_cdr_intercept(): """ Test that there is zero case detection when zero tests are performed """ for cdr_at_1000_tests in np.linspace(0.05, 0.5, 10): cdr_function = create_cdr_function(1000.0, cdr_at_10...
791
330
#!/usr/bin/env python3 # Copyright (c) 2019, Richard Hughes All rights reserved. # Released under the BSD license. Please see LICENSE.md for more information. import sys import os import argparse import glob import xml.dom.minidom import re # Define command line arguments parms=argparse.ArgumentParser() parms.add_ar...
5,339
1,678
''' Format Provider Tests ''' from textwrap import dedent import pytest from yarals import helpers from yarals.base import protocol from yarals.base import errors as ce # don't care about pylint(protected-access) warnings since these are just tests # pylint: disable=W0212 @pytest.mark.asyncio async def test_format(...
7,889
2,478
import warnings import socket class FCEUXServer: ''' Server class for making NES bots. Uses FCEUX emulator. Visit https://www.fceux.com for info. You will also need to load client lua script in the emulator. ''' def __init__(self, frame_func, quit_func=None, ip='localhost', port=1234): ...
5,109
1,439
from django import forms from .widgets import SpanWidget class MultiSelectFormField(forms.MultipleChoiceField): """ http://djangosnippets.org/snippets/1200/ """ widget = forms.CheckboxSelectMultiple def __init__(self, *args, **kwargs): self.max_choices = kwargs.pop('max_choices', 0) ...
905
274
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ author: Ewen Wang email: wolfgangwong2012@gmail.com license: Apache License 2.0 """ import warnings warnings.filterwarnings('ignore') import random random.seed(0) import time import json import pandas as pd import matplotlib.pyplot as plt import catboo...
5,480
1,637
#!/usr/bin/python import sys import socket import asyncio import select from hexdump import hexdump KISS_FEND = 0xC0 # Frame start/end marker KISS_FESC = 0xDB # Escape character KISS_TFEND = 0xDC # If after an escape, means there was an 0xC0 in the source message KISS_TFESC = 0xDD # If after an escape, means...
4,698
2,044
from django.db import models from users.models import User, BaseModel class CommonModel(models.Model): """This is common model which we are using for common attributes not included in Database as a table :param models.Model: Class to create a new instance of a model, instantiate it like any other Pyt...
2,903
823
#!/usr/bin/python import os import re import jinja2 def generate_metadata(name, additional_dict=None): result = { 'package': 'it.unimi.dsi.fastutil.%ss' % name.lower(), 'primitive': name.lower(), 'boxed_class': name } result.update(additional_dict or {}) return name, result kin...
2,171
701
from tests import test_article from tests import test_source
60
14
from random import randint from BST_version_3 import BinaryTreeNode, BinaryTree # I have to keep the build of lists under 3,000 total # my computer starts to freak out about memory at 10,000 # it slows at 3000. # recursion depth happens on count at 2000 items def test_set(): oaktree = BinaryTree(50.5) for i in range(...
7,451
3,564
import keras.layers as KL class BatchNorm(KL.BatchNormalization): """Batch Normalization class. Subclasses the Keras BN class and hardcodes training=False so the BN layer doesn't update during training. Batch normalization has a negative effect on training if batches are small so we disable it her...
445
125
import pytest from utils import make_hash_sha256 # test_utils.py def test_make_hash_sha256(): w = {'a': ['b', None, dict(c=dict(), d=(1, 2))], (3, 4): 'e'} x = {'a': ['b', None, dict(c=dict(), d=(1, 2))], (3, 4): 'e'} y = {'b': ['b', None, dict(c=dict(), d=(1, 2))], (3, 4): 'e'} z = {(3, 4): 'e', 'b'...
523
260
TOKEN = "" GUILD = "" # crypto bot API_KEY_COINMARKETCAP = ""
62
32
# Generated by Django 3.1.4 on 2022-02-25 05:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('organizations', '0002_organizationcustomer'), ('loans', '0001_initial'), ] operations = [ migration...
543
179
#!/usr/bin/env python2 """ Run exploit locally with: ./solve.py ./solve.py REMOTE HOST=challenge.acictf.com PORT=45110 """ import ast import struct import subprocess from pwn import * PROG_PATH = './challenge' PROT_RWX = constants.PROT_READ | constants.PROT_WRITE | constants.PROT_EXEC EGG_SIZE = 0x1000 def init...
4,026
1,787
#!/usr/bin/env python import os import sys import time import django sys.path.insert(0, './tests') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') if __name__ == '__main__': from django.core.management import execute_from_command_line args = sys.argv args.insert(1, 'test') if len(args) ...
403
147
from os import path import csv import json import random # Our dataset was created from http://www2.informatik.uni-freiburg.de/~cziegler/BX/ and reduced down to 1,000 records # The CSV file has semicolon delimiters due to book titles containing commas SCRIPT_DIR = path.dirname(path.realpath(__file__)) + '/' DB_FILE =...
1,485
449
from channels import route from .features import consumers path = r'^/api/projects/(?P<id>[0-9a-f-]+)/stream/$' channel_routing = [ route("websocket.connect", consumers.connect_to_project, path=path), route("websocket.receive", consumers.disconnect_from_project, path=path) ]
286
98
#!/usr/bin/env python # https://github.com/studioimaginaire/phue import rospy from geometry_msgs.msg import PoseStamped, Pose, Pose2D from std_msgs.msg import String import json import io import os # pose = Pose value # location = string value class Location(): def __init__(self): self.PATH = rospy.ge...
4,923
1,485
#!/usr/bin/env python """ Node to convert joystick commands to kinova arm cartesian movements """ import rospy from sensor_msgs.msg import Joy #from geometry_msgs.msg import Pose from kortex_driver.msg import TwistCommand, Finger, Empty, Pose from kortex_driver.srv import SendGripperCommand, SendGripperCommandRequest...
3,471
1,281
kraftausdruecke = [ "Mist", "Verdammt", "Mannmannmann", "Herrgottnochmal", "Echt jetzt", "Zum Teufel" ] berufe = [ "Baggerfรผhrer", "Velokurier", "Tierรคrztin", "Verkehrspolizist", "Schreinerin", "Apotheker", "Komponist", "Physikerin", "Buchhรคndlerin" ] ...
576
242
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: # set of all node strings ...
2,429
683
import streamlit as st from PIL import Image import cv2 import numpy as np from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accu...
3,391
1,170
""" python3 detect.py \ --model ${TEST_DATA}/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite """ import argparse import os import numpy as np import tensorflow as tf import numpy as np import PIL import matplotlib.pyplot as plt import matplotlib.image as matimage class ConvolutionalAutoencoder(tf.keras.mod...
3,485
1,256
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
4,905
1,958
""" 2018.Jan @author: Tomoki Emmei description: program to show multiplication and addition table """ import sys #read command line argument # Display the multiplication table def kakezan(a,b): Seki_tab=[[0 for i in range(a)] for j in range(b)]# array for the test for i in range(1,b+1): for j in range(...
1,231
440
from typing import Callable import numpy as np from iliad.integrators.states.lagrangian_leapfrog_state import LagrangianLeapfrogState from iliad.integrators.fields import riemannian from iliad.linalg import solve_psd from odyssey.distribution import Distribution class RiemannianLeapfrogState(LagrangianLeapfrogStat...
1,524
469
# Copyright (c) 2013, University of Liverpool # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program ...
2,002
624
# Copyright 2018 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,727
1,404
from functools import partial import math from electroncash.i18n import _ from electroncash.address import Address import electroncash.web as web from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from .util import * from .qrtextedit import ShowQRTextEdit from electroncash import bc...
7,625
2,505
""" * Copyright 2019 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing,...
2,906
912
from __future__ import print_function from cloudmesh.shell.command import command from cloudmesh.shell.command import PluginCommand from cloudmesh.docopts_example.api.manager import Manager from cloudmesh.common.console import Console from cloudmesh.common.util import path_expand from pprint import pprint from cloudmes...
1,091
297
from typing import * import unittest import contextlib import os import sys import tempfile from dvg.dvg import prune_overlapped_paragraphs, expand_file_iter @contextlib.contextmanager def back_to_curdir(): curdir = os.getcwd() try: yield finally: os.chdir(curdir) def touch(file_name: ...
2,790
970
class NoCongressApiKeyException(Exception): """ Thrown when no Congress API key is provided """
108
30
from typing import Union from fastapi import Depends from fastapi.responses import JSONResponse from sqlalchemy.orm import Session from authorization import get_all_roles from server import app, get_db from settings import settings from models import HealthCheck @app.get('/health', tags=['system'], response_model=He...
832
231
from .factal import * from .schema import *
43
13
# SecretPlots # Copyright (c) 2019. SecretBiology # # Author: Rohit Suratekar # Organisation: SecretBiology # Website: https://github.com/secretBiology/SecretPlots # Licence: MIT License # Creation: 05/10/19, 7:52 PM # # All Location Managers will go here from SecretPlots.managers._axis import AxisManager from...
1,482
475
# # This FLIP example combines narrow band flip, 2nd order wall boundary conditions, and # adaptive time stepping. # from manta import * dim = 3 res = 64 #res = 124 gs = vec3(res,res,res) if (dim==2): gs.z=1 s = Solver(name='main', gridSize = gs, dim=dim) narrowBand = 3 minParticles = pow(2,dim) s...
5,279
2,175
import hashlib #take a key key = str(input("KEY>>> ")) #take a message password = str(input("MESSAGE>>> ")) #function does does something #make this more complex or something IDK password = (key + password + key) hash1 = hashlib.new("sha256") password = password.encode("utf-8") print(password) has...
369
136
"""IO methods for radar data from MYRORSS or MRMS. MYRORSS = Multi-year Reanalysis of Remotely Sensed Storms MRMS = Multi-radar Multi-sensor """ import os import glob import warnings import numpy import pandas from netCDF4 import Dataset from gewittergefahr.gg_io import netcdf_io from gewittergefahr.gg_utils import ...
38,214
13,665
from setup.Base import Base from setup.Docker import Docker from setup.SystemD import SystemD
94
25
# Copyright 2021 Cory Paik. 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 ag...
10,325
4,862
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class DiveLogConfig(AppConfig): name = 'dive_log' verbose_name = _(u'Dyklog')
177
61
import json import logging import sys from decouple import config # general ENVIRONMENT: str = config("ENVIRONMENT", "docker") API_VERSION: str = config("API_VERSION", "/api") PROJECT_NAME: str = config("PROJECT_NAME", "Stocks") BACKEND_CORS_ORIGINS: str = config("BACKEND_CORS_ORIGINS", "*") DATETIME_FORMAT = "%Y-%...
3,051
1,212
#This problem was asked by Amazon. #Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. #For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". def DCP_13(s,k): #ciel k by the number of uni...
3,673
1,293
import base64 import hashlib import re import string import itertools from crypto_commons.netcat.netcat_commons import receive_until_match, nc, send, receive_until from crypto_commons.symmetrical.symmetrical import set_byte_cbc, set_cbc_payload_for_block def PoW(suffix, digest): for prefix in itertools.product(...
4,049
1,391
import configparser import re import sys import os from typing import Optional, Mapping, Iterator, Any, List, Dict _default_settings = { "node": { "id.message": "Terrestrial Amateur Radio Packet Network node ${node.alias} op is ${node.call}", "id.interval": 600, "admin.enabled": False, ...
8,170
2,491
# Copyright (c) 2017, Frappe and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import rebuild_tree def execute(): frappe.reload_doc('assets', 'doctype', 'asset_finance_book') frappe.reload_doc('assets', 'docty...
1,952
764
""" Web GUI Author: Irfan Chahyadi Source: github.com/irfanchahyadi/Scraping-Manga """ # IMPORT REQUIRED PACKAGE from flask import Flask, render_template, request, redirect, url_for, Response import os, webbrowser, time from gui import web_api import main app = Flask(__name__) @app.route('/tes') def tes(): return ...
1,709
663
#!/usr/bin/env python3 # Author: Joel Gruselius, Dec 2018 # Script for checking index clashes # Input one or several nucleotide sequences and print any matches found in # the index reference file. This version is only good for checking for # full matches. # It is pretty useful though to list overlapping indexes in th...
4,144
1,334
# Generated by Django 3.2.5 on 2021-07-20 19:37 import cloudinary.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('AwardsApp', '0006_userprofile_bio'), ] operations = [ migrations.AlterField( model_name='project', ...
658
206
"""input manatees: a list of "manatees", where one manatee is represented by a dictionary a single manatee has properties like "name", "age", et cetera n = the number of elements in "manatees" m = the number of properties per "manatee" (i.e. the number of keys in a manatee dictionary)""" # Efficiency: O(n) def example...
1,022
358
from django.urls import reverse from address.models import Address from core.tests import BaseTestSimpleApiMixin from thairod.utils.test_util import APITestCase from warehouse.models import Warehouse class WarehouseAPITestCase(BaseTestSimpleApiMixin, APITestCase): def setUp(self): self.model = Warehouse...
695
217
import datetime import logging import logging.handlers import os import atexit from flask import Flask, request, g from flask_login import current_user from flask_cors import CORS from importlib import reload from urllib.parse import urlsplit import meltano from meltano.core.project import Project from meltano.core.tr...
4,490
1,366
import maya.cmds as cmds import re import rsTools.utils.openMaya.dataUtils as dUtils import maya.OpenMayaAnim as OpenMayaAnimOld import maya.OpenMaya as OpenMayaOld import maya.api.OpenMaya as om import maya.api.OpenMayaAnim as oma def isDeformer(deformer): if not cmds.objExists(deformer): return False ...
24,456
7,421
import logging import os from queue import Queue from threading import Thread from time import time import cv2 class SaveThread(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue def run(self): while True: # Get the work from the queue and expand t...
804
229
# Licensed under an MIT style license -- see LICENSE.md from .utils import ( gw_results_file, functions, history_dictionary, command_line_arguments ) __author__ = ["Charlie Hoy <charlie.hoy@ligo.org>"]
208
72
from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.utils import timezone from django.views.generic import ListView, DetailView, View from .models import Item, Order, OrderItem, Address, Promo from .forms import AddressForm, PromoForm from django.http import ...
7,444
2,164
# Copyright (C) 2011 Gluster, Inc. <http://www.gluster.com> # This file is part of Gluster Management Gateway (GlusterMG). # # GlusterMG is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 3 of...
20,700
6,837
import cv2 as cv import numpy as np def generate_test_video(frames=1000): """ Generador de imรกgenes donde cada imagen tiene el รญndice de su posiciรณn dibujado en el centro y codificado en el pixel superior izquierdo. Para decodificar el รญndice se debe usar lo siguiente: pixel = image[0][0] indice = pixel[0]*25...
1,243
584
import importlib import logging import threading from time import sleep import timeout_decorator from django_pglocks import advisory_lock from django.conf import settings from django.db import transaction from django.db.models import Q from django.utils import timezone from .constants import TASKQ_DEFAULT_CONSUMER_...
7,220
2,080
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2021 by Murray Altheim. All rights reserved. This file is part # of the Robot Operating System project, released under the MIT License. Please # see the LICENSE file included as part of this package. # # author: Murray Altheim # created: 2021-02-24 # ...
14,786
4,207
import pygame import random class Tile(pygame.sprite.Sprite): """Tile class that acts as a sprite""" # Creates sprite tile with image def __init__(self, original_image, mask_image): super().__init__() self.image = original_image self.mask_image = mask_image self....
2,113
658
import sys from swatcher import Swatcher if __name__ == "__main__": files = sys.argv[1:] for file in files: s = Swatcher(file) s.export_ase_file() s.export_palette_image()
207
75
#! /usr/bin/env python from setuptools import setup VERSION = "1.0" AUTHOR = "James Klatzow, Virginie Uhlmann" AUTHOR_EMAIL = "uhlmann@ebi.ac.uk" setup( name="microMatch", version=VERSION, description="3D shape correspondence for microscopy data", author=AUTHOR, author_email=AUTHOR_EMAIL, pa...
1,179
367
import datetime import time import boto3 import sys import os import importlib print('sys.argv:\n{}\n\n'.format(sys.argv)) print('os.environ:\n{}\n\n'.format(os.environ)) # only run the following if running in aws glue environment (not availble locally) if 'GLUE_INSTALLATION' in os.environ: aws_glue_utils = impor...
1,615
557
import requests import time CLIENT_TOKEN_URI = "rest/V1/integration/customer/token" GET_CART_URI = "rest/default/V1/carts/mine" GET_CART_ITEM_URI = "rest/default/V1/carts/mine/items" ADD_TO_CART_URI = "rest/default/V1/carts/mine/items" ME_URI = "rest/default/V1/customers/me" DELETE_ITEM_URI = "rest/default/V1/carts/mi...
7,570
2,254
from spaghettiqueue.__init__ import main main() #Makes the code executable by doing python -m spaghettiqueue
108
32
import math # A function to print all prime factors of # a given number n def prime_factor(n): # Print the number of two's that divide n while n % 2 == 0: n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3, int(math.sqrt(n)) + 1, 2): ...
533
202
# AUTHOR: Zehui Gong # DATE: 2020/6/16 from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import OrderedDict import copy from paddle import fluid from paddle.fluid.param_attr import ParamAttr from paddle.fluid.initializer import Xavier, Const...
8,038
2,659
import numpy as np import tensorflow as tf from tensorflow.python.keras import backend as K from tensorflow.python.keras.layers import Layer, Lambda from tensorflow.python.keras.layers import InputSpec from tensorflow.python.ops import nn_ops from tensorflow.python.keras import initializers, regularizers, constraints...
55,219
16,881
""" test_update_resource_property.py -- Given a VIVO URI, a predicate, and two URIs -- VIVO resource URI and the source URI, generate the add and subtract RDF necessary to execute "five case logic" in updating VIVO with an authoritative source URI. Note. In common use, the source data is presented...
1,488
488
import matplotlib import matplotlib.pyplot as plt import os import pdb import pickle import copy import scipy.signal import scipy.interpolate import numpy as np from astropy.modeling import models, fitting from astropy.nddata import CCDData, StdDevUncertainty from astropy.io import ascii, fits from astropy.convolution ...
36,064
12,541
# Copyright (c) 2022 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from dataclasses import is_dataclass import pytest from hydra_zen import hydrated_dataclass, instantiate def f1(x, y): pass def f2(x, y, z): return x, y, z @pytest.mark.parametrize("conf2_sig", [True, False]) @pyt...
1,075
430
print("Hello World!") #because why the hell not that's why. It was like a free #point on Kattis. Actually got a compiler error on my first #try because I was new to Python3 at the time.
185
54
from django.db import models from forex.models import Currency class Country(models.Model): """ Represents a country, such as the US, or Mexico. """ name = models.CharField(max_length=255, blank=True, null=True, help_text="Official Country name (ISO Full name)") currency = models.ManyToManyField(...
3,165
1,019
import argparse from pathlib import Path import json import seaborn as sns import matplotlib.pyplot as plt from matplotlib import rcParams def main(input_file: Path, output_file: Path) -> None: with input_file.open('r') as fp: data = json.load(fp) plt.figure(figsize=(20, 13)) rcParams['font.fami...
920
331
from ptrait import TraitExtends import copy from pytest_assertutil import assert_equal class IntfA: @classmethod @TraitExtends.mark def a_classmethodA(cls, *args, **kwargs): kwa = copy.deepcopy(kwargs) kwa['a'] = kwargs.get('a', 0) + 1 return args, kwa @classmethod @Trait...
3,436
1,307
import yahoo_fin.stock_info as si import pandas as pd import os def download_data(etfs, time_frames): # ่Žทๅ–ๆ•ฐๆฎๅนถๅญ˜ๅ‚จ if not os.path.exists('./Data'): os.makedirs('./Data') if not os.path.exists('./Data/rawdata'): os.makedirs('./Data/rawdata') for ticker in etfs: for interval in time...
1,526
456
import datetime import re import os import logging import json _months = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ] _precision = [ 'ABT', 'CAL', 'EST', 'AFT', 'BEF' ] _date_expr = re.compile('(?:(' + '|'....
7,220
2,445
from HTMLParser import HTMLParser import json from os import makedirs from os.path import abspath, dirname, exists, join, normpath import pycurl import Queue import re import requests import tempfile import urllib2 class HimalayanDownloader: def __init__(self, eBookUrl, logger): self._logger = logger ...
4,020
1,165
import re import copy import hashlib class Node: def __init__(self, line): m = re.match(r"\/dev\/grid\/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T\s+(\d+)%", line) if m is None: self.valid = False return self.valid = True self.x = int(m.group(1)) s...
4,962
1,557
__author__ = 'wasi' from .summary import * from .code import *
64
23
from collections import defaultdict from prometheus.utils.misc import FrozenClass class RunnerState(FrozenClass): """ An object that is used to pass internal state during train/valid/infer. """ def __init__(self, **kwargs): # data self.device = None self.input = None s...
820
251
#-*- coding: utf-8 -*- import requests import numpy as np import json import concurrent.futures import codecs with codecs.open('./test_1.txt', 'r', 'utf-8') as frobj: input1 = frobj.read().strip() with codecs.open('./candidate_1.txt', 'r', 'utf-8') as frobj: candidate1 = frobj.read().strip() with codecs.open('./t...
1,262
564