text string | size int64 | token_count int64 |
|---|---|---|
from .utils import *
from .models import *
from .dna import *
| 62 | 20 |
from django import forms
from app.models import Application, Owner, Questionnaire, Tag, Rule, TagType
from crispy_forms.bootstrap import Field
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, ButtonHolder, Fieldset, Hidden, HTML
class ApplicationForm(forms.ModelForm):
cl... | 2,098 | 591 |
import motor.motor_asyncio
import os
mongo_server = os.environ['DB_HOST']
mongo_port = os.environ['DB_PORT']
mongo_db = os.environ['DB_NAME']
mongo_user = os.environ['DB_USER']
mongo_passwd = os.environ['DB_PASSWD']
MONGO_DETAILS = "mongodb://" + mongo_user + ":" + mongo_passwd + "@" + mongo_server + ":" + mongo_port +... | 495 | 186 |
import time
import grovepi
class WaterSensor(object):
def __init__(self, pin=2):
"""
connect sensor to digital port. D2 is default.
:param pin: Number
"""
self.pin = pin
grovepi.pinMode(self.pin, "INPUT")
def get(self):
"""
gets the value measur... | 512 | 161 |
import struct
from .tcpfull import ConnectionTcpFull
class ConnectionTcpAbridged(ConnectionTcpFull):
"""
This is the mode with the lowest overhead, as it will
only require 1 byte if the packet length is less than
508 bytes (127 << 2, which is very common).
"""
async def connect(self, ip, port... | 928 | 295 |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
""" test create new user with an email is successful"""
email = "ahmed.mansy@segmatek.com"
password= "Agmansy0100"
user = get_user_model().objects.cr... | 1,274 | 488 |
import numpy as np
class Light:
_position = np.array([960, 540, 300.0, 1])
_color = np.array([255, 255, 255])
def set_position(position):
Light._position = position
def set_color(color):
Light._color = color
def get_color():
return Light._color
def get_position():
... | 350 | 125 |
# 普通拍照例程
#
# 提示: 你需要插入SD卡来运行这个例程.
#
# 你可以使用你的OpenMV设备保存图片。
#导入相关模块,pyb用于LED控制。
import sensor, image, pyb
RED_LED_PIN = 1
BLUE_LED_PIN = 3
#摄像头相关初始化
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # or sensor.GRAYSCALE
sensor.set_framesize(sensor.QVGA) # or sensor.QQVGA (or others)
... | 727 | 443 |
# encoding: utf-8
import os
from website import settings
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecache'),
}
}
WATERBUTLER_RESOURCE = 'folder'
DISK_SAVING_MODE = se... | 344 | 141 |
#Example of dot product using numpy
import numpy as np
#Sample input to perceptron
inputs = [1.2, 2.2, 3.3, 2.5]
#Weights passed to perceptron
weights = [0.4,0.6,-0.7, 1.1]
#bias for a particular perceptron
bias = 2
#Take dot product between weights and input
#and add bias to the summation value
output = np.dot(in... | 371 | 145 |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Copyright (c) 2015-2019 Analog Devices, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... | 4,725 | 1,824 |
from django import forms
from .models import Product, Category
from mptt.forms import TreeNodeChoiceField
from django.forms.fields import ImageField
class ProductForm(forms.Form):
title = forms.CharField(
label='',
widget=forms.TextInput(
attrs={
'placehol... | 962 | 253 |
# Generated by Django 3.2 on 2021-06-16 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adminweb', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profissional',
name='cep',
... | 376 | 127 |
from .models import Input, Output, InputToOutput, Device
from rest_framework import serializers
from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer)
from taggit.models import Tag
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields ... | 7,064 | 2,081 |
from threading import Thread
from time import sleep
import win32api, win32con
import pyautogui
import keyboard
import os
def clickPositions(all_positions, repeat, timeout):
#Activate safety killswitch
thread = Thread(target = safetyKillswitch)
thread.start()
should_repeat = True
iteration = 0... | 894 | 292 |
"""
"""
import support
support.compileJPythonc("test256a.py", core=1, jar="test256.jar", output="test256.err")
#raise support.TestError("" + `x`)
| 150 | 64 |
import json
from pathlib import Path
from typing import Any, Dict
from git import Repo
from cruft.exceptions import CruftAlreadyPresent, NoCruftFound
CruftState = Dict[str, Any]
#######################
# Cruft related utils #
#######################
def get_cruft_file(project_dir_path: Path, exists: bool = True)... | 1,307 | 415 |
"""Main entrypoint for the repobee CLI application.
.. module:: main
:synopsis: Main entrypoint for the repobee CLI application.
.. moduleauthor:: Simon Larsén
"""
import argparse
import contextlib
import io
import logging
import os
import pathlib
import sys
from typing import List, Optional, Union, Mapping
from... | 8,604 | 2,483 |
from enum import Enum
class TestCommonConfig(object):
LOGGER_NAME = "testing-logger"
SHEET_TEST_DIRNAME = "sheets"
EMAIL_TEMPLATE_TEST_DIRNAME = "templates"
class TestSheetColHeader(Enum):
"""
TestEnHeader.xlsx 與 TestCnHeader.xlsx 的 Column 標頭定義,差異為英文跟中文
"""
EN_HOTELNAME = "HotelName"
... | 6,871 | 3,269 |
# 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... | 4,055 | 1,284 |
# -*- coding: utf-8 -*-
u"""
.. module:: labeled_status
"""
from django import template
from apps.volontulo.utils import OFFERS_STATUSES
register = template.Library()
@register.filter(name='human')
def human(status):
u"""Get offer status description.
:param status: string Status key
"""
return O... | 355 | 121 |
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
import eslint
from py_vulcanize import strip_js_comments
from catapult_build import parse_html
class JSChecker(object):
def __init__(sel... | 3,400 | 1,075 |
import enum
from django.db import models
from care.facility.models import FacilityBaseModel
from care.users.models import User
from django.contrib.postgres.fields import JSONField
class Notification(FacilityBaseModel):
class EventType(enum.Enum):
SYSTEM_GENERATED = 50
CUSTOM_MESSAGE = 100
E... | 1,919 | 702 |
from selenium import webdriver
from selenium import *
def start():
return webdriver.Chrome(executable_path='./services/chromedriver')
if __name__ == "__main__":
pass
| 176 | 53 |
from django.contrib import admin
from .models import Grade
admin.site.register(Grade)
| 87 | 26 |
import numpy as np
def calculate_iou(bboxes1, bboxes2):
"""
This calculates the intersection over union of N bounding boxes
in the form N x [left, top, right, bottom], e.g for N=2:
>> bb = [[21,34,45,67], [67,120, 89, 190]]
:param bboxes1: np array: N x 4 ground truth bounding boxes
:param bb... | 1,492 | 630 |
"""
Russian Peasant Multiplication (RPM) Algorithm Implemented In Python
RPM is a method of mutiplication of any 2 numbers using only multiplication
and division by 2.
The basics are that you divide the second number by 2 (integer division) until
it equals 1, every time you divide the second number by 2, you also multi... | 2,027 | 640 |
#!/usr/bin/env python # -*- coding: utf-8 -*-
import os
from collections import defaultdict
import cPickle as pkl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import codecs
import nltk
from nltk import compat
from nltk.tree import Tree
import nltk.data
from deptree import DependencyTree, Depe... | 34,989 | 9,809 |
from __future__ import print_function, unicode_literals
import os
from datetime import timedelta
import multiuploader.default_settings as DEFAULTS
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from multiuploader.models import MultiuploaderFi... | 1,056 | 289 |
import unittest
from app.models import Source
class testSource(unittest.TestCase):
"""
SourcesTest class to test the behavior of the Sources class
"""
def setUp(self):
"""
Method that runs before each other test runs
"""
self.new_source = Source('abc-news','ABC news','Yo... | 540 | 156 |
from typing import Literal, TypedDict
class ForvoAPIItem(TypedDict):
id: int
word: str
original: str
addtime: str
hits: int
username: str
sex: str
country: str
code: str
langname: str
pathmp3: str
pathogg: str
rate: int
num_votes: int
num_positive_votes: int... | 432 | 151 |
import os
import csv
import time
import stria
import pyfastx
import traceback
import multiprocessing
from PySide6.QtCore import *
from primer3 import primerdesign
from motif import *
from stats import *
from utils import *
from config import *
from backend import *
from annotate import *
__all__ = [
'SSRSearchThre... | 16,522 | 7,239 |
'''
Training a deep "incomplete" ANN on MNIST with Tensorflow
The ANN has no bias and no activation function
This function does not learn very well because the the hypothesis is completely off
The loss function is bad. The network is unstable in training (easily blow up) and
fails to learn the training dataset (<20%... | 3,327 | 1,200 |
import pytest
import structlog
@pytest.fixture(autouse=True)
def setup():
structlog.configure(
processors=[
structlog.processors.JSONRenderer(ensure_ascii=False),
],
context_class=structlog.threadlocal.wrap_dict(dict),
logger_factory=structlog.stdlib.LoggerFactory(),
... | 416 | 126 |
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import os
import urllib.parse as urlparse
class PostgresBaseManager:
def __init__(self,local):
self.database = 'postgres'
self.user = 'postgres'
self.password = '1234'
self.host = 'localhost'
self.p... | 3,271 | 1,101 |
#!/usr/bin/env python
import setpath
from bike.testutils import *
from bike.transformer.save import save
from moveToModule import *
class TestMoveClass(BRMTestCase):
def test_movesTheText(self):
src1=trimLines("""
def before(): pass
class TheClass:
pass
def after(): pas... | 6,763 | 1,792 |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Add test_plan field
Create Date: 2017-08-23 16:27:55.094736
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sqlalchemy as sa
f... | 924 | 349 |
import pandas as pd
import numpy as np
from math import *
import copy # deep copy objects
from model_param import *
#------------------------------------------------------------------------------
# Figure out when to launch another block for current kernel
#------------------------------------------------------------... | 16,818 | 4,511 |
import _ast
import ast
from typing import Dict, Union
import os
from pychecktext import teamcity, teamcity_messages
class CheckTextVisitor(ast.NodeVisitor):
def __init__(self, aliases: Dict[str, str] = {}):
self.literal_calls = []
self.expression_calls = []
self.aliases = aliases
s... | 4,322 | 1,272 |
# -*- coding: utf-8 -*-
"""
@author : Haoran You
"""
import sys
import data
from Apriori import Apriori
from optparse import OptionParser
optparser = OptionParser()
optparser.add_option('--inputFile', dest='input', help='filename containing csv', default='goods.csv')
optparser.add_option('--minSupport', dest='minS', ... | 834 | 271 |
import discord
from discord.ext import commands
import os
from .player import Player
from extra.menu import ConfirmSkill
import os
from datetime import datetime
bots_and_commands_channel_id = int(os.getenv('BOTS_AND_COMMANDS_CHANNEL_ID'))
class Agares(Player):
emoji = '<:Agares:839497855621660693>'
def __i... | 8,791 | 2,785 |
"""
Module responsible for all automation related to the device
"""
__author__ = 'Henrique da Silva Santos'
__copyright__ = 'Copyright 2020, WhatsAppManifest'
from WhatsAppManifest.automator.android.phone import AndroidPhone
from WhatsAppManifest.automator.android.contacts import AndroidContacts
| 300 | 89 |
from threp import THReplay
if __name__ == '__main__':
# 载入一个replay文件,参数为路径
tr = THReplay('rep_tst/th13_01.rpy')
# 获取rep基本信息,包含机体,难度,通关情况,字符串
# etc. Reimu A Normal All
print(tr.getBaseInfo())
# 获取rep基本信息的字典,包含机体,难度,通关情况,字符串
# 字典的键分别为 character shottype rank stage
# etc. Reimu A Normal ... | 1,968 | 1,356 |
import pytest
from django.urls import reverse
class TestHealthCheck:
def test_return_success_when_accessing_health_check(self, api_client, url):
response = api_client.get(url, format="json")
assert response.status_code == 200
assert list(response.json().keys()) == ["status", "time"]
... | 901 | 282 |
from __future__ import annotations
import typing
from dataclasses import dataclass
from solana.publickey import PublicKey
from anchorpy.borsh_extension import EnumForCodegen, BorshPubkey
import borsh_construct as borsh
class WonJSONValue(typing.TypedDict):
winner: str
class WonValue(typing.TypedDict):
winne... | 2,768 | 911 |
# -*- coding: utf-8 -*-
#
import pytest
import optimesh
from helpers import download_mesh
@pytest.mark.parametrize(
"options",
[
["--method", "cpt-dp"],
["--method", "cpt-uniform-fp"],
["--method", "cpt-uniform-qn"],
#
["--method", "cvt-uniform-lloyd"],
["--me... | 1,196 | 552 |
class WindowInteropHelper(object):
"""
Assists interoperation between Windows Presentation Foundation (WPF) and Win32 code.
WindowInteropHelper(window: Window)
"""
def EnsureHandle(self):
"""
EnsureHandle(self: WindowInteropHelper) -> IntPtr
Creates the HWND of the window if the HWND has ... | 1,087 | 351 |
# pylint: skip-file
# flake8: noqa
'''
OpenShiftCLI class that wraps the oc commands in a subprocess
'''
# pylint: disable=too-many-lines
from __future__ import print_function
import atexit
import json
import os
import re
import shutil
import subprocess
import tempfile
# pylint: disable=import-error
import ruamel.y... | 385 | 124 |
#!/usr/bin/env python
'''
Tests for bamutils stats
'''
import os
import unittest
import ngsutils.bam
import ngsutils.bam.stats
class StatsTest(unittest.TestCase):
def setUp(self):
self.bam = ngsutils.bam.bam_open(os.path.join(os.path.dirname(__file__), 'test.bam'))
def tearDown(self):
self.... | 1,025 | 374 |
from unittest import TestCase
from bavard_ml_utils.gcp.gcs import GCSClient
from test.utils import DirSpec, FileSpec
class TestGCSClient(TestCase):
test_data_spec = DirSpec(
path="gcs-test",
children=[
FileSpec(path="test-file.txt", content="This is a test."),
FileSpec(pat... | 2,042 | 648 |
# Peter Kowalsky - 10.06.19
import os
def check_if_file_exists(path):
exists = os.path.isfile(path)
if exists:
return 1
else:
return 0
def list_all_files_in_dir(path, type):
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if type in file:
... | 357 | 145 |
from fim_mission import *
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision.transforms as transforms
from torchvision import datasets, models
import matplo... | 2,746 | 986 |
from __future__ import print_function
import os
import sys
import numpy as np
from keras.models import Model
from keras.layers import Input, concatenate, Conv1D, MaxPooling1D, Conv2DTranspose,Lambda
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras import backend as K
import tens... | 4,337 | 1,596 |
import spacy
from spacy_langdetect import LanguageDetector
import en_core_web_sm
from glob import glob
nlp = en_core_web_sm.load()
#nlp = spacy.load('en')
nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)
print(LanguageDetector) | 252 | 90 |
# Copyright (C) 2009 Matthew McGowan
#
# Authors:
# Matthew McGowan
#
# This program 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, either version 3 of the License, or
# (at your option) any later version.
... | 43,623 | 15,044 |
import subprocess
import socket
import redis
import time
import os
import os.path
import sys
import warnings
import random
REDIS_DEBUGGER = os.environ.get('REDIS_DEBUGGER', None)
REDIS_SHOW_OUTPUT = int(os.environ.get(
'REDIS_VERBOSE', 1 if REDIS_DEBUGGER else 0))
def get_random_port():
while True:
... | 5,971 | 1,730 |
'''Contains DiscoAutoscale class that orchestrates AWS Autoscaling'''
import logging
import random
import boto
import boto.ec2
import boto.ec2.autoscale
import boto.ec2.autoscale.launchconfig
import boto.ec2.autoscale.group
from boto.ec2.autoscale.policy import ScalingPolicy
from boto.exception import BotoServerError
... | 16,843 | 4,794 |
# coding=utf-8
# Copyright 2022 The Google Research 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 17,621 | 5,697 |
#!/usr/bin/env python
# coding=utf-8
__metaclass__ = type
class Fibs:
"""docstring for Fibc"""
def __init__(self):
self.a = 0
self.b = 1
def next(self):
self.a, self.b = self.b, self.a+self.b
return self.a
def __iter__(self):
return self
fibs = Fibs()
for f in f... | 438 | 184 |
# draws a shape and fills with a colour
import turtle
import math
import colorsys
phi = 180 * (3 - math.sqrt(5))
# initialises the turtle Pen
t = turtle.Pen()
t.speed()
# defines the shape to be drawn
def square(t, size):
for tmp in range(0,4):
t.forward(size)
t.right(90)
num = 200
for x in reversed(range(0, ... | 517 | 241 |
"""
Additional utilities and patches for MiniNExT.
"""
from os.path import isdir
import os
import pwd
import grp
import shutil
from mininet.util import quietRun
from mininext.mount import ObjectPermissions
# Patches #
def isShellBuiltin(cmd):
"""Override to replace MiniNExT's existing isShellBuiltin() function... | 12,073 | 3,449 |
""" RealDolos' funky volafile upload tool"""
# pylint: disable=broad-except
import math
import re
import sys
# pylint: disable=no-name-in-module
try:
from os import posix_fadvise, POSIX_FADV_WILLNEED
except ImportError:
def posix_fadvise(*args, **kw):
"""Mock implementation for systems not supporting... | 2,575 | 941 |
# The Hazard Library
# Copyright (C) 2013-2018 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#... | 3,801 | 1,352 |
import os
from os import path, environ
from configparser import ConfigParser
from collections import OrderedDict
class Config(object):
"""
This class will take care of ConfigParser and writing / reading the
configuration.
TODO: What to do when there are more variables to be configured? Should we
... | 2,395 | 689 |
import h5py
import numpy as np
from code.model import UNetClassifier
def load_dataset(covid_file_path, normal_file_path):
covid = h5py.File(covid_file_path, 'r')['covid']
normal = h5py.File(normal_file_path, 'r')['normal']
all_images = np.expand_dims(np.concatenate([covid, normal]), axis=3)
all_labe... | 819 | 327 |
''' Every type you encounter ##EDIT_ME## you will need to adjust these settings '''
import pandas as pd
import numpy as np
import module_youtube_extract
import module_convert_audio_to_wav
import module_process_subtitles
import module_save_variables
import module_video_processing
import module_sample_name
import module_... | 54,947 | 22,804 |
import os
from kids.cache import cache
from datetime import datetime
from datmo.core.util.i18n import get as __
from datmo.core.entity.model import Model
from datmo.core.entity.code import Code
from datmo.core.entity.environment import Environment
from datmo.core.entity.file_collection import FileCollection
from datmo... | 9,462 | 2,589 |
def main():
_ = input()
string = input()
if _ == 0 or _ == 1:
return 0
if _ == 2:
if string[0] == string[1]:
return 1
return 0
last = string[0]
cnt = 0
for i in range(1, len(string)):
if string[i] == last:
cnt += 1
last = str... | 358 | 133 |
from app import app
from flask import render_template, flash, redirect, url_for
from app.forms import LoginForm
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/contato', methods=['GET','POST'])
def contato():
form = LoginForm()
if form.validate_on_submit... | 573 | 171 |
num = int(input("Enter a number: "))
sum = 0; size = 0; temp = num; temp2 = num
while(temp2!=0):
size += 1
temp2 = int(temp2/10)
while(temp!=0):
remainder = temp%10
sum += remainder**size
temp = int(temp/10)
if(sum == num):
print("It's an armstrong number")
else:
print("It's not an arms... | 336 | 134 |
# 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... | 174,251 | 53,270 |
import base64
import requests
from werkzeug.exceptions import BadRequest, NotFound
from flask import request, current_app, Response
from flask_restplus import Resource
from app.extensions import api
from ...mine.models.mine import Mine
from ....documents.mines.models.mine_document import MineDocument
from ....documen... | 4,189 | 1,195 |
from . import *
class AWS_DataPipeline_Pipeline_ParameterAttribute(CloudFormationProperty):
def write(self, w):
with w.block("parameter_attribute"):
self.property(w, "Key", "key", StringValueConverter())
self.property(w, "StringValue", "string_value", StringValueConverter())
class AWS_DataPipeline_... | 2,709 | 831 |
import collections.abc as collections_abc
import os.path as osp
from addict import Dict
import yaml
class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyErro... | 2,295 | 673 |
# MIT License
#
# Copyright (c) 2020 Deng Cai
#
# 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, merge, pub... | 7,748 | 2,404 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from collections import Counter
import numpy as np
import theano
import theano.tensor as T
punctuation = set(string.punctuation)
punctuation.add('\n')
punctuation.add('\t')
punctuation.add(u'’')
punctuation.add(u'‘')
punctuation.add(u'“')
punctuation.add(u'”... | 5,252 | 1,801 |
from django.apps import AppConfig
class AgendamentoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'agendamentos'
| 155 | 49 |
#!/usr/bin/env python3
"""This is a simple python3 calculator for demonstration purposes
some to-do's but we'll get to that"""
__author__ = "Sebastian Meier zu Biesen"
__copyright__ = "2000-2019 by MzB Solutions"
__email__ = "smzb@mitos-kalandiel.me"
class Calculator(object):
@property
def isDebug(self):
... | 3,443 | 1,069 |
import os
import sys
import time
import pyfiglet
from scapy.all import*
os.system("clear")
print (chr(27)+"[36m")
import pyfiglet
banner = pyfiglet.figlet_format("Tcp Syn Flood",font="slant")
print (banner)
print (chr(27)+"[33m")
print (" Author : Rahat Khan Tusar(RKT)")
print (" Github... | 1,001 | 436 |
import pickle
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
import pytest
from oddt.scoring.models import classifiers, regressors
@pytest.mark.filterwarnings('ignore:Stochastic Optimizer')
@pytest.mark.parametrize('cls',
[classifiers.svm(probabil... | 1,957 | 728 |
# -*- coding: utf-8 -*-
import pdb, six, importlib
import pandas as pd
from PyFin.api import makeSchedule, BizDayConventions
from sqlalchemy import create_engine, select, and_, or_
from utilities.singleton import Singleton
import sys
sys.path.append('..')
import config
# 连接句柄
@six.add_metaclass(Singleton)
class SQLE... | 9,570 | 2,969 |
from google.appengine.ext import ndb
class Collaborator(ndb.Model):
"""
Represents collab relationship at events
Notifications will only be sent if both the
sender and receiver have shared with each other
"""
srcUserId = ndb.StringProperty(required=True)
dstUserId = ndb.StringProperty(req... | 549 | 171 |
from graphene import Int
from .decorators import require_authenication
class PrimaryKeyMixin(object):
pk = Int(source='pk')
class LoginRequiredMixin(object):
@classmethod
@require_authenication(info_position=1)
def get_node(cls, info, id):
return super(LoginRequiredMixin, cls).get_node(inf... | 327 | 112 |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["FlagPriorityCodes"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class FlagPriorityCodes:
"""
Flag Priority Codes
This value set is provided a... | 1,237 | 401 |
"""SonarQube duplicated lines collector."""
from .base import SonarQubeMetricsBaseClass
class SonarQubeDuplicatedLines(SonarQubeMetricsBaseClass):
"""SonarQube duplicated lines collector."""
valueKey = "duplicated_lines"
totalKey = "lines"
| 256 | 87 |
# Generated by Django 3.2.9 on 2021-11-23 16:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='studentmodel',
name='DOB',
fi... | 370 | 127 |
import numpy as np
import torch
from typing import List
from sl_cutscenes.constants import SCENARIO_DEFAULTS
from sl_cutscenes.utils.camera_utils import ConstFunc, LinFunc, LinFuncOnce, SinFunc, TanhFunc
camera_movement_constraints = SCENARIO_DEFAULTS["camera_movement"]
class Camera(object):
'''
The camera o... | 6,159 | 2,012 |
import copy
import uuid
import json
from datetime import timedelta
from dateutil.parser import parse
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.views import auth_logout
from django.core.paginator import Paginator
fro... | 23,016 | 6,835 |
#Tests that blocks can't have multiple verification packets for the same transaction.
from typing import Dict, Any
import json
from pytest import raises
from e2e.Libs.Minisketch import Sketch
from e2e.Classes.Transactions.Data import Data
from e2e.Classes.Consensus.VerificationPacket import VerificationPacket
from e... | 2,251 | 749 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018年4月17日 @author: encodingl
'''
from django.shortcuts import render
#from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse
import paramiko
from django.contrib.auth.decorators import login_required
... | 2,891 | 906 |
from __future__ import print_function
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth import get_user_model
import os
from django.core.mail import send_mail
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.st... | 9,482 | 3,534 |
'''
Напишите программу, которая объявляет переменную: "name" и присваивает ей значение "Python".
Программа должна напечатать в одну строку, разделяя пробелами:
Строку "name"
Значение переменной "name"
Число 3
Число 8.5
Sample Input:
Sample Output:
name Python 3 8.5
'''
name = 'Python'
print('name', name, 3, 8.5)
| 316 | 137 |
# Created by Andrew Silva
# Extensions to https://github.com/nimarb/pytorch_influence_functions
import torch
import time
import datetime
import numpy as np
import copy
import logging
from torch.autograd import grad
import random
from cross_loss_influence.helpers.bolukbasi_prior_work.prior_pca_debiasing import extract_... | 24,568 | 7,830 |
"""
Test the fits-module by loading a dumped rtfits result and performing
all actions again
"""
import unittest
import numpy as np
import cloudpickle
import matplotlib.pyplot as plt
import copy
import os
class TestDUMPS(unittest.TestCase):
def setUp(self):
self.sig0_dB_path = os.path.dirname(__file__) + ... | 6,189 | 1,680 |
import numpy as np
from carculator_bus import *
tip = BusInputParameters()
tip.static()
_, array = fill_xarray_from_input_parameters(tip)
tm = BusModel(array, country="CH")
tm.set_all()
def test_presence_PHEVe():
# PHEV-e should be dropped
assert "PHEV-e" not in tm.array.powertrain.values.tolist()
def tes... | 3,234 | 1,090 |
# -*- coding: utf-8 -*-
"""
Ejercicio 2: Aproximación numérica de orden 1 y de orden 2 de la
derivada de la función f(x) = 1/x.
"""
import numpy as np
import matplotlib.pyplot as plt
# Función f(x)= 1/x y su derivada f'
f = lambda x:1/x # función f
df = lambda x:(-1)/x**2 # derivada exacta f'
#-----------... | 2,828 | 1,030 |
#!/usr/bin/env python
# coding: utf-8
#
# Copyright 2021 ONDEWO GmbH
#
# 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 ap... | 1,982 | 693 |
#!/usr/bin/python
# Copyright 2007 Google Inc. All rights reserved.
"""Extract UserMetrics "actions" strings from the Chrome source.
This program generates the list of known actions we expect to see in the
user behavior logs. It walks the Chrome source, looking for calls to
UserMetrics functions, extracting actions... | 4,149 | 1,367 |
#!/bin/env python
# Copyright (c) 2019 Platform9 Systems 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 applica... | 1,817 | 522 |
from __future__ import annotations
# Standard library
import re
from copy import deepcopy
from dataclasses import dataclass
from typing import Callable, Optional
__all__ = ['NamedEntity', 'NamedEntityList']
@dataclass(frozen=True)
class NamedEntity:
name: str
entity: str
string: str
span: tuple[int... | 2,898 | 847 |