text stringlengths 38 1.54M |
|---|
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.http import Http404
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from .models import Note
from .models ... |
class Solution(object):
def generateParenthesis(self, n):
def generate(current, opening_params_available, unclosed_opening_params):
#if we have used all "(" and need to close the paranthesis
if opening_params_available == 0:
return (current+')'*unclosed_opening_params... |
class Questions:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompt = [
"Are you working on a project?"
if yes:
print(Awseome! What kind of music do you like)
question_prompt = [
"
]
else:
ask next question
... |
from sklearn.cluster import KMeans
import numpy as np
import torch
__all__ = ['get_kMeans_indices']
def knn(ref, query):
"""return indices of ref for each query point. L2 norm
Args:
ref ([type]): points * 3
query ([type]): tar_points * 3
Returns:
[knn]: distance = query * 1 , ind... |
import sys
from itertools import starmap
from typing import Sequence, Mapping, Text, Callable, Optional, IO, Any, Iterable
import copy
import numpy as np
from fn.op import identity
from keras import callbacks
from keras.models import Model
class Validator(callbacks.Callback):
modes = ('max', 'min')
# TODO d... |
import types
import os.path
from threading import Thread
import time
from octoprint_powerbutton.power_states import *
SYSFS_GPIO = '/sys/class/gpio'
LED_COLOR_OFF = 0
LED_COLOR_RED = 1
LED_COLOR_GREEN = 2
LED_COLOR_YELLOW = 3
SHORT_PERIOD = 15
LONG_PERIOD = 50
def prop_or_default(dict, prop, default = None):
re... |
from ui import MainView
import socket,re,sys,threading
class Tcp_client(MainView.Ui_MainWindow):
def __init__(self):
super(Tcp_client, self).__init__()
self.tcp_socket = None
self.server_threading = None
self.client_threading = None
self.client_socket_list = list()
... |
##Prime Numbers with a Twist
##Ques. Write a code to check whether no is prime or not. Condition use function check() to find whether entered no is positive or negative ,if negative then enter the no, And if yes pas no as a parameter to prime() and check whether no is prime or not?
##
##Whether the number is positiv... |
import os
import cv2
import numpy as np
from skimage.segmentation import slic
import LJY_utils
from My_Lib.experiment import LM_Filter
from LJY_legacy.Automatic_Polyp_Detection import superpixel, mask_converter
def min_max_refresh(data, minmax):
if np.max(data)>minmax[1]:
minmax[1] = np.max(data)
if... |
import pytest
from pages.basket_page import BasketPage
from pages.login_page import LoginPage
from pages.main_page import MainPage
from pages.product_page import ProductPage
link = "http://selenium1py.pythonanywhere.com/"
@pytest.mark.login_guest
class TestLoginFromMainPage:
def test_guest_can_go_to_login_page... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.layers.python.layers import utils
def inference(inputs, batch_size, num_classes, training=True):
with tf.variable_scope('inference') as sc:
end_points_collection = sc.original_name_scope + '_end_points'
with sli... |
i=0
j = 0
"""
while (i<10):
print(i,end=" ")
i=i+1
"""
while (True):
if j<5:
print(j)
j=j+1
continue
print(j*2)
j = j + 1
if(j==10):
break
|
import os
from unittest import skip
from template import Template
from template.test import TestCase, main
@skip('Does not work on python >= 2.7')
class CompileTest(TestCase):
def testCompile(self):
ttcfg = {"POST_CHOMP": 1,
"INCLUDE_PATH": "test/src",
"COMPILE_EXT": ".t... |
# About Networks Explanation
import igraph as ig
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from textwrap import dedent as d
import numpy as np
# Python code to render networks and figures
def explain_make_network(n, p, style = 'Erdős–Rényi Random Graph', co... |
# ----------------------------------------------------------------------------
# 10-3. Guest: Write a program that prompts the user for their name. When they
# respond, write their name to a file called guest.txt.
# ----------------------------------------------------------------------------
name_0 = raw_input("What's ... |
# Copyright (C) 2016-2017 Virgil Security Inc.
#
# Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistribution... |
import os, sys
# Change this to wherever you've installed Penguz.
# Everything else in this file can stay as is.
django_root = os.path.join('/', 'var', 'django')
sys.path.append(django_root)
sys.path.append(os.path.join(django_root, 'penguz'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'penguz.settings'
import django.c... |
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import pandas as pd
df = pd.read_csv('AADR.csv')
df.set_index(pd.DatetimeIndex(df['Date'].values), inplace=True)
df.index.name = "Date"
df.drop(columns='Date', inplace=True)
df['Price_up'] = np.where... |
p = float(input('O preço do produto é R$'))
d = 5
pd = p - (p * d/100)
print('O produto que custava R${}, na promoção com desconto de {}% vai custar R${:.2f}.'.format(p, d, pd))
|
import math
name = input("What is your name? ")
pool = input("What shape is your pool, " + name + "? (Use RP for rectangular prism, C for cube, or CY for a cylindrical pool) ")
if pool == "RP":
length = float(input("What is the length of the pool in feet? "))
width = float(input("What is the width of the pool... |
#!/usr/bin/env python
import ctypes
import ConfigParser
import os
import time
Lib = ctypes.cdll.LoadLibrary(os.getcwd()+'/myRobotLibrary.so')
config = ConfigParser.ConfigParser()
config.read("config.ini")
config.sections()
# dump entire config file
for section in config.sections():
print (section)
if(secti... |
#!/usr/bin/env python
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
"""Test module for orchestra_openims"""
import loggi... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/response')
def resp():
username = request.args.get('username')
method = request.method
return render_template('response.html',
username=user... |
import re
import tweepy
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from geopy.geocoders import Nominatim
from tweepy import OAuthHandler
from textblob import TextBlob
import numpy as np
import reverse_geocode
import plotly.graph_objects as go... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import maabara as ma
import uncertainties as uc
import matplotlib as mp
import math
import numpy as np
import matplotlib.pyplot as plt
mp.rcParams['text.usetex']=True
mp.rcParams['text.latex.unicode']=True
plt.rc('text', usetex=True)
plt.rc('font', famil... |
from flask import Flask, request, render_template
import requests as req
import pandas as pd
import sys
# initialize flask app
app = Flask(__name__)
# scrape the 5 highest scored posts from a reddit URL
def scrapeTop5Posts(text):
# process different types of URL notation
if text[0:12] == 'https://www.': url = text ... |
from .core import *
from .tree import *
from .topo import Regulus, RegulusTree
# from .alg import *
from .utils import *
|
# Generated by Django 3.0.6 on 2020-06-05 15:23
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20200604_2156'),
]
operations = [
migrations.CreateModel(
name='Cat... |
# -*- coding: utf-8 -*-
import pip
import sys
import zipfile
from platform import system
from tempfile import mkdtemp
from os import path, getcwd, walk
from shutil import rmtree
def install_dependencies(req_fname, on):
if path.exists(req_fname):
pip.main(['install', '-r', req_fname, '-t', on])
def clean(... |
#!/bin/python3
# Format dataset to a format that C can parse easily
# CSV with . decimal sep and , as , separator
import pandas as pd
import os
import math
import numpy as np
dataset_name='Container_Crane_Controller_Data_Set.csv'
# Get home path
HOME=os.environ['HOME']
# Join paths to final
DATA_PATH=os.path.join(HO... |
def get_char_num(w):
"""
Returns the number of characters in word w.
"""
count = 0
for c in w:
count = count + 1
return count
def get_word_lengths(s):
"""
Returns a list of integers representing
the word lengths in string s.
"""
return map(get_char_num, s.split())
d... |
"""
Courses Request Handler
"""
import logging
import json
import webapp2
import models
MAX_STRING = u"\ufffd"
class CoursesHandler(webapp2.RequestHandler):
def get(self):
query_string = self.request.get('query')
if not query_string:
self.response.out.write('No query provided')
... |
class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
m = len(s)
n = len(p)
dp = [[False for col in range(n + 1)] for row in range(m + 1)]
dp[0][0] = True
for i in range(0, m + 1):
for j in ... |
from typing import List
import numpy as np
import math
import matplotlib.pyplot as plt
def plot(points_count:List, means:List):
plt.title("Approximate mathematical model of the mean nearest neighbour distance")
plt.ylim([0, 0.5])
plt.xlabel("Number of points (N)")
plt.ylabel("Mean nearest neighbour d... |
#!/usr/bin/env python
#coding=utf-8
from functools import wraps
from flask import g, Response, abort, request
from flaskext.mail import Mail
from flaskext.sqlalchemy import SQLAlchemy
from flaskext.cache import Cache
from flaskext.uploads import UploadSet, IMAGES
__all__ = ['mail', 'db', 'cache', 'photos']
mail = ... |
#! /usr/bin/env python3
import math
# QR分解の結果を比較する
fout = open ('../../MulSubCellTerm/MulSubCellTerm.sim/sim_1/behav/to_left.txt', 'r')
fref = open('ref.txt', 'r')
ok = True
line_no = 1
lout = fout.readline()
while lout:
# シミュレーション結果を読み込む
results = lout[:-1].split(' ')
val = int(results[0], 16)
# 負の値... |
# グリッド
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
# ↑ → ↓ ←
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
ans = [[0 for _ in range(w)] for _ in range(h)]
mines = []
for i in range(h):
for j in range(w):
if s[i][j] == '#':
for k in range(len(dx... |
# Generated by Django 3.2.3 on 2021-06-19 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0018_book_amount_available_books'),
]
operations = [
migrations.AlterField(
model_name='book',
name='active... |
#https://www.acmicpc.net/problem/12100
from collections import deque
from copy import deepcopy
import sys
#sys.stdout = open('output.txt','w')
input = sys.stdin.readline
n = int(input())
board =[]
for _ in range(n):
board.append(list(map(int,input().split())))
def game(board,n,di):
#상
if(di==0):
... |
"""
Novelty detection model: Autoencoder + ocsvm
tensorflow version: 2.0.0-alpha0
prediction on python client with tenosflow seving
python test.py --model_version 1 --workspace_dir ../workspace --test_path ../test_data
"""
import glob
import cv2
import imageio
import configparser
import numpy as np
import tensorflow... |
import os
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import parameters
from plot_style import PlotStyle, PlotUtil
from wt_from_ex_files impor... |
from DataStructures.tree import Tree
from Minimax import Minimax
import copy
class Board:
def __init__(self):
self.T = Tree()
self.initialState = []
self.utilityMap = {}
self.player1 = 1
self.player2 = 2
self.nextStateValue = []
self.utilityNodes = []
... |
import json
import click
import dateutil.parser
# https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python
class ANSIColor:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERL... |
import sys
import csv
stamps_fieldnames_dynamic = {
'Order ID (required)': 'Order Number',
'Order Number': 'Order Number',
'Order Date': 'Purchase Date',
'Order Value': 'Net Total ($)',
'Ship To - Name': 'Buyer Name',
'Ship To - Address 1': 'Street Address',
'Ship To - State/Province': 'Sta... |
numbers = list(map(int, input().split()))
new_num = []
avg = sum(numbers) // len(numbers)
for i in range(len(numbers)):
if numbers[i] > avg:
new_num.append(numbers[i])
new_num.sort(reverse=True)
if len(new_num) == 0:
print("No")
else:
print(*new_num[:5]) |
# KAMUS
# adminORuser : string
def help(adminORuser): # F16 - Help
if adminORuser == "admin":
print('''
---HELP---
register - untuk melakukan registrasi user baru
login - untuk melakukan login ke dalam sistem
tambahitem - untuk melakukan penambahan item
hapusitem - u... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy.spatial
import time
np.random.seed(17)
def distance(x1,x2):
return scipy.spatial.distance.sqeuclidean(x1, x2)
def gauss(x1, x2, sigma = 1):
return np.exp(-distance(x1, x2) / 2 / sigma ** 2)
def linear(x1, x2, sigma = 1):
return np.d... |
from __future__ import absolute_import, division, print_function
import sys
import inspect
import json
import re
import traceback
from dill.source import getname
from terraform_model.validator import CloudformationValidator
from terraform_model.parser import TransformRegistry
from terraform_model.validator import Refer... |
lhefiles=[
"root://cmsxrootd-site.fnal.gov//store/group/lpcml/eusai/lhe/ttbarOD_1.lhe",
"root://cmsxrootd-site.fnal.gov//store/group/lpcml/eusai/lhe/ttbarOD_10.lhe",
"root://cmsxrootd-site.fnal.gov//store/group/lpcml/eusai/lhe/ttbarOD_100.lhe",
"root://cmsxrootd-site.fnal.gov//store/group/lpcml/eusai/lhe/ttbarOD_1000.l... |
import sys
import pygame
from src.GameLoop import GameLoop
telaLargura = 1920
telaAltura = 1080
def main():
pygame.display.init()
gameDisplay = pygame.display.set_mode((telaLargura, telaAltura), 0, 0)
pygame.display.set_caption('Novel Creator')
gl = GameLoop(gameDisplay)
gl.run(telaLargura, telaAltura)
if __n... |
# https://www.acmicpc.net/problem/1931
# 회의실 배정
import sys
if __name__ == "__main__":
read = sys.stdin.readline
n = int(read())
arr = [list(map(int,read().split())) for _ in range(n)]
arr.sort(key=lambda x:(x[1],x[0])) # 끝나는 시간으로 오름차순 정렬 --> 두번째 키로 시작시간 정렬 필요. 22 12 순서로 들어오면 12 22 순으로 2개가 정답임
key =... |
import numpy as np
f = open("karate.csv")
lines = f.readlines()
f.close()
n = 34
A = [[0.0 for i in range(n)] for j in range(n)]
for line in lines:
source, target = line.strip().split(",")
source = int(source)
target = int(target)
A[target-1][source-1] = 1.0
# Make A column stochastic
A_trans = np.transpose(A)... |
# Generated by Django 2.2.1 on 2019-06-09 10:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20190609_0909'),
]
operations = [
migrations.AlterField(
model_name='classbook... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-12 12:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('goals', '0044_alter_field_code_on_component_add_unique_cons... |
import urllib
import json
import time
apikey = '8fbdd6e0-969d-47a6-808d-66635e50e81d'
url = "https://api.emcd.io/v1/btc/income/%s" % apikey
response = urllib.urlopen(url)
data = json.loads(response.read())
reward = data['income'][0]['income']
hrate = data['income'][0]['total_hashrate']
timest = data['income'][0]['ti... |
from django.shortcuts import render, redirect
from .models import User
from django.contrib import messages
import bcrypt
from apps.to_dos.models import Agreement
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
all_agreements_by_curren... |
import json
from django.contrib import messages
from django.shortcuts import redirect, reverse
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from market.core.views import MarketView
from market.checkout import utils
class AjaxResponseMixin(MarketView):
"""Mixin providin... |
# Create a python list with email and password
# display an error message if email is not in the
# list, if the email is in the list check if the
# two password fields matches, and if it does, change the
# 1. Create a function that will some all the numbers from a lower limit to an upper limit as seen on number 3 on as... |
#! -*- coding: utf-8 -*-
#
# created by giginet on 2014/6/29
#
__author__ = 'giginet'
from django.core.management.base import BaseCommand, CommandError
from ...scraper import RecentActivityScraper
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = RecentActivityScraper(verbose=True)... |
class Solution:
def replaceSpace(self, s: str) -> str:
arr = []
for c in s:
if c != ' ':
arr.append(c)
else:
arr.append('%20')
return ''.join(arr)
def replaceSpace2(self, s: str) -> str:
return s.replace(' ','%20')
so = So... |
from exchange import Exchange
class Stock:
def __init__(self, name, symbol, price, forecast14d, forecast3m, forecast6m, forecast1y, forecast5y, rating):
self.name = name
self.symbol = symbol
self.price = price
self.forecast14d = forecast14d
self.forecast3m = foreca... |
from TANE import map_attributes
import re
def import_metanome_fds(current_attributes):
attribute_mappings = map_attributes(current_attributes)
# FD Path
fd_path = '../tane-1.0/output/'
with open(fd_path + 'metanome.log', 'r') as f:
unstructured_fds = f.read()
multi_parent_fds = []
... |
import sys
from collections import deque
sys.stdin = open("../../../test/escape.txt", "r")
R, C = map(int, sys.stdin.readline().split())
forest = list()
for _ in range(R):
forest.append(list(sys.stdin.readline().rstrip()))
water = deque()
hedgehog = deque()
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs():
t... |
import aiohttp
class Client:
host = None
session = None
params = None
def __init__(self, host, session):
self.host = host
self.session = session
self.params = {}
@staticmethod
def create(host='http://testapi.ru'):
session = aiohttp.ClientSession()
retu... |
from dto.searchareadto import SearchareaDTO
from dto.celldto import CellDTO
from dto.point import Point
from dto.pose import Pose
from util.log import Log
from simulationmodel.searcharea import Searcharea
from simulationmodel.maps.tree import Tree
from simulationmodel.maps.tree import Leaf
from simulationmodel.cell ... |
import logging
from lakesuperior.messaging import formatters, handlers
messenger = logging.getLogger('_messenger')
class Messenger:
'''
Very simple message sender using the standard Python logging facility.
'''
_msg_routes = []
def __init__(self, config):
for route in config['routes']:
... |
"numpy exercises"
import numpy as np #1
print(np.show_config())
print(np.__version__) #2
arr = np.zeros(10) #3
print("%d bytes" % (arr.size * arr.itemsize)) #4 - memory of array
np.info(np.add) #5 open documentation for np.add
arr1 = np.zeros(10)
arr1[4] = 1
arr1 ... |
lock = [
[2, 9, 1],
[2, 4, 5],
[4, 6, 3],
[5, 7, 8],
[5, 6, 9],
] # ans - 394
def correct_but_in_wrong_pos_count(l1, l2):
return len([(p1, p2) for p1, v1 in enumerate(l1) for p2, v2 in enumerate(l2) if p1 != p2 and v1 == v2])
def crack(key):
# step 1
if not (len([x for x in key if x... |
from django.db import models
class Post(models.Model):
post_title = models.CharField(max_length=50, name="title")
date_of_post = models.DateTimeField(auto_now=True, name="date")
text_post = models.TextField(name="entry")
image_post = models.ImageField(upload_to='blog_images/', name='image')
def g... |
import os
import xml.dom.minidom
import shutil
source_path = 'flickr_backup/' # fill this in
set_path = 'set/' # fill this in
docs = os.listdir(source_path)
for doc in docs:
if 'contexts' in doc:
id = doc[0:-13]
#print 'Checking contexts for photo ' + id
contexts = xml.dom.minidom.parse(source_path + doc)
fo... |
#!/usr/bin/env python
import rospy
import math
import random
import sys
import numpy as np
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from statistics import mean
# robot dicision sensors
SENSORS = {
"FRONT": 0,
"FRONTAL_LEFT": 45,
"FRONTAL_RIGHT": 315,
"LEFT": 90,
"RI... |
from flask import Blueprint
bp = Blueprint('auction', __name__, url_prefix='/auction')
from . import views
|
# Generated by Django 2.0.2 on 2018-03-22 09:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mysite', '0004_auto_20180321_1710'),
]
operations = [
migrations.RemoveField(
model_name='player',
name='maiden',
... |
inp = input ('Enter a file name: ')
try:
h=open (inp)
except:
print('Invalid input!')
exit()
d=dict()
li=[]
for line in h:
words=line.split()
if len(words)==0: continue##skips blanck lines
if words [0]!='From': continue##skips lines not strating with "From"
li.append(words[1])
#... |
from typing import List
from flask import current_app, url_for
from mailjet_rest import Client
from taiga2.controllers import models_controller
from taiga2.models import DatasetSubscription
def send_emails_for_dataset(dataset_id: str, version_author_id: str):
dataset = models_controller.get_dataset(dataset_id, ... |
import random
studenti = ['Josip', 'Ivan', 'Ivan', 'Josip', 'Ivan', 'Ivan', 'Katarina', 'Božena', 'Ivona', 'Marija', 'Josipa', 'Marko', 'Dario', 'Mihael',
'Stana', 'Bruno', 'Anamarija', 'Andrea', 'Petar', 'Marko', 'Amnesa', 'Nikola', 'Antonela', 'Leon', 'Ivan', 'Ante', 'Ivan',
'Jure', 'Jan', 'Florijan', 'Boris', '... |
from __future__ import absolute_import
from . import numpy_wrapper
from . import numpy_grads
from . import numpy_extra
from .numpy_wrapper import *
from . import linalg
from . import fft
from . import random
|
start, end = [-4, 19]
for num in range(start, end + 1):
if num >= 0:
print(listn[num])
|
import cv2
import numpy as np
class MonoCalibrator:
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
def __init__(self, checkerSize, imgShape):
self.checkerSize = checkerSize #dimension of the checkerboard (x, y)
self.imgShape = imgShape ... |
# -*- coding: utf-8 -*-
# Import Dependencies
%matplotlib inline
# Start Python Imports
import math, time, random, datetime
# Data Manipulation
import numpy as np
import pandas as pd
# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-whitegrid')
# Preprocessing
from sklear... |
import eHive
import subprocess
import os
import sys
import random
import string
class VcfConcat(eHive.BaseRunnable):
"""Concat each of the VCF chunks into a single VCf"""
def random_generator(self, size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in rang... |
# Week 5
# Code Along 1
def string_to_dictionary(strng):
strng = strng.lower()
new_dict = dict()
words = strng.split()
for letter in words:
if letter in new_dict:
new_dict[letter] += 1
else:
new_dict[letter] = 1
return new_dict
my_var = "The quick brown fox ... |
class Solution:
def longestPalindrome(self, s: str) -> int:
if not s: return 0
ret = odd = 0
s_dict = {x: 0 for x in set(sorted(s))}
for s_str in s:
if s_str in s_dict:
s_dict[s_str] += 1
print(s_dict)
for val in s_dict.values():
... |
"""
File: nimm.py
-------------------------
Nimm is an ancient game of strategy, where players
alternate taking stones until there are zero left.
"""
STARTING_STONES = 20 # number of stones in the starting pile
STARTING_TURN = 1 # sets it so that Player 1 goes first
def main():
"""
This prog... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2019-02-20 14:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bossingest', '0005_remove_ingestjob_ingest_type'),
]
operations = [
migratio... |
""" Solve Tolman-Oppenheimer-Volkoff equations with ode from scipy
TOV equations:
dM/dr = 4 * pi * e * r^2
dP/dr = - G / r^2 * [e + P / c^2] * [M + 4 * pi * r^3 * P / c^2] *
1 / [1 - 2 * G * M / r / c^2]
From: https://en.wikipedia.org/wiki/Tolman-Oppenheimer-Volkoff_equation
- no... |
print("hello , my name is smita srivastava")
print("I am a software engineer and good ptrogrammer")
print('I am a student')
print('my hobby is a reading book, listening music')
|
def quickSort(array, left, right):
if left >= right:
return
pivot = array[(left+right)//2]
index = partition(array, left, right, pivot)
quickSort(array, left, index-1)
quickSort(array, index, right)
def partition(array, left, right, pivot):
while (left <= right):
while (array[l... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 19:24:09 2019
@author: cmoug
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import pyplot
#I1 = np.int(plt.imread('DataTP2\Data\I1.png')[:,:,1] ) * 255
#J1 = np.int(plt.imread('DataTP2\Data\J1.png')[:,:,1] ) * 255
I2 = plt.imread('Da... |
# -*- coding: utf-8 -*-
"""
smpa.routes
~~~~~~~~~~~~~~~~
Routing config.
"""
import os
from .resources.swagger import ApiSpecResource
from .resources.material import ( # NOQA
# Options
MaterialOptionRoofPost,
MaterialOptionRoofPatch,
MaterialOptionWallPost,
MaterialOptionWallPatch,
... |
import kaplot
from kaplot.objects import Container, PlotObject
from kaplot.astro.projection import Projection
#from kaplot.cext._wcslib import Wcs
import numpy
class WcsText(PlotObject):
def __init__(self, container, text, position, textangle=0, valign="center", halign="center",
wcs=None, transformation=None, *... |
import numpy as np
import starfish
from starfish.types import Axes
def process_fov(field_num: int, experiment_str: str):
"""Process a single field of view of ISS data
Parameters
----------
field_num : int
the field of view to process
experiment_str : int
path of experiment json fil... |
# -*- coding: utf-8 -*-
import json
import logging
from itertools import groupby
from urllib.parse import urlencode
from urllib.parse import urljoin
from urllib.request import urlopen
from pyramid.decorator import reify
from amnesia.resources import Resource
from amnesia.modules.folder import FolderEntity
from amn... |
import asyncio
import copy
import logging
import math
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import TYPE_CHECKING, Any, AsyncIterable, Callable, Dict, List, Optional, Tuple
from async_timeout import timeout
from hummingbot.connector.client_order_tracker import ClientOrderTracker
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/4/14 10:51
# @Author : GuoChang
# @Site : https://github.com/xiphodon
# @File : kneighbors_classifier.py
# @Software: PyCharm Community Edition
'''
kNN分类
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors, datase... |
import random
from django.http import Http404
from django.shortcuts import render
# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def halo(request):
return Response({'message': 'Halo Dunia!'})
@api_view(['POST'])
def run(... |
def setup():
global yogoogle,x,y,gameStarted,firstScreen
size(1680,1000)
background(90, 100, 255)
yogoogle = "YO GOOGLE"
img = loadImage("multipleandroids.jpg")
image(img,0,0,1680,1000)
x = True
y = True
x2 = True
y2 = True
firstScreen(x,y)
# secondScreen (x2,y2)
game... |
def main():
num = int(input())
# YOUR CODE GOES HERE
if num >= 90: print('A')
if num >= 80: print('B')
if num >= 70: print('C')
if num >= 60: print('D')
if num >= 50: print('E')
else: print('F')
return 0
if __name__ == '__main__':
main() |
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 10000
self.table = [[] for _ in range(self.size)]
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
... |
# coding: utf-8
from django.apps.registry import apps
def is_installed(app_name, retval=None):
"""
Décorateur exécutant la fonction si une ou plusieurs applications sont installées
:param app_name: Nom de l'application Django (pas le app_label)
:param retval: valeur à renvoyer si l'app n'est pas inst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.