index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
990,000
b7da13a879d7062b7e90dbc50c1789cf359282f4
""" @summary: Custom HTML parser using HTMLParser library, store the result in a tree @author: Alexandre Bisiaux """ from HTMLParser import HTMLParser from xml.etree import cElementTree as etree import requests """ Get text of a tree node @param node: The tree node @return: The text presents in the node Ex : <a> tex...
990,001
ad3d5ab73a1bd99dc0e960266d713ddd169d887e
import torch from torch.autograd import Variable from scipy.misc import imresize from imageio import imread, imsave import numpy as np from path import Path import argparse from tqdm import tqdm from models import PoseExpNet from inverse_warp import pose_vec2mat from utils import tensor2array from PIL import Image p...
990,002
728c3c3e5bbc9536a8a8b859e0bc62ac1c0ef0ae
"""Reply API Call handler for snapshots.""" from pymongo import Connection from pymongo.errors import InvalidId from bson.objectid import ObjectId from datetime import datetime from cgi import escape, parse_multipart, parse_header, FieldStorage from urlparse import parse_qs from json import dumps from boto.s3.connecti...
990,003
6290590fe88890aca747d5940fd9e48012462c29
import ants import numpy as np import h5py import time from zebrafish_io import lif_read_stack, save import multiprocessing as mp def pipeline(file_path,fixed_index,moving_indices,rigid_out_file,atlas_file,transform_out_file,out_diff_file): stack,spacing=lif_read_stack(file_path) #rigid=rigid_registration(stac...
990,004
80a5fb4b4c78da82be2296751919b04f57b91c6b
from ryu.controller.handler import MAIN_DISPATCHER from ryu.ofproto import ofproto_v1_3 from ryu.base import app_manager from ryu.topology import switches from ryu.topology import event as TopologyEvent from ryu.controller import dpset from ryu.controller.controller import Datapath from ryu.controller.handler import se...
990,005
30414317aeb4427615c3f05d90b306160128e33c
menuItems = { 'Wings': 0, 'Cookies': 0, 'Spring Rolls': 0, 'Salmon': 0, 'Steak': 0, 'Meat Tornado': 0, 'A Literal Garden': 0, 'Ice Cream': 0, 'Cake': 0, 'Pie': 0, 'Coffee': 0, 'Tea': 0, 'Unicorn Tears': 0, } response = '' print('**************************************\n** Welcome to t...
990,006
c8454367d3c8a098a03214a677cc700c72034bf3
""" g $$$$$$$$$$$$$$$$$$$$ f $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ t $$$$$$$$$$ o $$$$$$$$$$$$ """ def histogram_maker(dictionary_of_sales): for company in dictionary_of_sales.keys(): print(f"{company[0]} {dictionary_of_sales[company] * '$'}") sales_Q1 = { 'google': 20, 'facebook': 25, 'twitter': 10, ...
990,007
df003a5b4d735e95b75c0ad2c7ee03f616ab5f54
from django.shortcuts import render, get_object_or_404, redirect from .forms import InvestmentForm, ProductForm, ExpenseForm from .models import Investment, Expense, Product def investment_stat(request): investments = Investment.objects.all() return render(request, 'investments.html', {'investments': investmen...
990,008
7f9297b8136428c3f2c4d0b52d24a7fc8c16d2b1
import sys import matplotlib matplotlib.use('TkAgg') from matplotlib.pyplot import plot,draw,figure,cla,xlim from time import sleep from numpy import loadtxt if len(sys.argv) < 2: print "USAGE: %s file.dat"%sys.argv[0] sys.exit(1) f=figure() f.show() while 1: d = loadtxt(sys.argv[1]) cla() map(lambda i: pl...
990,009
27bc2ba5a21e4d88de7761c5504c4acab7f66c7b
import matplotlib.pyplot as plt from gwpy.time import Time from gwpy.timeseries import (TimeSeries, TimeSeriesDict) from matplotlib.ticker import MultipleLocator, FormatStrFormatter import pylab print "Import Modules Success" #Start-End Time start = Time('2014-03-24 00:00:00', format='iso', scale='utc') end = Time('2...
990,010
e3c0ebcd8241a16d94ad1df1fe48d60870470c09
# from django.contrib.auth.models import User class TemplateTest: def __init__(self, a, b): self.a = a self.b = b def modify(self, x, y): # print(getattr(self, x)) self.__dict__[x] = y modify.alters_data = True class A(object): def __init__(self): self._map = {}...
990,011
8a75d3671ad30944d0eca47082d4387eb4d10395
from django.shortcuts import render,redirect from user.forms import * from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login as builtInLogin, logout as builtInLogout # Create your views here. def selectUser(request): return render(request,'sign-up-choose.html') def ...
990,012
540a5b843a494b86072aa331f61f0cb3f1f798d1
from String import telephone_name_lookup def test_tel_directory(): names = ['bevavy 2019830294','kim 94409294','smith 298234205','lewis 329049235','jim 392029446','peter 3425252525','john 23425255'] (name_directory, phone_directory) = telephone_name_lookup.build_name_directory(names) results = telephone_...
990,013
01d80fd14ed5299f0236b20a530d6d99430a5272
import math reflec_index = [1.33, 1.34026 ,1.34782, 1.35568, 1.36384, 1.37233, 1.38115, 1.39032, 1.39986, 1.40987, 1.42009, 1.4308, 1.44193] for i in range(len(reflec_index)) : seta = math.degrees(math.asin((math.sin(math.radians(30)))*reflec_index[i])) print("Brix degree : "+ str(i*5) +" reflec_index : " + s...
990,014
0d3f65ca6c22ca7a7918b5aeec1424b31cd4539b
# Simple code for loading some standard data sets from the UCI Machine # Learning repository. # from classifier import data_item def read_wine_dataset(): '''Return a list of data_item object representing the UCI Wine data.''' dataset = [] fp = open('wine.txt') for line in fp: fields = line.spli...
990,015
8d12590d957f257d0bd3294e06af2db58c29047f
import json import asyncio async def dumps(content: dict) -> str: loop = asyncio.get_running_loop() json = await loop.run_in_executor(None, json.dumps, content) return json async def loads(content: str) -> dict: loop = asyncio.get_running_loop() dictionary = await loop.run_in_executor(None, json.l...
990,016
bb76226153814b101fa6686a5a747a82c028b122
""" Fine tune forward model using data generate by itself. choose S_init, S_goal controller gives a_1 excute a_1, get transition S_init, a_1, S_next use this transition to renforce the forward model Choose S_init, S_goal 1. using Policy (Fine tune in policy distribution) 2. randomly choose one (if not state spac...
990,017
29193872339962c72b1a9fa9dea05504ffbff608
import numpy as np import matplotlib.pyplot as plt from DubinsCar import DubinsCar from Environment import Environment def gen1(d): return np.radians(10) def randomDubins(): car = DubinsCar(theta=np.radians(45), speed=10) x, y = np.zeros(100), np.zeros(100) for i in xrange(100): angle = np.r...
990,018
a51363ec4e0abffea47f63c1c9203e1796f46677
#!/usr/bin/env python #Written by Roger Fachini #Startup script located at /etc/init/githttpstartup.conf import logging import socket import SimpleHTTPServer import SocketServer import json import time import os import commands import cgi IP = '' PORT = 80 BASE_DIR = '/robotics/services/pvcs/' LOG_DIR = '/robotics/...
990,019
737bfa88f64e7242021140ce914c694082660b89
import cv2 import numpy as np class CommonsVariables(object): labels = ['blow_down', 'bare_ground', 'conventional_mine', 'blooming', 'cultivation', 'artisinal_mine', 'haze', 'primary', 'slash_burn', ...
990,020
092d01e09987b7e1d93870d02baa0367adc88749
from django.urls import path from .views import * urlpatterns = [ path('login.html', loginView, name='login'), path('register.html', registerView, name='register'), path('setps.html', setpsView, name='setps'), path('logout.html', logoutView, name='logout'), path('', findpsView, name='findps') ]
990,021
02a2c33974219c9f386befc723506264d4632826
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split class DataProcessor(): ''' The DataProcessor class is repsonsible for parsing the given .csv file. ### Attributes #### :file : (str) the path to the file. :test :...
990,022
ca4f83a7a225b5a1f78b6bd9016a3b3fa93bdd81
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import configparser import logging.handlers import os PYTHON_LOGGER = logging.getLogger(__name__) if not os.path.exists("log"): os.mkdir("log") HDLR = logging.handlers.TimedRotatingFileHandler("log/config_reader.log", ...
990,023
edc55bcf5d44be31a0d3cd08613494c3bc209419
import jittor as jt from jittor import nn, Module from jittor.nn import Sequential from collections import OrderedDict import math class Flatten(Module): def execute(self, input): return input.view(input.size(0), -1) class Conv_block(Module): # verified: the same as ``Conv'' in ./fmobilefacenet def __...
990,024
c1a7b282cb54a44af7f10c5ba7e363ae9193378b
# Write a function that takes two arguments - a quiz question and the correct answer. # In your function, you will print the question, and ask the user for the answer. # If the user gets the answer correct, print a success message. # Else, print a message with the correct answer. # Your function does not need to return...
990,025
5f3a57be0883754c3df2a1761eef5bc80379277c
from flask import Flask,render_template,redirect,flash,url_for,request import requests import datetime import pandas as pd import os from bokeh.io import output_file, show, save from bokeh.plotting import figure from bokeh.models import ColumnDataSource, HoverTool, CustomJS from bokeh.models.widgets import Button from ...
990,026
26072f407e089cb7a4f607f4a260f6d854ce2d5f
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
990,027
e8e48f97456d196f8e1546ad024dfac731137270
import datetime import factory import factory.fuzzy import pytz from foosball.users.tests.factories import UserFactory class TeamFactory(factory.django.DjangoModelFactory): score = factory.fuzzy.FuzzyInteger(10) @factory.post_generation def players(self, create, extracted, **kwargs): if not cr...
990,028
889411af9586f6a7375fcff7809645c69ae5527e
# You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be i...
990,029
d76bbd5847181f76f0609e5139d2cf185617b40e
"""Helper to preprocess data.""" import pandas as pd from sklearn.model_selection import train_test_split class Preprocessor: """Class to handle preprocessing operations.""" def __init__(self, df): """Set DataFrame as class variable.""" self.df = df def remove_urequired_columns(self, unr...
990,030
67232fc8b46954395589e5264d2426d0b2db3ec7
#!/usr/bin/python # Import libraries import RPi.GPIO as GPIO import time import datetime from time import sleep # Pinouts from RPi Zero 2 W # 22 Panel on 24 LepiLED on # 27 Panel off 23 LepiLED off # Set up pin for latching relay FOR THE PANEL ON GPIO.setmode(GPIO.BCM) # Latching Relay #2 GPIO.setup(22, GPIO.OUT) ...
990,031
c26c030ad7948bbf2a68d40e512e77b22c3753b9
def notas(*n, sit=False): b = {} b['Total'] = len(n) b['Maior'] = max(n) b['Menor'] = min(n) b['Media'] = sum(n) / len(n) if sit: if b['Media'] > 7: b['Situação'] = 'BOA' elif 5 < b['Media'] < 7: b['Situação'] = 'RAZOÁVEL' elif r['Media'] < 5: ...
990,032
b5f5aee098e7cb0b7a1469a361378df34b470b3d
# # @lc app=leetcode id=18 lang=python3 # # [18] 4Sum # class Solution: def fourSum(self, nums, target): nums.sort() if len(nums) == 4: if sum(nums)==target: return [nums] else: return [] result = [] for idx, i in enumerate(nu...
990,033
bff3b950a4db58ce5977ee80d0a617c53d7e88ce
from django.conf.urls import url from django.contrib import admin from .views import ( workload_list, workload_create, workload_update, workload_delete, workload_report, workload_export, detail, sum_report, ) urlpatterns = [ url( r'^$', workload_list, name='list'), url( r'^create/$', workload_create,name...
990,034
32f86269149ffa9e1d692ddf1fa6e480db2ad5fc
# -*- coding: utf-8 -*- from __future__ import unicode_literals import tempfile from django.conf import settings from PIL import Image, ImageDraw, ImageFont def resize(image, width=None, height=None): if width is None and height is not None: imageWidth = (imageWidth * height) / imageHeight image...
990,035
d0a1ab7a2fde1abff0d603a452091d8a34f8b0d3
from django.template import Library from native_tags.nodes import do_function, do_comparison, do_block from native_tags.registry import load_module, AlreadyRegistered, register as native_register from django.conf import settings from django.utils.importlib import import_module from os import listdir register = Library...
990,036
c86903d684390fac3908ddac63ec93ce40352c9b
# Code is a modified version of 'Jose Julio @2009 "IMU_Razor9DOF.py"' # This script needs VPhyton, pyserial and pywin modules # First Install Python 2.6.4 # Install pywin from http://sourceforge.net/projects/pywin32/ # Install pyserial from http://sourceforge.net/projects/pyserial/files/ # Install Vphyton from http://...
990,037
3d05d365e01d2597199e608abdc6162245c1b6a9
# this will serve as the database, where we will connect to the file system # and fetch from the file system # what we will do in this database # create a record # update record # read record # delete record # all of this is called the CRUD operation # see how the functions below line up with each CRUD operation #...
990,038
99f9e4def160187aa541895e7f202fed0e94f8cd
"""Create the login parser.""" from __future__ import annotations import typing from awssso.console.login import login if typing.TYPE_CHECKING: import argparse def arg_parser_login( subparsers: argparse._SubParsersAction, parent_parser: argparse.ArgumentParser, default_args: None | dict = None, ) -...
990,039
998041791144a53755cae38a3db404812d995e63
# Generated by Django 2.2.8 on 2020-01-13 23:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('preproject', '0019_auto_20200113_2254'), ] operations = [ migrations.AlterField( model_name='preproject', name='solu...
990,040
d9c80b0414cf1c2bc8b28ef2c988571a80c4fbeb
import numpy as np def L_inf_prox(z, tau): p = z.shape[0] zs = np.fabs(z) z_rank = np.argsort(zs) zs = np.sort(zs) xmax = zs[-1] - tau i = 1 while xmax <= zs[-(i + 1)]: xmax = (xmax * i + zs[-(i + 1)]) / (i + 1.0) i += 1 if i + 1 > p: break zs[(-i) :...
990,041
eb7e2fe94e8e2938e50e2deb156d4c55337fecdf
# Generated by Django 3.0.6 on 2020-06-01 09:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('OnlineShoppingApp', '0009_addtocart'), ] operations = [ migrations.RenameField( model_name='addtocart', old_name='AddToCart_...
990,042
1da447bf1bd4f586bfd1f1d9cf111680f6909c0b
#!/usr/bin/env python from imports import * from configs import * def urlOK(url): r = requests.head(url) return r.status_code == 200
990,043
6de2c38a9a894ef2cef2e2ca7bbcd473a93c9130
from common import timestamp
990,044
e651f3ced0e1f8a41336b67d28c805820d31a167
import pygame, images from pygame.locals import * class Symbol(pygame.sprite.Sprite): images = pygame.sprite.Group() def __init__(self, image, x, y, color=None, action="door"): pygame.sprite.Sprite.__init__(self) image = images.Image(image, x, y, color) self.image = image # Make our top-left corner the...
990,045
19835de951e1fdbd38feca94269f68a51f247a5c
from typing import List, Optional from pydantic import BaseModel from datetime import datetime class Songbase(BaseModel): name: str duration : int uploadTime: datetime class Song(Songbase): class Config(): orm_mode = True class ShowSong(BaseModel): name: str duration: int uplo...
990,046
6ee441d0759691e8b590f13a6ffb0337db52b164
# 973. K Closest Points to Origin # Time: O(len(points)*log(K)) # Space: O(log(K)) class Solution: def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: import heapq heap = [] for point in points: dist = math.sqrt(point[0]**2+point[1]**2) if len...
990,047
1b92355877ff74eb9ffa6b175115df7755b239e1
cont = mulher = homem = 0 while True: idade = int(input("Idade: ")) sexo = " " p = ' ' while sexo not in "MF": sexo = str(input("Sexo [M/F]: ")).strip().upper()[0] if idade >= 18: cont += 1 if sexo == "M": homem += 1 elif sexo == "F" and idade >= 20: ...
990,048
17891d0b8c3b213fc10a2690a3bde7468d9d8785
# # complexity O(n) def parity(x): result = 0 while x: result ^= x&1 x >>= 1 return result # complexity O(k) # x = 00101100, x-1 = 00101011 # x & (x-1) = 00101000 def parity_Ologk(x): result = 0 while x: result ^= 1 x = x & (x-1) return result def parity_Olog...
990,049
3b6b9b3426c4aaf90c89b210386e036b9aaa4f38
import pytest from datetime import datetime from decimal import Decimal from b2c2.models import Balances, TradeResponse, SideEnum def test_can_add_trade_to_balance(): balance = Balances(__root__={'BTC': Decimal(0)}) trade_resp = TradeResponse( created=datetime.now(), instrument='BTCUSD.SPOT'...
990,050
1c80550ee95b9eeddd154de7251d4943cd78ea2a
# -*- coding: utf-8 -*- from odoo import models, fields class FruteriaSocio(models.Model): _name = 'fruteria.socio' _description = 'Socio fruteria' _inherits = {'res.partner': 'partner_id'} imagen_socio = fields.Binary('Imagen', related='partner_id.image') id_socio = fields.Integer('Id_Socio',req...
990,051
2d76f1f6a3578897586520113dcaccbd11f80fa2
import re a=5 b=6 # swap 2 variable a,b = b,a print ('swap: ', a, b) # delete duplicated element in an array old_list = [1,1,1,3,4] new_list = list(set(old_list)) print ('uniq a array: ', old_list, new_list) # reverse string s = 'abcde' ss = s[::-1] print ('reverse: ', s, ss) # make a dict using 2 related array ...
990,052
0606367a5851704cad332cf9bac681b7f97b1bad
#dataBase.py import os import json import time #import dataset import databases #import sqlite3 from sqlalchemy import * from sqlalchemy.ext import mutable from sqlalchemy import orm from sqlalchemy.ext import declarative from Server.server import cnf class JsonEncodedDict(TypeDecorator): """Enables JSON storage ...
990,053
2c089d309414663707d795267fc81769c8963e53
import torch import torch.nn as nn import torch.nn.functional as F class CrossEntropyLoss2d(nn.Module): def __init__(self, weight=None,reduce=True,size_average=True): super().__init__() self.loss = nn.NLLLoss(weight,reduce=reduce,size_average=size_average) def forward(self, outputs, targets)...
990,054
1267db37365ab61417eb77f1e6d9b8cb7d3ba46f
# -*- coding:utf-8 -*- import ftplib def returnDefault(ftp): try: # nlst()方法获取目录下的文件 dirList = ftp.nlst() except: dirList = [] print '[-] Could not list directory contents.' print '[-] Skipping To Next Target.' return retList = [] for filename in dirList...
990,055
ef469da38d69163ea7dcc1fc0c4a7a69c3fa765d
#!/usr/bin/python3 import os import sys import pymongo from modules import Scan_NTP,Ssh_Cracked,Telnet_Cracked,GET_Whitelist print('Welcome to Jormungandr system (^ ^)') col=pymongo.MongoClient() while True: print('''Please chose you modules!: 1,ssh cracked 2,ntp scan 3,telnet scracked enter you chose numbe...
990,056
5449188d2e83b7242e9e2de0f182f4d5716db43d
import json import time from datetime import datetime import requests import csv import os import os.path from urllib.parse import urljoin AAIDA_BACKEND_BASE_URL= os.getenv("AAIDA_BACKEND_BASE_URL") print(os.getcwd()) filename = 'responses-record.csv' url = urljoin(AAIDA_BACKEND_BASE_URL, 'cases/submit') #dummy loa...
990,057
4005589b4aa4cc7f2b94e25c80df8a8d9d18158d
cars = 10 space_in_a_car= 4.0 drivers = 3 passengers = 9 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print cars print drivers print passengers print drivers print carpool_capacity print average_passengers_...
990,058
f4d122e17534abd57f7e14314d9d892937ec3d9d
start = raw_input("Start ") end = raw_input("End? ") for x in range(start, end): print(x) def oneToTen(start, end): for x in range(start, end) print(x) return True result = oneToTen(0, 10) print result
990,059
46578f3e7f71a45c0de873a685de858d091bf676
import time import tensorflow as tf import numpy as np import networkx as nx import data_utils from model import * print("TF Version: ", tf.__version__) # Set random seed seed = 123 np.random.seed(seed) tf.set_random_seed(seed) # Settings flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('dataname', 'twi...
990,060
173d3d4858a2de042610391d0797e5af58d7b553
game = { "name": "Vainglory", "description": "MOBA", "status": "frequent updates", "features": "3v3, 5v5" } print(game) n = input("Enter key you want to delete: ") if n in game: del game[n] print(game) else: print("Error 404")
990,061
23dfb2f8e8c36c88bc21ca851a3335ad881e0371
import os import re def read_version(): with open(os.path.join('freezegun', '__init__.py')) as f: m = re.search(r'''__version__\s*=\s*['"]([^'"]*)['"]''', f.read()) if m: return m.group(1) raise ValueError("couldn't find version") def create_tag(): from subprocess import ...
990,062
d3c381ee37ef813c5a87a429f45e743badf771f0
# 1. Pedir dos números por teclado e imprimir la suma de ambos. print("Ejercicio 1") def sumar (numero_1, numero_2): resultado = numero_1 + numero_2 return resultado numero_1 = float(input("Introduce el primer número: ")) numero_2 = float(input("Introduce el segundo número: ")) resultado = sumar (numero_1, ...
990,063
be54859e42304ebc7c28d26dc70cffeb2f59affa
#!/usr/bin/python2.7 # # Tester for the assignement1 # DATABASE_NAME = 'dds_assignment' # TODO: Change these as per your code RATINGS_TABLE = 'ratings' RANGE_TABLE_PREFIX = 'range_part' RROBIN_TABLE_PREFIX = 'rrobin_part' USER_ID_COLNAME = 'userid' MOVIE_ID_COLNAME = 'movieid' RATING_COLNAME = 'rating' INPUT_FILE_PATH...
990,064
a06239ea75ff4d82dea2403d4f27b0471c20f3ff
#!/usr/bin/env python translation = str.maketrans('+-', '-+') T = int(input()) for i in range(1, T + 1): stack = input() s = 0 while '-' in stack: s += 1 lastBS = stack.rfind('-') stack = stack[0:lastBS+1].translate(translation) + stack[lastBS+1:] else: prin...
990,065
bb4735a9bd4b28650060472838d54c7afc41f3f7
import numpy import re import math import threading import time from OpenGL.GL import * from Cura.gui import openGLUtils from Cura.gui.view3D.renderer import Renderer class GCodeLayerRenderer(object): def __init__(self, prev_layer = None): self._x = 0 self._y = 0 self._z = ...
990,066
2914cd7e0283a7ce1c25ff1fffe6880d7b75a07c
t = int(input()) for T in range(t): n = int(input()) l = [] for i in range(n): s = input() l.append(list(s)) ans = 0 for i in range(10): count = 0 for j in range(n): count += int(l[j][i]) if count % 2 == 1: ans += 1 print(ans)
990,067
f633f5ff62e78dfdab19ed173ac624fdd97da890
import random import re import torch from torch.nn import functional as F from pytorch_transformers import GPT2Tokenizer, GPT2Model, GPT2LMHeadModel torch.set_grad_enabled(False) MODEL_PATH = './WoWQuestPytorch124M' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') tokenizer = GPT2Tokenizer.from_p...
990,068
c8bd17ce9492aef044ec2b986c815f1a50a25c89
class person: def __init__(self,fname,lname): self.firstname = fname self.lastname = lname def fullname(self): print(self.firstname , self.lastname) def subject(marks): total_marks = marks*5 print(total_marks) p1 = person("raj","kumar") p1.fullname() subject(100)
990,069
72099ff67d5a245634b3c1e0e6fb43b53ae19ac2
# baselineTeam.py # --------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley...
990,070
495b3a6631d5bb729097ce44fbb34da798131f66
def color(name,colour): if type(name) is not str: raise TypeError("only strings allowed") print(f"{name} likes {colour}") color("alley","green") color(21,"red")
990,071
520335e224f55d367329f5b6cfd6ca4c938ead74
# Generated by Django 2.0.7 on 2018-10-14 06:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appDatas', '0001_initial'), ] operations = [ migrations.RenameField( model_name='pill', old_name='qrcode', new_n...
990,072
97b89627f52004d09e651e733aa7ef04c4c2508b
import ROOT as r f = r.TFile("tree_cycles_hist.root", "recreate") t = r.TTree("Events", "") obj = r.vector("float")() t.Branch("Jet_pt", obj) rows = [[], [27.324586868286133, 24.88954734802246, 20.853023529052734], [], [20.330659866333008], [], []] for i,row in enumerate(rows): obj.clear() for x in row: ...
990,073
6aa29e8b5b8fa0c8dbb289ac016b587e114e1db3
import numpy as np from deepthought.experiments.encoding.experiment_templates.base import NestedCVExperimentTemplate class End2EndBaseline(NestedCVExperimentTemplate): def __init__(self, job_id, hdf5name, fold_generator, pipeline_factory, ...
990,074
6e4519d9a662f384e59f8f8f995343076712d88d
def perfectnum(num): sum= 0 for i in range(1, num): if (num % i == 0): sum += i if (num == sum): return True perfectnumbers = [] for i in range(1, 1000): if (perfectnum(i)): perfectnumbers.append(i) # listeye ekledik. print("Perfect Numbers Between 1 and 1000 are\n...
990,075
7960f5cad98fab18612a8ddb103386fedc8821f2
n = int(input("Digite um numero: ")) resto = n % 3 if resto > 0: print(n) else: print("Fizz")
990,076
339da4279f815e45db89bd6b115ed4d583fd09a5
from django.db import models # Create your models here. class Manufacturer(models.Model): name = models.CharField(max_length=50) date_added = models.DateField() def __str__(self): return f'{self.name} added on {self.date_added}'
990,077
d5ce9046b71d0cbe40a77b1b22c60339c8d10f9a
try: from unittest import mock except ImportError: import mock import betamax from betamax.decorator import use_cassette @mock.patch('betamax.recorder.Betamax', autospec=True) def test_wraps_session(Betamax): # This needs to be a magic mock so it will mock __exit__ recorder = mock.MagicMock(spec=beta...
990,078
dda2dbd589a326af41368501ff58a2a68c2b01e9
#from flask import Flask import numpy as np import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, case import datetime as dt from sqlalchemy.pool import NullPool from flask import Flask, jsonify, render_templ...
990,079
db54ea5a922913df0aeb5b5e3bfcdaa556a5632d
from pathlib import Path from unittest import IsolatedAsyncioTestCase import os import shutil import tempfile from unittest.mock import AsyncMock, MagicMock, patch, ANY from pyartcd.pipelines.promote import PromotePipeline from doozerlib.assembly import AssemblyTypes class TestPromotePipeline(IsolatedAsyncioTestCase...
990,080
9d653decc9c6ae9d42d0c7b9e4a67f0175f77e08
import os import torch from detectron2 import model_zoo from detectron2.config import get_cfg cfg = get_cfg() # Setting output directory cfg.OUTPUT_DIR = 'Table Detection/model/' # Set device cuda/cpu if torch.cuda.is_available(): cfg.MODEL.DEVICE = 'cuda' else: cfg.MODEL.DEVICE = 'cpu' print('Setting D...
990,081
2f9eef47f0f60b47f5a51149b20920ae0bbad1c5
from django.urls import path, include from rest_framework.routers import DefaultRouter from rest_framework_swagger.views import get_swagger_view from .api import * router = DefaultRouter() router.register(r'reviews', ReviewsViewSet, basename='reviews') schema_view = get_swagger_view(title='CovAnalytica API') urlpatt...
990,082
71248e02ceb6b9677682139e5be4fcf3153be205
from __future__ import print_function import argparse import os import shutil import time import random import visdom import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data as data from tor...
990,083
29056a332619e4b6fbe2ffe316a4fa1d119edc2a
import storymarket from django.conf import settings from django_storymarket.models import SyncedObject QUEUE_UPLOADS = getattr(settings, 'STORYMARKET_QUEUE_UPLOADS', False) if QUEUE_UPLOADS: from .tasks import upload_blob_task def save_to_storymarket(obj, storymarket_type, data): """ Push an object to St...
990,084
9cfd04f2f8617f6a3a20637e416e201f9e7017b9
# 9.1 class Restaurant: """Creating a Restaurant class""" def __init__(self, restaurant_name, cuisine_type, number_served=0): """assigning name and type""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = number_served def descrip...
990,085
7b9afb9f6267d468268d1415b664ff3855481fb0
import argparse import pandas as pd from Bio import Phylo import itertools import numpy as np import scipy.sparse def run(): parser = argparse.ArgumentParser() parser.add_argument('--tree', help='newick file with tree on which to cluster sequences from') parser.add_argument('--treeNameSep', ...
990,086
6c78cbf97f3509270abf5f6d7a96fb851f93137e
"""Analysis of SPH data. The analysis sub-package contains Plonk implementations of typical smoothed particle hydrodynamics post-simulation analysis tasks. Examples -------- Create a radial profile in the xy-plane. >>> p = Profile(snap, cmin=10, cmax=200, n_bins=100) >>> p.plot('radius', 'density') Calculate the an...
990,087
a686eb1b93f1b800ba6ab5395fb3ef0083c1185d
from time import sleep, time; import os; from java.io import File; from javax.imageio import ImageIO; from java.awt.image import BufferedImage #import java from math import * from gda.data import NumTracker from gda.jython import InterfaceProvider from gda.device.detector import DetectorBase from gda.device.dete...
990,088
a31cdd394365a216f1040499d57e4b1ddc223458
#!/usr/bin/env python3 import subprocess as sub class execHandler(): def __init__(self, password = 'asdf1234'): self.password = password def __del__(self): self.password = '' def decrypt(self, file): proc = sub.Popen(['gpg', '--batch', '--passphrase-fd', '0', '--decrypt', file], ...
990,089
41ec2d909fa40d35b59eacdf56fb61d169cadfcf
#Python program for merge sort def merge_sort(list1): if len(list1) > 1: mid = len(list1)//2 left_list = list1[:mid] right_list = list1[mid:] merge_sort(left_list) merge_sort(right_list) i = 0 j = 0 k = 0 while i < len(left_list) and j < len(ri...
990,090
fb4d2bad2e3cb91e73e32c547bd1e4852a55f1c3
#! /usr/bin/env python #coding=utf-8 from __future__ import division class LanguageModel: def __init__(self): self.m={} self.m0={} count=0 for line in open(r'G:\wangzq\PolyU\Code-Switching\Emotion_CS_Analysis\comments.lm.seg.txt'): words=[w.lower() for w in lin...
990,091
7c740ae10467e8d3e9092280cdb5d6593ca7bb30
live_grid = [[0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0]] def display_grid(gr...
990,092
69094f836d6380444279124f1230e4d3190194e6
#! python import h5py import numpy import matplotlib.pyplot import pandas import datetime def read_h5(filename): def selectValues(name, obj): if 'VALUES' in name: lstDataSets.append(obj) lstDataSets = [] with h5py.File(filename, mode='r') as of: of.visit...
990,093
ce9062fd96bc51a4286481276f3edc105fb44441
import webapp2 import jinja2 import os from google.appengine.ext import db jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '.'))) class Blog(webapp2.RequestHandler): def get(self): template = jinja_environment.get_templ...
990,094
d7e1d989e3d5f0622696d75899f431bd920140a2
################################################################################ ################################################################################ ## IMPORTANT NOTE ## # 1. Please set appropiate mode of operation towards the END OF THIS SCRIPT # Mode = 0 --> For si...
990,095
70b46fec7074701347e33f67c05843a82a488795
"""Test helper to handle making RPC requests to an AMPQ broker.""" import gzip import json import uuid import time from typing import Any, Optional import pika from pika.adapters.blocking_connection import BlockingChannel Connection = pika.BlockingConnection Channel = BlockingChannel class ResponseTimeout(Exceptio...
990,096
ac2a7aad5c3a11d7f8a774d7188cc90915a37388
# Load libraries import numpy as np from pandas import read_csv from pandas.plotting import scatter_matrix from matplotlib import pyplot from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import StratifiedKFold from sklearn.model_selecti...
990,097
77540aef5c16171efacbc833730810a6d2329ca8
# Module identify waveguides in refractive index data # Written by R. H. White rwhite@eoas.ubc.ca import numpy as np import xarray as xr import math from scipy.interpolate import interp1d from scipy import signal from scipy.signal import butter, lfilter, sosfilt import scipy.fftpack as fftpack from datetime import dat...
990,098
23a44d2ca57208d033762661f5f5c7ac382da66f
from abc import ABC, abstractmethod class IranKhodro(ABC): @abstractmethod def engine(self): pass class Samand(IranKhodro): def engine(self): print("man Samandam!") class Pejo207(IranKhodro): def engine(self): print("man Pejo207am") class Rona(IranKhodro): def engine...
990,099
9c1023e12e33ed39687ac3491f8a8c25e75e1620
import requests import re # https://github.com/firehol/blocklist-ipsets/blob/master/blocklist_de.ipset def getBaseIP(url: str) -> list: """Get IP address from IPset """ response = requests.get(url) #get data ip_sets = response.text ip_list = re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', ip_sets) return...