text
string
size
int64
token_count
int64
from django.forms import ModelForm from updates.models import Post class Postform(ModelForm): class Meta: model = Post fields = ['title','body','date']
159
49
#%% [markdown] # # We will load EEG data from the lab and attemp to build a classifier that distinguishes between learners and non-learners #%% import mne import numpy as np import os.path import glob import re import pandas as pd # try to enable cuda support to speed up filtering, make sure the MNE_USE_C...
1,965
756
# Exercício 066 soma = total = 0 while True: n = int(input('Digite um valor [999 para parar]: ')) if n == 999: break soma += n total += 1 print(f'O total de números digitados foi {total} e a soma deles vale {soma}')
241
98
import json import os from osdf.utils import api_data_utils from collections import defaultdict BASE_DIR = os.path.dirname(__file__) with open(os.path.join(BASE_DIR, "placement-tests/request.json")) as json_data: req_json = json.load(json_data) class TestVersioninfo(): # # Tests for api_data_utils.py # d...
749
255
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import integrate, optimize from scipy.signal import savgol_filter from dane import population as popu dias_restar = 4 # Los últimos días de información que no se tienen en cuenta dias_pred = 31 # Días sobre los cuáles se hará la predic...
10,396
4,040
import aiohttp from aiohttp import web from aiohttp_session import get_session import asyncio import logging from pathlib import Path logger = logging.getLogger(__name__) routes = web.RouteTableDef() @routes.get('/api/admin/course/{course_id}/reload_course') async def reload_course(req): session = await get_se...
733
235
#!/usr/bin/env python # coding: utf-8 # In[7]: import os write_to_csv_file = 'million_song_subset.csv' csv_file_read = open(write_to_csv_file,'r') csv_file_write = open(write_to_csv_file,'a') while True: next_line = csv_file_read.readline() if not next_line: break csv_file_size = os.pat...
751
300
# Copyright (c) 2013, Regents of the University of California # 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 # list o...
4,444
1,667
from typing import List, Tuple import numpy as np import pandas as pd import os import logging class CopelandVoter(): def __init__(self) -> None: self.__voting_matrix: np.ndarray = None self.__voting_sum: List[Tuple[str, float]] = [] @property def voting_matrix(self) -> np.ndarray: ...
4,351
1,224
from flask_wtf import FlaskForm from wtforms import validators from wtforms.fields import * class login_form(FlaskForm): email = EmailField('Email Address', [ validators.DataRequired(), ]) password = PasswordField('Password', [ validators.DataRequired(), validators.length(min=6, m...
2,528
672
# -*- coding: utf-8 -*- # # Copyright (c) 2017-2020 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ Docker specific functions - used when trying to retrieve packages when given a Dockerfile """ import logging import os import re import sys from tern.classes.docker_image import DockerImag...
11,220
3,075
import os import firebase_admin from firebase_admin import credentials, messaging from django.conf import settings from utils import common, constants logger = common.get_system_logger() cred = credentials.Certificate(os.path.join( settings.BASE_DIR, 'data', 'sales-yang-firebase-adminsdk-2ga7e-17745491...
2,003
822
# coding=utf-8 DEBUG = True TESTING = True SECRET_KEY = 'secret_key for test' # mongodb MONGODB_SETTINGS = { 'db': 'firefly_test', 'username': '', 'password': '', 'host': '127.0.0.1', 'port': 27017 } # redis cache CACHE_TYPE = 'redis' CACHE_REDIS_HOST = '127.0.0.1' CACHE_REDIS_PORT = 6379 CACHE_R...
1,944
831
import numpy as np from pyhack.py_runko_aux import * from pyhack.boris import * def boris_staggered(tile,dtf=1): c = tile.cfl cont = tile.get_container(0) pos = py_pos(cont) vel = py_vel(cont) E,B = py_em(cont) nq = pos.shape[0] dims = pos.shape[1] vel = boris_rp(vel,E,B,c,cont.q,dtf...
981
475
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. class mockData: """dictionary of mocking data for the mocking tests""" # dictionary to hold the mock data _data={} # function to add mock data to the _mock_data dictionary def _add(se...
1,806
778
#!/usr/bin/env python3 import rospy # Import eager packages from eager_core.utils.file_utils import launch_roscore, load_yaml from eager_core.eager_env import EagerEnv from eager_core.objects import Object from eager_core.wrappers.flatten import Flatten from eager_bridge_pybullet.pybullet_engine import PyBulletEngine...
2,134
642
# Copyright 2019 The Keras Tuner 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
3,811
1,220
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling...
14,129
4,788
from flask import Flask, render_template, flash, abort, redirect, url_for, request import os import common import json import numbers import urllib.parse import pandas as pd from datetime import datetime from math import log10, floor base_dir = '/home/nick/Data/_ensembles' app = Flask(__name__) app.config['ENV'] = 'de...
16,392
5,137
#! /usr/bin/python2.7 # -*- coding: utf8 -*- import datetime # from plugin_ajaxselect import AjaxSelect if 0: from gluon import db, Field, auth, IS_EMPTY_OR, IS_IN_DB, current, URL response = current.response response.files.insert(5, URL('static', 'plugin_ajaxselect/plugin_ajaxselect.js...
6,151
2,272
import tkinter as tk from tkinter import filedialog from urllib.request import urlopen from pathlib import Path from tkinter import ttk import numpy as np import base64 import io import re from src.theme import theme from src.algorithm import blosum from src.utils import RichText def qopen(path:str): '''Opens and...
12,559
4,275
import numpy as np import re def apply_colormaps_based_on_mask(mask, data_for_inside_mask, data_for_outside_mask, colormap_inside_mask, colormap_outside_mask): """ Returns the combination of applying two colormaps to two datasets on two mutually exclusive sets of pixels a...
4,050
1,208
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2012-2015 BigML # # 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 requi...
4,242
1,323
#!/usr/bin/env python """ Copyright (c) 2021 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
3,649
1,460
# -- coding: utf-8 -- from section_base import * from section_map_item import * from section_header import * from section_string_id import * from section_type_id import * from section_proto_id import * from section_field_id import * from section_method_id import * from section_class_def import * from section_type_list...
1,838
556
a = int(input()) b = int(input()) if a >=b*12: print("Buy it!") else: print("Try again")
91
43
# coding=utf-8 # init
22
11
import roslib;roslib.load_manifest('kobuki_dashboard') import rospy import diagnostic_msgs from rqt_robot_dashboard.dashboard import Dashboard from rqt_robot_dashboard.widgets import ConsoleDashWidget, MenuDashWidget, IconToolButton from python_qt_binding.QtWidgets import QMessageBox, QAction from python_qt_binding.Q...
4,416
1,388
import msgpack import lz4.block from msgpack.ext import Timestamp, ExtType import re def __map_obj(obj, key_map): if not isinstance(key_map, list): raise Exception('The key_map should be a list') elif len(obj) != len(key_map): raise Exception( 'The key_map list has length {} wherea...
3,339
1,186
from __future__ import absolute_import, division, print_function import glob # Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z" _version_major = 0 _version_minor = 1 _version_micro = '' # use '' for first of series, number for 1 and above _version_extra = 'dev' # _version_extra = '' # Uncom...
2,169
697
from graphics import * import math import random windowWidth = 400 windowHeight = 400 fireflyRadius = 3 win = GraphWin("Fireflies",windowWidth,windowHeight,autoflush=False) win.setBackground('black') closeWindow = False fireflies = [] flashedFliesOpenSet = [] # flies that need to reset urge of neighbors flashedFliesC...
3,765
1,583
# -*- coding: utf8 from gb.randomkit.random import RNG from gb.samplers import BaseSampler from gb.samplers import CollapsedGibbsSampler from gb.stamps import Timestamps from gb.sloppy import SloppyCounter from numpy.testing import assert_equal import numpy as np def test_get_probability(): d = {} d[0] = ...
2,350
1,084
#=========================================================================== # # Primary SMA API. # #=========================================================================== import socket from .. import util from . import Auth from . import Reply from . import Request #=============================================...
9,163
3,085
import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow from PyQt5.QtCore import QCoreApplication, QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWebEngineWidgets import QWebEngineProfile class MainWindowWeb(QMainWindow): def _...
1,988
656
# 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, software # distributed under t...
2,487
899
import tensorflow as tf """Class for KDD10 percent GAN architecture. Generator and discriminator. """ learning_rate = 0.00001 batch_size = 50 layer = 1 latent_dim = 32 dis_inter_layer_dim = 128 init_kernel = tf.contrib.layers.xavier_initializer() def generator(z_inp, is_training=False, getter=None, reuse=False): ...
4,137
1,185
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='setuptools-wotmod', version='0.2', packages=find_packages(), description='setuptools integration for creating World of Tanks mods', long_description=open('README.md').read(), author='jhakonen', url='https://gith...
646
222
import os from glob import glob import pandas as pd from tqdm import tqdm from constants import SNPS_DATA_PATH, SNPS_DATA_FOLDER, SNPS_DATA_FILE_NAME from services.docker_runner import Hg38dbDockerRunner def fetch_snps_data(snps_file_path): """ Fetch SNPs data from hg38 db :param snps_file_path: the path ...
2,264
833
from django.http import HttpResponse from django.shortcuts import render, redirect from lab1.views import login def docs(request): if not request.user.is_authenticated: return redirect(login.login_view) return render(request, 'docs.html')
258
73
import logging import socket import socketserver import struct import typing from ssdp.entity import * from ssdp.network import * logger = logging.getLogger("ssdp.socketserver") class RequestHandler(socketserver.BaseRequestHandler): def handle(self): packet_bytes = self.request[0] try: ...
2,154
656
#!/usr/bin/python from numpy import * from mpi4py import MPI from matplotlib.pyplot import * #MPI setting try: COMM=MPI.COMM_WORLD SIZE=COMM.Get_size() RANK=COMM.Get_rank() except: COMM=None SIZE=1 RANK=0 __all__=['mpido'] def mpido(func,inputlist,bcastouputmesh=True): ''' MPI for list...
1,040
412
import unittest import coverage from flask_script import Manager from project import create_app, db from project.api.models import User COV = coverage.coverage( branch=True, include='project/*', omit=[ 'project/tests/*', 'project/server/config.py', 'project/server/*/__init__.py' ...
1,480
483
# Copyright (c) cocotb contributors # 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 list of conditions a...
2,691
833
# Copyright (c) 2020. Robin Thibaut, Ghent University from os.path import join as jp import numpy as np from tomopal.crtomopy.crtomo.crc import ( Crtomo, datread, import_res, mesh_geometry, mtophase, ) from ..parent import inventory from ...geoview.diavatly import model_map # To plot results #...
8,259
3,048
from genetica.dna import DNA, genify from genetica.model import Genetica
72
24
# SPDX-License-Identifier: MIT # # Copyright (c) 2021 The Anvil Extras project team members listed at # https://github.com/anvilistas/anvil-extras/graphs/contributors # # This software is published at https://github.com/anvilistas/anvil-extras from functools import cache __version__ = "1.4.0" def __dir__(): ret...
1,015
318
import os import os.path as op import numpy as np import pandas as pd import cv2 import tensorflow as tf import settings from config import opts from tfrecords.tfrecord_reader import TfrecordReader import utils.util_funcs as uf import utils.convert_pose as cp from model.synthesize.synthesize_base import SynthesizeMult...
13,984
5,008
# coding: utf-8 import os from io import BytesIO import pytest from requests import compat from requests.utils import ( address_in_network, dotted_netmask, get_auth_from_url, get_encodings_from_content, get_environ_proxies, guess_filename, is_ipv4_address, is_valid_cidr, requote_uri, select_proxy, ...
7,018
2,526
# ----------------------------------------------------------------------------- # Clorm ORM FactBase implementation. FactBase provides a set-like container # specifically for storing facts (Predicate instances). # ------------------------------------------------------------------------------ import abc import io impor...
37,008
10,221
# -*- coding: utf-8 -*- # # ***** BEGIN GPL LICENSE BLOCK ***** # # -------------------------------------------------------------------------- # Blender 2.5 Extensions Framework # -------------------------------------------------------------------------- # # Authors: # Doug Hammond # # This program is free software; yo...
13,470
3,663
# pylint: disable=invalid-name ''' Pytests for the common utilities included in this package. Includes: - conversions.py - specs.py - utils.py To run the tests, type the following in the top level repo directory: python -m pytest --nat-file [path/to/gribfile] --prs-file [path/to/gribfile] ''' from...
16,305
4,850
#!/usr/bin/env python # package: org.ggp.base.util.symbol.grammar import threading class SymbolFormatException(Exception): source = '' def __init__(self, message, source): super(SymbolFormatException, self).__init__(message) self.source = source def getSource(self): return self.s...
6,448
1,776
#!/usr/bin/env python """ /******************************************************************************* * Copyright (c) cortical.io GmbH. All rights reserved. * * This software is confidential and proprietary information. * You shall use it only in accordance with the terms of the * license agreement you ente...
948
233
# [weight, value] I = [[4, 8], [4, 7], [6, 14]] k = 8 def knapRecursive(I, k): return knapRecursiveAux(I, k, len(I) - 1) def knapRecursiveAux(I, k, hi): # final element if hi == 0: # too big for sack if I[hi][0] > k: return 0 # fits else: retur...
705
287
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .images import ImageInferenceJob from .job import InferenceJob __all__ = [ 'InferenceJob', 'ImageInferenceJob', ]
232
80
# Import a library of functions called 'pygame' import pygame # Initialize the game engine pygame.init() # Define the colors we will use in RGB format BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Set the height and width of the screen size = [491, 700] screen =...
3,592
1,747
from pyte import tokens, util from pyte.superclasses import _PyteAugmentedValidator, _PyteOp from pyte.util import PY36 class FOR_LOOP(_PyteOp): """ Represents a for loop. """ def __init__(self, iterator: _PyteAugmentedValidator, body: list): """ Represents a for operator. :p...
2,929
944
from gpioapi import GpioAPI import rx MAX_TEMP = 38 COOL_TEMP = 30 class HotTubAPI: def __init__(self): self.gpioapi = GpioAPI(None) def transmissions(self): return self.gpioapi.transmission_subject def heat_up(self): reached_max_temp = self.gpioapi.transmission_subject.pipe( op.filter(lamb...
1,212
466
#!/usr/bin/python # Programmer : Yang Zhang # Contact: zocean636@gmail.com # Last-modified: 24 Jan 2019 15:20:08 import os,sys,argparse def parse_arg(): ''' This Function Parse the Argument ''' p=argparse.ArgumentParser( description = 'Example: %(prog)s -h', epilog='Library dependency :') p.add_argument(...
7,711
2,789
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy 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)...
5,404
1,842
# This little bit of magic fills the __all__ list # with every plugin name, and means that calling: # from plugins import * # within inmembrane.py will import every plugin import pkgutil __all__ = [] for p in pkgutil.iter_modules(__path__): __all__.append(p[1])
268
84
import schema from dvc.exceptions import DvcException from dvc.config import Config from dvc.dependency import SCHEMA, urlparse from dvc.dependency.base import DependencyBase from dvc.output.s3 import OutputS3 from dvc.output.gs import OutputGS from dvc.output.local import OutputLOCAL from dvc.output.hdfs import Outp...
1,984
640
# DomirScire import math import os import random import re import sys import collections if __name__ == '__main__': s = sorted(input().strip()) s_counter = collections.Counter(s).most_common() s_counter = sorted(s_counter, key=lambda x: (x[1] * -1, x[0])) for i in range(0, 3): print(s_counter[i...
343
126
import math import torch import torch.nn as nn from torch.nn import functional as F class KLRegression(nn.Module): """KL-divergence loss for probabilistic regression. It is computed using Monte Carlo (MC) samples from an arbitrary distribution.""" def __init__(self, eps=0.0): super()._...
2,600
841
""" Basic building blocks for generic class based views. We don't bind behaviour to http method handlers yet, which allows mixin classes to be composed in interesting ways. """ from rest_framework import status from rest_framework import mixins from custom.response import JsonResponse class CreateModelMixin(mixins....
2,478
749
import torch.cuda import torch.nn as nn import torch.nn.functional as F device = 'cuda' if torch.cuda.is_available() else 'cpu' class Actor(nn.Module): def __init__(self, state_space, action_space, hidden_size=64): super(Actor, self).__init__() self.linear_in = nn.Linear(state_space, hidden_size...
893
325
# coding=utf-8 import arrow from bs4 import BeautifulSoup from digesters.base_digester import BaseDigester TEMPLATE = """<html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>Atlassian HipChat</title> </head> <body style="box-sizing: border-box; height: 100%; width: 100%;...
7,284
2,322
from .FictionBook2 import FictionBook2 from .Author import Author from .TitleInfo import TitleInfo from .DocumentInfo import DocumentInfo
138
35
#!/usr/bin/env python # encoding: utf-8 # Copyright (C) 2015 Chintalagiri Shashank # Released under the MIT license. """ Simple Deployment Example ------------------------- """ from vendor_monitor import worker from twisted.internet import reactor import logging logging.basicConfig(level=logging.INFO) if __name_...
374
125
import os import shutil import tempfile import numpy as np from yt.loaders import load, load_uniform_grid from yt.testing import ( assert_array_equal, assert_fname, fake_random_ds, requires_file, requires_module, ) from yt.utilities.answer_testing.framework import data_dir_load from yt.visualizati...
3,746
1,572
""" Test the genetic optimizer driver """ import unittest import random from openmdao.main.datatypes.api import Float, Array, Enum, Int, Str from pyevolve import Selectors from openmdao.main.api import Assembly, Component, set_as_top, Driver from openmdao.lib.drivers.genetic import Genetic # pylint: disable-msg=E1...
10,580
3,402
import sqlite3 from datetime import datetime from sqlite3 import Error import pandas as pd from src.pricer import read_price_df DB_FILE_PATH = 'db.sqlite' def connect_to_db(db_file): """ Connect to an SQlite database, if db file does not exist it will be created :param db_file: absolute or relative path ...
2,974
977
import pandas as pd import numpy as np import morphs from six import exec_ from pathlib2 import Path from joblib import Parallel, delayed # adapted from klustakwik # NEVER POINT THIS AT SOMETHING YOU DONT TRUST def _read_python(path): assert path.exists() with open(path.as_posix(), "r") as f: contents...
2,793
1,055
from .generator import generate from .init import init
55
13
import atexit import glob import json import logging import os import shutil import sys import tkinter as tk import threading from tkinter import filedialog, messagebox import cv2 import numpy as np import pandas as pd import pygubu from PIL import Image, ImageTk from deprecated import deprecated PROJECT_PATH = os.pa...
2,512
806
import logging from jinja2 import Environment, FileSystemLoader import utils class Firewall: def __init__(self, config): self.config = config self.jinja_env = Environment( loader=FileSystemLoader('/opt/cosmic/router/bin/cs/templates'), trim_blocks=True, lstr...
17,814
6,416
# -*- coding: UTF-8 -*- import numpy import operator """ ================================================================================ kNN算法的步骤: 1. 计算已知类别数据集中的点与当前点之间的距离(欧式距离公式) 2. 按照距离递增次序排序 3. 选取与当前距离最小的k个点 4. 确定前k个点所在类别的出现频率 5. 返回前k个点出现频率最高的类别作为当前点的预测分类 ============================================================...
2,875
1,377
# Generated by Django 3.2.6 on 2021-09-05 19:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0011_auto_20210905_1619'), ] operations = [ migrations.AlterField( model_name='preco', name='categoria', ...
468
176
""" Main menu set up """ import pygame from .. import Setup from .. import Tools from .. import Constant as Con from ..Components import Info class MainMenu: def __init__(self): self.setup_background() self.setup_player() self.setup_cursor() self.info = Info.Info...
2,394
820
from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractUser from django.db import models from user.validators import UsernameValidator class User(AbstractUser): username = models.CharField( _("username"), max_length=36, unique=True, h...
634
168
from collections import Counter TEST = """eedadn drvtee eandsr raavrd atevrs tsrnev sdttsa rasrtv nssdts ntnada svetve tesnvt vntsnd vrdear dvrsen enarar""" def decode(lines: list[str], wantLeast=False): result = '' for i in range(len(lines[0])): count = Counter(line[i] for line in lines) if ...
812
316
# DRF Views types (APIView & ViewSet) # APIViews allows to write standard HTTP Methods as functions & give most control over the logic # Benefits: Perfect for implementing complex logic, calling other APIs, working with local files # Viewsets -> uses model operations for functions kist, create, retrieve, update, parti...
6,246
1,622
#!/usr/bin/env python import panflute as pf """ Pandoc filter that causes emphasis to be rendered using the custom macro '\myemph{...}' rather than '\emph{...}' in latex. Other output formats are unaffected. """ def latex(s): return pf.RawInline(s, format='latex') def myemph(e, doc): if type(e)==pf.Emph a...
466
174
import time import threading import argparse import tushare as ts import numpy as np import pandas as pd from pandas import datetime as dt from tqdm import tqdm from utils import * with open('../../tushare_token.txt', 'r') as f: token = f.readline() ts.set_token(token) tushare_api = ts.pro_api() # 股票列表 df_list ...
3,393
1,423
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008,2009 Benoit Chesneau <benoitc@e-engura.org> # # 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.or...
1,208
402
from django.views import View from comments.models import Comment from django.http import JsonResponse from utils.decorators import fail_safe_api from utils.models import nested_model_to_dict from utils.request import parse_body, set_user from django.contrib.contenttypes.models import ContentType class DetailAPIView(...
2,480
707
from aiohttp import web import urllib.parse from conf import settings ROUTER = { "poke_task": { "url": "/poke", "GET": "request_handle.poke_task", "POST": "request_handle.poke_task", }, "task": { "url": "/task/{task_id}", "GET": "request_handle.get_task", }, ...
2,857
890
import json from .life import BinaryLife class GOL(object): team_names: list = [] columns = 0 rows = 0 def __init__(self, **kwargs): self.load_config(**kwargs) self.create_life() def __repr__(self): s = [] s.append("+" + "-" * (self.columns) + "+") for i i...
3,668
1,153
from .mdp_value_iteration import value_iteration
48
15
from django.contrib import admin from .models import Shift, Service, Appointment class ShiftAdmin(admin.ModelAdmin): fields = ['date', 'master', 'room'] list_display = ('date', 'master', 'status') class ServicetAdmin(admin.ModelAdmin): list_display = ('service_name', 'cost', 'duration', 'room') ...
568
184
#!/usr/bin/env python3 """ Code to issue calls to the cassandra MX4J http server and get stats. """ import os import sys from optparse import OptionParser from esmond.api.client.jmx import CassandraJMX def main(): usage = '%prog [ -U ]' parser = OptionParser(usage=usage) parser.add_option('-U', '--url',...
2,007
716
from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): help = "Add missing id column for hostingstats." def handle(self, *args, **options): with connection.cursor() as cursor: self.cursor = cursor self.cursor.execute( ...
1,294
337
import numba as nb import numpy as np import scipy.stats @nb.njit(parallel=True) def tiecorrect(rankvals): """ parallelized version of scipy.stats.tiecorrect :param rankvals: p x n array of ranked data (output of rankdata function) """ tc = np.ones(rankvals.shape[1], dtype=np.float64) for j i...
2,493
998
class Piece(object): def __init__(self, is_tall: bool = True, is_dark: bool = True, is_square: bool = True, is_solid: bool = True, string: str = None): if string: self.is_tall = (string[0] == "1") se...
2,088
706
import hashlib import os import shutil from random import randint from typing import List from retrying import retry import build_docs from apysc._file import file_util from build_docs import _CodeBlock from build_docs import _CodeBlockFlake8Error from build_docs import _CodeBlockMypyError from build_doc...
21,061
8,400
# Create your views here. import docx import gensim import numpy as np from django.conf import settings from django.http import HttpResponse from django.shortcuts import render from docx.shared import RGBColor, Inches, Pt from nltk.tokenize import sent_tokenize, word_tokenize from .models import Skill, Level # View ...
15,551
4,707
from __future__ import annotations import abc from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union from cached_property import cached_property from .constants import EXTENSION_NAME from .registry import registry from .utils import GroupFuncType, import_from_string, load_cookies, store_c...
3,076
939
#!/usr/bin/env python3 import codekit.pygithub import github import itertools import pytest @pytest.fixture def git_author(): return github.InputGitAuthor(name='foo', email='foo@exmaple.org') def test_init(git_author): """Test TargetTag object instantiation""" t_tag = codekit.pygithub.TargetTag( ...
1,563
522
import unittest from model import node class DummyNode(node.Node): def __init__(self, ids: [str], names: [str]): super().__init__(ids, names) self.primary_id_prefix = 'TEST' class TestMethods(unittest.TestCase): def test_label(self): n = DummyNode([], []) self.assertEqual(n.l...
497
171
import functools def parse_input() -> list[list[str]]: groups = [[]] with open("input.txt") as file: for line in file: line_ = line.rstrip() if len(line_) > 0: groups[-1].append(line_) else: if not groups[-1] == []: ...
1,109
353