text stringlengths 38 1.54M |
|---|
from pydantic import BaseModel
class Jobs(BaseModel):
job_id: str
job_title: str
company: str
job_post_date: str
job_requirement_career_level: str
company_size: str
company_industry: str
job_description: str
job_employment_type: str
job_function: str
|
from odoo import models, fields, api
from odoo import exceptions
from odoo.exceptions import ValidationError
import logging
_logger = logging.getLogger(__name__)
class crossoveredbudgetlines (models.Model):
_inherit = 'crossovered.budget.lines'
x_bp_code = fields.Char(related='general_budget_id.x... |
"""
Name: Phan Tấn Đạt
ID: 18127078
Email: 18127078@student.hcmus.edu.vn
AI lab01 Project
"""
from Breadth_first_search import Breadth_first_search
from Uniform_cost_search import Uniform_cost_search
from Greedy_best_first_search import Greedy_best_first_search
from A_star_graph_search import A_star_graph_searc... |
import pandas_datareader.data as pdr
import datetime as dt
import pandas as pd
import numpy as np
start_date = dt.date.today() - dt.timedelta(3650)
end_date = dt.date.today()
tickers = ['MSFT']
ohlcv = pdr.get_data_yahoo(tickers[0],start_date,end_date)
df = ohlcv.copy()
BollBnd(ohlcv,20).iloc[-200:,[6,7,8]].p... |
"""proj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
from django.shortcuts import render
# Create your views here.
from axf.models import Wheel, Nav, Mustbuy, Shop, Mainshow, Foodtypes, Goods
def home(request): # 首页
# 获取顶部轮播图数据
wheels = Wheel.objects.all()
# 获取导航栏数据
navs = Nav.objects.all()
# 获取每日必购数据
mustbuys = Mustbuy.objects.all()
... |
#regular expressions
import re
mystr = """Tata Limited
Dr. David Landsman, executive director
18, Grosvenor Place
London SW1X 7HSc
Phone: +44 (20) 7235 8281
Fax: +44 (20) 7235 8727
Email: tata@tata.co.uk
Website: www.europe.tata.com
Directions: View map
Tata Sons, North America
1700 North Moore St, Suit... |
# Generated by Django 3.0.4 on 2020-08-12 19:49
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),
('expenses', '0009_auto_20... |
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time
browser = webdriver.Chrome()
browser.maximize_window()
browser.implicitly_wait(5)
song = "highest in the room"
browser.get("https://genius.com") #opens ge... |
import torch
from cfg.config_general import cfg
import os
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def get_idx2word(word2idx):
#create ... |
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
CUDA = torch.cuda.is_available()
|
from datetime import datetime
from pathlib import WindowsPath, PosixPath
from colorama import Fore, Style
import pandas as pd
import time
import os
from .ModelClass import ModelClass
# import config.py variables
from .config import db, server, user, _table, column_index, _sample_date, _sample_time, _time_span, column... |
# Generated by Django 3.0.2 on 2020-01-09 09:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
... |
from django.shortcuts import render, redirect
from .models import User
from django.contrib import messages
import bcrypt
# Create your views here.
def index(request):
return render(request, "index.html")
# def validate_login(request):
# user = User.objects.get(email=request.POST['email']) # hm...¿Es realment... |
'''
Description
Archana is very fond of strings. She likes to solve many questions related to strings. She comes across a problem which she is unable to solve. Help her to solve. The problem is as follows:-Given is a string of length L. Her task is to find the longest string from the given string with characters arran... |
"""
座右铭:吃饱不饿,努力学习
@project:预科
@author:Mr.Huang
@file:类变量和实例变量.PY
@ide:PyCharm
@time:2018-07-30 15:47:33
"""
#类变量:只有类名才能调用的变量,类变量一般在函数体之外
#实例变量:
class Employee(object):
#声明一个类变量,记录员工总人数
total_Emplyee_number=0#类变量需要打点调用
def __init__(self,name,salary):
self.name=name
self.salary=salary
... |
# https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python
"""
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'.
The range includ... |
"""
* Exercise 2.7, Sutton.
* k = 10
"""
import numpy as np
from random import random as rand, randint as randrange
import argparse
import matplotlib.pyplot as plt
class KArmTestBed:
def __init__(self, num_simulations, time_steps, k):
self.num_simulations = num_simulations
self.time_steps = time_... |
#!/usr/bin/env python3
"""
Sort out the six best and six worst months with a Google stock's historical prices file
Assignment 3,INF1340 Fall 2014
"""
__author__ = 'Xiwen Zhou, Juntian Wang,Susan Sim'
__email__ = "xw.zhou@mail.utoronto.ca,justinjtwang@gmail.com,ses@drsusansim.org"
__copyright__ = "2014 Susan Sim"
__... |
"""Module that provides a data structure representing a quantum system.
Data Structures:
QSystem: Quantum System, preferred over QRegistry (can save a lot of space)
Functions:
superposition: join two registries into one by calculating tensor product.
"""
import numpy as np
from qsimov.structures.qstructure im... |
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
time.sleep(3)
#单元素定位
# driver.find_element_by_id("")
# driver.find_element_by_name("")
# driver.find_element_by_class_name("")
# driver.find_element_by_tag_name("")#标签名称
# driver.find_element_by_link_text()#链接标签... |
# coding=utf-8
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print "Я создаю декораторы! И я получил следующие аргументы:", decorator_arg1, decorator_arg2
def my_decorator(func):
print "(Ака декоратор)Я - декоратор. И ты всё же смог передать мне(декоратору) эти аргументы:", decorator_arg1, d... |
''' Version 1.000
Code provided by Daniel Jiwoong Im and Chris Dongjoo Kim
Permission is granted for anyone to copy, use, modify, or distribute this
program and accompanying programs and documents for any purpose, provided
this copyright notice is retained and prominently displayed, along with
a note saying that t... |
#!/usr/bin/env python
# RVA Makerfest RetroPi controller
# Laser target button
# Adam
import RPi.GPIO as GPIO, time, os
import random
from subprocess import Popen, PIPE
F_PIN = 14
G_PIN = 4
light_sensor_pin = 18
servo_pin = 12
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(servo_pin, GPIO.OUT)
GPIO.setu... |
import cv2 as cv
class Filtragem:
def __init__(self):
pass
@staticmethod
def linear(imagem, matrix=(1, 1)):
return cv.blur(imagem, matrix)
@staticmethod
def linearMediano(imagem, intensidade):
return cv.medianBlur(imagem, intensidade)
@staticmethod
def porMetodo... |
from watson_developer_cloud import SpeechToTextV1
class Speech_To_Text_Component:
def __init__(self,debug_mode=False):
self.debug_mode=debug_mode
f = open("key.txt", "r")
f1 = f.read().splitlines()
f.close()
self.speech_to_text = SpeechToTextV1(
iam_apikey=f[14],
... |
from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from .validators import custom_year_validator
class CustomUser(AbstractUser):
class Permission... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
#2裁切框為小圖片
import cv2
import os
from re import split
def pos():
txt_file = open(r'./contours.txt', 'r')
read = txt_file.readlines() #讀取內容
count = len(read) #讀取行數
# print(read, count)
pos = [[0]*8 for i in range(count)]
for i in range(count):
line = read[i]
line= line[5:-2]
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Module contains code to download data from TheLatin Libary.com
Example:
$ python3 latin_downloader.py
"""
import collections
import io
import os
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
from pybloomfilter import BloomFilte... |
#!/usr/bin/python
import argparse
import ast
import atexit
import getpass
import json
import os
import re
import requests
import shlex
import subprocess
import sys
import time
import uuid
from docker import Client
OVN_REMOTE = ""
OVN_BRIDGE = "br-int"
def call_popen(cmd):
child = subprocess.Popen(cmd, stdout=su... |
from functools import partial
from mslice.util.qt import QtWidgets
from mslice.util.qt.QtCore import Qt
import os.path as path
import matplotlib.colors as colors
from matplotlib.lines import Line2D
from mslice.models.colors import to_hex
from mslice.presenters.plot_options_presenter import SlicePlotOptionsPresenter
... |
# 수열 A에서 정수 X보다 작은 수 구하기
N, X = map(int, input().split()) # N은 A의 정수 개수
A = list(map(int, input().split()))
def less_than(A, X):
less_than = []
for i in A:
if X > i:
less_than.append(str(i))
return less_than
print(" ".join(less_than(A, X)))
|
from twisted.internet import reactor
class Client(object):
id = property(lambda self: self._id)
meta = property(lambda self: self._meta)
comet_server = property(lambda self: self._comet_server)
def __init__(self, comet_server, id, timeout_cb, meta=None):
self._comet_server = comet_server
... |
# -*- coding: utf-8 -*-
"""
test.t_controlbeast.test_CB
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the ControlBeast team, see AUTHORS.
:license: ISC, see LICENSE for details.
"""
from unittest import TestCase
from controlbeast import get_version
class TestCbBase(TestCase):
"""
... |
species(
label = '[CH2]C(CC)C([O])=O(873)',
structure = SMILES('[CH2]C(CC)C([O])=O'),
E0 = (-86.1147,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,200,800... |
from django.db import models
# Create your models here.
class myapp(models.Model):
''' Models for myapp '''
email = models.EmailField()
friend = models.ForeignKey("self", related_name='referral',\
null=True, blank=True)
ref_id = models.CharField(max_length = 120, default = 'ABC', unique = True)
ip_ad... |
from netmiko import ConnectHandler
import getpass
username = raw_input("Username: ")
password = getpass.getpass()
r1 = {
"device_type" : "cisco_ios",
"ip" : "10.10.10.1",
"username" : usename,
"password" : password
}
r2 = {
"device_type" : "cisco_ios",
"ip" : "10.10.10... |
import math
from drafter.utils import Rect
from drafter.layouts import Node, Row, Column
from drafter.nodes import Text, Canvas
from drafter.shapes import Shape, String, Pie, Pango, LineShape
from ..common.color import Color
from ..common.utils import fmt_num
from ..common.boiler import boil
def TrainingsFooter(**k... |
from django.shortcuts import render,redirect
from .models import SDiscussion,DComment
# Create your views here.
def discussionList(request):
all_discussion = SDiscussion.objects.filter()
return render(request, 'discussion/discussionList.html',{
'd' : all_discussion
})
def inDiscussion(request,that... |
from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Pet, Vaccine
from django.db import models
def home(request):
try:
allpets = Pet.objects.all()
except:
raise Http404('we could not load pets for you')
return render(request, 'home.html', {
... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import os
import unittest
from telemetry.core import util
from telemetry.internal.platform import linux_based_platfor... |
lst = [1, 15, 22, 0, 10, -1]
def bubble_sort(lst):
sort = lst[:]
for i in range(len(sort) - 1):
for j in range(len(sort) - 1 - i):
if sort[j] > sort[j + 1]:
sort[j], sort[j + 1] = sort[j + 1], sort[j]
return sort
print(bubble_sort(lst))
|
# -*- coding:UTF-8 -*-
__author__ = 'joy'
import sys
from common import one_vehicle_price_sum
reload(sys)
sys.setdefaultencoding('utf8')
#计算整车价格
#start_province指编号
#unloadWay装卸方式
#agingWay时效方式
#invoiceWay发票方式
def getOneVehicleLinePrice(start_province,start_city,start_district,arrive_province,arrive_city,arrive_distr... |
"""
URL: https://stepik.org/lesson/334150/step/10?unit=317559
convert CamelCaseString to python_snake_string
"""
# my solution:
def convert_to_python_case(text):
import re
words = re.findall('[A-Z][^A-Z]*', text)
return '_'.join([str(word.lower()) for word in words])
# alternative solution 1:
def convert_... |
# print(3+5)
# print("3+5")
# print(type(3.14))
# print(type(type(42)))
# print(type(3.1)== float)
friend= "Lee"
Friend= "Park"
pi= 3.14
answer= 20
print(friend, pi, answer)
print(Friend==friend)
# 변수 이름 만들기: 알아볼 수 있는 대표적인 이름으로, 주석으로 설명 달아주기.
|
# Function to print the desired
# Alphabet Z Pattern
def alphabetPattern(N):
# Declaring the values of Right,
# Left and Diagonal values
Top, Bottom, Diagonal = 1, 1, N - 1
# Loop for printing the first row
for index in range(N):
print(Top, end=' ')
Top += 1
print()
... |
import subprocess
from py_utils import config_utils
from grovepi import digitalRead, pinMode
class HardwareHandler:
'''
The HardwareHandler groups all interactions with the hardware that are not detected through the touchscreen (or clicks) and reads from the
connected sensors.
Attributes:
dis... |
import lxml.etree as ET
import xmltodict
import os
import parmap
import pathlib
import sys
def xml_check(xml_file):
if pathlib.Path(xml_file).is_file():
try:
xml = ET.parse(xml_file)
return xml
except ET.XMLSyntaxError:
try:
xml = ET.XML(bytes(by... |
#! /usr/bin/env python
"""Tools for transforming CSV records and lists of CSV records.
"""
try:
from itertools import izip
except ImportError:
# For Python 3 compatibility
izip = zip
def add_column(existing_rows, new_column):
"""Take an existing iterable of rows, and add a new column of data to it.
... |
"""
Created on Fri Nov 29 12:33:10 2017
@author: Yannic Jänike
"""
import numpy as np
import random
from numpy.random import choice
import time
import matplotlib.pyplot as plt
class antColony():
class ant():
def __init__(self,init_location,possible_locations,pheromone_map,alpha,beta,first_pass):
... |
class IncentivizeZero:
def __init__(self):
self.num_legal_actions = 10
self.num_possible_obs = 10
self.max_reward_per_action = 1
self.min_reward_per_action = -1
self.fnc = incentivize_zero
def incentivize_zero(T, play):
if len(play) == 0:
reward, obs = 0, 0
... |
#------------------------------------------------------------------------------
# Name: Distance to Cloud Generator
# Description: Generates the distance to cloud from cloud mask
#
# Author: Robert S. Spencer
#
# Created: 7/11/2016
# Python: 2.7
#----------------------------------------------------... |
##
# Copyright (c) 2007-2016 Apple Inc. 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 l... |
from django.db import models
from django.contrib.auth.models import User
from datetime import timedelta, datetime
class ClientProfile(models.Model):
"""
Model to store client profile .
address,company name, phone number as fields
"""
user = models.OneToOneField(User, related_name='profile')
a... |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.metrics i... |
from django.shortcuts import render
from cart import cart
from django.shortcuts import render_to_response
from django.template import RequestContext
from Bank.models import Category
def cart_view(request):
if request.method == "POST":
postdata = request.POST.copy()
if postdata['submit'] == 'Updat... |
#!/usr/bin/python
activate_this = '/var/www/project-catalog/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, "/var/www/project-catalog/")
from main import app as application
application.secret_key = 'p... |
from django.shortcuts import render
from projects.models import Project
def project_index(request):
projects = Project.objects.all()
context = {
'projects': projects
}
return render(request, 'project_index.html', context)
def project_technologies(request, technology):
projects = Project.ob... |
# Author:jxy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# df = pd.read_excel(r"C:\Users\admin\Desktop\test.xlsx", sheet_name="目录")
# df = pd.read_csv(r"C:\Users\admin\Desktop\test1.csv", sep="@#", engine='python', encoding='utf-8')
df = pd.read_csv(r"C:\Users\admin\Desktop\test2.csv", sep="... |
from .finder import base_form
from .finder import odmiany_synonimow
class Question:
"""Potwierdza presupozycje pytan:
1) Kto zabił X w Y?
2) Kiedy zginal X?
3) Gdzie zginal X?
4) Jak zginal X?
"""
def __init__(self, zdanie = ""):
self.zdanie = zdanie.replace("?"... |
from tree_node_lib import *
class Solution:
def countNodes(self, root: TreeNode) -> int:
level = 0
cur = root
l = cur
r = cur
while 1:
l = l.left
r = r.right
if l and r :
level += 1
continue
elif... |
import os
import torch
from util import dataset, transform
import torch.multiprocessing as mp
import torch.distributed as dist
def main_process():
""" """
return args['rank'] % 8 == 0
def train(train_loader):
""" """
print(args)
if main_process():
print('Main process runs in ', args)
for i, (input, targe... |
import sqlite3
import sys
from wordcloud import WordCloud, STOPWORDS
import collections
import datetime
import matplotlib.pyplot as plt
from time import strftime
from sklearn.cluster import KMeans
import pandas as pd
# Code written for project
def analyze_data(df_messages, verbose, sample_size):
# Builds dictiona... |
def addFive(x):
return x + 1
numbers = [1,2,3,4,5]
mappedList = list(map(addFive, numbers))
print("The mapped list are , "+str(mappedList))
list2 = list(map((lambda x: x+2), numbers))
print(list2) |
import numpy as np
import pandas as pd
'''
Function to fill nan for the teams' head to head home team win rate
'''
def fill_nan_head_2_head_home_team_win_rate(match_df, full_df):
value = match_df['HEAD_2_HEAD_HOME_TEAM_WINS']
if not np.isnan(value):
return value
else:
# Find average
all_h... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 13:49:59 2020
@author: Hp
"""
import pandas as pd
details = pd.Series([[{"Name":"Suresh","C.NO":"hjyt64882991z","Address":"H.No:12,2nd cross,RC road,Hassan","Ph no":"6677884455"}],
[{"Name":"Mahesh","C.NO":"yeud64738274k","Address":"H.No... |
def name(a):
print(f'hello, {a}')
names = ['sergei', 'misha', 'ilia', 'alex', 'sasha']
for i in names:
name(i)
|
# Generated by Django 2.2.2 on 2019-06-08 11:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainattendance', '0002_auto_20190608_0644'),
]
operations = [
migrations.CreateModel(
name='CurrentAttendance',
fiel... |
import io, os, time, json
import logging
from datetime import datetime
import tempfile
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classificati... |
# import pytz
# from datetime import datetime
# from timezonefinder import TimezoneFinder
# tf = TimezoneFinder()
# latitude, longitude = 28.67 , 77.22
# Time_zone=tf.timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Berlin'
# print(Time_zone)
# # UTC = pytz.utc
# IST = pytz.timezone(Time_zone)
# # print("U... |
import pyworld as pw
import sounddevice as sd
import librosa
import numpy as np
import math
from operator import sub
from scipy.io.wavfile import write
x, fs = librosa.load('../data/f1_005.wav', dtype='double', sr=None)
_f0, t = pw.dio(x, fs) # raw pitch extractor
f0 = pw.stonemask(x, _f0, t, fs) # p... |
"""
Helpers
==========================
Commonly used generic data functions
- Create date: 2018-12-16
- Update date: 2019-01-03
- Version: 1.1
Notes:
==========================
- v1.0: Initial version
- v1.1: Add join helper function
"""
import datetime
from dateutil.relativedelta import relativedelta
import ... |
from meshgen.maincastlemesh import MainCastleMesh
from meshgen.castlewallmesh import CastleWallMesh
from meshgen.quadmesh import QuadMesh
class CastleMesh:
def __init__(self):
self.total_size1 = 15
self.total_size2 = 15
self.total_size3 = 50
self.space_to_wall = 1.2
def creat... |
from django.http import Http404, HttpResponse
from django.shortcuts import render
from rest_framework.generics import (
ListCreateAPIView,
RetrieveUpdateDestroyAPIView,
)
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from .serializers i... |
# Under MIT License, see LICENSE.txt
from pyhermes import McuCommunicator
from Engine.Communication.sender.sender_base_class import Sender
from Engine.robot import MAX_LINEAR_SPEED, MAX_ANGULAR_SPEED
from Util.constant import KickForce, DribbleState
from Util.geometry import clamp
import numpy as np
class SerialCom... |
import urllib2, urllib
import json, csv
import pprint as pp
import random
import time
from datetime import datetime, timedelta
import os, re, sys
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import boto
def convert_dataypes(x):
try:
return float(re.sub('[$-+]', '', x))
excep... |
# -*- coding: utf-8 -*-
import json
import time
import pili.api as api
class Stream(object):
"""
Stream属性
hub: 字符串类型,hub名字
key: 字符串类型,流名
disabledTill: 整型,Unix时间戳,在这之前流均不可用,-1表示永久不可用
converts: 字符串数组,流的转码规格
"""
def __init__(self, auth, hub, key):
self.__auth__ =... |
""" Watch the depth of a given symbol.
"""
import signal
import sys
from binance import (
BinanceClient,
configure_app,
get_default_arg_parser,
)
def quit_handler(signum, frame):
sys.exit(0)
signal.signal(signal.SIGINT, quit_handler)
signal.signal(signal.SIGTERM, quit_handler)
def main():
... |
from django import forms
from django.contrib.auth.models import User
from socialapp.models import User_Personal
from django.core import validators
from django.core.exceptions import ValidationError
def validate_gender(value):
if str(value).upper() != "MALE" and str(value).upper() != "FEMALE":
print("gende... |
from flask import Flask, render_template, url_for, request, redirect
import os
import json
import glob
from datetime import datetime
from app import app
@app.route('/')
@app.route('/index')
def index():
# Windows path
# names = sorted(os.listdir(os.getcwd() + r'\app\static\img\name'))
# tasks = sorted(os.l... |
# coding=utf-8
#------------------------------------------------------------------------------------------------------
# TDA596 Labs - Server Skeleton
# server/server.py
# Input: Node_ID total_number_of_ID
# Student Group:
# Student names: John Doe & John Doe
#-----------------------------------------------------------... |
import pandas as pd
dataset = pd.read_csv("AllCountries.csv")
selected_data = dataset.loc[:, ['Country', 'LandArea']]
#print(selected_data)
for i in selected_data.itertuples():
if i['LandArea'] > 2000: # i[2] or i.LandArea
print(i.Country)
# does this work row['landArea'] produce the same result? |
def readFile(filename):
userList = []
try:
with open(filename) as data:
data.readline()
for line in data:
eachLine = line.rstrip().split(',')
user = SysUser(eachLine)
userList.append(user)
except FileNotFoundError or Va... |
#!/usr/bin/python
import sys
import csv
"""
Your mapper function should print out 10 lines containing longest posts, sorted in
ascending order from shortest to longest.
"""
def mapper(inputFile, outputFile):
with open(inputFile,'rb') as tsvin, open(outputFile, 'wb') as csvout:
reader = csv.reader(tsvin,... |
def check():
for idx in range(3):
if lst[idx] == lst[idx + 1]:
return idx
mmax, cost = -1, 0
for i in range(int(input())):
lst = sorted(list(map(int, input().split())))
s = len(set(lst))
if s == 1:
cost = 50000 + lst[0] * 5000
elif s == 2:
if lst[0] == lst[1]... |
a=int(raw_input())
fact=1
if a==0:
print "1"
elif a>0:
for i in range(1,a+1):
fact=fact*i
print fact
|
from transformers import BertForSequenceClassification, BertTokenizerFast, Trainer, TrainingArguments
from nlp import load_dataset
import torch
import numpy as np
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
model = BertForSequenceClassification.from_pretrained('models/BERT_full_question... |
# -*- coding:utf-8 -*-
from openerp import api, models, fields
class HRSalaryRule(models.Model):
_inherit = "hr.salary.rule"
is_dynamic = fields.Boolean("Is dynamic Rule ?")
is_compute_prorata = fields.Boolean("Is compute prorata ?")
account_id = fields.Many2one("account.account", "Compte")
... |
# -*- coding: utf-8 -*-
"""Default configuration file. We check for SECRET_KEY,
DATABASE_PASSWORD and DATABASE_HOST on the environment. These values are
also set in instance/config.py.
To run this example, you will need to put those values in a config.py
file in the instance folder, or create a start up scrip where you... |
import cv2
# 選擇第二隻攝影機
cap = cv2.VideoCapture(0)
for i in range(47):
print("No.={} parameter={}".format(i,cap.get(i)))
while(True):
# 從攝影機擷取一張影像
ret, frame = cap.read()
# 顯示圖片
cv2.imshow('frame', frame)
# 若按下 q 鍵則離開迴圈
key = cv2.waitKey(1)
if key == ord('s'):
print(frame.shape)
if ... |
import numpy as np
from sklearn.metrics import mean_squared_error
import multiple_input as mi
# Define predict_with_network()
def predict_with_network(input_data_row, weights):
# Calculate node 0 value
node_0_input = (input_data_row * weights['node_0']).sum()
node_0_output = mi.relu(node_0_input)
# ... |
'''
Created on 23 avr. 2019
@author: gtexier
'''
from enum import IntEnum, unique
@unique
class Intersection(IntEnum):
'''
Name of the intersection types
'''
PathFour = 0
PathThreeLeftFront = 1
PathThreeRightFront = 2
PathThreeLeftRight = 3
PathTwoLeft = 4
PathTwoRight = 5
Path... |
'''
Write a Python program to print the following floating numbers upto 2 decimal places.
'''
x = 3.1415926
y = 12.9999
print "Original number:", x
# 1st variant
print "New number:", round(x, 2)
# or
#print "New number:", '{:.2f}'.format(x)
print "Original number:", y
# 1st variant
print "New number:", round(y, 2... |
#!/usr/bin/env python3
import random
import copy
def random_pirellone(m, n, seed="any", solvable=False):
if seed=="any":
random.seed()
seed = random.randrange(0,1000000)
else:
seed = int(seed)
random.seed(seed)
line = [random.randint(0, 1) for _ in range(n)]
inv = [i... |
import dash
import kdash
from flask import Flask
server = kdash.Add_Dash(Flask(__name__))
# dash_app = dash.Dash(server=server, url_base_pathname='/dataview/')
kdash.Add_Dash
if __name__ == '__main__':
server.run('0.0.0.0', 8888, debug=True)
|
from django.contrib import admin
from .models import Category, Keyword
# Register your models here.
admin.AdminSite.site_title = '宠物平台管理系统'
admin.AdminSite.site_header = '旅行者Ⅰ号'
admin.AdminSite.index_title = '平台管理'
class KeywordInline(admin.StackedInline):
model = Keyword
extra = 3
@admin.register(Categor... |
# Generated by Django 2.2.6 on 2019-11-16 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='baseoption',
name='color',
f... |
# zur Kommunikation ueber die serielle Schnittstelle
import serial
import string
# fuer die Datenbank-Verbindung (drauf achten, dass richtige fuer Python-Version installiert)
import mysql
import mysql.connector
from time import sleep
from time import gmtime, strftime
#Parameter fuer die Verbindung zur Datenbank:
#Date... |
from datetime import datetime
from flask import request
from flask_restful import Resource, abort
from flask_jsonpify import jsonify
from webargs import fields
from webargs.flaskparser import use_args
from shared import db
from models.timetable import Timetable
class TimetableHandler(Resource):
get_and_delete_args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.