index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,500 | dc2427655490bc3521cad798225289acaabf3ce5 | import pandas as pd
from evaluation import features, evaluation
datasets = [
"wine.csv",
"ionosphere.csv",
"movement_libras.csv",
"SCADI.csv",
"parkinsons.csv",
# "sonar.csv",
# "vehicle.csv"
]
solutions = [
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1... |
993,501 | e0e7b98e72fa47b146e749f39f0cb343a52e14c8 |
# 스트리밍 데이터의 이동 평균
#
# 정수 데이터가 스트리밍으로 (한번에 하나씩) 주어진다고 합시다. 이때, 주어진 범위 만큼의 이동 평균을 구하는 클래스 MovingAvg를 만들어 봅시다.
#
# MovingAvg는 처음에 이동 평균의 범위를 입력받아서 초기화 되며, 매 정수 데이타가 입력되는 nextVal(num)함수는 이때까지의 이동 평균을 반환합니다.
#
# 예를 들어서, 2,8,19,37,4,5 의 순서로 데이터가 입력되고, 이동 평균의 범위는 3이라고 합시다. 이 경우 다음과 같이 MovingAvg가 사용 될 것입니다.
# ma = MovingAvg(3... |
993,502 | f901f6a5d586bc716d36f18d66c936b719a7fe4f | ###################################################################################################################################################
# filename: ga.py
# author: Sara Davis
# date: 10/1/2018
# version: 1.0
# description: Generic Genetic Algorithm
##########################################################... |
993,503 | 6401f65be4227670e04e8e5cf200f26968afabe9 | from robot_control_class import RobotControl
rc = RobotControl()
num = int(input("Enter a number between 0 and 719 "))
laser = rc.get_laser(num)
print("Laser distance is %d meters" % laser)
|
993,504 | 8cd6a154eb819bfab0d0491f187cf7befb6dddb2 | import sqlite3
conn = sqlite3.connect('db.sqlite3')
print ("Opened database successfully")
conn.execute('CREATE TABLE computers (id INTEGER PRIMARY KEY,brand TEXT)')
conn.close() |
993,505 | 342e6801da125e5fc8fedcf3124c4f52ceb5bc8b | # -*- coding: utf-8 -*-
"""
@author: JiangSu
Email: jiangsukust@163.com
============================= pypls =============================
Provides
1. PartialLeastSquares(CrossValidation, ValsetValidation, Prediction)
-- CrossValidation, cv
-- ValsetValidation, vv
-- Prediction, predict
++ It sh... |
993,506 | de5fb3e0dfd8e5664b78b377e6abea106a2d4f09 | def testies():
my_dict = {'url' : ['url1'], # list of urls
'fnum' : [2], # number of files in each url
'sheet': [None]} # sheet number of every file per url, respectively to url
print(my_dict['url'], my_dict['sheet'])
my_dict['path'] = []
... |
993,507 | 254550e20cfc447edfb7abbbadf43245779dc2a9 | #! /usr/bin/env python
PACKAGE='wj_716_lidar'
from dynamic_reconfigure.parameter_generator_catkin import *
#from math import pi
#from driver_base.msg import SensorLevels
gen = ParameterGenerator()
# Name Type Reconfiguration level Description D... |
993,508 | 833ae1225e288dc63c7414bee6a0277f4083f212 | from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation
from tensorflow.keras.layers import Input, ZeroPadding2D, MaxPooling2D, Add
from tensorflow.keras.layers import AveragePooling2D, Flatten, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.initializers import glorot_uniform
... |
993,509 | d4ba5a4d7ebc2427d5a8725c671c4728b76fca29 | #coding:utf-8
"""
多继承: 一个类可以同时继承多个父类
会将多个父类的方法属性继承过来
""" |
993,510 | 74ad320f5a7d676a94ab26da09ab46280875c5ea | import random
import sys
sys.setrecursionlimit(5000)
sys.modules['_decimal'] = None
import decimal
from decimal import *
from decimal import Decimal
getcontext().Emin = -10 * 10000
getcontext().Emax = 10 * 10000
getcontext().traps[Overflow] = 0
getcontext().traps[Underflow] = 0
getcontext().traps[DivisionB... |
993,511 | f1c1f09653087f5e2c4702e8fd5e4acd67f3c515 | import tkinter
import tkinter.messagebox
import pickle
# main (root) GUI menu
class CrudGUI:
def __init__(self, master):
self.master = master
self.master.title('Welcome Menu')
self.top_frame = tkinter.Frame(self.master)
self.bottom_frame = tkinter.Frame(self.master)
self.... |
993,512 | 7aee90f77331e2779884f28c7d13f2736d545d2d | import pytest
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.actor import initrdinclude
from leapp.libraries.stdlib import api, CalledProcessError
from leapp.libraries.common.testutils import CurrentActorMocked, logger_mocked
from leapp.models import InitrdIncludes, InstalledTargetKernelVers... |
993,513 | 64f3495358e96fd438f06e72cbb4e81c64c7982f | # Time: O(n), where n=size(tree)
# Space: O(logn), stack space ~height of tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:... |
993,514 | 95277f65eee48987f77ff3f2c4c4c967da7a888b | #dict basics
fares = {10,20,30}
print(type(fares))#set
titanicData = {'id':(5,7,10), 'fare':(10,20,30), 'Sex':['Male','Female','NA']}
print(type(titanicData))
#tuple accessing
titanicData['id']
titanicData['Sex']
titanicData['pid']#if acces like this will throw error
titanicData.get('pid')#no error
type... |
993,515 | abc6fe125b375671e67a73275169372bef70edc3 | # Copyright 2023, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
993,516 | c7799b7af465e2b3d62b2aafc92f05b175a5df1f | #!/usr/bin/env python
'''
Beating the stock market
Given an array for which the ith element is price of given stock on day i.
If you were only permitted to buy one share of the stock and sell one share of the
stock, design an algorithm to find best times to buy and sell
'''
def bestBuySell(stock):
buy, sell, minP... |
993,517 | 83862050556dc6efcf0ed34d2fd54718b0888ce7 | from random import seed
from random import randint
seed()
stop = 1
while stop:
value = randint(1, 6)
print("Type 'r' to roll the dice")
print("Type 's' to stop")
rollAgain = input()
if rollAgain == "r":
print("DICE VALUE: "+ str(value) +"\n")
continue
else:
if rollAgain... |
993,518 | dd5db504a3cab012dbff723862c7caa4f775d131 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# 忽略警告
import warnings
warnings.filterwarnings('ignore')
# 单个单元格多个输出
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'
... |
993,519 | 7ed3f807ea0900931c8cefce84b8e2b0644fa737 | #!/usr/bin/env python
# coding: utf-8
# In[20]:
import pandas as pd
# In[21]:
p1=pd.Series({'r':67,'u':90})
# In[22]:
p1
# In[23]:
p1=pd.Series({'r':67,'u':90},index=['u','r'])
# In[24]:
p1
# In[25]:
p1=pd.Series({'r':67,'u':90},index=['a','b'])
# In[26]:
p1
# In[27]:
l1=[9,8,7,6,5,3]
#... |
993,520 | 18c886c3f8603f2c19a8384d89f5b71f2c3eea3a | """
Ryan Pepper (2018)
fileparser.py
This file contains a parser function that processes a text file.
"""
import re
def _read(filename, encodings=['ascii', 'utf-8', 'utf-16', 'latin-1']):
"""
_read(filename)
Try to read files and return the text regardless of their encoding.
Raises UnicodeError on... |
993,521 | 6cdcca1c94d576494a259389d2f214c9971c295e |
from __future__ import division, print_function, unicode_literals
import os
import numpy as np
import torch
import torch.utils.data
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn as nn
#get_ipython().magic(u'matplotlib inline')
import matplotlib.pyplot as plt
from to... |
993,522 | e6c4678c2bd0dc82ce6f86f186fa6ed0b3fc6df5 | class Solution(object):
def simplifyPath(self, path):
if not path:
return path
stack = []
temp = list(path.split('/'))
for each in temp:
if each == '.' or not each:
pass
elif each == '..':
if stack:
... |
993,523 | 0b0900420481ccbd67e23535c0a5fb195f6bf7d4 | from hashlib import sha256
import hmac
import json
from collections import OrderedDict
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from res... |
993,524 | 7775c311ea01de9b283508abbeeb32285254b43e | from django.conf.urls import patterns, include, url
from django.contrib import admin
import urls
from apps.blog import views
urlpatterns = patterns('',
url(r'^p/(?P<pk>[\w\d]+)/(?P<slug>[\w\d-]+)/$', views.PostDetail.as_view(), name='detail'),
url(r'^category/(?P<catname>[\w\d]+)/$', views.CatDetail.as_view(),... |
993,525 | 5d5299a5f4c05942ffb407d6519ea45fd71b989d | # Generated by Django 3.2 on 2021-06-19 08:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photographer', '0021_photoportfolio_seat_number'),
]
operations = [
migrations.AddField(
model_name='photoportfolio',
... |
993,526 | 807adbcce4c99262170c50b35d6a368aa8dfe216 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains implementation for DCC tools
"""
from __future__ import print_function, division, absolute_import
import os
import logging
import inspect
from collections import OrderedDict
from tpDcc import dcc
from tpDcc.core import tool
from tpDcc.managers ... |
993,527 | 36d67062ac0e5ce456568b5888710af246d3f75b | import urllib.request
import random
import json
import os
from time import sleep
#print(authenticNode)
connected_nodes = [] #nodes present in the network
banned_nodes = {} # banned nodes
trust_values = {} # trust values of each and every node
trust_ranking = {} # ranking based on trust value (visible)
def ch... |
993,528 | aa2429037a5d8feb8d8e452eb0cd47e1d54b3343 | import hashlib
h = hashlib.sha256()
h.update(b'Kim')
result = h.hexdigest()
print(result)
|
993,529 | 8f38d0eb94f9c937ac7f5dfb6ee28745c511f1f0 | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
gasNo = 0
costNo = 0
total = 0
while gasNo < len(gas) and costNo < len(cost):
if cost[costNo] < gas[gasNo]:
total = gas[gasNo] - cost[costNo]
... |
993,530 | 4874ee64554acc5e5245cb1c548fa737395724cd | ############################# Latihan - Tugas 1
'''
Gunakan API dari Zomato
Selamat datang di Zomato Apps:
Silahkan pilih opsi :
1. Cari resto
2. Daily Menu
Opsi 1 :
Mencari Restoran di kota tertentu
Input:
- Masukkan Nama Kota : (error handling)
- Masukkan Jumlah Restoran yang akan ditampilkan : conto... |
993,531 | 0d1b8e9a0de12372e36ae011b91ac19ca917763d | import re
import itertools
import numpy as np
#Python zip version
def count_doubles_zip(val):
total = 0
for c1, c2 in zip(val, val[1:]):
if c1 == c2:
total += 1
return total
#Python classic count
def count_doubles_classic(val):
total = 0
for i in range(len(val)-1):
if v... |
993,532 | 5dc2d487b6128e06ab9b58f79899014c8427b5ae | '''
Created on 12/12/2018
Modified on 26/02/2018
@author: Francesco Pugliese
'''
import pdb
class Postprocessing:
@staticmethod
def labels_to_eurosat_classes_converter(class_number):
if class_number == 0:
class_txt='Annual Crop'
elif class_number == 1:
... |
993,533 | 175c562a819b3fbee1727f3da1d012775992659d | /home/mi/besahre/Documents/Bachelorarbeit/Modelcar-111/catkin_ws_user/devel/.private/line_detection_fu/lib/python2.7/dist-packages/line_detection_fu/__init__.py |
993,534 | 84c930b962e2548d9a975609c250c17bc835d3d6 | # Generated by Django 2.0.3 on 2018-03-25 02:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='checkout',
fields=[
... |
993,535 | 151b22c171895f2b4c0700b57a174f9ee95337b3 | from .models import BookingDate, BookingWorkplace
from django.forms import ModelForm, DateInput, Select, DateField, IntegerField, Form, ChoiceField, SelectDateWidget
from .data import default_choices
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.widgets import NumberInput
from bootstrap_dat... |
993,536 | 224b7a21fce7b3cd1e13fbea019afb16a0774460 | #!/usr/bin/env python
# encoding: UTF-8
"""
This file is part of commix (@commixproject) tool.
Copyright (c) 2015 Anastasios Stasinopoulos (@ancst).
https://github.com/stasinopoulos/commix
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as... |
993,537 | b12dd5288ec5646d53f90aa519f58a5b6cd6844e | from image_processing.clustering import Cluster
import argparse
import glob
import cv2
import numpy as np
import csv
import pickle, pprint
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--features_db", required = True,
help = "Path to the directory that s... |
993,538 | ec33d43090b9cc6dd9507251c3a09bf6ec4e4ead | import requests
import responses
import string
import unittest
import mock
from drift import app, inventory_service_interface
from drift.exceptions import InventoryServiceError, SystemNotReturned
from . import fixtures
class InventoryServiceTests(unittest.TestCase):
def setUp(self):
test_connexion_app =... |
993,539 | b5bffcc2c828b26be96c1e0ec7d28596365cfc9b | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: andr.stankevich
#
# Created: 28.11.2018
# Copyright: (c) andr.stankevich 2018
# Licence: <your licence>
#------------------------------------------------------------------------
... |
993,540 | 2b411daa6ec21ffec907545c98c5b27d9bb268d2 | """
Code documentation for Microservice
.. include:: ./README.md
"""
from main import app
if __name__ == '__main__':
app.run(host=app.config['HOST'], port=app.config['PORT'])
|
993,541 | dbee7acdd8d7d4f46763565dd8d431a057f82258 | class Warehouse:
purpose = 'storage'
region = 'west'
w1 = Warehouse()
print(w1.purpose,w1.region)
w2 = Warehouse()
w2.region = 'east'
print(w2.purpose,w2.region)
|
993,542 | 3d329341d0bffff80c3a5bbc0acbe2b803fa6468 | # -*- coding: utf-8 -*-
# @Time : 2020/6/18 10:06
# @Author : skydm
# @Email : wzwei1636@163.com
# @File : high_train.py
# @Software: PyCharm
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
impor... |
993,543 | fced17102b89828cedad41abefb5c1d9639dd56a | # -*- coding: utf-8 -*-
"""
Name : c7_16_def_sharpe_ratio.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : Yuxing Yan
Date : 6/6/2017
email : yany@canisius.edu
paulyxy@hotmail.com
"""
def sharpeRatio(ticker,begdate=(2012,1,1),enddate=(2016,12,3... |
993,544 | 778f4ffd466f73ccdb38784c06f86e532ad9c32b | def find_small(lst):
small = lst[0]
small_index = 0
for i in range(1, len(lst)):
if lst[i] < small:
small = lst[i]
small_index = i
return small_index
def selection_sort(lst):
new_lst = []
for i in range(len(lst)):
small = find_small(lst)
new_lst.... |
993,545 | 21af862aa9985e6380a275630963c5d4342c1c55 | test_names = ['Quiz1', 'Quiz2', 'Midterm', 'Final']
test_grades = [100,70,86,95]
print('first item in list is', test_grades[0])
print('the list is', test_grades)
the_sum = 0
for the_grade in test_grades:
the_sum += the_grade
print('there are', len(test_grades), 'items in the list')
print(the_sum / len(test_gra... |
993,546 | 825229e6c2a1fed2e918496f2b91847373c55f09 | #!/usr/bin/python
# -*- coding: UTF-8 -*
import pandas as pd
import os
import numpy as np
def ELM(Efile_dir):
Enew_filename = Efile_dir + '/E_result.xlsx'
Efile_list = os.listdir(Efile_dir)
print("文件夹中有{}个文件".format(len(Efile_list)))
print('-'*100)
E_list=[]
E = 0
for file in Efi... |
993,547 | b49fab612a0426e310d27d2f68e786a26b8b55fc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @author: D. Roma
#
# 2014/10/29 First issue
# TODO:
# - Balls hang between them
# - Balls "hangs" on the wall
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from Balls import Balls
class Box():
'''
Contai... |
993,548 | 5b62bdbd20a4077833b8e4dfd0e3441c2e0a706b | $NetBSD$
Fix manual page directory.
--- setup.py.orig 2016-06-01 18:43:46.000000000 +0000
+++ setup.py
@@ -49,7 +49,7 @@ setup(name='Canto-curses',
library_dirs = ["/usr/local/lib", "/opt/local/lib"],
include_dirs = ["/usr/local/include", "/opt/local/include"])],
scripts=['bin/can... |
993,549 | ffca9b00f581fcb9a468c4ebc2283eae180d6249 | # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=Tru... |
993,550 | 79f0f740f67a4e2fa2bb1c26b90c440f84d8b6a0 | """
* view.common.uiobj.Style.py
*
* Copyright Synerty Pty Ltd 2013
*
* This software is proprietary, you are not free to copy
* or redistribute this code in any format.
*
* All rights to this software are reserved by
* Synerty Pty Ltd
*
"""
from twisted.web._flatten import flattenString
from twisted.w... |
993,551 | 89b06ee397b462664cde00143807a73c837b1db8 | def main():
N = int(input())
a = [0] + list(map(int, input().split()))
b = [0] * (N + 1)
for i in range(N,0,-1):
sum = 0
for j in range(2*i, N+1, i):
sum += b[j]
if sum % 2 != a[i] % 2:
b[i] = 1
ans = []
for i in range(1,N+1):
if b[... |
993,552 | 0a9dcddc815dee7d1e73c3c0fbd3969a3347ef71 | import argparse
# from fbchat.models import *
import logging
import os
import sys
import urllib.request
from getpass import getpass
from time import sleep
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from fbchat import Client
from API.InstagramAPI import I... |
993,553 | a5898d91c7889e9a0f2edb98e8ae3194d378cd0a | import re
from ePhone7.utils.spud_serial import SpudSerial
from ePhone7.config.configure import cfg
import spur
from lib.user_exception import UserException as Ux
from lib.wrappers import Trace
import lib.logging_esi as logging
from pyand import ADB, Fastboot
from os import path, listdir, mkdir
import shutil
log = log... |
993,554 | 973f272413cd877b49e1440082c61c47dcb360a4 |
STANDARD = 'abcdefghijklmnopqrstuvwxyz'
DP_memo = {}
def is_alphabetical_order(S):
a_pos = ord(S[0])
for ch in S:
if S != ch(a_pos):
return False
a_pos += 1
return True
def is_alphabet(S):
if S == STANDARD:
return True
return False
def DP(S):
'''
Sub... |
993,555 | 2f66d6c6696934b7dafbe0a691c0c1cf6c07f025 | import nltk
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
import string
import json
lemmatizer = WordNetLemmatizer()
class InvertedIndex:
documents = []
index = {}
process_content = ""
custom_separator = "111111111111111111... |
993,556 | c5e87c581d030c8aaa904ae4ed5c11b99863fca5 | from collections import namedtuple
from intervaltree import Interval
from rdflib import URIRef
EntityMention = namedtuple('EntityMention', ['start_char', 'end_char', 'uri'])
class RelRecord:
def __init__(self, relation, s0: int, s1: int, o0: int, o1: int,
ctext, cstart=0, cend=None, source_id=... |
993,557 | 76492508248f5e3e9e63df1d6892da62d1b405d0 | from django.views.generic import CreateView
from contact.forms import EmailForm
class HomeView(CreateView):
template_name = 'vitali/index.html'
form_class = EmailForm
success_url = '/contact/thanks/'
|
993,558 | 2b329aa4cc5611cdab25356a6fdecc91af0bcd99 | import os
# todo: remove debugging feature. Just use the built in debugging tools.
class Settings:
def __init__(self, debug=False):
self.valid_settings = ['DEBUG', 'INLINE_GRAPHS', 'LIN_SORTING_METHOD',
'NL_FITTING_METHOD', 'NL_SORTING_METHOD',
... |
993,559 | cd27a3ffbdb8538b7f2f7bed70ff913b5b7d14e4 | import cv2 as cv
import numpy as np
def skeletonize(image):
goal_point = [300, 500]
img = image
wh_pixels_up = []
wh_pixels_left = []
wh_pixels_right = []
thresh_erode = img.copy()
skel = np.zeros(img.shape, np.uint8)
element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3... |
993,560 | f31b44640ee418566c9de77451293063ffb08abf | """
Program 7
Write a program which takes 2 digits (X and Y) as input and generate a 2-dimensional array
The element value in the i-th row and j-th column of the array should be i*j.
The program should print the 2-dimensional array as output with X number of rows and Y number of columns
"""
#console input
input_str =... |
993,561 | e6480f7e21b7f592a20f32d0c371af81f3e674c1 | from utils import Utils
from vector import Vector
'''
Class responsible for point with 3 coordinates
'''
class Point3D:
'''
Init of Point3D class
@param x coordinate x of point
@param y coordinate y of point
@param z coordinate z of point
'''
def __init__(self, x, y, z):
self.point ... |
993,562 | 7e2632615656ceeef203a266f7c0e9c4ca4521cf | import torch
from torchvision import transforms # 数据预处理
from torchvision import datasets # 数据集获取
from torch.utils.data import DataLoader
# 针对MNIST图像数据集的预处理,不用深究
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, ))])
# 分别读取训练集、测试集
train_dataset ... |
993,563 | 042b18cb58b839d2de5a205ad8af980b96bc2726 | import turtle
wn=turtle.Screen()
owen=turtle.Turtle()
pendown()
def make_squares(turt,size,num):
for i in range(4):
turt.forward(size)
turt.left(90)
turt.left(90)
turt.penup()
turt.forward(2*size)
make_square(owen,20) |
993,564 | f1a88fc8809befa62284dd955baa35fe60bb4ce5 | '''
A script for searching through various possibilities with uncertainty model online learning, assuming
that we are modeling the uncertainty of the action model.
'''
import sys
sys.path.append('curiosity')
sys.path.append('tfutils')
import tensorflow as tf
from curiosity.interaction import train, environment, d... |
993,565 | 4e9fd5cde2e8b050e8a723f9a32e0b8ff0089042 | """
Create console program for proving Goldbach's conjecture.
Program accepts number for input and print result.
For pressing 'q' program successfully close.
Use function from Task 5.5 for validating input,
handle all exceptions and print user friendly output.
"""
from Session_7.Task_7_5 import check_number
def get_... |
993,566 | 34960b3047b9bf5f267b92ee3d82a3d8dc3d3753 | # No one writes a perffect programme
# The act of finding and removing bugs from code is called recommendation
# How to debug properly
# 1. use linting -> linting allows us to fing errors before running our code
# 2. use an ide or editor
# 3. learn to read errors
# 4. pdb -> python debugger -> favourite debugger (pdb... |
993,567 | 44d9775a5c94c59ba1ee4b062bd8b13f61c764a7 | from django.contrib import admin
from .models import Category,Doctor
# Register your models here
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class DoctorAdmin(admin.ModelAdmin):
list_displ... |
993,568 | 383c1cd76bdaa60b98fc5e9aef6cc002cbb36c32 | {
'extra_keys': (),
'file_ext': '.fits',
'filetype': 'dark',
'ld_tpn': 'acs_drk_ld.tpn',
'parkey': ('DETECTOR', 'CCDAMP', 'CCDGAIN'),
'parkey_relevance': {'ccdgain': '(DETECTOR != "SBC")', 'ccdamp': '(DETECTOR != "SBC")'},
'reffile_format': 'image',
'reffile_required': 'yes',
'reffil... |
993,569 | 025ee8681c6996f0bbf402cc17daba06d511ad2f | /Users/pmlee/anaconda3/lib/python3.6/shutil.py |
993,570 | 845e58d763118ae39f7d8bf37522c0655278f0c4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Will install necessary dependancies, set up folders and download databases
# necessay to use the pipeline.
#
# Should be run using:
#
# python setup.py ( install | update | updatedb )
#
import os
import sys
import shutil
import stat
import subprocess
def main():
... |
993,571 | 555fa2a3ff410bbf67f750d1b8f61f3b7145a71d | # Array to hold all error objects used to test code
import datetime
class Error:
def __init__(self, contract_type, date, error_code):
self.contractType = contract_type
self.date = date
self.errorCode = error_code
def get_contract_type(self):
return self.contractType
def g... |
993,572 | 198bf6639f423d30211d4f90bf336c5e28d7d46f | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 04 13:52:07 2018
@author: whuang67
"""
###### Bubble Sort ########################
def bubble_sort(arr):
for i in range(len(arr)-1, 0, -1):
for j in range(i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] ... |
993,573 | e3c858e6806156560592d6cf7ad84af932c79d91 | """
Read hippocampal subfield volumes computed by Freesurfer and/or ASHS
https://sites.google.com/site/hipposubfields/home
https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfields
>>> from freesurfer_volume_reader import ashs, freesurfer
>>>
>>> for volume_file in itertools.chain(
>>> ashs.HippocampalSu... |
993,574 | 2d9c0ddf86ca793636fe91b2d31fa6726f890f74 | #!/usr/bin/env python
# test is one way to improve quality.
# Perform operation test with small function unit.
# It is better to join parts that passed test.
# assert can be used to determine bool value.
assert(True)
#assert(False)
# error occurs if argument of assert function is false. follow it.
# AssertionError... |
993,575 | fa43b422dbae615498fe8f6331a3937191013459 | #温度转换
'''
(1) 输入输出的摄氏度采用大写字母C开头,温度可以是整数或小数,如:C12.34指摄氏度12.34度;
(2) 输入输出的华氏度采用大写字母F开头,温度可以是整数或小数,如:F87.65指华氏度87.65度;
(3) 不考虑异常输... |
993,576 | de1994db2d0f9c63e2ad8b642dbc02f3b4be7ab4 | #!/usr/local/bin/python3
# -*- coding:utf-8 -*-
"""
@author:
@file: 1389.py
@time: 2020/4/30 10:07
@desc:
"""
class Solution(object):
def createTargetArray(self, nums, index):
"""
:type nums: List[int]
:type index: List[int]
:rtype: List[int]
"""
target = []
... |
993,577 | bf3741ee6392603f19fff22886122826ce371f3f | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-23 02:05
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL... |
993,578 | 8dcbb99020cadb6e6fbdff3a7a7007b0dad61ca9 | from alignChannels import alignChannels
import numpy as np
from PIL import Image
# Problem 1: Image Alignment
# 1. Load images (all 3 channels)
red = np.load('red.npy')
green = np.load('green.npy')
blue = np.load('blue.npy')
def ncc(array1,array2): #NCC based alignment
flat_arr1 = array1.flatten()
fla... |
993,579 | cf6eaad8b31dc7ec3b4213568efa629b44176c97 | # Operator Overloading in Python ...!
# Behind the seen in Python
# print(f"Addition : {10+20}")
# # --or--
# print(f"Addition : {int.__add__(10, 20)}")
#
# print(f"Result : {'Santanu' + ' Banik'}")
# # --or--
# print(f"Result : {str.__add__('Santanu', ' Banik')}")
class OverloadOperator:
def __init__... |
993,580 | 045a474868c5fa81e47f503ca445706a364a2b99 | import logging
import os
import re
import yaml
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEn... |
993,581 | becc961e03b9ac78178e8dab8f61075f1e99f8a0 | first_employee = int(input())
second_employee = int(input())
third_employee = int(input())
people = int(input())
total_per_employee = first_employee + second_employee + third_employee
hours = 0
while people > 0:
people -= total_per_employee
hours += 1
if hours % 4 == 0:
hours += 1
... |
993,582 | 49a39518ddf2725882de584368f2ae0be357ea09 | from django.contrib import admin
from .models import Soft, Category
admin.site.register(Soft)
admin.site.register(Category)
|
993,583 | cdc23d86ae907d52c34461233fd0cbea4d7adecb | # -*- coding: utf-8 -*-
# Copyright (C) 1994-2019 Altair Engineering, Inc.
# For more information, contact Altair at www.altair.com.
#
# Commercial License Information:
#
# For a copy of the commercial license terms and conditions,
# go to: (http://www.pbspro.com/UserArea/agreement.html)
# or contact the Altair Legal ... |
993,584 | 231e787830b51f72e8c613fa48d85f3c95f653a4 | from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^dashboard/client/', views.client_home, name='client_home'),
url(r'^dashboard/worker/(?P<pk>[0-9]+)$',views.service_expand,name='service_expand'),
url(r'^dashboard/worker/profile/', views.update_worker, name='updat... |
993,585 | eadacb2885e02086ffce686c64719102439418f9 | valor = float(input('Digite o valor do produto desejado: '))
desconto = valor - (valor * (5 / 100))
print('O produto com desconto saiu de R${:.2f} por R${:.2f}.'.format(valor, desconto))
|
993,586 | 655a4b74a3ac446b4d086d42d26be2d3050be7a0 | # Validation of type annotations
import re
from typing import Match
def GetEmailMatch(email) -> Match:
return re.match(r'([^@]+)@example\.com', email)
|
993,587 | 7548f5f7aa1d1ba3f4ae63358236b611ae6363dc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : yinhuaxi@geotmt.com
# @Time : 2020/1/7 14:22
# @File : __init__.py.py
|
993,588 | 49000cb0aaf831008ab6330b5ff045d43760411a | import requests
URL = 'https://gen-net.herokuapp.com/api/users/{}'
name = input('Digite Nome: ')
response = requests.get(URL.format(name))
print(response.json())
|
993,589 | 5f81a0ffa36ef2ba60bc2bb369ae79454d36f8e5 | import csv
with open('one.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='\t')
writer.writerow(['S.No', 'Name', 'Mark']) # Write a single row, single list
rows = [[1, 'A', 2], [2, 'B', 3]]
writer.writerows(rows) # writerows - requires a nested list as in var row
with open('one.... |
993,590 | 56309534101618ab143e1bf5b67b85f7ddbc1e11 | from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from tensorflow.keras.models import *
def init_generators(train_data_dir, validation_data_dir, img_width, img_height, batch_size_train, batch_size_val):
train_datagen = ImageDataGenerator(
rescale=1. / 255,... |
993,591 | 0dde5ab567d8f55ca868c9b3fe3dd81c5e961591 | """Post views."""
#Django
from django.shortcuts import render
# Utilities
from datetime import datetime
posts =[
{
'title': 'Mont Blanc',
'user': {
'name':'Yésica Cortés',
'picture': 'https://picsum.photos/60/60/?image=1027',
},
... |
993,592 | 607bedbda9ff4333f93798acbcd736421bfc7d29 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ReST actions handlers."""
# System imports
import sys
import abc
import logging
import datetime
import importlib
from django.db import models
from django.conf import settings
from django.utils.timezone import utc
from django.db.models.query import QuerySet
from django.u... |
993,593 | b14c2b98a07fad5acc877d946f624a0191ab7c48 | from typing import Optional
from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from ..models import dbc, User, Chat
class AclMiddleware(BaseMiddleware):
async def setup_chat(self, data: dict, tg_user: types.User, tg_chat: Optional[types.Chat] = None):
user_id = tg_user.i... |
993,594 | 453c590063d3a417b02f59c307b059e41ccb0e23 | import socket
import sys
import pickle
from time import sleep
from queue import Queue
from _thread import *
import threading
from threading import Thread
sys.path.append('.\\LinearTopology')
import GLOBALS
import classes
import utility
response = [[]]
num = 0
def addMessage():
"""Initializes the Reponse list to ma... |
993,595 | 756ef23ad9664cec94fe3b80aab66f7e6fca77a4 | from rest_framework import generics
from addons.models import AddOn
from .serializers import AddOnSerializer
from rest_framework.permissions import AllowAny
class AddonsAPIView(generics.ListCreateAPIView):
permission_classes = [AllowAny]
serializer_class = AddOnSerializer
queryset = ... |
993,596 | 15cbbe9e8c232b5b545207a9ccc606ed727e63d5 | import requests
import json, os
url = "{0}:{1}".format(os.environ['HOSTNAME'] , "8989")
resp = requests.post('http://' + url + '/api/v1/type/service/botbuilder/',
json={
"cb_id" : "cb0001",
"chat_cate" : "EP",
"chat_sub_cate" ... |
993,597 | 289af8ae66f0734d44845e8cd84e1d36867428b8 | ii = [('MartHSI2.py', 1), ('WadeJEB.py', 1), ('NewmJLP.py', 1), ('KirbWPW2.py', 1), ('BachARE.py', 2), ('MartHRW.py', 1), ('BabbCRD.py', 2), ('WilbRLW3.py', 1), ('MartHRW2.py', 1), ('ChalTPW.py', 1), ('KeigTSS.py', 1), ('WaylFEP.py', 3), ('BentJDO.py', 1)] |
993,598 | f1625fcd4ede43241c44d4e4d6295b958e7111c5 | import sqlite3
import os
#
# class Blob:
# """Automatically encode a binary string."""
# def __init__(self, s):
# self.s = s
#
# def _quote(self):
# return "'%s'" % sqlite3.encode(self.s)
path = '/home/ju/JetBrainsProjects/PycharmProjects/hilar/hilar/src/data/beige2_hat.jpeg'
with open(path... |
993,599 | 4bb3e02374cd196187adcc4a7976c44cb7bdb5ed | a=3
b=4
c=1000000007
d=(3*3*3*3)%c
print d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.