text stringlengths 8 6.05M |
|---|
import boto3
import json
# def get_route_details(region):
# client = boto3.client('route53', region_name=region)
# response = client.list_hosted_zones()
# response = response['HostedZones']
# ids = []
# for i in range(len(response)):
# temp = response[i]
# ids.append(temp['Id'])
# ... |
from getSqlData import *
from encodeJson import *
def getData(latitude, longitude):
SqlData = getSqlData(latitude, longitude)
jsonData = encodeJson(SqlData)
return jsonData
|
print 1+2;
f = open('test', 'w');
f.write('6');
f.close();
f = open('test2', 'w');
f.write('demo output');
f.close();
|
s = 0
pa = int (input ('Digite o primeiro termo da PA '))
razao = int (input ('Digite a razão da PA '))
razao1 = razao * 10
for c in range(pa,razao1+1,razao):
s = razao + s
print(s)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pexpect
import sys
import os
import configparser
import re
from funcy import re_all, partial, lmap, re_find
from funcy import select, distinct, filter, re_test, lmapcat
from toolz import thread_last
prompter = "#$"
pager = "--More--"
logfile = sys.stdout
config = ... |
fname=input("Enter file name: ")
try:
f=open(fname)
except:
print("Entered file name is not available")
quit()
for l in f:
l=l.rstrip()
print(l.upper())
|
from django.contrib import admin
from django.apps import apps
from course.management.commands import refreshachievements
from .models import *
from .forms.forms import UserCreationForm, CaptchaPasswordResetForm
from django.forms import BaseInlineFormSet, ModelForm
from django.forms.widgets import TextInput
from django.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 定义方法
def cheese_and_cracker(cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give t... |
import tkinter
import tkinter.ttk as ttk
from world import world
from util_frames import ActorStatsFrame
from PIL import Image, ImageTk
import fonts
class PlayerActorFrame(ttk.Frame):
def __init__(self, master=None):
ttk.Frame.__init__(self, master)
self.actor_image = None
# create widget... |
"""Plot Graph to Show Unemployed people in Thailand"""
import matplotlib.pyplot as plt
def main():
"""Plot graph from people in Thailand who are unemployed"""
x = range(2550, 2560)
y = [0.9961, 1.0056, 1.0836, 0.7522, 0.4894, 0.4752, 0.5152, 0.5883, 0.6165, 0.6787]
plt.plot(x, y, color="blue", marker="... |
import random
a = 451
b = 55465215
c = a * b + b
# Testing 0
print(c)
def main():
while True:
if a < b:
print(str(b) + " " + "is greater")
break
elif a > b:
print(str(a) + " " + "is greater")
break
else:
print("test failed")
... |
#!/usr/bin/env python
# encoding=utf8
# made by zodman
import grab
import click
import urllib.parse
import logging
import slugify
from utils import get_conf
#logger = logging.getLogger('grab')
#logger.addHandler(logging.StreamHandler())
#logger.setLevel(logging.DEBUG)
def _upload_frozen(file, froze... |
#!/usr/bin/env python
import rospy
from dynamic_reconfigure.server import Server
from std_msgs.msg import Bool, Int8, Int32, Float64
from hektar.msg import wheelVelocity, armTarget, Claw
from hektar.cfg import HektarConfig
# Master control header. This node takes the state of features in the course and dictates arm and... |
#-*-coding:utf-8-*-
#__author__='maxiaohui'
from config import config
from test_device.terminal import frDevice
from adb.deviceLogger import getAdbLog
@getAdbLog
def addAdmin(name):
device34=frDevice(config.deviceId)
device34.enterSetting()
device34.addAdmin(name)
addAdmin("李丽丽") |
from flask import Flask, jsonify
from flask_migrate import Migrate
from .model import configure as config_db
from .serializer import configure as config_ma
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS... |
from rest_framework import status
from rest_framework_jwt.serializers import RefreshJSONWebTokenSerializer
from rest_framework_jwt.views import ObtainJSONWebToken, JSONWebTokenAPIView
from project.serializers import CurrentUserSerializer
from project.utils import LogUtilMixin
from django.contrib.auth import get_user_m... |
from flask_restful import abort, Resource
from . import db_session
from .token import Token
from flask import jsonify
def abort_if_user_not_found(app_name):
session = db_session.create_session()
app = session.query(Token).filter(Token.app == app_name).first()
if not app:
abort(404, message=f"App {... |
# Copyright 2022 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
# Problem name: Permutations
# Description: A permutation of integers 1,2,…,n is called beautiful if there are no adjacent elements whose difference is 1.
# Given n, construct a beautiful permutation if such a permutation exists.
# Strategy: use if-else concept
num=int(input())
if(num==1):
print(1)
eli... |
import pandas
import numpy
from pprint import pprint
def ID3(df,origina_df,features,target,parent_node_class = None):
#Setting default parent node class as None
#Define end scnarios --> If true, return leaf
#If all target_values have the same value, return this value
if len(numpy.unique(... |
# dataset, labels = data.from_file()
#
# model.fully_connected(dataset, labels, [20, 40, 60, 20, 12, 6], 50001)
from learn import data
from learn import model
if __name__ == '__main__':
dataset, labels = data.get_dataset()
model.fully_connected_(dataset, labels, [20, 40, 60, 20, 16], 100001) |
import torch
from torch import nn
from torch.nn import functional as F
from typing import Optional
def label_smoothed_nll_loss(
lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1
) -> torch.Tensor:
"""
Source: https://github.com/pytorch/fairseq/blob/mast... |
import os
import csv
import psycopg2
csv.field_size_limit(100000000)
db_name = os.environ["POSTGRES_DB"]
db_user = os.environ["POSTGRES_USER"]
db_psw = os.environ["POSTGRES_PASSWORD"]
conn = psycopg2.connect(
"host=/var/run/postgresql/ dbname={} user={} password={}".format(
db_name, db_user, db_psw))
cur... |
from selectorlib import Extractor
import requests
import json
ext = Extractor.from_yaml_file('css_format.yml')
def scrape(url):
headers = {
'dnt': '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko)... |
import re
import pytest
from unittest import mock
import builtins
def nested_lists():
allscores = set()
allnames = []
for i in range(int(input())):
list = []
name = input()
score = float(input())
list.append(name)
list.append(score)
allscores.add(score)
... |
import pygame
import os
import time
import random
pygame.init()
# Maximum height and width of the game surface
WIDTH, HEIGHT = (750, 750)
# To create the display surface
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the surface caption
pygame.display.set_caption("MyGame")
# Background image
... |
'''
Created on Jun 18, 2013
@author: jsflax
'''
|
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
"""take structure factor and hydrophobic factor as input value for
our kernel function"""
tm = pd.read_csv("merged_file.csv")
df = tm.drop_duplicates()
train_data = []
label = []
id = []
for each in df.values:
train_dat... |
import logging
from six.moves import input
from django.core.management import BaseCommand, CommandError, call_command
from elasticsearch_dsl import connections
from stretch import stretch_app
class Command(BaseCommand):
"""
Create or Update the Elasticsearch Indices from Stretch Indices
"""
can_impo... |
from peewee import (SqliteDatabase, Model, CharField, IntegerField, TextField
)
db = SqliteDatabase('matches.db')
class Match(Model):
# each match create with this first block of data
# data is in player matchlist
platformId = CharField()
gameId = IntegerField(unique=True)
cham... |
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from collections import Mapping
from flask.ext.mail import Message
from flamaster.extensions import mail, mongo
from mongoengine import StringField, ListField, EmailField, FileField
from .decorators import classproperty
from .utils import plural_unders... |
import json
import socket
import hashlib
import rsa
class Connector:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(0.5)
self.server_ip = 'localhost'
self.port = 2137
self.login = ''
self.token = -1
self... |
import logging
import config
from aiogram import Bot, Dispatcher, executor
from aiogram.contrib.fsm_storage.redis import RedisStorage
logging.basicConfig(level=logging.INFO)
storage = RedisStorage(host='localhost', port=6379)
bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot, storage=storage)
|
"""A simple example of asyncio. This code is available from python 3.7.
References
- history of asyncio: https://asyncio-notes.readthedocs.io/en/latest/asyncio-history.html
- asyncio: https://docs.python.org/3/library/asyncio.html
- asyncio.queue: https://docs.python.org/3.7/library/asyncio-queue.html
- producer-consu... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 5 11:14:59 2019
@author: Reuben
"""
from .variable import Store, Aliases
class Name_Space(dict):
def __init__(self, obj_cls=Store):
self.i = 0
self.obj_cls = obj_cls
self._active = None
def __missing__(self, key):
return self.c... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver.core import run
from revolver import contextmanager as ctx
from revolver import directory as dir
from revolver import package, file
def install():
package.ensure("git-core")
if not dir.exists(".rbenv"):
... |
# Copyright 2017 The Forseti Security 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 ap... |
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^... |
from django.test import TestCase
from common.models import Injection
class InfoTest(TestCase):
def test_info_page_renders_info_page_template(self):
response = self.client.get('/info/')
self.assertTemplateUsed(response, 'info/info.html')
def test_info_page_displays_all_medications(self):
... |
import numpy as np
import pandas as pb
# Use the motion parameters to fid the bad brains
# Use the qc_csv to find the bad brains
# Motion Based outliers
def read_par_file(motion_params_file):
volumes_count = 0
trans_x = []
trans_y = []
trans_z = []
rot_x = []
rot_y = []
rot_z = []
w... |
# Vorgestellter Ablauf:
# Eingabe von Datum eingeteilt in Tag und Monat
# Ausgabe des jeweiligen Sternzeichens anhand Zuordnung durch das Tool
def herausfinden():
if month == 1 and day < 20 or month == 12 and day > 22:
print("Steinbock")
elif month == 2 and day > 19 or month == 1 and day > 20:
... |
import unittest, os
SRC_PATH = os.path.join(os.path.dirname(__file__), 'src')
TEST_CASES = unittest.defaultTestLoader.discover(SRC_PATH, '*.py')
suite = unittest.TestSuite()
suite.addTest(TEST_CASES)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
|
# Generated by Django 3.0.4 on 2020-04-23 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apps', '0017_department_sequence'),
]
operations = [
migrations.AlterField(
model_name='department',
name='address',... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
from functions_script import vector_mean as mean
def b_1(x, y):
mx = mean(x)
my = mean(y)
numerator = denominator = 0.
for xi, yi in zip(x, y):
numerator += (xi - mx) * (yi - my)
denominator += (xi - mx) ** 2
return numerator /... |
import unittest
from app.code.bank.account import Account
class AccountTest(unittest.TestCase):
def test_create_valid_account(self):
account = Account("001", 50)
self.assertEqual(account.account_number, "001")
self.assertEqual(account.balance, 50)
def test_create_account(self):
... |
import math
def calcFuel(input):
fuel = math.floor(input / 3) - 2
return fuel
if __name__ == "__main__":
file = open("input.txt")
fuel_sum = 0
for line in file.readlines():
mass = int(line)
fuel = calcFuel(mass)
while fuel > 0:
fuel_sum += fuel
fuel... |
# -*- coding: utf-8 -*-
"""
libs.encoding_utils
~~~~~~~~~~~~~~
force encoding of a file
:copyright: (c) 2012 by arruda.
"""
import os
import shutil
def convert_to_utf8(filename):
# gather the encodings you think that the file may be
# encoded inside a tuple
encodings = ('ascii','iso-... |
integer = 11
float = 34.141
string = "Texto"
#representacion de digito
print("Mi texto {:d}".format(integer))
#representacion binaria
print("Mi texto {:b}".format(integer))
#representacion hexadecimal
print("Mi texto {:b}".format(integer))
#representacion flotante
print("Mi texto {:f}".format(integer)) |
import argparse
import pandas as pd
from owlready2 import *
from knowledge_graph.network_class import Network
def get_edges(ontology, source):
node_network = Network(ontology, source)
node_network.dfs_labeled_edges()
return node_network.get_results()
def test_answer():
assert search_node(get_ontolo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# collection of funcions related to the marshall gci scripts.
#
import requests, json, os, time
import numpy as np
import concurrent.futures
from astropy.time import Time
import astropy.units as u
import logging
logging.basicConfig(level = logging.INFO)
logging.getLogg... |
# APP CONFIGS
SECRET_KEY='develop',
CACHE_TYPE='null',
|
import argparse
import my_utils
import pyproj
from map_html import TOP as MAP_TOP
from map_html import BOTTOM as MAP_BOTTOM
from map_html import CIRCLE_RED_20, CIRCLE_RED_50
class Runner(object):
def __init__(self, args):
# self.user_id = args.user_id
# self.start_time = args.start_time
... |
"""
5. Faça um Programa que converta metros para centímetros.
5.1. 1 metro e igual a 100cm
5.2. cm = metro / 0.01
"""
def metros(x):
cm = x / 0.01
return str(int(cm)) + 'cm'
if __name__ == '__main__':
assert metros(1) == '100cm'
assert metros(2) == '200cm'
assert metros(3) == '300cm'
|
# Python
multiples_of_3 = filter(lambda x: x % 3 == 0, \
[1, 2, 3, 4, 5, 6, 7, 8, 9])
|
# Copyright 2022 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import numpy as np
from fractions import Fraction
a = np.matrix([[1, 2], [1, 1]])
u = np.array([[1], [1]])
for i in range(10):
u = a * u
print u
def rec(n, i):
if i == 0:
val = 2
elif i % 3 == 2:
val = 2 * (i // 3 + 1)
else:
val = 1
if i == n:
return val
e... |
import math
events = []
time = 0
class Event:
def __init__(self, delay, name, params):
global events
self.when = delay + time
self.name = name
self.params = params
global events
events.append(self)
@staticmethod
def popEvent():
"""
:return... |
from pyspark.sql import SQLContext
from pyspark.sql import HiveContext
from pyspark.sql.types import *
import ml_processing #import steel_thread
from pyspark import SparkContext
import forecast_data_v4 #import forecast_data_v3
import numpy as np
import pandas as pd
sc = SparkContext()
hive_context = HiveContext(sc)
... |
from django.urls import path
from django.urls.conf import re_path, path
from .apis import *
urlpatterns = [
path('exports/add', AddExportApi.as_view(), name='export_add'),
re_path(r'^exports/list/(?:start=(?P<start>(?:19|20)\d{2}(0[1-9]|1[012])))&(?:end=(?P<end>(?:19|20)\d{2}(0[1-9]|1[012])))$', ExportListApi... |
__all__ = [
'ResetRepositoryCounters',
]
from gim.core.tasks.repository import RepositoryJob
class ResetRepositoryCounters(RepositoryJob):
queue_name = 'reset-repo-counters'
def run(self, queue):
super(ResetRepositoryCounters, self).run(queue)
counters = self.object.counters
cou... |
x, y = map(int, input().split(' '))
c = 0
for n in range(1, y + 1):
c += 1
if c != x:
print(n, end=' ')
if c == x:
print(n)
c = 0 |
while True:
a, b = map(int,input().split())
if a + b == 0 :
break;
else :
print(a ** b)
|
import json
import os
import string
import subprocess
import random
from shutil import copy, rmtree
from web3 import Web3
from src.util.config import Config
from src.util.web3 import web3_provider
from brownie import accounts, project
from tests.utils.keys import get_viewing_key
signer_accounts = ['0xA48e330838A616... |
from classes.ListNode import ListNode
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
"""
https://leetcode.com/problems/remove-linked-list-elements/
had to delete the head elements differently
"""
if head is None:
return None
... |
#!/usr/bin/env python
from elasticsearch_dsl import Search, A
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError
import pytz
import datetime
from tzlocal import get_localzone
ES_SERVER = '172.31.23.21:9200'
class ELK(object):
def __init__(self):
self.elk_host... |
from collections import *
#User function Template for python3
class Solution:
#Function to return list of integers visited in snake pattern in matrix.
def snakePattern(self, matrix):
leftRight=True
output=[]
for i in range(len(matrix)):
currentLevel=deque([])... |
import itertools
import logging
import pandas as pd
from bitarray import bitarray
from aq.aq_description import Fact
class FactBase:
def __init__(self, target_prop):
self.target_prop = target_prop
self.positives = {}
self.negatives = {}
self.properties = []
s... |
'''
Created on 4 Jul 2011
@author: Will Rogers
Tests for the RecordFactory.
'''
import unittest
from apel.db.loader.record_factory import RecordFactory, RecordFactoryException
from apel.db.records import JobRecord
from apel.db.records import SummaryRecord
class Test(unittest.TestCase):
def setUp(self):
... |
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name="rosmap",
version="0.2",
packages=find_packages(),
scripts=['rosmap-launcher'],
install_requires=['GitPython>=2.1.8',
'pyyaml>=4.2b1',
'pyquery>=1.4.0',
'... |
import numpy as np
import matplotlib.pyplot as plt
POISSON_PARAM = 3
UNIFORM_FRONT = np.sqrt(3)
def normalized_distribution(x):
return (1 / np.sqrt(2 * np.pi)) * np.exp(-x * x / 2)
def laplace_distribution(x):
return (1 / np.sqrt(2)) * np.exp(-np.sqrt(2) * np.abs(x))
def uniform_distribution(x):
flag... |
"""MIPT Python Course Lection 25"""
visited = [False]
ans = []
def dfs(start, G, visited):
visited[start] = True
for u in G[start]:
if not visited[u]:
dfs()
ans.append(start)
for i in range(1, u+1):
if not visited[i]:
dfs(i, G, visited, ans)
ans[i] = ans[:... |
def addNumbers():
welcomeAdd = "This is the Add Section"
print(welcomeAdd)
firstNumber = int(input("Input the first number to add"))
secondNumber = int(input("Input the Second number to add"))
moreNumberInputs = input("Would you like to add more numbers?")
moreNumberInputs = moreNumberInpu... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'login.ui'
#
# Created by: PyQt5 UI code generator 5.12
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def openwindow(self):
self.window = QtWidgets... |
'''
Alessia Pizzoccheri - CS 5001 02
'''
import random
import turtle
import kmeans_viz
DATA = [
[-32.97, -21.06], [9.01, -31.63], [-20.35, 28.73], [-0.18, 26.73],
[-25.05, -9.56], [-0.13, 23.83], [19.88, -18.32], [17.49, -14.09],
[17.85, 27.17], [-30.94, -8.85], [4.81, 42.22], [-4.59, 11.18],
[9... |
from django.shortcuts import render
from common.models import Injection, CRI
from calc.forms import CalcInjForm, CRISimpleForm, CRIAdvancedForm, CRIInsulinForm, CRICPRForm, CRIMetoclopramideForm
from collections import OrderedDict
def calc_injection(request):
"""Calculates injection dosages based on weight.
... |
while True:
n = input("Please enter a number (0 to exit) : ")
n = int(n)
if n == 0:
break
print("Square of",n,"is ", n*n) |
#coding:utf-8
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import random
import tkinter
number = int()
def sim():
nombre_de_départ = number
liste = []
while nombre_de_départ > 0:
liste.append(nombre_de_départ)
for i in range(n... |
import math
from repartition_experiments.algorithms.utils import *
from repartition_experiments.algorithms.policy_remake import compute_zones_remake
def shape_to_end_coords(M, A, d=3):
'''
M: block shape M=(M1, M2, M3). Example: (500, 500, 500)
A: input array shape A=(A1, A2, A3). Example: (3500, 3500, 35... |
name = input("What is your Name?\n")
name_len = len(name)
print("Your Name is" , name, " and It has" , name_len, "Characters") |
from django.contrib import admin
from .models import Field, Lecturer, Course, Lecture, LectureSession, LectureClassSession, Department
admin.site.register(Department)
admin.site.register(Field)
admin.site.register(Lecturer)
admin.site.register(Course)
admin.site.register(Lecture)
admin.site.register(LectureSession)
a... |
import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from game_stats import GameStats
from ship import Ship
from ufo import Ufo
import game_functions
from button import Button
from scoreboard import CurrentScore
from scoreboard import HiScore
from scoreboard import Level
from life i... |
#!/usr/bin/python3
# Author: Connor McLeod
# Contact: con.mcleod92@gmail.com
# Source code: https://github.com/con-mcleod/MonthlyPerf_Report
# Latest Update: 10 August 2018
import sys, csv, sqlite3, os, glob, re
from xlrd import open_workbook
##############################
# #
# SQL DATABA... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.codegen.thrift.target_types import (
ThriftSourcesGeneratorTarget,
ThriftSourceTarget,
)
from pants.engine.target import BoolField
class ScroogeFinagleBoolField... |
from data import DataGeneratorNew
from core import ResNet
import tensorflow as tf
import math
slim = tf.contrib.slim
result_txt_file = "result.txt"
DATASET_DIR = "D:\\competition\\data\\test_img\\test"
CHECKPOINT_DIR = 'D:\\pycharm_program\\UrbanFunctionClassification\\checkpoint'
NUM_CLASSES = 9
BATCHSIZE = 1
def to... |
from datetime import datetime
import glob
import hashlib
import subprocess
#timeFilterTooOld = 3600 * 600
class Monitor :
def __init__(self, conf) :
print "init nginx stuff"
self.filterOlderThan = 3600 * conf["filterOlderThan"]
self.accessLogfiles = glob.glob(conf["accessLogs"]... |
s = set()
for w in input().split():
if w in s:
print("no")
exit()
s.add(w)
print("yes")
|
# Euler 46.Goldbach's other conjecture
import math
def primes_sieve2(limit):
a = [True] * limit
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in range(i*i, limit, i):
a[n] = False
def isComposite(x):
for i in range(2,x):
i... |
#Filename for easy use
fileName="noErrors.py"
mapFile="testMap"
#Variance for return values
carSpeedSensorError=30
carGyroSensorError=0
#Variance for calculation
carSteerError=0
carSpeedError=0
#Car Settings
carMaxSpeed=100
carMaxSteer=1
carStartX=55
carStartY=80
carStartAngle=-1.57075
#carStartX=4... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def jia(x, y):
return x + y
def jian(x, y):
return x - y
def cheng(x, y):
return x * y
def chu(x, y):
return x / y
operator = {'+': jia, '-': jian, '*': cheng, '/': chu}
print(operator['+'](3, 2))
|
__author__ = 'local admin'
def recursive_modexp(m, e, n):
"""
modular exponentiation
:param m: ?
:param e: ?
:param n: ?
:return:
"""
if e == 0:
return 1
if e % 2 == 1:
return recursive_modexp(m, e-1, n) * m % n
e... |
import random
import easygui
def initialize_game():
guessNumber = 10
maxNumber = 20
secretNumber = random.randint(1, maxNumber)
return [guessNumber, maxNumber, secretNumber]
def play_game(playerName, guessNumber, maxNumber, secretNumber):
for i in range(guessNumber):
guessCount = i + 1
... |
"""
Copyright 1999 Illinois Institute of Technology
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
without limitation the rights to use, copy, modify, merge, publis... |
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class Base(object):
create_time = models.DateField(auto_now_add=True)
update_time = models.DateField(auto_now=True)
class Meta():
abstract = False # 这个类不生成对象
# 考虑后续的扩展
# 分类
class C... |
import pickle
from pathlib import Path
from collections import defaultdict
import numpy as np
from second.core import box_np_ops
from second.data.dataset import get_dataset_class
from second.utils.progress_bar import progress_bar_iter as prog_bar
def create_groundtruth_database(dataset_class_name,
... |
from . import general
|
#!/usr/bin/python3
import cgi
import os
import cgitb
from time import time, localtime, strftime
import datetime
import calendar
cgitb.enable()
clock=strftime("%a, %b %d %Y %H:%M:%S", localtime())
def index():
""" Show the default page
"""
print ('content-type: text/html')
#print ('</html>')
index()
def showFo... |
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText
from apache_b... |
'''
Baseline methods.
-various LOF-based methods
-isolation forest
-dbscan
-l2
-elliptic envelope
-naive spectral
-
'''
import torch
import numpy as np
import sklearn
import sklearn.ensemble
import sklearn.covariance
import sklearn.cluster
import random
import utils
import pdb
'''
kNN method that uses distances to k ... |
import numpy as np
arr = []
val = list()
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
mask = [0,1,2,7,11,12,13]
for i in range(4):
for j in range(4):
val = val.append(sum([arr[i] for i in mask]))
mask = np.add(mask,1)
mask = np.add(mask,4)
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.