text stringlengths 38 1.54M |
|---|
def str_together(in_string):
"""Given a list of word strings, return a single string with all the
strings together, with ' - ' in between the words."""
return " - ".join(map(str,in_string))
fruits = ['Orange', 'Lemon', 'Lime', 'Cherry', 'Peach', 'Apricot']
fruit_string = str_together(fruits)
... |
import commands
import sys
from Utility import ( wlog)
def Estimate_Cutoff_and_Annotate_Artifact(conf_dict,logfile):
format_FPR_file = conf_dict['General']['outputdirectory']+'Format_False_Positive_Table.txt'
user_Max_FPR_cutoff = conf_dict['General']['max_fpr']
all_samples_MQS_WCQS_file = conf_dict['Gen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
class Formatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._spl... |
import helper
import gold
def parse_content(content):
'''Convert input into a dictionary word: number'''
content_dict = {word: float(freq) for string in content.splitlines() for word, freq in [string.split()]}
return content_dict
def make_tree(words):
'''Creates trie-like nested dictionary'''... |
from bs4 import BeautifulSoup
from selenium import webdriver
stock_file = r"C:\Users\Tut10\Desktop\PSTool-Python\Final\test.txt"
def Costco_Shipping(url):
"""This opens up chrome. Scans through the webpage for the out of stock class
prints out if in stock or out and writes it to file. Pretty simple
... |
from django.test import TestCase
from mayerapi.models import Payment,Loan,Client
from django.db.utils import IntegrityError
from datetime import datetime
from decimal import Decimal
import os.path
from mayerapi.tests.utils import(
create_client_from_model,
create_loan_from_model,
create_payment_from_mode... |
import math
import numpy
import os
import config
from itertools import combinations
#file_path = '%stest_out2.txt' % config.data_directory
def get_slim_metadata(file_path):
metadata_dict = {}
to_int = ['population_size', 'genome_size', 'number_generations', 'tract_length']
with open(file_path) as file... |
for i in range(2, 9+1) :
for j in range(1, 9+1) :
print('{} * {} = {}'.format(i, j, i*j)) |
# -*- coding: utf-8 -*-
import pandas as pd
__author__ = "Asim Krticic"
class Service(object):
"""This class
"""
def __calculate_subscription_period(self, x):
"""
Accepts joined data frame.
Calculate subscription period for every user.
Returns updated Pandas ... |
from collections import OrderedDict
import torch.distributed as dist
import torch
import torch.nn as nn
def parse_losses(losses):
log_vars = OrderedDict()
for loss_name, loss_value in losses.items():
if isinstance(loss_value, torch.Tensor):
log_vars[loss_name] = loss_value.mean()
e... |
def encode(json, schema):
payload = schema.Main()
payload.cjs = json['cjs']
payload.mainFields = json['mainFields']
payload.mode = json['mode']
payload.force = json['force']
payload.cache = json['cache']
payload.sourceMap = json['sourceMap']
return payload
def decode(payload):
retur... |
def draw_c(size, row):
if row == 0 or row == size -1:
print("* " * size, end ="")
else:
print("* ",end = " " * (size-1))
print(end =" " * size )
def draw_o(size, row):
if row == 0 or row == size -1:
print("* " * size, end ="")
else:
print("* "+" "*(size-2),end ="* ... |
# Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
pass
#TODO:
def fibonacci(n, m):
current, next_item = 1, 1
numbers = []
for x in range(1, m + 1):
if x >= n:
numbers.append(curren... |
from controller import Robot, Supervisor, Field, Node
from Arm import *
from Gripper import *
from Base import *
import numpy as np
import math
robot = Supervisor()
timestep = int(robot.getBasicTimeStep())
# Initialize the base, arm and gripper of the youbot robot
base = Base(robot)
arm = Arm(robot)
gripper = Grippe... |
# Generated by Django 2.1.1 on 2018-11-07 13:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('companies', '0008_companycategory'),
]
operations = [
migrations.AlterModelOptions(
name='compa... |
import os
import pty
import time
import select
m1, s1 = pty.openpty()
m_name1, s_name1 = os.ttyname(m1), os.ttyname(s1)
m2, s2 = pty.openpty()
m_name2, s_name2 = os.ttyname(m2), os.ttyname(s2)
print('{} -> {}'.format(s_name1, s_name2))
while 1:
ready, _, _ = select.select([m1, m2], [], [])
for device in rea... |
import sounddevice as sd
import numpy as np
class AudioHandler():
def __init__(self, duration=1, sample_rate=48000, device=0):
sd.default.samplerate = sample_rate
sd.default.device = device
sd.default.channels = 2
self.fs = sample_rate
self.duration = duration
def get... |
# Generated by Django 3.2 on 2021-07-19 11:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('communities', '0001_initial'),
('quizzes', '0001_initial'),
]
operations = [
migr... |
#!/usr/bin/env python
"""
model enumerator for the SDD package
"""
import sdd
def elements_as_list(node):
size = sdd.sdd_node_size(node)
elements = sdd.sdd_node_elements(node)
return [ sdd.sddNodeArray_getitem(elements,i) for
i in xrange(2*size) ]
def models(node,vtree):
"""A generator... |
from django.urls import path
from django.conf.urls import url
from . import views
app_name='core'
urlpatterns=[
path('signup1/',views.SignUp1.as_view(),name='signup1'),
path('signup2/',views.SignUp2.as_view(),name='signup2'),
]
|
"""
Date: December 15, 2015
Author: Laura Buchanan and Alex Simonoff
This module set all the functions and helper functions used by the main program.
"""
import time
import datetime
from Visualization import *
weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
months = ['January','F... |
from django.shortcuts import render,redirect,render_to_response
from .models import Petition_info,User
import os
# Create your views here.
def create(request):
return render(request,'creator.html',{'UserEmail':'Anonymous'})
def handle_uploaded_file(f,n):
destination = open(os.path.dirname(os.path.dirname(__file__)... |
'''
indexer for suche Search Engine
copyright (c) 2014 Suche
'''
from indexer.models import SucheURL,Link,Word,Result
from indexer.htmlparser import HTMLParser
from crawler.models import *
class Indexer:
def set_raw(self,raw):
'''
sets the raw data row to which the indexer is to operate.
'... |
import numpy as np
def equation3(theta):
"""
Equation 2.3 from the book.
Input
----------
theta: Angle that I want to evaluate equation 2.3 at. Input should be in degrees
Output
----------
Value of the function at theta, f(theta)
"""
th_rad = np.radians(theta) # Convert the ... |
# Dependencies
import os
import sys
import numpy as np
import tensorflow as tf
import time
import cv2
"""
tf.data.Dataset--
The dataset consists of elements of the same structure.
Each element has one or more tf.Tensor objects, which are called components.
Each component has tf.DType (type of elements of tensor) and... |
from rest_framework.generics import ListAPIView, RetrieveAPIView, UpdateAPIView, CreateAPIView, DestroyAPIView
from .serializers import OrderItemSerializer
from items.models import OrderItem
from rest_framework.response import Response
from django.conf import settings
from rest_framework import viewsets
# OrderItem API... |
import unittest
from flask import abort, url_for
from flask_testing import TestCase
from os import getenv
from application import app, db
from application.models import Tracks, Artists, Genres
from application.routes import delete
class UnitBase(TestCase):
def create_app(self):
#pass in test configuration... |
"""Testing changing editor status, but only with 'approve': 'accept'"""
import json
import requests
def test_changing_editor_status():
"""
Mustn't have emails 'editor@test.agh.edu.pl' and 'admin_test3@admin.agh.edu.pl'
in database or test will fail.
:return: None
"""
url_user = 'http://127.0.0... |
#!/usr/bin/env python3
import argparse
import re
from typing import List, Dict, Any
from core.kernel import Kernel
from core.command import Command
from core.task import Task
from core.operation import Operation
from core.simple_operation import SimpleOperation
parser = argparse.ArgumentParser(prog="cb-repair",
... |
# 1000 미만의 자연수 구하기
n = 1
while n< 1000:
print(n)
n += 1
for n in range(1,1000):
print(n)
result = 0
for n in range(1,1000):
if n %3 ==0 or n % 5 ==0:
# print(n)
result += n
print(result)
|
# Generated by Django 2.1.3 on 2018-11-16 12:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(aut... |
from setuptools import setup,find_packages
setup(
name = 'speedrecorder',
url = 'https://github.com/rweyant/speedtest-cli',
description='A function that records your internet speed',
version = '0.1',
packages = find_packages(),
install_requires=[
'ipgetter',
'requests']
)
|
def main():
passportDictionary = {
"byr": "req",
"iyr": "req",
"eyr": "req",
"hgt": "req",
"hcl": "req",
"ecl": "req",
"pid": "req",
"cid": "opt"
}
validEyeColors = [
"amb",
"blu",
"brn",
"gry",
"grn",
... |
from django.db import models
# database for the cities
class City(models.Model):
city = models.CharField(max_length=100)
abb = models.CharField(max_length=5)
def __str__(self):
return f'{self.city} ({self.abb})'
# Database for the hotels, connected with cities
class Hotel(models.Model):
cit... |
from django.conf import settings
from django.contrib.auth.views import PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
from django.conf.urls import url
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
url(r'^$'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-19 11:09
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('map', '0004_auto_20171113_0124'),
]
oper... |
from odoo import api, fields, models
from datetime import datetime
from odoo.exceptions import ValidationError
class Planning(models.Model):
_name = 'mrp.plan'
_description = 'MRP Planning'
def change_color_on_kanban(self):
for record in self:
color = 0
if record.s... |
fname = raw_input("Enter file name: ")
fh = open(fname) #opened files
lst = list()
for line in fh: #read it by line
line = line.rstrip() #white space is reduced for each line
words = line.split() #line is split into a list of words
#print "###", words
for i in words:
if i in lst:
... |
from flask import Flask
app = Flask(__name__)
from app.clientes import main
app.register_blueprint(main)
app.run(debug=True,port=3000)
|
import rw
import networkx as nx
import numpy as np
import pickle
import sys
filename=sys.argv[1]
usf_graph, usf_items = rw.read_csv("./snet/USF_animal_subset.snet")
usf_graph_nx = nx.from_numpy_matrix(usf_graph)
usf_numnodes = len(usf_items)
numsubs = 50
numlists = 3
listlength = 35
numsims = 1
#methods=['rw','goni'... |
import time
import csv
import sys
import math
import pandas as pd
import numpy as np
from sklearn.feature_selection import SelectFpr
import random
import collections
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier , RandomForestClassifier, GradientBoostingClassifier
#from... |
#coding=utf-8
__author__ = 'hqx'
class AppRunConfig(object):
capabilities = { 'platformName':'Android',
# 'platformVersion':'5.0.2',
'deviceName':'dq6lburkcqhylb6d',
#钉钉
'appPackage':'com.alibaba.android.rimet',
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
import json as simplejson
class Site(models.Model):
_name = 'htc.site'
_inherit = 'mail.thread'
site_group_id = fields.Many2one("htc.site.group", string="Site Group Code... |
#!/usr/bin/env python
import tornado.web
import tornado.httpserver
import tornado.database
from data.conversation import ConversationData
from data.message import MessageData
from data.deal import DealData
from data.user import UserData
import json
class ConvHandler(tornado.web.RequestHandler):
@property
def ... |
"""Author - Rahul Mehta """
import torch
import pandas as pd
import numpy as np
import seaborn as sns
from SRL_NN_Classifier import SRL_LSTM
from sklearn.metrics import classification_report
from SRL_dataset import SRL_dataset
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.model_sel... |
from django.shortcuts import render
from .models import Article, ArticleClassification, Tag, Mood
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.views.generic.base import View
# from django.views.decorators.csrf import csrf_exempt
# Cre... |
from direct.showbase import GarbageReport
from otp.ai.AIBaseGlobal import *
from otp.ai.MagicWordGlobal import *
from otp.avatar import DistributedAvatarAI
from otp.avatar import PlayerBase
from otp.distributed.ClsendTracker import ClsendTracker
from otp.otpbase import OTPGlobals
class DistributedPlayerAI(Distributed... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import CandidateRegistrationModel
from .forms import CandidateRegistrationForm
class IndexVie... |
from django.db import models
from django.contrib.auth.models import User
from tours.models import Tour
# Create your models here.
class Review(models.Model):
tour = models.ForeignKey(Tour, on_delete=models.CASCADE, related_name="reviews")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=... |
# coding: utf-8
"""
CMS Performance API
Use these endpoints to get a time series view of your website's performance. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspec... |
import psycopg2
import re
from backend.pg import PGBackend
'''
@author: anant bhardwaj
@date: Oct 3, 2013
DataHub DB wrapper for backends (only postgres implemented)
'''
class Connection:
def __init__(self, user, password, db_name=None):
self.backend = PGBackend(user, password, db_name=db_name)
def execute... |
from django.db import models
from django.shortcuts import render
from random import randrange
import math
# Create your models here.
class Ingatlan(models.Model):
tipus = models.CharField(max_length=30)
méret = models.CharField(max_length=30)
cím = models.CharField(max_length=50)
ár = models.CharField(... |
#
# 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020)
# 3.5 거듭제곱 연산자 : **, 74쪽
#
a = 1000
r = 0.05
n = 10
print(a * (1 + r) ** n)
bottom = float(input('직각삼각형의 밑변의 길이를 입력하시오: '))
height = float(input('직각삼각형의 높이를 입력하시오: '))
hypotenuse = (bottom ** 2 + height ** 2) ** 0.5
print('빗변은', hypotenuse, '입니다') |
import os
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. '
def func1():
number = 0
arr1 = []
for i in os.listdir('.'):
if os.path.isfile(i):
j = 0
check1 = True
check2 = 0
for j in range(len(i)):
if i[j] not i... |
import time
import serial
import struct
COM = "COM10"
print "GBA Dumper + Arduino DUE"
st = time.clock()
# buffer clear
ser = serial.Serial(port=COM, baudrate=115200)
time.sleep(0.1)
ser.close()
# restart
ser = serial.Serial(port=COM, baudrate=115200)
s = 0
for i in xrange(4):
s <<= 8
s = s + ord(ser.read(1))
... |
import pandas as pd
from sqlalchemy import create_engine
strConnection = 'postgresql://weather_user:159753@159.65.233.116:5432/weather_tool'
engine = create_engine(strConnection, pool_pre_ping=True)
query_CitiesFind = 'SELECT iata_code FROM cities c WHERE NOT EXISTS (SELECT * FROM airports a2 WHERE a2.iata_code = c.... |
from typing import List, Dict, Set, Tuple
"""
Beats 50% in terms of runtime
Beats 30% in terms of memory usage
It probably took me around 2 hours to
code this, but debugging it was quite
easy ( as opposed to some other problems
I worked on).
First submission was succesful
This was labelled as hard.
"""
"""
For ... |
#!/usr/bin/python
# vim: set fileencoding=\xe2
import re
from urlparse import urlparse
from pprint import pprint
print '''
_____ _ _____ _
/ ____| | |/ ____| | |
| (___ __ _ __| | | ___ __| | ___
\___ \ / _` |/ _` | | / _ \ / _` |/ _ \
____) | (_... |
from relogic.components.component import Component
from relogic.structures.structure import Structure
from typing import List
class SRLComponent(Component):
"""
"""
def execute(self, inputs: List[Structure]):
counter = 0
expanded_inputs = []
mapping = []
for idx, structure in enumerate(inputs)... |
# Assembler to machine code for Amoeba
import sys
commands = {
'LDA':'0000',
'STA':'0001',
'LDAN':'0010',
'ADD':'0011',
'SUB':'0100',
'MLT':'0101',
'DIV':'0110',
'JF':'0111',
'JB':'1000',
'JFE':'1001',
'JBE':'1010',
'CLO':'1011',
'PAN':'1100',
'PAC':'1101',
'NOP':'1110',
'END':'111... |
# Copyright 2019-2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
import json
from bson import ObjectId
import datetime
# to handle the objectID and datetime
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
if isinstance(o, datetime.d... |
import paho.mqtt.client as paho
broker="broker.hivemq.com"
#broker="iot.eclipse.org"
#define callback
def on_message(client, userdata, message):
print("received message =",message.payload)
client= paho.Client()
######Bind function to callback
client.on_message=on_message
#####
print("connecting t... |
def is_armstrong_number(number):
"""
Check to see if the given number is an Armstrong Number.
An armstrong number is a number that the sum of its digits
each raised to the power of the number of digits in the number
is equal to the number.
For example
* 9 is an Armstrong number, because 9 ... |
# -*- coding: utf-8 -*-
import sys
import tweepy
import webbrowser
import pickle
import os
from time import time, strftime, localtime
CONSUMER_KEY = 'zXhZvsaUSLbnk1E2KjcNw'
CONSUMER_SECRET = 'dqinsFtcx7aO7TKJYzTr3s8JpgWjwCMjFMnVwm41plg'
ACCESS_TOKEN = '9175042-LgX3UMYB9qSauD7DvEjp0Nsle3vttognI0Fy0KHZ4M'
ACCESS_TOKEN... |
import re
def count_animals(sentence):
return sum([int(n) for n in sentence.split() if n.isdigit()])
def count_animalsB(sentence):
return sum(map(int, re.findall(r'\d+',sentence)))
#spent time for my solution: 0.03591169500000002
#spent time for the best practice : 0.06533677399999993 |
from games.cards.Class_card import Card
from random import *
class DeckOfCards:
def __init__(self):
self.list1=[]
self.deck()
self.shuffle()
def deck(self):
for suit in range(1,5):
for value in range(2,15):
c1=Card(value,suit)
self.l... |
#Build List of Cities from Property list
#Call scrapy
import subprocess
import sqlite3
import json
import re
def gen_city_urls():
state_map = {
"OR":"Oregon",
"TX":"Texas",
"AZ":"Arizona",
"CA":"California",
"IL":"Illinois",
"OK":"Oklahoma",
"NJ":"New-Jersey"... |
# Generated by Django 3.0 on 2019-12-17 07:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('image', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='image',
name='pub_date',
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import *
from django.template import loader, RequestContext
from models import *
from django.core import exceptions
from ttsx_app.forms import add_serverform
# Create your views here.
def index(reques... |
import os
import numpy as np
from skimage.filters import threshold_local
from scipy.ndimage.measurements import center_of_mass
from lsst.ts.wep.cwfs.Image import Image
class AdapThresImage(Image):
def generateMultiDonut(self, spaceCoef, magRatio, theta):
"""
Gemerate multiple donut ima... |
# Условие
# Последовательность Фибоначчи определяется так:
# φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
# По данному числу n определите n-е число Фибоначчи φn.
# Эту задачу можно решать и циклом for.
n = int(input())
a = 0
b = 1
for i in range(n - 1):
a, b = b, a + b
print(b) |
import pandas as pd
from ipps import IppsData
from DRGtoMDC import DRGtoMDC
def main():
"""
Entry point for main logic
"""
# IppsData object know how to read the input data and add the necessary fields we need
ipps = IppsData()
# load data initializes the object
ipps.load... |
"""滤波器"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
# from . import utils
def strokeEdges(src, dst, blurKsize=7, edgeKsize=5):
"""
边缘检测
:param src:源图像
:param dst:目标图像
:param blurKsize:模糊滤波器的滤波核(奇数)
:param edgeKsize:边缘检测滤波器的滤波核(奇数)
"""
if blurKs... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 5 03:26:55 2020
@author: polin
"""
import requests
import json
code = "82e622ccc27b4ad0af0918182329a742"
region = 'westeurope'
def extract(obj, arr, code):
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
... |
#!/usr/bin/env python3
import argparse
import os,sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
from torch.utils.data import DataLoader
import torch.optim as optim
from torch.optim import lr_scheduler
from torch... |
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.random namespace.
"""
from __future__ import print_function as _print_function
from tensorflow._api.v1.compat.v2.random import experimental
from tensorflow.pyt... |
from datetime import datetime as dt, date, timedelta
import os
import mysql.connector
import constant
import Decrypt
from twilio.rest import Client
'''
Just sends a text message to the user
'''
#Fake data, purpose of this is just showing the work I done for this project
account_sid = Decrypt.TW_SID
auth_... |
# Copyright [2018] [Wang Yinghao]
#
# 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 writ... |
#!/usr/bin/env python
#
# Paulo Sherring 2020
# Portions Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google 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.... |
import datetime
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=100, blank=True, n... |
from django.conf.urls import url, include
from rest_framework import routers
from core.views import ProviderViewSet, UpdateViewSet
from rest_framework_swagger.views import get_swagger_view
router = routers.DefaultRouter()
router.register(r'provider', ProviderViewSet)
router.register(r'update', UpdateViewSet)
schema_... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time,sys,... |
"""
Luke
"""
import os.path as osp
import glob
import tqdm
import numpy as np
import mmcv
from mmcap.apis.inference import init_caption
from mmcap.apis.extract import extract_encoder_feat
from mmcap.datasets.tokenizers.tokenization_kobert import KoBertTokenizer
def extract_feat(model, tokenizer, src_dir:str, dst_di... |
from train import train_model
from data_loader import load
from examples.NIPS.MNIST.mnist import MNIST_Net, neural_predicate
import torch
from network import Network
from model import Model
from optimizer import Optimizer
train_queries = load('train.txt')
test_queries = load('test.txt')[:100]
def test(model):
... |
from security.backends.app import SecurityBackend
class SecurityTestingBackend(SecurityBackend):
name = 'security.backends.testing'
label = 'security_backends_testing'
backend_name = 'testing'
reader = 'security.backends.testing.reader.TestingBackendReader'
|
from django.contrib import admin
from .models import Profile, Classroom, Reservation
# Register your models here.
admin.site.register(Profile)
admin.site.register(Classroom)
admin.site.register(Reservation) |
from rest_framework.views import APIView
from api.models import Profile
from rest_framework.exceptions import PermissionDenied
class HaveProfileMixin:
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
try:
request.user.profile
except Profil... |
import re
print("----------匹配单个字符与数字----------")
'''
. 匹配除换行符以外的任意字符
[0123456789] []是字符集合,表达匹配方括号中所包含的任意一个字符
[tracy] 匹配't','r','a','c','y'中任意一个字符
[a-z] 匹配任意小写字母
[A-Z] 匹配任意大写字母
[0-9] 匹配任意数字,类似[0123456789]
[0-9a-zA-Z] 匹配任意的数字和字母
[0-9a-zA-Z_] 匹配任意的数字,字母和下划线
[^... |
##future feature
#%%
import requests
import json
def get_halts():
"""
use nyse api to get halts. Saves a json locally and then compares the new reponse to the local json to see if new halts or resumptions
"""
res = requests.get('https://www.nyse.com/api/trade-halts/current?offset=0&max=50').json()
... |
import geomstats.backend as gs
from geomstats.geometry.euclidean import Euclidean
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.geometry.special_orthogonal import SpecialOrthogonal
from tests.data_generation import TestData
class ConnectionTestData(TestData):
def metric_matrix_test_data(se... |
import os
import glob
import numpy as np
from random import randrange
from scipy.io import wavfile
class DataLoader:
def __init__(self, train_spec_dir, val_spec_dir, test_spec_dir, train_batch_size, val_batch_size,
test_batch_size, sequence_length, fft_length):
base_dir = ''
self.train... |
#!/usr/bin/env python
from ansible.module_utils.basic import *
module = AnsibleModule({})
print '{"platform": "' + get_platform() + '","distribution": "' + get_distribution() + '","version": "' + get_distribution_version() + '"}'
|
"""
This script is used to extract person's facial feature data from image using dlib face shape model and deep neural network model to extract face feature in 128-D vector
"""
import dlib
import cv2
import os
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.externals import joblib
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class YourSolution(object):
def inorderTraversal(self, root):
array = []
array = self.inorderTraversalInternal(root, array)
return array
def inorderT... |
# Modulo registro #
# Max Sebastian Herrera Salazar #
# Octubre 2017 #
# Version 1 #
import random
data = []
data2 = []
length=random.randrange(1,1000)
i=0
while i <= length :
data.append(random.randrange(150,1000))
data2.append(random.randrange(1,10000))
i = i + 1
#print(data)
archivo = open("registro.... |
import requests
url = 'http://datacamp.com/teach/documentation'
r = requests.get(url)
text = r.text
print(text) |
""" Transformations of coordinate systems. """
import numpy as np
from scipy.spatial.transform import Rotation as R
from wana import analysis
def transform_to_reference_system(sensor):
""" Tranform the data in the given sensor object to a reference system.
Use the angular velocities and time intervals to ca... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 11:25:38 2020
@author: PENG Feng
@email: im.pengf@outlook.com
"""
from utils import date_str_p1
import os
if not os.path.isdir("../input"):
os.makedirs("../input")
if not os.path.isdir("../output"):
os.makedirs("../output")
TYPE_E = "{}: improper types or le... |
import tensorflow as tf
import numpy as np
from segmentation import segmentation_model, divide_image, merge_image
if __name__ == '__main__':
x = tf.placeholder(dtype=tf.float32, shape=[None, 128, 128, 3])
output = segmentation_model(x, False)
out_mask = tf.nn.sigmoid(output)
saver = tf.train.Saver()... |
for var1 in range(20,0,-2): #decrementing in twos from 20 to 2/countdown loop
print(var1) #displaying number pattern
else:
print("Enough with loops") #signaling the end of the programme
cars=["VW","BMW","Ford","Mazda","Tata"] #declaring list of items
for mycars in cars:
print(mycars) #printing the previous... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.