index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
991,400
9770b437af921f6d213793f94d6a2628f08e8359
#coding=utf8 from django.shortcuts import render,render_to_response from django import forms from django.conf import settings from django.shortcuts import redirect from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django.contrib.auth import authenticate,login from...
991,401
e7aa8d577042225c13a876d3721d017b9251b748
import json import requests def joke(): URL = requests.get('https://v2.jokeapi.dev/joke/Programming,Miscellaneous,Dark,Pun,Spooky') JSON_URL = URL.json() if JSON_URL["type"] == "twopart": print(JSON_URL["setup"]) print(JSON_URL["delivery"]) elif JSON_URL["type"] == "single": print(JSON_URL["joke"]) ...
991,402
f9c7b28f35bfc68c885856ee2470da86589e6687
""" Question: Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 100 Then, the output of the program should be: 0,35,70 Hints: Use yield to ...
991,403
418b348d31fadc2857df0bc4c04d964cdc7a1baf
#!/usr/bin/env python import logging import sys from sklearn.feature_extraction.text import CountVectorizer from sentiment_analysis.make_dataset import read_dataset from sentiment_analysis.utils import write_pickle def make_bag_of_words_features( corpus_dataset_path, training_dataset_path, ...
991,404
cf59ee21080d1e56a2a36f8f382dd9eb82570683
import nltk import collections from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import numpy as np from pptx import Presentation import os def prcoss(tokens): count = nltk.defaultdict(int) for word in tokens: count[word] += 1 return count def c...
991,405
6df514e1662f986aee9e324d5a0479bbdcfaeec4
from __future__ import print_function from __future__ import absolute_import import random from .utils import rand_max import copy from .graph import StateNode class MCTS(object): """ The central MCTS class, which performs the tree search. It gets a tree policy, a default policy, and a backup strategy. ...
991,406
6cd56359a2d5491b58dd5f061c39b1782a03feb3
from .entity import Entity from .weapon import Weapon from ..tools import sf, gen_texture class Ship(Entity): def __init__(self, x=20, y=20): texture = gen_texture(x, y) super().__init__(texture) self.weapon = Weapon() def shoot(self, board): projectile = self.weapon.use(self....
991,407
6044e0f4ebb3537e5d50988ce854700ea540f104
import numpy as np import cv2 import pyrealsense2 as rs from ORB_VO.pso import PSO THRESHHOLD = 30 FEATUREMAX = 200 INLIER_DIST_THRE = 10 class Optimizer: def __init__(self, featureA, featureB, matches, intrin): self.featureA = featureA self.featureB = featureB self.matches = matches ...
991,408
21bf0e36a823c29119142c5ef199a2b14ec3ca3b
import torch.nn.functional as F from torch import nn from torchvision import models class SegNet(nn.Module): def __init__(self, num_classes, pretrained=False, fix_weights=False): super(SegNet, self).__init__() self.name = "true_segnet" self.num_classes = num_classes # vgg = models....
991,409
331e262af450ca3ddd3df3a68d4af10ad828bffe
# SECTION PROCESS - Processes command line arguments. # ===================================================== def resolve(args = [], type = ''): # Get the index of the type to resolve index = {'command': 0, 'argument': 1}[type] # Ensure the args list has enough items if len(args) > index: # Return the item...
991,410
2b9d4ef4683908f662c5ea1e05a8e7261df1991a
from rest_framework import viewsets from .models import Restaurant from .serializers import RestaurantSerializer from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.decorators import action class RestaurantViewSet(viewsets.ModelViewSet): ...
991,411
8268108044f9b1abe5153e912348d139601fa44d
from preprocess.load_data.data_loader import load_hotel_reserve customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() # 下の行から本書スタート # 予約回数を計算(「3-1 データ数、種類数の算出」の例題を参照) rsv_cnt_tb = reserve_tb.groupby('hotel_id').size().reset_index() rsv_cnt_tb.columns = ['hotel_id', 'rsv_cnt'] # 予約回数をもとに順位を計算 # ascendingをFalseにすること...
991,412
82619ab5ee680d769095c69db3915a0d20da96c5
MOD = 10 ** 9 + 7 import math __author__ = 'Danyang' class Solution(object): def solve(self, cipher): N, M = cipher return math.factorial(N + M - 1) / math.factorial(N) / math.factorial(M - 1) % MOD if __name__ == "__main__": import sys f = open("1.in", "r") testcase...
991,413
bbffff9dbe29982994c8edd101db86dc44786d6c
""" This module is one of the two entrypoints with train.py It is used to make predictions using our model. """ import pickle import logging from typing import Union from warnings import simplefilter import pandas as pd from pandas.core.common import SettingWithCopyWarning import src.config.base as base impo...
991,414
d643a01e1f285780f20512c7809f0f316c1692bf
from typing import Iterable, Tuple, List, Callable, Union from Day02.task import Mode, IntMachine, CustomList, work_code from Day17.task import my_machine from Day19 import INPUT from helper import Iterator, Point, get_all_combs from main import custom_print as custom_printer def get_affected_pos(inp: Union[List[int...
991,415
6176bddc84b89b27a561db0c83faa9280d9f890a
import pandas as pd from sqlalchemy import create_engine from util.scrawl import * import os def repay(): engine = create_engine('mysql+pymysql://root:gkd123,.@47.101.44.55:3306/Houseprice?charset=utf8', encoding='utf-8') df = pd.read_sql('select * from infodata', engine) cc = 0 for index, row in df.it...
991,416
5c738e0743d4960ebbefb62c4b405691136ed54c
#To add elements to a set using- add() #Initially colors is an empty set colors = set() print(colors) #set() colors.add('blue') colors.add('red') colors.add('white') print(colors) #{'blue...
991,417
90c3d457c3a902d7dd2077b46f17985f156a67bc
import vgg import numpy as np import tensorflow as tf import cv2 import os import wrapper from functools import reduce os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def gram_matrix(matrix): return np.matmul(matrix.T,matrix)/matrix.size content_layers = ('relu3_2','relu4_2', 'relu5_2') style_layers = ('relu1_1', 'relu2...
991,418
af039bcd7cffec5e8ab7b598bd7a01ab52338848
print("hello world") # comment : 메모 적어두는 곳 # variables : 변수 = "변하는 수" identity = 'pencil' print('I want to write it by',identity,'.') # 변수의 종류는 크게 두 가지 있음: 숫자와 문자열 변수로 나뉨. 이걸 변수의 data type이라고 함. 정수와 실수, 문자열 data type이라고 함. int, double (or float), string a = 5 b = 1.1 c = 'hello' # 숫자 변수는 사칙연산이 가능, 문자 변수는 불가능 a = a+1...
991,419
38d8f397a82b278fd1d22d6a80f26c3fe7e8b0bf
from dynamixel_sdk.port_handler import * from dynamixel_sdk.packet_handler import * from colors import * class ModelFlag: def __init__(self, address, data_length): self.address = address self.data_length = data_length class Dynamixel: protocol_versions = [1.0, 2.0] models = { # M...
991,420
98b75bc712ef8c65d8a67310e4083d7f4b502d1e
# # Copyright (C) University College London, 2007-2012, all rights reserved. # # This file is part of HemeLB and is CONFIDENTIAL. You may not work # with, install, use, duplicate, modify, redistribute or share this # file, or any part thereof, other than as allowed by any agreement # specifically made by you with Un...
991,421
8de4db3f673ee5d3a17bae14c9cac1d4e7810c76
import numpy as np import pandas as pd from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV import six class MLModelPipeline: def __init__(self, process_features, feature_selection, clf): self.process_features = process_features self.feature_selection = feature_...
991,422
528536c9c99a40a08783ef5f68b2a99a92da3aad
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import sys import numpy as np import parsebmp as pb # Define method def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) def bias_variable(shape, name): initial...
991,423
72c5a0e2ccee849db3dc473298e59067f622e535
#-*- coding:utf-8 -*- #!/usr/bin/env python import os import sys import datetime import logging import enviroment from daemon import run_daemon from time import sleep # 启动真正的运行进程 def start_server_in_subprocess(): import http.server as root_server logging.info('server start.') root_server.start_http_serve...
991,424
0d5e4bbe3f782f1bf1a8db2e2dcd24e0d7cd1467
import traceback import os import boto3 from botocore.exceptions import ClientError # , EndpointConnectionError def handleRecord(decoded_line): send = False cur_region = os.environ["AWS_REGION"] try: confirm = os.environ["CONFIRM_INSTANCES"] except KeyError: # Default to confirm the i...
991,425
6b9c32517548ff907fc7dc4a70db3ddd55076c84
def hello(): return "world" def test_hello(): assert hello() == "world"
991,426
433915870ed0252c02209e2da7c846a80dfc9394
# The MIT License (MIT) # Copyright (c) 2018 by the ESA CCI Toolbox development team and contributors # # 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 ...
991,427
5a64663eac9081e21b38069579274cae7cfedafc
# -*- coding: utf-8 -*- # @Time : 2019/1/9 15:24 # @Author : Junee # @FileName: 868二进制间距.py # @Software : PyCharm # Observing PEP 8 coding style class Solution(object): def binaryGap(self, N): """ :type N: int :rtype: int """ N = list(str(bin(N))) ...
991,428
88817ca6c6134942e50c4aff91738c514d92ecaa
import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class SendMail(): def __init__(self, content): # Create a multipart message and set headers password = content["password"]...
991,429
b36ae566985cf16ac84f23c608db0de26c8506be
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class User_profile(models.Model) : ezpdf_user = models.OneToOneField(User , on_delete = models.CASCADE) folder_id = models.Ch...
991,430
49f4b2fa5c0332989c09610b2f8ea5e8e14490f4
from mworks.conduit import * import time, sys client = IPCClientConduit("python_bridge_plugin_conduit") def hello_x(evt): print("got evt") print("evt.code = %i" % evt.code) print("evt.data = %d" % evt.data) print("evt.time = %i" % evt.time) client.initialize() client.register_callback_for_name...
991,431
33f44572032eed73e9ee7fd655af110a744eac7b
#token TOKEN = '732030625:AAHXvNnqwLREd1u6-nIyXqX_ZfL2PbKmwAA' #language from bot import rus_text from bot import eng_text DEFAULT_LANGUAGE = 'ru' TEXT = { 'ru': rus_text, 'ENG': eng_text }
991,432
08ec9397be6530c5a0095952df8ad61d71107444
''' Constants Module ''' ''' Hue/Intensity Gesture Skin Detector Constants''' class SkinCons(object): HUE_LT = 3 HUE_UT = 50 INTENSITY_LT = 15 INTENSITY_UT = 250 ''' Three Gesture Constants - Depth Lowerbound/UppperBound; Area Lowerbound/UppperBound''' class GesConsAttributes(object): pass cl...
991,433
6d33ac5cab71eda9d44e62e0757e75a32d31bcc8
import io import numpy as np import os import pygtrie import tempfile # shared global variables to be imported from model also UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # special error message class MyIOError(Exception): def __init__(self, filename): # custom error message message = """ ERROR: Unab...
991,434
087f988cf63b9fb3b4470989f6f89698b4c92bea
''' Read all the actorlogins csv files saved in the actorlogin dir and extract all the unique user actorlogins along with how many times each user interacted with the github platform. After extracting this information save it into a unique users file. (ONE TIME EXECUTION) ''' import os csv_files = [x for x in os.lis...
991,435
94ea4dd4c163d3840e2105f2ea2eb00c04127141
#!/usr/bin/env python import shelve import numpy as np import sys from rnarry.sequtils import GiantFASTAFile from rnarry.sequtils import reverse_complement from rnarry.utils import textwrap from rnarry.bxwrap import MultiTrackSplitBinnedArray MINREADSTOCALL = 10 MINPERCENTTOCALL = 0.9 blklength = lambda blks: sum(end...
991,436
7f15a1c532d9a6f1d7aa4e255b381f2316219d31
# -*- coding: utf-8 -*- class Card: SUITS = ['S', 'H', 'D', 'C'] RANKS = ['6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] SUITS_PRINTABLE = ['♠', '♥', '♦', '♣'] def __init__(self, suit, rank): self.suit = suit; self.rank = rank; def __repr__(self): return self.rank + self.pri...
991,437
184064077c31493900d49abe8e8fd49481c8e0c4
''' Created on Mar 27, 2019 @author: dsj529 ''' import numpy as np import pandas as pd from pandas.plotting import scatter_matrix from matplotlib import pyplot as plt from sklearn import model_selection, preprocessing from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics i...
991,438
b2822f2b6386413e7fc2bc143befa5f1de55d9d8
import random def guess(): number = random.randint(1, 20) attempt = 0 while (attempt != number): print('Take a guess') attempt = int(input()) if (attempt < number): print('Too low.') elif (attempt > number): print('Too high.') else: break print('Good job.') print('I am thinking of a number be...
991,439
2a82b2c70ea7f3e3472c0a03069dad0222774c06
import os to_split_fn = '/afs/csail.mit.edu/u/t/tzhan/eeg/patient_file_lists/largest/patient_largest_files_whole.txt' output_fn = '/afs/csail.mit.edu/u/t/tzhan/eeg/patient_file_lists/largest/hosp_largest_files.txt' # Number of files to split each hospital into split_n = 2 def chunkIt(seq, num): # split list into 'n' ...
991,440
5f381e7fde408830df2c4f73bf3137d4c5ad6e79
import uhal uhal.disableLogging() hw_man = uhal.ConnectionManager("file://connection.xml") amc13 = hw_man.getDevice("amc13") # reset AMC13 (necessary for daq link to be ready after reset of WFD) amc13.getNode("CONTROL0").write(0x1) amc13.dispatch()
991,441
94e10aab9145a2b9e206e211a7c812d0a9303002
#! /usr/bin/env python from __future__ import print_function from PyQt4 import QtCore,QtGui from PyQt4.QtOpenGL import * from OpenGL.GL import * from OpenGL.GLU import * import time import numpy import math import os, sys import Texture def distance(x1,y1,x2,y2): dx = x1 - x2 dy = y1 - y2 return math.sqrt(dx*...
991,442
4c15792d1105b57e5e11042bc7949ad77b8bff32
import io import tarfile import textwrap import sys SCRIPT_TEMPLATE= """#!/usr/bin/env python from distutils.core import setup setup(name='{name}', version='1.0', ) try: {script} except Exception as e: print(e) """ DEFAULT_SCRIPT = """print(42)""" def build_setup(script, name): script_body = textwrap.in...
991,443
485609f6d3dc345b05149c00ee62e2c6e41b7fd0
n = int(input()) initial = 5 total = 0 for i in range(n): liked = initial//2 total+=liked initial = liked*3 print(initial,liked,total)
991,444
5a02ed9788a12d065aca99c098dec2579f7e0c6f
import json import requests from song import Song class SpotifyRecom: def __init__(self, token): self.token = token def get_last_played_tracks(self, limit=10): url = f"https://api.spotify.com/v1/me/player/recently-played?limit={limit}" response = self._place_get_api_request(url) ...
991,445
33bcab25b344966d173bbce74e37cbd3bb29b72e
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.contrib.postgres.fields import ArrayField import os @python_2_unicode_compatible class Classes(models.Model): letter_yr = models.CharField(max_length=2, primary_key=True) ...
991,446
4db9f5dd32f67d70e42e20a62bf70db08ccb2fa6
''' Created on Aug 25, 2014 @author: Changlong ''' import zmq import threading import struct import logging import datetime import time import traceback from twisted.internet import threads from twisted.internet.defer import DeferredLock from DB import SBDB, SBDB_ORM # from SBPS import ProtocolReactor from Utils impo...
991,447
27dcd3afb436a08c860bfb7743404fbfffbbaed3
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Application de SoundBoard avec interface Qt ====================== Exécuter pour commencer l'utilisation de la SoundBoard. """ import json from PySide2.QtCore import (QRect, QSize) from PySide2.QtWidgets import ( QApplication, QDialog, QVBoxLayout, ...
991,448
0a7268804c61247fef6dc0f3a7c45afad00f08fc
class Solution: def solve(self, input, N): spoken_map, last_spoken = {}, None for i in range(len(input)): spoken_map[input[i]] = i + 1, n = len(input) last_spoken = input[n - 1] while n < N: n += 1 if len(spoken_map[last_spoken]) == 1: ...
991,449
196dcd51b8ab6b83133af71bc040fc165d0c3b64
k = [1, 2, 3, 4, 5] # increment the 3rd element def increment(list): list[2] += 10 print(list) increment(k)
991,450
6d3eb6811ee25bbda22be7945e0c252fef228a86
# Imports import pandas as pd import requests import re from bs4 import BeautifulSoup, SoupStrainer import selenium from selenium import webdriver import time import getpass import matplotlib.pyplot as plt import seaborn as sns #################### Analyze and Plot #################### sns.set_style("white") sns.se...
991,451
4140027e7565e537f78a9fee760e751d267092f6
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame,Series #from sklearn.cross_validation import train_test_split from sklearn.model_selection import KFold, cross_val_score as CVS, train_test_split as TTS #from sklearn.linear_model import Li...
991,452
03f3ebbb9adde4410ffa55623f3ec184a1edfb47
from nc8.instruction import Instruction import nc8.conversions class JumpInstruction(Instruction): def __init__(self): super(JumpInstruction, self).__init__('jmp', base_opcode=0xc0, argument_range=(0, 0xf), ...
991,453
5ac9e5b04ff5854301be7ac2fbac597abb62531c
#-*- coding: utf-8 -*- from copy import deepcopy from django.contrib import admin from mezzanine.pages.models import RichTextPage from mezzanine.pages.admin import PageAdmin from mezzanine.blog.admin import BlogPostAdmin from mezzanine.blog.models import BlogPost from .models import * HomePage_fieldsets = deepcopy(Pa...
991,454
d4c534f889a528f4922048c885c1f2488bcdbe17
from xai.brain.wordbase.nouns._loincloth import _LOINCLOTH #calss header class _LOINCLOTHS(_LOINCLOTH, ): def __init__(self,): _LOINCLOTH.__init__(self) self.name = "LOINCLOTHS" self.specie = 'nouns' self.basic = "loincloth" self.jsondata = {}
991,455
0cd5a2f55bb009f3baebe3da3b4f32daccc57bb0
# ================================================================================== # File: deviceclient.py # Author: Larry W Jordan Jr (larouex@gmail.com) # Use: Created and send telemetry to Azure IoT Central with this persisted # device client # # https://github.com/Larouex/cold-hub-azure-iot...
991,456
4e7432471668218a7d6c180aef830a7fa70d79b3
import geopandas as gpd from shapely.geometry import Polygon #lat_point_list = [-16.2, -16.2, -19.4, -19.4, -16.2] #lon_point_list = [ 176.4, 179.1, 179.1, 176.4, 176.4] #lat_point_list = [ -17.2982, -17.2982, -18.3024, -18.3024, -17.2982 ] #lon_point_list = [ 177.3083, 178.6267, 178.6267, 177.3083, 177.3083 ] lat_p...
991,457
abdd26a91cded96378c8d8a832a976423e8a1035
import torch import torch.nn as nn import torch.nn.functional as F import scipy.ndimage as ndimage class FocalLoss3d_ver1(nn.Module): def __init__(self, gamma=2, pw=10, threshold=1.0, erode=3, backzero=0): super().__init__() self.gamma = gamma self.pw=pw self.threshold=threshold ...
991,458
9b26d506029353748090fd9ba1ddaa26105a4035
from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), # Project apps url(r'^first-draft/', include('apps.first_draft.urls', namespace='first-draft')), ] if s...
991,459
5c32c15b9d72150894a40499573c9098bb6f2c8d
import cv2 import numpy as np import matplotlib.pyplot as plt # 取得する色の範囲を指定する lower_yellow = np.array([100,100,100]) upper_yellow = np.array([150,150,150]) cap = cv2.VideoCapture(0) cascade = cv2.CascadeClassifier('TrainingAssistant/results/cascades/tegaki_maru2/cascade.xml') #分類器の指定 while(1): # フレームを取得 re...
991,460
2cf922d1ef305316909ba84801aff210ae8a2151
import json from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.session import sessionmaker from Pub.RabbitMQ import RabbitMQInfo import sqlalchemy from os import path ''' sql config ''' with open(pa...
991,461
dcb6372256401f63b4a4232bbee277b35a4e28e3
from unittest import TestCase, main from project.card.card import Card from project.card.card_repository import CardRepository from project.card.magic_card import MagicCard class TestCardRepository(TestCase): def setUp(self): self.card_rep = CardRepository() self.magic_card = MagicCard('A') ...
991,462
e4c7747d8e44af31e1c4ca446a4cc797e843e1ca
from abc import ABC from typing import Dict import motor.motor_asyncio from application.main.config import settings from application.main.infrastructure.database.db_interface import DataBaseOperations from application.main.utility.config_loader import ConfigReaderInstance class Mongodb(DataBaseOperations, ABC): ...
991,463
17a8cd7204a5b0b802f95b0b1d0555b6847e0b13
from math import sqrt def prime_nums(n): if type(n) != int: raise TypeError() if n < 0: raise ValueError() rslt = [] for x in range(0, n): if is_prime(x): rslt.append(x) return rslt """ Based on. Title: Prime Numbers Author: James Conan Date: N/A Code version: Pseudocode Availability: http://www.cs.uwc...
991,464
c50533e019f99748c66231c6d1518c2e23360a1e
#!/usr/bin/env python import rospy from nav_msgs.msg import Path from geometry_msgs.msg import Twist, TwistStamped, PoseStamped import roslib import rospy import math import tf import numpy as np ROBOT_FRAME = 'base' GOAL_THRES_POS = 0.2 GOAL_THRES_ANG = 0.2 FACE_GOAL_DIST = 1.0 def getYaw(quat): _, _, yaw =...
991,465
4adb4af4e30d98b5b056f18b97508978e08bb4d3
from pyspark import SparkConf, SparkContext conf=SparkConf().setMaster('local').setAppName('FriendsByAge') sc=SparkContext(conf=conf) def parseLine(line): fields=line.split(',') age=int(fields[2]) numFriends=int(fields[3]) return (age, numFriends) lines=sc.textFile("file:///SparkCourse/fakef...
991,466
34b82743396a5c8a898bd7272d112ecfec23b9f3
""" :mod:`common` -- Common functions and classes for supporting FRBR Redis datastore """ __author__ = 'Jeremy Nelson' import urllib2,os,logging import sys,redis import namespaces as ns from lxml import etree try: import config REDIS_HOST = config.REDIS_HOST REDIS_PORT = config.REDIS_PORT REDIS_DB = ...
991,467
94fd5a7782d14b44a979d33a444b3c0675d4e446
import itertools n,k = map(int,input().split()) ab = [0]*n for i in range(n): ab[i] = input().split() a = [] b = [] for i in range(n): tmp1 = int(ab[i][0]) tmp2 = int(ab[i][1]) a.append(tmp1) b.append(tmp2) ab = zip(a,b) ab = sorted(ab) a,b = zip(*ab) s = 0 for i in range(n): s += int(b[i]) if s >= k: ...
991,468
9ff030f2815a263074844d1cd74fce0d19d44b76
import pygame as pg from duchshund_walk import globals from duchshund_walk.app_core import States from duchshund_walk.messages import message_display from duchshund_walk.settings import NICKNAME_MAX_LENGTH from duchshund_walk.settings import WHITE from duchshund_walk.settings import WORLD_HEIGH from duchshund_walk.sett...
991,469
4b615ac16099f42be5d47203fc43e4d46e82b8de
#!/opt/local/bin/python import tkinter as tk import tkinter.ttk as ttk import sys from random import randint import threading globstop = 0 mauvaisetage = False portes_ouvertes = 0 # à 1 les portes sont complétement ouvertes, à 0 elles sont fermées portes_bloquees = False PORTES_UN_PEU_OUVERTES = 0.5 # à quelle pro...
991,470
e80e86bbcb76b248356d1cd2dc70949bdc0b1f92
#!/usr/bin/python3 import os import zipfile, tempfile import click import shutil @click.command() @click.argument('input', nargs=1, type=click.Path(exists=True, file_okay=True, dir_okay=False)) def main(input): """A small script that converts docx files to lyx using pandoc and tex2lyx. A folder with the name of th...
991,471
6e67635ac77004e464ecbb494107ca87018c3d11
from fabric.api import * env.hosts = ['192.168.33.10'] env.user = 'vagrant' env.password = 'vagrant' def package(): local('python setup.py sdist --format=gztar', capture=False) def deploy(): dist = local('python setup.py --fullname', capture=True).strip() put('dist/%s.tar.gz' % dist, '/tmp/myapp.tar.gz') run...
991,472
030213bef6a4611876018682579ab6b8af2f6aa1
# -*- coding: utf-8 -*- from zope.i18nmessageid import MessageFactory as ZMessageFactory import warnings _ = ZMessageFactory('plone') def MessageFactory(*args, **kwargs): # BBB Remove in Plone 5.2 warnings.warn( "Name clash, now use '_' as usal. Will be removed in Plone 5.2", DeprecationWarni...
991,473
8a8f29658e6db4b0418dcf1a06d7ea5656d49ce9
#!/usr/bin/python # -*- coding: utf-8 -*- import itertools import time #mylist = list(itertools.product([0,1,2,3,4,5,6,7,8,9,],repeat=5)) passwd = ("".join(x) for x in itertools.product("0123456789",repeat=3)) #print(mylist) #print(len(mylist)) while True: try: time.sleep(0.5) str = next(passwd) ...
991,474
ed3d3cebe7108b2054f8f2806767ca6152eac47b
#Author : Rohit #license to : ABB Seden '''56 sonar-scanner-4.6.0.2311-linux/bin/sonar-scanner -Dsonar.login=5b1bd1feaea303f4b6b40f68998849018b917332 57 sonar-scanner-4.6.0.2311-linux/bin/sonar-scanner -Dsonar.login=5b1bd1feaea303f4b6b40f68998849018b917332 -Dsonar.java.binaries=. 58 vim sonar-project.properties 59 s...
991,475
57f88afe5d6918be27810c815b280682c77086b2
# -*- coding: utf-8 -*- """ actions.py :copyright: © 2019 by the EAB Tech team. 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...
991,476
ef86dcb590d54e95f8d6de436dde0575197447fd
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by wxk on 17-10-15 上午12:23 # Email="wangxk1991@gamil.com" # Desc: 短信通知类 from src.Notify import Notify class Sms(Notify): pass
991,477
3a69f68ba53cc795563304841dcf8b8049c15467
# ___________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2022 # National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of ...
991,478
348ae5edf29acf1293ee9ea5e00d26dcfa4b6c61
# Generated by Django 3.1.6 on 2021-06-03 18:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('banner', '0002_auto_20210603_0815'), ] operations = [ migrations.CreateModel( name='BannerSeen'...
991,479
49a3ae6630dcb9d34e9d86bc2469ba1ed9b582f5
from pymongo import MongoClient from requests import post client = MongoClient(API_mongoDB) #数据库地址 db = client['chatLog'] users = db['usercontacts'] for user in users.find(): # 遍历usercontacts文档,每次输出一个用户 userPhone = user['userPhone'] #提取用户手机号 userContacts = user['userContacts'] #提取userContacts中的信息,然后解析 c...
991,480
3bda0448e95d1b18a6920df6d75e34759192ff8e
abbreviations_map = { 'aca': [''], 'asme': ['american society of mechanical engineers'], 'ackerman union': ['au', 'ackerman'], 'afrikan student union': ['asu'], 'alpha gamma omega ucla': ['ago'], 'alpha kappa psi - ucla alpha upsilon chapter': ['akp'], 'alpha tau delta - gamma chapter': ['atd'], 'amer...
991,481
b677a829d1b0e1ae83713fc7db683ee16a5ca22e
import argparse import cv2 import numpy as np import torch from facenet_pytorch.models.mtcnn import MTCNN from omegaconf import OmegaConf from tqdm import tqdm import time from pathlib import Path from experiment import HairClassifier from transforms.transform import get_infer_transform from utils.infer_utils import ...
991,482
435f0edf22db434c748a323ee62e5e9b46a140c2
# -*- coding: utf-8 -*- # Copyright (c) 2015-2019 Jan-Philip Gehrcke. See LICENSE file for details. from __future__ import unicode_literals from unittest import TestCase from distutils import dir_util, file_util from inspect import currentframe import os test_data_folder_path = os.path.join(os.path.dir...
991,483
870b7b588cc3df622e09b6d7f12882a7304daac2
#!/usr/bin/env python2 import signal import logging from programs import Program from switches.base import SwitchProxy from writer.base import WriterProxy from manager.base import ManagerProxy from misc.autobahnWebSocketBase import WebSocketBase from conf.private import writer, switches, manager, switch_programs_file ...
991,484
cf8834e562f4f498e29c5c398ca7dbf0dfd941c4
# -*- coding: utf-8 -*- """Main module.""" def simpleAddition(num1, num2): return num1 + num2
991,485
f02f427e11a1843917f3a40d28a9e5f8101819f7
#run this by 'python3 manage.py runscript load_from_csv import csv from majorApp.models import News def run(): fhand = open('data/test_data.csv') reader = csv.reader(fhand) News.objects.all().delete() for row in reader: print(row) # news, created = News.objects.get_or_create(title_...
991,486
6cd7ad096e1abb15a2bac8ecdbb0fc47cce70b47
from datetime import datetime def list_to_json(book_list): size = len(book_list) json = '{"book_list": {' for index, book in enumerate(book_list): if index == size - 1: book_json = '"book": ' + book.to_json() else: book_json = '"book": ' + book.to_json() + ', ' ...
991,487
4be33ec39fb8e3ff4d5245d7b000400858826274
#!/usr/bin/python # Plot an image from a CSV file. xpix, ypix, iter. # JM Wed 22 Nov 2017 21:39:59 GMT import csv from PIL import Image from timeit import default_timer as timer from lc import colour_list import sys import os start = timer() lenlc = len( colour_list ) rnum = 93 maxiter = 150 white ...
991,488
c11bf33e1d0daa539d6cf6a0e2e5a8cdda1e39a7
import os import re import pandas as pd import numpy as np from firecloud import api as firecloud_api import datetime import glob """ _____ ___ ____ _____ ____ _ ___ _ _ ____ ____ _ _ ____ _ ____ | ___|_ _| _ \| ____/ ___| | / _ \| | | | _ \ / ___|| | | |/ ___| / \ | _ \ | |_ | || |...
991,489
694ef27a90b8fc515517608104e6c1e23e416bb6
x = lambda a, b: a + 1 + b print(x(2, 3))
991,490
921e2072d270a66b5d0da39a40ed00ba3be53856
import rclpy from rclpy.node import Node from contextlib import contextmanager from functools import partial, total_ordering from importlib import import_module import queue import socket from typing import Any import threading import traceback import time from ros2relay.message_socket.message_socket import MessageSo...
991,491
2d570b9ad381032d32b0f2afa7957d1c604bb054
import threading import time class myThread(threading.Thread): def __init__(self,s,name): threading.Thread.__init__(self) self.s=s self.name=name def run(self): c, addr = self.s.accept() while (True): try: msg = "server data" da...
991,492
7d2865faaf0d041cefae0b4b141871652de43dfc
""" https://github.com/openai/gym/wiki/Table-of-environments https://github.com/openai/gym/tree/master/gym/envs - check gym/gym/envs/__init__.py for solved properties (max_episode_steps, reward_threshold, optimum). Solved: avg_score >= reward_threshold, over 100 consecutive trials. "Unsolved environment" -...
991,493
630b2bb65e1686cfd2e3782e219caa24056c892a
""" Permission Related Code """ from .helpers import * from .imports import * class StaffMember(BaseModel): """Represents a staff member in Fates List""" name: str id: Union[str, int] perm: int staff_id: Union[str, int] async def is_staff_unlocked(bot_id: int, user_id: int): return await re...
991,494
d89d454eca7ff2db6405b5539702046543a60dac
a,b = input().split() c = len(set(list(a))) b = len(set(list(b))) if b == c: print("yes") else: print("no")
991,495
378a85f3f2960c3f61aed8d79c09bf7acc9e3a16
import numpy as np import torch import gym import argparse import os import utils import TD3 import kerbal_rl.env as envs def generate_input(obs) : mean_altitude = obs[1].mean_altitude speed = obs[1].vertical_speed dry_mass = obs[0].dry_mass mass = obs[0].mass max_thrust = obs[0].max_thrust thrust = obs[0].t...
991,496
015a82703bd5e83ae8d4baa835cf4dfc3cb9d648
import json import arrow import logging from ..parser.tconnect import TConnectEntry from ..parser.nightscout import NightscoutEntry logger = logging.getLogger(__name__) def process_cgm_events(readingData): data = [] for r in readingData: data.append(TConnectEntry.parse_reading_entry(r)) retu...
991,497
6ca2be7f4bf28f42e6dc9dc89f276f36225d0e99
# Classify images of dogs & cats # dataset is Kaggle's Dogs vs Cats # First, clustering the SURF features for all images # Second, represent each image by its feature counts of clusters (BOF) # Finally, logistic regression to classify dog or cat
991,498
31280b53a821644a1ba4a8b72599857a80c3b427
# Filename: calc_ssXtorisons.py # Author: Evelyne Deplazes # Date: May 5, 2018 # Script to calculate the five torsion angles that are defined by the # two residues that form a disulfide bbond (see below for defintion of # torsion angles) # the script relies on the definition of the disulfdie bonds by the keyword S...
991,499
f06972da07df5266400b718fb2f969c5e34a1459
from functions import * df, target = get_dataset() X_train, X_test, y_train, y_test = train_test_split(df, target, test_size=0.33, random_state=42) mean_value = np.mean(y_train) print(mean_value) y_pred_mean = [mean_value for _ in range(len(y_test))] mean_squared_error(y_test, y_pred_mean, squared=False) model = Ada...