index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
992,000 | db8772b88f62f0b4efe6ea71e9fda7ee47508346 | #!/usr/bin/env python
# coding:utf-8
# date: 2016-03-29
# author: dudp@foxmail.com
import re
import urllib
import urllib2
import cookielib
import mechanize
from bs4 import BeautifulSoup
login_url = 'https://login.salesforce.com'
home_page = 'https://na7.salesforce.com'
cookie_file = './.cookie'
username = 'xxxxxxxx... |
992,001 | 0cc5ea60c9040b1c368b7ffa34fd2574d31369c2 | """
python 的深浅拷贝
"""
#1. python 默认的赋值是浅拷贝,如对列表的赋值
In [1]: s = [1,2,3]
In [4]: s2 = s
In [7]: s2[0]= 2
In [8]: s
Out[8]: [2, 2, 3]
# 修改s2的元素会影响s的元素值
#2. [:]运算对不可变元素是深拷贝
In [10]: s
Out[10]: [2, 2, 3]
In [9]: s2 = s[:]
In [11]: s2[0]= 1
In [12]: s
Out[12]: [2, 2, 3]
# 此时对s2的修改不影响s的值
#3. [:]运算对可变元素是浅拷贝
In [13]: s = [1,2,... |
992,002 | 062427f010eb903475ed0df6854b71f950754f8d | from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from time import localtime, strftime
from datetime import datetime
from django.utils.crypto import get_random_string
from models import *
# Create your views here.
products = {
'1001': 19.99,
'1002': 24.99,
'1003': 4.99,
'1... |
992,003 | 45d8046fcc653864251029dcef81ad84b37bb10d | import sys
from collections.abc import Callable
from typing import Any, NamedTuple
from typing_extensions import TypeAlias
__all__ = ["scheduler"]
_ActionCallback: TypeAlias = Callable[..., Any]
if sys.version_info >= (3, 10):
class Event(NamedTuple):
time: float
priority: Any
sequence: i... |
992,004 | 2f6a18b378324c9e28d2e403b209a0d8e609f426 | version https://git-lfs.github.com/spec/v1
oid sha256:d68868d80e258d863e342461e21b8bda846eb4ad92f54f4b6a088c0c87fe9d5e
size 959
|
992,005 | 1e8c78ed0b57b707626b1a815eca292813c29d10 | # Generated by Django 3.1.5 on 2021-01-20 17:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('pages', '0001_initial'),... |
992,006 | 9e3ab97ea6462a1a00006528bed00a7cae892805 | from pymongo import MongoClient
client= MongoClient('localhost', 27017)
db=client.db_cek
def delete_all():
# 데이터베이스 안에 있는 것들을 모두 지운다.
db.orders.delete_many({})
def main():
delete_all()
if __name__=='__main__':
main() |
992,007 | e631ab71328ad420210671066913bdacce5279bf | #-*-coding:utf-8-*-
import os
import sys
import numpy as np
import cv2
from PIL import Image
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
class NumberRecognizer(object):
"""숫자 인식 클래스.
위 숫자 인식 클래스의 기능으로는
1) 학습용 숫자 이미지 전처리
2)
... |
992,008 | 4b9e6fdb28ed98241da22101cc68db5a16808fdf | #
# @lc app=leetcode.cn id=697 lang=python3
#
# [697] 数组的度
#
# https://leetcode-cn.com/problems/degree-of-an-array/description/
#
# algorithms
# Easy (60.62%)
# Likes: 349
# Dislikes: 0
# Total Accepted: 62.2K
# Total Submissions: 102.6K
# Testcase Example: '[1,2,2,3,1]'
#
# 给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任... |
992,009 | 37f2c02d4030627e89929cf041c4c235dbd30958 | import torch
import torch.nn as nn
from pykp.masked_softmax import MaskedSoftmax
class RNNEncoder(nn.Module):
def __init__(self, vocab_size, embed_size, hidden_size, num_layers, bidirectional, pad_token, dropout=0.0):
super(RNNEncoder, self).__init__()
self.vocab_size = vocab_size
self.emb... |
992,010 | a2d0e9066784174706f6f3f67bdd7ad7fcafa7e1 | # Created by Justin Lowe
import pyodbc
import csv
connection = pyodbc.connect("Driver={SQL Server Native Client 10.0};"
"Server=PETEST,1433;"
"Database=PEWarehouse;"
"Trusted_Connection=yes;")
#Trusted connection to force AD authentication.
cursor = c... |
992,011 | 2919a119611035c1f410e5b6371055066194d4c4 | import unittest
from homework7852.process_covid import (load_covid_data,
cases_per_population_by_age,
hospital_vs_confirmed,
create_confirmed_plot,
count_high_r... |
992,012 | 8630a2b99ef6180526b33211d39c170bde50477a | import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
from torch_model_base import TorchModelBase
import utils
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2022"
class TorchShallowNeuralClassifier(TorchModelBase):
def __init__(self,
hidden_dim=50,
... |
992,013 | a946d4fe5c1d33732ba4378c16e8e595132fe63d | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
992,014 | 2547d444750950223d15c839502367879d83c27c | #!/usr/bin/env python
from resource_management import *
# server configurations
config = Script.get_config()
ds_password = config['configurations']['freeipa-config']['freeipa.server.ds.password']
admin_password = config['configurations']['freeipa-config']['freeipa.server.admin.password']
master_password = config['con... |
992,015 | 0f3b7aabdcc7b907764bfa2fd1a8136854d29a16 | import unittest
import numpy as np
from day8 import split_to_layers, corruption_check, decode_image
class MyTestCase(unittest.TestCase):
def test_splitter(self):
data = [1,2,3,4,5,6,7,8,9,0,1,2]
layers = split_to_layers(data, 3, 2)
self.assertEqual(2, len(layers))
self.assertEqual(... |
992,016 | 0679311d0218ac077d0a57702c288dbc32c77b98 | import torch
import random
import cv2
import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple, deque
class ReplayMemory(object):
def __init__(self, max_size, batch_size, seed, device):
'''Initialise a Replay Buffer
max_size: max size of buffer
batch_size: si... |
992,017 | fda664c7e505d8362fbc9908f3e38a9fa1d2651a | # Generated by Django 2.1.2 on 2018-10-29 07:31
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20181029_0729'),
]
operations = [
migrations.AlterField(
model_name='housede... |
992,018 | cfd2ff89c8cfd0db3f419c8529b8091721f1acc6 | '''import urllib.request
from bs4 import BeautifulSoup
import re
import time
import random
class CommanClass:
def __init__(self):
self.header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
... |
992,019 | 7e4a8902e3668ed1701112ccb587a168456058b9 | # -*- coding: utf-8 -*-
"""Implements stereo camera calibration and rectify/undistort with a pair of CalibratedCamera objects.
"""
import cv2
import numpy as np
from .base import *
from .calibratedcamera import PinholeCamera
from EasyVision.vision import PyroCapture
import threading as mt
class StereoCamera(namedtu... |
992,020 | 8fcdbdc374e9c11e080432f0fc801becd35693aa | import numpy as np
def logmae(y_pred, y_true):
return np.log(np.max(np.abs(y_true - y_pred),1e-9))
|
992,021 | 5997d4b6b0c5f92bf36221a686fe721e264d0953 | #!/usr/bin/env python
# encoding=utf8
from __future__ import print_function
from flexbe_core import EventState, Logger
import rospy
from wm_nlu.srv import HKGetRoom
from std_msgs.msg import String
class SaraNLUgetRoom(EventState):
'''
Use wm_nlu to parse a sentence and return a room
># sentence string... |
992,022 | 9db2b10736b873451e517bafdda95f3cd19caf70 | users = {
"12": "Alice",
"11": "Sasha",
1:"Masha"
}
key = "11"
user = users.pop("12")
print(users)
user = users.pop("1123374631", "Unknown")
print(user)
users.clear()
print(users)
|
992,023 | 1047fffa5ee7f537b9f7660526423ca79f8a4af0 | import imp
import argparse
import os
import gamesman
import random
def main():
parser = argparse.ArgumentParser(description='Play games')
parser.add_argument('game', help='The path to the game script to run.')
arg = parser.parse_args()
name = os.path.split(os.path.splitext(arg.game)[0])[-1]
game = imp.load_source... |
992,024 | 38da98c8462ae4bcd4f6e46f577115af73258783 | from enum import Enum
import pygame
from sprites import make_outline_splites
from group import Group as MyGroup
class Screen(Enum):
START = 0
CHARACTER_SELECT = 1
STAGE_SELECT = 2
GAME = 3
RESULT = 4
OPTION = 5
QUIT = 6
class BaseScreen:
def __init__(self):
if not pygame.init... |
992,025 | 181d8ea743ca36656e810d461739edf85ef00c75 | import os
import tempfile
import pytest
from server import create_app
from server.db import get_db, init_db
with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
_data_sql = f.read().decode('utf8')
@pytest.fixture
def app():
db_fd, dp_path = tempfile.mkstemp()
app = create_app({'T... |
992,026 | fc82b64b6860ac93a1654f0aa6bfdefdc8227b6c | import FWCore.ParameterSet.Config as cms
ttHFGenFilter = cms.EDFilter("ttHFGenFilter",
genParticles = cms.InputTag("genParticles"),
genBHadFlavour = cms.InputTag("matchGenBHadron", "genBHadFlavour"),
genBHadFromTopWeakDecay = cms.InputTag("matchGenBHadron", "genBHadFromTopWeakDecay"),
genBHadPlusMothe... |
992,027 | b7fc125ccd82ad2fa1da55aa0a20e95aa477512a | from setuptools import setup
setup(
name='elemental',
version='0.1',
author='Zach Kelling',
author_email='zeekayy@gmail.com',
packages=['elemental',],
license='LICENSE',
description='Simple DSL for generating html templates',
long_description=open('README').read(),
)
|
992,028 | 40bc208d7dfe12bde3079367ae28880dfd93bf59 | class Node(object):
def __init__(self, value):
self.info = value
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self):
self.start = None
def display_list(self):
if self.start is None:
print("List is none")
print("L... |
992,029 | fd68ba09eb627583d4b786520b0ae90af4612de0 | from pyjarowinkler import distance
dict_of_orcids = {}
line_count = 1
print("Starting...")
with open("17.doi_with_merged_orcid.txt", "r") as inp:
for line in inp:
print("Loading: " + str(line_count))
doi = line.split("\t")[0].strip()
orcid = line.split("\t")[1].strip()
dict_of_or... |
992,030 | 4ede490e88951390a88f1b9790dfb1d06b0fb059 | from selenium import webdriver
import time
driver = webdriver.Chrome('/Users/Karol202/PycharmProjects/chromedriver.exe')
driver.get('https://google.com')
search_box = driver.find_element_by_name('q')
search_box.send_keys('Selenium')
search_box.submit()
time.sleep(5)
driver.quit()
|
992,031 | 2e80c948b8cd415fd2cea0248cd787fa2313ce40 | # -*- coding: utf-8 -*-
# Tom van Steijn, Royal HaskoningDHV
from xsboringen.borehole import Borehole, Segment
import numpy as np
class TestSegment(object):
def test_segment_lithology(self):
s = Segment(top=0., base=10., lithology='Z')
assert s.lithology == 'Z'
def test_segment_thickness(sel... |
992,032 | f978c1e47dfa7acbffa62797ad33bda58b4e78d6 | from django.urls import path,re_path
from .views import (SearchProductView)
urlpatterns = [
path('search/',SearchProductView.as_view(),name='query'),
] |
992,033 | fca8a71570cd99f2934cd2eef5f0e5aef46ae6fc | import numpy as np
from agents.robot import Robot
from agents.obstacle import Obstacle
def test_is_colliding():
robot = Robot(
position=np.array([0, 0]),
velocity=np.array([1, 1]),
goal=np.array([10, 10]),
radius=1,
velocity_lower_bound=-1,
velocity_upper_bound=1,
... |
992,034 | b44ba31282906aa3d94943774252281d9d6366d5 | from keras.models import Sequential ,Model
from keras.layers import Dense, Dropout, Activation, Flatten, Input, merge
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
from keras.callbacks import *
from keras.preprocessing.image import ImageDataGenerato... |
992,035 | c4e126614b667186da671418ac8cccd5258851fc | from cs50 import get_int
# check if value is between 1 and 8 and if is decimal number
while True:
inp = input("Height: ")
if str.isdecimal(inp) and int(inp) in range(1, 9):
break
height = int(inp)
# print the blocks
for i in range(1, height + 1):
print(f"{' ' * (height - i)}{'#' * i} {'#' * i}")... |
992,036 | befa14851af77c0d5a1d01b14fa46256047372f0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file exists only to run NREI requests from the command line in a way that makes it easy to use code profiling
functions, independent of the user interface.
"""
import cProfile, pstats # packages for testing the execution time of model commands
import pkg_resource... |
992,037 | 59c556ade8c8abcdcb4d67d585de1c1a4cd92add | from django.http import HttpResponse
from django.shortcuts import render
from .models import Post, Like
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', {'posts': posts})
def like(request):
if request.method == 'GET':
if request.user.is_authenticated:
... |
992,038 | 0e2ce6400c536a5faba51d4d7a999a0df99cbef2 |
"""
https://leetcode-cn.com/problems/number-of-ways-to-wear-different-hats-to-each-other/solution/python-3xie-gei-zi-ji-de-chao-xiang-xi-zhuang-ya-d/
https://leetcode-cn.com/problems/number-of-ways-to-wear-different-hats-to-each-other/solution/python-3xie-gei-zi-ji-de-chao-xiang-xi-zhuang-ya-d/
https://leetcode-cn.com... |
992,039 | 941fdb1b18f71b9bb6183bc3ecb892a509a66936 | import logging, pprint, hashlib, urllib, urllib2
from webapp2_extras import json
from lxml import etree
#import pylast
import Handlers, Config
# Routines for dealing with the last.fm API.
# cf http://www.last.fm/api/
# Note, chunks of this code are based on pyLast, which
# seems like a good library, but apart from ... |
992,040 | 9607bcb756166651d3b52f784575f48d372d9f1b | print ("PYTHON TEST PROGRAM")
for i in range(3):
for j in range(1,4):
print(i+j, end="")
print
|
992,041 | dfc20d4eed3709a6c8159ec7eb96c46ca4d3f018 | #!/usr/bin/env python
PKG = 'frg_rover'
import roslib; roslib.load_manifest(PKG)
#Need this for the Msgs to work
roslib.load_manifest('frg_rover_msgs')
import rospy
import numpy
import math
from numpy import *
from std_msgs.msg import UInt16
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
... |
992,042 | 2c4248d1a0edf9a668f92b97fb533394c461d8bc | from django.core.files.storage import default_storage
from django.db.models import Q
from rest_framework import viewsets, status, pagination
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response i... |
992,043 | 939cb7f5cb13829957eabf7cd6251a39e7a74d95 | # This software is copyright (c) 2010 UTI Limited Partnership.
# The original authors are Robert A. Brown, M. Louis Lauzon
# and Richard Frayne. This software is licensed in the terms
# set forth in the "FST License Notice.txt" file, which is
# included in the LICENSE directory of this distribution.
from distut... |
992,044 | 447d048d4cdf90186b9422e6642a3259290068f4 | import webbrowser
import time
total_breaks = 5
break_count = 0
print("This program stared on " + time.ctime())
while (break_count < total_breaks):
time.sleep(10)
webbrowser.open("http://www.youtube.com/watch?v=dQw4w9WgXcQ")
break_count = break_count + 1
|
992,045 | ffc6c76fe59dd7dc6ac9847648a9798f7217b0f3 | import t2
print(t2.palindrome(2,40)) |
992,046 | 86e319b87e42e188decae67054ddbea70512fb3e | """
# Name: meas_models/models.py
# Description:
# Created by: Phuc Le-Sanh
# Date Created: Nov 16 2016
# Last Modified: Nov 23 2016
# Modified by: Phuc Le-Sanh
"""
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugette... |
992,047 | 64822b6768eb2a653602ff0653e8dfd7f4d7554a | from django.urls import path
from .views import crearFase, listar_auditoria,listar_proyectos, proyectoCancelado
from . import views
#from .views import estadoProyecto,detallesProyecto,UsersProyecto,desvinculacionProyecto,ModificarRol,VerRoles,agregarUsuarios, VerUsersEnEspera, ActualizarUser, CrearRol, crearItem,agg_li... |
992,048 | 6f6c6fa6c2657adbff69c52bacf654a8aa266756 | # Project name : HackerRank: Day 27: Testing
# Link : https://www.hackerrank.com/challenges/30-testing/problem
# Try it on :
# Author : Wojciech Raszka
# E-mail : contact@gitpistachio.com
# Date created : 2020-07-15
# Description :
# Status : Accepted (169038695)
# Tags : python
#... |
992,049 | edfed4ff5872da11b4ce81d749489d89a6501545 | import io, os, sys, requests
from PIL import Image
from picamera import PiCamera
from time import sleep
_maxNumRetries = 10
camera = PiCamera()
camera.rotation = 270
camera.start_preview()
sleep(2)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
json = None
data = open('/home/pi/Desktop/image.... |
992,050 | c2f3fb111351badd811afdfc1202934eca481c34 | from collections import deque
def get_window_max(arr, win_size):
queue = deque()
res = []
# i, j = 0, 0
# while i < len(arr) and j < len(arr):
for j in range(len(arr)):
while len(queue) > 0 and queue[-1] < arr[j]:
queue.pop()
queue.append(arr[j])
# 如果队头恰好是即将抹去... |
992,051 | 7342abc75bc49d4aeedf10f3f861a5ba0ea23362 | #!/usr/bin/env python
import os
from setuptools import setup
# Utility function to read the README file.
# https://pythonhosted.org/an_example_pypi_project/setuptools.html#setting-up-setup-py
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='netflix-spectator-... |
992,052 | b1404fdc1ea51f18a141ce5ea71c431484082d63 | import paramiko
t = paramiko.Transport(("54.72.144.20", 7515))
t.connect(username='kgawda', password=open('/home/kjg/alx_ssh.txt').read().strip())
sesja = t.open_session()
sesja.exec_command('ls -al')
dane = sesja.recv(1024)
while dane:
print(dane.decode('utf-8'))
dane = sesja.recv(1024)
# while dane := sesj... |
992,053 | 538726cb2c7c9de4da8ad5694f47abbff1d7f0ca | #!/usr/bin/env python
#Data cleasing and blacklisting is based on the logic used in
#trendingtopics.org
import sys
import os
import re
import urllib
#doing date manipulation
try:
# See if we are running on Hadoop cluster
filepath = os.environ["map_input_file"]
filename = os.path.split(filepath)[-1]
except K... |
992,054 | b4bde82cef86f8fa3c3fbd08aad3f13ed41f1a64 | from keras import initializers, regularizers, constraints
from keras.layers import *
import keras.backend as K
from keras import regularizers
from keras import Model
import numpy as np
from keras.engine.topology import Layer
def zero_loss(y_true, y_pred):
return 0.5 * K.sum(y_pred, axis=0)
class CenterLossLayer(L... |
992,055 | a2c756886a39424fe56ef694d385f121c370c320 | #Twitter API credentials
consumer_key = "zCqqTurprj78ehJTBUtoo1YTs"
consumer_secret = "voYhiXqCKSITmJZturkp2rTkzRv8tDiVeVGJmdVlcbCd8oXGDT"
access_key = "16597102-GZG4gFoqf0Kvww0z236nSzTSS92AHJy2ITidGr7m8"
access_secret = "qQfa4A4hOu3q8qfPrm9DcVCM3RCBUEniNl8BBMBrkxc8q" |
992,056 | 33519c469658d5dd4d593dde9fcab25750fe9991 | '''
Script to get menus from yelp, and save ratings
Name: Chris Hume
Date : 12/6/13
'''
import foursquare, json, requests
import logging
from bs4 import BeautifulSoup
from urllib2 import urlopen
logging.basicConfig()
##############################
#
# get the individual ratings of each item
#
###################... |
992,057 | cc98fbfdd9553cf74f919b2b04c18bab65ae61bf | import bpy
import types
from traceback import print_exc
from inspect import isfunction, ismethod
from .addon import TEMP_PREFS_ID, prefs, temp_prefs
from .constants import (
ICON_UNKNOWN, ICON_FOLDER, ICON_FUNC, ICON_PROP, ICON_NONE,
TOOLTIP_LEN, PROOT, PDOT,
get_icon)
from .utils.collection_utils import so... |
992,058 | 72c5adcb94c889c05b014e7a940a598d525cb74e | import os
import dotenv
import jishaku
import discord
from discord.ext import commands
from command.database.loader import db_load, db_loaded, client_load, client_loaded
# loading env file so that we can use it
dotenv.load_dotenv()
def main():
db_load() # loads database
db = db_loaded()
client_load()
... |
992,059 | 66bbee5e60d798ca843c08be7af5c707d3d471b4 | from django.test import TestCase
from django.core.urlresolvers import reverse
from .views import ShiftListView, ShiftListCalendarView
from .forms import ShiftForm
class TestShiftListViews(TestCase):
def setUp(self):
self.view = ShiftListView()
def test_attrs(self):
# self.assertEqual(self.v... |
992,060 | 5c70c35be76b6686a6db5b984cef8fb487581ae2 | from arm_dashboard_client import * |
992,061 | b03a42e9d1948c69d354a54962c2b097d150a44c | #!/usr/bin/env python
# coding: utf-8
# XXX License
# Copyright (C)
# In[1]:
import requests
import json
from urllib.parse import urlparse, parse_qs
from bs4 import BeautifulSoup as bs
# In[2]:
# Convert ISIN to Bloomberg ticker from Google
def isin2bbg(isin_ticker):
url = 'https://www.google.com.tw/searc... |
992,062 | f204f445f5664be208b8e7dc3e4ce348bcda3073 | import math
n = int(input())
s = math.ceil(math.sqrt(n))
h = 10**5
for i in range(1,s+1):
if n%i==0:
if h > max(len(str(i)),len(str(int(n/i)))):
h = max(len(str(i)),len(str(int(n/i))))
print(h) |
992,063 | 963d2fd520f0f6b4ced4f8b48b77da5d3e8285d5 | import ctypes
import pathlib
import os
import sys
proj_folder = pathlib.Path(f'{os.getcwd()}\{__file__}').parent
if __name__ == "__main__":
# Load the shared library into ctypes
if sys.platform.startswith("win"):
c_lib = ctypes.CDLL("./cmult.dll")
else:
c_lib = ctypes.CDLL("./libcmult.so"... |
992,064 | 9d67631eda8b9054d4c44ef904975bb2dd5a46f2 | drinks = ["espresso", "chai", "decaf", "drip"]
caffeine = [64, 40, 0, 120]
zipped_drinks = zip(drinks, caffeine)
drinks_to_caffeine = {key:value for key, value in zipped_drinks} |
992,065 | 50ce16552a65605b1f7912cb582f467b6e238826 | # -*- coding: utf-8 -*-
# 2020-04-13
# author Liu,Yuxin
'''
【问题背景】国际乒联现在主席沙拉拉自从上任以来就立志于推行一系列改革,以推动乒乓球运动在全球的普及。
其中11分制改革引起了很大的争议,有一部分球员因为无法适应新规则只能选择退役。
华华就是其中一位,他退役之后走上了乒乓球研究工作,意图弄明白11分制和21分制对选手的不同影响。
在开展他的研究之前,他首先需要对他多年比赛的统计数据进行一些分析,所以需要你的帮忙。
【问题描述】华华通过以下方式进行分析,首先将比赛每个球的胜负列成一张表,
然后分别计算在11分制和21分制下,双方的比赛结果(截至记录末尾)。
比如现在... |
992,066 | da627cd44212a67501d4a449fba87f0856af49d5 | from bs4 import BeautifulSoup
import requests
import csv
"""
Web Scrapping Example: List of Top rated bollwood film on IMDB and created CSV file of film(name, rate, and starring)
"""
url= "https://www.imdb.com/india/top-rated-indian-movies/"
response= requests.get(url)
data = response.text
soup = BeautifulSoup(data,... |
992,067 | 79f51c4c802ba03ed55fa1861a7d4bfd1f19825b | """
Domemaster3D Camera Setup Script V2.4
2018-08-21
Created by Andrew Hazelden andrew@andrewhazelden.com
This script makes it easy to start creating fulldome stereoscopic content in Autodesk Maya.
-------------------------------------------------------------------------------------------------------
Version History... |
992,068 | ea01654d46b56aa7aa8bbf3ad3ea7c0414a068a4 | class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if not nums2:
return
idx = m + ... |
992,069 | 07cf935d7a6d71c48b22be9a86cf423d76c0b08f | import glob
import sys
import cdms2 as cdms
import numpy as np
import MV2 as MV
import difflib
import pickle
#import ENSO_years_piControl as en
global crunchy
import socket
if socket.gethostname().find("crunchy")>=0:
crunchy = True
else:
crunchy = False
import peakfinder as pf
import cdtime,cdutil,genutil
fro... |
992,070 | cef731783cdc91dc3af6e8a7d0c7da6d91b59534 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
# Basic solution - 2^n O
def fib(n):
if n == 1 or n == 2:
result = 1
else:
result = fib(n-1) + fib(n-2)
return result
# In[8]:
fib(5)
# In[9]:
fib(35)
# already taking a few seconds
# In[12]:
# A memoized solution - 2n+1 O
def fib... |
992,071 | 9454b359f30e7fef6e21b4fa0e47f32e3f3a5f4d | # default feature sets
DEF_LIB_SETS = ['mfcc']
DEF_ECHO_SETS = []
# deault dataset cache capacity
DEF_CACHE_CAP = 6
# top genres of songs in small dataset
TOP_GENRES = ['Experimental', 'Electronic', 'Rock', 'Instrumental', 'Pop', 'Folk', 'Hip-Hop', 'International']
|
992,072 | 8a42190eb8d73838261aa53d8985db42e12e4093 | import sys
import time
import RPi.GPIO as GPIO
import math
# set mode to GPIO
GPIO.setmode(GPIO.BOARD)
DEFAULT_STEP_PINS = [11,13,15,19]
class MotorController():
def __init__(self,delaytime = 0.001,StepPins = DEFAULT_STEP_PINS):
self.time_delay = delaytime
self.step_pins = StepPins
for pin in self.step_pins :... |
992,073 | 5b86d992421c3fbad8b93959b77f6f65b4afed80 | __author__ = 'lanx'
import regression
import numpy as np
import matplotlib.pyplot as plt
def loadDataSet(fileName):
numFeat = len(open(fileName).readline().split('\t'))-1
dataMat=[]; labelMat=[]
fr=open(fileName)
for line in fr.readlines():
lineArr = []
curLine = line.strip().split('\t'... |
992,074 | 1419ace98160dee4aa8956e363e9a2472c991739 | # Copyright (C) 2017 Daniel Watkins <daniel@daniel-watkins.co.uk>
#
# 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 app... |
992,075 | 51eae6e001aa5fac5437402b75eb6bd416055653 | from __future__ import print_function
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import CleanData
import StudentConfidence
import OfficeHourRequests
import ConfidenceAndExtraResources
import ConfidenceAndSmi... |
992,076 | ee49494a0078a5de7b4f909970b2909416cd2b56 | import requests
from bs4 import BeautifulSoup
url = "https://www.ptt.cc/bbs/joke/index.html"
for i in range(10): #the page
r = requests.get(url)
soup = BeautifulSoup(r.text,"html.parser")
sel = soup.select("div.title a") #標題
u = soup.select("div.btn-group.btn-group-paging a") #a標籤
print ("本頁的URL為"+... |
992,077 | 7a9fa1d3cad09d207f33686994a09466f07ff0f1 | import unittest
from os.path import join, dirname, abspath
import sys
root_directory = abspath(join(dirname(__file__), '..', '..', '..', 'src'))
sys.path += [root_directory]
class TestSortingMethods(unittest.TestCase):
data_folder = abspath(join(dirname(__file__), '..', '..', '..', 'output'))
file_to_open ... |
992,078 | b6ac333c0a131069ba104d58f16be4e66ddf58be | import os
import gensim, logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
class Corpus(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
for line in open(self.filename, encoding = "utf8"):
if not ... |
992,079 | f6f93b7015142f25bc3f8812c5f32bb00358312a |
class Parent(object):
def __init__(self):
pass
def deco(fun):
def decorated(self, x):
print("Calling decorated function...")
x = fun(self, x)
print("Exit...")
return x
return decorated
@deco
def f(self, x):
raise NotImple... |
992,080 | ccc7662af76961d613d4391babacc103d2cbc19b | #! /usr/bin/python3
print("content-type: text/html")
print()
import cgi
import subprocess as sp
db = cgi.FieldStorage()
choice = db.getvalue("choice")
image = db.getvalue("image")
tag = db.getvalue("tag")
container = db.getvalue("container")
port = db.getvalue("port")
state = db.getvalue("state")
output=""
if choic... |
992,081 | 4ba70139154009d6e137fd5babf1e62f52bfdd41 | import os
import glob
#os.chdir('/home/jacob/Desktop/S.AureusCOL_seq/')
#alignment_files = glob.glob('*.aln')
#print alignment_files
#rate_out_files = '/home/jacob/Desktop/RESULT/MODULE2'
#if not os.path.exists(rate_out_files):
#os.makedirs(rate_out_files)
#with open(os.path.join(rate_out_files,alignment_files)) a... |
992,082 | 6d78607df1208fc3f47880657b0d0b007c2aacab | """
The file can generate a smooth trajectory (a list of waypoint) according to
given initial state and goal state.
The algorithm is mainly based on following publications
"Trajectory Generation For Car-Like Robots Using Cubic Curvature Polynomials",
Nagy and Kelly, 2001
"Adaptive Model Predictive Motion Plan... |
992,083 | aa49b57be62ae2b9b5b4128b9b43584390b6c5ad | #!/usr/bin/python
#-*- coding: utf-8 -*-
from lda import Collection, Dictionary, Model, Info, Viewer, utils, Word2Vec, ImagePlotter
from lda.docLoader import loadCategories
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import names
from gensim.models import TfidfModel
import os.path
from lda impor... |
992,084 | 6c08d139595331a49bed9f3a5a1702898af3e6ff |
# coding: utf-8
# # yangs - Yet Another NonoGram Solver
#
#
#
# ## Aim
#
# Solve the first part of the GCHQ Christmas puzzle using a concise, easy-to-understand Python program.
#
# ## Method
#
# The [puzzle](http://www.gchq.gov.uk/press_and_media/news_and_features/Pages/Directors-Christmas-puzzle-2015.aspx) is... |
992,085 | f73b5f34d05792638ffda6d679b73664fd170dd2 | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num=0
k=len(digits)
for i in range(k):
num+=digits[i]*10**(k-i-1)
digits=[]
if num==0:
for i in range(k):
... |
992,086 | 3496736d2d913232e982d399ae9954c802808ce8 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
##############################################################################
#
# comprueba.py 0.99: a simple program checker
#
# Copyright (C) 2008 Juan Miguel Vilar
# Universitat Jaume I
# Castelló (Spain)
#
# This program is fre... |
992,087 | a2a19e506116c81bb1a71e8ed93c851e59925a51 | from basegraph import graph as grafo
def check_if_is_spouse(person1, person2):
return person2 in grafo[person1]["spouse"]
def check_if_has_relationship(person1, person2):
return person2 in grafo[person1]["relationships"]
def check_if_is_child(person, parent):
return person in grafo[parent]["parent"]
... |
992,088 | 685072b991f6e89afaaaaf4655a77e72ecfa3e07 | #Example
# get bash version by subprocess
import subprocess
cmd = ["bash","--version"]
sp=subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
rc=sp.wait()
out,err = sp.communicate()
if rc==0:
for each_line in out.splitlines():
if "version" in each_line a... |
992,089 | d654229deb54b9a21ce617fde714b4d445588299 | # coding=utf-8
# Copyright 2020 The Gin-Config 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 applicable la... |
992,090 | 1aa3b7cba489d71dff5f0cf1a89804e344edc463 | from django.contrib import admin
import models as core
class CandidateAdmin(admin.ModelAdmin):
fields = ['username', 'email', 'domain']
admin.site.register(core.Entry)
admin.site.register(core.Block)
admin.site.register(core.Domain)
admin.site.register(core.Candidate)
admin.site.register(core.CandidateEntry)
adm... |
992,091 | 0cd00038134d59e857d2e4205519e777c8557b8e | import os
from dataclasses import dataclass, field
import pandas as pd
import s3
from utils import unpickle, make_pickle
def format_jira(jid: str) -> str:
"""
Transforms jira ID to keep same notation across the project.
:param jid: Jira ID (ex: SGDS-123, or OMICS-456_do_something)
"""
jid = jid.lo... |
992,092 | 5167f44f8eb8d6fe3181d78321a1a981f2bc6f98 | #!/usr/bin/python
import random
import os
import numpy as np
import time
import sys
def Get_Nid(name):
if name == "Baltimore Orioles":
return 0
elif name == "Boston Red Sox":
return 1
elif name == "Chicago White Sox":
return 2
elif name == "Cleveland Indians":
return 3
elif name == "Detroit Tigers":
ret... |
992,093 | 64fefc6fa98c69f55bb0c22913e3c071f0561bab | try:
from libKMCUDA import kmeans_cuda
_LIBKMCUDA_FOUND = True
except ModuleNotFoundError:
_LIBKMCUDA_FOUND = False
from functools import partial
import logging
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from stratification.cluster.utils import silh... |
992,094 | 668a60d1327482caea2b80c1ba026fb151bb655d | from rest_framework import pagination
class StandardTweetsPagination(pagination.PageNumberPagination):
page_size = 3
page_size_query_param = 'page_size'
|
992,095 | b766931038900db4f821f38ac8365e951688abf3 | # coding: utf-8
'''
Created by JamesYi
Created on 2018/10/23
'''
import argparse
import os
import math
import time
import torch.nn.functional as F
from torch import optim
import torch
from torch.nn.utils import clip_grad_norm
from model import Encoder, AttentionDecoder, Seq2Seq
from utils import load_dataset, device,... |
992,096 | a5d630b9aa20db732322c8cde5e52e6945e2ffe3 | #########################################################################################
#############################--- SOLUCION DE RETO 2--- ##################################
#########################################################################################
try:
#INGRESANDO NOMBRE DEL ESTUDIANTE
es... |
992,097 | 91e5d1f9a0d94ad75348d13767a6717a249a5785 | from generator import *
from backend import banner, Backend
headerCode = r'''
let _bytesToString = bytes => bytes.map(c => String.fromCharCode(c)).join('');
let _bytesToCString = bytes => {
let nind = bytes.indexOf(0);
if(nind == -1)
return _bytesToString(bytes);
else
return _bytesToString(bytes.slice(0, nind))... |
992,098 | 6399b709bcefed0c806e5ed3bbc730ccc4d571d4 | """
In this simulation, the fog device moves in different nodes. There are linked to another nodes.
@author: Isaac Lera
"""
import os
import time
import json
import random
import logging.config
import networkx as nx
import matplotlib.pyplot as plt
from pathlib import Path
from yafs.core import Sim
from yafs.a... |
992,099 | cc40170e4a7d7ca564229cc27806bdec4dfb0d4b | """
Создать матрицу случайных чисел и сохранить ее в json файл.
После прочесть ее, обнулить все четные элементы и сохранить в другой файл.
"""
import json
from random import randint as rd
def matrix_to_json():
"""Function creates a matrix and saves it into a json-file"""
data_dict = {k: v for k, v in enumerat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.