index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
987,300 | ac806ebc71c159a119c078beac48856480f611fb | b = []
for i in [2,3,4]:
a = i *3
b.append(a)
print(sum(b)) |
987,301 | 8d185a319ae34754b7a0bd3ff1cc58a329a3ef6f | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0011_posts_user_contacted'),
('accounts', '0014_iptracker_interest_count'),
]
operations = [
migrations.Rem... |
987,302 | 69492fbbc065381ee13bcf7b92e50b245a7e1250 | from .state import *
class Task:
def __init__(self,script,targets,timeout=5,state=WAITNG):
self.script = script
self.targets = [ [agent,WAITNG,''] for agent in targets]
self.state = state
self.timeout = timeout |
987,303 | 508acb60d047202c8ca9886c0dc7bb52af1136ca | import threading
import requests
from queue import Queue
from bs4 import BeautifulSoup
import time
class ThreadCrawl(threading.Thread):
def __init__(self, crawler, blogQueue, dataQueue, header):
super(ThreadCrawl, self).__init__()
self.crawler = crawler
self.blogQueue = blogQueue
s... |
987,304 | 7ae3c7fdb6eb8504e116fa6f727ecb4f277c5285 | from typing_extensions import Self
from stripe.api_resources.abstract.api_resource import APIResource as APIResource
class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid: str, **params) -> Self: ...
def save(self, idempotency_key: str | None = ...) -> Self: ...
|
987,305 | 17a35d326afe42cba1756192d402e24ba1c36fed | from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.sum_basic import SumBasicSummarizer
from sumy.parsers.plaintext import PlaintextParser
from .normalization import STOP_WORDS, stemmer
def sum_basic(text, config={'summary_length': 1}):
summarizer = SumBasicSummarizer(stemmer.lemmatize)
summarizer... |
987,306 | a13f58aa8b24cc2796c1bda66f9cea19b5584c58 | import json
import re
import bottle
import sqlitedatastore as datastore
@bottle.route('/')
def index_html():
return bottle.static_file('sample_06_09.html', root='./static')
@bottle.route('/file/<filename:path>')
def static(filename):
return bottle.static_file(filename, root='./static')
@bottle.get('/get'... |
987,307 | 7567847552b7250bdbc0e009b58be14db1452733 | import numpy as np
import random
from random import randint
from random import seed
## TODO: Implement this function
##
## Input:
## - dmat (np.array): symmetric array of distances
## - K (int): Number of clusters
##
## Output:
## (np.array): initialize by choosing random number of points as medioids
def random_... |
987,308 | 8407ae6aa3dabfe866ef7a16ef001ba7e097f399 | import pandas as pd
from pandas import read_csv
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
print('IMPLEMENTING ... |
987,309 | 6b3b0ac8c7790f70a9b991994106241f460dbbc5 | from fastai.vision.all import *
path = untar_data(URLs.PETS)/'images'
def is_cat(x): return x[0].isupper()
dls = ImageDataLoaders.from_name_func(
path, get_image_files(path), valid_pct=0.2, seed=42,
label_func=is_cat, item_tfms=Resize(224))
learn = cnn_learner(dls, resnet34, metrics=error_rate)
learn.fine_tun... |
987,310 | b437e5f7ec4c6079953d66b47a1db21cfc6d531b | {
'targets': [
{
'target_name': 'lib_node_activex',
'type': 'static_library',
'sources': [
'src/utils.cpp',
'src/disp.cpp'
],
'defines': [
'BUILDING_NODE_EXTENSION',
],
'direct_dependent_settings': {
'include_dirs': ['include']
},
... |
987,311 | bef39113f5058b36332bcfb113ad8276ff396604 | import os
import pathlib
from uuid import uuid4
import pytest
import panaetius
from panaetius.exceptions import InvalidPythonException, KeyErrorTooDeepException
# test config paths
def test_default_config_path_set(header):
# act
config = panaetius.Config(header)
# assert
assert str(config.config_p... |
987,312 | b13fbbf279a0763a6091b327fb027f44940ac64b | from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from selenium import webdriver
# options = webdriver.ChromeOptions()
# options.add_argument('--ignore-certificate-errors')
# options.add_argument("--test-type")
# options.binary_locat... |
987,313 | 2731046b498b9f6ceab8bf0b2626dea31f53f8dc | casa=int(input('Qual o valor da casa? '))
salario=int(input('Qual o seu salario? '))
anos=int(input('Quantos anos pretende pagar? '))
prestação=casa/(anos*12)
if prestação>(salario*0.3):
print ('Empréstimo não aprovado')
else:
print ('Emprestimo Aprovado') |
987,314 | fe032c1df849e7c7b7a87b4a4eb09b50203d57f7 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-08-14 09:29
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def slugify_title(apps, schema_editor):
News = apps.get_model('corp', 'News')
for n in News.objects.all():
n.slug = ... |
987,315 | 526225c1637e07a4ef8b42d1298dc72ba7f5fcba | #!/usr/bin/env python3
import sys
from pprint import pprint
from src import get_weather
if __name__ == '__main__':
if len(sys.argv) == 1:
sys.stderr.write('Not enough arguments\n')
sys.exit(1)
city, *_ = sys.argv[1:]
try:
pprint(get_weather(city))
except Exception:
... |
987,316 | e1bc1841cc5f8568599396e097a3f685b195c617 | import abc
from malib.utils.typing import Any
class BaseClient(abc.ABC):
def info(self, level: str, message: str, nid: str):
pass
@abc.abstractmethod
def create_table(self, primary: str, secondary: str, nid: str):
pass
@abc.abstractmethod
def send_scalar(self, key: int, tag: str,... |
987,317 | d92d20be08ea8d497f557c14e794dd65e7e85dfb | import os
import cv2
path1 = './result_fullres_4channel/'
path2 = './result_fullres_3channel/'
save_path = './final_result_fullres'
if not os.path.exists(save_path):
os.makedirs(save_path)
for file in os.listdir(path1):
image_path1 = os.path.join(path1, file)
image_path2 = os.path.join(path2, file)
img... |
987,318 | 899d6f16fd5375c70b07de4377598108543cbfa8 | # -*- coding: utf-8 -*-
# @Time : 2019/10/14 0014 20:23
# @Author :
# @FileName: demo1.py
# @Software: PyCharm
import matplotlib.pylab as plt
import numpy as np
path = r'E:\bawei\DeepLearning_1\深度一\tensorflow补充'
img = plt.imread(path+r'\1.bmp')
gravity = np.array([1., 0., 0.])
greyimg = np.dot(255-img, gravity)/2... |
987,319 | c0eeffa32a53840a8f8c75fc974908d9f4cbe227 | # from account import Account
# from current_account import CurrentAccount
# from negative_amount_error import NegativeAmountError # do we have to import all our errors to the client script?!
# from insufficient_funds_error import InsufficientFundsException
#
# barry = Account("barry", "jones", "f")
#
# # print(barry._... |
987,320 | 2025acb95f9b0d79e7671f51ec1153a02b9fc81f | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2018 Kevin Ottens <ervin@ipsquad.net>
#
# The authors license this file to You 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://... |
987,321 | 00570bc6fabeb13df85974dc2099faf631cb35c6 |
import sys
import box
class MovieHeader(box.FullBox):
def parse(self, buf):
super(MovieHeader, self).parse(buf)
if self.version == 1:
self.creation_time = buf.readint64()
self.modification_time = buf.readint64()
self.timescale = buf.readint32()
self.... |
987,322 | c8d837e06ec1372891e72ca8fa74f2ab85e1b363 | from django.contrib import admin
# Register your models here.
from weather_hour.models import City, WeatherHour
@admin.register(City)
class CityAdmin(admin.ModelAdmin):
list_display = ("code", "name", "url", "parent")
@admin.register(WeatherHour)
class WeatherHourAdmin(admin.ModelAdmin):
list_display = ("c... |
987,323 | 9a72788b6cebd2c3e2dfc76bcdb3cb3b7f9992ff | import sys
import click
import requests
from fuzzywuzzy import process
VERSION = '0.0.5'
# -h로도 help를 볼 수 있도록 한다.
OPTIONS = dict(help_option_names=['-h', '--help'])
HOST_URL = 'https://gitignore.io/api/'
FUZZY_THRESHOLD = 80
@click.group(invoke_without_command=True, context_settings=OPTIONS)
@click.option('-v', '--... |
987,324 | b7711d0e7d856f5a9ab9b3529843a0bd9ba6dabd | #! /Users/tseccull/anaconda2/bin/python
# SCRIPT THAT USES THE EXTINCTION TABLE PROVIDED FOR THE FORS@ INSTRUMENT TO CORRECT ANY EXTICNTION IN THE SPECTRUM
# CAUSED BY AIRMASS. THIS SCRIPT REQUIRES THE PRESENCE OF THE 'fors2_extinct_table.fits'FILE IN THE DIRECTORY
# CONTAINING THE SPECTRA TO BE CORRECTED.
import as... |
987,325 | 490f762f16e7e268de10194d5dd04eba4a2423f3 |
def config_samples(samples) :
import ROOT
samples.AddSample('Data' , path='Data' ,legend_name='Data, background subtracted', isActive=True, plotColor=ROOT.kBlack, isData=True )
samples.AddSample('Wgg' , path='Wgg' ,legend_name='W#gamma#gamma Signal', isActive=True, plotColor=ROOT.kRed-3... |
987,326 | 648b8fb6fa19346665c56500d12df1d574070b92 | import os
import datetime
from back_end.get_fault import faults_todb
from back_end.get_station import get_base_info
from back_end.get_status import delay_missing_to_db, get_delay_missing_list
from back_end.get_aws_value import get_aws_value, get_lastest_value
from AWSMonitor.models import MissingDelay
from back_end.ge... |
987,327 | e0b24143e33392c45e53239cc4afc3bcfe1bdfe9 | NUM_MONTHS = 12
def main():
# creating a list to hold rain info
rain = [0] * NUM_MONTHS
# Get rainfall for each month
for index in range(NUM_MONTHS):
print("Enter the rainfall for month ", index + 1, ": ", sep="", end="")
rain = float(input())
values = [rain]
ave_rain = r... |
987,328 | 2ab344d6e7f1421d50ba399e5fe1c4bb13df7117 |
##Tick Tac Toe##
from collections import Counter
from time import sleep
import random
import os
openSpaces=[]
Grid = [
0,0,0,
0,0,0,
0,0,0
]
winScenario = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7],
]
##RESET##
def reset():
clear()... |
987,329 | 5e8ec4c6a0c43901b3cc506a995684f690f9afe8 | from board import Board
import unittest
from random import choice
class Service:
'''Class that contains the method needed for performing the services required by the problem.'''
def __init__(self, board):
'''
Constructor for the Service class.
:param board: an instance of t... |
987,330 | 8c3fb69b57984d80b9266fe42fb9823471e081c8 | from timezone_field import TimeZoneFormField
from django.forms import BooleanField, CharField, PasswordInput, ModelMultipleChoiceField
from django.contrib.auth import get_user_model
from core.forms import ModalForm, create_form
from .models import DepartmentGroup
from core.forms import TagSelect
_user = get_user_mode... |
987,331 | 0ebb6bc4994eaf14601d1004df8ef874a261795c | import pygame
import os
import sys
import imgctrl as im
sys.path.append('C:\\Users\\YoungWoo\\Desktop\\git\\python-study\\src\\yw')
import yw_keyboard as key
pygame.init()
current_path = os.path.dirname(__file__)
img_path = os.path.join(current_path, "images")
background = im.ImageControl(os.path.join(img_path, 'ba... |
987,332 | 3386d69cc0095347e17817908d60835ca44a1014 | from math import exp
# the Poission distribution when:
# if we have an average of success in specific region "lambda"
# and we have specific number of scuccess in this specific region K
# them we easly apply this for our random var p(x) = (lambda ^ k) * exp(-lambda) / factorial(K)
#____________ Task _____________
# ... |
987,333 | 60e03c8a7052daf7fc13488aaf642c54d0ac5f97 | DB_NAME = 'records.db' |
987,334 | 6934ebb305ddc3824dda2e832d58b1009560106f | import subprocess
import time
import requests
from subprocess import Popen
from urllib3.exceptions import MaxRetryError
from log import log
kubernetes_connection_process = None
def kubernetes_request(query):
for i in range(0, 100):
try:
result = requests.get(query)
return resul... |
987,335 | e028238c8da2f70c35693b198f61e6f6845c86e3 | from django.db import models
from django.conf import settings
from products.models import Product
from decimal import *
from django.db.models.signals import pre_save, post_save, m2m_changed
User = settings.AUTH_USER_MODEL
class CartManager(models.Manager):
def new_or_get(self,request):
cart_id = request.... |
987,336 | 2a15b910253852e899f21e898efcfe29ab56f3b4 | import json
from salesforce_bulk import SalesforceBulk
from salesforce_bulk.util import IteratorBytesIO
from time import sleep
from salesforce_bulk import CsvDictsAdapter
import pandas as pd
import unicodecsv
import config as cfg
#Authentication
bulk = SalesforceBulk(username=cfg.USERNAME,
password=cfg.PASSWORD,
s... |
987,337 | 6d872acaca9cbd404cd949bd21ee61a358da4c9d | from torchvision.transforms import ToTensor, Compose, Grayscale, ToPILImage
from torchvision.datasets import CIFAR10
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
##################
# simple composition of transforms
transforms = Compose([ToTensor(),
... |
987,338 | a3510cbb14c9ea54d7e3786616b0edda621ca96b | from contextual_bandit import *
class ContextualEpsilonGreedy(ContextualBandit):
def __init__(self, policy_args, model_args):
super().__init__(policy_args=policy_args, model_args=model_args)
self.p = policy_args["p"]
self.decay = policy_args["decay"]
self.policy_name = "ContextualEpsilonGreedy" + "(p: {}, dec... |
987,339 | dd1621a5815ee04cf0dd81293300f13c5ea22c72 | import random,time
from autocorrect import spell
# from __future__ import division
# from __future__ import print_function
import json
import sys
import argparse
import cv2,os
import editdistance
import numpy as np
import random
import pandas as pd
import tensorflow as tf
from flask import jsonify
from keras.models i... |
987,340 | 67b94a9a7dad6dea31be596d85751c8fd56d4cbd | # Generated by Django 3.0.2 on 2020-03-23 11:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0002_company_user'),
]
operations = [
migrations.AddField(
model_name='company',
name='currency',
... |
987,341 | 25c59bcef389adc60261c732c9188789ac1e6770 | def check_sum_before_and_after_index(int_list):
"""Determine if there exists an element in the array such that the sum of
the elements on its left is equal to the sum of the elements on its right.
If there are no elements to the left/right, then the sum is considered to be
zero.
>>> int_lst = [1, 2... |
987,342 | 946db708e84c5ff80f8d6fe625b6392c63fc8552 |
# coding: utf-8
# In[2]:
import tensorflow as tf
from tensorflow.keras.layers import Dense,GlobalAvgPool2D,Input
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.models import Model
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.callbacks import EarlyStopping,CSV... |
987,343 | 6392cf728fb47d07f06a33ffc2ed67cc28e36bbb | # -----------------------------------------------------------------------------
# http://pythonhosted.org/django-auth-ldap/
# -----------------------------------------------------------------------------
from django_auth_ldap.config import LDAPSearch, PosixGroupType
import ldap
LDAP_BASE_DC = 'dc=dighum,dc=kcl,dc=ac... |
987,344 | c8e9bcc9d2557363139407595083471d5fa2f156 | from __future__ import print_function
import chainermn
def train(hyperparameters, num_gpus, hosts, current_host):
if len(hosts) == 1:
raise Exception('Exception on a single machine')
communicator = hyperparameters.get('communicator', 'naive' if num_gpus == 0 else 'pure_nccl')
comm = chainermn.cr... |
987,345 | 3af817ae4c372794628d0f550c23148c16e6be54 | from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
'''
PART II
np.radom.rand() generate a normal distribution with a \sigma^2 = 1 and
\mu = 0
'''
def cahistn(N, mu, corr_mat, BINS):
N = int(N)
normdist = np.random.multivariate_normal(mu, ... |
987,346 | 0c0c47651de01c1e6e8f9c187725f087ed18856b | from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label="Username",required=True,max_length=200)
username.widget = forms.TextInput(attrs={'class':'form-control'})
password = forms.CharField(label="Password",required=True,max_length=200)
password.widget = forms.Passw... |
987,347 | 26d8d516af09cb46cb2f68b7bc7f13a0d159e733 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from geometry_msgs.msg import Twist
from geometry_msgs.msg import PoseWithCovarianceStamped
from sensor_msgs.msg import LaserScan
import tf
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import actionlib_msgs
import math
# Ref: h... |
987,348 | 0e3f4cc1ed2d2a81928acf6c9a9915968dfc88d3 | from torch.distributions.categorical import Categorical
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import namedtuple
from tensorboardX import SummaryWriter
import torch.multiprocessing as mp
import math
import os
def run_step(env,a):
next_s,r,... |
987,349 | da880aae0bb01a28ad0293f7b8b8168e89369c1d | import random
import string
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt
from index.models import TOrder, TAddress, TUser, TShop
# Create your views here.
#======================订单页面渲染======================
def show_... |
987,350 | 14a20a28b9144603a98dee5b543c042dc1dabae1 | import json#cPickle as pickle
import cv2
import numpy as np
from sys import stdout
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint
from scipy.misc import imsave
import t... |
987,351 | 4c9ccdebe93bff970b17ae8c1f114f76928faabc | import numpy
from scipy import misc
def get_picture(paths):
address = 0
fo = open("texture","w")
for path in paths:
image = misc.imread(path,mode="RGBA")
the_shape = image.shape
new_shape = (the_shape[0],the_shape[1])
shape_array = numpy.ones(new_shape, dtype=numpy.int)
... |
987,352 | 6baf8eedbcbc433251641ec21e46b114415ebf5f | """The main module of Space Invaders game
"""
import os
import time
import random
from pathlib import Path
import pygame
from tools.asset_library import AssetsLibrary
class InputsTemp:
"""Temporary class for inputs.
"""
def __init__(self):
self.width_height = (750, 750)
def setup_display(width... |
987,353 | 8b74a182b773c829ee7f15aaeedf13a50ffc0752 | from django.contrib import admin
from Trainer.models import UserProfileInfo, Document
# Register your models here.
admin.site.register(UserProfileInfo)
admin.site.register(Document)
|
987,354 | 386de61934231cbdcad355fe86d9a1efffd4688d | from PIL import Image
import os
# Reference : https://note.nkmk.me/en/python-pillow-add-margin-expand-canvas/
def resizing():
dir_path = 'archive/images'
dir_names = os.listdir(dir_path)
for dir_name in dir_names :
if dir_name != ".DS_Store" :
file_path = f"{dir_path}/{dir_name}"
... |
987,355 | 909e52a35646a8207030d558c30c1e1255f582f0 | from microbit import *
def draw_counter(counter):
for x in range(5):
for y in range(5):
display.set_pixel(x, y, 9 if counter > 5*x+y else 0)
counter = 0
while True:
if button_a.was_pressed():
counter += 1
draw_counter(counter)
|
987,356 | 2a3b1cc04a215982e50b6829073bd13b09896b66 | from typing import Any, Optional
from httpx import AsyncClient, TimeoutException
from .....config import config
from .....exceptions import ConfigError
from ....utils import http_status_handler
from .....exceptions import HTTPException
def get_uri(uri: Optional[str]) -> str:
if not uri:
raise ConfigErro... |
987,357 | 53c5eb907860eb7b4dc22eea30063f94a93a0a94 | """ Setup python project. """
|
987,358 | 05775d40a355affc0d469888ee93da9447189954 | #!/usr/bin/python3.5
gunicorn -b :5000 -w 1 -t 120 jtyd_spider_run:app >> service.log 2>&1 &
ps x | grep jtyd_spider_run | grep -v grep | cut -c 1-5 | xargs kill -9
nohup python -m celery worker -l INFO -c 5 -A apps.celery_init.celery -B &
ps x | grep celery | grep -v grep | cut -c 1-5 | xargs kill -9
# 创建虚拟环境
vir... |
987,359 | f8fb703303876e8d2487102ae1a157ff29318c24 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import sys
# NB: This file exists for convenience in development by catching the ModuleNotFoundError condition and
# appending to the system-path. This file mimics the automatically generated CLI wrapper that the
# package-build process create... |
987,360 | e3cb5838d70458198fd70b41ee1483c55e50f5ad | """ Setup script for package """
from setuptools import setup, find_packages
with open("requirements.txt") as reqs:
requirements = reqs.read().splitlines()
setup(
name="fleetmanagement",
version="0.1",
description='Predictive model for Fleet Management problem',
author='Pau Vilar',
author_ema... |
987,361 | 35a0c16f338ff62bd52037dea4f80eca1a71c20f | """
Tests for register()
"""
from auth import register, MAX_USERNAME, MIN_PASSWORD, MAX_NAME
from data import data
from error import InputError
from helpers import expect_error
def test_long_username():
"""
Test a username that is too long.
"""
expect_error(register, InputError,
"a"... |
987,362 | 3b61138bf75faa65a905fcfd1760ad4eedff356d | import datetime
class Scroller(object):
def __init__(self, min_value, max_value, speed=None):
self.min_value = min_value
self.max_value = max_value
self._value = min_value
self._scroll_speed = (max_value - min_value) / 10 if speed is None else speed
self._scroll_start = Non... |
987,363 | bde3ca1cd001e6ede7f5cf4f63e7cfdc99c92ad2 |
def parse_roman_numeral(num):
o={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
u=[]
for i in range(len(num)):
u.append(o[num[i]])
u.append(0)
final=[]
for i in range(len(u)-1):
if u[i]>=u[i+1] or u[i]==0:
final.append(u[i])
else:
final.append... |
987,364 | a499b1f7f8dbd452391683b5ba2c4b37290340c1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
After eating chocolate bars your whole life, you’ve decided to go on a quest to
find the greatest chocolate bar in the world.
You’ve found a website that has over 1700 reviews of chocolate bars from all
around the world. It’s displayed in the web browser on this page... |
987,365 | 5bbce88095f718102431b165ef922d567cd48950 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from dnc_msgs/Cmd_WF.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class Cmd_WF(genpy.Message):
_md5sum = "d06405f78ad4d1752ebdd64f2ef906dc"
_type = "dnc_msgs/Cmd_W... |
987,366 | 7e4ac3088bcbb1b73e28270fd1ce5ca9ac9a229b | #encoding: utf-8
__author__ = 'Jon'
import tornado.web
import tornado.ioloop
import tornado.escape
import requests
from tornado import gen
from tornado.options import options, define
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from bs4 import BeautifulSoup
from pp... |
987,367 | 6561fd61fcf043196f076d4478de19d0f6c85a95 | from tkinter import *
from tkinter import ttk
from ttkthemes import themed_tk as tk
import mysql.connector
import tkinter.messagebox
rootl = tk.ThemedTk()
rootl.get_themes()
rootl.set_theme("radiance")
rootl.title("Module Registration System")
rootl.iconbitmap(r'images/upes.ico')
mailL = StringVar()
pwordL = StringV... |
987,368 | b065636756707b7f6af90ce47ad9fc781d416ffe | '''
roommanger to optimize user room mapping
'''
from models.roommap import Roommap
import datetime
class RoomManager():
def __init__(self, database, sensorManager):
print("init Roommanger")
self.DB = database
self.sensorManager = sensorManager
def checkRoomManagerEntrys(self):
... |
987,369 | 01af81388a50bb703183d0110dccfd1a67734575 | if __name__ == '__main__':
number = int(input("Input = "))
stars = 1
spaces = (2 * number) - 2
for _ in range(number): # top half
for _ in range(stars):
print('*', end="")
for _ in range(spaces):
print(' ', end="")
for _ in range(stars):
print... |
987,370 | fd91e978aedfd296e55b298e403d355ddbd5673b | import torch.nn as nn
import MyResNet
import torch
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.cnn = MyResNet.resnet50(pretrained=True, num_classes=100000)
def forward(self, image):
x = self.cnn(image)
return x
... |
987,371 | 9744874ef5c63383bfca50ab7e19e88a01452ea2 | #manipulando string
texto = 'Técnico em Desenvolvimento de Sistemas'
print(texto)
#EXEMPLO DE FATIAMENTO DO CONTEÚDO
print(texto[3])
print(texto[0:15])
#STRING
print(len(texto)) #conta a quantidade de caractere
print(texto.upper()) #escreve tudo em maiúsculo
print(texto.lower()) #escreve tudo em minúsculo
print(te... |
987,372 | ac63ef9f9156df5d90f8b2c4088035ee7706313d | import json
from collections import deque
from importlib import import_module
from CLE.config import ANCHOR_STATE_IDLE, ANCHOR_STATE_CONFIGURED, ANCHOR_STATE_WORKING
from CLE.ds.coap_client import set_config, set_state, popqueue
# from CLE.ds.sql import objects as db_objects, AnchorModel, DefaultConfigModel, AnchorRe... |
987,373 | d65735afce594deb4fa7f08b4b338269c6cff59a | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas import DataFrame,Series
s1 = Series(np.random.randn(1000))
sns.distplot(s1,hist=True,kde=True,rug=True) #rug下方的线代表密度
sns.kdeplot(s1,shade=True) #shade 填充
|
987,374 | f3a6553a0567d2696c3e278c74d1b3e216f02738 | from appium.webdriver.common.mobileby import MobileBy
from page.base_page import BasePage
from page.edit_member_page import EditMemberPage
class AddManuallyPage(BasePage):
# def __init__(self, driver):
# self.driver = driver
def click_add_manually(self):
# self.driver.find_element(MobileBy.X... |
987,375 | 160bfce80d1a32a16451f229abe5e9ca2509eac0 | import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self,
vocab_size,
embedding_dim,
embedding_weight,
hidden_size,
num_layers,
output_size):
super(LSTM, self).__init__()
... |
987,376 | 4e6d9cb8e0c02cc2ead63e52a5e4cc08b3a8c057 | d = {100: "theja", 200: "ravi", 300: "shiva", 400: "ram", 500: "sri"}
print(d)
del d
print(d)
# {100: 'theja', 200: 'ravi', 300: 'shiva', 400: 'ram', 500: 'sri'}
# Traceback (most recent call last):
# File "/Code/venv/dict/11DeleteDict.py", line 4, in <module>
# print(d)
# NameError: name 'd' is not defined
|
987,377 | ac002386ab8ab92b9009c8fd715d8b172ba00cc8 | # Given 2 singly linked lists, return an intersecting node if they are intersecting (by reference)
# Example:
# Input: 5 -> 4 -> 12 -> 7 and 9 -> 12 -> 7
# Output: 12 (this node exists in both lists)
# Idea: If there is an intersection node, then it will have the same value and same next.
# That means all nodes af... |
987,378 | e7b4531753199cb09c5cb6e0963cc9c6e1e379bc | from collections import OrderedDict
import mock
from paperspace.commands.common import CommandBase
output_response = ""
class TestBaseClass(object):
def test_json_print(self):
global output_response
output_response = ""
def log_to_var(message):
global output_response
... |
987,379 | 479de1d1a68273f72765c5dcc0cc5c3fa3e2c86a | # Usage:
# Run the script from a folder with file "all.mbox"
# Attachments will be extracted into subfolder "attachments"
# with prefix "n " where "n" is an order of attachment in mbox file.
import mailbox, pickle, traceback, os
from email.header import decode_header
mb = mailbox.mbox('all.mbox')
prefs_path = '... |
987,380 | f4281692b8d6348b6b42957b3bebb5178cf4a70d | '''
Football Selection
The head coach for the football team requires several players for the upcoming tournament. He asked N students to stand in increasing height order to make his selection process easier. But the students had a different plan; some of the students were not interested in playing football so they plac... |
987,381 | d620fee8b9a521b77a285018801eca4a25bdfae2 | from scipy.io import loadmat
from matplotlib import pyplot as plt
from sklearn.preprocessing import normalize
data = loadmat('/tmp/params.mat')
cmap = 'coolwarm'
plt.figure(2)
heatmap_U = plt.pcolor(normalize(data['U'], norm='l1', axis=1), cmap=cmap)
plt.show()
|
987,382 | ee35b05aabaa9cf8761fff0f9529d7320f4fc029 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 14:48:45 2019
@author: pengy10
"""
import pandas as pd
## Different sets of simulation runs
Model_list = ["ModelA", "ModelB", "ModelC", "ModelD", "ModelD_gromacs_run1", "ModelD_gromacs_run2"]
for file_name in Model_list:
## unbound state ... |
987,383 | 8f6f1c0d061286714082808561826191e60c5e1b | def quick_sort(array):
if len(array) <= 1:
return array
else:
pivot = array.pop()
highest = []
lowest = []
for i in array:
if i < pivot:
lowest.append(i)
else:
highest.append(i)
return quick_sort(lowest) + [pivot] + quick_sort(highest... |
987,384 | e8f3afd9bdb02341bafbc397932fdb6541d87b8b | def my_max(a,b):
return a if a>b else b
print('a'<'b')
def my_abs(a):
return a if a>0 else -a
print(my_abs(-9))
def my_sum(a):
t=[]
for i in range(a+1):
for j in range(a+1):
if(i+j == a):
t.append(i)
t.append(j)
return t
# for i in range(... |
987,385 | 8710364d5051c84fd42839a0c3f7a4ed0e6c5378 | #!/usr/bin/env python
import pgp_survey
import re
surveys_directory = "surveys"
# Input trait surveys and list of traits.
trait_surveys, trait_survey_traits = pgp_survey.get_trait_surveys(surveys_directory)
# Input participant survey.
participant_survey = pgp_survey.get_participant_survey(surveys_directory)
for hu... |
987,386 | 1962908d549cc0ee17cf7fab9d0dffaadaf08f7c |
class PreHelper(object):
def maxCV(array):
return array[1] |
987,387 | 0a419a1912b50b81e59aa47b561cdbab7251d370 | import pandas as pd
from definitions import ROOT_DIR
def purchase_init(purchase_path):
df_purchase_full = pd.read_csv(purchase_path, parse_dates=['buytime'])
df_purchase_full['buytime'] = pd.to_datetime(df_purchase_full['buytime'].dt.strftime("%Y-%m-%d"))
# get purchase feature
df_purchase_full = df_p... |
987,388 | f12fc1cff528428916eca3404ad45db3f7e7d15e | # -*- coding:utf-8 -*-
from collections import Iterable,Iterator
class MyRange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
re... |
987,389 | b06c38a8c90707f49fd2d3037491e6a9a8e53116 | class Solution:
# roman specility
# 1 minus has only previous one IV, IX
#
def romanToInt(self, s: str) -> int:
roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
num = 0
prev = 0
for i in s[::-1]:
cur = roman[i]
if prev > cur:
... |
987,390 | c0913078067ad5fb8efe70afa9bf14fc6eb6ba89 | import numpy as np
import cv2 as cv
def Threashold(img,l,r):
rows,cols =img.shape
newMatrix=[[] for i in range(rows)]
for i in range(rows):
for j in range(cols):
newMatrix[i].append(Change(img[i,j],l,r))
return np.array(newMatrix)
def Change(val,... |
987,391 | 4afb8bd6d1e98d5c119899f785c42804dec7126e | import numpy as np
from root_numpy import root2array, tree2array
import h5py
def x_arr(filename, tree, branch, cols):
arr = root2array(filename, tree, branches=[branch])
print arr.dtype.names
x = np.array([np.concatenate(x).astype(np.float32).reshape(-1,cols) for x in arr])
x = np.squeeze(x)
return x
hcal... |
987,392 | 9005586d670025a50fa46f9f4cf439e469830bbe | from FlatlandModel import FlatlandModel
import numpy as np
from enum import Enum
from pedsim_msgs.msg import Ped, InteractiveObstacle
class PedsimWaypointMode(Enum):
LOOP = 0
RANDOM = 1
class PedsimAgentType(Enum):
ADULT = 0
CHILD = 1
ELDER = 2
VEHICLE = 3
SERVICEROBOT = 4
class Interacti... |
987,393 | ceee41bfccb568ee4d3611a0a31f3a83364d277a | def quarter_of(month):
if month in range(4): return 1
elif month in range(4,7): return 2
elif month in range(7,10): return 3
else: return 4}
|
987,394 | 486389cc4c471a24839de6f4bcba225322a9601f | from cgi import escape
from collections import defaultdict
from boto.ses import SESConnection
def first_nonzero_index(input_list):
for i, item in enumerate(input_list):
if item != 0:
return i
return -1
def last_nonzero_index(input_list):
reversed_list = input_list[::-1]
index = ... |
987,395 | a1d732908c75407f73a3db73985d8e50cadc2b61 | '''
Created on 12 nov. 2017
@author: mbl
'''
#from pyAudioTracking import pyAudioTracking
#from time import strftime, localtime
import sys
#import unicodedata
import locale
class pyAudioInputList(object):
'''
open, parse, getline from text file
'''
def __init__(self, trackingob... |
987,396 | f6bbbffb1ca7aee996717c68934b3195bab90319 | class Produto:
def __init__(self, descricao, valor):
self.descricao = descricao
self.valor = valor
class Cliente:
def __init__(self, nome):
self.nome = nome
class Carrinho:
def __init__(self, cliente):
self.produtos = []
self.cliente = cliente
def... |
987,397 | 2879db94dfd44d028f08cb8d5d05c31bfaf64c47 | # Generated by Django 3.0.4 on 2021-01-27 14:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('draft', '0010_draft_code'),
]
operations = [
migrations.AddField(
model_name='draft',
name='mode',
field... |
987,398 | af44bbe45f6e0ec217beeca79be59d0cb0f11478 | from torchvision import models
from backbones.octConv_ResNet import oct_resnet26, oct_resnet50, oct_resnet101, oct_resnet152
from backbones.SENet import senet154, se_resnet101, se_resnet152, se_resnext50_32x4d, se_resnext101_32x4d
from backbones.efficientnet import EfficientNet
def set_parameter_requires_grad(model, f... |
987,399 | 8762ae3d53dc3e8a1d1766470935fc24635c430f | # 6.4.1.py | ian luna
for x in range(5, 80, 5):
print(x, end =' ')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.