text stringlengths 38 1.54M |
|---|
def my_sum(a, b):
return a + b
def my_max(a, b):
if a > b:
return a
else:
return b
|
"""
Given an Array, Find the maximum sun sub-array
I/P:
a = [1, 2, 5, -7, 1, 2]
O/P:
[1, 2, 5]
Explanation:
sum of sub array [1, 2, 5] is 8 and it is maximum sum of all sub-array of given array.
"""
def get_max_sum_subarray(arr):
maxi = 0
element_sum = 0
main_max = 0
temp = []
for i in arr:
... |
def position(liste:list,element:int) -> int:
"""Fonction qui renvoie l'index d'un élément dans une liste
Args:
liste (list): Liste dans laquelle sera fait la recherche
element (int): Element a chercher
Returns:
int: index de l'élement ou -1 si pas présent
"""
res = -1
... |
"""Functions for interacting with the RSCB PDB web services."""
import requests
import xml.etree.ElementTree as ElementTree
import molecupy
ROOT_URL = "http://www.rcsb.org/pdb/rest/"
advanced_search_xml = """<orgPdbQuery>
<queryType>org.pdb.query.simple.%s</queryType>
%s
</orgPdbQuery>"""
def query_rcsb... |
# some guidance from https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/
# and http://henrysbench.capnfatz.com/henrys-bench/arduino-sensors-and-input/arduino-hc-sr501-motion-sensor-tutorial/
from subprocess import call
def screen_on(value):
call(["vcgencmd", "display_power", "1" if value else "0"])
try:... |
from .constants import APPLICATION_NAME, APPLICATION_PASSWORD, MERCHANT_CODE, REFENCE_NUMBER_PREFIX
from datetime import datetime
import random
"""
These are static util function which are implemented to create request dicts for each api service with given parameters
These functions are related to api's paymen... |
# Copyright 2021, The TensorFlow Federated 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 law o... |
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
# pass attack band because it is hard to do reversely, so storing as global var is bad
# This is smart approach, we store the left/right projection on the first row of each... |
from controls import *
from send_email import activation_email
import json
class PostForm():
def __init__(self):
self.current = request_info()
self.filled = filled_reqs()
self.leng = len(self.current)
self.leng_2 = len(self.filled)
self.state="normal"
if self.current == [[]]:
self.leng=0
if self.fi... |
import mimetypes
import os
from multiprocessing.pool import ThreadPool
import boto3
SITE_DIR = '_site'
s3 = boto3.client('s3')
def is_woff(path):
return path.endswith('woff') or path.endswith('woff2')
def upload_file(args):
filepath, mime = args
key = filepath.replace(SITE_DIR + '/', '')
print 'Uplo... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:\Users\lex\py_proj\survillace_generator\main_window.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
... |
def short_circuiting(is_Friend = True,is_User = True):
#Short Circuiting
if is_Friend or is_User:
print("best friends forever") |
import gym
from gym import spaces
import numpy as np
import random
from envs.maze_layouts import maze_layouts
class ContinualParticleMaze():
"""
Particle maze for continual learning. Mazes should be set by a runner class
of the environment; see agent.py for an example.
"""
def __init__(self, grid... |
# Generated by Django 2.1.7 on 2020-10-30 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('board', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='bb',
options={'ordering': ['-published... |
import numpy as np
from typing import Dict, List
from .document import Document
from .vectorizers import TfidfVectorizer, CountVectorizer
class Comparator:
"""
API used for loading and comparing documents.
"""
def __init__(self, path: str) -> None:
self._doc = self.load_document(path)
... |
# -*- coding: utf-8 -*-
import scrapy
from ganji.items import AutohomeItem_koubei
import time
from scrapy.conf import settings
from scrapy.mail import MailSender
import logging
import json
website ='autohome_koubei'
class CarSpider(scrapy.Spider):
name = website
allowed_domains = ["autohome.com... |
import sys
ranks = ['2', '3', '4', '5', '6', '7', '8',
'9', '10', 'J', 'Q', 'K', 'A']
class Card:
def __init__(self, card, trump):
self.suit = card[-1]
self.rank = ranks.index(card[:-1])
self.is_trump = self.suit == trump
def draws_with(self, other):
if not self.... |
#!/usr/bin/env python
import struct
import Config
from Util import Util
class MsgHead:
parser = struct.Struct('=iibb%dsiii' % (Config.IDLEN + 2))
_fields = ['pos', 'len', 'sent', 'mode', ['id', 1, Config.IDLEN + 2], 'time', 'frompid', 'topid']
#struct msghead
size = parser.size
def unpack(sel... |
from paytmpg.pg.request.ExtraParameterMap import ExtraParameterMap
from paytmpg.pg.utils.stringUtil import make_string, equals
class RefundBaseRequest(ExtraParameterMap):
def __init__(self):
self.mid = None
self.orderId = None
self.refId = None
super(RefundBaseRequest, self).__ini... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Contains functions and class definitinos for supervised training of a
multiclass gaussian model
Created on Wed Nov 30 20:56:56 2016
@author: ibackus
"""
import numpy as np
import utils
class GaussianModel():
"""
GaussianModel() fits multiple gaussians to th... |
import unittest
from unittest.mock import patch, MagicMock
import pytest
from adk.src.adk.builtin_steps.automation.execute_script.ebs.create_ebs_volume import CreateEbsVolume
@pytest.mark.unit_test
class TestCreateEbsVolume(unittest.TestCase):
def setUp(self):
self.patcher = patch('boto3.client')
... |
import FWCore.ParameterSet.Config as cms
from RecoEgamma.EgammaElectronProducers.gsfElectronSequence_cff import *
from RecoEgamma.EgammaElectronProducers.uncleanedOnlyElectronSequence_cff import *
from RecoEgamma.EgammaPhotonProducers.photonSequence_cff import *
from RecoEgamma.EgammaPhotonProducers.conversionSequence... |
import numpy as np
from vtk_rw import read_vtk, write_vtk
iterations = 1000
hemis = ['rh', 'lh']
mesh_file="/scr/ilz3/myelinconnect/new_groupavg/surfs/lowres/%s_lowres_new.vtk"
t1_file = '/scr/ilz3/myelinconnect/new_groupavg/t1/smooth_3/%s_t1_avg_smooth_3.npy'
mask_file = '/scr/ilz3/myelinconnect/new_groupavg/masks/%... |
from bs4 import BeautifulSoup
import os
import codecs
MAPPING = {
"code":2,
"title":3,
"people":4,
"organization":5
}
def main():
in_dir = r"/Users/liuyang/Desktop/nsfc" # html
out_file = in_dir + os.sep + "out.csv" # csv
htmls = get_all_html(in_dir)
data = []
for h in htmls:
... |
def banknotes(values, price):
for i in values:
if i > price:
values.remove(i)
papers = [price + 1] * (1 + max(values))
for i in values:
papers[i] = 1
for i in range(1 + max(values), price + 1):
papers.append(1 + min([papers[i - j] for j in values]))
return -1 if... |
from setuptools import setup
setup(
name='ferret',
version='1.0',
description='A data collection and analysis tool for Politics & War.',
author='Lyrositor',
packages=['ferret'],
python_requires='>=3.5',
install_requires=['tornado', 'transcrypt', 'sqlalchemy', 'requests',
... |
# -*- coding: utf-8 -*-
from Parser import Parser, Document
from Indexer import IndexerSimple
from Models import ModeleLangue, Okapi
from Query import QueryParser
from Metrics import Precision, Rappel, FMesure, AvgPrecision, ReciprocalRank, NDCG
from Eval import EvalIRModel
import numpy as np
import pandas as pd
#///... |
# Generated by Django 3.1.4 on 2020-12-17 10:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('checkout', '0003_auto_20201215_2000'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='delivery_cost',
... |
import logging
# from conf import settings
# import conf.settings
# from conf import settings
# from bin import atm
import os
import sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
import logging
from conf import settings
def logger(log_type):
logger=logging.getL... |
import io
import sys
import base64
import traceback
import numpy as np
import skimage
import skimage.io
import skimage.segmentation
from skimage.measure import regionprops
class ImageProcessor:
def __init__(self):
pass
def convert_image_b64string_to_ndarray(self, base64_image):
encoded = base64.b64decode... |
import numpy as np
from SALib.analyze import delta
from SALib.sample import latin
from fishery import fish_game
import matplotlib.pyplot as plt
# Set up dictionary with system parameters
problem = {
'num_vars': 9,
'names': ['a', 'b', 'c', 'd','h',
'K','m','sigmaX','sigmaY'],
'bounds': [[ 0.002, 2],
... |
# Copyright ServiceNow, Inc. 2021 – 2022
# This source code is licensed under the Apache 2.0 license found in the LICENSE file
# in the root directory of this source tree.
import abc
import json
import os
import time
from typing import List, Optional
import h5py
import structlog
from filelock import FileLock
from ret... |
class Solution(object):
def wordPattern(self, pattern, str):
map1,map2 = {},{}
strs = str.strip().split(" ")
pattern = list(pattern)
if len(pattern) != len(strs):return False
for s,c in zip(strs,pattern):
if s not in map1 and c not in map2:
map1[s]... |
import numpy
class TelemeterAiData:
def __init__(self):
self.state = numpy.uint8(0)
self.cpu = numpy.uint8(0)
self.run_number = numpy.uint8(0)
self.output_file_number = numpy.uint8(0)
self.crc = numpy.uint8(0)
def concat_data(self):
ai_data = numpy.ui... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
''' - Lecture de la table ROUND_MATCH
- saisie les scores du tour
- Mise à jour de la date de fin du tour en question ROUND
- Ecriture dans la table SCORE
- Rmise à blanc de la table ROUND_MATCH'''
import tkinter as tk
from tkinter.constants import DISABL... |
from django.contrib import admin
from .models import Product
# Register your models here.
@admin.register(Product)
class Product(admin.ModelAdmin):
list_display = ['name','weight','price','created_at','updated_at']
list_filter = ['created_at',]
list_editable = ['weight','price']
ordering = ['-price',] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Alex
# @Date: 2015-12-29 23:06:32
# @Last Modified by: Alex
# @Last Modified time: 2015-12-29 23:07:45
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length=50)
password = forms.CharField(max_length=50,
... |
import sys
sys.stdin = open('input.txt')
def realnum(password):
i = 1
while len(password) > 1:
if i >= len(password):
break
current = password.pop(-i)
if current == password[-i]:
password.pop(-i)
if i > 1:
i -= 1
else:
... |
from struct import *
from math import *
import cmath
import scipy
from numpy import *
from scipy.signal import *
import sys
#from os import *
import os
linen=10000
outn=1500
lines=int(sys.argv[2])
fi=open(sys.argv[1]+".bin","rb")
fi.seek(2*int(sys.argv[3])*10000,os.SEEK_SET)
f2=open(sys.argv[1]+"_"+sys.argv[3]+"mag.... |
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
'''
Created on 2018年7月2日
@author: Administrator
'''
from sklearn import linear_model, datasets
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
def linear_regression_example():
# 加载糖尿病数据样本
dia... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 23:05:20 2019
@author: duck
"""
from matplotlib import pyplot as plt
"""with open("outputfile.dat", "r") as out:
lines = out.readlines()
A = []; B = [];
for i in lines:
print "i, len(i), i[0:7]:", i, len(i), i[0:7]
... |
import pandas as pd
from chip2probe.sitespredict.imads import iMADS
from chip2probe.sitespredict.imadsmodel import iMADSModel
from chip2probe.sitespredict.pbmescore import PBMEscore
from chip2probe.sitespredict.kompas import Kompas
from chip2probe.sitespredict.sitesplotter import SitesPlotter
seq = "TTACGGCAAGCGGGCCG... |
from kerastuner import RandomSearch
from tensorflow.keras import utils
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.res... |
from lib import game
import json
import copy
import Tree
import pylos as pyl
class Tree_Generator():
'''Creates the Tree chart for PylosAI'''
def __init__(self):
pass
def board_free(self, state):
'''
travel the board and save all the free positions in a list
... |
## Functions to get COVID/population/school data from the web
import plotly.graph_objects as go
import dash
import numpy as np
import requests
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html
import plotly.figure_factory as ff
import pandas as pd
import json
from io imp... |
# coding: utf-8
""" Data generation example.
"""
import os
is_travis = ('TRAVIS' in os.environ)
if is_travis:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from pybold.data import gen_rnd_bloc_bold
from pybold.hrf_model import spm_hrf
from pybold.utils import fwhm, ... |
import cv2
import numpy as np
img = cv2.imread("colorBalls.jpg")
HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
verdeoInf = np.array([70,100,100])
verdeoSup = np.array([100,255,255])
verdeoMask = cv2.inRange(HSV,verdeoInf,verdeoSup)
res = cv2.bitwise_and(img, img, mask=verdeoMask)
cv2.imshow('img', img)
cv2.imshow('mask', ... |
#!/usr/bin/env python
# coding: utf-8
# # THE SPARKS FOUNDATION
#
# # VIVISHA SINGH
# # Data Science and Business Analytics
# # Task-1
# # Prediction using Supervised ML
# # Predict the percentage of an student based on the no. of study hours.
# In[ ]:
#importing all libraries
import numpy as np
import pandas as ... |
import numpy
from numpy.random import randn
import matplotlib.pyplot as plt
#A Brief matplotlib API Primer
fig = plt.figure()
#to adjust the figure
fig.subplots_adjust(left=0.0, bottom=None, right=1.2, top=None,
wspace=0, hspace=None)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplo... |
import torch
def arrange_data(data_tmp, M, gen_rand_indx, rand_idx):
# Extracts a batch of data from the dataset loader
x_tmp = []
v_tmp = []
for data in data_tmp:
x_tmp.append(torch.stack([x[0] for x in data]))
v_tmp.append(torch.stack([v[1] for v in data]))
if gen_rand_indx:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
信号槽连接滑块LCD
'''
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout, QLCDNumber, QSlider
from PyQt5.QtCore import Qt
class WinForm(QWidget):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.initUI(... |
#!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
from constants import get_all_emotions, get_all_features
from itertools import islice
import glob
import csv
import pdb
def get_defined_landmarks(file_path):
'''
Retrieve landmarks defined in lm2 file
'''
defined_landmarks = []
with open(file_path) as file:
... |
import unittest
from database.src.Database import Database
from web.service.github.api.v3.AuthenticationsCreator import AuthenticationsCreator
from web.service.github.api.v3.authentication.Authentication import Authentication
from web.service.github.api.v3.authentication.NonAuthentication import NonAuthentication
from ... |
t = int(input().strip())
for i in range(t):
n,c,m = input().strip().split(' ')
n,c,m = [int(n),int(c),int(m)]
tot_choc=n//c
wrap=tot_choc
#print(tot_choc, wrap)
while wrap >= m:
extra_choc = wrap//m
wrap-=m*extra_choc
wrap+=extra_choc
tot_choc+= extra_c... |
"""
Combat handler.
"""
from muddery.server.combat.combat_runner.base_combat import BaseCombat, CStatus
from muddery.server.utils.honours_handler import HONOURS_HANDLER
class HonourCombat(BaseCombat):
"""
This implements the honour combat handler.
"""
def __del__(self):
"""
This hook ... |
""" Chalenge 167 Task 1 Python"""
from sympy import isprime, nextprime
def is_circular_prime(prime: int) -> bool:
"""
Checks if a prime number is circular prime.
"""
prime_str = str(prime)
for i in range(len(prime_str)):
if not isprime(int(prime_str[i:] + prime_str[:i])):
retu... |
from neuron import h
from utils.cell import Cell
class TableCell(Cell):
def _create_cell(self):
self.section = h.Section()
self.section.insert("table")
def record(self):
tvec = h.Vector()
tvec.record(h._ref_t, sec=self.section)
avec = h.Vector()
avec.record(se... |
import os
import statistics
import numpy as np
import matplotlib.pyplot as plt
def LCG(x, a=np.uint64(1664525), c=np.uint64(1013904223)):
"""Linear Congruential Generator
Args:
x (int): Seed
a (uint64, optional): Miltiplier. Defaults to np.uint64(1664525).
c (uint64, optional): Increm... |
''' Sprawdzanie czy graf nieskierowany jest dwudzielny (czyli czy da się podzielić jego
wierzchołki na dwa zbiory, takie że krawędzie łączą jedynie wierzchołki z różnych zbiorów) '''
# robimy BFS (lub DFS) przydzielajac wiercholkom "kolory"
from collections import deque
def isBipartite(G,s): # s - wierzcholek st... |
from django.shortcuts import render
from .models import Wheel, Nav, test_table
from django.forms.models import model_to_dict
from django.core import serializers
import json
import pandas as pd
from django.http import HttpResponse
from data_static import *
# Create your views here.
def jsdaoru(request):
wheelsLi... |
n = int(input())
li = list(map(int, input().split()))
cnt_li = [1]*n
min_v = min(li)
for i in range(1, n):
tmp = -1
k = -1
bol = 0
for j in range(i):
if li[j] < li[i]:
if cnt_li[j] > tmp:
tmp = cnt_li[j]
k = j
bol = 1
if bol == 1:
cnt_li[i] = cnt_li[k]+1
else:
cnt_li[i] = 1
print(... |
from AlgoExpert.patternmatcher import patternMatcher
import unittest
class TestProgram(unittest.TestCase):
def test_case_1(self):
self.assertEqual(patternMatcher(
"xxyxxy", "gogopowerrangergogopowerranger"), ["go", "powerranger"])
|
#https://programmers.co.kr/learn/courses/30/lessons/42862
def solution(n, lost, reserve):
lost = set(lost)
reserve = set(reserve)
both = lost.intersection(reserve)
lost = lost.difference(both)
reserve = reserve.difference(both)
students = ['student']*n
for l in lost:
students[l-1] ... |
from timeit import default_timer as timer
from pydispatch import dispatcher
from webserver import WebServer
import subprocess
import time
import random
import math
Web_Server = WebServer() # Webserver running on BBB for an HTML interface
try:
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
e... |
# 2019 카카오 개발자 겨울 인턴십 / 튜플
# https://programmers.co.kr/learn/courses/30/lessons/64065?language=python3
import sys
input = sys.stdin.readline
def solution(s):
answer = []
ss = s[2:-2].split("},{")
ss.sort(key = len)
for i in ss:
arr = i.split(",")
for a in arr:
if int(a) not ... |
#it prints the birthday message
def name():
x = str(input("Enter your name\n"))
print("Happy Birthday" ,x)
name() |
def count_set_bits(n):
count = 0
while n != 0:
if (n & 1) > 0:
count += 1
n = n >> 1
return count
def count_set_bits_brian_kerningam(n):
count = 0
while n > 0:
n = n & (n - 1) # 4 = 100, 3 = 011 bitwise & will make left most bit 0. This is true for all n and... |
import configparser
import os.path
import requests
import smtplib
import json
config = configparser.ConfigParser()
if os.path.isfile('weathermailer_custom.conf'):
config.read('weathermailer_custom.conf')
else:
config.read('weathermailer.conf')
phonenumber = list(config.items('phonenumbers'))
smtpserver = conf... |
#!/usr/bin/env python
import sys
import os
import argparse
from termcolor import colored
import json
from json import encoder
import logging
import subprocess
from ampyutils import exeprogram, amutils, location
import am_config as amc
__author__ = 'amuls'
def treatCmdOpts(argv: list):
"""
Treats the comman... |
import json
import logging
import os
import random
import time
import requests
import pyfiglet
from pathlib import Path
from flask import (Flask, flash, jsonify, make_response, redirect,
render_template, request, url_for)
from flask_wtf import FlaskForm
# Flask app
app = Flask(__name__, template_f... |
#necessary
import pygame, sys, time, random
from pygame.locals import *
#creating the 'Hoop' class
class Hoop(pygame.sprite.Sprite):
#making the hoop sprite
def __init__(self,x):
super().__init__()
#the x coordinate and making it's rectangle
#note the rectangle is only the top line o... |
import requests
from PyQt5.QtCore import QThread
from PyQt5.QtCore import pyqtSignal
from bs4 import BeautifulSoup
agent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.8 Mobile Safari/537.36'
baseUrl = "http://club.sanguosha.com/forum.php?mod=viewthrea... |
import unittest
import pytest
from unittest.mock import patch, MagicMock
import resource_manager.src.util.common_test_utils as common_test_utils
import resource_manager.src.util.boto3_client_factory as client_factory
SERVICE_NAME = 'some_service'
@pytest.mark.unit_test
class TestCommonTestUtil(unittest.TestCase):
... |
#
# Copyright 2015-2020 Andrey Galkin <andrey@futoin.org>
#
# 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 applicabl... |
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dpRob0=[0]*len(nums)
dpNotRob0=[0]*len(nums)
dpRob0[0]=nums[0]
dpRob0[1]=0 #####
for i in range(2,len(nums)-1):
for j in range(i-1):
... |
import sqlite3
import argparse
from gensim.models.doc2vec import Doc2Vec
import numpy as np
from gensim import matutils
import itertools
from sklearn.preprocessing import normalize
from random import shuffle
def getItemReviews(item, db):
con = sqlite3.connect(db)
c = con.cursor()
c.execute("SELECT user,ra... |
import pandas as pd
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# Load data
data = pd.read_csv("MarvellousInfosystems_PlayPredictor.csv")
# print(data.head())
# data['Play'].uniqu... |
from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from dummy_task import dummyVal
def print_hello():
return 'Hello world!'
dag = DAG('hello_world', description='Simple tutorial DAG',
schedule_interval='*/3 * * * *',
start_date=... |
class Solution(object):
def hammingWeight(self, n):
res = 0
while n:
res += n%2
n = n//2
return res |
import matplotlib.pyplot as plt
import pandas as pd
from bs4 import BeautifulSoup
from requests import get
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
fromyear = int(input("Enter From Year: "))
tillyear = int(input("Till Year: "))
# Redeclaring the lists to store data in
name... |
import pygame, time, sys
pygame.init()
pygame.time.delay(100)
WIDTH= 600
HEIGHT= 400
#create the object
bg= pygame.image.load("Images/courtBACKGROUND.jpg")
dROSE= pygame.image.load("Images/roseSPRITE.jpg")
##create object to open window
screen= pygame.display.set_mode((WIDTH, HEIGHT))
white= (255, 255, 255)
black= (0... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# gen.py
# Diceware passphrase generator.
# More info: https://www.eff.org/dice
# Note: This uses secrets, has protection against shell injection attacks,
# and I have tried to keep things as secure as possible however the best way to
# generate diceware passphrases is by han... |
#!flask/bin/python
# ! /usr/bin/env python
# coding=utf-8
from flask import Flask, jsonify, abort, request, render_template, redirect, url_for, flash, send_from_directory, send_file
from werkzeug.utils import secure_filename
from app import app
import json
import os
from jtnltk import qacorpus, frequency, synon... |
import os
from importlib import util
from unittest import TestCase
import pandas as pd
from proxy_builder import RidgeCSRegression
class TestRidgeCSRegression(TestCase):
def setUp(self) -> None:
pkg_name = "proxy_builder_tests.test_files"
file_train_input = "cds_spreads_data_all.csv"
sp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-01-25 08:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('internship', '0029_auto_20180122_2251'),
]
operations = [
migrations.RemoveFie... |
#!/usr/bin/env python
import math
def dist(x1, y1, x2, y2):
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
def avg(gen):
total = 0
n = 0
for i in gen:
total += i
n += 1
return float(total) / float(n)
|
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
height_new = float(height)
weight_new = float(weight)
bmi = weight_new / height_new**2
bmi_final = print(int(bmi))
|
"""
this is the main script, that will take ages, for sure.
"""
from typing import List, Tuple, Optional, Callable
from identify_idioms.service import build_iip
from idiom2vec.cleaners import Cleaner, CocaSpokCleaner, CocaMagCleaner, OpenSubCleaner
from idiom2vec.paths import (
OPENSUB_ORIGIN_SPLITS_DIR,
OPENSU... |
#to input the list and find sum of numbers in list except one number and print them
limit=int(input("enter limit"))
lst=list()
for i in range(0,limit):
number=int(input("enter number"))
lst.append(number)
#finding total of list
#total=20
#20-2=18
#20-5=15
#20-6=14
#20-7=13
out=list() #empty list
total=sum(lst... |
#!/usr/bin/env python
# Copyright 2019 Pascal Audet & Helen Janiszewski
#
# This file is part of OBStools.
#
# 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 wi... |
from flask import Flask, request, url_for, session
import mysql.connector
from mysql.connector import (connection)
import re
import requests
from flask_session import Session
from passlib.hash import sha256_crypt
app = Flask(__name__)
app.config["DEBUG"] = True
app.secret_key = 'your secret key'
app.confi... |
from django.urls import path
from.import views
urlpatterns=[
path('',views.home,name="home"),
path('register',views.register,name='register'),
path('login',views.login,name='login'),
path('logout',views.logout,name='logout'),
path('arts',views.arts,name='arts'),
] |
from Persons import *
from random import *
# from endings import *
from FUFS import *
def getStatus(self):
self.player1.showName()
self.player1.showHappyStatus()
self.player1.showParentStatus()
self.player1.showMarriedStatus()
self.player1.showAliveStatus()
self.player1.showGood()
self.pla... |
import argparse
import logging
import os
import sys
from core.logger import LOGGER_NAME, setup_logging
from vincere import VincereAPI
from vincere.candidate import CandidateAPI
logger = logging.getLogger(LOGGER_NAME)
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.st... |
#! /usr/bin/env python
for i in range(2):
print "this is before continue"
continue
print "this is after the countinue statement "
|
import pandas as pd
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
import numpy as np
from io import BytesIO
from PIL import Image
import base64
import keras
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Dense, Activati... |
import pandas as pd
import matplotlib.pyplot as plt
xlsx = pd.ExcelFile(r'D:\isi7\Python\1cwiczenia\wd_cw8\imiona.xlsx')
df = pd.read_excel(xlsx)
Kob = df[df['Plec']==('K')].agg({'Liczba':['sum']})
Men = df[df['Plec']==('M')].agg({'Liczba':['sum']})
lista = df.groupby(['Plec']).agg({'Liczba':['sum']})
etykiety... |
'''
.. py:module:: tinyurl
:platform: Unix
Shorten URL by querying Tinyurl.com
'''
import urllib
base_url = 'http://tinyurl.com/api-create.php?url='
def get(url):
'''Shorten given URL.
:param url: URL to shorten
:type url: str
:returns: str -- URL shortened by querying tinyurl.com
''... |
from __future__ import annotations
from prettyqt import core
from prettyqt.qt import QtCharts
class AbstractSeriesMixin(core.ObjectMixin):
pass
class AbstractSeries(AbstractSeriesMixin, QtCharts.QAbstractSeries):
pass
|
f = open('email.txt')
try:
f.write() # raise Exception()
except Exception:
pass
finally:
f.close() # Never closed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.