text
string
size
int64
token_count
int64
""" from: http://adventofcode.com/2017/day/6 --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks....
2,645
714
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unittests for the GDAl tools. This file is part of the REDRESS algorithm M. Lamare, M. Dumont, G. Picard (IGE, CEN). """ import pytest from geojson import Polygon, Feature, FeatureCollection, dump from redress.geospatial.gdal_ops import (build_poly_from_coords, ...
3,328
1,226
from output.models.ms_data.regex.letterlike_symbols_xsd.letterlike_symbols import Doc __all__ = [ "Doc", ]
112
42
"""test.py Python3 Test script that demonstrates the passing of an initialized python structure to C and retrieving the structure back. """ import testMod from ctypes import * class TESTSTRUCT(Structure): pass TESTSTRUCT._fields_ = [ ("name", c_char_p), ("next", POINTER(TESTSTRUCT), #We can use a ...
1,296
430
def addition(num1, num2): return num1 + num2 def subtraction(num1, num2): return num1 - num2 def multiplication(num1, num2): return num1 * num2 def division(num1, num2): if num2 == 0: return None return num1 / num2
246
91
from __future__ import print_function import os import csv import graphviz import numpy as np import plotly.graph_objs as go import plotly import plotly.plotly as py import matplotlib.pyplot as plt import matplotlib.pylab as pylab import copy import warnings import matplotlib as mpl from plotly.offline import download...
33,258
11,655
# -*- coding: utf-8 -*- """ --------------------------------------------- File Name: 粗避障 Desciption: Author: fanzhiwei date: 2019/9/5 9:58 --------------------------------------------- Change Activity: 2019/9/5 9:58 -------------------------------------...
1,683
619
from django.utils.text import slugify from django_extensions.db.fields import AutoSlugField from django.db import models from datetime import datetime def get_current_date_time(): return datetime.now() # Create your models here. class Post(models.Model): title = models.CharField(max_length=50) slug = AutoSlugFi...
965
316
from brl_gym.estimators.learnable_bf.learnable_bf import LearnableBF #from brl_gym.estimators.learnable_bf.bf_dataset import BayesFilterDataset
145
55
import os import argparse import logging import numpy as np import torch as th from torch.utils.data import DataLoader from torchvision import transforms import ttools from ttools.modules.image_operators import crop_like import rendernet.dataset as dset import rendernet.modules.preprocessors as pre import rendernet....
4,156
1,616
from django.db import models # Create your models here. from shortener.models import CondenseURL class UrlViewedManager(models.Manager): def create_event(self, condensed_object, ip_address): if isinstance(condensed_object, CondenseURL): obj, created = self.get_or_create(url=condensed_object) ...
1,002
302
def clean_pycache(dir_, ignores=''): import shutil for path in dir_.glob('**/__pycache__'): if ignores and path.match(ignores): continue shutil.rmtree(path) if __name__ == "__main__": from pathlib import Path clean_pycache(Path(__file__).parents[2])
299
101
from dataclasses import dataclass from typing import List from orbsim_language.orbsim_ast.expression_node import ExpressionNode @dataclass class TupleCreationNode(ExpressionNode): elems: List[ExpressionNode]
212
56
import sys import numpy as np import pandas as pd def df_add_keys(df): ax = df['fof_halo_angmom_x'] ay = df['fof_halo_angmom_y'] az = df['fof_halo_angmom_z'] mag = np.sqrt(ax**2 + ay**2 + az**2) dx = ax/mag dy = ay/mag dz = az/mag df['fof_halo_angmom_dx'] = dx df['fof_halo_angmom_d...
1,345
629
from sys import stdout def print_action(action): def print_action_decorator(function): def puts(string): stdout.write(string) stdout.flush() def function_wrapper(*args, **kwargs): puts("{0}... ".format(action)) return_value = function(*args, **kwargs...
649
193
import argparse import csv import os parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help="Input path of the missing urls CSV file") parser.add_argument('-o', '--output', help="Output directory where the new CSV files will be stored") parser.add_argument('-q', '--quiet', action='store_true', he...
1,845
579
# -*- coding: utf-8 -*- """ Created on Tue Nov 21 11:20:06 2017 @author: NPB """ import cv2 import pickle def loadDictionary(filename): with open(filename,"rb") as fd: feat=pickle.load(fd) return feat["accuracy"],feat["labels"], feat["dictionary"] def loadAux(filename, flagPatches): if flagPatch...
2,302
881
# @Created Date: 2019-12-08 06:46:49 pm # @Filename: api.py # @Email: 1730416009@stu.suda.edu.cn # @Author: ZeFeng Zhu # @Last Modified: 2020-02-16 10:54:32 am # @Copyright (c) 2020 MinghuiGroup, Soochow University from typing import Iterable, Iterator, Optional, Union, Generator, Dict, List from time import perf_coun...
22,087
7,134
''' Function and classes representing statistical tools. ''' __author__ = ['Miguel Ramos Pernas'] __email__ = ['miguel.ramos.pernas@cern.ch'] from hep_spt.stats.core import chi2_one_dof, one_sigma from hep_spt.core import decorate, taking_ndarray from hep_spt import PACKAGE_PATH import numpy as np import os from scip...
9,409
3,292
import tornado import logging import httplib try: import simplejson as json except ImportError: import json from octopus.core.framework.wsappframework import WSAppFramework, MainLoopApplication from octopus.core.framework.webservice import MappingSet from octopus.core.communication.http import Http400 from oc...
3,088
870
from provstore.document import Document from provstore.bundle_manager import BundleManager from provstore.bundle import Bundle
127
28
from __future__ import annotations import typing as tp from loguru import logger class SingletonMeta(type): """ The Singleton class ensures there is always only one instance of a certain class that is globally available. This implementation is __init__ signature agnostic. """ _instances: tp.Dic...
834
246
# Login to https://developer.spotify.com/dashboard/, create an application and fill these out before use! client_id = "" client_secret = ""
139
38
import cv2 import numpy as np import matplotlib.image as mpimg from pathlib import Path from model import * CAMERA_STEERING_CORRECTION = 0.2 def image_path(sample, camera="center"): """ Transform the sample path to the repository structure. Args: sample: a sample (row) of the data d...
7,871
2,560
import json import logging from typing import List import os import sys import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer, BertTokenizer from vilbert.vilbert import BertConfig from utils.cli import get_parser from utils.dataset.commo...
4,848
1,684
from modeledcommandparameter import * from pseudoregion import * class Refp(ModeledCommandParameter, PseudoRegion): """ Reference particle """ begtag = 'REFP' endtag = '' models = { 'model_descriptor': {'desc': 'Phase model', 'name': 'phmodref', ...
3,184
1,057
import numpy as np import torch from torch.nn import functional as F from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms from torchvision.utils import save_image from utils.fast_tensor_dataloader import FastTensorDataLoader def get_mnist_dataloaders(batch_size=128, path_to_d...
10,620
3,724
from flask import ( Blueprint,session, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from anonymail.auth import login_required from anonymail.db import get_db import datetime now = datetime.datetime.now() current_year = now.year bp = Blueprint('posts', __name__) @b...
1,780
532
# from python-decouple import config from flask import Flask, request, jsonify from .obj_detector import object_detection # from flask_sqlalchemy import SQLAlchemy from dotenv import load_dotenv load_dotenv() def create_app(): app = Flask(__name__) @app.route('/img_summary', methods=['GET']) ...
959
303
from .subroutine import subroutine from parameters.string_parameter import string_parameter as String from parameters.numeric_parameter import numeric_parameter as Numeric from parameters.array_parameter import array_parameter as Array from ast import literal_eval class array_subroutine(subroutine): """Subroutine...
2,579
660
import requests import json from config import config from logbook import Logger, StreamHandler import sys StreamHandler(sys.stdout).push_application() log = Logger('auth') class Auth(object): def __init__(self): self.config = config self.auth_code = self.token =None def get_auth_code(self):...
1,164
334
# Copyright (c) 2019 Bita Hasheminezhad # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # #942: `fold_left`, `fold_right` and `fmap` do not work with a lazy function import numpy as np from phylanx import Phyl...
1,540
564
# Die Fibonacci-Folge ist die unendliche Folge natürlicher Zahlen, die (ursprünglich) mit zweimal der Zahl 1 beginnt # oder (häufig, in moderner Schreibweise) zusätzlich mit einer führenden Zahl 0 versehen ist. # Im Anschluss ergibt jeweils die Summe zweier aufeinanderfolgender Zahlen die unmittelbar danach folgende Za...
644
262
import numpy as np import dnnlib.tflib as tflib from training import dataset tflib.init_tf() class LabelGenerator: def __init__(self, tfrecord_dir: str = None): if tfrecord_dir: self.training_set = dataset.TFRecordDataset(tfrecord_dir, shuffle_mb=0) self.labels_available = True ...
4,063
1,340
from collections import namedtuple import pytest from rest_framework.authtoken.models import Token from tests.conftest import twilio_vcr from apostello import models StatusCode = namedtuple("StatusCode", "anon, user, staff") @pytest.mark.slow @pytest.mark.parametrize( "url,status_code", [ ("/", Sta...
3,333
1,359
""" A *really* simple guestbook flask app. Data is stored in a SQLite database that looks something like the following: +------------+------------------+------------+ | Name | Email | signed_on | +============+==================+============+ | John Doe | jdoe@example.com | 2012-05-28 | +------...
2,491
768
import sqlite3 import base64 import requests import json import hashlib import logging from lingvodoc.queue.client import QueueClient def get_dict_attributes(sqconn): dict_trav = sqconn.cursor() dict_trav.execute("""SELECT dict_name, dict_identificator, ...
25,673
7,008
""" Tests the code. """ from torch.utils.data import DataLoader from models import MODELS from pipeline import argument_parser from pipeline.datasets import DATASETS, get_dataset from run import main def test_datasets(): """ Tests all the datasets defined in pipeline.datasets.DATASETS. """ for ds_name in DA...
1,550
494
# -*- coding: utf-8 -*- import numpy as np import random import os import sys import torch from src.agent import ( EpsilonGreedyAgent, MaxAgent, RandomAgent, RandomCreateBVAgent, ProbabilityAgent, QAgent, QAndUtilityAgent, MultiEpsilonGreedyAgent, MultiMaxAgent, MultiProbabilit...
2,185
785
def func(x, y, z): """ :param x: <caret> :param y: :param z: :return: """
101
47
from hashlib import sha3_256 import magic from enums import Dep, MangoType MIME_MTYPE = { 'text/plain': MangoType.text, 'audio/flac': MangoType.audio_flac, 'audio/wav': MangoType.audio_wav, 'image/png': MangoType.picture_png, 'image/jpeg': MangoType.picture_jpg, 'video/x-matroska': MangoType....
1,439
591
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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 ...
2,258
731
# Generated by Django 3.1.2 on 2022-02-27 17:59 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import versatileimagefield.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(setting...
1,529
466
#!/usr/bin/python # -*- coding: utf-8 -*- # python version 2.7 # Cemal Melih Tanis (C) ############################################################################### import os import shutil import datetime from pytz import timezone from uuid import uuid4 from definitions import * import fetchers import cal...
424,971
175,053
import sys import subprocess def main(): edgeRcPath = sys.argv[1] branch = sys.argv[2] navlist = sys.argv[3:] domain = 'https://console.stage.redhat.com' if 'prod' in branch: domain = 'https://console.redhat.com' if 'beta' in branch: domain += '/beta' purgeAssets = ['fed-mod...
898
304
################################################# #****************LINEAR MODELS******************# ################################################# CLASSIF_LOGISTIC_REGRESSION = {"C":{"range": (1., 100.), "type": 1}, "tol":{"range": (0.0001,0.9999), "type": 1}} ...
3,261
1,119
# -*- coding: utf-8 -*- from datetime import timedelta import logging from delorean import Delorean import tornado.web from gryphon.dashboards.handlers.admin_base import AdminBaseHandler from gryphon.lib.exchange import exchange_factory from gryphon.lib.models.order import Order from gryphon.lib.models.exchange impor...
6,300
1,916
import yfinance as yf import numpy as np import pandas as pd class StockSetup(): """ The object of this class includes a dataframe, a classifier trained on it and some associated test and prediction stats """ def __init__(self, ticker: str, target:int) -> None: """Initialize the ob...
4,897
1,612
from collections import OrderedDict from .base import ApiBase import logging logger = logging.getLogger(__name__) class CustomRecords(ApiBase): SIMPLE_FIELDS = [ 'allowAttachments', 'allowInlineEditing', 'allowNumberingOverride', 'allowQuickSearch', 'altName', 'au...
1,893
570
import graphene from schema.queries import Query from schema.mutations import Mutations schema = graphene.Schema(query=Query, mutation=Mutations)
147
42
""" This module contains a number of other commands that can be run via the cli. All classes in this submodule which inherit the baseclass `airbox.commands.base.Command` are automatically included in the possible commands to execute via the commandline. The commands can be called using their `name` property. """ from...
1,710
466
#!/usr/bin/python # Copyright 2015 Google 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 appli...
1,881
667
import re from ava.common.check import _ValueCheck, _TimingCheck from ava.common.exception import InvalidFormatException # metadata name = __name__ description = "checks for shell injection" class ShellInjectionCheck(_ValueCheck): """ Checks for Shell Injection by executing the 'id' command. The payload use...
3,421
1,018
import os import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import scipy.io as sio import cPickle import subprocess import uuid def Get_Class_Ind(Class_INT): concepts = [] concepts.append(('Animal', [ 'n01443537', 'n01503061', 'n01639765', 'n01662784', 'n01674464', 'n01726692'...
5,536
2,467
import argparse import logging import os import sys import numpy as np from tqdm import tqdm import time import torch import torch.nn as nn from torch import optim from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from models.unet import UNet from models.nested_unet import Nest...
5,967
2,037
from booking.constants import myConstant
41
12
import urllib import xml.etree.ElementTree as ET address = raw_input('Enter location: ') url = address print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved',len(data),'characters' tree = ET.fromstring(data) sumcount=count=0 counts = tree.findall('.//count') for i in counts: co...
411
157
from flask import Flask from flask.ext.tweepy import Tweepy app = Flask(__name__) app.config.setdefault('TWEEPY_CONSUMER_KEY', 'sve32G2LtUhvgyj64J0aaEPNk') app.config.setdefault('TWEEPY_CONSUMER_SECRET', '0z4NmfjET4BrLiOGsspTkVKxzDK1Qv6Yb2oiHpZC9Vi0T9cY2X') app.config.setdefault('TWEEPY_ACCESS_TOKEN_KEY', '1425531373-...
882
419
from __future__ import absolute_import from .__main__ import main from .sftp import * from .sync import * __version__ = '0.6'
128
44
"""Simple predictor using random forest """ import pandas as pd import numpy as np import math from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing from sklearn.metrics import mean_absolute_error from sklearn.metrics import f1_score fr...
2,636
865
def showSpeed(func, r, *args): '''Usage: showSpeed(function, runs) You can also pass arguments into <function> like so: showSpeed(function, runs, <other>, <args>, <here> ...) showSpeed() prints the average execution time of <function> over <runs> runs ''' def formatted(f): import re ...
2,135
678
#!/usr/bin/env python u""" polygonize.py Yara Mohajerani (Last update 09/2020) Read output predictions and convert to shapefile lines """ import os import sys import rasterio import numpy as np import getopt import shapefile from skimage.measure import find_contours from shapely.geometry import Polygon,LineString,Poin...
9,106
4,057
import numpy as np import pytest from autofit.graphical import ( EPMeanField, LaplaceOptimiser, EPOptimiser, Factor, ) from autofit.messages import FixedMessage, NormalMessage np.random.seed(1) prior_std = 10. error_std = 1. a = np.array([[-1.3], [0.7]]) b = np.array([-0.5]) n_obs = 100 n_features,...
4,573
1,870
import math from torch import nn import torch import torch.nn.functional as F import linear_cpu as linear class LinearFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, weights, bias, params): is_bias = int(params[0]) outputs = linear.forward(input, weights, bias, is_bi...
1,716
571
""" Files API """ import boto3 import os import io from datetime import datetime, timedelta import json import time from s3_helpers import write_s3_json, read_s3_json, delete_s3_key from api_helpers import json_serial from search_files import crawl_available_files, update_pdf_fields from dynamo_helpers import add_file_...
11,907
3,510
# coding: utf-8 """ """ import flask import flask_login import json from flask_babel import _ from . import frontend from .. import logic from ..logic.object_permissions import Permissions from ..logic.security_tokens import verify_token from ..logic.languages import get_languages, get_language, get_language_by_lang...
40,240
10,984
#!/usr/bin/env python3 import codecs import os import re from setuptools import setup with open('README.md', 'r') as f: readme = f.read() here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*f...
1,474
510
def or_gate(a:int, b:int): return a | b def and_gate(a:int, b:int): return a & b def nor_gate(a:int, b:int): return 1 - (a | b) def nand_gate(a:int, b:int): return 1 - (a | b) def xor_gate(a:int, b:int): return a ^ b def xnor_gate(a:int, b:int): return 1 - (a ^ b)
311
158
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------- # Copyright (c) 2016 The Regents of the University of California # # This file is part of kevlar (http://github.com/dib-lab/kevlar) and is # licensed under the MIT license: see LICENSE. # ----...
10,522
4,073
def get_magic_triangle(n): triangle = [[1], [1, 1]] for _ in range(2, n): row = [1] last_row = triangle[-1] for i in range(1, len(last_row)): num = last_row[i-1] + last_row[i] row.append(num) row.append(1) triangle.append(row) ret...
361
141
# -*- coding: utf-8 -*- import os import telebot import time import random import threading from emoji import emojize from telebot import types from pymongo import MongoClient import traceback token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) #client=MongoClient(os.environ['database']) #db=client. #u...
1,353
470
from .api import MojangApi from .dispatcher import Dispatch from .exceptions import ( ApiException, ResourceNotFound, InternalServerException, UserNotFound, ) __version__ = "0.0.1a" __license__ = "MIT" __author__ = "capslock321"
262
93
from loguru import logger from channels.db import database_sync_to_async from schema.base import query from .models import Player from .schemata import PlayerConnection @query.field("allPlayers") @database_sync_to_async def resolve_all_players(root, info, after='', before='', first=0, last=0): players = [p for ...
553
171
import asyncio import logging import random import time from abc import ABC from typing import Literal, Optional import aiohttp import discord from redbot.core import Config, bank, checks, commands from redbot.core.utils.chat_formatting import box from redbot.core.utils.menus import DEFAULT_CONTROLS, menu from tabulat...
50,039
13,647
""" Deep Learning """ import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.preprocessing import StandardScaler f...
2,118
769
import re # import all settings-modules here, so we can only import this module to get them all from python_settings.settings_activatable import * from python_settings.settings_child_placeholder import * from python_settings.settings_choice import * from python_settings.settings_comment import * from python_settings.s...
1,529
403
# -*- coding: utf-8 -*- import timeit from functools import wraps from titan.manages.global_manager import GlobalManager def run_time_sum(func): @wraps(func) def wrapper(*args, **kwargs): start = timeit.default_timer() __func = func(*args, **kwargs) end = timeit.default_timer() ...
460
146
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved. # See "LICENSE" file for license. import re open_r_str = r'\<\?cs\s*([a-zA-Z]+)([:]|\s)' close_r_str = r'\<\?cs\s*/([a-zA-Z]+)\s*\?\>' open_r = re.compile(open_r_str) close_r = re.compile(close_r_str)
262
128
# -*- coding: utf-8 -*- # Copyright 2019 Subteno IT # License MIT License import requests import xmltodict import string import random import io class PrestaConnectError(RuntimeError): pass class PrestaConnect: _BOUNDARY_CHARS = string.digits + string.ascii_letters _STATUSES = (200, 201) def __ini...
3,142
980
import bpy from bpy.types import Panel from bpy.props import * import math default_surface_names = [ ("bcc", "bcc", "", 1), ("schwarzp", "schwarzp", "", 2), ("schwarzd", "schwarzd", "", 3), ("gyroid", "gyroid", "", 4), ("double-p", "double-p", "", 5), ("double-d", "double-d", "", 6), ("doub...
2,884
1,065
import argparse import torch from torch.nn import Softplus from pina import PINN, Plotter from pina.model import FeedForward from problems.burgers import Burgers1D class myFeature(torch.nn.Module): """ Feature: sin(pi*x) """ def __init__(self, idx): super(myFeature, self).__init__() s...
1,702
611
""" In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the same depth, but have different parents. We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. Re...
2,072
718
from .configuration_entry import ConfigurationEntry from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Action(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__i...
456
117
from collections import namedtuple Style = namedtuple('Style', 'name fg bg') default_pal = { Style('inv-black', 'black', 'light gray'), Style('green-bold', 'dark green,bold', ''), Style('red-bold', 'dark red,bold', ''), Style('blue-bold', 'dark blue,bold', ''), St...
1,119
407
#!/usr/bin/env python3 import tensorflow as tf x=tf.Variable(0.5) y = x*x sess = tf.Session() sess.run(tf.global_variables_initializer()) print("x =",sess.run(x)) print("y =",sess.run(y))
189
82
import os import random import cv2 import numpy as np from gen_textures import add_noise, texture, blank_image from nist_tools.extract_nist_text import BaseMain, parse_args, display class CombineMain(BaseMain): SRC_DIR = 'blurred' DST_DIR = 'combined_raw' BG_DIR = 'backgrounds' SMPL_DIR = 'combined...
3,468
1,237
# this function looks for either the encounter date or the patient's date of birth # so that we can avoid duplicate encounters. import time def look_for_date (date_string, driver): print('looking for date') date_present = False for div in driver.find_elements_by_class_name('card.my-4.patient-card.assessme...
1,205
355
from flask import g from flask_restplus import Resource, marshal from app import db from app.api.namespaces.token_namespace import token_ns, token from app.api.security.authentication import basic_auth, token_auth @token_ns.route('', strict_slashes=False) @token_ns.response(401, 'Unauthenticated') @token_ns.response...
1,047
332
# -*- coding: utf-8 -*- # low --> Starting index, high --> Ending index class Solution(object): def quickSort(self, arr, low, high): if low < high: pi = self.partition(arr, low, high) self.quickSort(arr, low, pi - 1) self.quickSort(arr, pi + 1, high) return a...
1,025
395
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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 file # to you under the Apache Licen...
4,816
1,545
import json def dummy_function(): return [] def test_norun(): this shall not run if __name__ == '__main__': test_norun()
150
61
# -*- coding: utf-8 -*- """ # @file name : module_containers.py # @author : tingsongyu # @date : 2019-09-20 10:08:00 # @brief : 模型容器——Sequential, ModuleList, ModuleDict """ import torch import torchvision import torch.nn as nn from collections import OrderedDict # ============================ Sequenti...
3,283
1,305
import pytest import shutil as sh import pandas as pd from pathlib import Path from glob import glob import libs.dirs as dirs from libs.iteration_manager import SampleImages from libs.utils import copy_files, replace_symbols class Te...
2,124
642
data={ "田中広輔":"赤く燃え上がる 夢見たこの世界で 研ぎ澄ませそのセンス 打てよ広輔", "長野久義":"歓声を背に受け 頂をみつめて 紅一筋に 突き進め長野", "安部友裕":"新しい時代に 今手を伸ばせ 終わらぬ夢の先に 導いてくれ", "堂林翔太":"光り輝く その道を 翔けぬけて魅せろ 堂林SHOW TIME!", "會澤翼":"いざ大空へ翔ばたけ 熱い想い乗せ 勝利へ導く一打 決めろよ翼", "菊池涼介":"【前奏:始まりの鐘が鳴る 広島伝説】\n光を追い越して メーター振りきり駆け抜けろ 止まらないぜ 韋駄天菊池", "野間峻祥":"鋭い打球飛ばせ 自慢...
558
648
BASE_URL = 'https://api.themoviedb.org/3'
42
22
speed(0) def make_square(i): if i % 2 == 0: begin_fill() for i in range(4): forward(25) left(90) end_fill() penup() setposition(-100, 0) pendown() for i in range (6): pendown() make_square(i) penup() forward(35)
284
121
""" Module for reading data from 'linearX.csv' and 'linearY.csv' """ import numpy as np def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"): """ Loads the X, Y matrices. Splits into training, validation and test sets """ X = np.genfromtxt(x_file) Y = np.genfromtxt(y_...
771
303
from django import forms from .models import Experiment class CreateExperimentForm(forms.ModelForm): class Meta: model = Experiment fields = ['name', 'description', 'dataset'] def save(self, commit=True): self.instance.experimenter = self.request.user return super().save(comm...
331
90
from datetime import datetime from dateutil.relativedelta import relativedelta class Timex: """ Simply represents a Timex object. Main reason for this class is that the datetime class (and other Python equivalents) do not allow to reflect a month or a day but only a single point in time. """ _dat...
3,377
1,090
import argparse import json from os import openpty def create_dic_question_id(path): set_name = ['train', 'val', 'test'] dic_qid = {} for i in range(len(set_name)): print("Processing, ", set_name[i]) annot_path = path.replace("change", set_name[i]) annot_fi = open(annot_path) ...
1,172
405