text
string
size
int64
token_count
int64
from data_retrieval import * import emailer from login.config import Config from sentiment_analysis import * import tweepy import json def send_email(user_id, post_id): # Note: can determine user_id from post_id try: emailer.send_email(Config.EMAIL_SENDER, get_email(user_id), get_post_content(post_id), Co...
1,189
429
""" This tutorial shows how to generate adversarial examples using FGSM and train a model using adversarial training with TensorFlow. It is very similar to mnist_tutorial_keras_tf.py, which does the same thing but with a dependence on keras. The original paper can be found at: https://arxiv.org/abs/1412.6572 """ from _...
3,291
1,117
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # by [jackhanyuan](https://github.com/jackhanyuan) 07/03/2022 import argparse import copy import glob import os import re import sys import time from pathlib import Path import cv2 import acl import torch import numpy as np from PIL import Image import torch.nn.functiona...
7,434
2,869
import os with open("./simple_graph.txt", "r") as f: N = int(f.readline()) edges = [] while True: line = f.readline().strip() if line == None or len(line) == 0: break line = line.split(" ") edges.append([int(line[0]), int(line[1])]) con = [] for i in range(N): ...
1,044
387
# coding=utf-8 """   __title__ = ''   __file__ = ''   __author__ = 'tianmuchunxiao'   __mtime__ = '2019/7/4' """ import requests import datetime import pandas as pd from io import StringIO TODAY = datetime.date.strftime(datetime.date.today(), '%Y%m%d') class Data(object): URL = '' PARAMS = {} HEADERS = {} file_pa...
3,516
1,983
import datetime import logging import pytz import socket logger = logging.getLogger('common') def get_fqdn(ip_address): """ Function that transforms a given IP address into the associated FQDN name for that host. :param ip_address: IP address of the remote host. :return: FQDN name for that host...
4,151
1,249
""" """ from evennia import default_cmds from evennia import CmdSet class CoCCharacterCmdSet(default_cmds.CharacterCmdSet): """ The `CharacterCmdSet` contains general in-game commands like `look`, `get`, etc available on in-game Character objects. It is merged with the `AccountCmdSet` when an Accoun...
2,455
701
""" Non-cython methods for getting counts and distributions from data. """ import numpy as np try: # cython from .pycounts import counts_from_data, distribution_from_data except ImportError: # no cython from boltons.iterutils import windowed_iter from collections import Counter, defaultdict from it...
6,300
1,592
""" @author: Badita Marin-Georgian @email: geo.badita@gmail.com @date: 21.03.2020 00:58 """ from env_interpretation import Meeting from env_interpretation.meeting import get_valid_meetings def test_get_meetings_4_robots(env4_robots): env_data = env4_robots.get_env_metadata() cycles_length = [l...
1,845
740
# Confidential, Copyright 2020, Sony Corporation of America, All rights reserved. import copy import numpy as np from pandemic_simulator.environment import CityRegistry, Home, GroceryStore, Office, School, Hospital, PopulationParams, \ LocationParams from pandemic_simulator.script_helpers import make_standard_loc...
1,670
542
from libs import * def SIFT_algo(training_image,training_gray,test_image,test_gray): #test_gray = cv2.cvtColor(test_image, cv2.COLOR_RGB2GRAY) #training_gray = cv2.cvtColor(training_image, cv2.COLOR_RGB2GRAY) # Creating SIFT Object sift = cv2.SIFT_create() # Detecting features ...
1,008
364
from typing import List class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: if k <= 0: return 0 else: numOfCards = len(cardPoints) totalPart1 = sum(cardPoints) * (k//numOfCards) k = k%numOfCards totalPart2...
651
200
import pandas as pd import argparse badword = ["!", "$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","/","]","^","_","`","{","|","}","~","の","®"] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--path', help='the path of file') ...
1,192
436
from Ipv4_stun.transfer import Transfer #m=Transfer(address=('172.16.0.156',9080)) m=Transfer(address=('127.0.0.1', 82)) m.run()
133
75
"""season.py: Generates random NJBA season data.""" __author__ = "Matthew Frazier" __copyright__ = "Copyright 2019, University of Delaware, CISC 637 Database Systems" __email__ = "matthew@udel.edu" from datetime import timedelta import calendar import csv ''' Steps to run this project: 1. Create a virtual env a...
4,030
1,158
import numpy as np import pandas as pd import pace from pace.definitions import amino_acids, builtin_aa_encodings, builtin_allele_similarities from pace.sklearn import create_one_hot_encoder from pkg_resources import resource_stream def load_allele_similarity(allele_similarity_name): allele_similarity = ...
2,746
840
import tkinter as tk from tkinter import * from tkinter import messagebox from tkinter.simpledialog import askinteger from protocol.secure_transmission.secure_channel import establish_secure_channel_to_server from protocol.message_type import MessageType from protocol.data_conversion.from_byte import deserialize_messag...
13,884
5,237
#!/usr/bin/env python """Light weight python client for Akismet API.""" __title__ = 'akispy' __version__ = '0.2' __author__ = 'Ryan Leland' __copyright__ = 'Copyright 2012 Ryan Leland' import http.client, urllib.request, urllib.parse, urllib.error class Connection(object): _key = None _version = None ...
3,285
912
""" This script is used to compute mffc features for target task datasets. Warning: Need manual editing for switching datasets """ import os import librosa import soundfile as sf import numpy as np from tqdm import tqdm from pathlib import Path FILES_LOCATION = '../data/UrbanSound8K/audio' FILES_LOCATION = '../data/G...
1,599
615
import argparse import astunparse import sys from . import check parser = argparse.ArgumentParser() parser.add_argument("file", nargs="?", type=argparse.FileType("r"), default=sys.stdin) args = parser.parse_args() poisoned = check(args.file.read()) print("Possible SQL injections:") for p in poi...
391
128
#!/usr/bin/env python # -*- coding: utf-8 -*- a='Du hast mich' b='Du, du hast'+'\n'+a c=a+' gefragt' def j(i): return '\n'.join(i) d=j([b,b,'']) e=j(['Willst du bis der Tod euch scheidet','Treurig sein für alle Tage?','Nein, nein!','']) f=j([d,b,a,'',j([c,c,c,'Und ich hab nichts gesagt','']),e,e]) print j([d,f,f,e])
318
157
import pyuvm_unittest from pyuvm import * class s06_reporting_classes_TestCase(pyuvm_unittest.pyuvm_TestCase): """Basic test cases.""" def test_object_creation(self): """ Test that we actually get a logger in our object. """ ro = uvm_report_object('ro') self.assertTrue...
799
231
from django.db import models from django.core.validators import MinValueValidator from .nodo import Nodo class PuntoDeRetiro(Nodo): capacidad = models.IntegerField(validators=[MinValueValidator(1)])
203
59
import asyncio from typing import Sequence from async_service import Service, background_asyncio_service from eth.abc import BlockHeaderAPI from eth.exceptions import CheckpointsMustBeCanonical from eth_typing import BlockNumber from trinity._utils.pauser import Pauser from trinity.chains.base import AsyncChainAPI fr...
8,429
2,426
""" A federated learning client using SCAFFOLD. Reference: Karimireddy et al., "SCAFFOLD: Stochastic Controlled Averaging for Federated Learning" (https://arxiv.org/pdf/1910.06378.pdf) """ import os from dataclasses import dataclass import torch from plato.clients import simple @dataclass class Report(simple.Re...
2,436
666
import asyncio import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from bilireq.auth import Auth from bilireq.dynamic import get_user_dynamics, get_followed_dynamics_update_info, get_followed_new_dynamics, get_followed_history_dynamics from bilireq.live import get_rooms_info_by_ids ...
2,307
822
import re import numpy def read_pgm(filename, byteorder='>'): """Return image data from a raw PGM file as numpy array. Format specification: http://netpbm.sourceforge.net/doc/pgm.html """ with open(filename, 'rb') as f: buffer = f.read() try: header, width, height, maxval = re.sea...
1,105
378
from .config import RecconSpanExtractionConfig from .tokenization import RecconSpanExtractionTokenizer from .modeling import RecconSpanExtractionModel from .preprocess import RecconSpanExtractionPreprocessor from .postprocess import RecconSpanExtractionPostprocessor from .train import train from .eval import evaluate f...
406
96
'''Don't change the basic param''' import os '''prog path''' config_path = os.path.split(__file__)[0] marktemp_path = os.path.join(config_path,"markenv.tex") '''tools setting''' image_download_retry_time = 10 # 在尝试重试次数达到上限后,是否等待手动下载该文件放到目录 # wait_manully_if_all_failed = False # 在tex文件里添加图片的时候,使用相对路径还是绝对路径 give_rele_pa...
331
170
# Questão 12. Construa uma função que receba uma string como parâmetro # e devolva outra string com os carateres emba- ralhados. Por exemplo: # se função receber a palavra python, pode retornar npthyo, ophtyn ou # qualquer outra combinação possível, de forma aleatória. Padronize em # sua função que todos os caracte...
669
241
# Numpy массивы # Документация по NumPy: https://numpy.org/doc/stable/ # Список универсальных функций NumPy https://numpy.org/devdocs/reference/ufuncs.html # NumPy - векторные/научные вычисления. Пакет содержит функциональные средства для работы с многомерными массивами # и высокоуровневыми математическими функциями ...
54,872
28,114
from setuptools import setup with open('README.md','r', encoding='utf-8') as f: long_description = f.read() setup(name='submit_hpc', version='0.1.2', description='Collection of growing job submission scripts, not to replace workflow specifications.', url='https://github.com/jlevy44/Submit-HPC', ...
704
217
#! /usr/bin/env python import tensorflow as tf import tensorflow.contrib.slim as slim seed = 0 def fc2d(inputs, num_outputs, activation_fn, scope): with tf.variable_scope(scope, reuse=tf.AUTO_REUSE) as s: n0, n1, n2 = inputs.get_shape().as_list() weights = tf.get_varia...
18,209
4,496
import tensorflow as tf import itertools import numpy as np FLAGS = tf.flags.FLAGS def stepped_spiral_actions(theta_incr=np.pi/180): coverage = FLAGS.num_steps*FLAGS.step_size/FLAGS.img_side**2 start_theta = np.pi/4 start_r = np.sqrt(2)*FLAGS.step_size start_position = np.ones(...
5,924
2,026
import os import unittest from camelback.lexer import Lexer class TestLexer(unittest.TestCase): SOURCE_CODE_FILE = os.path.join(os.path.dirname(__file__), 'bin', 'snakecase.c') def test_tokenize_source_code(self): with open(TestLexer.SOURCE_CODE_FILE) as f: stream = f.read() lexe...
1,336
445
"""Fixtures and configuration for the test suite.""" from pathlib import Path import pytest import vcr from pycwatch import CryptoWatchClient BASE_DIR = Path(__file__).parent.absolute() api_vcr = my_vcr = vcr.VCR( serializer="yaml", cassette_library_dir=BASE_DIR.joinpath("vcr_cassettes").as_posix(), rec...
568
206
""" .. module:: CXResolutionEstimate.py :platform: Unix :synopsis: A class for predicting the resolution of a ptychography measurement. .. moduleauthor:: David Vine <djvine@gmail.com> """ import requests import pdb import scipy as sp import numpy as np import scipy.fftpack as spf from pylab import * class Hen...
6,861
2,945
# Generated by Django 3.1 on 2020-12-06 09:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('classes', '0006_auto_20201205_2224'), ] operations = [ migrations.RemoveField( model_name='classsyllabus', name='compo...
997
298
import sys from pyspark.sql import SparkSession, functions, types from pyspark.sql.functions import date_format import json def views_in_dow(): data_stream = spark.read.json('stream_cleanned') data_channel = spark.read.json('channel_cleanned') data_stream.createOrReplaceTempView('data_s') data_c...
1,129
362
from flask import Flask from flask_restful import Api from elasticapm.contrib.flask import ElasticAPM from flask_restful_swagger import swagger from resources import custom_logger from resources.routes import initialize_routes import logging app = Flask(__name__) app.config.from_object("config.Config") # Initializing...
570
186
import discord, random from discord.ext import commands from discord_slash import cog_ext from discord_slash.utils.manage_commands import create_option class Slash(commands.Cog): def __init__(self, bot): self.bot = bot @cog_ext.cog_slash(name="rng", description="Générer un nombre aléatoire !", options...
1,593
511
from flask import Flask from kubernetes.client.rest import ApiException from pprint import pprint from kubernetes import client, config app = Flask(__name__) @app.route("/ing") def ing(): # Configure API key authorization: BearerToken configuration = kubernetes.client.Configuration() configuration.api_key...
1,538
490
i_am_broke = False if i_am_broke: print("I am broke.") else: print("I am not broke.") my_bank_account = 1000 if my_bank_account <= 0: print("I am broke.") else: print("I am not broke.") # equal == # less < # greater > # not equal != # less or equal <= # greater or equal >= my_age = 21 if my_age ...
447
180
print("x") print("x") print("x")
34
17
# Generated by Django 2.2.24 on 2021-12-28 20:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('neighbour', '0013_profile_neighbourhood'), ] operations = [ migrations.AlterModelOptions( name='neighbourhood', options={'o...
498
166
from __future__ import annotations from typing import List, Type import numpy # list of numarray data types integer_types: List[Type] = [ numpy.int8, numpy.uint8, numpy.int16, numpy.uint16, numpy.int32, numpy.uint32, numpy.int64, numpy.uint64] float_types: List[Type] = [numpy.float32, numpy.float64] comple...
427
157
import torch import os import subprocess as sp from mlutils.pt.training import TrainerBatch from mlutils.callbacks import Callback from os import path import numpy as np import json class WeightedSum: def __init__(self, name, init, postprocessing=None): self.name = name self.v = init self....
10,286
3,420
#!/usr/bin/python """ TODO: where'd I get this from? """ import math import random p = ( 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103, 30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197, 62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20, 125,136,171,168,68,175,74,165...
6,612
3,900
from test_base import DisplaySDKTest from utils import * class RandomTest(DisplaySDKTest): def test_banner_random(self): click_btn(self, "All Errors") for i in range(10): click_load_ad_btn(self, "Banner") accept_location(self) webview = block_until_webvie...
3,555
972
import logging from configparser import ConfigParser from typing import Callable __plugins = {} def plugin_disabled(config, path): name = '.'.join(path.replace('/', '.').replace('\\', '.').split('.')[:-2]) return config.getboolean(name, "disabled", fallback=False) def plugin_mjs(config): from glob impor...
1,964
592
"""Handle copying data between sites. tsm_mover.py contains the necessary classes to upload and download from tape backup and syncronize it with the runDB. Author: Boris Bauermeister Email: Boris.Bauermeister@fysik.su.se """ import datetime import logging import os import time import hashlib import ...
30,325
9,293
from network.route import * class Host(object): def __init__(self, name, r, s, a=1): self.name = name self.receiving_cap = r self.sending_cap = s self.amp_factor = a self.links = [] def add_link(self, l): self.links.append(l) def __str__(self): if...
2,076
728
# V0 # V1 # https://www.hrwhisper.me/leetcode-wiggle-sort-ii/ class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ temp = sorted(nums) s, t = (len(nums) + 1) >> 1, len(n...
5,310
1,896
import config.Text class ZigZag: def __init__(self, name: str): self._name = name @property def name(self): return self._name @property def conditions(self): conditions = { 'wa_b': { config.Text.waves: ['waveA', 'waveB'], config...
517
153
from django.shortcuts import get_object_or_404, redirect, render from .models import ShortURL def redirect_alias(request, short_name): shorturl = get_object_or_404(ShortURL, alias=short_name) return redirect(shorturl.url)
232
77
import argparse import sys import logging as log from pyautomailer import PyAutoMailer, PyAutoMailerMode def main(): parser = parse_args(sys.argv[1:]) # Auto mailer init. am = PyAutoMailer(parser.sender, parser.host, parser.port, parser.use...
4,153
1,204
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # Example code written by a python developer to access cpp implementation of Foo # This file should be hand-written by a python developer from foo_interface import FooInterface from djinni.support import decode...
4,225
1,428
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import logging import os import to...
4,324
1,336
# para executar # python write_to_video.py --output example.avi # ou # python write_to_video.py --output example.avi --picamera 1 # python -m pip install imutils from __future__ import print_function from imutils.video import VideoStream import numpy as np import argparse import imutils import time import cv2 #https:...
2,727
989
# =============================================================================== # Created: 1 Nov 2021 # @author: Jesse Wilson (Anaplan Asia Pte Ltd) # Description: Abstract Anaplan Authentication Class # Input: Username & Password, or SHA keypair # Output: Anaplan JWT and token expiry time # ================...
3,973
1,363
class OsuTimingPoint(object): """ representats a timingpoint in osu if change is False: ms_per_beat = -100.0 * bpm_multiplier """ def __init__(self, starttime:float or str=0.0, ms_per_beat:float or str=-100.0, change:bool=False): self.starttime:float = float(starttime) self.ms_per_beat:float = float(ms_...
561
240
import Adafruit_PCA9685 pwm = Adafruit_PCA9685.PCA9685() pwm.set_pwm_freq(50) initPWM = 320 setPWM = initPWM ctrlPort = 11 def main(): global setPWM while 1: commandInput = input() if commandInput == 'w': setPWM += 1 elif commandInput == 's': setPWM -= 1 pwm.set_pwm(ctrlPort, 0,...
427
235
#cred.py, python script with my client ID and my client secret import cred import spotipy from spotipy.oauth2 import SpotifyClientCredentials import pandas as pd client_credential_manager = SpotifyClientCredentials(client_id= cred.client_ID, client_secret= cred.client_SECRET) sp = spotipy.Spotify(client_credentials_ma...
2,042
642
#! /usr/bin/env python # -*- coding: utf-8 -*- # ユーザーストリームで流れているアカウントの画像を片っ端から取得、保存。 # Perl の名刺化スクリプトと連携せよ。 # 2012 / 11 / 14 # jskny # http://d.hatena.ne.jp/iacctech/20110429/1304090609 import sys, tweepy, urllib, urllib2 import os, time, subprocess, socket import re from tweepy.streaming import StreamListener, ...
3,053
1,490
from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from ...factories import UserFactory class UserViewTest(TestCase): def setUp(self): self.client = APIClient() self.user = UserFactory() self.client.force_authenticate(user=self.user) ...
541
159
ports = { "ssh": {"type": "PortLiteral", "port": "22", "protocol": "6",}, "udp/netbios-dgm": {"type": "PortLiteral", "port": "138", "protocol": "17",}, "udp/netbios-ns": {"type": "PortLiteral", "port": "137", "protocol": "17",}, "tcp/ssh": {"type": "PortLiteral", "port": "22", "protocol": "6",}, ...
2,862
1,202
# -*- coding: utf-8 -*- """ Created on Mon Mar 18 18:38:38 2019 @author: Oshikuru """ import numpy as np import matplotlib.pyplot as plt import random import data import pdb import IPython param_delta = 0.5 param_niter = 100 param_lambda = 0.01 def binlogreg_classify(X, w, b): scores = np.dot(X, w) + b ret...
2,336
1,010
from collections import Counter class Solution: """ @param nums: a list of integers @return: return a boolean """ def isPossible(self, nums): left = Counter(nums) # record nums not placed end = Counter() # record subsequences ended with certain num for num in ...
778
217
from _ast import In, NotIn, Is, IsNot from collections import deque, Counter from decimal import Decimal from fractions import Fraction from safe_eval.rules import BinOpRule, CallableTypeRule, CallableRule, GetattrTypeRule, CallableMethodRule k_view_type = type({}.keys()) v_view_type = type({}.values()) it_view_type ...
2,867
972
#!/usr/bin/env mayapy # # Copyright 2021 Autodesk # # 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 a...
6,745
1,935
# -*- coding: utf-8 -*- import numpy as np import talib as ta from abc import ABC, abstractproperty, abstractclassmethod, abstractmethod class BaseExchangeStrategy(ABC): """交易策略基类""" shortable = True # 能否做空 leverage = 1 # 策略杠杆 def __init__(self, *initial_data, **kwargs): """支持按字典方式传入参数信息"""...
5,443
2,296
from django.contrib import admin from core import models from .category import CategoryAdmin from .trait import TraitAdmin from .user import UserAdmin admin.site.register(models.User, UserAdmin) admin.site.register(models.Ability) admin.site.register(models.Category, CategoryAdmin) admin.site.register(models.Trait, ...
492
145
import numpy as np import sys import caffe import glob import uuid import cv2 from util import transform_img from mouth_detector_dlib import mouth_detector from caffe.proto import caffe_pb2 import os import shutil from util import histogram_equalization from teeth_cnn import teeth_cnn mouth_detector_instance = mouth_d...
2,196
1,091
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
33,650
8,263
import sys import omfgp as gp import time if gp.USES_USCARD: import uscard from machine import Pin def get_default_reader(): """Return default smart card reader.""" if gp.USES_USCARD: return uscard.Reader(name="Smart card reader", ifaceId=2, ...
2,163
743
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: 基准测试 Desc : """ from timeit import timeit __author__ = 'Xiong Neng' class Stock(): # 鼓励使用__slots__提升性能 __slots__ = ["name", "shares", "price"] def __init__(self, name, shares, price): self.name = name self.shares = shares...
685
295
from dataclasses import dataclass from typing import Optional import matplotlib.pyplot as plt import numpy as np @dataclass() class TreeNode: idx_start: int idx_end: int center: np.ndarray radius: float is_leaf: bool left: Optional["TreeNode"] right: Optional["TreeNode"] @dataclass() cl...
7,276
2,421
file = open('corruptionChecksum_input.txt', 'r') spreadsheet = file.readlines() def find_smallest(inputs): smallest = int(inputs[0]) for value in inputs: number = int(value) if number < smallest: smallest = number return smallest def find_largest(inputs): largest = int(in...
644
197
# Copyright 2020 ByteDance Inc. # # 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 writin...
3,579
1,098
from django.db import migrations, transaction class Migration(migrations.Migration): dependencies = [ ('homepage', '0001_initial'), ('homepage', '0003_course_test_data'), ('homepage', '0004_followed_courses_test_data'), ] def generate_data(apps, schema_editor): ...
1,621
547
import cv2 import numpy as np from matplotlib import pyplot as plt from util import resize_min_dim, smart_hsv_range IMAGE_FILENAME = '/Users/ryanbrott/Desktop/36.jpg' MIN_DIMENSION = 480 # LOWER_HSV, UPPER_HSV = (170, 80, 0), (7, 255, 255) LOWER_HSV, UPPER_HSV = (175, 80, 80), (22, 255, 255) image = cv2.imread(IMAGE_...
1,220
652
from django.db import models from dashboard.models import projects class AnalysisConfig(models.Model): project = models.OneToOneField( projects, on_delete=models.CASCADE, primary_key=True) mesh = models.TextField() visualizationMesh = models.TextField() config = models.TextFiel...
1,114
332
""" ToDo: convert to proper format Tests for modules in this directory """ from __future__ import print_function # Author: Vladan Lucic, last modified 05.04.07 import scipy import scipy.ndimage import numpy import pyto.util.numpy_plus as np_plus # define test arrays aa = numpy.arange(12, dtype='int32') aa = aa.resh...
1,924
763
#coding=utf-8 __author__ = 'zxlee' __github__ = 'https://github.com/SmileZXLee/GithubRepositoryStatistics' class Repository : def __init__(self,brief,url,language,star_count,fork_count,star_url,fork_url,is_fork): #仓库介绍 self.brief = brief.replace('\r','').replace('\n','').replace('\t','').strip() #仓库url ...
922
411
#!/bin/python3 # author: Jan Hybs import enum import pathlib from bson import objectid from flask import Flask, redirect, session, render_template, url_for import flask.json from flask_cors import CORS from loguru import logger from entities.crates import ICrate from env import Env from functools import wraps def ...
3,242
954
import base64 from collections import deque from io import BytesIO import os import time from PIL import Image import pandas as pd from pandas.core.arrays import boolean import praw import requests import streamlit as st import datetime import pytesseract pytesseract.pytesseract.tesseract_cmd ='context/tesseract' impo...
18,740
5,664
from npt import log from . import search as Search from . import download as Download from . import processing as Processing from . import mosaic as Mosaic
157
41
class Student: def __init__(self,name,major,gpa): self.name=name self.major=major self.gpa=gpa def on_honor_roll (self): if self.gpa>=8.5: return True else: return False
252
89
token = 'Mzc5NTc3MDc1NTU3NzI4MjU2.DXixQA.DLLB8b81nSyB1IGNJ6WeEeukAQU' #Put Your bots token here prefix = '^^' #put prefix here link = 'https://discordapp.com/oauth2/authorize?client_id=379577075557728256&scope=bot&permissions=134659080' #put bot invite link here ownerid = '227860415709708288' #put your id here...
324
178
class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] start = 0 end = len(nums) - 1 while start <= end: mid = start + ((end - start) // 2) # Check if mid is the single number if start < ...
761
233
# Copyright (c) 2021 John Carrino import struct from dataclasses import dataclass import numpy as np from scipy.spatial.transform import Rotation @dataclass class ThrowData: NUM_POINTS = 2000 SENSORS_GRAVITY_STANDARD = 9.80665 SENSORS_DPS_TO_RADS = 0.017453293 OUTPUT_SCALE_FACTOR_400G = (SENSORS_GRAVI...
3,466
1,307
import unittest import vnmrjpy as vj import numpy as np import matplotlib.pyplot as plt import time #import cupy as cp RP={'rcvrs':4,'filter_size':(11,7),'virtualcoilboost':False} PLOTTING = False class Test_hankelutils(unittest.TestCase): def test_lvl2_hankel_average(self): #rp={'rcvrs':4,'filter_s...
7,754
3,183
#setup import docx2txt # extract text text = docx2txt.process("../documents/ambev.docx") text2 = docx2txt.process("../documents/ambev2.docx") text3 = docx2txt.process("../documents/ambev3.docx") from whoosh.fields import Schema, TEXT schema = Schema(title=TEXT, content=TEXT) import os, os.path from whoosh import i...
1,057
387
from django.urls import path from .views import FileList, FileDetail urlpatterns = [ path('',FileList.as_view()), path('<int:pk>/',FileDetail.as_view()), # individual items from django ]
196
61
""" Generate barcode images with various encodings TODO - Include text at bottom - DXF instead """ #======================================================== # Imports #======================================================== from dxfwrite import DXFEngine as dxf #=====================================================...
4,427
1,416
from django.contrib import admin from cheeseshop.apps.catalog.models import Brand admin.site.register(Brand)
110
33
# 373:查找和最小的 K 对数字 # leetcode submit region begin(Prohibit modification and deletion) from heapq import heappop, heappush from typing import List class Solution: def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: m, n = len(nums1), len(nums2) ans = [] ...
672
269
# Core Django imports. from django.urls import path from django.shortcuts import redirect, render # LMS app imports from lms.views.course.course_views import ( CourseListView,fetch_questions,compute_stats,display_lp,Edit_quiz,preview_quiz,fetch_questions_oneatatime,compute_html,enter_comment,quiz_lp ) ...
2,505
925
"""A module of errors.""" class RasterioIOError(IOError): """A failure to open a dataset using the presently registered drivers.""" class RasterioDriverRegistrationError(ValueError): """To be raised when, eg, _gdal.GDALGetDriverByName("MEM") returns NULL"""
270
82
def parse_boolean(value): if type(value) == bool: return value if value in ['True', 'true', 'T', 't', '1']: return True if value in ['False', 'false', 'F', 'f', '0']: return False return False
236
81