index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
994,800
c088123e9e001371e3b9094c9bf701dcccfd8cec
import re, sys import pandas as pd import numpy as np class gaf: """A simple class for reading or generating gaf files""" annotations = pd.DataFrame() def read_gaf(self,infile): obofile = open(infile,"r") lines = obofile.readlines() if self.check_gaf_version(lines): self....
994,801
f99bdb6f74033c804cab7f14c2851d0332ce2289
if __name__ == '__main__': from kaa import bot bot.run()
994,802
924122a604ce0aa26e735dd7019a23d1129b5bfa
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets 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/LI...
994,803
a7c0ec840fce2a37e2e950ca316b04cefae02c99
#!/usr/bin/env python3 """Script to create PLDM FW update package""" import argparse import binascii import enum import json import math import os import struct import sys from datetime import datetime from bitarray import bitarray from bitarray.util import ba2int string_types = dict( [ ("Unknown", 0), ...
994,804
4b95c493a12bd665694f05b17d6e70ce141fc968
import os,inspect,sys current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.append(parent_dir) import pandas as pd import pathlib import matplotlib.image as im import numpy as np import tensorflow as tf import config from sklearn.metri...
994,805
ccc9a0640f2069ffeab85ac1a5c162e3737480ab
from sklearn.datasets import load_breast_cancer from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA, SparsePCA from sklearn.datasets import load_breast_cancer from sklearn.ensemble import RandomForestClassifier,...
994,806
9b3f461a50f8a57683e5bf5613751a27ea721af9
""" For this code we need to import two famous third party library into our code. numpy, opencv. Numpy: for working with arrays (efficiently and fast) Opencv: Open Source Computer Vision Library the goal of this code is to use opencv to do OCR (Optical character reader) for numbers. after installing opencv and numpy...
994,807
748a2fa95b49187f5e7e856f9f9120f1fa259f1e
import pexpect import time username = '' password = '' email = '' child = pexpect.spawn('ssh bbsu@ptt.cc') child.expect('new'.encode('big5')) time.sleep(5) print('sending username...') child.sendline(str(username + '\r\n').encode('big5')) child.expect(':') time.sleep(5) print('sending password...') child.sendline(st...
994,808
78287b4fc4a2f6007445461bb373a2ee9eb6e398
from typing import Literal Width = Literal[ '0', 'px', '0.5', '1', '1.5', '2', '2.5', '3', '3.5', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14', '16', '20', '24', '28', '32', '36', '40', '44', '48', ...
994,809
ac9a4f1e04d7735c0626430ee78e724a1b2836fe
# unittests/__init__.py from datetime import datetime import logging import re import time from search import Query, InvalidQueryError from .testobject import ( TestObject, PropertyTestObject, NestedTestObject ) logger = logging.getLogger(__name__) REGISTERED_UNITTESTS = [] #NB: This should all be co...
994,810
a4a484b5cda5c58ecb0d4978ac6149dffc86d028
import time import serial import RPi.GPIO as GPIO # Set up gpio for button push PIN_NUM = 7 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(PIN_NUM, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) class HardwareInterface: def __init__(self): # Set up printer self.ser = serial.Serial('/dev/seri...
994,811
d5f8a201b262f37af12ebe5321835720b5ba7be0
import sqlite3 from sqlite3 import Error def sqlite_connect(db_file = '/Users/vs/Documents/workspace@roy/text-editor/textEditor/database/writerBox.db'): try: conn = sqlite3.connect(db_file) return conn except Error as e: raise e def create_new_table(statement): try: con...
994,812
2961dcbb2fba16b974da5c791fb56f15aa383209
def minimumBribes(q): bribe = 0 for position in range(len(q)): print('index: {}'.format(q.index(q[position])+1)) print('q: {}'.format(q[position])) if q[position] <= q.index(q[position])+2: bribe += q.index(q[position])+1 - q[position] print('Posicao Correta') ...
994,813
1c531888c113592a86928d6f3197e0f9d2933e1e
list1 = [] print(list1) list2 = [1,] print(list2) list3 = [1, 2] print(list3) tuple1 = (1, 2, 3) print(tuple1) print(tuple1[0]) dic1 = {'book1':'C语言','book2':'R语言', 'book3':'Python语言'} print(dic1) dic1['book4'] = '深度学习与keras' print(dic1) print(dic1.keys()) print(dic1.values()) # 字符串 """ 座右铭:好好学习,天天向上 """ str1 = '好好学...
994,814
3ecc1bb6db05589e315b790a422d9971d05d0b1c
#!/usr/bin/python # -*- coding: utf-8 -*- import sys ''' 对于从1到N的连续整集合,能划分成两个子集合,且保证每个集合的数字和是相等的。 举个例子,如果N=3,对于{1,2,3}能划分成两个子集合,他们每个的所有数字和是相等的: {3} and {1,2} 这是唯一一种分发(交换集合位置被认为是同一种划分方案,因此不会增加划分方案总数) 如果N=7,有四种方法能划分集合{1,2,3,4,5,6,7},每一种分发的子集合各数字和是相等的: {1,6,7} and {2,3,4,5} {注 1+6+7=2+3+4+5} {2,5,7} and {1,3,4,6} {3...
994,815
780d848c6828270ff597a54816bb0d77ee622988
# 1306. Jump Game III class Solution: def canReach(self, arr: List[int], start: int) -> bool: stack, visited, n = [start], set(), len(arr) while stack: i = stack.pop() if arr[i] == 0: return True visited.add(i) i1, i2 = i + arr[i], i -...
994,816
62bf352ae5560cc9d02e76b22bd870576ee576e7
# Local imports import logging import bb_auditlogger import config_services import bb_dbconnector_factory from messaging import bb_sms_handler import bb_notification_handler as notify # Set up the logger logger = logging.getLogger(__name__) # Method is run when a SET command to determine which particular setting the...
994,817
d6b9ac206c2ca884cec9cbec8adacccc4dfa6e72
cnt = df.isurban.value_counts(normalize = true)
994,818
909fa6a56de4f9d966519b67b937557a25501a28
import sys import math script, Dvc, ep, delta = sys.argv Dvc = int(Dvc) ep = float(ep) delta = float(delta) print("VC Dimension : {}".format(Dvc)) print("Epsilon : {}".format(ep)) print("Delta : {}".format(delta)) def testN(N): poly = (2*N)**Dvc + 1 internalLog = 4 * poly / delta ln = ma...
994,819
ba5a378d3180f96545056a8b87a87846fe26fef9
# -*- coding=utf8 -*- __author__ = 'admin' #@Time :2019/1/9 16:43 import time #装饰器的架子 def timmer(func): #func=test # def wrapper(name,age,gender): #以下类似都用*args,**kwargs同写 def wrapper(*args,**kwargs): #print(func) #作用域 start_time=time.time() res=func(*args,**kwargs) #就是在运行test() #...
994,820
0ceb29a3b3d91771dc78b6c1bb68ba547a5a555b
#!/usr/bin/python3 """ 11-square: class Square from Rectangle """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """ Square inherits from Rectangle Attributes: size (int): side of square Methods: __init__ - initialises the square ...
994,821
f0449bc7e3ea671e05e98252fb5c5c2620fb829d
import pytest from unittest import TestCase from moto import mock_dynamodb2 from ..dynamo_connector import DynamoConnector class TestDynamo(TestCase): """ Class to test async """ @mock_dynamodb2 def setUp(self): self.connector = DynamoConnector() @mock_dynamodb2 def tearDown(self...
994,822
cf13bfe920e97d0ee3df4cd77c88b72e0848ddfe
expected_output = { "vlan": { "vlan1": { "vlan_name": "default", "vlan_status": "active", "vlan_port": [ "Gi1/0/1", "Gi1/0/2", "Gi1/0/4", "Gi1/0/5", "Gi1/0/6", "Gi1/0/8", ...
994,823
33d4e555aea4235ec02c235bb21525260cdf8c69
from os import getcwd from scrapy.commands.parse import Command from scrapy.http.headers import Headers from scrapy.http.request import Request from scrapy.http.response.html import HtmlResponse from unittest import TestCase, main from Doc.quotes.quotes.spiders.quotes_spider_2 import QuotesSpider2 START_PAGE = '/tag/...
994,824
f82a8950bd3072a73839241220f03c9ddb53b738
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from random import choice, sample import time import unicodedata import sys import logging _LOG = logging.getLogger(__name__) from django.db import connection from django.http import HttpResponseNotFound, H...
994,825
50833190036c025a8659e08a6f49ba093a6d2c93
from celery import Celery import time import logging from app import config celery_app = Celery() celery_app.config_from_object(config) TASK_PRIORITY_HIGH = 9 TASK_PRIORITY_MEDIUM = 4 TASK_PRIORITY_LOW = 0 @celery_app.task(name="app.one.low", priority=TASK_PRIORITY_LOW) def one_low(): time.sleep(config.task_s...
994,826
3c197da02ec10310d788193a5311291dd0c7f432
from contextlib import contextmanager from thenewboston_node.core.clients.node import NodeClient @contextmanager def force_node_client(node_client: NodeClient): try: NodeClient.set_instance_cache(node_client) yield finally: NodeClient.clear_instance_cache()
994,827
97618039e190da47544cddd8a82b6ae6c42bbb15
import torch import torchvision from ptpt.log import error from pathlib import Path def get_dataset(task: str): if task in ['ffhq1024','ffhq1024-large']: transforms = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize([0.5, 0.5, 0....
994,828
b8c3acf85983b367f5cfb05abed687caa4297512
""" 클래스 속성 오버라이드 - """
994,829
7d3ae571ef7f6058e8af52bc334ca6d49f097c6f
import xml.etree.ElementTree as ET from dataclasses import dataclass from typing import List, Dict, Iterator, Optional from urllib.parse import urlparse import requests from panasonic_camera.discover import discover_panasonic_camera_devices class RejectError(Exception): pass class BusyError(Exception): pa...
994,830
fa8ea38f7b212434db36e70099da20b9dab10685
from unityagents import UnityEnvironment from maddpg import MADDPG from ddpg import ReplayBuffer import numpy as np import torch import matplotlib.pyplot as plt from collections import deque env = UnityEnvironment(file_name = "Tennis.app") brain_name = env.brain_names[0] brain = env.brains[brain_name] agent = MAD...
994,831
5c8a557a4fdd43e15765e9f9eb56cd688e005b19
from django.shortcuts import render, redirect, get_object_or_404, HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_POST from django.utils import timezone from django.contrib import messages from suds.client import Client from ecommerce.local_setting...
994,832
a24e3caafe7ee44d38a93f27de6edaa47a2a9ae7
# Classes # -> Making an object from a class is called instantiation, and you work with instances of a class. # In this chapter you’ll write classes and create instances of those classes. # You’ll specify the kind of information that can be stored in instances, and you’ll define actions that can be taken with thes...
994,833
2b294832a25c98e0d21bcc45ec7cbe1143061b3f
import socket import sys import select s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost',5285)) r,w,e = select.select([s],[],[]) msg = r[0].recv(64) if not msg: print 'server connection dropped'
994,834
bed6e9964d4d2994925788be9b76958d5a84e968
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 2 16:56:55 2017 @author: shivam """ import numpy as np import os from skimage.feature import hog from skimage import color, transform from skimage.io import imread,imshow from sklearn import svm from sklearn.externals import joblib def getkey(n)...
994,835
8cc2205c9a20450571b5332d6988b0df319f17fd
import sys import math import os import osfiles import argparse import molio from org.nmrfx.structure.chemistry.energy import RNARotamer from org.nmrfx.structure.chemistry.energy import Dihedral from org.nmrfx.structure.rna import RNAAnalysis def dumpDis(mol, fileName='distances.txt', delta=0.5, atomPat='*.H*',maxDis=...
994,836
9cc769de93bb4407dfe4d6752bb36e377bd32b1f
import cv2 img = cv2.imread('RAA_dc.png') # print(type(img)) cv2.imshow('', img) cv2.waitKey(0) #& 0xFF # if key==27: cv2.destroyAllWindows()
994,837
6a58edac3691138c2f915bb7d9c189e4d8facca3
def maxim(arr): return max(arr) print(maxim([4,1,-5,0,4,8,2,1]))
994,838
312a513f3c368fc69f8af017c60cb52edd6e730c
import pokesql.builder import pokeapi.provider provider = pokeapi.provider.PokeapiProvider() type_max = 17 print("Conecting to database...") builder = pokesql.builder.PokeSQLBuilder("localhost", "root", "yourpassword", "pokemon") print("Database connected !") print("Start building database...") builder.build_data...
994,839
ab18c38536301feaf0139e375103e5fa89f2b23f
from xai.brain.wordbase.nouns._instalment import _INSTALMENT #calss header class _INSTALMENTS(_INSTALMENT, ): def __init__(self,): _INSTALMENT.__init__(self) self.name = "INSTALMENTS" self.specie = 'nouns' self.basic = "instalment" self.jsondata = {}
994,840
de5861761f9fde47fde6cf7ba89cbdf249256709
""" Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. """ class Solution: # @param {integer} n # @return {integer} def trailingZeroes(self, n): x = 5 ans = 0 while n >= x: ans += n / x ...
994,841
8d25e7c621e97d3b9c784d80d7a55ffb0ecec9b7
#!/usr/bin/python3 import os import sys data_dir = "../data/wikipedia/" languages = ["fr", "ko"] models = ["lstm"] def read_wordlist(path): try: infile = open(path,"r") result = {line.split(" ")[0] for line in infile} infile.close() return result except OSError: print("Failed to open for wordlist creati...
994,842
dd68d8e5b8bf3f41411813979579d490caa24618
import pandas as pd from sklearn import metrics, preprocessing from sklearn.model_selection import train_test_split, GridSearchCV import numpy as np from numpy import genfromtxt from classifiers import * import matplotlib.pyplot as plt import time def main(): ''' loads dataset and learns 3 models. chooses be...
994,843
6eef084eb2b3417c6f59571bc50204088147822c
""" Intuition Return the sum of all positive differences for count of alphabets from String t in String s. """ class Solution: def solve(self, s, t): c1 = Counter(s) c2 = Counter(t) ct = 0 for i, val in c2.items(): ct += max(val - c1.get(i, 0), 0) return ct
994,844
3e46baeee6176b2bafa4e3833ec976ec7ede21dc
from django.db import models from django.contrib.auth.models import User LEVEL_CHOICES = ( ('1', 'Easy'), ('2', 'Medium'), ('3', 'Hard'), ) class Set(models.Model): title = models.CharField(max_length=200) level = models.CharField(max_length=20, choices=LEVEL_CHOICES) creator = models.ForeignKey(User, rel...
994,845
408b6a8fef4cf67be56adbd2f140f8b0a6e4dd2e
import json from pathlib import Path from configuration.config import data_dir def remove_duplication(): # res_path = (Path(data_dir)/'result.json').open('w') for l in (Path(data_dir)/'submission_object.json').open(): l = json.loads(l) mention_data = l['mention_data'] for m in mention...
994,846
6bfdf4338426c036445b8953c8b0b9ac1866aca1
# Time Limit Exceeded # probably have bug class Solution: def numDistinct(self, s: str, t: str) -> int: self.result = 0 self.arrange_combine(s, t, "") return self.result def arrange_combine(self, s, t, curr): if curr == t: self.result += 1 if s == "": ...
994,847
5e4858b3e56ab054c282e23ec9fa2c8ce73e952a
import csv import sys import logfile from os.path import exists import datetime from dateutil import parser from pprint import pprint IT_REQUESTS = 0 IT_TIME = 1 IT_SIZE = 2 IT_TIME_MAX = 3 IT_SIZE_MAX = 4 def check_last_state(log_file, config, options): state = config.get('state') if state: log_file...
994,848
a9616f07c1e6c7fb1ef9f7dd0f5491f93bc974d8
""" (C) Copyright 2021 IBM Corp. 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 law or agreed to in writing, software d...
994,849
62d7fc36559b65d707677d5fc47849ce676eb0f0
def main(): print ("PYTHON GUESSING GAME") main() answer = "dog" guess = "" while not guess == answer: print("I'm thinking of an animal") guess = input("What animal am I thinking about?") guess = guess.lower() if guess == answer: choice = input("Do you like the animal? Y for yes and...
994,850
d4606ab34391223ba8c46acac9fe969532b44b99
#!/usr/bin/python3 """ Makes sure bluetooth service is not running while suspended. """ import sys import subprocess as sp from pathlib import Path import logging logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) BT_STATE_PATH = Path("/var/tmp/bluetooth-rfkill-before-suspend"...
994,851
e35063d76b71630145927f653c2637bcae1ff786
print("Welcome to faulty calculator:This is develop by Kirtika\n") print(" + for Addition ") print(" - for Substration") print(" * for Multiply ") print(" / for Division") print(" ** for Power") print(" % for modulo\n") num1=int(input("Enter first Number:\n")) num2=int(input("Enter second Number:\n")) operation=inpu...
994,852
53eb1025d0e90bc57ff78f6b5b5f063140bc403a
from ast import literal_eval import numpy as np import pickle def filter_data(tokens_list): return [token for token in tokens_list if token != ' '] def reverse_vocab(word_dictionary): return {value: key for key, value in word_dictionary.items()} def word_level(sentence, word_dictionary, mode, checker): ...
994,853
c2bba8b1e747f7797a3cce7704e3e33c9470eba6
#!/usr/bin/python3 if __name__ == "__main__": from calculator_1 import add, sub, mul, div from sys import argv leng = len(argv[1:]) if leng != 3: print("Usage: ./100-my_calculator.py <a> <operator> <b>") exit(1) for i, arg in enumerate(argv[1:]): if i == 0: arg1 =...
994,854
186377b94c8a5207762139591eaf13b9043afc80
import random def crearLista(desde,hasta): n = int(input("Ingrese la cantidad de numeros que desea que se agreguen a la lista: ")) lista = [] for i in range(n): num = random.randint(desde,hasta) lista.append(num) return lista def sumaLista(lista): suma = 0 for i in ...
994,855
a9f093117e548b62bb7a6e21c1c22cb7630642bc
from bs4 import BeautifulSoup import urllib2 import numpy as np from numpy.linalg import inv import pandas as pd import sympy as sp from scipy import linalg import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA def Scrape(): site...
994,856
106aecc650f6563c32cc1435ca32474a2d38b3f8
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
994,857
370f1ee50fe85f35aef18f1c19b0be60c0549e58
from . import lstm all_models = { 'lstm': lstm }
994,858
18c9133cdce4bbf90300f88c67a18721ddf8ff2a
"""Module to handling Transantiago-data headers""" import os import zipfile import rarfile import gzip #import TransantiagoConstants #For Jupyter. from Utils import TransantiagoConstants defaultEtapasHeaders = TransantiagoConstants.defaultEtapasHeaders defaultViajesHeaders = TransantiagoConstants.defaultViajesHeader...
994,859
066c35f2f6f544f1c87ffab3845e3037d217b618
# Copyright (c) 2014 - 2016 Qualcomm Technologies International, Ltd. # All Rights Reserved. # Qualcomm Technologies International, Ltd. Confidential and Proprietary. # Part of BlueLab-7.1-Release # Part of the Python bindings for the kalaccess library. from ctypes import c_uint, c_void_p, POINTER from ka_ctype...
994,860
a970d068974da2473c4dea77b286eab540e25e38
from ._main import __version__ __all__ = ['__version__']
994,861
9eeba07938408d8f892bc990211f39280b15a621
''' For a 6x6 array, calculate the maximum hourglass sum where an hourglass is: a b c d e f g ''' def hourglassSum(arr): ans = 0 for x in range(int(len(arr)/2)+1): for y in range(int(len(arr[x])/2)+1): sum_nums = sum(arr[x][y:y+3]) + arr[x+1][y+1] + sum(arr[x+2][y:y+3]) ans ...
994,862
be5336924b80a93e239e778314a6c4abbc32f8dd
############################################################################### '''''' ############################################################################### from ._base import _Vanishable, _Colourable, _Fillable, _Fadable from .edges import Edges from .grid import Grid from .ticks import Ticks from .legend im...
994,863
1816c1cc03bdd006665cee1bb29836d22b7ce048
# -*- coding: utf-8 -*- MONTHS = {1: 'Января', 2: 'Февраля', 3: 'Марта', 4: 'Апреля', 5: 'Мая', 6: 'Июня', 7: 'Июля', 8: 'Августа', 9: 'Сентября', 10: 'Октября', 11: 'Ноября', 12: 'Декабря'}
994,864
8a4d08f06ef857756d908817c671af642adc6496
names = ['Michael', 'Bob', 'Tracy'] for name in names: if name == "Michael": print("指定名字:%s" %(name)) else: print(name) name1 = "liuxinchi" name2 = "liuxinchi" if name1 == name2: print(True) else: print(False); d = {}; d['Jack'] = 90 if 'Jacka' in d: print(d['Jacka']) else: p...
994,865
00a4ee01195920cd48b1dddcfa242cedc1b7f2e0
from datetime import datetime from django.db import models # Create your models here. class Owner(models.Model): name = models.CharField(max_length=50) short_name = models.CharField(max_length=20) def __unicode__(self): return self.short_name def __str__(self): return self.__unicode__()...
994,866
20d471b2dfd9ae115b862560c85f37657410e8b0
#!/usr/bin/env python # coding: utf-8 # In[1]: List = ["Name = Morali Shah", "email = shahmorali@gmail.com", "slackname = @morali", "biostack = Drug Development"] print (*List, sep = "\n") # In[ ]:
994,867
44ac278abe1062d5f2d60392e85a2e41da30734c
products_info = input().split() products = [products_info[i] for i in range(len(products_info)) if i % 2 == 0] quantities = [int(products_info[i]) for i in range(len(products_info)) if not i % 2 == 0] my_dict = dict(zip(products, quantities)) print(my_dict)
994,868
391a769fbc6e2c53c895195845914b08a462b34e
import pandas as pd def write_client_database(df_clients_path, clients_table): allRows = clients_table.rowCount() new_df = pd.DataFrame(columns=['Cliente','Dirección','RUC']) for row in range(allRows): client = clients_table.item(row,0) address = clients_table.item(row,1) ruc = clie...
994,869
f99695e711677b78587d72c7b202c68f418c58ea
# expression = input() expression = '{([]){}()}' # expression = '][' brackets = [('(', ')'), ('[', ']'), ('{', '}')] counts = all([expression.count(a) == expression.count(b) for a, b in brackets]) # do all bracket pairs counts match? order = all([expression.find(a) <= expression.find(b) for...
994,870
442978f04badc7c542d31370ae696ae3e766692f
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from c7n.manager import resources from c7n import query @resources.register("appstream-fleet") class AppStreamFleet(query.QueryResourceManager): class resource_type(query.TypeInfo): service = "appstream" enum_spec = ('d...
994,871
ba5ad38b9ad0c4db3e62e75f8f2d463a42be9ee3
data = [ [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 1], [0, 1, 1], [0, 1, 1], ] targets = [1, 1, 1, -1, -1, -1] test_data = [1, 1, 1] from sklearn.naive_bayes import MultinomialNB model = MultinomialNB() model.fit(data, targets) result = model.predict(test_data) print(result)
994,872
07fa8baeb072cf6a3b21aa8fc88b49ec5c948ba4
def num_ways(msg): if (len(msg) == 0): return 1 if (len(msg) != 1): str2 = int(msg[0:2]) msg2 = msg[2:len(msg)] msg1 = msg[1:len(msg)] if (str2 < 27): return 1 + num_ways(msg1) + num_ways(msg2) else: return 1 + num_ways(msg1) ev = "12...
994,873
be93779f45f4522e5fac0d03c80e61ec6dd0b6d5
#! /usr/bin/python3 import unittest from collections import defaultdict def mostfrequenteven(l): f = defaultdict(lambda: 0) for n in l: if n % 2 == 0: f[n] += 1 if len(f) > 0: m = max(f.values()) l = [i for i in f.keys() if f[i] == m] l.sort() return l[0] else: return -1 class T...
994,874
ff39f349bf570a99c809f3c110b057d5a98318e2
import operator class Polynomial: def __init__(self, coefss): if not coefss: self.coeffs = [0] self.degree = 0 return for i, coeff in enumerate(coefss): if not isinstance(coeff, (int, float)): raise TypeError("polynomial coeffs should...
994,875
a0ed3f1511adf47f83d3821158fccb90a907bd55
from lilaclib import * import os repo_depends = ["simgear", "flightgear-data"] build_prefix = 'extra-x86_64' def pre_build(): aur_pre_build() for line in edit_file('PKGBUILD'): if line.startswith('depends='): print("depends=('libxmu' 'openscenegraph34' 'openal' 'qt5-svg')") co...
994,876
5c69b1e64a32b18abdb3c12af378fcb587084479
firstName = "Alex " lastName = "Perrotta" print "Hello, my name is " + (firstName) + (lastName) first = raw_input("first name: ") last = raw_input("last name: ")
994,877
c1c96f50ca6721c36ef15dede27dce9ae4940a21
from .. import MMC_MASS # Neural Net feats HH_FEATURES_NN = [ "ditau_tau0_pt", "ditau_tau0_eta", "ditau_tau0_phi", "ditau_tau0_m", "ditau_tau1_pt", "ditau_tau1_eta", "ditau_tau1_phi", "ditau_tau1_m", "met_et", "met_etx", "met_ety", ] # # reco level training; go...
994,878
be1a52b2d31a41b6142df7fbae5a64a93fa3e70f
# Python doesn't provide it's own representation of LinkList, further we required a special type of \ # Link list, where the values were inserted in a sorted order # Import Node class, see Node.py for details from Node import Node class SortedLinkList: def __init__(self): self.start_node = Node(None, pr...
994,879
08169439bdf4ae6da065b30974bc1c2d2db05ce1
def formula(n:int)->int: return (3*pow(n,4)+2*pow(n,3)-3*pow(n,2)-2*n)//12 print(formula(100))
994,880
7a4a9685fa84731221afbda1d450081575f8da0f
# OCSP command-line test tool? openssl ocsp -whatever
994,881
51d538d5d5107a1939195d6cf5c83ff13a12427f
import math def cos_exp(x): return(math.cos(x)*math.exp(x))
994,882
85665cdbb51d101ef7f61a4c3e3a467a6ed3091d
def template_text(x, y, z): return f'{x}時の{y}は{z}' def test_template_text(): assert template_text(12, '気温', 22.4) == '12時の気温は22.4' print(template_text(12, '気温', 22.4))
994,883
830f633f0da3ed37989732c593ebff43cf5247fc
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def getAllElements(root1, root2): arr1 = [] arr2 = [] if(root1): arr1 = inorder(root1,arr1) if(root2): arr2 = inorder(root2,arr2) N = len(arr1) M ...
994,884
c09034c1d14c0b27f18a9316c232c8e758750625
from PyQt5 import QtCore, QtGui, QtWidgets import random import sys class Ui_MainWindow(QtWidgets.QMainWindow): def __init__(self, bo, rounter, app, MainWindow, c_pl, pl_n): super(Ui_MainWindow, self).__init__() self.navhov = False self.setMouseTracking(True) self.gS_l = ["Started"...
994,885
1d97998f2946c068f8d5b5a41f707b6f4fae207d
import csv import argparse import pathlib import logging import os import traceback import datetime import redis from dotenv import load_dotenv from multiprocessing import Pool from services import Postgres from psycopg2.extensions import AsIs from constants import county_csv_headers, date_keys from common import repla...
994,886
660deeef18163545053ea6fc8e69234e3707f125
from functools import reduce import pydash as _ from toolz import pipe from progressbar import progressbar import utils as u from data_cleaners import clean_page def is_valid_page(page): '''Invalid pages are images or disambiguation pages that were not flagged at the parser level. Also check that the page has more ...
994,887
97b0938118ac418024deaeecb4338a80a82657bb
# -*- coding: utf-8 -*- import os import sys def entrypoint_exists(entry_point): if sys.platform == "win32": entry_point += ".exe" executable_dir = os.path.dirname(sys.executable) return os.path.exists(os.path.join(executable_dir, entry_point))
994,888
06593b574344ab888faad19841950b7dda541857
import final_project as fp # Example string input. Use it to test your code. example_input="John is connected to Bryant, Debra, Walter.\ John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\ Bryant is connected to Olive, Ollie, Freda, Mercedes.\ Bryant likes to play City Comptroller: The Fiscal...
994,889
33ec20f9abbd052635cd0619920d7d43984fdafa
import tensorflow as tf import awesome_gans.modules as t tf.set_random_seed(777) # reproducibility class CycleGAN: def __init__( self, s, batch_size=8, height=128, width=128, channel=3, sample_num=1 * 1, sample_size=1, df_dim=64, g...
994,890
40f634813d86c0b52491af676c89dece532efc20
import requests from bs4 import BeautifulSoup #pulling all homepage content to test out the web-scraper url = 'http://mothertreewellness.com' response = requests.get(url, timeout = 5) content = BeautifulSoup( response.content, "html.parser") print (content)
994,891
35e15d19521612ef418e84821edc2099a9f8c00b
# Generated by Django 3.1.7 on 2021-03-25 12:45 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('United', '0007_auto_20210304_1552'), ] operations = [ migrations.CreateMod...
994,892
3648836158d0134512a2e697a293eee997d0a7e9
"""Base class of stress testing""" import time import logging import sys from logging.handlers import RotatingFileHandler from selenium.webdriver import Firefox as ffx from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_cond...
994,893
dd34c4979e6fc2d07f93017346284566a521ac7b
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # __author__:吕从雷 import pandas as pd import re filt = re.compile('\n') f = open('../liepin/workyear_data/workyear.txt') def load_data(): ''' 加载从hive导出的原始数据,以及过滤不相关数据 :return: work_list ''' line = f.readline() work_list = [] while line: ...
994,894
7ce7c709a373019279571b81c63e34b2d5b8985c
import parsl from parsl.app.app import python_app from parsl.tests.configs.local_threads import config from parsl.executors.errors import UnsupportedFeatureError from parsl.executors import WorkQueueExecutor @python_app def double(x, parsl_resource_specification={}): return x * 2 def test_resource(n=2): spe...
994,895
9d1cc84eaa3b14881de9675bcbafe42cdff34522
from unittest import TestCase import numpy as np from numpy.testing import assert_allclose from graphdg.standardize import ArrayStandardizer class TestNormalizers(TestCase): def setUp(self): self.matrix = np.array([ [0, 1, 2], [1, 2, 4], ]) def test_standardize(self)...
994,896
b5a79cbbc5a5705478af6d71de398fbcab52b8ab
from django.conf.urls import url from . import views app_name = 'TransportationManagement' urlpatterns = [ url(r'^$',views.need_login, name='login'), url(r'^index/$', views.index, name='index'), url(r'^hello/$', views.hello, name='hello'), url(r'^test/$', views.test, name='test'), url(r'^accident/...
994,897
38c0e5040e53822de7751dcde252f4e38c2f189a
#!/usr/bin/env python import os import numpy import multiprocessing __MULTIPROCESSING__ = True # Enulate HW - for testing without hardware __EMULATE_HW__ = False # Simulate Events = for testing __SIMULATE_EVENTS__ = True
994,898
e210a3f9fda1c9fda34269f34f7d7db6a129c630
#!/usr/bin/python """@package OSCServer Documentation for this module """ import sys sys.path.append("/usr/local/pltn/Modules") from OSC import OSCServer from CommonLED import CommonLED from Effects import Effects import time from subprocess import call import threading from pltnGpio import pltnGpio #import ledTwitte...
994,899
50e22fb1bb8918b9b1c5185b31d79398ef653a2e
# -*- coding: utf-8 -*- from __future__ import print_function from acq4.util import Qt import pyqtgraph as pg from acq4.util.debug import Profiler Ui_Form = Qt.importTemplate('.atlasCtrlTemplate') class Atlas(Qt.QObject): DBIdentity = None """An Atlas is responsible for determining the position of ...