text stringlengths 38 1.54M |
|---|
from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator
from django.db.models import Count
from .models import Post, Group, Comment, Follow
from .forms import PostForm, CommentForm
from django.http import HttpResponseRedirect
from django.views.decorators.cache impor... |
__author__ = 'bensmith'
sums = 0
for i in range(1, 1001):
sums += i ** i
toString = str(sums)
for i in range(len(toString)-10, len(toString)):
print(toString[i], end="") |
#!/usr/bin/python
"""This challenge is defined in https://raw.githubusercontent.com/RoboCupAtHome/RuleBook/master/Manipulation.tex
In short, the robot starts at 1-1.5m from a bookcase and must wait until started by an operator (by voice or a start button)
This bookcase has a couple of shelves on which some items are... |
#coding:utf8
'''
星期一 Mon Monday
星期二 Tue Tuesday
星期三 Wed Wednesday
星期四 Thu Thursday
星期五 Fri Friday
星期六 Sat Saturday
星期日 Sun Sunday
'''
weeks = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday',
'Sunday','Monday']
import datetime
print datetime.datetime.now().weekday()
start = datetime.datetime(2... |
"""
Build a Diamond I - SOLUTION
Use a FOR loop to print a diamond of stars that looks like this:
*
***
*****
*******
*********
*******
*****
***
*
"""
level = 5
x = list(range(1, level+1))
for i in x:
a = (level - i) * ' '
b = i * '*'
c = (i - 1) * '*'
print(a + b + c)
x.rever... |
#!/usr/bin/env python3
A, B = map(int, input().split())
price = "-1"
for x in range(1, 100000+1):
if int(x * 0.08) == A and int(x * 0.1) == B:
price = x
break
print(price)
|
from src.align.segmental import SegmentalAlign
class SegmentalAnalysis:
def __init__(self, segmental_align: SegmentalAlign):
self.__run(segmental_align)
def __run(self, segmental_align: SegmentalAlign):
pass
|
import sqlite3
import json
import numpy as np
class DatabaseConnector:
def __init__(self):
self.connection = sqlite3.connect('../assets/peaBrain.db')
self.c = self.connection.cursor()
def getTrainingCases(self, tableName):
cases = []
for row in self.c.execute('SELECT training_c... |
import sys
from collections import Counter, defaultdict
def digits(number):
count = Counter(number)
count = defaultdict(int, count)
dcount = {}
dcount[0] = count['Z']
dcount[2] = count['W']
dcount[6] = count['X']
dcount[7] = count['S'] - dcount[6]
dcount[5] = count['V'] - d... |
import numpy as np
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# from matplotlib.animation import ArtistAnimation
lenx = 1
lent = 1
deltat = 1 / 100
deltax = 1 / 100
Nt = 100
Nx = int(lenx / deltax)
st = deltat / deltax
u = np.zeros([Nx, Nt])
u[0, :]... |
import schedule
import time
def notify():
print("Hello!")
schedule.every(1).to(3).seconds.do(notify) |
# !/usr/bin/env python3
# -*- coding:utf-8 _*-
from __future__ import print_function
import pandas as pd
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score
from imblearn.over_sampling import SMOTE
from sklearn.cluster imp... |
from sqlalchemy.orm import sessionmaker
from seekingalpha_crawler.models import Companies, db_connect, \
create_table, Transcripts, InternalParticipants, ExternalParticipants,\
QA, QADialogue, Presentation, PresentationDialogue
class saveToSqlite(object):
def __init__(self):
"""
Initialize... |
#!/usr/bin/env python2
# -*- encoding: utf-8 -*-
GIMP_API = 'GimpApi.py'
from os import linesep as sep
from re import match, compile as re_compile
from Util import stream_join, concat_stream, nseq, compose, uh, infseq, identitystar, _globalq
from Gui import Gui
LET_RE = re_compile(r'^\s*(\w+)\s*=\s*(.+)$')
# Gimp... |
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from valid_detectors.learned_valid_detector import LearnedValidDetector
from decision_module import DecisionModule
from gv import dbg, rng
from action import StandaloneAction
from event import NewTransitionEvent
from util import first_sentence
... |
from common.controler import xls_control
from common.public import request
import time
import traceback
from tqdm import tqdm
class microsoft_appSource():
def __init__(self, row=2):
# excel 记录的起始行数, row = 1 是 title行
self.row = row
self.xls_op = xls_control()
self.xls_op.openXls(fil... |
import os
import sys
import csv
import time
import datetime
# YAML setup
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.boolean_representation = ['False', 'True']
class Logger():
def __init__(self, argv, args, short_args={}, files=[], stats={}):
self.save = args.save
... |
# Original code: https://github.com/ClayFlannigan/icp
# Modified to reject pairs that have greater distance than the specified threshold
# Add covariance check
import numpy as np
from sklearn.neighbors import NearestNeighbors
def compute_C_k(point1, point2):
d = point1 - point2
alpha = np.pi/2 + np.arctan2(d[... |
# *** MY CODE ***
import os
longest_word = {}
directory = raw_input("Enter a directory: ")
for user_file in os.listdir(directory):
if os.path.isfile(user_file):
long_word = ""
with open(user_file, "r") as f:
for line in f:
for word in line.split():
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scrapyproject', '0008_scrapersdeploy'),
]
operations = [
migrations.AddField(
model_name='linkgendeploy',
... |
'''
Given an array of equal-length strings, check if it is possible to rearrange the strings in such a way
that after the rearrangement the strings at consecutive positions would differ by exactly one character.
Example
For inputArray = ["aba", "bbb", "bab"], the output should be
stringsRearrangement(inputArray) = fa... |
#!/usr/bin/python3
import os
import requests
import json
import time
s=requests.session()
try:
f=open('checkpoint.txt', 'r').read()
except Exception as e:
raise e
val=f.split('\n')
try:
sellchk=val[0]
except Exception as e:
sellchk=''
try:
buychk=val[1]
except Exception as e:
buychk=''
run=0
while run==0:
res... |
#from pymysql import connections
import os
#import boto3
#from config import *
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/", methods=['GET','POST'])
def home():
return render_template('Home.html')
if __name__ =='__main__':
app.run(host='0.0.0.0',port=8080,debug=True... |
# write a Python program to check whether a file exists
import os
open('abc.txt','r')
print(os.path.isfile('abc.txt'))
# Write a Python program to determine if a Python shell is executing in 32bit or 64bit mode on os
import struct
print(struct.calcsize("P")*8)
#get os name , Platform and release information
# impo... |
#
# 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... |
from pyramid.i18n import TranslationStringFactory
PROJECTNAME = 'voteit.statistics'
StatisticsMF = TranslationStringFactory(PROJECTNAME)
def includeme(config):
config.scan(PROJECTNAME)
config.add_translation_dirs('%s:locale/' % PROJECTNAME)
|
#!/usr/bin/env python
# This runs way too long, need to fix
from common import *
def tri():
i = 1
while True:
yield (i*(i-1))/2
i += 1
def main():
tr = tri()
for n in tr:
if len(divisors(n)) > 500:
print n
if __name__ == '__main__':
main() |
def cs2(n, l):
if n == 0:
return 1
elif n < 0:
return 0
elif l[n] != -1:
return l[n]
else:
l[n] = cs2(n - 1, l) + cs2(n - 2, l) + cs2(n - 3, l)
return l[n]
print cs2(50, [-1 for _ in range(51)])
|
import time
def get_msg_level(m) :
global dc
global ic
global ac
global wc
global ec
global cc
global tc
if 'DEBUG' in m:
dc=dc+1
return "DEBUG"
elif 'INFO' in m:
ic=ic+1
return "INFO"
elif 'AUDIT' in m:
ac=ac+1
return "AUDIT"
elif 'WARNING' in m:
wc=wc+1
return "WARNING"
elif 'ERROR' in m:... |
#!python
__author__ = "DMcG"
__date__ = "$Jun 23, 2015 10:27:29 AM$"
import socket
import time
from io import BytesIO
from opendis.DataOutputStream import DataOutputStream
from opendis.dis7 import EntityStatePdu
from opendis.RangeCoordinates import *
UDP_PORT = 3001
DESTINATION_ADDRESS = "127.0.0.1"
udpSocket = s... |
# -*- coding: utf-8 -*-
import numpy as np
import click
from matplotlib import pyplot as plt
def plot_result(org_csv, inter_csv, bsp_csv):
"""
スプライン補間比較用
"""
org = np.loadtxt(org_csv, delimiter=",", skiprows=1)
inter = np.loadtxt(inter_csv, delimiter=",", skiprows=1)
bsp = np.loadtxt(bsp_csv,... |
from nose.tools import *
import sys
print("parser_tests: current path is:")
print(sys.path)
from lexer_tokens import *
from parser_code import Parser
from parser_elements import *
def setup():
print("Setting up parser tests")
def teardown():
print("Tearing down parser tests")
def test_parse_prog():
emp... |
#!/usr/bin/env python
import scipy as sc
print 'Reduce the read access to the global memory per thread block'
print '(the thread block dimension and size)'
p = sc.array([2,4,6,8])
tn = 3 + 3 + 3*2*p
print '\nwithout using cache'
print tn, '(*n)'
print '\n2nd\t4th\t6th\t8th\t(spatial order)'
print '1D'
for n,nx in... |
# flake8: noqa
from setuptools import setup
from distutils.util import convert_path
main_ns = {}
ver_path = convert_path('gps_track_clustering/version.py')
with open(ver_path) as ver_file:
exec(ver_file.read(), main_ns)
setup(name = 'gps_track_clustering',
version = main_ns['__version... |
import turtle as a
import sys
t = a.Turtle()
def draw(n):
for i in range(n):
t.forward(100)
t.left(360/n)
sides = 5
if(len(sys.argv) > 1):
if(sys.argv[1].isdigit()):
if (isinstance(int(sys.argv[1]), int)) and (int(sys.argv[1]) < 10):
print("Drawing with sides " + sys.argv[1])
... |
from django import forms
from .models import SignUp, Patient
from django.contrib.auth.models import User
class Sign(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model=User
fields=('username','password',)
help_texts={'username': None, 'password': N... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
from math import sqrt, ceil, floor
def factorize(n):
"""
Faktorizira število n.
Če je število n sodo, vrne njegovo polovico in 2. Tako se izogne neskončni zanki v primeru,
ko je n oblike 4k + 2, saj takih ni mogoče izraziti kot (x+y)(x-y), kjer sta x in y cela.
"""
def isSquare(... |
from package.sqlpackagesetting import SqlPackageSetting
class SqlPackage(object):
def __init__(self, setting: SqlPackageSetting):
self.__setting = setting
self.__database = None
self.__silent = False
self.__files = []
@property
def setting(self):
return self.__sett... |
# pylint: disable=E1101
# pylint: disable=no-name-in-module
""" Contains widget and their logic related to displaying menu and dispatching click buttons to gameServerClient"""
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.butto... |
import os
import glob
import warnings
import numpy as np
import nibabel
def _single_glob(pattern):
filenames = glob.glob(pattern)
if not filenames:
print('Warning: non exitant file with pattern {}'.format(pattern))
return None
if len(filenames) > 1:
raise ValueError('Non unique f... |
# Generated by Django 2.0.13 on 2019-03-15 15:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('andablog', '0006_auto_20170609_1759'),
]
operations = [
migrations.AddField(
model_name='entry',
name='content_mark... |
"""
Read documents from xhtml
"""
from __future__ import absolute_import
from bs4 import BeautifulSoup
import six
from pyth import document
from pyth.format import PythReader
from pyth.plugins.xhtml.css import CSS
class XHTMLReader(PythReader):
@classmethod
def read(self, source, css_source=None, encoding=... |
import re
from tqdm import tqdm
import codecs
import json
import pandas as pd
from SenetnceCropus import Sentence
import json
sentence = []
train_data = json.load(open('all_data_me.json',encoding='utf-8'))
for w in train_data:
sentence.append(w["segSentenceNumG"])
for w in sentence:
print(w)
import multiproces... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#usage python languagedetector.py scriptdir infile
import sys
import re
import subprocess
import codecs
import os
class LanguageDetector:
def __init__(self,scriptdir,inf):
self.inf=inf
self.tt_me='/mount/projekte/sfb-732/inf/users/sarah/tools/tree_tagger/... |
x = 3
while x >= 1:
ques = input('password please: ')
password = 'a123456'
if ques != password:
print('unsuccess, you have', x - 1, 'chances')
x = x - 1
elif ques == password:
print('success')
break
|
# Generated by Django 2.2.5 on 2020-03-15 18:46
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reservations', '0021_auto_20200316_0015'),
]
operations = [
migrations.AlterField(
model_name='reservation',
... |
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import TampereProvider
class TampereOAuth2Adapter(OAuth2Adap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright 2015 Baidu, Inc.
#
########################################################################
"""
File: test_list_transcoding.py
Date: 2015/07/2 14:09:40
"""
import os
import sys
impor... |
from cipher_crack.ciphers import transposition
def test_transposition_decipher():
to_decipher = "EVLNE ACDTK ESEAQ ROFOJ DEECU WIREE"
key = "ZEBRAS"
expected_output = "WEAREDISCOVEREDFLEEATONCEQKJEU"
assert transposition.decipher(to_decipher,key) == expected_output
def test_transposition_decipher_no_n... |
##**************************************************************************************************
##
## FileName : pathMaker.py
## Description: Functions for making a path
##
##**************************************************************************************************
def JetBTagPath( process , jet... |
"""信号量:与锁的作用类似
# 限制固定数量的进程 同时访问代码段
"""
import json
import time
import random
from multiprocessing import Process, Lock, Semaphore
class TrySemaphore(Process):
def __init__(self, man, sam):
super().__init__()
self.man = man
self.sam = sam
def run(self):
self.sam.acquire()
... |
def solution(phone_book):
phone_book = sorted(phone_book)
for i in range(len(phone_book) - 1):
temp_num1 = len(phone_book[i])
temp_num2 = len(phone_book[i + 1])
if temp_num1 <= temp_num2:
if phone_book[i + 1][ : temp_num1] == phone_book[i]:
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class MLP( nn.Module):
def __init__(self, input_dimension, hidden_size , target_dimension = 1, activation_layer = 'LeakyReLU'):
super().__init__()
Activation = nn.LeakyReLU
# if activation_layer == 'DICE': pass
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pywikibot, re, sys, argparse
import blib
from blib import getparam, rmparam, tname, pname, msg, site
def process_text_on_page(index, pagetitle, text):
global args
def pagemsg(txt):
msg("Page %s %s: %s" % (index, pagetitle, txt))
def expand_text(tempcall... |
# Generated by Django 3.1.2 on 2020-11-24 17:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('Book', '0002_auto_202011... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Employee(models.Model):
Employee_Id=models.IntegerField(primary_key = True)
Employee_Name=models.CharField(max_length=50)
Department_Name=models.CharField(max_length=50)
|
import mysql.connector
cnx = mysql.connector.connect(user='cmoneal', password='829812390',
host='127.0.0.1',
port='8080',
database='cmoneal')
cursor = cnx.cursor()
add_phone = ("INSERT INTO Phone "
"(s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv, sqlite3, datetime, sys
conn = None
try:
conn = sqlite3.connect( "registration.db" )
conn.text_factory = str #bugger 8-bit bytestrings
print "** Opening csv file"
with open('reginfo.csv', 'rb') as csvfile:
datareader = csv.DictReader(csv... |
"""
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]... |
import enum
from functools import cache
import cv2
import os
import time
class Moving(enum.Enum):
X = 0
Y = 1
W = 2
H = 3
class ObjectTracker:
def __init__(self, filename, n_tracks=1):
directory = os.path.join(os.path.dirname(__file__), 'haarcascade')
self.classifier = cv2.Casca... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Даны основания равнобедренной трапеции и угол при большем основании. Найти площадь трапеции.
import math
a = float(input("Введите длину большего основания: "))
b = float(input("Введите длину меньшего основания: "))
alpha = float(input("Введите угол при боль... |
import os
import boto3
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
from html.parser import HTMLParser
import operator
import csv
import json
from multiprocessing.dummy import Pool
import time
from s3_md5_compare import md5_compare
class MyHTMLParser(HTMLParser):
def __init__(s... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 15:50:15 2018
@author: eiahb
"""
#import scipy,pprint
#from pprint import pprint
import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
#from sklearn.metrics import log_loss
#import datetime
from my_class.common_function import *
from imblearn.over_sa... |
import json
import logging
import os
import tarfile
from datetime import datetime
from typing import Dict, List
from .utils import normalize_tarinfo, tar_addbytes
class File:
"""
An individually restorable file
"""
def __init__(self, path: str, size: int, modified: int):
self.path = path
... |
from rest_framework import serializers
from relationship.models import IMUser, FriendShip
from django.contrib.auth.models import User
from rest_framework.fields import Field
class IMUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = IMUser
fields = ('userid', 'phone', 'name... |
# type: ignore
Clock.bpm = 160
# p1 >> bass([0, 1, 2, 3, 4, 5, 6, 7])
d2 >> dbass([0, 4, 0, -4, 0, 4, 0, -4], amp=[0.5])
p1 >> play("1234", dur=2)
p2 >> play(
"&",
sample=1,
dur=2,
sus=2,
# slide=1,
# pan=linvar([-1, 1], 8),
fmod=2,
)
p3 >> play()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200, default="")
option_A = models.CharField(max_length=200, default='')
op... |
import os
import numpy as np
import pybullet as p
import pybullet_data
import time
import trimesh
import argparse
import grasp_utils as gu
import pybullet_utils as pu
from collections import OrderedDict
import csv
import tqdm
import tf_conversions
from mico_controller import MicoController
import rospy
import threading... |
#!/usr/bin/python
# -*- coding:utf8 -*-
import os
import datetime
savefile = open('newIduser-traj-geolife.txt', 'a+')
poiFile = open('gps-poi.txt', 'a+')
allFileNum = 0
poiDict = {}
userId = 0
poi = 1
def printPath(path):
global allFileNum
'''''
打印一个目录下的所有文件夹和文件
'''
# 所有文件夹,第一个字段是次目录的级别
dirL... |
from django.core.files.base import ContentFile
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from users.models import UserFeed, UserNotification, UserReport
from posts.models ... |
# Copyright 2020 Huy Le Nguyen (@usimarit)
#
# 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 t... |
from pathlib import Path
import os
import unittest
from sox import file_info
from sox.core import SoxError
def relpath(f):
return os.path.join(os.path.dirname(__file__), f)
SPACEY_FILE = relpath("data/annoying filename (derp).wav")
INPUT_FILE = relpath('data/input.wav')
INPUT_FILE2 = relpath('data/input.aiff')... |
#!/usr/bin/env python3
import time #used for sleep mainly
import socket, sys, os, signal, threading
import szasar, select
PORT = 6012
PORT2 = 6013
FILES_PATH = "files"
MAX_FILE_SIZE = 10 * 1 << 20 # 10 MiB
SPACE_MARGIN = 50 * 1 << 20 # 50 MiB
USERS = ("anonimous", "sar", "sza")
PASSWORDS = ("", "sar", "sza")
backup... |
__author__ = 'vasilev_is'
import random
import math
import numpy as np
class AbstractMeasurer:
"Defining a measurer abstraction"
#_xstart=[]
#_xend=[]
def measure (self, x):
raise NotImplementedError("Please Implement this method")
def getCovMatrix(self):
raise NotImplementedErr... |
"""This is the docstring for the convertSkewToTemp.py module."""
import numpy as np
def convertSkewToTemp(xcoord, press, skew):
"""
convertSkewToTemp(xcoord, press, skew)
Determines temperature from knowledge of a plotting coordinate
system and corresponding plot skew.
Parameters
- - - -... |
from corems.molecular_id.calc.ClusterFilter import ClusteringFilter
class MolecularFormulaSearchFilters:
@staticmethod
def filter_kendrick( ms_peak_indexes, mass_spectrum_obj):
index_to_remove = []
if mass_spectrum_obj.molecular_search_settings.use_runtime_kendrick_filter:
... |
from .io_base import read_final, read_defect_indexes
from .atom import cell, atom
from .defect import defect
|
import os
import pytest
import intake
from streamz.utils_test import wait_for
catfile = os.path.join(os.path.dirname(__file__), "catalog.yaml")
def test_simple():
cat = intake.open_catalog(catfile)
s = cat.simple.read()
l = s.sink_to_list()
assert not l
s.start()
wait_for(lambda: l == [1, 2, ... |
# -*- coding: utf-8 -*-
def power(a,b=1):#计算b个a相乘,b为位置参数,默认是1
sum = 1
while b>0:
sum = sum * a
b = b -1
return sum
#单例
def add_end(L = None):
if L is None:
L = []
L.append('初始化')
else:
L.append('end')
return L
x = int(input('请输入第一个数'))
y = int(input ('请输入第二个数'))
if (not isinstance(x,int)) | (not isinst... |
"""
__init__
__new__
cls
self
@classmethod
@staticmethod
__str__
__repr__
"""
class Singleton(object):
def __init__(self):
self.a = 88
self.__hidden = -1
def __new__(cls):
if not hasattr(cls,'instance'):
cls.instance = super(Singleton,cls).__new__(cls)
return cls.ins... |
""""connection_forwarder.py: SF connection object."""
import logging
import socket
import threading
from codecs import encode
from six import BytesIO
from moteconnection.connection_events import ConnectionEvents
from moteconnection.utils import split_in_two
log = logging.getLogger(__name__)
log.setLevel(logging.INF... |
with open("F://JRF//Trivim2//Projects//11//coordinates.txt")as cordd:
if cordd.readlines()[1].split("\t")[0]!= "none" :
print "true"
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class DeletionMethod(Model):
"""NOTE: This class is auto generated by the swag... |
#Q1
try:
x
except:
print("syntax error")
#Q3
x = []
x = input("enter 4 digits: ")
while(len(x) != 4):
x = input("String is too long/short, please provide 4 digits: ")
#Q4
print("Enter the username and password: ")
count = 0
while count <= 3:
user = input("Enter the username: ")
password = input("... |
from datetime import datetime
from application.salary import calculate_salary
from db.people import get_employees
if __name__ == '__main__':
calculate_salary()
get_employees()
date = datetime.now()
print(date)
|
#!/usr/bin/env python3
"""
AdventOfCode day 12.
"""
import argparse
import logging
import os
import sys
import json
import fnmatch
from datetime import datetime
def get_args():
"""Parse args from terminal."""
parser = argparse.ArgumentParser(
description='AdventOfCode')
parser.add_argument(
... |
# -*- coding: UTF-8 -*-
'''
Created on 2017年12月6日
@author: dongwh3
'''
import numpy as np
class CrossEntropy(object):
def Calculate(self, A, Y):
assert(A.shape[0] == 1)
assert(Y.shape[0] == 1)
assert(A.shape[1] == Y.shape[1])
m = A.shape[1]
L_mat = (-1) * (Y * np.log(A) + (1... |
import numpy as np
from collections import defaultdict
import json
import os
def make_epsilon_greedy_policy(action_space_size, Q_state, epsilon):
epsilon = max(epsilon, 0.10)
policy_state = np.ones(action_space_size) * epsilon / action_space_size
policy_state[np.argmax(Q_state)] = 1 - epsilon + (epsilon /... |
# tests.py 06/01/2016 (c) D.J.Whale
#
# Test harness for forth.py
import unittest
import forth
# Aliases, for brevity
LIT = forth.Forth.LITERAL
STR = forth.Forth.STRING
class Experiment(unittest.TestCase):
"""A small smoke test - non exhaustive"""
def setUp(self):
#print("setup")
self.f = f... |
import io
import mimetypes
import os
import tempfile
from collections import namedtuple
from contextlib import contextmanager
from cached_property import cached_property
from fluffy.app import app
from fluffy.utils import content_is_binary
from fluffy.utils import gen_unique_id
from fluffy.utils import ONE_MB
MIME_... |
'''
Created on Apr 27, 2018
@author: Debiprasanna.M
'''
#-------------------------------------------------------
#importing modules
import paramiko
import time
import re
#pdb.set_trace()
# setting parameters like host IP, username, passwd and number of iteration
# to gather cmds
HOST = "10.16.82.125... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from .utils import get_gravatar_url
from .managers import UserManager
class User(AbstractBaseUser):
username = models.CharField(max_length=15, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.... |
import os
import json
import frontmatter
from datetime import datetime
POST_DIR = "./posts/"
POST_JSON_DIR = POST_DIR + "json/"
LOCATION_MD_BASE_URL = "https://raw.githubusercontent.com/typekev/typekev-blog/master/posts"
LOCATION_JSON_BASE_URL = f"{LOCATION_MD_BASE_URL}/json"
posts = {}
def get_md_location(id):
... |
# MATH AND FORMATTING (34PTS TOTAL)
# By Nathan Satterfield
# FORMATTING
# PROBLEM 1 (2pts)
# Use {}.format() to print 0.000321192 in scientific notation to two decimals
print("{:.2e}".format(0.000321192))
# PROBLEM 2 (2pts)
# You get 8 out of 9 on a quiz.
# Print 8/9 using {}.format() so that it appears as 88.9%
pr... |
import random
import numpy as np
from torch.utils.data import Dataset
from .base import _include_repr
from .utils import ensure_same_sampling_rate
__doctest_skip__ = ['*']
class SpeechNoiseMix(Dataset):
r"""Mix speech and noise with speech as target.
Add noise to each speech sample from the provided data... |
import copy
import queue
import threading
def decode_opcode(opcode):
return (opcode % 100, opcode // 100)
def get_values(params, modes, memory):
values = []
for param in params:
mode = modes % 10
modes = modes // 10
if mode == 0:
values.append(memory[param])
el... |
# coding: utf-8
"""
난이도 : 2
문제 : 문자열 뒤집어 출력
알고리즘 : 처음 숫자 입력받은 만큼 반복하며, 입력받은 문자열을 split(공백 구분)하고 각 단어별로 뒤집어서([::-1] 사용),
' '.join()으로 문자열로 만들어 출력
"""
## 내 풀이
for _ in range(int(input())):
print(' '.join([i[::-1] for i in input().split()]))
## 다른 사람 숏 코딩
exec('print(*input()[::-1].sp... |
import unittest
from registration_system import registration_system as foo
# The dictionary is stored across the three test cases
class TestRegistrationSystem(unittest.TestCase):
def test_given(self):
self.assertEqual('OK', foo('abacaba'))
self.assertEqual('OK', foo('acaba'))
self.assertEq... |
# Generated by Django 3.0.7 on 2020-06-26 07:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('BankManagement', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='Employee_ID',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.