text
string
size
int64
token_count
int64
from .neural_network import Neural_network
43
13
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.utils.translation import ugettext_lazy as _ from .models import Ride class RideForm(forms.ModelForm): date = forms.DateField( label=_('Date'), widget=forms.DateInput(format=('%Y...
1,496
447
import asyncio from mlserver import MLModel from mlserver.codecs import NumpyCodec from mlserver.types import InferenceRequest, InferenceResponse class SumModel(MLModel): async def predict(self, payload: InferenceRequest) -> InferenceResponse: decoded = self.decode(payload.inputs[0]) total = dec...
843
256
from time import time import torch import torch.nn as nn class FastAttention(nn.Module): def __init__(self, input_shape, head, n_features): super(FastAttention, self).__init__() self.head = head self.input_shape = input_shape self.depth = int(input_shape // head) self.n_f...
10,459
3,496
""" gtp_connection.py Module for playing games of Go using GoTextProtocol Parts of this code were originally based on the gtp module in the Deep-Go project by Isaac Henrion and Amos Storkey at the University of Edinburgh. """ import signal, os import traceback from sys import stdin, stdout, stderr from board_util im...
28,970
8,959
import weakref from .Cell import Cell class SubCell(Cell): def __init__(self, parent, cell, subpath, readonly): assert isinstance(cell, Cell) assert not isinstance(cell, SubCell) fullpath = cell._path + subpath super().__init__(parent=parent, path=fullpath) self._cell = wea...
2,634
761
#!/usr/bin/env python # -*- coding: utf-8 -*- # The aim of this package is to : # - guarantee protected code execution is safe and *will* happen (eventually) # - report usage via colosstat # - recover when code fails ( possibly recording previous state, for example ) # one possibility is to implement another levelof ...
460
122
from frisky.events import MessageEvent from frisky.plugin import FriskyPlugin, PluginRepositoryMixin from frisky.responses import FriskyResponse class HelpPlugin(FriskyPlugin, PluginRepositoryMixin): commands = ['help'] def command_help(self, message: MessageEvent) -> FriskyResponse: if len(message....
965
274
# -*- coding: utf-8 -*- from PyQt5.QtWidgets import QGraphicsItem, QGraphicsRectItem, QGraphicsItemGroup from PyQt5.QtCore import pyqtSlot class MyItemGroup(QGraphicsItemGroup): Type = QGraphicsItem.UserType + 3 def __init__(self, parent=None): super(MyItemGroup, self).__init__(parent) def __rep...
1,663
564
# Copyright 2022 MosaicML. All Rights Reserved. from dataclasses import dataclass import yahp as hp from composer.models.model_hparams import ModelHparams @dataclass class SSDHparams(ModelHparams): input_size: int = hp.optional( doc="input size", default=300, ) num_classes: int = hp.opt...
998
337
from os.path import join from utils import getFileList class ImageFolder: def __init__(self, path, sub=None, annot='annot') -> None: self.root = path self.image = 'images' self.annot = annot self.image_root = join(path, self.image) self.annot_root = join(path, self.annot) ...
1,303
410
''' Author: your name Date: 2021-06-18 10:13:00 LastEditTime: 2021-07-08 14:13:07 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: /genetic-drawing/main.py ''' import cv2 import os import time from IPython.display import clear_output from genetic_drawing import * gen = GeneticDrawing('0...
1,704
710
import logging from typing import List, Union, Optional import torch import torch.nn import torch.nn.functional as F from tqdm import tqdm import flair.nn from flair.data import Dictionary, Sentence, Label from flair.datasets import SentenceDataset, DataLoader from flair.embeddings import TokenEmbeddings from flair....
10,991
2,978
import requests from bs4 import BeautifulSoup def spider_xiaohuar_content(url, headers): response = requests.get(url=url, headers=headers) print(response.status_code) if response.status_code == 200: response.encoding = 'utf-8' html = response.content # 参数:网页内容,解析器 soup = B...
1,708
637
#尝试直接读取文件夹内所有csv,记得看看列表,是不是读对了 import glob import pandas as pd import numpy as np io = glob.glob(r"*.csv") len_io=len(io) print('总共输入表的数量为:',len_io) prob_list=[] for i in range(len_io): sub_1 = pd.read_csv(io[i]) denominator=len(sub_1) for my_classes in ['healthy','multiple_diseases','rust',...
749
342
# Copyright 2016 NTT Data. # 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 app...
10,468
2,843
news = ['klik untuk membaca', 'klik untuk maklumat']
53
24
from sonosscripts import stop, play_pause, previous, next, change_bass, change_volume, mute_volume modules = { "stop": stop, "play_pause": play_pause, "previous": previous, "next": next, "change_bass": change_bass, "change_volume": change_volume, "mute_volume": mute_volume }
306
110
""" Class SaleBot It is initialised by nlp model (bag-of-word, tf-idf, word2vec) It returns response with a question as the input """ from gensim.corpora import Dictionary #from gensim.models import FastText from gensim.models import Word2Vec , WordEmbeddingSimilarityIndex from gensim.similarities import SoftCo...
3,925
1,184
# -*- coding: utf-8 -*- """Demo123_Convolution_Visualization.ipynb # **Spit some [tensor] flow** We need to learn the intricacies of tensorflow to master deep learning `Let's get this over with` """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf print(tf.__version__) ...
2,452
1,015
import argparse as ap import hail from pprint import pprint import time from hail_scripts.v01.utils.vds_utils import write_vds p = ap.ArgumentParser(description="Convert a tsv table to a .vds") p.add_argument("-c", "--chrom-column", required=True) p.add_argument("-p", "--pos-column", required=True) p.add_argument("-r...
1,482
591
#!/usr/bin/env python # Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list ...
4,649
1,486
######################################################################################### # -*- coding: utf-8 -*- # # This file is part of the SKALogger project # # # ######################################################################################### """Contain the tests for the SKALogger.""" import re import py...
8,433
2,803
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import urlparse def process_buffer(buffer): if not buffer or len(buffer) < 2: return buffer = [line.decode('utf-8', 'ignore') for line in buffer] split_buffer = [line.strip().lower().split("\t") for line in buff...
2,053
590
import pytest from graphviz import jupyter_integration def test_get_jupyter_format_mimetype_invalid_raises_unknown(): with pytest.raises(ValueError, match=r'unknown'): jupyter_integration.get_jupyter_format_mimetype('Brian!') def test_get_jupyter_mimetype_format_normalizes(): assert jupyter_integra...
625
219
import numpy as np def main(): s = np.mean(np.random.randn(100)) print(s) if __name__ == '__main__': main()
122
52
import mountaincar as mc import numpy as np from collections import namedtuple from collections import defaultdict import matplotlib.pylab as plb import matplotlib.pyplot as plt from time import time State = namedtuple('State', ['x', 'v']) class SarsaMountainCar(object): def __init__(self, learning_rate=0.1, rew...
544
170
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd """ The following functions are used to create an annotated heatmap and they were copied from: https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html#using-the-helper-function-code-style ""...
4,931
1,543
# Copyright 2020 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...
6,675
2,113
import logging import keyring SERVICE_NAME = "Orange3 - {}" log = logging.getLogger(__name__) class CredentialManager: """ Class for storage of passwords in the system keyring service. All attributes of this class are safely stored. Args: service_name (str): service name used for storing i...
1,475
437
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine 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, version 3 of the License. # # Cyphon En...
3,799
1,090
import json import requests from collections import defaultdict from fuzzywuzzy import process from random import sample # Constants """ Constants for default responses that do not need any further computation. """ DEFAULT_STOP_RESPONSE = 'All right. See you next time!' DEFAULT_ERROR_MESSAGE = "I'm sorry. I don't kn...
4,805
1,458
import torch import numpy as np import logging, yaml, os, sys, argparse, time from tqdm import tqdm from collections import defaultdict from Logger import Logger import matplotlib matplotlib.use('agg') matplotlib.rcParams['agg.path.chunksize'] = 10000 import matplotlib.pyplot as plt from scipy.io import wavfile from ra...
12,649
4,095
import logging import asyncio import aiohttp from .defaults import * from .app import App from .featured import FeaturedList log = logging.getLogger(__name__) class Client: """Main class for the Steam API""" def __init__(self, *, loop=None, **opts): self.loop = asyncio.get_event_loop() if loop is ...
2,247
700
import sys import numpy as np import matplotlib.pyplot as plt f = open(sys.argv[1], 'r') lines = f.readlines() f.close() pop_size = int(lines.pop(0)) pops = [] for l in lines: if l[0] == '[': pops.append(l.strip()) for j in range(len(pops)): p = [] for n in pops[j][1:-1].split(','): p.a...
881
398
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ analyses for bVAE entanglement, etc """ import torch import sys sys.path.append("..") # Adds higher directory to python modules path. import matplotlib.pyplot as plt import numpy as np from data.dspritesb import dSpriteBackgroundDataset from torchvision import tran...
7,486
2,695
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ## Centering & Scaling ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #%% Standard scaling import numpy as np from sklearn.preprocessing import StandardScaler X = np.array([[ 100...
2,684
991
from pbtaskrunner import db from pbtaskrunner import app from datetime import datetime def date_time_now(): return datetime.now class TestTask(db.Model): """Database representation of a Task test""" __tablename__ = 'test_task' request_id = db.Column(db.Integer, primary_key=True) requester = db....
943
306
# -*- coding: utf-8 -*- from openerp.osv import fields, osv from openerp import tools class MassMailingReport(osv.Model): _name = 'mail.statistics.report' _auto = False _description = 'Mass Mailing Statistics' _columns = { 'scheduled_date': fields.datetime('Scheduled Date', readonly=True), ...
2,244
648
import app if __name__ == "__main__": app.daily_summary("data/Input.txt", "data/Output.csv")
97
37
import urllib, re class FakeUseragentURLopener(urllib.FancyURLopener): version = "Mozilla/5.0 (Ubuntu; X11; Linux i686; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" urllib._urlopener = FakeUseragentURLopener() download_pdf_regex = re.compile('.*<li class="pdf"><a class="sprite pdf-resource-sprite" href="([^"]*)" title...
2,750
882
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.openid import OpenID from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, MAIL_SECURE app = Flask(__name__) app.config.from_object('config') db = S...
1,533
535
# Generated by Django 3.0.8 on 2020-09-03 17:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Blog', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='post', name='wallpaper_representation', ...
330
114
from threading import Lock import discord from discord.ext import commands from loguru import logger from local_types import Snowflake from modules import is_bot_admin class Colors(commands.Cog): bot: discord.ext.commands.Bot colorRoles = {} mutex = Lock() def __init__(self, bot): self.bo...
3,460
1,076
import sys sys.path.append("./generated") sys.path.append("../../package/pywinrt/projection/pywinrt") import _winrt _winrt.init_apartment(_winrt.MTA) def import_ns(ns): import importlib.machinery import importlib.util module_name = "_winrt_" + ns.replace('.', '_') loader = importlib.machinery.Extensio...
526
181
#!/usr/bin/env python import sys import subprocess import evalBedFile # Delly file format (when only del summaries in file - cat *.del.txt | grep Deletion) # The summary line contains the chromosome, the estimated start and end of the structural variant, # the size of the variant, the number of supporting pairs, the ...
2,247
781
import ctypes import struct import time # # A small example how to use basic_dsp in a different language. # class VecResult(ctypes.Structure): _fields_ = [("resultCode", ctypes.c_int), ("result", ctypes.c_void_p)] lib = ctypes.WinDLL('basic_dsp.dll') new64Proto = ctypes.WINFUNCTYPE ( ctypes...
1,645
651
#!/usr/bin/env python # coding: utf-8 import pygame import operator from mino import * from random import * from pygame.locals import * from ui import * from screeninfo import get_monitors from pygame.surface import Surface import sys from function import * #화면크기 조정 screen_width = 0 screen_height = 0 for m in get_m...
53,171
17,681
""" Created on Sep 1, 2011 @author: guillaume """ from scipy import zeros from chemex.bases.two_states.fast import R_IXY, DR_IXY, DW, KAB, KBA def compute_liouvillians(pb=0.0, kex=0.0, dw=0.0, r_ixy=5.0, dr_ixy=0.0): """ Compute the exchange matrix (Liouvillian) The function a...
2,305
829
import tempfile import shutil import os import pandas import numpy as np import datetime import pkg_resources from unittest import TestCase from dfs.nba.featurizers import feature_generators from dfs.nba.featurizers import fantasy_points_fzr, last5games_fzr, nf_stats_fzr, vegas_fzr, \ opp_ffpg_fzr, salary_fzr class...
7,261
2,959
from blocksync._consts import ByteSizes from blocksync._status import Blocks def test_initialize_status(fake_status): # Expect: Set chunk size assert fake_status.chunk_size == fake_status.src_size // fake_status.workers def test_add_block(fake_status): # Expect: Add each blocks and calculate done block ...
1,346
485
#!/usr/bin/python3 import os def readFixture(sdk): f = open(os.path.join('tests', 'fixtures', sdk), 'r') lines = f.readlines() f.close() return [ line.strip('\n') for line in lines] def valuesFromDisplay(display): return [value-1 for value in display]
275
98
# General Utility Libraries import sys import os import warnings # PyQt5, GUI Library from PyQt5 import QtCore, QtGui, QtWidgets # Serial and Midi Port Library import rtmidi import serial import serial.tools.list_ports # SKORE Library from lib_skore import read_config, update_config import globals #----------------...
33,787
11,948
import requests from .values import ROUTES from .values import LOCALES from .values import REGIONS from .values import ENDPOINTS def value_check(*args): KEYS = ROUTES + LOCALES + REGIONS for arg in args: if arg not in KEYS: raise ValueError else: return True class W...
1,814
562
for i in range(30): print("a_", end="") print() for i in range(30): print("b_", end="") print() for i in range(30): print("c_", end="")
153
66
import os import pytest from typing import Any, Callable, Dict, List import LearnSubtitles as ls def prepare(language: str) -> List: """ Create LearnSubtitles objects for every subtitle in folder 'language' """ test_dir = "testfiles/" + language subs = [ ls.LearnSubtitles(os.path.abspath(os.path...
1,256
446
import pandas as pd import numpy as np from time import time import matplotlib.pyplot as plt from sklearn.ensemble import ExtraTreesClassifier train = pd.read_excel('stats.xls', sheet_name='train') test = pd.read_excel('stats.xls', sheet_name='test') array_train = train.values array_test = test.values X = array_trai...
2,455
877
#-*- coding: utf-8 -*- from logpot.admin.base import AuthenticateView from logpot.utils import ImageUtil from flask import flash, redirect from flask_admin import expose from flask_admin.contrib.fileadmin import FileAdmin from flask_admin.babel import gettext import os import os.path as op from operator import itemg...
618
181
from .emailutil import *
24
7
from __future__ import annotations import multiprocessing import os import re import sys from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from itertools import chain from pathlib import Path from urllib.parse import urlparse import click import requests from requests.models i...
4,888
1,446
import os import time from hashlib import sha256 import requests from dotenv import load_dotenv from fastapi.security import OAuth2PasswordBearer BASE_DIR = os.path.dirname(os.path.abspath(__file__)) load_dotenv(os.path.join(BASE_DIR, "../.env")) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/activate-login-c...
1,060
372
"""Correlate based on geograpgic information.""" from alert_manager import AlertManager from utility import Utility class GeoCorrelator(object): """Geographic correlator.""" def __init__(self, device_id): """Initialize the Geographic Correlator.""" self.geo_anchor = {} self.threshold...
4,362
1,192
import numpy as np import matplotlib.pyplot as plt N =[20,40,50,75,100,150,200] scale = [0.0001, 0.001, 0.005, 0.01, 0.1, 1, 10] ...
1,697
647
#!/usr/bin/env python print("hey there, this is my first pip package")
72
24
from .django_q import AstToDjangoQVisitor from .django_q_ext import * from .shorthand import apply_odata_query
111
38
# scrape articles from RAND site, see https://vashu11.livejournal.com/20523.html import re import requests from bs4 import BeautifulSoup import os content = ['https://www.rand.org/pubs/papers.html'] + ['https://www.rand.org/pubs/papers.{}.html'.format(i) for i in range(2, 108)] def get_articles(page): page = requ...
1,457
518
from dbnd._core.commands.metrics import log_snowflake_table from dbnd_snowflake.snowflake_resources import log_snowflake_resource_usage __all__ = [ "log_snowflake_resource_usage", "log_snowflake_table", ]
215
90
# A parser for multiple FINO2 .dat files in a directory. import os import pathlib import pandas as pd import numpy as np import glob import sys class fino2_dats: """FINO2 data class """ def __init__(self, info, conf): self.path = os.path.join( (pathlib.Path(os.getcwd()).parent), str...
2,422
741
import subprocess as sp import os import time import platform from os.path import exists #colar vars class color: lightblue='\033[1;34m' #light blue lightred='\033[1;31m' #light red lightgreen='\033[1;32m' #lightgreen red='\033[0;31m' #red yellow='\033[1;33m' #yellow none='\033[0m' #no color ...
2,481
957
#! /usr/bin/env python ''' This script calculates total heterozygosity. #Example input: CHROM POS REF sample1 sample2 sample3 sample4 sample5 sample6 sample7 sample8 chr_1 1 A W N N A N N N N chr_1 2 C Y Y N C C N C N chr_1 3 C N C N C C C C C chr_1 4 ...
3,880
1,594
# -*- coding: utf-8 -*- """ Created on Wed Jun 27 17:24:58 2018 @author: Mauro """ #============================================================================== # Imports #============================================================================== import struct #=================================================...
2,748
759
#!/usr/bin/env python import pandas as pd from scipy import stats import numpy as np #import seaborn as sns #import matplotlib.pyplot as plt import math from Bio import SeqIO import io import re import pysam from functools import reduce import argparse import os parser = argparse.ArgumentParser() parser.add_argum...
8,726
2,817
import datetime from django.contrib import admin from django.core.exceptions import ObjectDoesNotExist from django.db.models import Max from . import models, forms from address.biz import geocode from utils import common from utils.django_base import BaseAdmin # Register your models here. class ParkingPositionInlin...
6,315
1,997
import matplotlib import matplotlib.pyplot as plt import numpy as np filenames=["euler.dat","rk4.dat","leapfrog.dat"] fig, axs = plt.subplots(nrows=3, ncols=3) ax=axs[0][0] ax.set_title('Euler') ax=axs[0][1] ax.set_title('RK4') ax=axs[0][2] ax.set_title('Leap_frog') for i in range(3): f=open(filenames[i],"r") s...
965
470
import requests from bs4 import BeautifulSoup from time import sleep url = "http://zipnet.in/index.php?page=missing_person_search&criteria=browse_all&Page_No=1" r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') all_tables = soup.findAll('table') for table in all_tables: print('--- table ---')...
565
191
import mailpile.plugins from mailpile.commands import Command from mailpile.mailutils import Email, ExtractEmails from mailpile.util import * class VCard(Command): """Add/remove/list/edit vcards""" ORDER = ('Internals', 6) KIND = '' SYNOPSIS = '<nickname>' def command(self, save=True): session, config =...
4,654
1,662
import numpy as np from pylab import * D = 10 acc1 = np.load('res/small/acc.npy').reshape(D, -1).mean(axis=0) loss1 = np.load('res/small/loss.npy').reshape(D, -1).mean(axis=0) acc2 = np.load('res/large/acc.npy').reshape(D, -1).mean(axis=0) loss2 = np.load('res/large/loss.npy').reshape(D, -1).mean(axis=0) cut = int(acc...
1,663
875
from flask_restful import reqparse def send_api_response(response_code, response_message, http_status, response_data={}): if http_status not in [200, 201]: return {'responseCode': response_code, 'responseMessage': response_message }, int(http_status), \ {"Acc...
696
186
""" A fake DB-API 2 driver. """ # DB names used to trigger certain behaviours. INVALID_DB = 'invalid-db' INVALID_CURSOR = 'invalid-cursor' HAPPY_OUT = 'happy-out' apilevel = '2.0' threadsafety = 2 paramstyle = 'qmark' def connect(database): return Connection(database) class Connection(object): """ A f...
3,435
985
''' ================================================ ## VOICEBOOK REPOSITORY ## ================================================ repository name: voicebook repository version: 1.0 repository link: https://github.com/jim-schwoebel/voicebook author: Jim Schwoebel author contact: js@neur...
4,081
1,217
from typing import List, Tuple, Union import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from ..utils._checks import ( _check_participant, _check_participants, _check_type, ) from ..utils._docs import fill_doc @fill_doc def boxplot_scores_evolution( csv, participant: ...
5,178
1,712
class Everland: def __init__(self): self.rooms = [] def add_room(self, room): self.rooms.append(room) def get_monthly_consumptions(self): total_consumption = 0 for room in self.rooms: total_consumption += room.expenses + room.room_cost return f"Monthly c...
1,755
525
# Generated by Django 3.1.6 on 2021-02-25 05:46 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), ('cont...
14,770
4,145
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of the minifold project. # https://github.com/nokia/minifold __author__ = "Marc-Olivier Buob" __maintainer__ = "Marc-Olivier Buob" __email__ = "marc-olivier.buob@nokia-bell-labs.com" __copyright__ = "Copyright (C) 2018, Nokia" __license__ ...
2,448
901
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-18 11:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
4,515
1,276
from bs4 import BeautifulSoup import re import urllib import pickle as pkl def cleanhtml(raw_html): cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, '', raw_html) cleanr_still = re.compile('\\xa0') cleanertext = re.sub(cleanr_still, '', cleantext) cleanr_even = re.compile('\\u2019s') cle...
2,820
867
# 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...
1,116
344
from django.urls import path from .views import index, create, delete, update urlpatterns = [ path('', index, name='index'), path('create/', create, name='create'), path('delete/<int:pk>', delete, name='delete'), path('update/<int:pk>', update, name='update'), ]
280
89
""" Adapted from https://realpython.com/python-web-scraping-practical-introduction/ for the purpose of scraping https://publications.parliament.uk/pa/ld/ldjudgmt.HTML to create an expanded HOLJ+ corpus """ import requests from requests import get from requests.exceptions import RequestException from contextlib import ...
1,831
529
# #!/usr/bin/python import os import numpy as np import pandas as pd from keras.models import load_model from keras.models import Sequential from keras.utils import np_utils from keras.layers.core import Dense, Activation, Dropout from keras import optimizers from matplotlib import pyplot as plt print('Loading data...
1,881
723
from socket import socket, gaierror, getservbyport, AF_INET, SOCK_STREAM, setdefaulttimeout from tqdm import tqdm from datetime import datetime def detect_port_services(ip, range_start, range_end): port_services = {} port_detecting_progress = tqdm(range(range_start, range_end + 1)) try: for port i...
2,487
726
# -*- coding: utf-8 -*- import json from collections import OrderedDict from typing import List import dash_core_components as dcc import dash_html_components as html import dash_table import pandas as pd from dash import dash from dash.dependencies import Input, Output, State from zvdata import IntervalLevel from zv...
14,829
3,950
import numpy as np class CTCCodec(object): """ Convert index to label """ def __init__(self, char_label, top_k): # char_label : all the characters. self.top_k = top_k self.index = {} list_character = list(char_label) for i, char in enumerate(list_character): ...
1,139
376
from common_libs import * from cublas_functions import * linalg.init() def cublas_calculate_transpose_non_batched(h, a_gpu): cublas_transpose = get_single_transpose_function(a_gpu) m, k = a_gpu.shape at_gpu = gpuarray.empty((k, m), a_gpu.dtype) k, n = at_gpu.shape # Calculate transpose transa =...
4,333
1,858
import os from time import localtime, strftime pwd = os.curdir root_dir = pwd + './../' weights_path = '{}data/imagenet_models/VGG16.v2.caffemodel'.format(root_dir) cfg_path = '{}experiments/cfgs/mask_rcnn_alt_opt.yml'.format(root_dir) log_file="{}experiments/logs/mask_rcnn_alt_opt_{}".format(root_dir, strfti...
793
344
from direct.directnotify import DirectNotifyGlobal from direct.distributed import DistributedObject from toontown.ai import DistributedPhaseEventMgr class DistributedTrashcanZeroMgr(DistributedPhaseEventMgr.DistributedPhaseEventMgr): neverDisable = 1 notify = DirectNotifyGlobal.directNotify.newCategory('Distri...
1,325
418
""" .. _ft_seeg_example: ========================================= Apply bipolar montage to depth electrodes ========================================= This scripts shows a very simple example on how to create an Interface wrapping a desired function of a Matlab toolbox (|FieldTrip|). .. |FieldTrip| raw:: html <a...
1,575
542
# Simple tree structure import numpy as np import math class Node: ''' Class defining a node for the game tree. Nodes store their position on the board, their reward, their visits and their children. ''' def __init__(self, parent, boardposition, current_player): self.parent = parent ...
2,224
620
# -*- coding: utf-8 -*- """Console script for vibrant_frequencies.""" import logging import click from .prototype import visualize @click.command() def main(): logging.getLogger('').setLevel(logging.WARN) visualize() if __name__ == "__main__": main()
269
94
from __future__ import annotations from typing import TYPE_CHECKING from .packet import ( ConnectionRequest, ConnectionRequestAccepted, NewIncomingConnection, OfflinePing, OfflinePong, OnlinePing, OnlinePong, OpenConnectionRequest1, OpenConnectionReply1, OpenConnectionRequest2, ...
6,568
1,803