text stringlengths 38 1.54M |
|---|
import sys
import os
import rospy
import math
import numpy as np
from threading import Thread
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import PolygonStamped, PointStamped, PoseStamped, PoseWithCovarianceStamped
from nav_msgs.msg import Odometry
class StateSubscriber:
"""
Cla... |
# coding: utf-8
import collections
import sys
ID, GENDER, PRODUCT, CLASP_TYPE, POCKET_TYPE, SEAM_LENGHT, CUTTING, DESIGN_EFFECTS, SEASON = range(9)
Description = collections.namedtuple("Description",
['gender', 'product', 'clas_type', 'pocket_type', 'seam_lenght', 'cutting', 'design_effects', 'season', 'i... |
# coding=utf-8
from __future__ import unicode_literals, print_function
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
from pub_site import create_app
app = create_app(os.getenv('ENV') or 'prod')
|
from flask import g, abort
from flask_restaction import Resource
from purepage import db
from couchdb.http import NotFound, CouchdbException
class Article(Resource):
"""Article"""
schema_article = {
"_id": ("unicode&required", "文章ID"),
"userid": ("unicode&required", "作者"),
"catalog": ... |
import urllib2
import json
def get_parking_spots():
contents = json.loads(urllib2.urlopen("http://smart-parking-bruck.c9users.io:8081/parking_spots?name=P1").read())
if(contents[0]["name"] != "P1"):
print "Test failed: get_parking_spots()"
else:
print "Test passed: get_parking_spots()"
def get_parking_lot():... |
from aws_cdk import (
aws_lambda as lambda_,
aws_apigateway as apigw,
core
)
class ApplicationStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, lambda_arn: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
referenced_function = lambda_.Function.... |
import unittest
import os,sys
cur_dir = os.path.dirname(__file__)
par_dir = os.path.dirname(cur_dir)
sys.path.append(par_dir)
from mysql import *
import pytest
class Mysql(unittest.TestCase):
@pytest.mark.run(order=3)
def test_connect(self):
with mysql() as db:
self.assertEqual(db.connect()... |
from flask import Flask, Blueprint,render_template,redirect,url_for, request, jsonify, make_response
app=Blueprint('api_tester', __name__)
@app.route('/api_tester', methods=['GET', 'POST'])
def display_tester():
return render_template("api_tester.html")
|
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, Field
from typing import Optional
from schemas.pyobject import PyObjectId
class InputItem(BaseModel):
name: str
description: Optional[str] = None
class Item(BaseModel):
id: PyObjectId = Field(..., alias='_id')
name: str
... |
"""
.. moduleauthor:: Li, Wang <wangziqi@foreseefund.com>
"""
import pandas as pd
from orca.barra.base import BarraOptimizerBase
from orca.barra import util
class BarraOptimizer(BarraOptimizerBase):
def __init__(self, config, debug_on, alpha, univ, dates):
super(BarraOptimizer, self).__init__(config, d... |
from openpyxl import *
xl=load_workbook("Login.xlsx")
ss=xl.active
for i in ss.iter_cols(min_col=1,max_col=2,min_row=1,max_row=3,values_only=True):
for c in i:
print(c) |
"""
qSQLA Query Syntax
==================
qSQLA is a Query Syntax to filter flat records derived from SQLAlchemy selectable objects.
Each field can be queried with a number of different operators.
The filters are provided in the query string of a ``HTTP GET`` request. The operator is added with a double underscore
to... |
from pycorenlp import StanfordCoreNLP
# You have to download the latest StanfordCoreNLP model from https://stanfordnlp.github.io/CoreNLP/index.html#download and call it with the following command, adjusting the path accordingly
# java -mx4g -cp "D:\Felix\Downloads\stanford-corenlp-4.2.0\\*" edu.stanford.nlp.pipelin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Fast Azimuthal Integration
# https://github.com/pyFAI/pyFAI
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# This program is free software... |
# -*- coding: utf-8 -*-
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License");... |
"""
Generic plot functions based on matplotlib
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import int
try:
## Python 2
basestring
except:
## Python 3
basestring = str
import pylab
import matplotlib
import matplotlib.ticker
import matplot... |
from aocd import data
from itertools import repeat, starmap
def remove_matchy_matchy(d):
for i in range(len(d) - 1):
if d[i].lower() == d[i+1].lower() and d[i].islower() != d[i+1].islower():
return d[:i] + d[i+2:]
return d
def stripped(d, l):
n = d.replace(l, '').replace(l.upper(), '')... |
# -*- coding: utf-8 -*-
# @Time : 2020/2/27 14:40
# @Author : Deng Wenxing
# @Email : dengwenxingae86@163.com
# @File : baseAsyncIOCoroutine.py
# @Software: PyCharm
from asyncio import Queue
import asyncio
async def add(store,name):
for i in range(5):
await asyncio.sleep(1)
await store.put... |
"""
author @shashanknp
created @2020-09-13 01:30:51
"""
def findInfected(i, time, V, current, pos):
if pos[i] == 1:
return
pos[i] = 1
for j in range(len(V)):
if time[i][j] > current:
findInfected(j, time, V, time[i][j], pos)
return pos
T = int(input())
for it in range(... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 19:04:29 2021
@author: USER
"""
import random
ans = random.sample(range(1,50),6)
print(ans) |
# -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from triangle import classify_triangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html h... |
"""This program will determine the cost of painting a wall"""
# 1. Define
import math
def gather_wall_sq_ft():
"""This function gathers the number of walls and the dimensions of those walls from the user, transforms the dimensions
into sq ft, and then outputs a list of the square footage of each wall
"""... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 11 07:52:43 2016
@author: OffermanTW1
"""
from pandas import Series, DataFrame
#Import regular operators and comparisons
from operator import lt, le, eq, ne, gt, ge
from operator import add, sub, truediv, mul
#Import custom operators and comparison
... |
from pprint import pprint
from fb_mcbot.models import FBUser, Conversation, StudentSociety, Admin, Major, Course
class Question:
question_type = {'NOTHING': 0, 'USER_TYPE': 1, 'AUTHENTICATE': 2, 'CHANGE_STATUS': 9, 'EVENT_TYPES':10}
def get_question_type(question):
try:
result = Question.... |
import mnist_loader
training_data, validation_data, test_data = mnist_loader.load_data_wrapper()
training_data = list(training_data)
# print(len(training_data))
# print(training_data[0][0].shape)
# x, y = training_data[0]
# print("Training data shape")
# print(x.shape)
# print(y.shape)
# Display the image
# from mat... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
import RPi.GPIO as GPIO
import time
# Create your views here.
def index(request):
my_dict = {'key': 'value'}
return render(req... |
from tkinter import *
import sys
import os
columns = int(sys.argv[1]) #x
rows = int(sys.argv[2]) #y
b = rows
print("line equation is y= ",-rows/columns, "x + ", b)
print("point({}:0)".format(columns))
print("point(0:{})".format(rows))
print("row = {}\ncolumn = {}".format(rows,columns))
root = Tk()
w = 0
h = 0
... |
# coding: utf-8
from collections.abc import MutableSequence, MutableMapping, MutableSet
from types import SimpleNamespace
import copy, itertools, uuid, pprint
import sys, io
import importlib
import threading
from contextlib import contextmanager
import dictdiffer
from tinysync.wrappers import *
from tinysync.persist... |
input = open("input", "r")
inputLines = input.readlines()
input.close()
inputNums = []
for line in inputLines:
inputNums.append(int(line.rstrip()))
inputNums.sort()
# targetJolts = inputNums[-1] + 3
oneDiffs = 0
threeDiffs = 0
inputNums.insert(0, 0) # insert 0 at beginning for charging input
for n in range... |
import psycopg2
class PostgresConnection:
def __init__(self, _host, _database, _user, _pass):
self.conn = psycopg2.connect(
host=_host,
database=_database,
user=_user,
password=_pass)
self.conn.set_client_encoding('UTF8')
self.cur = self.conn... |
__author__ = 'leebird'
import re
import codecs
import os
import random
import string
class TextProcessor(object):
# in text there may be {not_tag} <not_tag>
# may be a more strict pattern for bionex tags
pattern_bracket = re.compile(r'<[^<>]*?>')
pattern_brace = re.compile(r'\{[^{}]*?\}')
pattern_... |
"""
Write a code to take the user input
a name of the pair & display the pair formed.
For e.g. Pair of Bat is:
User Input: Ball
Output : So the Pair is Bat & Ball.
"""
print("Welcome!! Here I am Gonna Write the Name of a Pair of a Thing & you Have to Guess the Another Pair ")
user = input("Pair of Bat is ... |
from typing import Dict
from typing import List
from . import dependency
from . import test_job
from .. import docker
import logging
import time
class SingleContainerCLISuiteJob(test_job.TestJob):
def __init__(self, steps: List[test_job.CLITest], docker_image_under_test: str | dependency.Dependency, cmd_to_run_in_... |
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
prev = 0
hi = 0
ans = keysPressed[0]
for i, t in enumerate(releaseTimes):
if t-prev > hi:
hi = t-prev
ans = keysPressed[i]
elif t-prev == h... |
# encoding: utf-8
import numpy as np
import glob
import time
import cv2
import os
from torch.utils.data import Dataset
from cvtransforms import *
import torch
import glob
import re
import copy
import json
import random
import math
import editdistance
from torch.utils.data import Dataset, DataLoader
class MyDatas... |
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Band(models.Model):
name = models.CharField(max_length=100)
members = models.ManyToManyField( User, through='UserHasBand')
created_at = models.DateTimeField( default=datetime.now, blank=True )
updated_... |
__author__ = 'ash'
import numpy as np
from sets import Set
import sys
#import pulp
import Node
class Task:
def __init__(self,vm_dep_list,storage_priority,public_priority):
self.vm_dep_list = vm_dep_list
self.storage_priority = storage_priority
self.public_priority = public_priority
@... |
import sys
import math
from PIL import Image
if len(sys.argv) < 2:
print('Not enough arguments')
filename = sys.argv[1]
im = Image.open(filename)
pixelMap = im.load()
img = Image.new(im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
c1 = math.floor(pix... |
from django.apps import AppConfig
class KairosConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'kairos'
|
# ==============================================================================================================
# The following snippet demonstrates how to manipulate kaolin's camera.
# ==============================================================================================================
import torch
from kao... |
import textwrap
def wrap(string, max_width):
finalString = ""
for i in range(0, len(string), int(max_width)):
finalString += string[i:i+max_width] + '\n'
return finalString
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(resul... |
import numpy as np
import torch
from torch.utils.data.sampler import SubsetRandomSampler
from torchvision import datasets, transforms
def get_random_shift(scale=2, image_size=28):
pad_amount = image_size * (scale - 1)
crop_size = image_size + pad_amount
random_shift = transforms.Compose([
transfor... |
import os
from bllipparser import RerankingParser
from bllipparser.ModelFetcher import download_and_install_model
import logging
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
def importArticles(corpusFileName):
articles = []
... |
from Functions.MyViews import ItemView, ItemsView
from .. import models
from Functions.DynamicSer import DynamicSerializer
MyModel = models.Availablity
class ModelSer(DynamicSerializer):
class Meta:
model = MyModel
fields = '__all__'
class Views(ItemsView):
queryset = MyModel.objects.all()
... |
# -*- coding: utf-8 -*-
from gallery.utils import db_cli
class BaseResource(object):
def __init__(self, type):
self._db = db_cli.resource
self.type = type
self.tags = []
self.visit_log = []
def save(self):
self._save_disk()
data = self._to_document()
se... |
from django.db import models
class SUBJECT(models.Model):
"""
The patient class for MIMIC-III.
"ROW_ID","SUBJECT_ID","GENDER","DOB","DOD","DOD_HOSP","DOD_SSN","EXPIRE_FLAG"
we keeo all fields except row-IDs.
"""
# TODO: 1. Determine if the pre-pop-processing will:
# TODO: - integeri... |
text = input()
for i in range(len(text)):
if text[i] == ":":
if (i + 1) in range(len(text)) and not text[i+1] == " ":
print(f"{text[i]}{text[i+1]}")
|
import random
#H - represents Heads
#T - represents Tails
class Game:
def Simulate(self, probHeads):
reward = -250
twoBack = ""
oneBack = ""
for i in range(1,21):
score = random.random()
if score <= probHeads:
outcome = 'H'
els... |
import asyncio
import json
import csv
from os import pardir, pipe
from binance import AsyncClient
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException, BinanceOrderException
api_key = '8VLvEFhyBTmZOp8XZDLHhuRy0WpFHAlKzp9RLGRN5laRvPB4lmuuC3kDoeK9a14q'
api_secr... |
"""
You've got much data to manage and of course you use
zero-based and non-negative ID's to make each data item unique!
Therefore you need a method, which returns the smallest
unused ID for your next new data item...
Note: The given array of used IDs may be unsorted. For
test reasons there may be duplicate I... |
#!/usr/bin/python3
#
# Copyright (c) 2012 Mikkel Schubert <MikkelSch@gmail.com>
#
# 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
... |
# 单词翻转
def inplace(str):
str = list(str)
n = len(str)
i = 0
j = n-1
while i < j:
str[i],str[j] = str[j],str[i]
i +=1
j -=1
return "".join(str)
def inversion(str):
mid = []
# str =str[::-1]
str = inplace(str)
print(str)
str = str.split(" ")
for i i... |
from django.conf.urls.defaults import *
from piston.resource import Resource
from models import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
project_handler = Resource(AuthProjectHandler)
note_handler = Resource(AuthNoteHandler)
event_handler = Resource(A... |
from typing import Any, Dict, List
import pytest
import panel as pn
from panel.widgets import TextToSpeech, Utterance, Voice
TEXT = """By Aesop
There was a time, so the story goes, when all the animals lived together in harmony. The lion
didn’t chase the oxen, the wolf didn’t hunt the sheep, and owls didn’t swoop ... |
#!/usr/bin/env python3
# coding=utf-8
"""
线性判别分析(LDA):西瓜数据集
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
csv_file = 'watermelon.csv'
def model_training():
df = pd.read_csv(csv_file, encoding="utf-8")
m, n = df.shape
df0, df1 = df[df.Label == 0], df[df.Label == 1]
m0, m1... |
from __future__ import unicode_literals, print_function
import pytest
from spacy.attrs import LOWER
from spacy.matcher import Matcher
@pytest.mark.models
def test_simple_types(EN):
tokens = EN(u'Mr. Best flew to New York on Saturday morning.')
ents = list(tokens.ents)
assert ents[0].start == 1
assert... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pop.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import mysql.connector as connector
import pandas as pd
mydb = connector.connect(ho... |
# Copyright (c) 2015-2019 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from django.template import defaultfilters as filters
from django.urls import reverse # noqa
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import tables
from starlingx_dashboard.dashboards.admi... |
import copy
import hyperopt
import numpy as np
import xgboost as xgb
class CVTS(object):
"""
Time series cross validator.
Define time series folds in terms of dates.
Example with monthly data, where we care about a one- to three-month forecast
>>> import pandas as pd
>>> date_index = pd.date... |
import os
from airflow.models import DagBag
#################################
# DAG BAG Configuration path
#################################
dags_dirs = [
"~/parallel",
"~/sequential",
"~/templates",
"~/triggers",
"~/sensors"
]
#################################
# Iteration loop
################... |
from flask.views import MethodView
from app.server.helpers import *
from app.server.helpers.auth import login_required
from app.server.api.models import Task, TaskSchema, TournamentsToObject, Tournament
from flask import request
class GetAllTasksForTournament(MethodView):
@login_required
def get(self):
... |
#!/usr/bin/env python
import sys
from subprocess import call
for l in sys.stdin:
l = l[:-1]
print './youtube-dl --proxy 127.0.0.1:8087 ' + 'https://www.youtube.com/watch?{0}&list=PL782D0D8FA14D3055 > log/{1} 2>&1 &'.format(l, l)
|
"""
Created at 7:56 PM on 02 Jul 2014
Project: match
Subprogram: galcomb
Author: Andrew Crooks
Affiliation: Graduate Student @ UC Riverside
"""
'''
Combines science images with galmodel*.fits images and outputs galcomb*.fits for processing with sextractor.
Also outputs an image with just the simulated galaxies that ... |
##first generate a list with all terms
##sort the list. then remove duplicates.
def combo():
list=[]
temp=0
for a in range(2,101):
for b in range(2,101):
temp=0
temp=a**b
list.append(temp)
else:
return list
def sortdupe(list):
list.sort()
newlist=[]
for i in list:
if i not in newlist:
newli... |
#!/usr/bin/python
import requests
import ConfigParser
from getpass import getpass
class Setup:
URLS = {
"1": "https://www.fireservicerota.co.uk",
"2": "https://www.brandweerrooster.nl"
}
CONFIG_FILE = '.local_settings.ini'
domain = None
api_key = None
def __init__(self):
pass
def get_sett... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from __future__ import division, with_statement
'''
Copyright 2010, 陈同 (chentong_biology@163.com).
Please see the license file for legal information.
===========================================================
'''
__author__ = 'chentong & ct586[9]'
__author_email__ = 'ch... |
#!/usr/bin/python3
import unittest
from python.common.baseunittest import BaseUnitTest
from python.eapi.methods.loans.loan import Loan
class TestLoans(BaseUnitTest):
"""Runs Loan test scenarios."""
@BaseUnitTest.log_try_except
def test_01_get_multi(self):
"""
1. Get multiple.
"""
... |
'''
使用递归的几种情况
(1)指数函数
(2)优化的指数函数
(3)判断回文字符串
(4)二分查找
(5)选择子集和
'''
import time
# 使用递归的几种情况:
# (1)指数函数
def power(n, k): # 计算n的k次方
# 边界条件 当k减少到0的时候
if k == 0:
return 1
else:
return n * power(n, k - 1)
# (2)优化的指数函数
def power_optimize(n, k):
if k == 0:
return 1
else:
... |
from django.urls import path
from . import views as uv
urlpatterns = [
path('', uv.home, name='homepage'),
path('about/', uv.about, name='about'),
path('services/', uv.services, name='services'),
path('contact/', uv.contact, name='contact'),
path('profile/', uv.profile, name='profile'),
] |
month = input("Enter the month:")
day = input("Enter the day of the month:")
if month in ["January", "February"]:
print("It's winter!")
elif month in ["April", "May"]:
print("It's Spring!")
elif month in ["July", "August"]:
print("It's Summer!")
elif month in ["October", "November"]:
print("It's Fall!")
if mon... |
meat = {'beef': 199, 'pork': 99, 'chiken': 49}
for name, price in meat.items():
print(name, 'is', price, 'yen') |
from graphql import (
GraphQLObjectType
)
from .listen_to_messages import ListenToMessagesSubscription
RootSubscriptionType = GraphQLObjectType(
"Subscriptions",
{
'listenToMessages': ListenToMessagesSubscription
},
)
__all__ = ['RootSubscriptionType']
|
"""Główny moduł programu."""
import sys
import pygame
from pygame.sprite import Group
from settings import Settings
import functions as fct
from UI_buttons import (ColorIndicator, EraserButton,
ReferenceGridButton, ClearButton, ButtonsGroup,
SaveButton, LoadButton, Rect... |
from .asm import ASM
from .attachment import Attachment
from .bcc_settings import BCCSettings
from .bypass_list_management import BypassListManagement
from .category import Category
from .click_tracking import ClickTracking
from .content import Content
from .custom_arg import CustomArg
from .email import Email
from .ex... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from datascience import *
import matplotlib
path_data = '../../assets/data/'
matplotlib.use('Agg')
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
import numpy as np
np.set_printoptions(threshold=... |
'''
Bryan Coleman
BJC18BV
membership question for L = {w E {0,1}* : w is a binary palendrome}
'''
import sys
def solution(tape):
accept = True
reject = False
state = 'q0'
current = 0
head = tape[current]
while True:
if state == 'q0':
if head == ' ':
#emp... |
from rest_framework import generics
from rest_framework.exceptions import ParseError
from inventoryProject.permissions import IsSuperUserOrStaffReadOnly, IsSuperUser, IsStaffUser
from items.models.asset_custom_fields import AssetField, IntAssetField, FloatAssetField, ShortTextAssetField, \
LongTextAssetField
... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Table 1. Review
class Review(db.Model):
__tablename__ = "reviews"
id = db.Column( db.Integer, primary_key=True )
date = db.Column( db.DateTime, nullable=False )
condition = db.Column( db.String, nullable=False )
animals = db.Column( db.Bo... |
from django.db import models
class GlobalSettings(models.Model):
current_session = models.PositiveIntegerField()
penalty_points = models.PositiveIntegerField() # Indicates how much points will be the penalty for editing each time.
bonus_points = models.PositiveIntegerField() # Maximum bonus points for exac... |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
mnist = keras.datasets.mnist
(x_train_orig, y_train), (x_test_orig, y_test) = mnist.load_data()
print("mnist dataset: train=%s test=%s" % (x_train_orig.shape, x_test_orig.shape))
# print("x_tes... |
from __future__ import (absolute_import, division, print_function, unicode_literals)
import pickle
import matplotlib.pyplot as plt
import numpy as np
import pydot
import tensorflow as tf
import tqdm
from keras.utils import vis_utils
from tensorflow.keras import datasets, layers, models
vis_utils.pydot = pydot
def ... |
markup = {
"application": "App",
"imports": [],
"startup": "test_app.views.main"
}
|
# Generated by Django 3.0.8 on 2020-07-06 18:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zemax', '0016_house_image3'),
]
operations = [
migrations.AlterField(
model_name='house',
name='image2',
... |
from rest_framework import permissions
from rest_framework.viewsets import ModelViewSet
from src.profiles.models import MyUser
from src.profiles.serializers import GetUserSerializer, GetUserPublicSerializer
class PublicUserView(ModelViewSet):
""" Public user information"""
queryset = MyUser.objects.all()
... |
import numpy as np
import pickle
from RealSenseCamera import RealSenseCamera
k = RealSenseCamera(serial_no='834412071881')
k.start()
frames = []
try:
while True:
image_dict = k.get_feed()[1]
color_image = image_dict['color_image']
depth_image = image_dict['depth_image']
frames.app... |
import airflow_home.credential_vars
import psycopg2
connection_options = ('redshift', 'zeus')
class NotAValidDatabase(Exception):
pass
def db_conn(source):
global cursor
global conn
if source == 'redshift':
conn = psycopg2.connect(airflow_home.credential_vars.redshift_conn_string)
... |
import sys
_module = sys.modules[__name__]
del sys
conf = _module
adult_census = _module
adult_census_attention_mlp = _module
adult_census_bayesian_tabmlp = _module
adult_census_cont_den_full_example = _module
adult_census_cont_den_run_all_models = _module
adult_census_enc_dec_full_example = _module
adult_census_enc_de... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/6/2 9:06
@Author : QDY
@FileName: 面试题64. 求1+2+…+n.py
求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
"""
class Solution:
def __init__(self):
self.res = 0
... |
from ew.static import cfg as ewcfg
from . import prankcmds
cmd_map = {
# Swilldermuk -- Please make swilldermuk specific cmd/util files on reimplementation
ewcfg.cmd_gambit: prankcmds.gambit,
ewcfg.cmd_credence: prankcmds.credence, #debug
ewcfg.cmd_get_credence: prankcmds.get_credence, #debug
ewcfg... |
#!/usr/bin/env python
# coding: utf-8
import os
import re
class ReadData:
def __init__(self, path):
self.path = path
# For correct sorting.
def atoi(self,text):
return int(text) if text.isdigit() else text
def natural_keys(self,text):
'''
alist.sort(key=natural_keys) ... |
from typing import Dict, Optional, Tuple, Union
import ConfigSpace as CS
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter, UniformIntegerHyperparameter
import numpy as np
from torch import nn
from autoPyTorch.datasets.base_dataset impor... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
from django.template.defaultfilters import slugify as default_slugify
from unidecode import unidecode
from taggit.models imp... |
# # def decor1(func):
# # def inner():
# # x = func()
# # return x*x
# # return inner
# # def decor(func):
# # def inner():
# # x = func()
# # return 2 * x
# # return inner
# # @decor1
# # @deco
# r# def num():
# # return 10
# def decor(func):
# def inner(a,b):
# if a < b:
# a, b = b, a
# retur... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='{{ cookiecutter.description }}',
author='{{ cookiecutter.author_name }}',
author_email='{{ cookiecutter.author_email }}',
license='{% if cookiecutter.open_source_license ==... |
"""
This file contains global variables used within the package.
SUPPORTED_PLANS - the plan types which have been implemented, of type tuple.
SUPPORTED_MARKETS - the markets for each sport that are supported
A dictionary with supported sports as keys and their markets
as a list of values.
"""
SUPPORTED_PLAN... |
"""
Python Interface to UpCloud's API
"""
__version__ = "0.0.1"
__author__ = "Elias Nygren"
__author_email__ = "elias.nygren@outlook.com"
__license__ = "See: http://creativecommons.org/licenses/by-nd/3.0/ "
__copyright__ = "Copyright (c) 2015 Elias Nygren"
from .server import Server
from .storage import Storage
from... |
from django.views.generic.base import TemplateView
from django.views.generic import ListView
from accounts.forms import SignupForm
from django.views.generic.edit import CreateView
#from django.conf.urls import reverse_lazy
from django.urls import reverse_lazy # 윗줄이 바뀐지몰라 구글 검색후 대체
from django.contrib.aut... |
# Copyright 2019 The TensorFlow 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 applica... |
'''names = ('Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',)
i = 2
while i < 12:
print(names)
i+=2
'''
a = int(input("введите число")
while a <= 100:
if (a > 100) and (a < 1000):
print("это число трёхзначное")
else:
... |
print('''
This is a very long string
It continues here.
And it's not over yet.
"Hello,world!"
Still here.''')
x = 1 + 2 \
+ 3 + 4
print(x)
print("abcd\n1234")
print("C:\\ProgramFile\\python")
print(r"C:\ProgramFile\python""\\")
# Python3中所有字符串都是Unicode字符串
print(u"Unicode字符串")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.