text stringlengths 38 1.54M |
|---|
seasons = ['spring','summer','fall','winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons,start=1)))
print(list(enumerate(seasons,start=3)))
for i,element in enumerate(seasons):
print(i,element)
list1=[1,2,3,4,5,6]
list2=list1[::-1]
list3=[i**i for i in list1 if not i%2]
print(list1,list2,list3)... |
#coding=utf-8
import caffe
import numpy as np
root='./' #根目录
deploy=root + 'mnist/deploy.prototxt' #deploy文件
caffe_model=root + 'mnist/lenet_iter_9380.caffemodel' #训练好的 caffemodel
net = caffe.Net(deploy,caffe_model,caffe.TEST) #加载model和network
[(k,v[0].data.shape) for k,v in net.params.items()] #查看各层参数规模
w1=... |
import sqlite3
def putData(records):
# DB 연결, SQL 구문 호출 위해 객체 생성
con = sqlite3.connect('soccer.db')
cur = con.cursor()
sql = 'insert into soccer values (?,?,?);'
try :
# 웹 페이지 data 들을 sql 형태에 맞게 넣기
for record in records :
cur.execute(sql,record)
except :
pass
# 작업한 내용을 실제로 DB에 반영
con.commit()
# D... |
# Copyright 2023 Canonical Ltd.
# Licensed under the Apache V2, see LICENCE file for details.
"""
This example:
1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
itself active
3. Destroys the unit and application
"""
from juju import jasyncio
from juju.m... |
"""
4-7. Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to
print the numbers in your list.
"""
if __name__ == '__main__':
threes = list(range(3, 31, 3))
for x in threes: print(x) |
''' Helper Display Functions
helper functions for optical model display and testing, framework matplotlib 3d
functions:
x,y,z = plot_3d_ellipsoid(C, r, e, rev, theta = 0., full = False)
x,y,z = plot_3d_line(o, v, xl)
img = get_retinal_img(paths, r, d)
'''
''' Imports '''
# nd... |
# coding=utf-8
'''
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,
但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
'''
class Solution:
def IsPopOrder(self, pushV, popV):
stack = [] # 辅助栈
# 遍历输入栈,比较输入栈栈顶元素和弹出栈的首元素,相等则输入栈弹出和弹出栈弹出首元素,若辅... |
from collections import defaultdict
import fileops
import sys
class Tools():
""" Class to store and manage all fiber related tools
need to add methods to edit and query tools
"""
def __init__(self):
pass
def add_tool(self,tooltype=None):
"""adds new tools to database"... |
import yaml
import os
import logging
import json
from collections import OrderedDict
class toscaToHOT:
test_mode = True #just for test, cmd choose from apache_cmd and ftp_cmd
root_logIn = {'ubuntu': "#!/bin/sh\ncp -f /home/ubuntu/.ssh/authorized_keys /root/.ssh/\npasswd root<<EOF\npassword\npassword\nEOF\n"}... |
# Generated by Django 3.1.1 on 2021-02-06 20:44
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
... |
"""empty message
Revision ID: 25bd2e34ee4b
Revises: ca4aceeab91e
Create Date: 2020-05-21 20:30:23.210030
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '25bd2e34ee4b'
down_revision = 'ca4aceeab91e'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# Ваша цель добраться до правой части карты живым. Ваши союзники помогут вам.
# You don't need to fight the ogres, just move! Your allies will protect you.
# http://codecombat.com/play/level/signs-and-portents
hero.moveRight()
hero.moveRight()
hero.moveUp()
hero.moveRight()
hero.moveRight()
hero.moveRight()
hero.moveDo... |
from starter2 import *
import xtra_energy
reload(xtra_energy)
import three_loopers_u500 as TL
#ds=TL.loops['u501'].load(111)
ds = yt.load('/data/cb1/Projects/P19_CoreSimulations/new_sims/u26_sphere_amr/DD0001/data0001')
YT_divv = ('gas','divv')
import xtra_operators as xo
def derp(field,data):
#gi = xtra_energy.g... |
'''
Created on 2017/09/01
@author: samejima
'''
import numpy as np
import sequences
def quantize(xyz, pixel_x = 0.0005, pixel_y = 0.0005):
'''
This calculates a normal map, nx, ny, nx over all pixels,
from xyz data that has continuous values of x, y, z, nx, ny, nz
Parameters for quantizatio... |
#!/usr/bin/env python
# @Author : pengyun
import redis
from flask import Flask
from pymongo import MongoClient
from config import config, redis_host, redis_port, mongo_host, mongo_port
from server.auth import login_manager
from .extensions import (cache, bootstrap, mail, moment, cors,
oauth,... |
import codecs
def hex_to_b64(hex):
b64 = codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode()
return b64
hex = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
b64 = hex_to_b64(hex)
print(b64)
|
import sys
import spacy
def main():
params = "<corpus_text> <output_file>"
if len(sys.argv)-1 < len(params.split(" ")):
print(len(sys.argv))
print(len(params.split(" ")))
print("Need " + str(len(params.split(" "))-(len(sys.argv)-1)) + " more args")
print("all params: " + params... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import statistics as st
import datetime as dt
pd.set_option('max_columns', 20)
data = pd.read_csv('all_seasons.csv')
#we are going to set the season as an index
good_data = data.set_index('season')
good_data = good_data.drop(... |
#! /usr/bin/python
"""
File name: tpColorChanger.py
Author: Tomas Poveda
Description: Tool to change color of curve controls quickly
"""
try:
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from shiboken2 import wrapInstance
except:
from PySide.... |
import cv2
import numpy as np
# def square_image(img, size=(300,300), color = (190,208,183)):
# w = size[0]
# h = size[1]
# dst = Image.new('RGB', (w,h), color)
# img = Image.open(img)
# img.thumbnail((w,h))
# if img.width < w:
# start_x = int((w - img.width)/2)
# start_y =... |
import speech_recognition as sr
from gtts import gTTS
from translation import evaluate
from SentimentAnalysis import predict
import os
from time import sleep
import pyglet
from sarcasm import predict_text
import playsound
import numpy as np
def translate():
r = sr.Recognizer()
with sr.Microphone() as source:
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Pizzahut Takeaway Order',
'version': '1.0',
'category': 'POS',
'author': 'Hashmicro/MP Technolabs / Vatsal',
'website': 'http://www.hashmicro.com/',
'description': """
================... |
import math
#Thanks to Matt, he helped us solve this algorithim out. We love you <3
def convexHull(points):
n = len(points)
if (n < 3):
return("wtf")
lUpper = [points[0], points[1]]
for i in range(2, len(points)):
lUpper.append(points[i])
while(len(lUpper) > 2 and turningLeft(lU... |
class Desc:
var = 0
def __set__(self, obj, val):
raise ValueError
def __get__(self, obj, cls):
if Desc.var == 0:
Desc.var = obj
return None
else:
return Desc.var
def __delete__(self,obj):
if Desc.var == obj:
Desc.var = 0
class Sem:
lock = Desc()
def __init__(self, name):
self.name = name
d... |
# python 3.6.4
# encoding: utf-8
"""
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
提示:
每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add... |
import sys
from PyQt5.QtWidgets import *
class MyWindow(QWidget):
def __init__(self):
super(MyWindow, self).__init__()
self.setWindowTitle('嵌套布局示例')
# 全局布局
wlayout = QHBoxLayout()
hlayout = QHBoxLayout()
vlayout = QVBoxLayout()
glayout = QGridLayout()
formlayout = QFormLayout()
hlayout.addWidget... |
"""Compiles/decompiles SVG table.
https://docs.microsoft.com/en-us/typography/opentype/spec/svg
The XML format is:
.. code-block:: xml
<SVG>
<svgDoc endGlyphID="1" startGlyphID="1">
<![CDATA[ <complete SVG doc> ]]
</svgDoc>
...
<svgDoc endGlyphID="n" startGlyphID="m">
<![CDATA[ <complete SVG doc> ]]
... |
from weatherapp.core.providers.accuweather import AccuWeatherProvider
from weatherapp.core.providers.rp5 import RP5Provider |
import json
from contextlib import contextmanager
from datetime import datetime, timezone
from website_monitor.writer.handler import parse_message, save_to_db
from website_monitor.status import Status
MESSAGE = {
'url': 'http://www.ya.ru',
'timestamp': '2021-02-10T18:04:28.023922+00:00',
'status_code': 2... |
alpha = list('abcdefghijklmnopqrstuvwxyz')
# Basic way of iterating by using a count variable
count = 0
for letter in alpha:
print('{}: {}'.format(count, letter))
count += 1
# Using 'enumerate()' it iterate
for index, letter in enumerate(alpha):
print('{}: {}'.format(index, letter))
# Unpacking a tuple ... |
"""Here I import webbrowser.py file in order to open the URL
to the youtube trailer for the movies in the show_trailer function.
This was something that I did for my own knowledge and was not
required for the project.
"""
import webbrowser
"""Here I create the movies class which inherits from the object class.
The __i... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Dict, Optional, Union
from pytext.common.constants import Stage
from pytext.config import doc_classification as DocClassification
from pytext.config.field_config import WordLabelConfig
from pytext.data.bert... |
"""Demonstrate the creation of a wxPython GridBagSizer."""
import wx
class MainFrame(wx.Frame):
"""Create and show the frame for the application."""
def __init__(self, *args, **kwargs):
"""Initialise the MainFrame class."""
super(MainFrame, self).__init__(*args, **kwargs)
panel = Main... |
#!/usr/bin/env python
# encoding: utf-8
import json
import os
import pipes
import shlex
import sys
import textwrap
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from talus_client.cmds import TalusCmd, ENABLED_COMMANDS
import readline
import rlcompleter
if 'libedit' in readline.__doc__:
readlin... |
import numpy as np
from CL_1l import System
import os
import pickle
def exists_folder(f_name):
return os.path.isdir(f_name)
def set_folders(folder, n_test):
path = os.path.join(folder,str(n_test))
if not exists_folder(folder): os.mkdir(folder)
if not exists_folder(path): os.mkdir(path)
return pat... |
import string
def punctuation(string1, string2):
print("I'm in the function")
print(string1, string2, "there")
for i in string.punctuation:
if i in string1:
string1 = string1.replace(" ", "")
string1 = string1.replace(i, "")
print(string1)
elif i in strin... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
from pdb import set_trace
import numpy as np
from copy import deepcopy
from time import sleep
import pylab as plt
import math
import itertools
from draw_env import *
from pomdp_client import *
GLOBAL_TIME = 0
class AgentPOMDP(ClientPOMDP)... |
import os
import random
import shutil
from PIL import Image
from PIL import ImageFile
# error--image file is truncated
ImageFile.LOAD_TRUNCATED_IMAGES = True
map_file = 'dishname_cut.txt'
data_dir = '../data/all_data_cut/'
train_data_dir = '../data/train_data/'
#val_data_dir = '../data/val_data/'
test_data_dir = '../... |
#!/usr/bin/python
import sys, tarfile, urllib, string, os, time
# From username, grab all game records and unarchive them
# http://www.gokgs.com/gameArchives.jsp?user=Heretix&oldAccounts=y
# http://www.gokgs.com/servlet/archives/en_US/Heretix-all-2008-12.tar.gz
delay... |
def threshold_revert_long_bogey(df, target, fwd_pred, prof_thresh, bogey_name='bogey'):
fwd_bars = int(fwd_pred / BARSEC)
tmp = pd.DataFrame({'idx': df.index, 'curr': df[target].values})
tmp.set_index('idx', drop=True, inplace=True)
for i in range(fwd_bars):
tmp[i] = tmp.curr.pct_change(i).... |
n, k = map(int, input().split())
heights = map(int, input().split())
print(len([1 for height in heights if height >= k]))
|
from typing import Dict, List
from fastapi import BackgroundTasks
import numpy as np
import logging
import os
from src.middleware.profiler import do_cprofile
from src.jobs import store_data_job
from src.constants import PLATFORM_ENUM
from src.configurations import PlatformConfigurations
from src.app.ml.active_predicto... |
"""
Django settings for root project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths ins... |
import logging.config
import sys
import tornado.ioloop
import tornado.web
import settings
from poll_client import views
from consumer.poll_consumer import PollUpdatesConsumer
def make_app():
return tornado.web.Application([
(r"/", views.MainHandler),
(r"/subscribe", views.SubscribePollChangesHa... |
"""
Implementation of Compute Nodes.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
class Node(object):
"""Abstract base class for commpute nodes."""
def __init__(self, wallet):
"""Initializes the compute node
Parameters
----------
... |
import os
import sagemaker
from sagemaker.tensorflow import TensorFlow
sagemaker_session = sagemaker.Session()
role = "arn:aws:iam::335727716642:role/service-role/AmazonSageMaker-ExecutionRole-20200205T232539"
local_instance_type = "local"
remote_instance_type = "ml.t3.large"
source_dir = os.getcwd()
local_data_dir ... |
import zepben.evolve as cim
import asyncio
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
ns = cim.NetworkService()
pt = cim.PowerTransformer()
pte1 = cim.PowerTransformerEnd(power_transformer=pt)
pt.add_end(pte1)
pte2 = cim.PowerTransformerEnd(power_trans... |
#BOJ11659 구간 합 구하기 4 20210221
import sys
input = sys.stdin.readline
def main():
n, m = map(int, input().rstrip().split())
li = list(map(int, input().rstrip().split()))
sumI =[0]
sum_ = 0
for v in li:
sum_ += v
sumI.append(sum_)
for _ in range(m):
a,b = map(int, input().r... |
import sqlite3
import sys
from time import time
import re
import math
import itertools
DATA_LIMIT = 5000
def parse_time_to_min(h, m):
return int(h) * 60 + int(m)
class Row(dict):
def __init__(self, *E, **F):
dict.__init__(self, *E, **F)
def __getattr__(self, name):
return self[name]
def ... |
import sys
import getopt
import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
import librosa
import pdb
# seach ahead and behind current frame estimate for the next closest frame
searchAhead = 5
searchBehind = 1
searchWidth = searchBehind + 1 + searchAhead
testSequenceLength = 200
# fake [searchWi... |
DATABASE_NAME = "postgres"
DATABASE_USERNAME = "postgres"
DATABASE_PASSWORD = "postgres"
DATABASE_HOST = "localhost"
|
from mysite.iclock.models import *
from django.template import loader, Context, RequestContext, Library, Template, Context, TemplateDoesNotExist
from django.http import QueryDict, HttpResponse, HttpResponseRedirect, HttpResponseNotModified, HttpResponseNotFound
from django.shortcuts import render_to_response
from djang... |
# -*- coding: utf-8 -*-
# @Time : 2019/11/05
# @Author : WKJ
# @Description :
import urllib.request
import json
import time
from collections import OrderedDict
def getData(Authorization):
#时序库查询特征数据
url = 'http://10.6.9.39:15016/api/v1/data/namespace/thermalpower/timeseries/features/types/Infer... |
class Person():
def __init__ (self, name):
self.name = name
def greeting(self):
return f'{self.name}: Hi, my name is {self.name}!'
class Student(Person):
def learn(self):
return f'{self.name}: I get it!'
class Instructor(Person):
def teach(self):
return f'{self.name}... |
from requests.exceptions import RequestException
from utils import fetch
def check_proxy(p):
try:
res = fetch('http://weixin.sogou.com/weixin?query=python&type=2&page=1', proxy=p['address'])
if len(res.text) < 10000:
p.delete()
except RequestException:
p.delete()
|
import json
with open("person_info.json") as f:
reader = csv.reader(f)
data = [r for r in reader]
data.pop(0)
a = int("1")
#b = int("3sadsa")
print a
|
class Person:
def __init__(self,name):
self.name=name
def talk(self):
print(f"Hi I am {self.name}")
Name=Person("swathi")
Name.talk()
Name2=Person("rohit")
Name2.talk() |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Solution: Mini-batch stocahstic gradient decent \n",
"\n",
"- June 8, 2020\n",
"\n",
"- I filled up lines for the function MSEStep(X, y, W, b, learn_rate = 0.005)"
]
},
{
"cell_type": "code",
"executio... |
from django.apps import AppConfig
class AdbizproductengineConfig(AppConfig):
name = 'adbizProductEngine'
|
from django.urls import path,include
from accounts import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('accounts/', views.EmployeeList.as_view()),
path('accounts/<int:pk>/', views.EmployeeDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
|
#!/usr/bin/python
import sys
import logging
import operator
import json
from functools import reduce
from lambdas import connectionManager
from lambdas import config
from models.responseInfoModel import ResponseInfo
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def updateFarmerCropDetails(... |
import os
import shutil
# parameters setting
base_path = os.getcwd()
# 三部分的sum必须等于1,否则会报错误
train_ratio = 0.8
validation_ratio = 0.2
test_ratio = 0
folder_name = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
if train_ratio+test_ratio+validation_ratio != 1.0:
raise Exception(
"train_ratio + test_ratio ... |
"""
pulse 2 a simulation without accurate timing
"""
import pyvisa as visa
from pyinstrument import PSupply
# instrument address
PSN5744USB = "USB0::2391::38151::US15J0384P::0::INSTR"
PSN5744Eth = "TCPIP0::169.254.57.0::inst0::INSTR"
PSTektronix = "USB0::1689::913::081001126668003045::0::INSTR"
rm = visa.ResourceMa... |
"""
Carlos Paredes Márquez.
Libreria de particulas. xd
28/10/2020.
"""
from particula import Particula
import json
class Libreria:
def __init__(self):
self.__particulas = []
def agregar_final(self, particula:Particula):
self.__particulas.append(particula)
def agregar_inicio(self, ... |
def find_twos_and_eights(n):
## Print list of all integers leading up to n:
# nl = []
# for i in range(n):
# nl.append(str(i))
# print(nl)
l = []
for i in range(0, n, 2):
l.append(str(i))
## Print list of all even numbers:
# print(l)
#
## Print list of all even nu... |
# -*- coding: utf-8 -*-
from _path import init_path; init_path()
import sys; sys.modules.pop('threading', None)
from gevent import monkey; monkey.patch_all()
import argparse
import gevent
import os
import logging
from settings import settings
from _path import HOME_DIR
# 分析参数
ARGS = argparse.ArgumentParser(descripti... |
'''
The Abundancy (A) of a number n is defined as:
(sum of divisors of n) / n
For example:
A(8) = (1 + 2 + 4 + 8) / 8 = 15/8
A(25) = (1 + 5 + 25) / 25 = 31/25
Friendly Pairs are pairs of numbers (m, n), such that their abundancies are equal: A(n) = A(m).
Write a function that returns "Friendly!" if the two given n... |
# Copyright 2019 Atalaya Tech, Inc.
# 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 writing, ... |
from __future__ import print_function
import os
import cv2
import numpy as np
from tensorflow.python.keras.models import load_model
from tensorflow.python.keras.preprocessing.image import img_to_array
dir_path = os.getcwd()
face_classifier = cv2.CascadeClassifier(dir_path + '/haarcascade_frontalface_default.xml')
... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras import backend as k
from tensorflow.keras import regularizers
import hyperparameters as hp
class SamplingLayer(layers.Layer):
def __init__(self, *args, **kwar... |
import dateparser
import datetime
from fastapi import FastAPI
from pymongo import MongoClient
from starlette.middleware.cors import CORSMiddleware
from scrutinizer import Variable
from typing import Optional
# developing locally
# app = FastAPI()
# running on UA VM
app = FastAPI(openapi_prefix="/api/v1")
client = M... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 28 14:25:24 2019
@author: Nick
"""
#Code taken from:
#https://stackoverflow.com/questions/19726663/how-to-save-the-pandas-dataframe-series-data-as-a-figure/39358752#39358752
#https://stackoverflow.com/questions/43564943/saving-matplotlib-plot-to-memory-and-pla... |
import torch
from objective.base import Objective
from utils import assert_true
class Logistic_Gradient(Objective):
def _validate_inputs(self, w, x, y):
assert_true(w.dim() == 2,
"Input w should be 2D")
assert_true(x.dim() == 2,
"Input datapoint should be 2... |
import sys
import re
from multiprocessing.connection import Listener
from kazoo.client import KazooClient
from kazoo.client import KazooState
from data_api import DataAPI
class DataApiListener():
def __init__(self, pipe_address, zoo_address):
# Requests pipe
self.listener = Listener(pipe_address)
# Kazoo cli... |
"""Common fixtures for testing."""
import pytest
from numpy import ma
from netCDF4 import Dataset
from argortqcpy.checks import CheckBase
from argortqcpy.profile import ProfileBase, Profile
class FakeProfile(ProfileBase):
"""A fake profile class created for testing."""
def __init__(self):
"""Initia... |
import bluetooth
bt_addr = "20:15:08:03:83:73"
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bt_addr, port))
while 1:
tosend = raw_input()
if tosend!='q':
sock.send(tosend)
else:
break;
sock.close()
|
from galactic_conquest_1_5.game.defaults.player_default import PlayerTemplate
class TurnManager:
def __init__(self, file):
self.current_player = 0
self.total_players = file.total_players_generated
self.order = self.determine_order(file)
def determine_order(self, file):
_players... |
import pandas as pd
import os,re
from text2listEN import *
from cal_tfidf import *
class caltfidf():
def __init__(self):
self.briefintro()
self.df = self.readdata()
self.dict_category_id = self.gendict_category_id(self.df)
self.dict_index_text = self.genindex_text(self.df)
def... |
# Copyright 2020 The Oppia 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 ... |
from find_element.start import driver,NoSuchElementException
def login():
try:
driver.find_element_by_xpath('//android.widget.EditText[@content-desc="请输入QQ号码或手机或邮箱"]').clear()
driver.find_element_by_xpath('//android.widget.EditText[@content-desc="请输入QQ号码或手机或邮箱"]').send_keys('273659024')
driver.f... |
N = int(input())
l = []
for i in range(N):
mountInfo = input().split()
mountInfo[1] = int(mountInfo[1])
l.append(mountInfo)
l.sort(key=lambda x: x[1], reverse=True)
l = l[:2]
print(l[1][0])
|
# July 1 : Now it can read the f125w.cat. For example:
# Oct 20 : revised
# Dec 03 : revised for frontier a2744. Compare two catalog.
# #a1423 nir 833 x y ra dec f225w f275w f336w f390w f435w f475w f606w f625w f775... |
#!/usr/bin/python3
def search_replace(my_list, search, replace):
my_list1 = my_list.copy()
x = lambda x:x+1
z = 0
for cnt in range(len(my_list1)):
if my_list1[z] == search:
my_list1[z] = replace
z = x(z)
return my_list1
|
import sys, getopt, os
sys.path.append(os.path.dirname(__file__) + '\\..')
from ECG import console
if __name__ == "__main__":
numclasses = 5
expsnum = 1
batchsize = 1
maxepoch = 1
patience = 4
timesteps = 1
#imbalanced
balanced = False
svmkernel = 'linear'
print('svm... |
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from .models import Credential,Feedback
def main(request):
template = loader.get_template('games/main.html')
return HttpResponse(template.render({}, request))
def contact(request):
if request.meth... |
from django.contrib import admin
from .models import Policy, Coverage, City, State, Vehicle
admin.site.register(Policy)
admin.site.register(Vehicle)
admin.site.register(Coverage)
admin.site.register(State)
admin.site.register(City)
|
t = int(input())
x = 1
while x <= t:
n = int(input())
arr = []
maxleft = 0
il = -1
maxright = 0
ir = -1
for i in range(n):
line = input().split("*")
arr.append([line[0], line[1]])
if len(arr[i][0]) > maxleft:
il = i
maxleft = len(arr[i][0])
... |
# -*- coding: utf-8 -*-
from collective.civicrm.config import PROJECTNAME
from collective.civicrm.config import SITE_KEY_RECORD
from collective.civicrm.config import URL_RECORD
from collective.civicrm.interfaces import ICiviCRMSettings
from collective.civicrm.testing import INTEGRATION_TESTING
from plone import api
fro... |
from django.db import models
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_candidate = models.BooleanField(default=False)
is_institute = models.BooleanField(default=False)
class Candidate(models.Model):
user = mode... |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import GridCells
from std_msgs.msg import String
from geometry_msgs.msg import Twist, Point, Pose, PoseStamped, PoseWithCovarianceStamped
from nav_msgs.msg import Odometry, OccupancyGrid, Path
from kobuki_msgs.msg import BumperEvent
import tf
import numpy
import mat... |
#!/usr/bin/env python
from datetime import datetime
import sys
import boto3
import json
client = boto3.client("config")
def lambda_handler():
pass
compliance_type ="COMPLIANT"
config_recorder_response = client.describe_configuration_recorder_status()
for config_recorder in config_recorder_response["Configurati... |
from backend.handler.contactor import contactor
from backend.handler.contactor import contactor_group |
import math
def solution(s):
total_list = []
for i in range(1, math.ceil(len(s) // 2) + 1):
cnt = 1
start_val = s[0:1 * i]
temp_text = ""
for j in range(1, math.ceil(len(s) / i)):
next_val = s[j * i:(j + 1) * i]
if start_val == next_val:
... |
#!/usr/bin/env python3
import rospy
import dynamic_reconfigure.client
def callback(config):
rospy.loginfo("Config set to {start_navigation}".format(**config))
if __name__ == "__main__":
rospy.init_node("dynamic_client")
client = dynamic_reconfigure.client.Client("dyn_param_server", timeout=30, conf... |
"""
Image's field.
"""
from wtforms import widgets, fields
class ImageInput(widgets.TextInput):
pass
class ImageField(fields.StringField):
"""
Image's field.
"""
def __init__(self, image_type="image", *args, **kwargs):
"""
Args:
image_type: (string) image's type, co... |
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.core.mail.message import EmailMessage
from DRFtutorial import settings
FROM_EMAIL = settings.EMAIL_HOST_USER
# @shared_task : celery로 따로 작업할 코드라고 선언하는 부분입니다.
@shared_task
def send_email():
subject = 'email test 3'
... |
#!/usr/bin/env python
"""Kernel for producing a run-input file from a set of input files using grompp.
"""
__author__ = "David Dotson <dotsdl@gmail.com>"
__license__ = "MIT"
from radical.ensemblemd.exceptions import NoKernelConfigurationError
from radical.ensemblemd.kernel_plugins.kernel_base import KernelBase... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import isfile, join
from os import listdir
import os
import pandas as pd
import sys
import re
from pathlib import Path
import inflect
assert sys.version_info >= (3, 6), "运行python版本必需高于3.6"
# determine if application is a script file or frozen exe
if getattr(... |
import requests
from django.conf import settings
from django.contrib.gis.geos import Point
from django.core.management.base import BaseCommand
from django.db import transaction
from munigeo.models import Municipality
from ...models import Harbor
class Command(BaseCommand):
@staticmethod
def _get_servicemap_u... |
import pandas as pd
import numpy as np
import os
data = [0]*15
all = 0
for i in range(1,31):
#print(i, end=': ')
#print(':')
filename = str(i) + '.csv'
df=pd.read_csv(filename,header=None,sep=',')
series1 = df[8]
series2 = df[9]
#print(series1)
#print(series2)
#print(series1[40])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.