text stringlengths 38 1.54M |
|---|
"""
Jack Baude double pendulum prediction
- predicts where a double pendulm will be in space with time
given the mass of the two bobs, lengths of the pendulum arms
and the intial starting postion
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
class doublePen:
#Con... |
from typing import List
from pydantic import BaseModel
from pydantic import Field
from stellar_model.model.horizon.trade import Trade
from stellar_model.response.page_model import PageModel
__all__ = ["TradesResponse"]
class Embedded(BaseModel):
records: List[Trade]
class TradesResponse(PageModel):
"""
... |
#!/home/darkdevil/PycharmProjects/Django_Project_2/venv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from typing import List
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
result, last, lightOn = 0, 0, [True] + [False]*len(light)
for i, k in enumerate(light):
lightOn[k] = True
while last + 1 < len(lightOn) and lightOn[last + 1]:
last += 1
if last == i + 1:
... |
while 1:
en = [int(x) for x in raw_input().split()]
if sum(en) == 0:
break
to = [0 for i in xrange(en[1])]
te = [1 for i in xrange(4)]
for i in xrange(en[0]):
a = [int(x) for x in raw_input().split()]
if len(a) == sum(a) and not te[0] == 0:
te[0] = 0
elif ... |
from unittest import TestCase
from flask import Flask
import urllib
import requests
app = Flask(__name__)
class TestOrganization(TestCase):
token_user1 = "mock_user_001"
token_user2 = "mock_user_002"
def tearDown(self):
# TEAR DOWN TEST
response = requests.get(url="http://localhost:5000/... |
import json
import os
from urllib.request import urlopen
import pandas as pd
import numpy as np
import h5py
def collectData():
url = 'https://poloniex.com/public?command=returnChartData¤cyPair=USDT_BTC&start=1356998100&end=9999999999&period=300'
openUrl = urlopen(url)
r = openUrl.read()
openUrl.c... |
from PluginInterface import *
from Manialink import *
from WindowElements import *
"""
\file ChatCommands.py
\brief Contains the plugin for general chat commands that are not related to/present in another plugin
"""
class ChatCommands(PluginInterface):
def __init__(self, pipes, args):
"""
\brief Construct the Ch... |
import os
PROGRAM_NAME = "needle"
PROGRAM_OUTPUT_NAME = ""
INPUT_PARAMETERS = "32 10"
LLVM_PATH = ""
EXEC_MODE = 1 # 0 -> Single threaded, 1 -> Multi-threaded
CF_STAGE_1_NUM = 100
CF_STAGE_2_NUM = 100
# Loads that transfer data from global memory
GLOBAL_LOAD_LIST = [285, 296, 305, 312] #K2
# Stores that transfer d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import custom.fields
class Migration(migrations.Migration):
dependencies = [
('Notification', '0006_auto_20160821_0502'),
]
operations = [
migrations.AlterField(
model_na... |
import numpy as np
import random
class Data_loader():
def __init__(self, mode, config):
'''
query_seq: [total, time_steps]
query_mask: [total, time_steps]
taret_seq: [total, time_steps]
target_seq_len: [total]
'''
self.query_seq = np.load(".... |
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... |
import datetime
class Paciente:
def __init__(self,apellido,nombre,dni,telefono,mail,id_paciente = None):
self.apellido = apellido
self.nombre = nombre
self.dni = dni
self.telefono = telefono
self.mail = mail
self.fecha_creacion = datetime.datetime.today()
... |
import time
from karait import Message, Queue
print 'Starting python writer.'
messages_written = 0
start = time.time()
queue = Queue()
while True:
queue.write({
'messages_written': messages_written,
'sender': 'writer.py',
'started_running': start,
'messages_written_per_second': (m... |
#User inputs
#1. f= function f(x)
#2. n=number of decimal places correct to be found
#3. x0=an initial approximation for root
#Output
#real root of f(x) correct upto n decimal places
# import sympy for findingderivative
from sympy import *
from sympy import diff, Symbol
from sympy.parsing.sympy_parser import *
f... |
__author__ = 'joe'
import urllib2
req = urllib2.Request('http://www.baibai.com/')
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
# print e.code
# print e.reason
if hasattr(e, 'code'):
print 'the server could not fulfill the request '
print 'Error code', e.code
elif hasattr(e... |
# -*- coding:utf-8 -*-
import redis
import logging
class Config(object):
"""加载配置"""
# 开启调试模式
DEBUG = True
# 秘钥
SECRET_KEY = 'AK0j4NSomJQKm8gD/917OniOIC8DEMQRP+xPBvGanEBieaADMBTA0EBTrJdAiXgU'
# 配置mysql数据库:开发中使用真实IP
SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1:3306/iHome_07'
... |
import pafy
from pydub import AudioSegment
import os
import sys
import argparse
import re
def get_arguments():
parser = argparse.ArgumentParser(prog='python3 ' + __file__,
usage='%(prog)s --url URL [options]')
parser.add_argument('--url', required=True, help='URL for You ... |
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title('1th window')
root.iconbitmap('images/diablo.ico')
img = ImageTk.PhotoImage(Image.open('images/diablo.ico'))
# add window
def openWindow():
global img
top = Toplevel()
top.title('2nd Window')
top.iconbitmap('images/diablo.ico'... |
class PID:
"""PID Controller
"""
def __init__(self, P=80, I=0, D=0, duty=26):
self.Kp = P
self.Ki = I
self.Kd = D
self.err_pre = 0
self.err_last = 0
self.u = 0
self.integral = 0
self.last_duty = duty
self.pre_duty = duty
def upd... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mock
from model.flake.analysis.data_point import DataPoint
from services.flake_failure import confidence
from waterfall.test import wf_testcase
cla... |
############################################################################################################
#
# getMemSistemas.py
#
# NOME DO PROEJTO.....: Coleta de Memorias dos Servidores Acompanhados por Capacidade com tratamento de erro
#
# AUTOR...............: Guilherme DXC
#
# DATA................: 29/11/2017
#... |
#!/usr/bin/env python3
import zipfile
from pathlib import Path
blender_scripts = Path('blender_scripts')
pygdml = Path('pygdml')
curdir = Path()
internal_dir = Path('blender_gdml')
with zipfile.ZipFile('blender_gdml.zip', 'w', zipfile.ZIP_DEFLATED) as myzip:
write = lambda pre, name: myzip.write(str(pre / name)... |
class Cell:
def __init__(self,surface):
self.x = random.randint(20,1980)
self.y = random.randint(20,1980)
self.mass = 7
self.surface = surface
self.color = colors_cells[random.randint(0,len(colors_cells)-1)]
def draw(self,cam):
pygame.draw.circle(self.surface,sel... |
# Quick and dirty tkinter app for displaying temperature and humidity data
# sent via serial communication
# I have hard wired the serial port to be '/dev/ttyUSB0'
# If you are using a Linux machine - eg an RPi then plug the USB end
# of the serial cable into your machine and then in a terminal type
# dmesg
# and you w... |
#!/usr/bin/python
"""
Append one or more columns from the second file to the main file matching the files by a column
"""
import sys
import argparse
import gzip
def parseArguments():
parser = argparse.ArgumentParser(description="Add column from another file to the current file", add_help=True, epilog = "Fini... |
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2019 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold cop... |
import requests
import json , requests , pytest
url='http://127.0.0.1:5000/v1/sanitized/input/'
def do_req(payload):
return requests.post(url,payload)
def test_post_req_1():
test_payload={"input":'/*'}
response=do_req(test_payload)
assert response.status_code==200
assert resp... |
import math
import numpy as np
from scipy.stats import poisson
from scipy.optimize import minimize, LinearConstraint # optimization
from scipy.linalg.blas import dgemm, dgemv # matrix multiplication
from scipy.linalg import inv # matrix inversion
from scipy.sparse.linalg import expm # matrix exponential
def find_Sal... |
#write a function called sum_floats
#This function should accept a variable number of arguments.
#Should return the sum of all the parameters that are floats.
# if the are no floats return 0
def sum_floats(*args):
if (any(type(val) == float for val in args)):
return sum((val for val in args if type(val)==f... |
import urllib.parse
import urllib.request
import json
### API STUFF
BASE_URL = "http://open.mapquestapi.com/directions/v2/route?"
BASE_ELEV_URL = "http://open.mapquestapi.com/elevation/v1/profile?"
KEY = "10uEWhCB5WKuQ2IGAcocTuyEikkUK8Yk"
def build_url(user_input: list) -> str:
''' Builds URL depending on wh... |
import sys
sys.stdin = open('1949.txt', 'r')
def dfs(y, x, k, cnt):
global ans
ans = max(ans, cnt)
for v in range(4):
ny, nx = y + dy[v], x + dx[v]
if 0 <= ny < N and 0 <= nx < N and not visited[ny][nx]:
if arr[y][x] > arr[ny][nx]:
visited[ny][nx] = 1
... |
import os
count = 0
def isValid(nums):
for i in range(1, len(nums)):
if nums[i] - nums[i-1] > 3:
return False
return True
def removeOneAndTest(nums: list):
#print(nums)
global count
#if isValid(nums):
#print("Valid")
count += 1
#else:
#print("Not valid"... |
def abbrivation(statement):
lst=statement.split()
output=""
for word in lst:
output+=word[0]
output=output.upper()
return output
statement=str(input("Enter the statement:"))
class sol:
def solve(self,s):
rp=s[0]
ans=s[0]
for i in s[1:]:
if i!=rp:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-01 23:43
from __future__ import unicode_literals
from django.db import migrations
def create_profiles(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the histor... |
from req import Aio_Req,Sin_Req,Post_Req
from lxml import etree
import asyncio
import json
import re
from settings import *
import threading as th
from m_queue import TaskQueue
from log import log
from urllib.parse import urljoin
from db import Mon
task_queue = TaskQueue()
mon = Mon()
class SJJY_Spider(obj... |
class File:
UTF8 = 'utf-8'
def __init__(self, name):
self.name = name
with open(self.name, 'a', encoding=self.UTF8) as f:
pass
def append_error(self, message):
print(message)
with open(self.name, 'a', encoding=self.UTF8) as f:
f.write(message)
... |
import unittest
import base64
from bsn_sdk_py.trans.transaction_header import created_peer_chaincode_chaincodeinvocationspec,\
created_peer_chaincode_chaincodeinput, created_peer_chaincode_chaincodespec,\
created_peer_chaincode_chaincodeid
class TestRequest(unittest.TestCase):
def test_ChaincodeInvocation... |
try:
try:
a = 5
b = 7
c = "five"
d = "seven"
print(a*c)
print(c+d)
except:
print(b*c)
else:
print(c*d)
finally:
print("first finally")
except:
print("second except")
else:
print("second else")
finall... |
def main():
with open('input') as f:
cases = int(f.readline()[:-1])
for casen in range(cases):
case = f.readline()[:-1]
res = ''
for s in case:
if not res:
res += s
elif s < res[0]:
res += s
... |
'''
@Author: your name
@Date: 2020-04-01 15:59:44
@LastEditTime: 2020-04-01 21:58:43
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /Algrithm/LeetCode/35.搜索插入位置.py
'''
#
# @lc app=leetcode.cn id=35 lang=python3
#
# [35] 搜索插入位置
#
# @lc code=start
class Solution:
def searchInsert... |
from atsim import potentials
import math
import pytest
def test_potclass_testEnergy():
"""Check potentials.Potential.energy"""
potfunc = potentials.buck(1388.773, 2.76, 175)
pot = potentials.Potential("A", "B", potfunc)
assert pytest.approx(-10041.34343169, abs = 1e-5) == pot.energy(0.5)
def test_potclass_t... |
import sys
import argparse
import numpy as np
from props import *
parser = argparse.ArgumentParser()
parser.add_argument('--num_decode', type=int, default=20)
parser.add_argument('--sim_delta', type=float, default=0.4)
parser.add_argument('--prop_delta', type=float, default=0.9)
args = parser.parse_args()
data = [lin... |
# Generated by Django 2.0.5 on 2018-06-03 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracker', '0006_auto_20180529_2256'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='blood_sugar'... |
# Copyright (c) 2015, FJTC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the follow... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from Models.fighting_game_model import *
from Models.users_model import *
from SettingsIni import SettingsIni
from utilities import make_session_id
import datetime
class DAL:
"""
Data Access Layer class
"""
d... |
#!/usr/bin/python26
#-*-coding:utf-8-*-
import os
import sys
import json
default_encoding="utf-8"
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
#filepath = os.environ["map_input_file"]
for line in sys.stdin:
try:
line = line.strip().strip("\n").stri... |
import argparse
import pickle
import time
from datetime import datetime
from typing import List
import tinvest
from constants import (
TOKEN,
MAX_PRICE_USD,
USD_TO_RUB,
PARSED_BONDS_FILE,
MIN_RATIO,
DEBUG
)
from tinvest.schemas import (
LimitOrderRequest,
MarketInstrument,
Operation... |
from hamstir_gym.envs.hamstir_gibson_env import HamstirGibsonEnv
import argparse
import os
import gym
import numpy as np
import matplotlib.pyplot as plt
from stable_baselines.common.policies import CnnPolicy
from stable_baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from stable_baselines.bench import Monito... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""Crotal - A static site generator
-----------------------------------
usage::
crotal --help
"""
import os
import sys
import shutil
import argparse
from crotal import utils
from crotal import server
from crotal import deploy
from crotal import settings
from crotal impor... |
# Generated by Django 3.2.5 on 2021-08-24 12:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TUPConline_appointment', '0008_alter_schedule_category'),
]
operations = [
migrations.AlterField(
model_name='schedule',
... |
import pytest
from kii import exceptions as exc
from kii.acl import * # NOQA
from kii.users import AccountType
from ..conf import (
get_api_with_test_user,
get_admin_api,
cleanup,
)
GROUP_NAME = 'test_group'
BUCKET_ID = 'test_bucket'
class AclApp:
@classmethod
def setup_class(cls):
cl... |
# Three points in the same line (linear function)
# The independent variable is x and the dependent variable is y.
x1 = 5.0
y1 = 11.0
x2 = -0.5
y2 = 0.0
x3 = 1.0
y3 = 3.0
k = 2.0
n = 1.0
result = (y1 == k * x1 + n) and (y2 == k * x2 + n) and (y3 == k * x3 + n)
print('Result ', result)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import cgitb; cgitb.enable() # for troubleshooting
from eggslib.eggsml import eggsml
try:
import simplejson as json
except ImportError:
import json
import time
from calendar import timegm # inverse of gmtime()
e = eggsml()
e.parse('slashdotfrokost')
def jsondate(ts... |
import qiime2
from q2_types.sample_data import AlphaDiversityFormat
def chrono_plot(output_dir: str, alpha_diversity: AlphaDiversityFormat,
metadata: qiime2.CategoricalMetadataColumn):
# Parse sample dates specified in the metadata column: use datetime x axis
# (see e.g.
# https://docs.bokeh.org/e... |
import copy
class WeightBreakdown:
def __init__(self, press, deadlift, bench, squat):
self.maxes = {'press' : press, 'deadlift' : deadlift, 'bench' : bench, 'squat' : squat}
# Calculate a specific weight for a set on a specific day and round down to increment of 5
def calculate_set_weight(se... |
# Generated by Django 2.1.4 on 2019-01-11 09:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projectx_app', '0059_auto_20190111_0908'),
]
operations = [
migrations.AlterField(
model_name='systemcompanysetup',
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 23:15:27 2018
@author: Ittipat
"""
import numpy as np
import matplotlib.pyplot as plt
#xdata = np.array([0.0, 1.0, 3.0, 4.3, 7.0, 8.0, 8.5, 10.0, 12.0])
#ydata = np.array([0.01, 0.02, 0.04, 0.11, 0.43, 0.7, 0.89, 0.95, 0.99])
xdata = np.array([1.393618635, 0... |
# -*- coding: utf-8 -*-
import threading
import logging
from robot import MakeRobot
from time import sleep
from datetime import datetime, timedelta
from config import *
from constants import *
class Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, target=self.run, args=())
... |
import os.path
class test11:
def sub(self, stem1, stem2, stem3, stem4, stem5, stem6, print_path):
Get_items = stem1
Get_supplier = stem2
pub_N_box = stem3
Get_No = stem4
Get_Rev = stem5
date_one = stem6
print_path = print_path
str_all = '''
... |
import scrapy
import csv
class BrickSetSpider(scrapy.Spider):
name = 'brick_spider'
start_urls = []
def parse(self, response):
rows = []
filename = "data.csv"
SET_SELECTOR = 'li.k-content'
category = None
news = []
for brickset in response.css(SET_SELECT... |
import random
import os
import pickle
import math
import numpy as np
from util.sum_tree_buffer import SumTreeBuffer
class PrioritizedExperienceReplay(object):
def __init__(self, buffer_size=200000, dtype=object, epsilon=.001, alpha=0.6):
self._dtype = dtype
self._epsilon = epsilon
self._... |
from urllib import request, parse
postDict = {}
postDict['appReceiptNum'] = 'YSC1990000456'
data = parse.urlencode(postDict).encode()
url = 'https://egov.uscis.gov/casestatus/mycasestatus.do'
req = request.Request(url, data=data)
resp = request.urlopen(req).read().decode('utf-8')
start = resp.find('<h1>')
end = ... |
#!/usr/bin/env python
import cgitb; cgitb.enable()
import cgi, MySQLdb, os, itertools, math
import pygooglechart
from pprint import pprint as _pprint
CHART_FONT_SIZE = 11
CHART_WIDTH = 220
CHART_HEIGHT_FACTOR = 40
def pprint(data):
print 'Content-type: text/html\n'
_pprint(data)
def main():
if not os.... |
from .sqlite_wrapper import authenticate, db_init
from .tcp_listener import get_server_info, start_server
|
from flask import Flask ,render_template,request,redirect,session
app=Flask(__name__)
app.secret_key = 'ThisIsSecret'
app.number=0
@app.route('/')
def input():
session['number']+=1
return render_template('list.html', number=session['number'])
@app.route('/increment', methods=['post'])
def counter():
session['... |
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("Cosmic & Sapphire")
MainWindow.resize(415, 351)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObject... |
from django.conf.urls.defaults import patterns, include, url
from frontends.views import *
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from equipo.forum.views import *
from django.conf.urls.defaults import *
from equipo.forum.mod... |
#!/usr/bin/python
#
# Copyright (c) 2016, Cray Inc.
# 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. Redistributions of source code must retain the above copyright notice,
# this list of co... |
'''
Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois
disso, você deve mostrar, para cada palavra, quais são as suas vogais.
'''
'''
palavras = ('amarelo', 'bonito', 'imagem', 'cor', 'uva', 'cachorro', 'carro', 'casa', 'agua', 'passaro', 'cabelo', 'vasilha', 'frances')
for i in range... |
import json
import os, datetime, shutil
json_directory = "C:\\Users\\Utente\\Dropbox\\Map the Movie"
json_data = "data.json"
json_data_dir = os.path.join(json_directory, json_data)
json_views = "views.json"
json_views_dir = os.path.join(json_directory, json_views)
cinema_json_file = "cinema.json"
json_file = "attori_a... |
def interaction(a, b):
return sum([x*y for x,y in zip(a,b)])
def solve(a, b, k):
mn = b[0]
mp = b[0]
for s in b:
if s < mn:
mn = s
if s > mp:
mp = s
i = mn if abs(mn) > abs(mp) else mp
i = b.index(i)
if b[i] < 0:
a[i] -= k
else: a[i] += k
return interaction(a, b)
I = lambda : map(int, raw_input(... |
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-model2extjs',
version='0.1'... |
import os, re, json
OUT = dict()
games = []
for file in os.listdir("games"):
if file.endswith(".swf"):
games.append(re.sub("([a-z0-9])([A-Z0-9])",r"\g<1> \g<2>",file[:-4]))
OUT["games"] = games
OUT["count"] = len(games)
with open("games.json","w") as f:
json.dump(OUT,f)
|
import abc
import operator as op
import typing as t
import pandas as pd
from fn import F
from ptypes.base import Monoid, Parametric
A = t.TypeVar('A')
__all__ = ['DataFrameMonoid', 'MRows', 'MTuple', 'MStruct']
class DataFrameMonoid(Monoid, metaclass=abc.ABCMeta):
@abc.abstractmethod
def binder(self, a: ... |
from django.shortcuts import render
from sahh.models import Courses, CustomUser, Department, Enterprise, Nursery, Sections, Staffs, Students, Teacher
def show_demo_page(request):
return render(request, 'stuff_template/index.html') |
import itertools
L = [2 for x in xrange(1,1001)]
SL = reduce(lambda x,y:x+y, map(lambda x:int(x), str(reduce(lambda x,y:x*y, L))))
print SL
|
from mlsolver.kripke import World, KripkeStructure
from mlsolver.formula import Implies, Not, And, Or
from ourFormula import Atom
import itertools
from progress.bar import *
def false_in_worlds(worlds, formula, reachable, player, remove):
"""Returns a list with all worlds of Kripke structure, where formula
i... |
"""
Focal mechanisms
----------------
The :meth:`pygmt.Figure.meca` method can plot focal mechanisms or beachballs.
We can specify the focal mechanism nodal planes or moment tensor components
as a dictionary using the ``spec`` parameter (or they can be specified as a
1-D or 2-D array, or within a file). The size of th... |
func = lambda x, y: x + y
print(func(1, 2))
#3
print(func('a', 'b'))
# 'ab'
print((lambda x, y: x + y)(1, 2))
# 3
print((lambda x, y: x + y)('a', 'b'))
# 'ab' |
import dataclasses
from triton.debugger import torch_wrapper
torch = torch_wrapper.torch
@dataclasses.dataclass
class RegisteredStorage:
storage: torch.Storage
dtype: torch.dtype
size: int
ptr: int
@property
def end_ptr(self) -> int:
return self.ptr + self.size
@property
de... |
# Generated by Django 2.2.6 on 2020-01-09 02:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main_app', '0022_auto_20200109_0234'),
]
operations = [
migrations.RemoveField(
model_name='eater',
name='taste',
),... |
class WordDictionary:
data = [True] + [None for i in range(26)]
def find(self, word, pos, node):
while pos < len(word):
if word[pos] == '.':
for i in range(1, 27):
if node[i] and self.find(word, pos + 1, node[i]):
return True
... |
from rest_framework.pagination import PageNumberPagination
class SmallNopage(PageNumberPagination):
page_size = 1
|
#/bin/python3
# TODO: Make a local version (maybe, or just get rid of the option aspect); make an option to save; Also do some maintenance in case of bad characters, if there is a space in the hostname it won't do an opsdb query, etc.
# TODO: Perhaps make this a legacy thing to MASH, allow console, set clone bit, add s... |
import logging
from typing import Iterable
import numpy as np
from scipy.stats import multivariate_normal
from ..problem import Problem
from ..result import ProfilerResult, Result
from .util import initialize_profile
logger = logging.getLogger(__name__)
def approximate_parameter_profile(
problem: Problem,
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-24 17:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('churchForm', '0004_auto_20180324_1713'),
]
operations = [
migrations.AlterF... |
#!/usr/bin/env python
#Benötigte Module: asyncio websockets
import asyncio
import datetime
import websockets
import pprint
#server config <change ip if you like>
ip = "0.0.0.0"
port = 8080
#global vars
clients = set()
@asyncio.coroutine
def sendMsg(socket, msg):
print ("info>send>begin:\n" + msg + "\ninfo>send>end... |
import socket
host="localhost"
port=80
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((host,port))
client.send("from raspberry pi")
while True:
print(client.recv(4096))
|
x = int(input("Enter the num:"))
if x%7==0:
print("yes",x,"its a mulitiple of 7")
else:
print("no",x,"isn't multiple of 7") |
'''
Write a Python program to multiply all the items in a dictionary.
'''
dict1 = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
print ("Old dictionary:", dict1)
for key, value in dict1.items():
dict1[key] = value * 10
print ("New dictionary:", dict1) |
import tensorflow as tf
import numpy as np
from object_detection.utils import visualization_utils, label_map_util, ops
import os
class ObjectDetector(object):
def __init__(self,model_name):
self.model_name = model_name
self.graph = tf.Graph()
self.num_class = 1
self.initialize_graph... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
#Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
... |
# encoding: utf-8
"""
@project:Data_Structure&&Algorithm
@author: Jiang Hui
@language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux
@time: 4/8/19 5:24 PM
@desc: 给你一根长度为n的绳子,请把绳子剪成m段 (m和n都是整数,n>1并且m>1)每段绳子的长度记为k[0],k[1],...,k[m].
请问k[0]*k[1]*...*k[m]可能的最大乘积是多少?
"""
class Solution:
def maxProduct... |
#coding:utf-8
"""
Les chaine de carractere : les methode chaine tavaillent sur copie , et pas la chaine elle meme !!
"""
"""# La classe str : help(str)
str.upper(), str.lower(), str.capitalise(), str.title()
str.center(<largeur>,<caractere_de_remplissage>)
... |
num=input("number:");
num1=int(num);
s=list();
k=0;
while(num1>0):
k=num1%2;
num1=num1//2;
s.append(k);
print(s);
n=len(s);
i=n-1;
while(i>=0):
print(s[i],end='');
i=i-1;
|
# Removes misc characters from string
def replace(string):
string = string.replace("&", "")
string = string.replace("-", " ")
string = string.replace("(", "")
string = string.replace(")", "")
string = string.replace("/", " ")
string = string.replace(",", "")
string = string.replace(".", "")
... |
#!python3
"""
5.3
Flip Bit to Win: You have an integer and you can flip exactly one bit from a O to a 1. Write code to
find the length of the longest sequence of 1 s you could create.
EXAMPLE
input: 1775 (or: 11011101111)
output: 8
Hints: #159, #226, #31 4, #352
run time: O(b)
memory O(b)
"""
# process the num and... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
REQUIRED_PACKAGES = [
# 'tensorflow>=1.4.0',
'gensim>=4.0.0',
'networkx',
'joblib',
'fastdtw',
'tqdm',
'numpy',
'scikit-learn',
'pandas',
'matplotlib',
'deepctr'
]
setuptools.setup(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.