index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,100 | baf3bde709ec04b6f41dce8a8b8512ad7847c164 | def multiple_parameters(name, location):
print(f"Hello {name}")
print(f"I live in {location}")
#positional arguments
multiple_parameters("Selva", "Chennai")
#keyword arguments
multiple_parameters(location="Chennai", name="Selva")
|
3,101 | 00be3d813ce4335ff9ea02ed9f1884d3210f3d5a | #!/usr/bin/env python
import pathlib
from blastsight.view.viewer import Viewer
"""
In this demo, we'll show how you can create a basic animation.
An animation is interpreted as changing the state of the viewer one frame at the time.
That means we'll define a function that makes a change in one single frame.
The fun... |
3,102 | 342063b37038c804c2afa78091b1f1c2facbc560 | import base64
import json
from werkzeug.exceptions import Unauthorized
from ab import app
from ab.utils import logger
from ab.plugins.spring import eureka
def _login(username, password):
"""
only for test
:return the access token
"""
try:
logger.info('login as user {username}'.format(us... |
3,103 | e2d8a1e13a4162cd606eec12530451ab230c95b6 | from unittest.mock import MagicMock
import pytest
from charpe.mediums.email_handler import EmailHandler
from charpe.errors import InsuficientInformation
def test_send_requirements(config):
handler = EmailHandler(config)
with pytest.raises(InsuficientInformation):
handler.publish({})
with pytest... |
3,104 | 71eadf5073b5ed13c7d4a58b2aeb52f550a32238 | #!/usr/bin/env python3
import argparse
import json
import os
import random
import timeit
from glob import glob
import numpy as np
def parse_args():
"""[summary]
Returns:
[type]: [description]
"""
parser = argparse.ArgumentParser()
parser.add_argument('--train_dir',
... |
3,105 | 6fd4df7370de2343fe7723a2d8f5aacffa333835 | import pickle
import pytest
from reader import EntryError
from reader import FeedError
from reader import SingleUpdateHookError
from reader import TagError
from reader.exceptions import _FancyExceptionBase
def test_fancy_exception_base():
exc = _FancyExceptionBase('message')
assert str(exc) == 'message'
... |
3,106 | 5663ded291405bcf0d410041485487bb17560223 |
"""
《Engineering a Compiler》
即《编译器设计第二版》
https://www.clear.rice.edu/comp412/
"""
# 《parsing-techniques》 讲前端
## http://parsing-techniques.duguying.net/ebook/2/1/3.html
"""
前端看Parsing Techniques,后端看鲸书,都是最好的。
"""
# 《essential of programming language》
# sicp
"""
如果对编程语言设计方面感兴趣,想对编程语言和编译器设计有大概的概念,可以看看PLP。
想快速实践可以看《自制脚本语... |
3,107 | 29abcfc010453e3a67346ea2df238e07b85502a8 | """
Estructuras que extraen valores de una función y se almacenan en objetos iterables (que se pueden recorrer
Son mas eficientes que las funciones tradicionales
muy útiles con listas de valores infinitos
Bajos determinados escenarios, será muy útil que un generador devuelva los valores de uno en uno
Un generador ... |
3,108 | 46d6771fd9f589e2498cd019ba72232cbda06e5a | from editor.editor import Editor
e = Editor()
e.showWindow() |
3,109 | 1829bd8e87c470a71fea97dd3a47c30477b6e6f1 | """"Pirata barba Negra ( màs de 2 pasos a las izquierda o a la derecha y se cae):
rampa para subir a su barco (5 pasos de ancho y 15 de largo")leer por teclado un valor entero.
a) si el entero es par 1 paso hacia adelante
b)si el entero es impar , pero el entero - 1 es divisible por 4, el pirata da un paso a la derec... |
3,110 | a1c1f18e7b95f36a214a1a16f2434be2825829c3 | import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
import matplotlib.pyplot as plt
from sympy import sympify, Symbol
curr_pos = 0
import numpy as np
def bisection(st,maxnum,maxer,xlf,xuf):
file2 = open("test.txt","w")
file2.write("Hello World")
file2.close()
fi = open("test.txt", "w")
x... |
3,111 | 3272296bca0d6343540597baebef8d882a1267c0 | from ..core import promise, rule
_context = {
'@vocab': 'https://schema.org/',
'fairsharing': 'https://fairsharing.org/',
'html': 'fairsharing:bsg-s001284',
}
@promise
def resolve_html(url):
from urllib.request import urlopen
return urlopen(url).read().decode()
@rule({
'@context': _context,
'@type': 'W... |
3,112 | 01f4d097cc5f4173fa5a13268b91753566a9f7e1 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: Sequitr
# Purpose: Sequitr is a small, lightweight Python library for common image
# processing tasks in optical microscopy, in particular, single-
# molecule imaging, super-resolution... |
3,113 | 8397dcdcb9ec2f35dac0c26b8878a23f9149512b |
import os
# must pip install sox
# type sudo apt install sox into cmd
duration = .2 # seconds
freq = 550 # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
|
3,114 | e045dc348fb2e9de51dbeada1d1826211cf89eae | from terminaltables import AsciiTable
import copy
table_data = [
['WAR', 'WAW'],
['S1 -> S2: R1', 'row1 column2'],
['row2 column1', 'row2 column2'],
['row3 column1', 'row3 column2']
]
table = AsciiTable(table_data)
def getDependenceStr(ins1, ins2, reg):
return f"{ins1} -> {ins2}: {reg}"
def get... |
3,115 | f114a86a3c6bea274b01763ce3e8cd5c8aea44a0 | # -*- coding: utf-8 -*-
num = input().split()
A = float(num[0])
B = float(num[1])
C = float(num[2])
if A == 0:
print("Impossivel calcular")
else:
delta = B**2 - (4*A*C)
if delta < 0.0:
print("Impossivel calcular")
else:
raiz = delta ** 0.5
r1 = (-B+raiz)/(2*A)
r2 =... |
3,116 | 1811c0c5aca9d209638e2221cad2c30e80ee5199 | #Takes - Contact Name(Must be saved in phone's contact list), Message, Time as input
# and sends message to the given contact at given time
# Accuracy Level ~ Seconds. (Also depends on your network speed)
from selenium import webdriver
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
f... |
3,117 | e50feccd583d7e33877d5fcc377a1d79dc247d3a |
import pickle
class myPickle:
def make(self, obj,fileName):
print("myPickle make file",fileName)
pickle.dump( obj, open(fileName,'wb') )
print(" DONE")
def load(self, fileName):
print("myPickle load file",fileName)
tr = pickle.load( open(fileName,'rb') ... |
3,118 | 61085eecc8fd0b70bc11e5a85c3958ba3b905eaf | # Jython/Walk_comprehension.py
import os
restFiles = [os.path.join(d[0], f) for d in os.walk(".")
for f in d[2] if f.endswith(".java") and
"PythonInterpreter" in open(os.path.join(d[0], f)).read()]
for r in restFiles:
print(r)
|
3,119 | 0aa0fcbb0ec1272bea93574a9287de9f526539c8 | import torch
def DiceLoss(pred,target,smooth=2):
# print("pred shape: ",pred.shape)
# print("target shape: ",target.shape)
index = (2*torch.sum(pred*target)+smooth)/(torch.sum(pred)+torch.sum(target)+smooth)
#if torch.sum(target).item() == 0:
#print("instersection: ",torch.sum(pred*target).item())
... |
3,120 | c233ce4e14e9a59a9fb0f29589ced947efeb73a9 | """Tests for flatten_me.flatten_me."""
import pytest
ASSERTIONS = [
[[1, [2, 3], 4], [1, 2, 3, 4]],
[[['a', 'b'], 'c', ['d']], ['a', 'b', 'c', 'd']],
[['!', '?'], ['!', '?']],
[[[True, False], ['!'], ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]
]
@pytest.mark.parametrize("n, result", ASSERTI... |
3,121 | ebe79cf1b54870055ce8502430f5fae833f3d96d | import matplotlib.pyplot as plt
def visualize_data(positive_images, negative_images):
# INPUTS
# positive_images - Images where the label = 1 (True)
# negative_images - Images where the label = 0 (False)
figure = plt.figure()
count = 0
for i in range(positive_images.shape[0]):
... |
3,122 | a0086a9d27a091776378cd8bde31c59899fc07ac | """Tools for working with Scores."""
from typing import List, Optional
from citrine._serialization import properties
from citrine._serialization.polymorphic_serializable import PolymorphicSerializable
from citrine._serialization.serializable import Serializable
from citrine._session import Session
from citrine.informa... |
3,123 | 6782761bcbf53ea5076b6dfb7de66d0e68a9f45d | import json
import requests
import config
class RequestAnnotation:
def schedule(self,
command: str,
**kwargs):
response = requests.post(url=f"http://localhost:{config.annotation_port}/{command}",
json=kwargs)
# not 'text' for annotating, but... |
3,124 | 65aa27addaec6014fe5fd66df2c0d3632231a314 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from connect import Connect
class Resource:
def __init__(self, row: tuple):
self.video_path = row[0]
self.pic_path = row[1]
|
3,125 | fda73b5dac038f077da460d6ebfb432b756909d9 | #
# linter.py
# Linter for SublimeLinter version 4.
#
# Written by Brian Schott (Hackerpilot)
# Copyright © 2014-2019 Economic Modeling Specialists, Intl.
#
# License: MIT
#
"""This module exports the D-Scanner plugin class."""
from SublimeLinter.lint import Linter, STREAM_STDOUT
class Dscanner(Linter):
"""Pro... |
3,126 | f8c85f34fb55ee1c3b3020bcec87b60ae80e4ed2 | import sqlite3
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS hands"
+ "(id INTEGER PRIMARY KEY, first INTEGER,"
+ ... |
3,127 | a7d8efe3231b3e3b9bfc5ef64a936816e8b67d6c | """
Copyright © 2017 Bilal Elmoussaoui <bil.elmoussaoui@gmail.com>
This file is part of Authenticator.
Authenticator 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 ... |
3,128 | 20637e41df8a33e3837905a4729ae0b4a9f94dbb | """to get the all the module and its location"""
import sys
print(sys.modules)
|
3,129 | b4267612e7939b635542099e1ba31e661720607a | #from getData import getRatings
import numpy as np
num_factors = 10
num_iter = 75
regularization = 0.05
lr = 0.005
folds=5
#to make sure you are able to repeat results, set the random seed to something:
np.random.seed(17)
def split_matrix(ratings, num_users, num_movies):
#Convert data into (IxJ... |
3,130 | 11163dc99ee65ab44494c08d81e110e9c42390ae | # -*- coding: utf-8 -*-
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.middleware.csrf import get_token
from django.template.context import Context
from django.utils.translation impor... |
3,131 | 8186b7bddbdcdd730a3f79da1bd075c25c0c3998 | import uuid
from website.util import api_v2_url
from django.db import models
from osf.models import base
from website.security import random_string
from framework.auth import cas
from website import settings
from future.moves.urllib.parse import urljoin
def generate_client_secret():
return random_string(lengt... |
3,132 | 1d4df09256324cce50fad096cdeff289af229728 | from PyQt5.QtCore import QObject, pyqtSlot
from Controllers.BookController import BookController
from Model.BookModel import BookModel
from Controllers.DatabaseController import DatabaseController
#Issuance Controller class contains the issuance properties and performs database operations for the issuance
class Issuan... |
3,133 | be7fb94c3c423b67aa917a34328acda5926cf78a | from django.urls import path
from .views import PostListView, PostDetailView
urlpatterns = [
path('blog/', PostListView.as_view()),
path('blog/<pk>/', PostDetailView.as_view()),
] |
3,134 | 07a172c28057dc803efdbdc10a9e2e11df4e527b | from room import Room
from player import Player
from item import Item
# Declare all the rooms
items = {
'scimitar': Item('Scimitar', '+7 Attack'),
'mace': Item('Mace', '+13 Attack'),
'tower_shield': Item('Tower Shield', '+8 Block'),
'heraldic_shield': Item('Heraldic Shield', '+12 Block'),
'chainmail... |
3,135 | b53b0e6ff14750bbba3c2e5e2ea2fc5bb1abccec | import math as m
import functions_by_alexandra as fba
import funs
from functions_by_alexandra import User, a
from pkg import bps, geom
print(type(funs))
print(type(funs.add ))
#
# print(add(2,3))
print("Result: ", funs.add(10, 20))
print("Result: ", fba.add(10,20))
print(type(fba ))
print(a )
print(m... |
3,136 | ff1bb2634ffec6181a42c80a4b2a19c2c27a8f9f | import socket
from Server.MachineClient.Identification import Identification
from Server.SQL import DataBase
import threading
import time
from Server.Connection.AcceptClients import Accept
from Server.Connection.ConnectionCheck import ConnectionCheck
from Server.Clients_Data import Clients
class MachineClient:
de... |
3,137 | b32784bf398a58ba4b6e86fedcdc3ac9de0e8d51 | from django import forms
from django.core.exceptions import ValidationError
from django.db import connection
from customer.helper_funcs import dictfetchall
class OrderForm(forms.Form):
item_id = forms.IntegerField(required=True)
quantity = forms.IntegerField(required=True)
def clean(self):
cleane... |
3,138 | 16db443642746af4ae45862627baaa9eca54a165 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 18:45:08 2020
@author: Neeraj
"""
import cv2
import numpy as np
num_down=2
num_bilateral=50
img_rgb=cv2.imread("stunning-latest-pics-of-Kajal-Agarwal.jpg") #image path
img_rgb=cv2.resize(img_rgb,(800,800))
img_color=img_rgb
for _ in range(num_... |
3,139 | 87c413051ed38b52fbcc0b0cf84ecd75cd1e3f0c | import sys, getopt
import sys, locale
import httplib
import json
#sys.argv = [sys.argv[0], '--id=275', '--ofile=275.json']
def getRouteId(routeName, out_filename):
conn = httplib.HTTPConnection("data.ntpc.gov.tw")
qryString = "/od/data/api/67BB3C2B-E7D1-43A7-B872-61B2F082E11B?$format=json&$filter=nameZh%20eq%... |
3,140 | 46b1991bba83968466390d306a4415b362b6a868 | #!/usr/bin/env python
import sys
import json
import time
import random
import pathlib
import argparse
import subprocess
proc = None
def get_wallpaper(FOLDER):
files = [path for path in pathlib.Path(FOLDER).iterdir()
if path.is_file()]
return random.choice(files)
def get_outputs():
cmd = ... |
3,141 | 11ad3e1ab4ffd491e27998a7235b7e18857632ed | # Generated by Django 3.0.4 on 2020-03-29 09:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portfolio_app', '0008_feedback_product'),
]
operations = [
migrations.RemoveField(
model_name='feedback',
name... |
3,142 | cb13011def8fc7ed6a2e98a794343857e3e34562 | import pickle
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import random
from sklearn.manifold import TSNE
import matplotlib
def loadXY():
zippedXY = pickle.load(open("../Vectorizer/zippedXY_wff_2k.p","rb"))
#random.shuffle(zippedXY)
X,Y = zip(*zippedXY)
return X,Y
def out... |
3,143 | 8dfb1312d82bb10f2376eb726f75a4a596319acb | #!/usr/local/bin/python
import requests as rq
import sqlite3 as sq
from dateutil import parser
import datetime
import pytz
import json
from os.path import expanduser
import shutil
from os.path import isfile
import time
#FRED Config
urls = {'FRED':"http://api.stlouisfed.org/fred"}
urls['FRED_SER'] = urls['FRED'] + "/se... |
3,144 | b29c11b11fd357c7c4f774c3c6a857297ff0d021 | """
losettings.py
Contains a class for profiles and methods to save and load them from xml files.
Author: Stonepaw
Version 2.0
Rewrote pretty much everything. Much more modular and requires no maintence when a new attribute is added.
No longer fully supports profiles from 1.6 and earlier.
Copy... |
3,145 | 83b65b951b06b117c2e85ba348e9b591865c1c2e | #--------------------------------------------------------------------------------
# G e n e r a l I n f o r m a t i o n
#--------------------------------------------------------------------------------
# Name: Exercise 2.6 - Planetary Orbits
#
# Usage: Calculate information for planetary orbits
#
# Description: ... |
3,146 | a68d682ba6d441b9d7fb69ec1ee318a0ef65ed40 | """
Read a real number. If it is positive print it's square root, if it's not print the square of it.
"""
import math
print('Insert a number')
num1 = float(input())
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1**2}')
|
3,147 | 6c65d63ef07b6cdb2029e6a6e99f6ee35b448c4b | individual = html.Div([
html.Div([ # input container
html.Div([
dcc.RadioItems(id='view-radio',
options=[
{'label': i, 'value': i} for i in ['Players',
'Tea... |
3,148 | 174c4c1ed7f2197e012644999cf23f5e82f4b7c3 | def has23(nums):
this = nums[0] == 2 or nums[0] == 3
that = nums[1] == 2 or nums[1] == 3
return this or that
|
3,149 | dd4dc1c4a0dc47711d1d0512ef3f6b7908735766 |
import numpy as np
import tensorflow as tf
class LocNet:
def __init__(self, scope, buttom_layer):
self.scope = scope
with tf.variable_scope(scope) as scope:
self.build_graph(buttom_layer)
self.gt_loc = tf.placeholder(dtype=tf.float32, shape=(None,4),name='gt_loc')
... |
3,150 | 8c42e06fd92f0110b3ba8c4e7cc0ac45b9e44378 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__copyright__ = """
This code is licensed under the MIT license.
Copyright University Innsbruck, Institute for General, Inorganic, and Theoretical Chemistry, Podewitz Group
See LICENSE for details
"""
from scipy.signal import argrelextrema
from typing import List, Tuple
i... |
3,151 | 850310b6c431981a246832e8a6f5417a88587b99 | import torch
class Activation(torch.nn.Module):
def __init__(self):
super().__init__()
self.swish = lambda x: x * torch.sigmoid(x)
self.linear = lambda x: x
self.sigmoid = lambda x: torch.sigmoid(x)
self.neg = lambda x: -x
self.sine = lambda x: torch.sin(x)
self.params = torch.nn.Parameter(torch.zero... |
3,152 | 6f9f204cbd6817d5e40f57e71614ad03b64d9003 | # Generated by Django 3.2.6 on 2021-08-15 05:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tasks',
name='cleanlinessLevel',
... |
3,153 | b888745b3ce815f7c9eb18f5e76bacfadfbff3f5 | from libs.storage.blocks.iterators.base import BaseBlockIterator
from libs.storage.const import SEPARATOR
class ContentsBlockIterator(BaseBlockIterator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.contents = self.block_content.split(SEPARATOR)
self.titles =... |
3,154 | 913e1f5a0af436ef081ab567c44b4149299d0ec6 | # Generated by Django 2.2.4 on 2019-08-19 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('application', '0003_auto_20190818_1623'),
]
operations = [
migrations.AlterField(
model_name='user',
name='visited',... |
3,155 | ac459bff6d4281ce07b70dbccde3243412ddb414 | # processing functions for diagrams
import torch
import numpy as np
def remove_filler(dgm, val=np.inf):
"""
remove filler rows from diagram
"""
inds = (dgm[:,0] != val)
return dgm[inds,:]
def remove_zero_bars(dgm):
"""
remove zero bars from diagram
"""
inds = dgm... |
3,156 | 284e4f79748c17d44518f2ce424db5b1697373dc | __version__ = '0.90.03'
|
3,157 | 5ddde3aa6eaa30b70743272a532874663067eed6 | #!/usr/bin/env python3
import sys
import os
import math
import random
if hasattr(sys, '__interactivehook__'):
del sys.__interactivehook__
print('Python3 startup file loaded from ~/.config/pystartup.py')
|
3,158 | 98dd7446045f09e6d709f8e5e63b0a94341a796e | # -*- coding: utf-8 -*-
import time
import re
from config import allowed_users, master_users, chat_groups
from bs4 import BeautifulSoup
import requests
import urllib.request, urllib.error, urllib.parse
import http.cookiejar
import json
import os
import sys
#from random import randint, choice
from random import uniform,... |
3,159 | 0f0595793e98187c6aaf5b1f4b59affb06bb598e | from phylo_utils.data import fixed_equal_nucleotide_frequencies
from phylo_utils.substitution_models.tn93 import TN93
class K80(TN93):
_name = 'K80'
_freqs = fixed_equal_nucleotide_frequencies.copy()
def __init__(self, kappa, scale_q=True):
super(K80, self).__init__(kappa, kappa, 1, self._freqs, s... |
3,160 | 41698e9d8349ddf3f42aa3d4fc405c69077d1aa3 | from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
import ATLAS1
import ATLAS_v2
from atlas.config import dbConfig
import pandas as pd
import ContentCategories
import NgramMapping
import SentimentAnalysis_2
import TrigDriv_2
import TopicModeling
import logging
import tr... |
3,161 | e235be879cf8a00eb9f39f90859689a29b26f1c6 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 10 12:18:06 2017
@author: wqmike123
"""
#%% build a simple CNN with gloVec as initial
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers impo... |
3,162 | 87f3885b4357d66a745932f3c79804e6c15a57fa | import numpy as np
from ARA import *
from State import *
def theta_given_s(theta, q):
"""
Probability of an random event theta given current state s.
Args:
theta: Random event
s = [q, r, w]: State
Returns:
Unnormalized probability of the random event.
"""
if q == 0:
... |
3,163 | 3f4f60ff315c8e7e4637a84629894012ed13280e | import src.integralimage as II
import src.adaboost as AB
import src.utils as UT
import numpy as np
if __name__ == "__main__":
pos_training_path = 'dataset-1/trainset/faces'
neg_training_path = 'dataset-1/trainset/non-faces'
pos_testing_path = 'dataset-1/testset/faces'
neg_testing_path = 'dataset-1/tes... |
3,164 | 4b075d8211d7047f6f08fe6f6f55e4703bdb6f1f | from django.db import models
# Create your models here.
class Todo(models.Model):
title = models.CharField(max_length=200)
completed = models.IntegerField(default=0)
|
3,165 | 4d18c056845403adc9c4b5848fafa06d0fe4ff4c | class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
left= 0
#for right in range(len(s)-1, -1, -1):
for right in reversed(range(len(s))):
if s[right] == s[left]:
left += 1
... |
3,166 | 1fdb9db4c1c8b83c72eeb34f10ef9d289b43b79f | from Bio import SeqIO
def flatten(l):
return [j for i in l for j in i]
def filter_sequences_by_len_from_fasta(file, max_len):
with open(file) as handle:
return [str(record.seq) for record in SeqIO.parse(handle, 'fasta') if len(record.seq) <= max_len] |
3,167 | 2003060f7793de678b4a259ad9424cd5927a57f7 | """ Class implementing ReportGenerator """
from urllib.parse import urlparse
import requests
from src.classes.reporter.flag import Flag
from src.classes.reporter.line_finder import LineFinder
class ReportGenerator(object):
"""
Class designed to generate reports after CSP audition
The ReportGenerator cla... |
3,168 | e94d66732a172286814bc0b0051a52c1374a4de5 | import asyncio
import sys
import aioredis
import msgpack
async def main(host: str, endpoint: str, message: str):
msg = msgpack.packb(
{
"endpoint": endpoint,
"headers": {"Content-Type": "text/json"},
"payload": message.encode("utf-8"),
},
)
redis = awai... |
3,169 | 20167058697450f342c2ac3787bd1721f860dc58 | from kraken.core.maths import Vec3, Vec3, Euler, Quat, Xfo
from kraken.core.objects.components.base_example_component import BaseExampleComponent
from kraken.core.objects.attributes.attribute_group import AttributeGroup
from kraken.core.objects.attributes.scalar_attribute import ScalarAttribute
from kraken.core.objec... |
3,170 | 856afd30a2ed01a1d44bbe91a7b69998e9a51bb7 | from __future__ import print_function
import os, sys, time
import fitz
import PySimpleGUI as sg
"""
PyMuPDF utility
----------------
For a given entry in a page's getImagleList() list, function "recoverpix"
returns either the raw image data, or a modified pixmap if an /SMask entry
exists.
The item's first two entries ... |
3,171 | a598da0a749fcc5a6719cec31ede0eb13fab228e | import pytest
import app
import urllib.parse
@pytest.fixture
def client():
app.app.config['TESTING'] = True
with app.app.test_client() as client:
yield client
def test_query_missing_args(client):
response = client.get('/data/query')
assert 'errors' in response.json and '400' in response.sta... |
3,172 | cf2fcd013c3e9992da36806ca93aacb4b5399396 | from .tacotron_v2_synthesizer import Tacotron2Synthesizer
|
3,173 | 5dffda8215b8cfdb2459ec6a9e02f10a352a6fd0 | from wtforms import Form as BaseForm
from wtforms.widgets import ListWidget
class Form(BaseForm):
def as_ul(self):
widget = ListWidget()
return widget(self)
|
3,174 | a9344151a997842972aa68c417a77b3ca80e6cfa | # -*- coding:utf-8 -*-
from flask import redirect, url_for, render_template
from flask.globals import request, session
from flask_admin import BaseView, expose
from util import navigator, common
class Billings(BaseView):
@expose('/')
def index(self):
return redirect(url_for('.billingHistory'))
... |
3,175 | 2eb49d08136c3540e1305310f03255e2ecbf0c40 | import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title('Loop')
############ Time consuming :
# nameLable1 = ttk.Label(win,text="Enter your name : ")
# nameLable1.grid(row=0,column=0,sticky=tk.W)
# ageLable1 = ttk.Label(win,text="Enter your age: ")
# ageLable1.grid(row=1,column=0,sticky=tk.W)
#... |
3,176 | 967984444d9e26452226b13f33c5afbc96b5fe2b | import os
from enum import Enum
STAFF_CODE = os.getenv('STAFF_CODE', '20190607')
ADMIN_CODE = os.getenv('ADMIN_CODE', 'nerd-bear')
TEAM_NAMES = (
'밍크고래팀',
'혹등고래팀',
'대왕고래팀',
'향유고래팀',
)
TEAM_COUNT = 3
MAX_TEAM_MEMBER_COUNT = 10
class TIME_CHECK(Enum):
BEFORE_START = 0
DURING_TIME = 1
AFTER... |
3,177 | ae0ccbb9b0a2c61d9ee9615ba8d0c1a186a81c34 | # coding=utf-8
# oscm_app/cart/models
# django imports
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
# OSCM imports
from ...constants import CARTS, CART_STATUSES, DEFAULT_CART_STATUS
from ...utils import get_attr
from ..cart_manager i... |
3,178 | c9e0586942430fcd5b81c5716a06a4eef2c2f203 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 15:09:26 2017
@author: Jieun
"""
from scipy.stats import invgauss
from scipy.stats import norm
# rv = invgauss.ppf(0.95,mu)
# a = 8/(2*rv)
# print a
# norm.ppf uses mean = 0 and stddev = 1, which is the "standard" normal distribution
# can use a different mean and s... |
3,179 | 68a1d5a77abd19aece04bd560df121ceddccea42 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 13:34:46 2017
@author: Sven Geboers
"""
from math import pi,e
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def LevelToIntensity(NoiseLevelIndB):
I0 = 10.**(-12) #This is the treshold hearing intensity, matchin... |
3,180 | c4b4585501319fd8a8106c91751bb1408912827a | # from django.shortcuts import render
# from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views import generic
from django.urls import reverse_lazy
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import aut... |
3,181 | f615e7bbfa9179d0bfb321242cd8df4ae7b48993 | import org.cogroo.gc.cmdline
import typing
class __module_protocol__(typing.Protocol):
# A module protocol which reflects the result of ``jp.JPackage("org.cogroo.gc")``.
cmdline: org.cogroo.gc.cmdline.__module_protocol__
|
3,182 | 32ca107fde4c98b61d85f6648f30c7601b31c7f3 | """
Django settings for geobombay project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... |
3,183 | d6791c8122129a46631582e7d9339ea08bd2e92b | # Default imports
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
data = pd.read_csv('data/house_prices_multivariate.csv')
# Your solution code here
def select_from_model(dataframe):
X = dataframe.iloc[:, :-1]
y... |
3,184 | 58d137d614a0d5c11bf4325c1ade13f4f4f89f52 | print("2 + 3 * 4 =")
print(2 + 3 * 4)
print("2 + (3 * 4) = ")
print(2 + (3 * 4))
|
3,185 | 006f499eed7cd5d73bb0cb9b242c90726fff35c1 | from odoo import models,fields, api
class director(models.Model):
#Clasica
_inherit = 'base.entidad'
_name = 'cinemateca.director'
name = fields.Char(string="name", required=True, help="Nombre del director")
apellidos = fields.Char(string="apellidos", required=True, help="Apellidos del director")
... |
3,186 | cce85d8a34fd20c699b7a87d402b34231b0d5dbb | from ..models import Empleado, Puesto, Tareas
from django.contrib.auth import login, logout
from django.contrib.auth.models import User, Group
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import EmpleadoSeri... |
3,187 | e71a23ef7a065bc4210e55552e19c83c428bc194 | """This module contains an algorithm to find the different
components in a graph represented as an adjacency matrix.
"""
def find_components(adjacency_matrix):
visited = set()
components = []
for node in range(len(adjacency_matrix)):
if node not in visited:
component = []
b... |
3,188 | 0f3430cbfc928d26dc443fde518881923861f2e3 | from django.urls import path
from .views import PasswordList
urlpatterns = [
path('', PasswordList.as_view()),
]
|
3,189 | 5669476cc735f569263417b907e8f4a9802cd325 | import socket
import sys
TCP_IP = '192.168.149.129'
TCP_PORT = 5005
BUFFER_SIZE = 2000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while 1:
print 'user data:'
content = sys.stdin.readline();
s.send(content)
data = s.recv(BUFFER_SIZE)
print "received data:", data
s.clo... |
3,190 | a917dd6171a78142fefa8c8bfad0110729fc1bb0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-15 18:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('aposta', '0003_aposta_nome'),
]
operations = [
... |
3,191 | aee8fa7bc1426945d61421fc72732e43ddadafa1 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 29 19:10:06 2018
@author: labuser
"""
# 2018-09-29
import os
import numpy as np
from scipy.stats import cauchy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import pandas as pd
def limit_scan(fname, ax):
data = pd.read_csv(fname, sep='\t', ... |
3,192 | 309807e04bfbf6c32b7105fe87d6ad1247ae411a | #
# PySNMP MIB module ADTRAN-ATLAS-HSSI-V35-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-ATLAS-HSSI-V35-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:59:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
3,193 | 51b32972c97df50a45eb2b9ca58cdec0394e63ee | from fractions import Fraction as f
print f(49,98) * f(19, 95) * f(16, 64) * f(26, 65)
|
3,194 | 1630a3d0becac195feee95a1c3b23568612a48d2 | import preprocessing
import tokenization
import vectorspacemodel
import pickle
import collections
import os
import math
import operator
from itertools import islice
def take(n, iterable):
# "Return first n items of the iterable as a list"
return list(islice(iterable, n))
directory = os.getcwd()
... |
3,195 | ca3cdbd5d5d30be4f40925366994c3ea9d9b9614 | from django.db import models
from datetime import datetime
class Folder(models.Model):
folder = models.CharField(max_length=200, default = "misc")
num_of_entries = models.IntegerField(default=0)
def __str__(self):
return self.folder
class Meta:
verbose_name_plural = "Folders/Categories"
class Bookmark(model... |
3,196 | 8f554166c28fe4c9a093568a97d39b6ba515241b | # This implementation of EPG takes data as XML and produces corresponding pseudonymized data
from lxml import etree
from utils import generalize_or_supress
from hashlib import sha256
from count import getLast, saveCount
import pickle
from hmac import new
from random import random
from json import loads
from bigchain i... |
3,197 | ba7f66a0f9cf1028add778315033d596e10d6f16 | import numpy as np
import tensorflow as tf
x_data = np.random.rand(100)
y_data = x_data * 10 + 5
#构造线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y=k*x_data+b
#二次代价函数 square求平方
loss= tf.reduce_mean(tf.square(y_data-y))
#定义一个梯度下降法来进行训练的优化器
optimizer=tf.train.GradientDescentOptimizer(.2)
train=optimizer.minimize(... |
3,198 | ffd034eb5f0482c027dcc344bddb01b90249511c | import os
import io
import time
import multiprocessing as mp
from queue import Empty
import picamera
from PIL import Image
from http import server
import socketserver
import numpy as np
import cv2
class QueueOutputMJPEG(object):
def __init__(self, queue, finished):
self.queue = queue
self.finished ... |
3,199 | 1cf5ce11b965d65426ed421ef369954c59d7eba9 | # Generated by Django 3.2.4 on 2021-06-29 13:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_blogdetail'),
]
operations = [
migrations.RenameField(
model_name='bloglist',
old_name='about',
new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.