text
string
size
int64
token_count
int64
import bottle root = __import__("pathlib").Path(__file__).resolve().parent bottle.TEMPLATE_PATH = [str(root / "views")] app = bottle.default_app() host = "127.0.0.1" port = "65534" from . import controller from . import download_video
238
92
import logging import numpy as np __all__ = [ 'generate_random_points_inside_balls', 'generate_random_point_inside_balls', 'generate_random_points_inside_ball', 'generate_random_point_inside_ball', ] # %% def generate_random_points_inside_balls( X, normalizer, mode, phi, n=1, ...
2,045
703
#!/usr/bin/env python3 def getpts(path): pts = set() loc = [0, 0] for step in path: direction = step[0] distance = int(step[1:]) if direction == "R": for s in range(distance): pts.add((loc[0] + s + 1, loc[1])) loc[0] += distance eli...
1,189
409
import unittest from streamlink.plugins.openrectv import OPENRECtv class TestPluginOPENRECtv(unittest.TestCase): def test_can_handle_url(self): should_match = [ 'https://www.openrec.tv/live/DXRLAPSGTpx', 'https://www.openrec.tv/movie/JsDw3rAV2Rj', ] for url in shou...
609
212
# Generated by Django 3.1.3 on 2021-05-07 18:57 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), ] ope...
2,264
685
# Script de criação do dashboard # https://dash.plotly.com/dash-html-components # Imports import traceback import pandas as pd import plotly.express as px import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html from dash.dependencies import Input, Output # Módulo...
6,474
1,882
from rest_framework import serializers from core.models import Prompt, CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ["id", "username"] class PromptSerializer(serializers.HyperlinkedModelSerializer): created_by = CustomUserSeriali...
752
207
c.Session.debug = True c.LabApp.token = 'test' c.LabApp.open_browser = False c.NotebookApp.port_retries = 0 c.LabApp.workspaces_dir = './build/cypress-tests' c.FileContentsManager.root_dir = './build/cypress-tests' c.LabApp.quit_button = False
246
96
from django.contrib.gis import admin from apps.access.models import InvitedEmail class InvitedEmailAdmin(admin.ModelAdmin): pass admin.site.register(InvitedEmail, InvitedEmailAdmin)
191
58
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-02 14:10 from __future__ import unicode_literals from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('ciudadano', '0052_auto_20170920_1003'), ] operations = [ migrat...
1,550
478
def test_example(app): app.login_admin() app.get("http://localhost/litecart/admin/?app=catalog&doc=catalog&category_id=1") menu=app.driver.find_elements_by_css_selector("tr .row") for n in range(0,len(menu)): element = app.driver.find_elements_by_css_selector("tr .row") element[n].clic...
491
170
from pyautogui import * import pyautogui import time while 1: if pyautogui.locateOnScreen('img.png', region=(150,175,350,600), grayscale=True, confidence=0.8) != None: print("I can see it") time.sleep(0.5) else: print("I am unable to see it") time.sleep(0.5)
302
119
# Copyright 2020 Bradbase import itertools from datetime import datetime, timedelta, date from calendar import monthrange from harvest import Harvest from .harvestdataclasses import * class DetailedReports(Harvest): def __init__(self, uri, auth): super().__init__(uri, auth) self.client_cache = ...
7,526
2,266
""" Send a kill signal to a BiblioPixel process running on this machine to abruptly kill it DEPRECATED: use .. code-block:: bash $ kill -kill `bpa-pid` """ DESCRIPTION = """ Example: .. code-block:: bash $ bp kill """ from .. util.signal_handler import make_command add_arguments, run = make_command('SI...
328
118
# Standard imports import json import ast # Third party imports import pandas as pd from tabulate import tabulate # Local application imports from utils.logger import logger class Dataloding: """Loads movie lens and TMDB data from data folder. """ def __init__(self, data_folder='data'): sel...
5,645
1,649
from django.apps import AppConfig class CoremodelsConfig(AppConfig): name = 'coremodels'
95
32
class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: boxTypes.sort(key=lambda x: x[1],reverse = True) r = 0 remaining = truckSize for boxType in boxTypes: b = min(remaining,boxType[0]) r += b * boxType[1] ...
421
130
# -*- coding: utf-8 -*- from wtforms import Form, StringField, validators class LoginForm(Form): username = StringField('Username:', validators=[validators.required(), validators.Length(min=1, max=30)]) password = StringField('Password:', validators=[validators.required(), validators.Length(min=1, max...
688
228
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 00:44:49 2020 @author: Aanal Sonara """ import cv2 cap = cv2.VideoCapture(0) while cap.isOpened(): _, frame = cap.read() cv2.imshow("live video", frame) k = cv2.waitKey(1) and 0xFF if k==27: break cap.release() cv2.destr...
334
153
import configparser import os import tempfile import urllib.request import xml.dom.minidom import xml.etree.ElementTree as ET from urllib.error import HTTPError, URLError from urllib.parse import urlparse from bs4 import BeautifulSoup from tinytag import TinyTag import gevent dir_path = os.path.dirname(os.path.realpa...
5,515
1,947
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import numpy import torch import torchnet from tqdm import tqdm from torchnet.engine import Engine from torchnet.logger import VisdomPlotLogger, VisdomLogger import project.deco as deco from project.sequoder import SequenceEncoder, get_loss def get_args(...
4,341
1,474
# Copyright 2017 Intel 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 required by applicable law or agreed to in wri...
18,420
4,731
class prefixtoinfix: def prefixToInfix(self,prefix): stack = [] l = [] # read prefix in reverse order i = len(prefix) - 1 for j in prefix: if j == ' ': return [],False while i >= 0: if not self.isOperator(prefix[i]): ...
875
246
from ipykernel.kernelbase import Kernel from iarm.arm import Arm import re import warnings import iarm.exceptions class ArmKernel(Kernel): implementation = 'IArm' implementation_version = '0.1.0' language = 'ARM' language_version = iarm.__version__ language_info = { 'name': 'ARM Coretex M0...
13,212
3,704
#! /usr/bin/evn python class Student(object): __slots__ = ('__birth', '__age') @property def birth(self): return self.__birth @birth.setter def birth(self, value): self.__birth = value @property def age(self): return 2015 - self.__birth if __name__ == '__main__...
383
148
from .vocab import gloveVocabulary
35
15
import pygame class Weapon(pygame.sprite.Sprite): def __init__(self, player, groups): super().__init__(groups) self.spriteType = 'weapon' direction = player.status.split('_')[0] # graphic fullPath = f'./src/img/weapons/{player.weapon}/{direction}.png' self.image = ...
980
311
from abc import ABC, abstractmethod, ABCMeta from Visitor import Visitor class AST(ABC): def __eq__(self, other): return self.__dict__ == other.__dict__ @abstractmethod def accept(self, v, param): return v.visit(self, param) class Program(AST): #decl:list(Decl) def...
3,052
1,133
# # Download images from the LOC IIIF server and store them locally # import requests from pathlib import Path import shutil import time base = 'https://www.loc.gov/' iiifbase = 'https://tile.loc.gov/image-services/iiif/' def getImages(item, dest_dir): downloaded_images = list() Path(dest_dir).mkdir(parents=Tr...
1,224
412
from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list, update_water_levels import floodsystem.flood as flood import floodsystem.plot as plot from datetime import datetime, timedelta import datetime stations = build_station_list() update_water_levels(stations) ...
1,291
375
import hmac, hashlib, binascii from hashlib import sha1 from binascii import a2b_hex, b2a_hex, unhexlify from pbkdf2_ctypes import pbkdf2_bin from multiprocessing import Pool, Queue, cpu_count from datetime import datetime from time import sleep numOfPs = cpu_count() def hmac4times(ptk, pke): tempPke = pke r...
2,007
711
import pygame from gui_components.gui_util import get_font, BLACK, BLUE, GRAY class Cell: def __init__(self, value, row, col, width, height): self.value = value self.temp = 0 self.row = row self.col = col self.width = width self.height = height self.set_by...
1,256
445
""" Remove Dups: Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? """ from linkedlist import linkedlist def remove_dup(linked_list): placeholder = dict() pointer1 = linked_list.top # This guy deletes the du...
2,246
728
# -*- encoding: utf-8 -*- import sys sys.path.append('../') from habet import Application, Response, Handler, errors import json #custom error register class InvalidJSONError(errors.BaseServerError): def __init__(self, *args, **kwargs): super(InvalidJSONError, self).__init__(*args, **kwargs) self.status = 4...
1,172
387
"""API Django models.""" from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Target(models.Model): """Definition of a Target.""" BAN = 'ban' ALLOW = 'allow' TARGET_ACTION_CHOICES = ( ...
2,516
772
from django.urls import path from .views import UserLogin, UserRegister urlpatterns = [ path("accounts/", UserRegister.as_view()), path("login/", UserLogin.as_view()), ]
179
56
#! /usr/bin/env python3 import argparse from pathlib import Path from pytorch_lightning import seed_everything from ranking_utils.datasets.antique import ANTIQUE from ranking_utils.datasets.fiqa import FiQA from ranking_utils.datasets.insuranceqa import InsuranceQA from ranking_utils.datasets.trecdl import TRECDL20...
1,795
609
#!/usr/bin/python # # The MIT License (MIT) # # Copyright (c) 2014 Corrado Ubezio # # 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 rig...
6,158
2,159
# encoding=utf-8 import random from collections import namedtuple Point = namedtuple('Point', 'x y') DIRECTIONS = { 'N': Point(0, -1), 'E': Point(1, 0), 'S': Point(0, 1), 'W': Point(-1, 0), } class LightCycleBaseBot(object): def get_next_step(self, arena, x, y, direction): raise NotIm...
945
305
""" This module allows to perform a specific extrinsic evaluation of files by a specified criteria. Antoine Orgerit - François Gréau - Lisa Fougeron La Rochelle Université - 2019-2020 """ import langid import json import copy import subprocess from os import listdir, remove from os.path import isfile, join from utils...
6,629
2,180
# Copyright 2021 Red Hat, Inc. # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
5,002
1,489
import time, os from openpyxl import load_workbook from openpyxl import Workbook from .config import * class Excel(): """This is a class that saves data to an excel file.""" def loadFile(self, fileName): """load excel file""" self.wb = load_workbook(fileName) self.sheets = self.wb.get_...
2,207
619
import numpy as np # TODO: Do advanced prediction based on profiling work. def predict_energy(total_epochs, epoch_energy_usages): avg_epoch_energy = np.mean(epoch_energy_usages) return total_epochs * avg_epoch_energy def predict_time(total_epochs, epoch_times): avg_epoch_time = np.mean(epoch_times) ...
357
133
from city_scrapers_core.constants import BOARD from city_scrapers_core.spiders import CityScrapersSpider from city_scrapers.mixins import DetAuthorityMixin class DetDowntownDevelopmentAuthoritySpider(DetAuthorityMixin, CityScrapersSpider): name = "det_downtown_development_authority" agency = "Detroit Downtow...
946
314
from common.bert_args import BertArgs from sutime import SUTime from parsing.nltk_nlp_utils import NLTK_NLP from common import globals_args from common import hand_files parser_mode = globals_args.parser_mode wh_words_set = {"what", "which", "whom", "who", "when", "where", "why", "how", "how many", "how large",...
2,172
789
from torchtext.data.datasets_utils import ( _RawTextIterableDataset, _wrap_split_argument, _add_docstring_header, _download_extract_validate, _create_dataset_directory, _create_data_from_csv, ) import os import logging URL = 'https://drive.google.com/uc?export=download&id=0Bz8a_Dbh9QhbZVhsUnRWR...
1,378
589
import os from threading import Thread from typing import List from aiExchangeMessages_pb2 import SimulationID def _handle_vehicle(sid: SimulationID, vid: str, requests: List[str]) -> None: vid_obj = VehicleID() vid_obj.vid = vid i = 0 while i < 10: i += 1 print(sid.sid + ": Test sta...
2,962
880
"""Generate SVG minimap.""" from aioify import wrap as aiowrap from subprocess import Popen, PIPE import math import xml.etree.ElementTree as ET from aocrecs.consts import PREDATOR_IDS, HERDABLE_IDS, HUNT_IDS, BOAR_IDS, FISH_IDS, FORAGE_ID, TC_IDS GOLD_COLOR = '#FFC700' STONE_COLOR = '#919191' FOOD_COLOR = '#A5C46C'...
4,869
1,780
import scrapy from scrapy.item import Field class TitleItem(scrapy.Item): heading = Field() class LinkItem(scrapy.Item): article = Field()
150
50
import os from datetime import datetime from flask import render_template, request, jsonify, send_from_directory, url_for from Application import app, db from Application.db_operations import update_researcher_timestamp, insert_location_point_in_db, \ insert_or_update_existing_researcher, get_all_researchers_from_d...
3,526
1,180
import tweepy import dog from postDog import postDog from config import data if __name__ == '__main__': auth = tweepy.OAuthHandler(data["OAUTH_HANDLER_1"], data["OAUTH_HANDLER_2"]) auth.set_access_token(data["API_KEY_1"], data["API_KEY_2"]) api = tweepy.API(auth) dogPic = dog.getDog(filename='assets...
347
142
#!/usr/bin/env python # Copyright (c) 2016 Sten Linnarsson # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # li...
12,019
4,239
import logging import tcp_log_socket logging_socket = tcp_log_socket.local_logging_socket(__name__) logger = logging_socket.logger #Test method simulating a method with required arguments; division is used to test exception handling def test_args(div1, div2): logger.info("Simulating a method with argument...
1,260
374
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm ##################################################################### from django.http import HttpResponse fr...
3,154
864
import os import unittest from vext.install import DEFAULT_PTH_CONTENT class TestVextPTH(unittest.TestCase): # Preliminary test, that verifies that def test_can_exec_pth_content(self): # Stub test, verify lines starting with 'import' in the pth can # be exec'd and doesn't raise any exceptions...
689
206
import argparse from pprint import pformat import txaio txaio.use_twisted() from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner class ClientSession(ApplicationSession): async def onJoin(self, details): print('MONITOR session joined: {}'.format(details)) xbr_config = self.co...
2,196
660
#!/usr/bin/env python2.7 # Version date : Aug 21, 2018 # # --> very minor correction compared to previous version. As keywords may change in files through time, when we delete # a keyword, we first check if the keyword is preseent rather than "blindly" deleting it # --> also corrected integer vs float divisions in ...
29,349
10,028
from django.urls import path from . import views urlpatterns = [ path('', views.course_list, name='course_list'), path('<course_slug>/', views.session_list, name='session_list'), path('<course_slug>/<session_slug>/', views.session_detail, name='session_detail'), path('<course_slug>/<session_slug>/<pas...
394
127
from api import app, BAD_PARAM, STATUS_OK, BAD_REQUEST from flask import request, jsonify, abort, make_response,render_template, json import sys from lung_cancer.connection_settings import get_connection_string, TABLE_SCAN_IMAGES, TABLE_GIF, TABLE_MODEL, TABLE_FEATURES, LIGHTGBM_MODEL_NAME, DATABASE_NAME,NUMBER_PATIEN...
4,651
1,625
import bloodFunctions as blood import time try: samples = [] blood.initSpiAdc() start = time.time() while (time.time() - start) < 60: samples.append(blood.getAdc()) finish = time.time() blood.deinitSpiAdc() blood.save(samples, start, finish) finally: print("Blood measure sc...
335
117
import logging import re from typing import Literal, Optional import discord from discord.ext import commands from emoji import UNICODE_EMOJI_ENGLISH, is_emoji from bot.bot import Bot from bot.constants import Colours, Roles from bot.utils.decorators import whitelist_override from bot.utils.extensions import invoke_h...
5,144
1,749
# WAP to accept a filename from user and print all words starting with capital letters. def main(): inputFilePath = input("Please enter file name: ") if __name__ == "__main__": main()
198
56
# This is automatically-generated code. # Uses the jinja2 library for templating. import cvxpy as cp import numpy as np import scipy as sp # setup problemID = "least_abs_dev_0" prob = None opt_val = None # Variable declarations import scipy.sparse as sps np.random.seed(0) m = 5000 n = 200 A = np.random.rand...
1,215
481
from __future__ import print_function import os import sys import time import gdal import numpy as np # ------------------------------------------------------------------------- # Files to process # ------------------------------------------------------------------------- fileNames = [ 'tasmax_day_BCSD_rcp85_r1i...
2,621
961
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
1,380
489
""" Ivoire is an RSpec-like testing framework for Python. Globals defined in this module: current_result: Should be set by a runner to an object that has the same interface as unittest.TestResult. It will be used by every example that is instantiated to record test results d...
746
187
# Blair Johnson 2021 from facenet_pytorch import InceptionResnetV1, MTCNN import numpy as np def create_embeddings(images): ''' Take an iterable of image candidates and return an iterable of image embeddings. ''' if type(images) != list: images = [images] extractor = MTCNN() encoder ...
1,699
581
from IPython import embed as shell import itertools import numpy as np import random # SEED = 1234 NUM_PROBS = 1 NUM_CLOTH = 4 filename = "probs/base_prob.prob" GOAL = "(RobotAt baxter robot_end_pose)" # init Baxter pose BAXTER_INIT_POSE = [0, 0, 0] BAXTER_END_POSE = [0, 0, 0] R_ARM_INIT = [0, 0, 0, 0, 0, 0, 0] # [...
6,075
2,576
import pytest from colorviews import AlphaColor class TestGetAttr: @pytest.mark.parametrize("attr, expected", [ ("h", 0.75), ("s", 0.47), ("v", 0.29), ("a", 0.79), ]) def test_valid(self, attr, expected): color = AlphaColor.from_hsva(0.75, 0.47, 0.29, 0.79) ...
2,633
1,315
import random, logging from collections import Counter from flask import Flask, session, request, render_template, jsonify from app.util import unflatten from app.fiftycents import FiftyCentsGame from app.fiftycents import Card log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) app = Flask(...
2,645
799
import time import logging import pickle import json import consolemenu from generic_lib import georeverse, geolookup from bluvo_main import BlueLink from tools.stamps import postOffice from params import * # p_parameters are read logging.basicConfig(format='%(asctime)s - %(levelname)-8s - %(filename)-18s - %(messag...
4,905
1,558
#!/usr/bin/env python3 """ Author : kai Date : 2019-06-26 Purpose: Rock the Casbah """ import argparse import sys import re import csv # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python ...
2,962
931
from django.urls import path from users import views app_name = 'users' urlpatterns = [ path('create/',views.CreateUserView.as_view(),name='create'), path('token/',views.CreateTokenView.as_view(),name='token'), path('me/', views.ManageUserView.as_view(),name='me'), ]
292
105
import matplotlib as mpl import matplotlib.pyplot as plt import networkx as nx import pandas as pd def get_a_dict(filepath): df = pd.read_csv(filepath).iloc[:, 1:13] theme_dict = {} interesting_theme_idx = [3, 6, 11, 15, 16] theme_names = ['Horrendous IVR', 'Mobile Disengagement', "Couldn't Find it O...
4,200
1,861
# -*- coding: utf-8 -*- # Copyright (c) 2021, BS and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.nestedset import get_descendants_of from frappe.utils import flt class GLEntry(Document...
332
108
# Generated by Django 3.0.4 on 2020-03-14 15:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', fi...
574
188
from torch import Tensor from torchvision import transforms class SVHNTransform: """ """ def __call__(self, x) -> Tensor: """ Make SVHN transform Args: x: Input tensor Return: Transform tensor """ x = transforms.ToTensor()(x) ...
645
198
#!/home/rakeshmistry/bin/Python-3.4.3/bin/python3 # @author: rakesh mistry - 'inspire' # @date: 2015-08-06 import sys import re import os import math # Function: parseSmt2File def parseSmt2FileVariables(smt2File): compiledVarPattern = re.compile("[ \t]*\(declare-fun") varMap = {} for line in smt2File: ...
1,508
534
#!/usr/bin/python #coding=utf-8 import json, re, logging, time, io, os import sys from simplified_scrapy.core.config_helper import Configs from simplified_scrapy.core.sqlite_cookiestore import SqliteCookieStore from simplified_scrapy.core.request_helper import requestPost, requestGet, getResponseStr, extractHtml from s...
9,880
2,805
#!/usr/bin/evn python #--coding:utf-8--*-- #Name:天睿电子图书管理系统系统10处注入打包 避免重复 #Refer:http://www.wooyun.org/bugs/wooyun-2015-0120852/ #Author:xq17 def assign(service,arg): if service=="tianrui_lib": return True,arg def audit(arg): urls = [ arg + 'gl_tj_0.asp?id=1', arg + '...
1,457
697
# -*- coding: utf-8 -*- def gb2unicode_simple(x): a, b = (x & 0xFF00) >> 8, x & 0x00FF if 0xAA <= a <= 0xAF and 0xA1 <= b <= 0xFE: return 0xE000 + (a - 0xAA) * 0x5E + b - 0xA1 elif 0xA1 <= a <= 0xA7 and (0x40 <= b <= 0x7E or 0x80 <= b <= 0xA0): return 0xE4C6 + (a - 0xA1) * 0x60 + (0x3F + b ...
49,239
44,010
from __future__ import annotations from copy import deepcopy from dataclasses import dataclass from typing import Callable, TypeVar from pymon import Future, Pipe, cmap, creducel, hof_2, this_async from pymon.core import returns_future from moona.lifespan import LifespanContext LifespanFunc = Callable[[LifespanCont...
6,176
2,070
import discord from discord.ext import commands import json import os import psycopg2 import pytz class Birthday(commands.Cog): """Never forget birthday of your friends""" def __init__(self): # Set up database DATABASE_URL = os.environ["DATABASE_URL"] self.dbcon = psycopg2.connect(D...
4,246
1,373
#sub processes to scrape using the normal Google scraper #include libs import sys sys.path.insert(0, '..') from include import * def save_sources(): call(["python3", "job_save_sources.py"]) def scraper(): call(["python3", "job_scraper.py"]) def reset_scraper(): call(["python3", "job_reset_scraper.py"]) ...
651
233
# producer to stream data into kafka from boto.s3.connection import S3Connection import datetime import json import bz2 from kafka import KafkaProducer from kafka.errors import KafkaError import time import pytz conn = S3Connection() key = conn.get_bucket('aspk-reddit-posts').get_key('comments/RC_2017-11.bz2') produc...
1,620
518
#from pydantic import BaseModel as Model # This gives us backwards compatible API calls from fastapi_camelcase import CamelModel as Model from typing import Optional, List from datetime import date, datetime class UserDefinition(Model): username: str password: Optional[str] = None firstname: Optional[str]...
3,060
915
################################################## # Import Own Assets ################################################## from hyperparameter_hunter.data.data_core import BaseDataChunk, BaseDataset, NullDataChunk ################################################## # Import Miscellaneous Assets #########################...
7,931
2,772
from getthat import getthat # from sna.search import Sna Sna = getthat("sna.search", "Sna") sna = Sna()
108
45
import os import torch from tqdm import tqdm import numpy as np import clip.clip as clip import src.templates as templates import src.datasets as datasets from src.args import parse_arguments from src.models.modeling import ClassificationHead, ImageEncoder, ImageClassifier from src.models.eval import evaluate de...
2,481
769
from flask import Blueprint bp = Blueprint('main', __name__) @bp.after_app_request def after_request(response): """Cache Bust """ cache_cont = "no-cache, no-store, must-revalidate, public, max-age=0" response.headers["Cache-Control"] = cache_cont response.headers["Expires"] = 0 re...
425
151
from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): ...
734
259
import matplotlib.pyplot as plt import pandas as pd import scipy.stats as st import statsmodels.api as sm import math import numpy as np __all__ = ["deming", "passingbablok", "linear"] class _Deming(object): """Internal class for drawing a Deming regression plot""" def __init__(self, method1, method2, ...
21,018
6,628
#! /usr/bin/env python -*- coding: utf-8 -*- """ Name: setup.py Desscription: Install the maclib package. Version: 1 - Inital release Author: J.MacGrillen <macgrillen@gmail.com> Copyright: Copyright (c) John MacGrillen. All rights reserved. """ from setuptool...
1,470
449
# Playing with pattern matching in python 3.10 # Add lambda to parse commands into command and corresponding units parse_command = lambda x, y: (x, int(y)) # Read puzzle input with open ('day2.txt') as fp: commands = [parse_command(*x.strip().split(' ')) for x in fp.readlines()] horizontal_position = 0 depth = 0...
1,021
289
#!/bin/env python3 from argparse import ArgumentParser import csv import os from pathlib import Path import subprocess import sys this_directory = Path(__file__).parent.resolve() vector_script_path = this_directory / 'prepare_vector.sh' def run_single_processing(in_file_path: Path, out_file_path: Path, layer_name: ...
2,159
704
from django.db import models from django.contrib.auth.models import User from django.core.validators import MinLengthValidator # Create your models here. class Post(models.Model): image = models.ImageField(upload_to='uploads/') content = models.TextField(max_length=200, validators=[MinLengthValidator(10)]) ...
1,688
533
def duplicate_count(text): x = set() y = set() for char in text: char = char.lower() if char in x: y.add(char) x.add(char) return len(y) def duplicate_count2(s): return len([c for c in set(s.lower()) if s.lower().count(c) > 1])
286
105
import stable.modalities.dir_dataset as dataset import os.path def test_load_all_images(): srcdir = os.path.join("tests", "assets") data, metadata = dataset.load_all_images(srcdir) assert metadata["resolutions"] == [(125, 140)] assert data[0].shape[2] == 2 assert metadata["filenames"][0] == ["mari...
375
134
import logging import jsonschema from flask import Flask, jsonify from flask import make_response from flasgger import Swagger from sample.config import Config def init_logging(app): handler = logging.StreamHandler() handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(ascti...
1,118
375
import numpy as np from .cnn import CNN from .kviews import KViews from .. import const class EndToEnd(): def __init__( self, bg_model: CNN, rs_model: KViews ) -> None: self.name = 'EndToEnd' self.bg_model = bg_model self.rs_model = rs_model def metadata(...
909
317