index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
100 | d815c6e233d81dfb144442a83e6006aa4e29bfce | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @Author : Copyright@Ryuchen
# ==================================================
from .version import VERSION
__all__ = [
"VERSION"
]
|
101 | eec52695e5afcc21e5fed6453e96cc3a58e7c1df | import micropython
# viper function taking and returning ints
@micropython.viper
def viper_int(x:int, y:int) -> int:
return x + y + 3
print(viper_int(1, 2))
# viper function taking and returning objects
@micropython.viper
def viper_object(x:object, y:object) -> object:
return x + y
print(viper_obj... |
102 | 9119fc1c75de980bbcf74f1e06a36ba587fc490b | import backtrader as bt
class RSIStrategy(bt.Strategy):
def __init__(self):
self.order = None
self.position.size = 0
self.sellAlert1 = False
self.sellAlert2 = False
self.buyAlert = False
self.failureNum = 0
self.successNum = 0
self.rsi_... |
103 | 99785ffb4b594db1fac05ca3d3f5764151b2b7b6 | import django
from rest_framework import serializers
from django.shortcuts import render
from .models import Student
from .serializiers import StudentSerializer
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse,JsonResponse
import io
from rest_framework.parsers import JSONParser
f... |
104 | cf0eb9685cdfc412871d3b36270ddab3e520bb8f | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class CnnArticleItem(scrapy.Item):
title = scrapy.Field()
developments = scrapy.Field()
body = scrapy.Field()
date = scrapy.Field()
clas... |
105 | a42a94798d176e20646d41cf0f4b7e4f99e0790b | import requests
from SPARQLWrapper import SPARQLWrapper, JSON
from rdflib import Graph
from plenum.server.plugin.graphchain.graph_store import GraphStore
from plenum.server.plugin.graphchain.logger import get_debug_logger
logger = get_debug_logger()
class StardogGraphStore(GraphStore):
def __init__(self, ts_db_... |
106 | 7affd79fb0bb47283bbd9a7fbcaa0ba43aa8e6a6 | # Write a program to accept a no & count number of zeros in it.(int=32bits)
def countOfZeros(num):
cnt = 0
while(num!=0):
cnt+=1
num = num&(num-1)
return (32-cnt)
def main():
num = eval(input('Enter number to count zeros in it\'s binary: '))
print('Assumung int... |
107 | 62a7958ba5ebb6da866d6ef156e52136df22f235 |
# =============>This is a Normal mathematical tasks<==========
x = 7
x = 7 // 3 # rounds the number = 2 ans class int
#x = 7 / 3 # gives the floating number = 2.33333335 ans class float
#x = 7 % 3 # gives the reminder = 1 ans class int
#print("x is {}" .format(x))
#print(type(x))
# ================>This is how to ... |
108 | 0744ec646e7b9303c67c25dff2997568c6171b91 | #!/usr/bin/env python3
#
# nextskeleton - An assembler skeleton for the ZX Spectrum Next
#
# Copyright (C) 2020 Richard "Shred" Körber
# https://github.com/shred/nextskeleton
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
109 | 8abfb6a9ca3a7a909a1e8125e8c03e29b2bacda8 | from StockDatabase import StockDatabase
from RNNinner import RecurrentAnalyzer
import torch
import matplotlib.pyplot as plt
import numpy as np
database = StockDatabase()
database.read_data()
prices = torch.tensor(database.normalize(database.get_stock_prices('AAPL',length=2000)))
print(prices.shape)
model = RecurrentA... |
110 | 14f309d478de6de5a0b493503176941fdfa8b702 | import cv2
import numpy as np
if __name__ == "__main__":
cap = cv2.VideoCapture()
while True:
ret, frame = cap.read()
cv2.imshow(frame)
|
111 | 9cab749b915dbb808ac105caa5287b50729f5fd9 | # Generated by Django 3.2.4 on 2021-09-13 17:41
import dataUpload.models
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
... |
112 | 93e5852df00733c024a59d37699bae58bd893030 | #!/usr/bin/env python3
# -*- coding=utf-8 -*-
# description:
# author:jack
# create_time: 2017/12/30
"""
卡片基类
"""
import logging
class BaseCard(object):
def __init__(self, field=[]):
self.data = {}
self.support_set_field = field
def add_cue_words(self, arr):
"""
为卡片添加cue wor... |
113 | 8be4bf5c1a5a7b841edc915793571686ee0bffe6 | """
Given an array nums and a value val, remove all instances of
that value in-place and return the new length.
Do not allocate extra space for another array, you must do
this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter
... |
114 | 1de8c129769827c7fe763ce221cb9fdf8226e473 | def TongTien(m1,m2,s):
if s <=100:
tong = m1 * s
else:
tong = m1 * 100 + m2 * (s-100)
print tong
m1 = float(raw_input("nhap gia m1 :"))
m2 = float(raw_input("nhap gia m2 :"))
s = int (raw_input("nhap so dien da dung :"))
TongTien(m1,m2,s) |
115 | 9989d31dfe13809d67f629cc283cd02ce354a74e | """tables
Revision ID: 35f6815c3112
Revises: None
Create Date: 2013-07-28 21:15:38.385006
"""
# revision identifiers, used by Alembic.
revision = '35f6815c3112'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op... |
116 | 540ae4be6a41d52d9c803f829fc8b13b523b31bc | #MenuTitle: Find and Replace Corner Components at Certain Angles
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Replace Corner Components at blunt or acute angles.
"""
import vanilla, math
from Foundation import NSPoint
class ReplaceCornersAtCertainAngles( object... |
117 | 91df15d6d89d070677704572d35218558317a6ec | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data=pd.read_excel("data_SHA.xls")
fig,ax=plt.subplots()
ax.plot(data["Date"],data["HCHFI"],label="HCHFI")
ax.plot(data["Date"],data["SHA"]/2.67547,label="SSE Composite Index")
ax.plot(data["Date"],data["Hushen300 Index"]/3.20393,label="Hushen300 In... |
118 | b38d23a7de3c805ddde4ed2d236e3c6e7bb5e2d0 | #!/usr/bin/python3
import os
import netifaces
# nicList = netifaces.interfaces()
NICList = [i for i in netifaces.interfaces() if i != "lo"]
for i in NICList:
os.system("sudo ifconfig " + i + " promisc")
os.system("sudo python ./src/top.py")
|
119 | 203e678d565753bb51e1bbd90ffec0f3260b22fb | #Copyright 2020 Side Li, Arun Kumar
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing... |
120 | bf5422792533f85967a5573d9e6f370a7967a914 | N = int(input("Max value N? "))
s = set()
for i in range(2, N + 1):
s.add(i)
for num in sorted(s):
k = num + num
while k <= N:
if k in s:
s.remove(k)
k += num
print("Primes:", end = " ")
for num in sorted(s):
print(num, end = " ")
|
121 | 9c4676edbeef3748a4947f827fefa29e95674bfa | #https://www.youtube.com/watch?v=CQ5kc_j4RjA
import pandas as pd
#import quandl
import math, datetime
import time
import numpy as np
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import cross_validation, preprocessing, svm
from sklearn.metrics import accuracy_s... |
122 | 4e61f9fefe8e6b5203ba05ac9bd626db1102df36 | #!/usr/bin/python
"""
Created on Aug 1 2014
"""
import rospy
def my_callback(event):
print 'Timer called at ' + str(event.current_real)
if __name__ == '__main__':
rospy.init_node('timer')
rospy.Timer(rospy.Duration(2), my_callback)
rospy.spin() |
123 | 53573a21364e9dfef9ed1164185ab441dbc29601 | from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseNotAllowed
from booli import booliwood
from models import add_bosta, get_all_bostas, Bosta
from django import forms
import time
class BostaForm(forms.Form):
maxPrice = forms.IntegerField()
livin... |
124 | 4642537f8af1f060f5ee43cc9e98bd07be6a558c | # import libraries
import sys
import pandas as pd
import numpy as n
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""
This function loads the message and categories files and
merge them and return the new dataframe for the project
"""
# Read messages an... |
125 | a57059927a7bd3311c1d104bfc80877912c7d995 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 07:48:47 2018
@author: hfuji
"""
import os
from PIL import Image
import glob
import shutil
src_jpg_dir = 'D:/Develop/data/VOCdevkit/VOC2007/JPEGImages/'
dst_bmp_dir = 'D:/Temp/'
jpg_files = glob.glob(src_jpg_dir + '*.jpg')
cnt = 0
for jpg_file in ... |
126 | 7dc99d33023dbb13938ac413af7d3e9471fdbc3d | #the initial DNA sequence
dnaSequence = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'
#seperating the DNA sequence at the specified location
firstFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [0:22]
secondFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [23:100]
... |
127 | 000dd63089fd0c6184fd032fe75ccc920beee7a8 | #!/usr/bin/python
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
#Your code here
def loadData(fileDj):
data = []
fid = open(fileDj)
for line in fid:
line = line.strip()
m = [float(x) for x in line.split(' ')]
data.append(m)
return data
## K-means... |
128 | 1980fb4d6e7d3c6fe51f4a242610b5489e553859 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/14 14:31
# @Author : lixiaofeng
# @File : page_zaojiao.py
# @Software: PyCharm
# @desc :
from common.basics import Crazy
class Zaojiaopage(Crazy):
"""早教小程序"""
zao_btn_loc = ('xpath', '//*[@resource-id="com.tencent.mm:id/cx" and @text="... |
129 | fa8d603fbea287161d31499f96a7fe7e56e8eaa1 | def filtra_acima(wires, origem):
return [wire for wire in wires if wire[0] > origem ]
def filtra_abaixo(wires, destino):
return [wire for wire in wires if wire[1] < destino ]
def calculate(wires):
count = 0
for i in xrange(len(wires)):
wires_acima = filtra_acima(wires, wires[i][0])
wir... |
130 | fa3cec0781b9ca5c1d99a7500748104d7cdce631 | import json
import jieba
import util
from pypinyin import pinyin, Style
class Song:
def __init__(self, songName, artistName, lyric):
self.songName = songName
self.artistName = artistName
self.lyric = lyric
self.phrasePinyinDict = util.lyricToPinYi(self.lyric)
def getSongName(se... |
131 | 089bdd6d68a69aff6f3c11f7f5ffb75aed73cd24 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 14:52:03 2018
@author: mayn
"""
import matplotlib.pyplot as plt
import DNA_Object
import json
def draw_area(dna, room):
area_center, area = DNA_Object.get_room_area(room)
plt.plot(area['x'], area['y'], linewidth='0.5', color='k',)
plt.xlim((-15000, 20000... |
132 | 50a4084dd3028acc2e6788e77794c100efcb3fac | import random
import numpy as np
import os
import torch
class Agent:
def __init__(self):
self.model = torch.load(__file__[:-8] + "/agent.pkl")
def act(self, state):
state = torch.tensor(state)
with torch.no_grad():
return self.model(state.unsqueeze(0)).max(1)[1].it... |
133 | de704bffe2e23a8a83d34204e325b7fb2454ef66 | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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/LICEN... |
134 | 0b0eebd31d822ff5c1b951c3ee213f58a3a13aa0 | #coding=utf-8
#
"""
my custom common module
"""
import json
import base64
# sdk账号信息
APP_ID = '10676432'
API_KEY = 'Hy1D1urUTdXzTOzqr9LeN3gc'
SECRET_KEY = 'foS4GMg2w3QZtO9XNoSQF17Kkk007xWk'
def print_json(obj):
"""json格式打印信息
Args:
obj 待打印的对象信息
"""
print(json.dumps(obj, ensure_ascii=False))
... |
135 | 68e09f72e8338efbef108ffd0c93eff067bf7b07 | # -*- coding: UTF-8 -*-
from keywords.httpkeys1 import HTTP
http1 = HTTP()
# ip = '10.68.170.184:8080'
ip = '10.68.170.184:8080'
http1.post('http://'+ip+'/music_download/api/login','username=admin&password=123456')
# http1.savejson('result','id')
# http1.get('http://47.101.197.102:8080/music/api/user','{id}')
# dat... |
136 | 2af8677e76b77b9bfa579012a85ea331c0c7f390 | from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
class LayoutWindow(FloatLayout):
pass
class floatlayoutApp(App):
def build(self):
return LayoutWindow()
if __name__== "__main__":
display = floatlayoutApp()
display.run() |
137 | 0d20b75bcc87db8f3e4bdd9d6448cc44c979de1d | """
问题描述
玛莎(Marsha)和比尔(Bill)拥有一系列大理石。他们希望将藏品分开,以使两者获得相等的份额。如果所有的大理石都具有相同的价值,这将很容易,因为那样他们就可以将收藏品分成两半。
但不幸的是,有些大理石比其他大理石更大或更漂亮。因此,玛莎(Marsha)和比尔(Bill)首先为每个大理石分配一个值,即一个介于1到6之间的自然数。
现在,他们希望对大理石进行分割,以使每个大理石都获得相同的总价值。不幸的是,他们意识到以这种方式分割大理石可能是不可能的(即使所有大理石的总价值是均匀的)。
例如,如果存在一个值为1的大理石,值为3的一个,值为4的两个,则不能将它们拆分为相等值的集合。因此,他们要求您编写一个程序来检查... |
138 | 264896da4d92797b9f31e28c19a2e315efff815a | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-08-26 21:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exchange', '0004_auto_20170826_2120'),
]
operations = [
migrations.AlterMod... |
139 | 63a2258bf0ed779254b68a683e3d30e9fb356b1f | from django.contrib import admin
# from .models import Usuario
# from .models import Lote
# from .models import Fornecedor
# from .models import Cliente
# from .models import Medicamento
# from .models import Medicamento_Entrada
# from .models import Medicamento_Saida
# Register your models here.
#
# class UsuarioAdmin... |
140 | 0e4c82d6eb77d2b6357925c9aab516bcc3310a4c | # 4 Pillars of OOP:
# 1. Encapsulation: Encapsulation in Python is the process of wrapping up variables and methods into a single entity.In programming, a class is an example that wraps all the variables and methods defined inside it.
# 2. Abstraction: Abstraction in Python is the process of hiding the real implementat... |
141 | 26d14bc74d893f6f14ee7405280f4af41854c544 | import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import argparse
import numpy as np
def run(path, output):
#xml_df = xml_to_csv(path)
#xml_df.to_csv(output, index=None)
# for filename in os.listdir(path):
# base_file, ext = os.path.splitext(filename)
# print(bas... |
142 | 3b1426e0f29093e1e462765bcf1d351a064b9639 | # -*- coding: utf-8 -*-
########### SVN repository information ###################
# $Date: $
# $Author: $
# $Revision: $
# $URL: $
# $Id: $
########### SVN repository information ###################
'''
*GSASIIfpaGUI: Fundamental Parameters Routines*
===============================================
This module contain... |
143 | 4652cd5548b550cc21d126fc4fbe3e316ecb71b2 | import json
import requests as requests
from flask import Flask
from flask import request
from tools import AESCipher, tokenId, TokenKey, appId
from tools import TCApplyNeedleUrl, TCCreditNeedleUrl, TCWJNeedleUrl
app = Flask(__name__)
@app.route('/', methods=['POST'])
def hello_world():
if reques... |
144 | b88af16693eca10d0bd78fd706389f5468c9b99b | from django.urls import path
from .views import job_upload_view, job_view, job_applicants_view, posted_job_view, bussiness_list_view
app_name = 'jobs'
urlpatterns = [
path('', job_view, name='job-index'),
path('applicants/', job_applicants_view, name='job-applicants'),
path('posted/', posted_job_view, name='job-... |
145 | 43bad38d209b5c326cb9f17ba1ae135d06320e97 | from rest_framework import filters
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from apis.models import Contact, Address, InvoicePosition, Country, Invoice
from apis.serializers import ContactSerializer, AddressS... |
146 | 1429524b0ae3b679bc3d4386dd17ed50b0fff381 | balance=42
annualInterestRate=0.20
monthlyPaymentRate=0.04
monthlyir = annualInterestRate/12
rb=balance
for i in range(12):
mp = monthlyPaymentRate * rb
rb=rb-mp
rb=rb+rb*monthlyir
print('remaining balance: ',round(rb,2))
|
147 | cef4568b4568bceeedca6d57c0ccacfaae67c061 | from time import time
import threading
import os
#hh:mm:ss
movie1Time = "00:00:00"
movie2Time = "00:00:00"
movie3Time = "00:00:00"
movie4Time = "00:00:00"
movie5Time = "00:00:00"
timer1Start = None
timer1Time = "00:00:00"
timer1Running = False
timer2Start = None
timer2Time = "00:00:00"
timer2Running = False
timer3Star... |
148 | 051bd11c42815ec8f8ece8eae9d33890da77129c | # -*- coding: utf-8 -*-
from services.interfaces.i_service import IService
from services.dbservices.db_service import DBService
class GetCommunitiesByOffsetService(IService):
def __init__(self, core, parameters):
super(GetCommunitiesByOffsetService, self).__init__(core, parameters)
def run(self):
... |
149 | 03f73a55e0a0773bbdbb0d5e29a2db598ba2e080 | #Week 5
#Task 1.1
a = 13
b = 14
calculation = a + 1 <=b
calculation2 = a + 1 >=b
calculation3 = a + 1 !=b
print (calculation)
print (calculation2)
print (calculation3)
#Task 1.2
myage = input("How old are you : ")
print ("Hi there, You are " +myage+ " years old")
#Task 1.3
num1 = input("Enter the first number : ")
num2... |
150 | ba72af921a9562d748bcd65f1837ea8eb5da5697 | from random import choice, random, randrange
from math import fsum
import os
import numpy as np
def mat17(N, ATOM_TYPES, ndenmax=0.04302, ndenmin=0.0000013905, xmax=51.2, xmin=25.6, ymax=51.2, ymin=25.6,
zmax=51.2, zmin=25.6, epmax=513.264, epmin=1.2580, sigmax=6.549291, sigmin=1.052342, qmax=0.0, qmin=0.0):
#epmax DE... |
151 | dab1adcd185092fc425b5d87150f27e7b67bff6c | ba0563.pngMap = [
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'0000000000000000000000000000000000000... |
152 | 924fd89a835528fa28e1226912a2e4be9c4e1d5d | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.core.urlresolvers import reverse
from google_product_feeder.feed import CSVMerchantFeed, MERCHANT_FEED_COLUMNS
CSV_HEADINGS = ','.join(MERCHANT_FEED_COLUMNS) + '\r\n'
class AttrNameF... |
153 | 99a6b450792d434e18b8f9ff350c72abe5366d95 | try:
alp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
idx=eval(input("请输入一个整数"))
print(alp[idx])
except NameError:
print("输入错误,请输入一个整数")
except:
print("其他错误")
else:
print("没有发生错误")
finally:
print("程序执行完毕,不知道是否发生了异常")
|
154 | 3c9302b5cb92e5103ed16ec56e1b349f0662950c | # -*- encoding: utf-8 -*-
from django.contrib import admin
from finish.wall.models import (Autor, Category, Announcement, Banner, Caricatura,
Video, TypePost, Post, Phrase, TypeGalery,
ImageGalery, Sponsor)
class AutorAdmin(admin.ModelAdmin):
pass
... |
155 | ab352c9431fda19bc21a9f7ffa075303641cca45 | from opengever.propertysheets.assignment import get_document_assignment_slots
from opengever.propertysheets.assignment import get_dossier_assignment_slots
from opengever.propertysheets.storage import PropertySheetSchemaStorage
from plone.restapi.services import Service
LISTING_TO_SLOTS = {
u'dossiers': get_dossie... |
156 | 43e721ac45570e4f9ab9c1970abee3da6db40afa | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
157 | 07ac061d7d1eaf23b6c95fbcbf6753f25e568188 | from scipy.io import wavfile
import numpy
from matplotlib import pyplot as plt
import librosa
import noisereduce
def loadWavFile(fileName, filePath, savePlot, maxAudioLength, reduceNoise = True):
# Read file
# rate, data = wavfile.read(filePath)
# print(filePath, rate, data.shape, "audio length", data.shap... |
158 | bb481fa038835abc6d61a4985b1e30c7c00bff96 | def pixels_generator(w, h):
i = 0
while i < (w * h):
yield divmod(i, w)
i = i + 1
|
159 | b6824251b1165ca6c66049d40c79fccee6bc7d3a | from .. import db
class Account(db.Model):
id = db.Column(db.Integer, primary_key=True)
acc = db.Column(db.String(50), unique=True)#TODO 调整长度
pwd = db.Column(db.String(50))#TODO 调整长度
name = db.Column(db.String(20))
sex = db.Column(db.SmallInteger)
idno = db.Column(db.String(20))
phone = db... |
160 | 485f85ec5e3f38148978453ea5e7f9a54eb310e1 | import dash_table
import pandas as pd
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from dash_oop_components import DashComponent
import dash_table
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from dash_oo... |
161 | bdc9856bfc61127d6bca31658b1faf3da09f5b86 | #! /user/bin/env python
import requests
from getpass import getpass
import csv
# Set up the variables
with open("ACI PostMan Variable Values.csv", encoding='utf-8-sig') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
print("Let's configure the subnets... |
162 | debd51b923a6fc3b278a5083478bfb271a5913a8 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import gc
import logging
import os
import mock
import sys
import time
from shellbot import Context, Engine
from shellbot.i18n import Localization, localization as l10n, _
class LocalizationTests(unittest.TestCase):
def test_default(self):
lo... |
163 | 5917c891d2885f779dc33f189f1a875efbd0c302 | from abc import ABCMeta, abstractmethod
from datetime import datetime
from enum import Enum
from application.response import ResponseError
class ModelBase:
__metaclass__ = ABCMeta
@classmethod
@abstractmethod
def _get_cls_schema(cls):
pass
def __new__(cls, schema):
if schema is ... |
164 | 41417e3ce52edf6aee432886bbab6d16ec5bc88d | """
Created on 01/10/18.
Author: morgan
Copyright defined in text_classification/LICENSE.txt
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class RNNClassifier(nn.Module):
def __init__(self, batch_size, num_classes, hidden_size, vocab_size, embed_size, w... |
165 | 9a55ccf758b4b2cc440153ab3b1f97823863a848 | from django.db import models
# Create your models here.
class Logins(models.Model):
created = models.DateTimeField(auto_now_add=True)
login_addr = models.GenericIPAddressField()
hostname = models.CharField(max_length=200)
|
166 | 6c0b2fa8166bb21a514dc188858e1de285ad9b0a | # -*- coding: utf-8 -*-
#
# File: PatrimonyCertificate.py
#
# Copyright (c) 2015 by CommunesPlone
# Generator: ArchGenXML Version 2.7
# http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
__author__ = """Gauthier BASTIEN <gbastien@commune.sambreville.be>, Stephan GEULETTE
<stephan.ge... |
167 | d327151c9659078e12e4aca46631de33e7ca4dcf | import numpy as np
import numdifftools as nd
from scipy import stats
from scipy import optimize
from functools import partial
class TCRPowerCalculator:
def __init__(self, pcmodel):
self.pcmodel = pcmodel
self.predict_variance = self.pcmodel.predict_variance
self.predict_mean = self.pcmodel.predict_mean
self.... |
168 | 704b3c57ca080862bed7a4caa65d1c8d5a32fa0b | import onmt
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.cuda
from torch.autograd import Variable
class CopyGenerator(nn.Module):
"""
Generator module that additionally considers copying
words directly from the source.
"""
def __init__(self, opt, src_dict, tgt_d... |
169 | 630011b188548df9e55b6f1ddbefa08e322b9cba | from datetime import datetime
import cv2
import numpy as np
from sklearn.cluster import KMeans,MiniBatchKMeans
class FeatureGetter(object):
def __init__(self):
self.sift_det = cv2.xfeatures2d.SIFT_create()
def get_img(self, img_path):
img = cv2.imread(img_path)
return img
def get_fe... |
170 | 7e1f77210b3beb4e496ff95686d65bd7d79561a3 | import random
a=input("enter 'r' to roll the dice and 'q' to quit")
while True:
if (a=="r"):
print(random.randint(1,6))
elif(a=="q"):
print("bye!")
exit()
else:
print("give either 'r' or 'q'")
|
171 | 9188d58a6d9e832b8908b823d57249fcdd80ff51 | class Classifier(object):
"""
Trained classifier
"""
def __init__(self, classifier, scaler, orient, color_space, pix_per_cell,
cell_per_block, spatial_size, hist_bins):
"""
Initializes an instance.
Parameters
----------
classifier : Trained S... |
172 | 2f6e0b6a7e14ac9c5a38db6fd2b1cf23cff7144e | class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class dequeue:
def __init__(self):
self.front = None
self.last = None
self.count = 0
def add_front(self, data):
new_nodef = Node(data)
if(self.front ==... |
173 | 95f7710fb0137617025819b6240312ce02915328 | #!/usr/bin/env python
from ROOT import TFileMerger
import subprocess
def MergeFiles(output, fileList, skipList=[], acceptList=[], n=20):
merger = TFileMerger(False)
merger.OutputFile(output);
merger.SetMaxOpenedFiles(n);
print "Total number of files is {0}".format(len(fileList))
for fileName... |
174 | bfb2d7b811fd450b53493375fa130649349d308f | for i in range(0,20):
if i % 20 == 0:
print('Stop It')
else:
print('The For Loop Failed') |
175 | 720ec6c222659a13d4a0f3cf9096b70ce6e2b2b3 | # Copyright 2010 Google Inc. All Rights Reserved.
#
import copy
import logging
import threading
from automation.common import command as cmd
from automation.common import logger
from automation.common.command_executer import CommandExecuter
from automation.common import job
from automation.common import job_group
fro... |
176 | 700d35f9e941fe9325821a377ec1ca1c245ddaec | import jiml.cli
def write_file(path, text):
path.write_text(text)
return path
def test_argparse(tmp_path):
tmpl = write_file(tmp_path / 't.yaml', 'key: {{ var }}')
inp = write_file(tmp_path / 'i.json', '{"var": "Hello!"}')
out = tmp_path / 'o.json'
jiml.cli.main(jiml.cli.parse_args(
... |
177 | e868998833774c829b05ae8da3280bed61363be1 | #!/usr/bin/env python2
from rpcz import compiler
PROTO = '../index_server.proto'
compiler.generate_proto(PROTO, '.')
compiler.generate_proto(
PROTO, '.',
with_plugin='python_rpcz', suffix='_rpcz.py')
|
178 | 848e4abcd0b4f118030fc62f1272a19bfce9db4e | import argparse
import gc
import gcsfs
import nibabel as nib
import nilearn
import nobrainer
import numpy as np
import os
import os.path as op
import pandas as pd
import tensorflow as tf
def interpolate_images(baseline, image, alphas):
alphas_x = alphas[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]
basel... |
179 | 3817770a80f8ab16322485522be18edd6b3f5516 | from flask import Flask
app=Flask('__name__')
@app.route("/my/<name>/<age>")
def my(name,age):
name ="saral"
age="20"
return "my name is {} and age is {}".format(name,age) |
180 | 9931fc25118981bcce80cffd3fda9dc99d951bf5 | s = input()
if len(s) < 26:
for i in range(26):
c = chr(ord("a")+i)
if c not in s:
print(s+c)
exit()
else:
for i in reversed(range(1,26)):
if s[i-1] < s[i]:
s1 = s[0:i-1]
for j in range(26):
c = chr(ord("a")+j)
... |
181 | e30bd33ae18881307e7cf4f60d3c60eae91573bc | # Copyright (c) 2019 Jannika Lossner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dis... |
182 | ba8b46f830abaaaedf1730cba2f04fd677f11da4 | # -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, unicode_literals, division
__all__ = ['getLevelName', 'getLevel'] #, 'getLevelOrName', '_checkLevel']
import logging
# private re-implementations till Python Core fixes Lib/logging
# XXX bug numbers here
def getLevelName(level, format='... |
183 | 88c304f224ab60062582abbfa1146a651e1233e6 | def missing_value_count_and_percent(df):
"""
Return the number and percent of missing values for each column.
Args:
df (Dataframe): A dataframe with many columns
Return:
df (Dataframe): A dataframe with one column showing number of missing values, one column showing percentage of ... |
184 | e5d31a2ea4a8615d24626be2414f5ae49b9cd6a1 | """
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
"""
# 196ms. 98 percentile
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:
... |
185 | 7e2bf898eb1c0118205042797e6dac535342979b | import os
import tkinter as tk
from tkinter import messagebox
from os.path import join
from pynput import keyboard
from src.save_count import SaveCount
class MainApplication(tk.Frame):
def __init__(self, root: tk.Tk):
super().__init__(root)
self.root = root
self.pack(padx=32, pady=32, e... |
186 | f8601ed7ba7c2b8d2dd8d5f74f7b5ae8e99dad78 | IS_ZERO = lambda x: x == 0
ONE = 1
SUB1 = lambda x: x - 1
MULT = lambda x: lambda y: x * y
IF = lambda cond: lambda t_func: lambda f_func: t_func(None) if cond else f_func(None)
print(
(
lambda myself: (
lambda n: (
IF(
IS_ZERO(n)
)(
... |
187 | 8e854398084e89b0b8436d6b0a2bf8f36a9c7bd5 | from unittest import TestCase
from unittest.mock import patch, mock_open, call
from network_simulator.exceptions.device_exceptions import DeviceAlreadyRegisteredException, UnknownDeviceException
from network_simulator.service import NetworkSimulatorService
from network_simulator.service.network_simulator_service impor... |
188 | fcd3e4c0d42649833e6c5ff6414c993654691d16 | from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from product.models import Item,Product,Category
# Register your models here.
admin.site.register(Category,MPTTModelAdmin)
admin.site.register(Item)
admin.site.register(Product) |
189 | 565888d771f53934805555390e48d4886a43bdb6 | import renderdoc as rd
from typing import List
import rdtest
class D3D12_Resource_Mapping_Zoo(rdtest.TestCase):
demos_test_name = 'D3D12_Resource_Mapping_Zoo'
def test_debug_pixel(self, x, y, test_name):
pipe: rd.PipeState = self.controller.GetPipelineState()
if not pipe.GetShaderReflection(... |
190 | 607fc97c4520c7f54ee44e768776ceae2b70c378 | import os
from flask import Flask
from flask import request
result=""
app = Flask(__name__)
@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
global result
#print (request.is_json)
content = request.get_json()
#print (content)
#print ("true")
#print (content["encode"])
#p... |
191 | 247e352b7772a1da74a26f007228355f5af8d3b3 | def lcs(X, Y, m, n):
dp = [[0]*(n+1) for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if X[i-1] == Y[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
index = dp[m][n]
s = ""
... |
192 | 5ac4dd62d8e56c7baf38f9fe9f8b4a5034f1cb80 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# (119ms)
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool... |
193 | daccc5aafb3e250e7fa7ac9db69a147b7e916736 | import numpy as np
import matplotlib.pyplot as plt
def f(x:float,y:np.ndarray) -> np.ndarray:
"""
Работает с вектором { y , y'}
"""
# return some function result
return np.array([y[1], np.sqrt(abs(-np.exp(y[1])*y[0] + 2.71*y[0]**2/np.log(x)+1/x**2))])
# return np.array([y[1], -y[0]... |
194 | 18b43ea8696e2e54f4c1cbbece4cde1fd3130145 | from robocorp_ls_core.python_ls import PythonLanguageServer
from robocorp_ls_core.basic import overrides
from robocorp_ls_core.robotframework_log import get_logger
from typing import Optional, List, Dict
from robocorp_ls_core.protocols import IConfig, IMonitor, ITestInfoTypedDict, IWorkspace
from functools import parti... |
195 | 6ad36f2b115c822a50a38e88a8d7d524fc5b045b | a,b,c=map(int,input().split())
frag='NO'
for i in range(b-1):
if (i+1)*a%b==c:
frag='YES'
break
print(frag)
|
196 | 02182f0379e58b64bbe17cc5f433e8aae7814976 | from flask import Blueprint
web = Blueprint('web', __name__)
from app.web import auth
from app.web import user
from app.web import book
|
197 | 074defa92c8bc5afc221c9c19842d808fbf1e112 | # -*- coding: utf-8 -*-
import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
... |
198 | c879230efe12bde9042159da221a2b9b4c1d8349 | #-*- coding: utf-8 -*-
import re
import sys
import os
import pandas as pd
import jieba
import logging
import argparse
from sklearn.externals import joblib
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import f1_score,accuracy_score
from sklearn.feature_extraction.text im... |
199 | 7525691ece4fe66bb175e470db3ac78f701e3730 | # create item based on name using post method, get specific item or list of items using get method, update item using put and delete item using del method.
import os
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT, timedelta
from security import authenticate, identity
from resources.us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.