index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,600 | 81855abd45882f76ab9127f81e26e7368140014e | ## 2. ReLU Activation Function ##
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
x = np.linspace(-2, 2, 20)
def relu(x):
outp = np.maximum(0,x)
return outp
relu_y = relu(x)
print(x, relu_y)
plt.plot(x,relu_y)
## 3. Trigonometric Functions ##
x = np.linspace(-2*np.pi, 2*np.pi, 100... |
13,601 | 66e35cf958e187ca4a0abef383e41ee4ff5f7b59 | # Base on stock_pred.py
from datetime import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers imp... |
13,602 | 51d60b06186c34f0a814bee2c3a5aa0854185510 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 14 19:42:45 2018
@author: singh.shivam
"""
import numpy as np
import matplotlib.pyplot as plt
l = [i for i in range(1,13)]
x = np.array(l)
print(x)
maxy=np.array([39,41,43,47,49,51,45,38,37,29,27,25])
miny=np.array([21,23,27,28,32,35,31,28,21,19,17,18])
... |
13,603 | 8ae9731b4ce209ff3171ea328e7f6defd5c9d40b | def to_bebisspråket(text):
vowels = "aeiouyåäö"
res = ""
for word in text.split():
res += word[:word.find(any(c for c in word.lower() if c in vowels))+1]*3 + " "
return res.strip()
|
13,604 | 6ea55426fcd24db36847baa5656080052f234554 | #!/usr/bin/env python3
"""
Given a WAD, it'll detect if it's for DOOM1 or 2 (based on map names) and
run GZDoom with the right iwad arg
"""
import argparse
import os
import wad
import subprocess
import dero_config
parser = argparse.ArgumentParser()
parser.add_argument('--pwad', type=str, required=True, help='Path to... |
13,605 | 2b72778600c7936d1cf3098e13bbc7bc5816a91b | from django.urls import path
from .views import Event_List, Event_Detail, get_price, checkout_view
from django.conf.urls import url
app_name = 'event'
urlpatterns = [path('event_list', Event_List.as_view(), name='event_list'),
path('<int:id>/<slug:slug>/', Event_Detail.as_view(), name='event_detail'),... |
13,606 | ddb4a15bc37378805d062a78f6489508e8f303b8 | '''
Permutation Experiments
Usage: python3 03_excitation_02_permutation.py
NOTE The parameter DIMS_TO_PERMUTE (per comparison type as stored in variable MODE) encodes which event-to-dimension associations to permute. It results from empirical observations of results from "03_excitation_01_effects.py". Also, note ANALYS... |
13,607 | 9a584ed7cbcbeb5305dc36de56b1a33f0a4e8353 | '''Module to generate test graphs'''
from random import randint
from random import sample
from subprocess import call
import sys
filename = "test"
def printUsage():
print "Enter 1 n to generate star graph with n nodes"
print "Enter 2 n to generate line graph with n nodes"
print "Enter 3 n to generate a ran... |
13,608 | 52c8ab928074af1aeb3cda29e03d0c76f698c63b |
from flask import render_template, request
from app import app
from app.logic import generate_text
@app.route('/')
def index():
context = {
'troll_text': generate_text(),
}
return render_template('index.html', **context)
@app.route('/_get_text')
def get_troll_text():
subject = request.args.get('subject')
# Cl... |
13,609 | 383629fe5a15f07d541c475f80af6c21dffc5349 | import math
import time
from misc import plot_vline
from matplotlib.figure import Figure
from pylab import cm
from matplotlib.gridspec import GridSpec
from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas
import pylab as plt
def calculate_mean_bo_b_images(dwi_file, bval_file=False, bvec_fi... |
13,610 | c5928907ecc51b1e708a13bc15040b90e8f7916f | import numpy as np
import pandas as pd
import googlemaps
import json
from datetime import datetime
# Choose starting and ending times
start_time = "2020-09-01T04:00:00.464Z"
end_time = "2020-09-03T22:00:00.464Z"
YOUR_API_KEY = ""
starttime = datetime.strptime(start_time,'%Y-%m-%dT%H:%M:%S.%fZ')
endtime = datetim... |
13,611 | 6221644c0a134556df821e7b356c314ccb60ed35 | # Generated by Django 3.2 on 2021-05-27 18:38
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('presupuestos', '0001_initial'),
]
oper... |
13,612 | c655e004966fb4320bf0319651a0ca3dc67b0cd5 | from mcpi.minecraft import Minecraft
mc = Minecraft.create()
x,y,z = mc.player.getTilePos()
a = 0
while a<20:
mc.setBlocks(x-20,y-1,z,x+20,y-10,z,19)
z=z+5
a=a+1
|
13,613 | 26d07d7c231d2cfd7eb7dcda4a8d4574483c0317 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
13,614 | 3e689c0f840ccc425934b2c65492366ee2b59b79 | """Test suite for fmbiopy.io."""
from uuid import uuid4
import pandas as pd
from pytest import fixture, mark
from fmbiopy.io import *
@fixture
def list_data():
return [["n1", "n2", "n3"], ["a", "b", "c"], ["1", "2", "3"]]
@mark.parametrize("delimiter", [(","), ("\t")])
def test_list_to_csv(list_data, sandbox,... |
13,615 | 47b9870beada4a0dfdfa44dbeaa830abbcd87972 | import json
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
res = "test complete !! your value = " + event['key'] + "\n"
return res # Echo back the first key value
|
13,616 | d8178b6e9c0ac862e929e09428270c17958b46cb | from socket import *
from logger import _logging as Log
import threading
import time
import binascii
import struct
import codecs
import re
from socket import error as sckerror
class Mysocket():
def __init__(self, host, port):
self.k = Log()
self.logger = self.k.Getlogger(__name__)
self.HOST... |
13,617 | 48496ba26f0eeac18b97886f5a4f51737d6d022c | #python为了将语意变得更加明确,就引入了async和awit关键字用于定义原声协程
#from collections import Awaitable
import types
# async def downloader(url):
# return "TT"
@types.coroutine
def downloader(url):
yield "TT"
async def download_url(url):
#do somethine
html = await downloader(url)
return html
if __name__ == "__main__":
... |
13,618 | 2b3b70271c13a28e4457ec6458b45415dab5b6d1 | from datetime import timedelta, datetime
def filter_dict(obj, val=None):
# TODO: We should not always remove all None items (maybe!?)
return dict(filter(lambda item: item[1] is not val, obj.items()))
def get_season_tag_name(key):
table = {
"Clas Ohlson": "COB",
"Matkasse": "MK",
... |
13,619 | 5f5fbefb79b6164ec56bd5b1ffaf97d1832914e3 | from django.conf.urls import include, patterns
urlpatterns = patterns(
'',
(r'^messages/', include('django_messages.urls')),
)
|
13,620 | facb557ba15deaed25c967e33021f6e934cc4fc6 | from collections import Counter
import time
def greedy(money):
#checking if input is a string or value is negative
while (money.isalpha() or float(money) < 0):
money = input("Change: ")
else:
money = float(money) #accepts floating numbers
cents = int(100*money) #converting to... |
13,621 | 09476ef95b54ba7e083c05e80df1be6a82fce2d9 | # NOTE: Generated By HttpRunner v3.1.4
# FROM: opsLogin.har
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase, Parameters
import pytest
import ast
class TestCaseOpslogin(HttpRunner):
@pytest.mark.parametrize(
"param",
Parameters({
"userName-password-verifyCode1... |
13,622 | 1429dcdf5515bb5ea6f48f7c120d5c4fdc2f4677 | #!/usr/bin/env python3
import pandas as pd
import sys
path_tbl = str(sys.argv[1])
tbl = pd.read_csv(path_tbl, sep = '\t')
print("Method", "SNP_threshold", "Comparison", "Number_isolate_pairs", sep = '\t')
for snp_threshold in range(1,21):
for comparison in [ 'different_carrier', 'same_carrier_same_timepoint' ]:
... |
13,623 | 576712d3ac1abb7f44e6989343bef8982f27f24e | #created by Christos Kagkelidis
import socket
from api.database import Database
from datetime import datetime
import psycopg2
import msvcrt
import pickle
import sys
# def add_record_to_db(data, cursor):
# print('Adding record to database...')
# try:
# cursor.execute("""INSERT INTO "sensor_data" (s_id... |
13,624 | e639f3e3aecf9c429c11bcb80e3549feb190a41a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'han'
import torch
import torch.nn.functional as F
class MyNLLLoss(torch.nn.modules.loss._Loss):
"""
a standard negative log likelihood loss. It is useful to train a classification
problem with `C` classes.
Shape:
- y_pred: (batch, ... |
13,625 | 9ea537619f8d9b76474c89938d8f2abe6808dfdd | #-*- coding:utf-8 -*-
import sys
import os
import random
import time
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets
from tensorflow.keras import layers
os.environ["TF_CPP_MIN_LOG_LEVEL"]='2'
def printUsages():
print "Usage: python wsabie_model_train.py [... |
13,626 | 25099380b4bf9d4672ba9b59c2da917a7db0722f | import argparse
import os
import settings
from libs.utils import classifier_factory
from libs.bbc import train_bbc
from libs.cnn import train_cnn
from libs.rz import train_rz
def main():
parser = argparse.ArgumentParser("model training")
parser.add_argument("--dataset", type=str, choices=["bbc", "cnn", "rz"],... |
13,627 | d5aa59215067072f1e354392a38e51bdfba48c12 |
class Tree:
"""This is a class representing a binary tree"""
def __init__(self, data, left = None, right = None):
self.left = left
self.right = right
self.data = data
def printInOrder(self):
if (self.left != None):
self.left.printInOrder()
print self.d... |
13,628 | 6eb1501db132cc6c1aaf64201559e74bf2c38a3b | import os
import json
import pickle
def get_dictionary(file_entry, file_mode):
if file_mode == 'json':
with open(file_entry, 'r') as f:
dictionary = json.load(f)
elif file_mode == 'pickle':
with open(file_entry, 'rb') as f:
dictionary = pickle.load(f)
else:
... |
13,629 | 684c10b9038291ad388c6f58cee051389fcdb914 | import logging
import json
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
req_body = req.get_json()
# Read Input JSOn
threat = req_body["threat"]
year = req_body["analysisYear"]
parameter... |
13,630 | 0f6be2529cbbf4d1a6c3bf1b172c8e28c046367b | '''
Copyright (C) 2014 Jacques Lucke
mail@jlucke.com
Created by Jacques Lucke
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... |
13,631 | 7a2b65e341327aeee1c928557aa505eba3a53c5d | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('foodpantry', '0006_auto_20150414_0325'),
]
operations = [
migrations.A... |
13,632 | d190ebed84e90430d172ebc3f4c0c1514a2bccdb | # -*- coding: utf-8 -*-
"""
CATS ANALYSIS
"""
# Basic Libraries
import pandas as pd
import numpy as np
# Pull in data
test = pd.read_csv('./test.csv')
train = pd.read_csv('./train.csv')
df = train.copy()
df['logy'] = np.log(df['SalePrice'])
# function for CATS
def cda(colname):
print(pd.co... |
13,633 | a927732b156da2f3a5e464d0a7d8315eb5f17638 | D=int(input())
C=list(map(int,input().split()))
S=[list(map(int,input().split())) for i in range(D)]
T=[int(input()) for i in range(D)]
l=[0]*26
v=0
for d in range(D):
x=[S[d][i]-sum([(d+1-l[j])*C[j] for j in range(26) if i!=j]) for i in range(26)]
l[T[d]-1]=d+1
v+=x[T[d]-1]
print(v) |
13,634 | 2a1826df25eb0521f45ef79a158aafa24ba05af0 | import socket
# import cv2
import numpy as np
import pickle
#Upload image
# img = cv2.imread('/path/to/image', 0)
#Turn image into numpy-array
arr = np.array([[1,2,3],[4,5,6]])
#Receiver ip
ip = socket.gethostname()
#Set up socket and stuff
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Loop through each ar... |
13,635 | ed6b20c7afac51e01a8fb7508be62a9fa348cacc | from collections import deque as Queue
def slider(arr,k):
n=len(arr)
q=Queue()
#from the first k elements keep the max and decreasing
for i in range(k):
while(len(q) and arr[i]<=arr[q[-1]]):
q.pop()
q.append(i)
for i in range(k,n):
#previous window min
p... |
13,636 | 3acd966117f296b2805cd8d91c19f67b8481703d | from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# init driver
driver = webdriver.Chrome(executable_path=r"C:\Users\yordi\Automation\python-seleniu... |
13,637 | 2566a27c7ee27ce269e210d4c482d7c30e62bbd1 | from django.apps import AppConfig
class MytodoConfig(AppConfig):
name = 'MyTodo'
|
13,638 | 374ca3769ca1423dcbe5a7237d253a0a1b6fdde2 | import torch
from torch import nn
from pyg_graph_models import GCN, GraphAttentionPooling, ResNetBlock, TensorNetworkModule
from utils import construct_graph_batch, pad_tensor
import numpy as np
from torch_geometric.utils import to_dense_batch
from torch.distributions import Categorical
from sinkhorn import Sink... |
13,639 | 651301f923de9606a71975193f851196a6a5ce7c | # Uses python3
import sys
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
data = []
data.append(0)
data.append(1)
# print(0, 0)
# print(1, len(data))
for _ in range(n - 1):
previous, current = current, (previous + current) % 10
... |
13,640 | 95ef3cc7d25eeb8e72eff4bf5f5726f77de0a716 | # _*_ coding.utf-8 _*_
# 开发人员 : leehm
# 开发时间 : 2020/7/7 22:59
# 文件名称 : 44.py
# 开发工具 : PyCharm
s1 = input()
|
13,641 | 27ccffb2db2e07e26f325ed28561b76806cab669 | import os.path
from glob import glob
from torch.utils import Dataset
from PIL import Image
class DatasetFolder(Dataset):
def __init__(self, root, pattern, transform=None, target_transform=None):
# classes, class_to_idx = find_classes(root)
samples = glob(pattern)
self.loader ... |
13,642 | 7c174405dac6ea7d664a7988c5b137920366521b | # -*- coding: utf-8 -*-
# Created by li huayong on 2019/10/9
import numpy as np
import torch
import random
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
if __name__ == '__main__':
... |
13,643 | e777af91cdff564970170156e896712587dc0957 | from sklearn.linear_model import LinearRegression
predictor = LinearRegression(n_jobs=-1)
predictor.fit(X=TRAIN_INPUT, y=TRAIN_OUTPUT) |
13,644 | 007d71bc68830ef3b08985ed0d93d5ba4abc447a | # -*- coding: utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
from easy_thumbnails.files import get_thumbnailer
from djangocms_address import settings
register = template.Library()
@register.filter()
def render_logo(item):
image = item.logo
if not image:
return u''
... |
13,645 | 564a13be0241e222a21778f2c663d8c7b49b5eca | # # ЗАДАЧА 1
# #
# # Реализовать класс Person, у которого должно быть два публичных поля: age и name.
# # Также у него должен быть следующий набор методов: know(person),
# # который позволяет добавить другого человека в список знакомых.
# # И метод is_known(person), который возвращает знакомы ли два человека
#
#
# c... |
13,646 | 1f02ddb59b3ce388e85e9a607f955c8ebd9ad2e3 | str1=str(input())
str2=str1[::-1]
if(str1==str2):
print("True")
else:
print("False") |
13,647 | 97a60a28a7646d7a71fa0480b9734c816ca03fa2 | import os
import cv2
import time
from moviepy.editor import AudioFileClip
import tqdm
import glob
from PyPDF2 import PdfFileMerger, PdfFileReader
from modules.tape import TapeFrame, Tapes, PDF
class VideoReader:
def __init__(self, dt: float = 1.0, take_speech: bool = True, verbose: bool = True, **kwargs):
... |
13,648 | bd152ef06d569fa062812ca373b5865eaec7bc01 | #
# @lc app=leetcode.cn id=209 lang=python3
#
# [209] 长度最小的子数组
#
# @lc code=start
from typing import List
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
n = len(nums)
res = n+1
for i in range(n):
total = 0
for length in range(1, n+1):
... |
13,649 | 8d409647853193c0f19b5b010fa3819127f8278b | import africastalking
import os
class SMS:
def __init__(self):
# Set your app credentials
self.username = os.getenv("AFRICASTALKING_USERNAME")
self.api_key = os.getenv("AFRICASTALKING_API_KEY")
# Initialize the SDK
africastalking.initialize(self.username, self.api_key)
... |
13,650 | 65c89351e2f575359f5cd8aef43c0c9b90a56b3e | # FUNCTIONAL TESTS INVOLVING USER STORIES
import os
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui im... |
13,651 | ab56892cc17d387cd0a9b595ccaa6e9de52c7482 | #!/usr/bin/python
import sys
import os
usuario = sys.argv[1]
clave = sys.argv[2]
basedatos = input ("¿A que base de datos quieres hacerle una copia de seguridad?")
print ("Vas a copiar la base de datos:" + basedatos)
cadena = "mysqldump -u " + usuario + " -p" + clave + " " + basedatos + " | gzip > backup.sql.gz"
pr... |
13,652 | 2a431dfaeff82093e43b487b9da4745491bcdb83 | import os
import sys
import pickle
import subprocess
import numpy as np
import glob ####
def dispatch(script_path, dataset_name, data_dir, boundaries_path, names, out_pattern_base, memory, fails_only=False):
jobs = []
# print(data_dir) ####
for name in names:
bam_path = os.path.join(data_dir, name,... |
13,653 | 85692cf4a4fe3d088dc6aca36318f0ef54cf00b5 | """
Created on Mar 2, 2012
@author: Alex Hansen
"""
# local import
parse_line = "A simple CEST experiment"
description = \
''' HELP NOT YET IMPLEMENTED
Use 4-space indentation in description.
Add measured spin to parse_line. ie)
15N - one line experiment description
Paramet... |
13,654 | f3db338a83c3dc93ad198e730cbf7b90a538f5a0 | from tkinter import *
ventana = Tk()
ventana.title("Calculadora")
indice = 0
# Funciones
def click_boton(valor):
# con global accedemos a la variable global indice que declaramos antes y
# asi poder actualizar su valor desde la funcion click_boton
global indice
pantalla.insert(indice, valor)
indic... |
13,655 | 079a712fa8b759cafbc90329e513167b883014c3 | # -*- coding: utf-8 -*-
import os
if os.path.exists( r'\\10.99.1.6\Digital\Library\hq_toolbox' )==False and os.path.exists(r'\\XMFTDYPROJECT\digital\film_project\Tool\hq_toolbox')==False :
raise IOError()
#####################################################################################
import maya.cmds as cmds... |
13,656 | fe2a1e1fea20a1e43b0673e95170f1358f861dac | #Avery Tan(altan:1392212), Canopus Tong(canopus:1412275)
#
#
#
#Requires queue python library
#
#
#
import p1
from queue import PriorityQueue
class Node(object):
"""
class we use to make implement priority queue
"""
def __init__(self,coor):
self.coor = coor
self.g=0
self.h... |
13,657 | 3067bef87f622d3acfb727157a811e99a17a3b27 | from random import randrange
pokracovani_hry = "hra"
while pokracovani_hry == "hra":
hod_kostkou = randrange (0,3)
if hod_kostkou == 0:
tah_pocitace = "kamen"
elif hod_kostkou == 1:
tah_pocitace = "nuzky"
elif hod_kostkou == 2:
tah_pocitace = "papir"
tah_hrace = input ("zvol kamen, nuz... |
13,658 | 30d7be1c038a5b424b728594c550ce801ee65d70 | import numpy as np
from sklearn.cluster import KMeans
def generate_points():
N = 50
points = [(x,y) for x in range(N) for y in range(N)]
points = np.asarray(points)
for i in xrange(len(points)):
if (i%4 == 0):
a = np.random.randint(10, 100)
b = np.random.randint(10, 100... |
13,659 | dc0b4f6aa2b2818dcf6ff78068892e5a0a1812b3 | from django.shortcuts import render, redirect, reverse
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from shopcart.models import ShopCart
from goods.models import Goods
from users.models import Address
from . import models
@r... |
13,660 | b0a051ebe1b86ae35e6b0da58c491ed274958021 | from datetime import datetime as dt
def None_check(key, value):
if value is None or value == '':
print(f'{key} is empty.')
value = None
return value
def str_check(key, value):
if type(value) != str:
raise TypeError(f'{key} must be str type')
return value
def int_check(key, va... |
13,661 | 2dddb7ca2fc22ca95409ea48aeb8aca65cdf430c | # GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Returns a risk list of URLs matching a filtration"
class Input:
LIST = "list"
class Output:
RISK_LIST = "risk_list"
class DownloadUrlRiskListInput(insightconnect_plugin_ru... |
13,662 | d22845051ec9d63aa9a92c6696656a09c911cc77 | # -*- coding: utf-8 -*-
"""
DECAWAVE DW1000 ANTENNA DELAY CALIBRATION SOFTWARE (x64)
NOTES:
-This program uses the DecaWave DW1000 Arduino adapter board made by Wayne
Holder to determine the anntena delay value of one anchor and one receiver
-Note that this script is very preliminary; it currently requires the ... |
13,663 | 6d84017b9c946e33c4ee063992d8f5db0fbdd7be | /Users/karljo/anaconda3/lib/python3.6/copy.py |
13,664 | a4a2044305fd3184a13e2d100e79755bee35a358 | from pprint import pprint
import re
extract_x = re.compile('x=((?P<spread>\d+\.\.\d+)|(?P<single>(\d+)))')
extract_y = re.compile('y=((?P<spread>\d+\.\.\d+)|(?P<single>(\d+)))')
def x_vals(line):
return match_var(extract_x, line)
def y_vals(line):
return match_var(extract_y, line)
def match_var(extract, li... |
13,665 | c74e1e44728427135d53f4fb397bbdf20a221a28 | from database_classes import StorageSystem, StorageSystemException
storage_reader = StorageSystem()
system = True
while system:
username = input("What is your username? ")
password = input("What is your password? ")
print(storage_reader.get_by_username_pw(username, password))
if storage_reader.get_by_... |
13,666 | 9ee59db613194128ec097f50fb0681796254b457 | # encoding:utf-8
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
def doPCA(data):
pca = PCA(n_components=2)
pca.fit(data)
return pca
if __name__ == "__main__":
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
... |
13,667 | 4c633ca84646e32b5168d2743d1caada014438e2 | """Python/Flask prgram to integrate recipe_program.py with GUI (homepage.html)"""
from flask import Flask, render_template, request, jsonify
import urllib # urlencode function
import urllib2 # urlopen function (better than urllib version)
import json
from pickle import dump, load
from os.path import exists
from reci... |
13,668 | 076849b44c06c17bee7cf5549c28c34a0980ad36 | from .ygritte import Ygritte |
13,669 | 5a57d0c13b0b9d8abdeffbabe3b40c2883da03e1 | """Run through the Picket Fence image bank."""
from unittest import TestCase
from pylinac import PicketFence
from tests_basic.utils import DataBankMixin
def run_pf(path):
"""Function to pass to the process pool executor to process picket fence images."""
try:
mypf = PicketFence(path)
mypf.ana... |
13,670 | 67559cf4b4626d4a1fbe61fe32f2998ccf6ff832 | import logging
import os
import configparser
import copy
from enum import Enum
from generic_organization_service.interfaces.responses.generic_response import Description
from antidote import register
from generic_organization.settings import BASE_CODE_FOLDER, TEMPLATE_FOLDER_LIST
logger = logging.getLogger(__name__)
... |
13,671 | 1801e002dcc5cf71b5d7f96980fd1ec042c1df1f |
def convert(filepath,savepath):
content = "@relation train_file\n"
with open(filepath,mode="r") as file:
lines = file.readlines()
for i in range(lines.__len__()):
if i == 0:
tmp = lines[0].split(",")
for j in range(tmp.__len__()-1):
... |
13,672 | 7b7ad917b04f948ebae174eb6e34eaff25cdfeae | #!/usr/bin/env python3
"""
concatenating of two matrices with specific axis
"""
def cat_matrices2D(mat1, mat2, axis=0):
"""
enter a matrix
and Returns a list of concatenated matrices
"""
if (len(mat1[0]) == len(mat2[0])) and (axis == 0):
concat = [ele.copy() for ele in mat1]
concat... |
13,673 | dab9cd3fce7fe8d0da2f3883b487007c396bdb87 | """
============================
Author:赵健
Date:2019-09-01
Time:16:28
E-mail:948883947@qq.com
File:constants.py
============================
"""
import os
# 项目路径
OB_DIR = os.path.dirname(os.path.dirname(__file__))
# 测试用例表格存储路径
DATA_DIR = os.path.join(OB_DIR, 'data')
# 配置文件存储路径
CF_DIR = os.path.join(OB_DIR, 'configs')
... |
13,674 | 9321af9002df719d383a7f4ad6335c77b1cd6127 | import time
from enum import IntEnum
from typing import Any, ClassVar, Dict, List, TypeVar, Union
from pymilvus.exceptions import (
AutoIDException,
ExceptionsMessage,
InvalidConsistencyLevel,
)
from pymilvus.grpc_gen import common_pb2
from pymilvus.grpc_gen import milvus_pb2 as milvus_types
Status = Type... |
13,675 | 812719671ca2ce668a25674d7a82ac62913df920 | # python3
import sys
import math
import unittest
import io
import os
class SeparatingClustersDistanceChecker:
def __init__(self):
self.n = int(sys.stdin.readline())
self.points = [tuple(map(int, sys.stdin.readline().split())) for _ in range(self.n)]
self.k = int(sys.stdin.readline())
... |
13,676 | 84549412fbf4fe8117b8b67667fc5fb8c94976b8 | """
챕터: day6
주제: 정규식
문제: 정규식 기호 연습
작성자: 주동석
작성일: 2018. 11. 22
"""
import re
"""
1. apple에 a가 들어있는지 확인
2. apple에 b가 들어있는지 확인
3. 정규식을 이용하여, 사용자가 입력한 영어 문장에서 a, e, i, o, u가 포함되어 있는지 찾아서 출력하시오. 만족하는 첫번째만 출력한다.
<입력> This is a test.
"""
s1 = "apple"
if re.search("a", s1):
print("a가 들어있습니다.")
else:
... |
13,677 | bbea4d09e520d06a22c7e04eae3af5bd7abfb8bb | import io_helper
import logging
import sys
import subprocess
import os
IMAGEDIR = ''
SCPPATH = ''
UTTID = sys.argv[1]
def main():
utt2recpath = io_helper.parse_dictfile(SCPPATH)
recpath = utt2recpath[UTTID]
imagename = io_helper.path2uttid(recpath)
imagepath = os.path.join(IMAGEDIR, '%s.png' % imagena... |
13,678 | b9506a7ebc84ca2cd721e8cc7a293aa7c820d249 | import unittest
from appmap._implementation import testing_framework
original_run = unittest.TestCase.run
session = testing_framework.session('unittest')
def get_test_location(cls, method_name):
from appmap._implementation.utils import get_function_location
fn = getattr(cls, method_name)
return get_func... |
13,679 | 2ade7817616eff6ea2bf212ebc3c46dc84536f34 | atomic_weights = {
'C': 12,
'O': 16,
'H': 1,
'N': 14,
'S': 32,
}
amino_acids = {
'A': 'ala',
'R': 'arg',
'N': 'asn',
'D': 'asp',
'C': 'cys',
'E': 'glu',
'Q': 'gln',
'G': 'gly',
'H': 'his',
'I': 'ile',
'L': 'leu',
'K': 'lys',
'M': 'met',
'F': 'phe',
'P': 'pro',
'S': 'ser',
'T... |
13,680 | 583f042acda1f09fdea5324cdb1e140bb2a1ccc9 | """
Utilities for the *dicom_parser* package.
"""
from dicom_parser.utils.parse_tag import parse_tag
from dicom_parser.utils.path_generator import generate_paths
from dicom_parser.utils.read_file import read_file
from dicom_parser.utils.requires_pandas import requires_pandas
|
13,681 | 4659611a0aaac9605237518d31250dff8d449a7a | # Author: Rishabh Sharma <rishabh.sharma.gunner@gmail.com>
# This module was developed under funding provided by
# Google Summer of Code 2014
import os
from datetime import datetime
from itertools import compress
from urllib.parse import urlsplit
import astropy.units as u
from astropy.time import Time, TimeDelta
fro... |
13,682 | c2d475169dc4104347997861369f00111d56b6fb | '''
First graph model to be trained for this task.
This file defines the method required to spawn and return a tensorflow graph for the autoencoder model.
coded by: Animesh
'''
import tensorflow as tf
graph = tf.Graph() #create a new graph object
with graph.as_default():
# define the computations o... |
13,683 | 7262b49beadabf3dfc9536fe342f1df02be3aa10 | from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
import random
from models import *
def index(request):
if 'id' not in request.session:
return render(request, "DnD_app/index.html")
return redirect("/profile")
def re... |
13,684 | 04bd6f89e13b83d87fcf57da738d5eac40c008f6 | #!/usr/bin/env python
#
# Autogenerated by Thrift Compiler (0.13.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
import sys
import pprint
if sys.version_info[0] > 2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
from thrift.transport imp... |
13,685 | ccfba5f50ba45914ae96d2e153299adc6ecfe54f | from django.db import models
from django.contrib.auth.models import User
class Order(models.Model):
cliente = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name="Cliente"
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto... |
13,686 | 0d480c5e9d4776a0cee088f958648f92821a2e36 | from django.test import TestCase
import httplib
import json
import urllib
import wechat_utils
# Create your tests here.
def _weichat_msg():
c = httplib.HTTPSConnection("qyapi.weixin.qq.com")
c.request("GET", "/cgi-bin/gettoken?corpid=wx416865667552f10b&corpsecret=60gcQRI8S-1hbMSvqf5CzBnYKBk1O3qOTmPw9Lk37R... |
13,687 | 9a019ba4a9a290b194c36bae40e24a0b93bda7ce | from pylab import scatter, xlabel, ylabel, xlim, ylim, show
from numpy import loadtxt
data = loadtxt("stars.txt", float)
x = data[:,0]
y = data[:,1]
scatter(x,y)
xlabel("Temperture")
ylabel("Magniude")
xlim(0,13000)
ylim(-5,20)
show()
|
13,688 | e1c0faab5138aaca4327b88791a89158c2c7d33e | #implementation of MAML for updating coefficients of Label Shift task.
import torch
from torch import optim
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
# torch.manual_seed(0)
torch.set_default_dtype(torch.double) #bug fix - float matmul
#enable cuda if possible
device = torch.device... |
13,689 | e57e1fd512812770e613ee7c5477250b777914da | """
Chloe Jane Coleman
"""
name = input("Please enter your name")
while name == "":
name = input("Your name must have at least one character \nPlease enter your name")
print(name[::2])
|
13,690 | 67f6b828bbd826610680f346fb7123b26e52a986 | # словарь с информацией о пользователе
user_info = {
'name': str,
'surname': str,
'year': str,
'city': str,
'email': str,
'phone_num': str,
}
def output_user_info(name, surname, year, city, email, phone_num):
""" функция принимает именованные аргументы и выводит в одну строку """
print(f'{name}, {surname}, {y... |
13,691 | 751d1748fe7dfa073d526a649c0bad5904951d2d | # Generated by Django 3.1.7 on 2021-04-10 13:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ups', '0002_package'),
]
operations = [
migrations.RemoveField(
model_name='package',
... |
13,692 | 1b60854726c4f08abc1f235f1ea7a88e101c6f56 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-07-04 09:43:51
# @Author : Zhi Liu (zhiliu.mind@gmail.com)
# @Link : http://iridescent.ink
# @Version : $1.1$
import numpy as np
from improc.blkptcs import showblks
blks = np.uint8(np.random.randint(0, 255, (8, 8, 3, 101)))
showblks(blks, bgcolor='k... |
13,693 | 410fef0c1e9f30b0d95bc615078622c7190b5459 | #different methods to swap two numbers in python
print('first method')
a=int(input('enter 1st no.: '))
b=int(input('enter 2nd no.: '))
a,b=b,a
print('a=',a)
print('b=',b)
print('second method')
a=int(input('enter 1st no.: '))
b=int(input('enter 2nd no.: '))
b=a*b
a=b/a
b=b/a
print(a)
print(b)
print... |
13,694 | e2add2147a8868b695b55ac28cf0f88ddebf8fb5 |
# FTSE100 Data from https://en.wikipedia.org/wiki/S%26P_100
# Run the below script to get the data
#
"""
var data = [];
for(var x of $("#constituents tr")){
var tds = $(x).find('td')
data.push({'company':$(tds[1]).text().trim(), 'symbol': $(tds[0]).text().trim(), 'sector': $(tds[2]).text().trim()});
}
consol... |
13,695 | 7e76fa4df100f6630f042820069f89ca3032c910 | def sortIntegers(A):
i = 0
length = len(A)
while i < length - 1:
j = length - 1
while j > i:
if A[j]<A[j-1]:
temp = A[j]
A[j] = A[j-1]
A[j-1] = temp
j = j - 1
i = i + 1
return A
A = [3, 1, 2, 5... |
13,696 | 65aba8e3f3e6617b6ade26c8ccb46db90117a9ac | """ Tests of the configuration
:Author: Jonathan Karr <jonrkarr@gmail.com>
:Date: 2018-08-20
:Copyright: 2018, Karr Lab
:License: MIT
"""
import os
import pathlib
import pkg_resources
import unittest
import wc_env_manager.config.core
class Test(unittest.TestCase):
def test_get_config(self):
config = wc... |
13,697 | fed571d26b6f03237cf629dc4e5176d31b15629c | #!/usr/bin/python
# -*- coding: utf-8 -*-
# context_proc/processor.py
""" Context processor """
from django.conf import settings
def cont_settings_(request):
"""
Get context settings from settings file
"""
return {"settings": settings}
|
13,698 | 60a1e162fee523ea753cbfa83ae1ca1f7f4a379c | import torch
import torch.nn as nn
from entmax import entmax15, sparsemax
from .sparsesoftmax import sparse_softmax
def entropy(p: torch.Tensor):
"""Numerically stable computation of Shannon's entropy
for probability distributions with zero-valued elements.
Arguments:
p {torch.Tensor} -- tensor o... |
13,699 | e2f6b96784624751d75f673fd47ede1c22985977 | # Use partial function from functools module to rewrite the method for doubleNum and tripleNum
from functools import partial
def multiply(x, y):
return x * y
def doubleNum(x):
return multiply(x, 2)
def tripleNum(x):
return multiply(x, 3)
newDoubleNum = partial(multiply, y=2)
print(newDoubleNum(69))
new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.