index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
16,800 | 044ca78bdc03c5e5553f12af8249c71c04d7a9a7 | #! python3
from pyforms.gui.appmanager import start_app
from pyforms.gui.basewidget import BaseWidget
from pyforms.gui.controls.ControlButton import ControlButton
from pyforms.gui.controls.ControlDir import ControlDir
from pyforms.gui.controls.ControlFile import ControlFile
from pyforms.gui.controls.ControlList... |
16,801 | bc0ea9ae8748256fbfab6042a09a67f755addb1d | from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '41c907f395dc1244c69ab23a40fa363b'
posts = [
{
'author': 'Corey Schafer',
'title': 'Blog Post 1',
'content': 'First post content',
'date_... |
16,802 | 3f70d7a3d253f4c6fdf992544b82df44fe622345 | from django.apps import AppConfig
class CassetteDjangoConfig(AppConfig):
name = 'cassette_django'
|
16,803 | 92e77c0d3ce942662092d4edb3237220058f068a | import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from model import createNetwork, createDeconvNetwork, createLeanNetwork
from mesh_optimizer import Optimizer
from prepare_data import prepareData, createBatches, prepare_mask
import tensorflow as tf
import numpy as np
import time
# =... |
16,804 | 27d190eaf8c5427b176e1ffd8da01069e9bea7b8 | from rest_framework import serializers
from main.order.models import Company
from main.api.serializers.reseller.product import ProductSerializer
class CompanySerializer(serializers.ModelSerializer):
username = serializers.SerializerMethodField()
products = serializers.HyperlinkedIdentityField(
view_na... |
16,805 | 93fbedc1d37b35d28f4d9529dc9e56cab2dcd02f | import pygame, sys
import numpy as np
#initialize pygame
pygame.init()
#variables
width= 600
height= 600
line_width= 10
crimson=(220, 20, 60)
line_color= (52, 235, 232)
board_rows=3
board_cols=3
circle_radius= 50
circle_width= 15
circle_color = (153, 102, 255)
square_color = (153, 102, 255)
square_width= 15
space= 55
... |
16,806 | 1272fc6f4f24ad69ddcc8be9c7749005009c159f | # Copyright (c) Alibaba, Inc. and its affiliates.
import datetime
import os
import os.path as osp
from collections import OrderedDict
import json
import torch
from torch import distributed as dist
from modelscope.metainfo import Hooks
from modelscope.trainers.hooks.builder import HOOKS
from modelscope.trainers.hooks.... |
16,807 | 1d0c3600974853e81eb3795c0475572beda01572 | #################
## imports
import os
import json
import time
from flask import Flask, render_template, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
################
## config
app = Flask(__name__, instance_relative_config=True)
app.c... |
16,808 | 4da0ad39685cb4af0f0a564e5db959a088fe8a5c | from browser import alert, window, ajax
from javascript import JSON
class MapRenderer:
def __init__(self, center, zoom, get_location_url, camera_view_url):
self.center = center
self.zoom = zoom
# get data
self.leaflet = window.L
self.shapes = {}
self.markers = None... |
16,809 | 7233a337ba4237dfe08d47d72a9a3ba9cde36a5e | #Copyright 2010 Thomas A Caswell
#tcaswell@uchicago.edu
#http://jfi.uchicago.edu/~tcaswell
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 3 of the License, or (at
#your option) an... |
16,810 | 239ab87d3065e6d7280a89d313d0ea3f6f81d19c | import random
import numpy as np
from sklearn.metrics import roc_auc_score
import pandas
from tqdm import tqdm
# from tut
import ujson as json
import node2vec
import networkx as nx
from gensim.models import Word2Vec
import logging
import random
import numpy as np
from sklearn.metrics import roc_auc_score
# from tut
de... |
16,811 | 71d4a9dc57be7fc542311a0810c631ba7b51ea6d | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import re
import string
with open('1.txt','r',encoding='utf-8') as f:
string = f.read()
def Find(string):
# findall() 查找匹配正则表达式的字符串
url = re.findall(r"https://ftopx.com/pic/1920x1080(.+?)\"", string)
new_li1 = list(set(url))
str1='\n'.join(new_li1)... |
16,812 | ae95a0bbe55f3f3ce5441437d34dc6be1d8041bb | import pytest
import time
import math
from selenium import webdriver
@pytest.fixture(scope="function")
def browser():
print("\nstart browser for test..")
browser = webdriver.Chrome()
yield browser
print("\nquit browser..")
browser.quit()
@pytest.mark.parametrize('numbers', ["236895", "236896", "23... |
16,813 | 20b4a709a1ea17515562a3fd0b74859653390a77 | import rospy
from colab_reachy_ros.srv import Speak
def say_something(sentence: str):
rospy.wait_for_service("/speak")
speech_service = rospy.ServiceProxy("/speak", Speak)
speech_service(sentence) |
16,814 | e89cde63736d073818bf363950de6a3a77341c86 |
s = input('请输入数字:')
x = int(s)
print("结果是:",x*2)
print(1,2,3,4) # 1 2 3 4
print(1, 2, 3, 4, sep=' ')
print(1, 2, 3, 4, sep='#')
print(1, 2, 3, 4, sep=' ', end='\n')
print(5, 6, 7, 8, end='')
print("AAAAAA",end='')
s = input('请输入第一个数字:')
x = int(s)
y = int(input('请输入第二个数字:'))
print('和为:',x + y)
print('积为:',x * y)
... |
16,815 | b707c5bfc810611a5c7cb7fa8e3296937c179ae5 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from rest_framework import status
from django.test import TestCase, Client
from django.urls import reverse
from FHLBuilder import models as db
from FHLBuilder import serializers as ss
from FHLBuilder import collection, choices
# Create your... |
16,816 | 3e4e1499350cbc156640fc63b55a47f459b95060 | import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import random
def sp_noise(image,prob):
output = np.zeros(image.shape, np.uint8)
thres=1-prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn=random.random()
if rdn<prob:
... |
16,817 | 0084c18006ab4ff8c1f8e33cbc2e67c35482d72c | import os
import pickle
from random import shuffle
from argparse import ArgumentParser
from collections import namedtuple
Data = namedtuple('Data', ['x', 'y', 'pos', 'total'])
def process_command():
parser = ArgumentParser(description="Combine small bins into a large bin.")
parser.add_argument(
'--sr... |
16,818 | bdea0dafdf9a9e828ee73ed046bb0782ddccd267 | from __future__ import division
import random
from deap import creator, base, tools, algorithms
import os
import time
import config
import melody
import write
import miditotxt
import discriminator
def evaluate(individual):
global tim
config.listToConfig(individual)
config.init()
x = 0
... |
16,819 | 800b3ebe53323ec3c08f0bbc4da66d9c674dea73 | from fastapi import FastAPI
from fastapi_utils.openapi import simplify_operation_ids
from pydantic import BaseModel, Field
from typing import Optional
from enum import Enum
from domain.security.command import login
app = FastAPI()
class Result(BaseModel):
status: str
class Empty(BaseModel):
pass
class AddT... |
16,820 | f8bcd663b293776f61809a9c704317590c741468 | # Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# Your algorithm's runtime complexity must be in the order of O(log n).
# If the target is not found in the array, return [-1, -1].
# Example 1:
# Input: nums = [5,7,7,8,8,10], target = 8
# Ou... |
16,821 | ebbd1d1abc43ad318ed2438f653e0e1681eb3569 | # coding: utf-8
"""
Daraa
This data store is offered by CubeWerx Inc. as a demonstration of its in-progress OGC API implementation. # noqa: E501
The version of the OpenAPI document: 9.3.45
Contact: mgalluch@cubewerx.com
Generated by: https://openapi-generator.tech
"""
from __future__ import ab... |
16,822 | 343ca5cfe570dea95fda35e0912b4e66f46513e3 | print('hello')
def create_cars(canvas, window, scale):
cars=[]
window_bottom=window.winfo_height()
window_top=0
window_left=0
window_right=window.winfo_width()
road_center=window_right/2
road_width=window_right/6
NUM_WIDE=4
NUM_TALL=3
car_w=road_width/NUM_WIDE
... |
16,823 | 4d46a937e9b652e36e95e01489793fd14e4c1e6e | import socket, struct
import telnetlib
def readline(sc, show = True):
res = ""
while len(res) == 0 or res[-1] != "\n":
data = sc.recv(1)
if len(data) == 0:
print repr(res)
print "Server disconnected"
exit()
res += data
if show:
... |
16,824 | 8da89c0eaac1021cacc29882f7e7a7c5f69423b3 | import pickle
import os
def output_cache(cc):
""" output results to a pickle serialized file. """
out_file = os.path.join(cc.scene_dir, 'output', cc.scene_id+'_pickle')
if cc.atmo_src == 'narr':
out_file += '_narr'
elif cc.atmo_src == 'merra':
out_file += '_merra'
with open(out_f... |
16,825 | d73ed3c3c3716f790386bf989dda084b8f29e77c | from rest_framework.viewsets import ModelViewSet
from .serializers import AnnonceSerializer
from .models import Annonce
class AnnonceViewSet(ModelViewSet):
serializer_class = AnnonceSerializer
queryset = Annonce.objects.all()
|
16,826 | 9ad45daee671bd9dee89e7ae60a18cd4e64f880e | import sys
sys.path.append('./')
import os
import numpy as np
import cv2
from config import cfg
from utils.image_reader_forward import Image_reader
class Pic_vedio():
def __init__(self):
self.reader=Image_reader(img_path=cfg.img_path,label_path=cfg.label_path)
self.vedio_dir=cfg.vedio_dir
se... |
16,827 | 139d0f53d0fa5f34b7bc10f5ef871aacbb70b2a9 | #!/usr/bin/env python2
# coding: utf-8
import re
import uuid
from .idbase import IDBase
from .idc_id import IDCID
from .idc_id import IDC_ID_LEN
SERVER_ID_LEN = 12
def _mac_addr(s):
s = str(s)
if re.match("^[0-9a-f]{12}$", s) is None:
raise ValueError('server id mac addr must be 12 char hex, but: {s... |
16,828 | 1e7c070c1314372a95cbbc792dba4fe7796da30b | import torch.nn as nn
class TransparentDataParallel(nn.DataParallel):
def set_best(self, *args, **kwargs):
return self.module.set_best(*args, **kwargs)
def recover_best(self, *args, **kwargs):
return self.module.recover_best(*args, **kwargs)
def save(self, *args, **kwargs):
retu... |
16,829 | 4e0bf8a5156df07ad0ac48611076b21422295964 | #!python
from __future__ import print_function
import unittest
######################################################################
# this problem is from
# https://www.interviewcake.com/question/python/stock-price
# Writing programming interview questions hasn't made me rich. Maybe
# trading Apple stocks will.
#... |
16,830 | 687355b0f637a9ebe2fce9cd5c576f4506569e2c | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import bandwidth as bw
from unittest import TestCase
import numpy as np
class TestBWCFfunction(TestCase):
def test_squaredband(self):
bandwidth = 7.0
central_frequency = 43.0
min_freq = 38.0
max_freq = 50.0
num_of_points = 1... |
16,831 | 3d28e3801cf3642878e3ff403a69752d4ea34f21 | def fun():
str="hye i m just try to learn python"
print(str)
print(str.replace(' ',''))
fun();
|
16,832 | 77c000bd9c236205006b69bb50bf010359a7b077 | ''' besomebody.py (c) 2013 - 2018 Matthew J. Ernisse <matt@going-flying.com>
Impersonate a variety of folks.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:
* Redistributions of source code must retain the
above ... |
16,833 | 7e66e26209663bd31a22614dc4fb0181dd0684f0 | from argparse import ArgumentParser, Namespace
from dataclasses import dataclass
from pathlib import PurePath
from core_get.actions.init.init_options import InitOptions
from core_get.options.options import Options
from core_get.cli.parse.parser import Parser
@dataclass
class InitOptionsParser(Parser):
name: str ... |
16,834 | 604d9425443be25b0e0e365f454432ebbe0dee81 | from numpy import linalg
from laika.lib.coordinates import ecef2geodetic, geodetic2ecef
from laika import AstroDog
from laika.gps_time import GPSTime
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import scipy
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import ... |
16,835 | 819fe6e51c984bc83bddba9ca1c5790e79c6f063 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'gallery.views.home', name='home'),
url(r'^login/$', 'django.contrib.auth.views.login', name="Kaleeri Login"),
url(r'^register/$', 'gallery.views.register', ... |
16,836 | 9be31b839c153683ad366be4926f9d87ba855287 | from selenium import webdriver
browser = webdriver.Chrome(executable_path="/Users/shiv/desktop/drivers/chrome/chromedriver")
browser.get("https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India")
browser.implicitly_wait(10)
# browser.maximize_window()
row = len(browser.find_elements_by_xpath... |
16,837 | 646420353380fe1a3eecdb5135f4d83ab65175a3 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-06-13 05:48
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depen... |
16,838 | f9c4b91c1ab06ea9055f42b4fad145a5a96ba331 | # /bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2020 Aljosha Friemann <a.friemann@automate.wtf>
#
# Distributed under terms of the 3-clause BSD license.
from typing import Dict
import ruamel.yaml as yaml
def load(path: str) -> Dict:
with open(path, 'rb') as stream:
return yaml.safe_load(stream... |
16,839 | 33d01b434e52b056a752f29ccfd00ba0b7d79506 | moves = int(input())
result = 0
from_0_to_9 = 0
from_10_to_19 = 0
from_20_to_29 = 0
from_30_to_39 = 0
from_40_to_50 = 0
invalid_num = 0
for i in range(1, moves+1):
num = int(input())
if num >= 0 and num <= 9:
from_0_to_9 += 1
result += num * 0.20
elif num >= 10 and num <= 19:
from... |
16,840 | 54c448465184730a522dbc94231016dc5ae15f30 | # Copyright 2018 AT&T Intellectual Property. All other 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
#
# Unless required... |
16,841 | a444db7aaa54ad3f7e1f727f587775ba1e88dd0d | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 15:05:49 2020
@author: blakeconrad
"""
import pandas as pd
import numpy as np
df = pd.read_csv("DraftKingsdata_Cleaner.csv")
import os
import pyomo.environ as pyo
from pyomo.environ import *
from pyomo.opt import SolverFactory
opt = pyo.SolverFactory('glpk')
mode... |
16,842 | 626d43c14d979001b88e50903a1b28793c6a8e9b | import os
path = '../experiment/test/results-B100'
for png in os.listdir(path):
file_path = os.path.join(path, png)
if 'x1' in png:
new_file_path = png.split('x')[0][:-1]
os.rename(file_path, os.path.join(path, new_file_path+".png"))
|
16,843 | ef267dfa1b4be7817d50f6c806500f20afbd9858 | #Copyright (c) 2018-2020 William Emerison Six
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish... |
16,844 | b9235ac55e9283bd8254168786f8cd2c8cf8541f | from argparse import ArgumentTypeError
from . import assert_conv_fails
from terseparse import types
import pytest
def test_Int():
t = types.Int(-0xF, 0x10)
t('-15') == -15
t('-0xF') == -0xF
t('0xF') == 15
t('15') == 15
assert_conv_fails(t, '-16')
assert_conv_fails(t, '-0x10')
assert_c... |
16,845 | 8b03cce1e799f0a5882fe961987990239edda6df |
def get_input_t():
inp = '''389125467'''
return [int(x) for x in inp]
def get_input():
inp = '''364297581'''
return [int(x) for x in inp]
def s2_input(inp):
for x in range(max(inp)+1,1000001):
inp.append(x)
return inp
def s1(inp,move_cnt):
cur_pos = 0
for _ in range(move_cnt... |
16,846 | 9d18079184fa0501bdf3f886a559e921c1635bb6 |
import torch
from nnet import activation
def cross_entropy_loss(outputs, labels):
"""Calculates cross entropy loss given outputs and actual labels
H(y,p) = -sum (yi * pi ) of ith element
"""
# works properly
m = labels.shape[0]
p = outputs
log_likelihood = -1*torch.log(p[range(... |
16,847 | 94346037d7cc9e628de28fb45cee82d1ce520d27 | import discord
from discord.ext import commands
TOKEN = 'NTIyNTc3NjY2Mjg1NTAyNDg0.DvNAZA.qqTVZxaJwvIcORzzK4OC0D1DuOg'
client = commands.Bot(command_prefix = 'a!')
client.remove_command('help')
players = {}
@client.event
async def on_ready():
await client.change_presence(game=discord.Game(name='Music... |
16,848 | ef16cc721605e26cb22ead8241d7cae1d8e34016 | import requests
import os
from bs4 import BeautifulSoup
def get_web_text(url):
webpage = requests.get(url)
raw_text = BeautifulSoup(webpage.text, "html.parser")
div = raw_text.find(id="gutenb").get_text()
return div
def write_into_file(text, filename, file_path):
os.chdir(file_path)
with open... |
16,849 | 3ed78bf0b4c296544cc112836f171b4b6f786f34 | # Run faster using pypy :)
# pip install pycryptodome && pip install tqdm
from Crypto.Cipher import AES
from tqdm import tqdm
with open('./provided/Readme.txt') as f:
d = f.read().split('\n')
enc_data = (
[x for x in d if 'Encrypted Data' in x][0].split()[-1].decode('hex'))
known_bytes = (
... |
16,850 | feece64d33659d6479f835fabdc4e3fcf574554d | #encoding: utf-8
import csv
def lercsv():
#Abre o arquivo csv com a lista de clientes
with open('Lista-Clientes.csv', 'rb') as f:
reader = csv.reader(f, delimiter=';')
arquivolido = list(reader)
clientes = len(arquivolido)
listapronta = [[0 for x in range(3)] for y in range(clientes)... |
16,851 | 9e8baad96472346ec0d225b546552ada7f178499 | # Generated by Django 3.2 on 2021-04-09 12:21
import datetime
import django.contrib.gis.db.models.fields
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('spot', '0001_initial'),
]
operations = [
migr... |
16,852 | 05a16f6b575be416ea51533b5ee37cafdb9b24b4 | from django.contrib import admin
from django.urls import include, path
from . import views
urlpatterns = [
path('',views.traveller, name ='traveller')
] |
16,853 | 6f875f7a093dc10c3e3ed07978c6058e43f90afc | print("Enter number of elements for list :")
n=int(input())
list = []
s=""
for i in range(0,n):
list.append(input())
s=s+list[i]
print("Is list palindrome ?")
print(str(s==s[::-1])) |
16,854 | 476e8243df8b87dcdab3f34b0e7feffff6bafc74 | # 网易财经获取的20年上证指数历史数据
# 根据当前时间前150天的历史数据,预测当天上证指数的涨跌
import pandas as pd # 引入pandas库,用来加载CSV数据
import numpy as np # 引入numpy库,支持高级大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库
from sklearn import svm # svm库
from sklearn import cross_validation # 交叉验证
data = pd.read_csv('000777.csv', encoding='gbk', parse_dates=[0], index_col=0)
... |
16,855 | 1a4d1186072a5c45bf910a5fe35ef396d047bd2c | from django.apps import AppConfig
class KhmapConfig(AppConfig):
name = 'khmap'
|
16,856 | b83af801bf5819f3d6ddbf6c6b36c5d36f75d150 | import telebot
from telebot import types
import db_users
bot = telebot.TeleBot("1299818980:AAFzO8-7l_0iKWoe2hgQopIg0Aw28BJouNM")
@bot.message_handler(commands=['start'])
def start(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("ОТЗЫВЫ")
item2 = types.Keyb... |
16,857 | 9578a89c7eb79fe2b195d50f21fbce39a8137e15 | from srht.app import db, app
from srht.objects import User
from datetime import datetime
from docopt import docopt
#Functions driving behaviour
def remove_admin(arguments):
u = User.query.filter(User.username == arguments['<name>']).first()
if(u):
u.admin = False # remove admin
db.session.commi... |
16,858 | f637fac4f16f465aa93bd132559e74c926963c8d | from socket import *
import socket, sys, threading, time, re, sqlite3
con_temp = sqlite3.connect('Users.db')
cur = con_temp.cursor()
cur.execute('CREATE TABLE Users(ID TEXT, PASSWORD TEXT)')
con_temp.close()
CRLF = re.compile(r'(.*?)\r\n')
lists = []
clients = dict()
message = {
230: '230 User logged in',
... |
16,859 | e289cdfc1fdda17be24d12f23b2933addfbd9d09 | import os
import torch
from torch import optim
from torch.optim.lr_scheduler import StepLR
from torch import nn
from torch.nn import functional as F
from tvae.data.imagenet import Multiset_Preprocessor
from tvae.containers.tvae import TVAE, TVAE_with_Preprocessor
from tvae.models.mlp import FC_Encoder, FC_Decoder
from... |
16,860 | fc7ff8f2c1be209621b9bf46fc50b5b47d53262f | # -*- coding: utf-8 -*-
from MethodHelper import *
print "// generated file"
print "#ifndef LAZYOBJECTOPERATIONDATA_H"
print "#define LAZYOBJECTOPERATIONDATA_H"
print ''
print '#include <Config.h>'
print ''
print 'BEG_METIL_LEVEL1_NAMESPACE;'
print ''
for m in methods:
if m[ 0 ] == 'O':
print 'struct Lazy... |
16,861 | 2a6dcc5c7a2505648212b48b1fd9e9cec649e933 | from master import db
from master import Viewrender
from models import *
def db_getuserByemail(email):
return User.query.filter_by(email=email).first()
def db_getuserByid(id):
return User.query.filter_by(id=id).first()
def db_getpostByid(id):
return Post.query.filter_by(id=id).first()
def db_gettags... |
16,862 | 7261567473e2ac31258f4748a15b21baf5168163 | import sys
import simplejson as json
import urllib
import traceback
import gzip
import fileinput
import re
import getopt
from datetime import datetime
FILTER_PROJECT = 'en'
LIMIT = 10
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "p:m:L:")
except getopt.GetoptError, e... |
16,863 | 3f1207de81a3a4d929408af5c8a75aeb2db08941 | from fastapi import FastAPI
from app.data.deeds import data
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, world!"}
@app.get("/deeds")
def deeds():
return get_deeds()
def get_deeds():
return data
|
16,864 | d07c38daac0d07966c8a69b6d009c4d7b44a5a1b | import numpy as np
def one_hot(labels, item_labels):
''' Create one-hot encodings for each item in item_labels according to labels
Parameters
----------
labels : list shape (M,)
list of distinct labels of which to categorize item_labels
item_labels : list shape (X,)
... |
16,865 | 29db8536589f513bb3c4a413cdd43c5beeb4fc13 | from features.AbstractFeature import AbstractFeature
from util.Settings import cmd_prefix
class OnMessageFeature(AbstractFeature):
command_str = None
def should_execute(self, message):
"""
Whether or not this feature should execute, based on the given message
"""
if self.command_str is not None:
return... |
16,866 | 9b29b57ebc073a5a6b3d309b90687d307094742f | """A simple logging routine to store inputs to the system."""
from datetime import datetime
from pytz import timezone, utc
import boto3
from flask import Flask
import gin
app = Flask(__name__)
def pst():
# From https://gist.github.com/vladwa/8cd97099e32c1088025dfaca5f1bfd33
date_format = '%m_%d_%Y_%H_%M_%S_... |
16,867 | 04be7bc1d62cead00b6a840a9de80183b1356bfc | # Generated by Django 2.2.20 on 2021-05-24 22:45
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),
('hom... |
16,868 | 445a35de705c601eca6055ff2369a2ded4f2a397 | import socket
import json
IP = {
'Node0': '192.168.2.1',
'Node1': '192.168.2.2',
'Node2': '192.168.2.3',
'Node3': '192.168.2.4',
'Node4': '192.168.2.5',
'Node5': '192.168.2.6',
'Node6': '192.168.2.7',
'Node7': '192.168.2.8',
'Node8': '192.168.2.9',
'Node9': '192.168.2.10',
'... |
16,869 | e3a08b4ec3bcce9b9a6ea91f31b93639790b1207 | import numpy as np
# hist = {'acc': [0.60170666666666661, 0.64970666666666665, 0.67247999999999997, 0.70096000000000003, 0.72831999999999997, 0.75327999999999995, 0.79210666666666663, 0.83685333333333334, 0.89738666666666667, 0.94869333333333339, 0.98768, 0.99856, 0.99978666666666671, 0.9998933333333333, 1.0, 1.0, 1.0,... |
16,870 | 5f1a4c3a03b2ef9ec08bc5af78667b8ffc79daab | import unittest
import numpy as np
from chainer import testing
from chainercv.visualizations import vis_image
try:
import matplotlib # NOQA
optional_modules = True
except ImportError:
optional_modules = False
@testing.parameterize(
{'img': np.random.randint(0, 255, size=(3, 32, 32)).astype(np.flo... |
16,871 | d67277ef7c02df3430bceb52ee5cbff6c6477b30 | """
Make a resource for the current container.
Presumes there is something in the container indicating the current
page info from Sphinx.
"""
from typing import Dict, Any
from wired import ServiceContainer
from themester.protocols import Resource, Root
from themester.resources import Document
from themester.sphinx.m... |
16,872 | 99925b0266af056d8806cd0ea97af67e25322969 | from common import *
from event import *
from rain import *
import xarray as xr
def to_netcdf(Rain_gage=None, Rain_radar=None, out_file='{site}.nc', path='', site='City', station_names=None, **kwargs):
def __do_ll(Rain, ds0):
ll = ['lat', 'lon']
if type(station_names) is list:
ll.... |
16,873 | 3ba3ee151cfcfeae2c4d1162f5d54e06a7c73e44 | import tensorflow as tf
class NonParametricModel(object):
def __init__(self, support_set):
self.support_set = tf.constant(support_set)
self.video_feature_ph = tf.placeholder(tf.float32, [1, support_set.shape[1]])
logits = tf.matmul(a=self.support_set, b=self.video_feature_ph, transpose_b=True)
self... |
16,874 | a1d2e0f78318c1ee84f0a76144c7c56213ef44e4 | def playerChoises(playerA, playerB, playerOptions) :
while True :
playerAHand = input(
playerA + " what is your option? \ntype pp for paper, st for stone or sc for scissors\n")
if playerAHand == playerOptions['paper'] or playerAHand == playerOptions['stone'] or playerAHand == \
... |
16,875 | dcdb1839a4f4dc3c6665a187b1fea6415d03f473 | import flask
from flask import request, jsonify
app = flask.Flask(__name__)
@app.route('/', methods=['get'])
def home():
return 'hello world'
if __name__ == "__main__":
app.run(debug=True) |
16,876 | 1cefa7c9e9df0477d75b15c389e48d37bd274934 | #!/bin/python
with open('DYToEE_selected_event_list.txt', 'r') as input_f:
evtlist = input_f.readlines()
nevts = len(evtlist)
print('N evts:',nevts)
nfiles = 5
print('N files to split over:',nfiles)
nbatch = nevts//nfiles
print('N evts / file:',nbatch)
for f in range(nfiles):
start = f*nbatch
stop = (... |
16,877 | 3dd28e4da31d0698c79008a856a3e0d0bbb29416 | from bottle import run, get, post, request, delete
import pandas as pd
import MySQLdb
#SQL Parameters
server = 'localhost'
db = 'mydb'
#Create the connection
conn = MySQLdb.connect(host="localhost", # your host, usually localhost
user="dassowmd", # your username
p... |
16,878 | 8fc489600771c56d9668547b5b1885f9600addd1 | #! /usr/bin/python
class InvalidInputException(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value)
def increment(number):
"""increment: list -> list
Purpose: Checks if input is valid and then calls increment helper.
This should throw... |
16,879 | 8f9c7eaaf8b80a2253924586e8a4bcf65d57b62d | import argparse
from pydoc import locate
from torch.nn import DataParallel
import utils
parser = argparse.ArgumentParser(description='Validate a experiment with different test time augmentations.')
parser.add_argument('name', help='Use one of the experiment names here excluding the .py ending.')
args = parser.parse_... |
16,880 | a1e6a087063dd5083573278039457f4b24090c58 | ###################################################################################
#
# Copyright (C) 2018 MuK IT GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either... |
16,881 | b8e7aaf6d486a7ee926375918cedbfbab51415eb |
class Cli:
def __init__(self):
pass
def start(self,command):
pass |
16,882 | f0cb3b63a82c17588622c2ff834f1a4796e205b6 | from wsmode import messages as m
class MessageCallbackHandler:
def __init__(
self,
):
self.handlers = {}
def dispatch(self, topic_message: m.TopicMessage):
topic_message_type = topic_message.__class__
handler_func = self.handlers.get(topic_message_type)
return hand... |
16,883 | 9602d1f7a48a519d7430eeca4e4c56953c795306 | # -*- coding=utf-8 -*-
import urllib3
from random import randint
class BDPing:
def __init__(self):
self.http = urllib3.PoolManager(timeout=3.0)
def get_proxy(self):
return self.http.request('GET', 'http://127.0.0.1:5010/get/').data
def delete_proxy(self, proxy):
self.http.request... |
16,884 | 8a434c4da79b716e176f24d32c4104d96b0a53ff | import json as js, spatial, os, numpy as np
from laspy.file import File
#start_time = time.time()
#print("--- %s seconds ---" % (time.time() - start_time))
def get_header(filename):
inFile = File(filename, mode="r")
header = spatial.las_header(inFile.header)
head_obj = js.dumps(header)
inFile.close()... |
16,885 | 9b663a5a76a5d3396cacf2d167bb39cb8d447a7a | #Hrček na kolesu
#Obvezna naloga------------------------------------------------------
def v_seznam(s):
if s != "":
s = s.split("; ")
i = 0
while i < len(s):
s[i] = s[i].replace(",", ".")
s[i] = float(s[i])
i += 1
return s
else:
... |
16,886 | ca4b9d8281e93607611bc86c8b80b90b16ec2e84 | #!/usr/bin/python
from db_conn import DB_Connector
class getnode(object):
def __init__(self,host):
self.hst = host
self.loc()
def loc(self):
dbconn=DB_Connector('192.168.42.112','invent','invent#123','inventory')
sql="select node from ip_node where ip='% s'" % self.hst
result=dbconn.Execute(... |
16,887 | 4049e467178376a7702aaf385808107312475986 | # MoreFourCal.py
from FourCal import FourCal
class MoreFourCal(FourCal):
def pow(self):
result = self.first ** self.second
return result
def div(self):
if self.second == 0:
return 0
else:
return self.first / self.second
a = MoreFourCal(4, 2)
print(a.sum(... |
16,888 | 490117da5dd0599a899c94d8894bad41314148ee | #!/usr/bin/env python
from dataclasses import dataclass, field
from platform import python_version_tuple
@dataclass
class Point:
x: int = field(default=0)
y: int = field(default=0)
direction: int = field(default=0)
def __repr__(self):
str_direction = ["N", "E", "S", "W"]
return f"{se... |
16,889 | b027e0552b1e488ce8024b2726d3c406203dafa0 | import pymongo
import time
client=pymongo.MongoClient(['localhost:27002','localhost:27001','localhost:27000'],replicaSet='repSetTest')
#selec the collection and drop it before using
collection=client.test.repTest
collection.drop()
#insert record
collection.insert_one(dict(name='Foo',age='30'))
for x in range(5):
... |
16,890 | 40f0df607c7a11a7a4093416c18192595045ceeb | #!/usr/bin/env python
import os
import sys
import operator
import HTSeq
def gtf_to_transcript_exons(gtf, transcript_type):
"""
Parse gtf and return a dictionary where
key: trancsript_id
value: list of exon entries
"""
gft = HTSeq.GFF_Reader(gtf)
transcripts = {}
for gtf_line in gft:
... |
16,891 | 76c40754adab57ae3656428d2ab6f9646a7fec4b | def inp(x):
return x[-1]+x[1:]+x[0]
print(inp("abcd")) |
16,892 | 16c3c2469b6f31aae5220c7c2ad830d196c5c0fc | #!/usr/bin/env python
import time
import webapp2_extras.appengine.auth.models
import webapp2_extras.appengine.sessions_ndb
from google.appengine.ext import ndb
from google.appengine.api import memcache
from webapp2_extras import sessions, security
import logging
class Session(webapp2_extras.appengine.sessions_ndb.Se... |
16,893 | f5d006445b21badfbc198705a417a243e213f003 | import random
from game import constants
from game.point import Point
from game.control_actors_action import ControlActorsAction
from game.draw_actors_action import DrawActorsAction
from game.handle_collisions_action import HandleCollisionsAction
from game.move_actors_action import MoveActorsAction
from game.arc... |
16,894 | c846640a33f54a33938e20d50e336fc134fff632 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 3 12:21:21 2017
@author: HonkyT
Snake vector thingy!!
"""
#5 4 3
#6 1 2
#7 8 9
#while counter<tal:
def snakefunction(tal):
#initialize variables on the number 3
###############################
counter=3
x_idx=1
y_idx=1
varv=2 #or 'circl... |
16,895 | 66f2f9670dfa862646060c06735481b795986934 | from input import input
from tools import *
from output import output
def main():
_input = input("map_2.input")
closest_factories = create_closest_dicts(
_input.mines, _input.factories, _input.dict_mines_factories
)
all_drones = _input.haulers + _input.excavators + _input.miners
closest_... |
16,896 | 103be797a94a84d8b1ffc353b87a28f82d755f3b | import gspread
from oauth2client.service_account import ServiceAccountCredentials
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
import time
import sys
from PyQt5 import QtCore, QtGui, QtWidget... |
16,897 | 244117abc7ef1ff846acce723363020f0c1e286b | import requests
import json
import time
import os
import base64
import cv2 as cv
from requests.exceptions import Timeout
def encode_img(str_img_path):
img = cv.imread(str_img_path)
_, imdata = cv.imencode('.JPG', img)
byte = base64.b64encode(imdata).decode('ascii')
del (img)
del (imdat... |
16,898 | 48fe96efa3016bde5245bc98bbec66fd0e2eae67 | import cv2
import numpy as np
img = cv2.imread('./img/house.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gftt =cv2.GFTTDetector_create()
keypoints = gftt.detect(gray, None)
img_draw = cv2.drawKeypoints(img, keypoints, None)
cv2.imshow('GFTTDectector', img_draw)
cv2.waitKey(0)
cv2.destroyAllWindows() |
16,899 | bb08a0b6c131393c91d97d0ce843813df1030afb | #!/usr/bin/env python
# $Id: report_client.py 174393 2018-03-13 16:40:03Z kbu $
#
# Copyright (C) 1990 - 2009 CONTACT Software GmbH
# All rights reserved.
# http://www.contact.de/
"""
report client implementation
"""
import io
import os
import pickle
import shutil
import traceback
from cdb import CADDOK
from cdb impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.