index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
991,600
90b9f8b66f4db0cf33a72ef92a874263dbf744a5
from django.db import models from django.conf import settings class Image(models.Model): """ Image model, really just a default, a more reasonable one would create some thumbnails based on the need of the site. """ title = models.CharField(max_length=255, blank=True, null=True) image = models....
991,601
440c1101a229df90fc661ac4e59b7018152fca52
import tensorflow as tf import matplotlib.pyplot as plt import pandas as pd import numpy as np # 加载数据,将数据拆分为:训练数据、测试数据 (train_image, train_label), (test_image, test_label) = tf.keras.datasets.fashion_mnist.load_data() print(train_image.shape) # 打印训练数据维度 print(train_label.shape) # 打印标签的信息 print(train_image[0]) #...
991,602
2e8bdf4e2468eba083a2fe8c292ae04d2d69b411
l=[] sonuc=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] a=int(input("şifre giriniz:")) i=1 while(i==1): kalan=(a%36) l.append(kalan) bolum=int(a/36) if (bolum>=36): i=1 a=bolum ...
991,603
a043710528a2169c7a05436639a85026e1dc99f6
import uvicorn if __name__ == "__main__": uvicorn.run( "src:app", host="0.0.0.0", port=5000, log_level="info", debug=True, reload=True )
991,604
dcd02e0862a42a3b8bd09199064c1bee80308ebd
import threading import tornado.ioloop import tornado.web from tornado.httpserver import HTTPServer import time import logging from handler import WsRPCHandler from auth import authenticator import tornado.options from tornado.log import enable_pretty_logging enable_pretty_logging() logging.getLogger().setLevel(logging...
991,605
f929b3059e009fd60347a8545d117f63af4b6eaa
n1,n2=map(int,input().split()) sum=0 sum=n1+n2 #print result print(sum)
991,606
291411679f4a7f83e017945e30d70d37c9c289ec
from __future__ import print_function import json from os.path import isfile, join from os import makedirs import argparse from node2vec import Node2Vec import time import shutil class Entity2Vec(Node2Vec): """Generates a set of property-specific entity embeddings from a Knowledge Graph""" def __init__(self...
991,607
81f897ea2a38caa81d178d43a1795dca7d495b96
# Generated by Django 3.2 on 2021-07-30 03:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('menteerequest', '0013_mentee_request_finish_check'), ] operations = [ migrations.AddField( model_name='mname', name='p...
991,608
a45a0f276014a24e5374c2a233395bb12edf08dd
import cv2 # Remember to rotate your camera cap = cv2.VideoCapture(0) while cap.isOpened(): isSuccess, frame = cap.read() rotated = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) cv2.imshow('My webcam stream', rotated) # Press 'Esc' to quit if cv2.waitKey(1) == 27: break cap.release()...
991,609
2c41c2e4e8fc3c0ab42341ec89d52f94d1793976
import io num_tests = 0 failed_tests = 0 def equal(expr, expected): global num_tests global failed_tests num_tests += 1 if(expr == expected): print("Test Passed with result: '", expr, "'", sep = '') else: failed_tests += 1 print("Failed!\n expected: '", expected, "'\n bu...
991,610
9c8dd33cd8b40af67e19b3233d0af30cb2042f2a
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import sklearn.preprocessing as skp import sklearn.feature_extraction as skf import scipy.sparse as ss import sklearn.model_selection as sms import sklearn.linear_model as slm import tqdm import sklearn.neighbors as skn import sklearn.ensemble as se impor...
991,611
2fdaca50777f273534a00375b9f4a5c92c353c27
#!/usr/bin/env python2 from pwn import * ''' bugs: if you have a charizard, you can set the charizards artwork so that bird_attack_name points to a mem location and it will leak that memlocation by switching to the charizard in a fight when catching a pokemon when you are full, it does not set the poke_type correctl...
991,612
0d5a045ce2a48b6600496115ae582318c6986de2
a=int(input("enter the number")) temp=a a1=str(a) b=len(a1) print(b) sum=0 while temp!=0: digit = temp % 10 q=temp//10 temp=q sum += digit ** b if a == sum: print(a,"is an Armstrong number") else: print(a,"is not an Armstrong number")
991,613
45a40fc7bc07506365ba475d797c78585484306f
class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 0: return 0 memo = [0 for x in range(len(nums))] memo[0] = nums[0] for i in range(1, len(nums)): memo[i] = max(memo[i-1], memo[i-2] + nums[i]) return memo[-1]
991,614
7e6bde91bcddf98329ea24906f5cad1eba53a973
from random import randint class Board: """ a datatype representing a C4 board with an arbitrary number of rows and cols """ def __init__( self, width, height ): """ the constructor for objects of type Board """ self.width = width self.height = height W = self.widt...
991,615
1b33580bdf91373cb33e760928618b529bccbf19
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 25 00:21:12 2018 @author: Kazuki """ import pandas as pd imp_2 = pd.read_csv('/Users/Kazuki/Downloads/imp_801_imp_lgb_onlyMe.py-2 (2) 0.08.51.csv') imp_2['split'] /= imp_2['split'].max() imp_2['gain'] /= imp_2['gain'].max() imp_2['total'] = imp_2[...
991,616
f19653a5fc1ecf6d5c3b258efd6fc1ce3ea885e6
#!/usr/bin/python3 import sys import re # AB BA CD BA # CD DC AB DC # CA AC DB BD # DB BD CA AC # Each pattern has 8 patterns # Rotate 90° or not, flip X or not, flip Y or not # 2³=8 class Tile: def _parse_line(line): return int(line.replace('.', '0').replace('#', '1'), 2) def __init__...
991,617
a5dbde761cfc4763634c73997043fd9cc9085468
import numpy as np def score(a,b): if a == b : return 1 else : return -1 seq1 = "ATTACA" seq2 = "ATGCT" matrix = np.zeros((len(seq2)+1,len(seq1)+1)) gap = -1 for i in range(len(seq2)+1) : matrix[i][0] = gap * i for i in range(len(seq1)+1) : matrix[0][i] = gap * i for i in range(1,len(seq2)+1): for j in ra...
991,618
8a5f41e1f7a7da5a9202cbf2e99b571c9c099e6f
import cv2 import argparse import numpy as np capt = cv2.VideoCapture('test.mp4') frame_width = int(capt.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height =int(capt.get(cv2.CAP_PROP_FRAME_HEIGHT)) #Parte do código para o background subtraction parser = argparse.ArgumentParser(description='Movement Detector.') parser.add_a...
991,619
50005677fd04d15701563a69a9d29b5b1074d466
# -*- coding: utf-8 -*- """ ORIGINAL PROGRAM SOURCE CODE: 1: from __future__ import division, print_function, absolute_import 2: 3: import numpy as np 4: from numpy.testing import assert_array_almost_equal, assert_ 5: from scipy.sparse import csr_matrix 6: 7: 8: def _check_csr_rowslice(i, sl, X, Xcsr): 9: np_s...
991,620
e404554d5315ce4322bc76de7ccccb1b6bdd163f
class Test(): def __init__(self): self.x=[1,2,3] a=Test() b=Test() a.x.append([1,2,3]) print(a.x,b.x) c=list() d=list() c.append([1,2,3])
991,621
80fe0d4dd09b9d7179eb913d793fc9a4fcdd1c29
import json import requests import datetime from django import template from apps.accounts.models import User from apps.coins.utils import * from apps.coins.models import Coin, NewCoin, EthereumTokenWallet register = template.Library() @register.simple_tag def get_balance_BTC(user): balance = get_balance(user, "...
991,622
59209b06ca4f6ecd6e5c8668607b2134e7b82078
class Bunker: def __init__(self): self.survivors = [] self.supplies = [] self.medicine = [] @property def food(self): foods = [supply for supply in self.supplies if supply.__class__.__name__ == "FoodSupply"] if not foods: raise IndexError("There are no fo...
991,623
99454b0b3f4094356b3584b5d0e6f6a7e6c94539
from authentification.queries import verify_password from product.models import Product from django.shortcuts import render, redirect from authentification.views import verify_login from product.queries import retrieve_info, add_product, delete # Create your views here. @verify_login def update_products(request, id): ...
991,624
ac5f7ed805cc41ddfa4e627d24bdebfc1f1ec604
# -*- coding: utf-8 -*- from platinumegg.app.cabaret.util.cabareterror import CabaretError from platinumegg.app.cabaret.util.api import BackendApi import settings from platinumegg.app.cabaret.util.url_maker import UrlMaker from platinumegg.app.cabaret.models.Player import PlayerScout, PlayerAp,\ PlayerExp, PlayerRe...
991,625
4b6df09e6c7f37734dbd2c71e13cb35a8d47ee4a
print("enter num") num = int(input()) var=0 def fun(num): var = 0 while num !=0: num=num // 10 var = var+1 return var print(fun(num))
991,626
21d7d1197b99a3747b2057e11b4f53a94b397dbc
# Przekopiuj zawartość import this do zmiennej. a = """The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't s...
991,627
bf48143548db120c645772df2e2f998ed210076c
# https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/ class Solution(object): def findSolution(self, customfunction, z): seen = set() res = [] def g(x, y): if (x, y) not in seen: seen.add((x, y)) v = customfunction.f(x, y) if v == z: res.append([x, y]) elif...
991,628
ac29ffc3b933c6bd2090cea6dbf6ba0ccb8ad54f
#doCalc() # APDataArray[ # AP[ # <Latitude(+- deg)> # <Longitude(+- deg)> # <Altitude(ft)> # <DistanceToAP(ratio)> # ] # ... (4x...
991,629
ee14b4e528f7ca848ca45be3e3eeedc62b2c79ba
frequency_colors = {'01': '#77C000', '06': '#ee188d', '10': '#03aa87', '19': '#f46817', '37': "#7b7bc6", '89': '#ee188d'}
991,630
358af60f9a9e5ff455bb4464ef1a6fb3db87e566
# Loads Cifar10. and fits a simple cnn. Uses a custom_loss # Custom loss has been DIY softmax loss (cross entropy) so can verify with original import numpy as np # import matplotlib.pyplot as plt # import tensorflow as tf import keras from keras import backend as K import code import time import cv2 import math # impo...
991,631
0c6382d308a89bf74d114ba8ef73e9cd429162e1
from Comentario import Comentario import unicodedata import json #DEFINIMOS LA CLASE JUEGO class Juego: #CONSTRUCTOR DE JUEGO def __init__ (self,id,nombre,anio,precio,categoria1,categoria2,categoria3,foto,banner,descripcion): self.id = id self.nombre = nombre self.anio = anio se...
991,632
712c89b34ac831954498a5e71f1ec68a50b5379c
from openmdao.api import ExplicitComponent import numpy as np from input_params import max_n_turbines class AbstractThrustCoefficient(ExplicitComponent): def __init__(self, number, n_cases): super(AbstractThrustCoefficient, self).__init__() self.number = number self.n_cases = n_cases ...
991,633
f72c14c25f6f7954663b449b2af74ca3216ec458
[{"id":76,"name":"Анна-Мария Ангелова","description":"<p>Анна-Мария Ангелова е завършила Американския университет в България, където именно се&nbsp;запалва искрата към анализирането на данните и предприемачеството. През последните 5 г. тя&nbsp;взима участие в няколко проекта за иновации в Исландия и Дания, работи за ед...
991,634
d6425a409c07102385c877a20b4e71caa075fe7a
# 2020 카카오 인턴십2 수식 최대화 # https://programmers.co.kr/learn/courses/30/lessons/67257 from itertools import permutations def solution(expression): op_list = ['+', '-', '*'] op = [] operand = expression.replace('+', ' ').replace('-', ' ').replace('*', ' ').split() answer = [] for i in expression: ...
991,635
c4eaa8f0d3324ccd1baee1add89950fba4c986b6
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright [2017] Tatarnikov Viktor [viktor@tatarnikov.org] # # 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/licen...
991,636
e1469a384d153ac65b5f538517abf858cc05107c
# -* encoding: utf-8 *- from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.backends import RemoteUserBackend class ProxyRemoteUserMiddleware(RemoteUserMiddleware): """ This authenticates the remote user against the commonly used HTTP_REMOTE_USER meta field s...
991,637
164f1d5c27c651cde250962f55591714e92c2b83
# # Test script just to make sure if works! # # Edited by C. Do on 2014-2-13 import eqsansscript_class_2015Brev1 reload(eqsansscript_class_2015Brev1) from eqsansscript_class_2015Brev1 import * {{title}} {{ipts}} {{ configuration.absolute_scale_factor }} {% for entry in entries %} {{ entry.background_scatterin...
991,638
333f13c22ed7813b8badee0f1095d79d3d1640ab
def print_hm(h): r = len(h) c = len(h[0]) for i in range(1, r): for j in range(1, c): print(h[i][j], end='\t') print() class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ # ...
991,639
fc384a60dcf113b091e4f1a7b5608594381fd1ef
#Example file to show how to generate mesh with pydistmesh and write it to a file type compatible with fenics #Alex Martinez-Marchese # Python imports import numpy as np import matplotlib.pyplot as plt # Local imports import dolfin as df import distmesh as dm #Cone measurements rad = 0.01 vfr = 0.004 #Functions de...
991,640
a8fe5081c171ab3e94e3ee6a5dcacad082ef9ed9
from django.apps import AppConfig class CostoadminConfig(AppConfig): name = 'costoadmin'
991,641
840901148676ef625045c94c96190243fc48a2da
import roboclaw, time, math i = 10 flag = True while i != -10: print(i) roboclaw.M2Forward(128,int(round(i/math.sqrt(3.0)))) roboclaw.M1Forward(128,int(round(i/math.sqrt(3.0)))) roboclaw.M1Backward(129,i) i = i + 10 if flag else i - 10 if i > 120: i = 120 flag = False time.sleep(0.05)
991,642
cce4c572881a0fc0c3e6e883921214e5f753eaed
# -*- coding: utf-8 -*- # Simple Python Search Engine built on Redis # https://github.com/ebaum/searchpyre __author__ = 'Eugene Baumstein' __license__ = 'MIT' __version__ = '0.1' import re import os import math import time import datetime import collections import unicodedata from redis import StrictRedis from itert...
991,643
75a4ca0c9e55c364889d5917dd7d6d040d74cd95
# http://blog.yhathq.com/posts/logistic-regression-and-python.html import pandas as pd import statsmodels.api as sm import pylab as pl import numpy as np def cartesian(arrays, out=None): """ Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like ...
991,644
cde85c40185b0c9aab24df850199076d549fda26
import socket import argparse from resources import TCPing, Statistics, Visualiser, SocketAPI, Timer import sys import signal def parse_args(): arg_parser = argparse.ArgumentParser(description='TCPing console app') arg_parser.add_argument('dest_ip', metavar='dest_ip', type=check_ip, ...
991,645
f5950fead522dcddb56d07b9dfbb8693a090f6bc
""" Implement stack """ class Stack(object): """stack class""" def __init__(self, arg): super(Stack, self).__init__() self.arg = arg def size(self): self.ob
991,646
056c2716a2e4bee85c6f9d50f3e3e33ec2f294f7
r''' __ _ _ _ / _(_) | ___ (_) ___ | |_| | |/ _ \ | |/ _ \ | _| | | __/ | | (_) | |_| |_|_|\___| |_|\___/ ''' ##============================================================================= ## Generally ##=================================================================...
991,647
b1d1ab238bc67bf799999d59513e1a4db11a8506
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import autotools, shelltools, get shelltools.export('HAVE_VALGRIND_TRUE', '#') shelltools.export('HAVE_VALGRIND_FALSE', '') def setup():...
991,648
f4e16668662d49b0ea12a76040d1a5d16fc260ea
#!/usr/bin/env python # # Copyright 2016 Google Inc. 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/LICENSE-2.0 # # Unl...
991,649
c46efbb689e3a27b87c7f1fc47b94b997795150d
def answer(n): count = 0 n = int(n) while n != 1: if n&1 == 0 or n == 4: n = n >> 1 elif ((n-1)>>1)&1 == 0 or n == 3: n -= 1 else: n += 1 count += 1 return count if __name__ == "__main__": print answer("4") == 2 print answer(...
991,650
98bdff59e1425ed2654ef42b918ef417f43d1c81
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-30 08:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comment', '0001_initial'), ] operations = [ migrations.AlterField( ...
991,651
f1afbb2977e4eb21105ab41f75f1f65b5272286b
#! /usr/bin/python from dircache import listdir from re import compile,match from optparse import OptionParser from time import mktime,localtime import sys xmlpattern = compile("^.*\.xml") extractpattern = compile("^.*\+(.*)\+s(.*),_(.*),_(.*),_(.*),_(.*),_(.*),_(.*),_(.*),_(.*)e.*") intpattern = compile("^(.*)\..*...
991,652
3b3df1d27bd921366747dc6bbc888c5a79951e1e
import logging from cmreslogging.handlers import CMRESHandler handler = CMRESHandler(hosts=[{'host': 'localhost', 'port': 9200}], auth_type=CMRESHandler.AuthType.NO_AUTH, es_index_name="my_python_index") logging.basicConfig(filename='app.log', filemode='w', format='...
991,653
c36c34fe39bcc8ba58dadac6231e1387ca0c4ec7
import clr; from System import Array, String from System.ComponentModel import TypeConverter, StringConverter # Connection settings class Connection(object) : DisplayName = 'connection' Category = 'Connection' Description = 'Serial number of the main phone.' DefaultValue = '' ReadOnlyF...
991,654
5cb3a2df2693ea4d511b5d3dd38600def11d8249
# -*- coding: utf-8 -* # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any ...
991,655
7a0e8619e858492e5c985a1b5b0a982a56e0b62c
Sighv={ 'IGHV3OR15':(238-537), # Scaffold1099214757507 'IGHV3-23':(797-1845), # Scaffold1099214148171 'IGHV3-72':(700393-701553), # Scaffold1099548049584 'IGHV3-7': (654699-654992), # Scaffold1099548049584 'IGHV3-49':(187218-187895) # Scaffold1099548049584 } #Chr10: Lambda Siglv={ ...
991,656
1049df00d76d7bd45efbfc8f1f66b897caadb18b
from django import forms class per_day_form(forms.Form): #sets different field for per_day_form amount = forms.IntegerField(max_value=200, min_value=0) due_date_month = forms.ChoiceField(choices=[(x, x) for x in range(1, 13)], label='Due Date') due_date_day = forms.ChoiceField(choices=[(x, x) for x in ...
991,657
ab8938a13104cc34194bd50fb5ff1ec012ee2f79
import numpy as np from PIL import Image, ImageOps, ImageDraw __all__ = ['convert_bboxes_to_float', 'convert_bboxes_to_int', 'bboxes_filter_center', 'crop_bboxes', 'resize_bboxes', 'pad_image', 'crop_image', 'draw_boxes', ...
991,658
3bf21cb27874d498085048fbf33b3d3125522ecd
from math import pi E = 10e9 # Pa I = 1.25e-5 # m**4 L = 3 # m # n = 1,2,3,... def column_eigenvalue(n): return n*pi/L # n = 1,2,3,... def buckling_load(n): return n**2 * pi**2 * E * I / L**2 for n in range(1,9): print("%d %11.4f %11.3f" % (n, column_eigenvalue(n), buckling_load(n)/1e3))
991,659
63c9b8e09abe223dba258cc0e6e4c6a48af100ac
from django.shortcuts import render import datetime import hashlib import json from django.http import JsonResponse class Blockchain: def __init__(self): self.chain = [] self.create_block(nonce = 1, previous_hash = '0') def create_block(self, nonce, previous_hash): block = {'index': l...
991,660
7a8b784a807bc977d3ca2876d7d98ec3fae37c66
"""gamershub URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
991,661
e37854f3f063424968bf1671501101272df954e0
# Done by Carlos Amaral (2021/01/02) import random def guess(x): random_number = random.randint(1, x) guess = 0 while guess != random_number: print('Press 12 to quit at any time') guess = int(input(f'Please, guess a number between 1 and {x}: ')) if guess == 12: break ...
991,662
e7016e0c3f8320b590f2c112b034508c8044f4fb
#!/usr/bin/python3 """ script that lists all states from the database hbtn_0e_0_usa """ import MySQLdb import sys if __name__ == '__main__': miConexion = MySQLdb.connect(host='localhost', user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) cur = miConexion.cursor() cur.e...
991,663
7ff44d3e91b665f636aec6ff96bd0d236340d20a
from django.db import models import re from django.utils.timezone import now # Create your models here. class UserManager(models.Manager): def basic_validation(self, postData): errors = {} EMAIL_REGEX = re.compile( r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if len(postD...
991,664
f8bf4a10fee73e7dadd79b324bf870569561158a
def f(s): if s == "": return [""] result = [] for p in f(s[1:]): for i in range(len(p) + 1): # p_i = s[0] + p[i:] # p_i = p[:i-1] + s[i] + p[i+1:] # p_i = p[:i] + s[0] + p[i:] p_i = p[:i] + s[0] result.append(p_i) return result...
991,665
7591cf50848822ad59098d06da02d2cd7a6a2bcd
a, b = map(int, input().split()) ans = "Yay!" if a <= 8 and b <= 8 else ":(" print(ans)
991,666
acbebf2546d62ad55423bef0845a6223e1bd7ea8
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: playback.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protob...
991,667
9c4e7499b77346b6248df0779c79fe38e8863dd9
from brownie import accounts, ForceTransfer, chain, web3 import brownie import pytest def main(): address_empty_contract = '0xEC60d52feBcB327d7a3887920Abe8175986715e7' caller = accounts.load('accountDeploy01') force_transfer = caller.deploy( ForceTransfer, address_empty_contract, p...
991,668
596a2a3834dc9983f71e436e150caf898d266768
import Image import ImageDraw import ImageFont def draw_object(position, sequence): counter = 0 for j in range(20): for i in range(4 - j % 2): if j % 2 == 1: translate = SIZE / 2 else: translate = 0 draw.ellipse((SIZE * i + translate + position[0],SIZE * j + position[1],SIZE * (i + 1) + transla...
991,669
0c5c18e3e92843f729103d880bbf967ebab5ee4d
''' Agenda: 1.)Print how many links present in a page 2.)Print all link in console using loop(Extract all link) 3.)Clicking on the link ''' from selenium import webdriver from selenium.webdriver.common.by import By driver=webdriver.Chrome(executable_path='C:\\Users\\Dell\\PycharmProjects\\selenium\\drivers\\chrome...
991,670
5a75f674fa7972ff3cadc7731a2f45db8fbb2227
from typing import * # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: def getIntersect(head): slow = head fast = head while...
991,671
7133aabfd2787ec66aa09f4500f8677f1595752d
import argparse import json import multiprocessing as mp import os import threading import numpy as np import pandas as pd import tqdm from utils.utils import getDatasetDict from utils.read_config import Config config = Config() """ Define parser """ parser = argparse.ArgumentParser() parser.add_...
991,672
0963e755c4cd75915a988af41db7152cd7d93447
# File: jtemp.py # Author: Tyler Jordan # Modified: 8/28/2015 # Purpose: Assist CBP engineers with Juniper configuration tasks import sys,fileinput,code,re,csv import utility import math import pprint import re from utility import * from storage import * from jnpr.junos import Device from jnpr.junos.u...
991,673
091f2e6b3e72e8223877e7c9ce1ff152f7db37e9
from django.http import JsonResponse from rest_framework.decorators import api_view, parser_classes from rest_framework.parsers import JSONParser from admin.myRNN.models import myRNN @api_view(['GET']) @parser_classes([JSONParser]) def ram_price(request): myRNN().ram_price() return JsonResponse({'RNN ram_pri...
991,674
7923825f11f6c69dba506465dd1b26ac3e2fb4dd
def cube_volume(x): return x*x*x
991,675
bb46b8d86837301eadcceac5a1ee0c8167db8365
from django.urls import path from .views import SitesView urlpatterns = [ path('/', SitesView.as_view()) ]
991,676
cc93a47fd2a3d0d39c1ef2c05bcd70bbf8a56b6f
from numpy import * from plotBoundary import * # import your LR training code # parameters data = 'ls' print '======Training======' # load data from csv files train = loadtxt('data/data_'+name+'_train.csv') X = train[:,0:2] Y = train[:,2:3] # Carry out training. ### TODO ### # Define the predictLR(x) ...
991,677
02642d35a5777f1c88583753a413c3531e33ab50
import math as m import numpy as np import pylab import sympy as sp from numpy import reshape as rs from numpy import matrix as mat from matplotlib.patches import Ellipse def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:,order] class robot(object)...
991,678
8507ba4d597876af0f004050c07e02a4317c79b6
#Program setup - numbers import random import pickle Size = 50 f = open('Lotto_Data.dat','wb') Lotto_Size = 6 grid = [0]*(Size*Lotto_Size) count = 0 #Option: Seed the number table with random numbers #while count < Size: # q = 0 # while q < 6: # num = int(random.random()*49+1) # grid[num] += 1 # q += 1 # count +=...
991,679
14197c1aa8eaf6248ba3270a3fb20be40ebef96e
import logging formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ex_log = logging.getLogger('Exception_Logger') log = logging.getLogger('Logger') ex_log.setLevel(logging.WARNING) log.setLevel(logging.INFO) fh1 = logging.FileHandler('ex_log.log', encoding='utf-8') fh2 = logging.Fi...
991,680
5be23f0d0dde720a35cc94f39cf6059356b44452
from torchvision import models model = models.densenet121(pretrained=True) for pram in model.parameters(): pram
991,681
53f92e056fbbda9c2b33196b5ea108fe07703f8b
import json import yaml class Detector(object): def __init__(self, config_file): config = yaml.load(open(config_file)) # 伪代码 需修改 # self.__detector1 = Detector1(config) # self.__detector2 = Detector2(config) def detect(self, code): infos1 = self.__detector1.detect(code...
991,682
3af4c288207f00b8fe3b4ed9ab27ffa7826f9154
#!/usr/bin/env python3 import sys import os class Place(object): """ Fluent Interface for a location in the quest. Provides default behavior Args: items: a list of items that the player has at their disposal finished_places: integer to represent how many steps have been' ...
991,683
2cab4c4183d885c65cff80a6a26bf00881310bf9
from common import TreeNode class Solution(object): def LDR(self, root): res = [] stack = [None] node = root while node: if node.left: stack.append(node) node = node.left else: while node and not n...
991,684
5abc79e28c4b85d51c613a4a8744048a15766506
#!/home/apollo/anaconda3/bin/python3 #-*- coding: utf-8 -*- #****************************************************************************** # Author : jtx # Last modified: 2020-09-03 16:37 # Filename : investor_kbp.py # Description : 投资人kbp #*******************************************************************...
991,685
8e232f76ca60e912db798c53e8e678e3ed4a4b94
import tensorflow as tf import numpy as np from PIL import Image import os import math from typing import List, Tuple from memory import BaseMemory from experience import Experience import networks os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' class Brain: def __init__(self, memory: BaseMemory, img_size: Tuple, nov_t...
991,686
9f9ec86e8c46b92acbc722ed43fefa90e3e9e73b
# -*- coding: UTF-8 -*- from typing import Tuple import torch from torch import nn, Tensor class SparseCircleLoss(nn.Module): def __init__(self, m: float, emdsize: int ,class_num: int, gamma: float) -> None: super(SparseCircleLoss, self).__init__() self.margin = m self.gamma = gamma ...
991,687
26b3de9324f7a1f2713cd46879cd4d17e2018fb6
import caffe from caffe import layers as L, params as P, to_proto def mynet(): data, label = L.DummyData(shape=[dict(dim=[8, 1, 28, 28]), dict(dim=[8, 1, 1, 1])], transform_param=dict(scale=1./255), ntop=2) # CAFFE = 1 # MKL2017 = 3 kw...
991,688
517c8456331b67fd9454b2349d2473a2599aa9ad
import cv2 import face_recognition print(cv2.__version__) image = face_recognition.load_image_file('/home/fred/Documents/coding/Lernen/faceRecognizer/demoImages/unknown/u3.jpg') face_locations = face_recognition.face_locations(image) print(face_locations) image=cv2.cvtColor(image, cv2.COLOR_RGB2BGR) for (row1, col1, ...
991,689
aa8c6a7abd9b2439fa276f9ea06bc690fa8cc3b4
""" Smartcheck: smart spellcheck in pure Python. FEATURES: - Norvig's autocorrect - 3-gram language model TODO: - Combine Norvig + 3-gram approaches - Build better error model with errors from text - Save + pickle the trained 3-gram, language, error models """ from nltk import bigrams, word_tokenize fro...
991,690
4f0099377cb336e4cfae51fa031f02d12c3d38d5
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' def single_number(arr): lst = set() for i in arr: if i in lst: lst.remove(i) else: lst.add(i) return list(lst)[0] if __name__ == '__main__': # Use the main function t...
991,691
63e2add369d4a92fdf5444a6e32062284c32ca98
import cv2 import numpy as np from matplotlib import pyplot as plt def nothing(i): print(i) cv2.namedWindow("image") cv2.createTrackbar('x',"image",0,100,nothing) cv2.createTrackbar('y',"image",0,100,nothing) while(True): img = cv2.imread("media/balu_f.jpg") img = cv2.resize(img, (960,540)) ...
991,692
63832b43c8d58ddd5b547d8d65b0d3ac869dd5ef
import numpy as np t = int(input()) def match(string): zc = sum(np.array(list(string)) == "0") oc = sum(np.array(list(string)) == "1") return zc == oc * oc for k in range(t): s = input() c = 0 for i in range(len(s)-1): for j in range(i+1, len(s)): if match(s[i:j+1]): ...
991,693
e5ab463e61fdab9c8e7653841626001b2d22486c
import unittest import numpy as np from SimPEG.electromagnetics import viscous_remanent_magnetization as vrm class VRM_waveform_tests(unittest.TestCase): def test_discrete(self): """ Test ensures that if all different waveform classes are used to construct the same waveform, the character...
991,694
2a2206a5d488008850b39b3448e489b3441613df
""" Test cases for Recommendations Model """ import logging import unittest import os from service.models import Recommendation, DataValidationError, db, Type from service import app from .factories import RecommendationFactory TEST_DATABASE_URI = os.getenv( "TEST_DATABASE_URI", "postgres://postgres:postgres@loca...
991,695
c1cb1a8d764cff27cf807edb91dbe3bbd2d2c376
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/6/21 23:47 # @Author : SNCKnight # @File : 08_operator_precedence.py # @Software: PyCharm """运算符优先级 一般用()控制运算优先级 ** 指数 (最高优先级) ~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) * / % // 乘,除,取模和取整除 + - 加法减法 >> << 右移,左移运算符 & 位 'AND' ^ | 位运算符 <= < > >= 比较运算符 <> == ...
991,696
266f25c98379fe914fd1d928316bfd4afa129878
""" Copyright 2021 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. """ import contextlib import re import socket import subprocess import time import requests import yaml from . import config, ...
991,697
b3af7f087e2c15d0eb147ea759e14abe5bf8415d
import sys, os ROOT_FOLDER = os.path.dirname( os.path.dirname( os.path.abspath(__file__))) sys.path.insert(0, ROOT_FOLDER) from pipelines import data_curation from launchers import data_update_launcher def main(): data_update_launcher.main() print("Running data curation pipeline") data_cura...
991,698
69655a4ab2aec09b6d12726053d358c397891b8f
''' Created on April 27, 2018 @author: Edwin Simpson ''' import os import evaluation.experiment from evaluation.experiment import Experiment import data.load_data as load_data import numpy as np regen_data = False gt, annos, doc_start, features, gt_val, _, _, _ = load_data.load_biomedical_data(regen_data) # , debug...
991,699
c671d01e0b7cee73fba1f757e891cb7440b6e3bd
import sqlite3 connection = sqlite3.connect('databaseContratos.db') c = connection.cursor() def DELETE(codigo): c.execute("DELETE FROM CONTRATO WHERE codigo=:codigo", {'codigo': codigo}) c.execute("SELECT * FROM CONTRATO") print(c.fetchall()) connection.commit() connection.close() cod...