text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class account_bank_statement_line(osv.osv):
_inherit = 'account.bank.statement.line'
def onchange_account_id_analytic(self, cr, uid, ids, account_id... |
def checkio(numbers_array):
r=[]
nl=list(numbers_array)
print("==================")
while len(numbers_array) > len(r):
max=0
for m in nl:
if abs(m) >=abs(max) :
max=m
r.append(max)
print("结果:",r)
nl.remove(max)
print("nl:",nl)
... |
def process(prices, profit):
index = 0
if len(prices) <= 1:
return 0
#assume first element is lowest
low = prices[0]
high = prices[1]
test_profit = high - low
for price in prices:
if price > high:
high = price
temp_profit = high - low
#is this test necessary
#YES because now profit is passed in... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-28 12:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import post_app.models
class Migration(migrations.Migration):
dependencies = [
('post_app', '0001_initial'),
]
o... |
# def imprimir_mensaje():
# print("Mensaje especial: ")
# print("Estoy aprendiendo a usar funciones")
# imprimir_mensaje()
# imprimir_mensaje()
# imprimir_mensaje()
def conversacion(mensaje):
print("Hola")
print("¿Cómo estás?")
print(mensaje)
print("Adios")
opcion = int(input("Elige un... |
# -*- coding: utf-8 -*-
from models import User, Image
from session import session
# UserとImageを追加する。
testuser = User('test_cascade', '', '')
testimage = Image('image name', testuser)
session.add(testuser)
session.add(testimage)
session.commit()
# 追加されているか確認
user = session.query(User).filter(User.name=='test_cascade... |
import smtplib
import os
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
from email.mime.base import MIMEBase
def new_file(test_dir):
# 列举test_dir目录下的所有文件,结果以列表形式返回。
global lists
lists = os.listdir(t... |
# Feature Extraction with RFE
from pandas import read_csv
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
# load data
filename = 'pima-indians-diabetes.data.csv'
data = read_csv(filename)
array = data.values
X = array[:, 0:8]
Y = array[:, 8]
# feature extraction
model = L... |
import logging
import src.embedding_algorithms.embedding as embedding
import src.link_prediction.evaluation as evaluation
import src.utils as utils
import time
from sklearn.model_selection import train_test_split
from stellargraph.data import EdgeSplitter
logger = logging.getLogger('sna')
def run(graph, args):
... |
Tiempo = ""
Tiempo = raw_input("Hace calor, frio, o esta templado"+Tiempo)
if Tiempo == "calor" :
print("Quitate el sueter")
elif Tiempo == "frio" :
print("Ponte un sueter")
elif Tiempo == "templado" :
print("Ponte lo que quieras") |
# from django.shortcuts import render, redirect
# from django.contrib import messages
# from .forms import SignUpForm
# from django.contrib.auth.decorators import login_required
# def signup(request):
# if request.method == "POST":
# form = SignUpForm(request.POST)
# if form.is_valid():
# ... |
from django.urls import path
from .views import UserCreateView, UserUpdateView, UserListView, UserDetailView, UserDeleteView, TeamCreateView
app_name = 'users'
urlpatterns = [
path('', UserListView.as_view(), name='users-list'),
path('<int:pk>/', UserDetailView.as_view(), name='user-detail'),
path('creat... |
from flask import Flask,render_template,request
import requests
app = Flask(__name__)
class Weather():
def __init__(self,city):
self.url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=API_LEY'.format(city)
def get_weather(self):
data = dict()
try:
response = ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWind... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
import uuid
class User(models.Model):
email = models.EmailField()
name = models.CharField(max_length=120)
username = models.CharField(max_length=120)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# author: cg错过
# time : 2017-09-30
class EmailUtil:
# 发送邮件模块
def __init__(self, dictNeedRunMsg, fileUti... |
# coding: utf-8
"""
SpaCy deep_learning_keras.py solution to Kaggle Toxic Comment challenge
"""
from utils import xprint_init, xprint
from framework import Evaluator, seed_random, show_auc
from clf_spacy import ClfSpacy
submission_name = 'spacy_lstm9'
epochs = 40
def get_clf0():
return ClfSpacy(n_hidden=64,... |
from django import forms
from django.contrib.auth.models import User, Group
from .models import report
from .models import folder
from .models import Document
from django.forms import ModelForm
class ReportForm(forms.Form):
title = forms.CharField()
short_description = forms.CharField(max_length=30)
detaile... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
import sqlite3
from itemadapter import ItemAdapter
class QuotePipeline:
def ... |
#!/usr/bin/env python
# Copyright The OpenTelemetry Authors
#
# 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 applicabl... |
import numpy as np
def sample_equal_proportion(y, proportion=0.667, random_state=None):
"""Sample in equal proportion.
Sample in equal proportion.
Parameters
----------
y : array, shape (n_obs)
Input data to be split
proportion : float, default: 0.667
Proportion to split into t... |
"""
This module is used to interact with the 7shifts API to create or update sales
receipts in 7shifts, which are used for sales projections and dashboards.
See https://developers.7shifts.com/reference/listsalesreceipts for more
details.
"""
from . import base
from . import exceptions
from . import dates
ENDPOINT = '... |
from bson.objectid import ObjectId
import trueskill
import orm
SOURCE_TYPE_CHOICES = ('tio', 'challonge', 'smashgg', 'other')
# Embedded documents
class AliasMapping(orm.Document):
collection_name = None
fields = [('player_id', orm.ObjectIDField()),
('player_alias', orm.StringField(required=T... |
#三目运行符
#练习1
# a=10
# b=20
#
# max= a if a>b else b
# print(max)
# 练习2: 有3个数,使用一行代码求最大值,提示:使用三目运行符
a=30
b=10
c=20
# max= a if a>b else b
# max2=max if max >c else c
max2=(a if a>b else b) if (a if a>b else b) >c else c
print(max2)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-28 08:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('TestOnline', '0010_auto_20170728_1426'),
]
operati... |
from aws_cdk import (aws_s3 as s3, core)
class NewBucketStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# The code that defines your stack goes here
bucket = s3.Bucket(self, "learnAWSCDK", versioned=True)
|
def _give_me_a_good_name(value, nextValue, maxDelta):
# check if the next value is within the permissable limit
if nextValue - value > maxDelta:
return False
return True
def validate_soc_reading(values):
last_but_one_reading = len(values) - 1
# iterate over all exepct last one
for i in ra... |
from django.db.models import manager
from mptt import managers as mptt_managers
class CommonManager(manager.Manager):
pass
class TreeManager(mptt_managers.TreeManager):
pass
|
# Generated by Django 2.1.3 on 2018-12-02 21:46
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scheduler', '0012_auto_20181202_2141'),
]
operations = [
migrations.AddField(
model_name='room',
nam... |
#!/usr/bin/env python3
print("Generating plots.")
import importlib
from collections import namedtuple
import numpy as np
import matplotlib.pyplot as plt
seaborn_loader = importlib.find_loader("seaborn")
if seaborn_loader is not None:
import seaborn as sns
else:
sns = None
if sns:
sns.set_context('poster'... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 16:46:47 2021
@author: Sosig
"""
encrypted = "96B4A9A08AA7AB87A8 A2 8B 87 85 B4 A3 B186 85 83 85 9C F2 F6 F0 FF E8 A5 A9 AB"
def helper(a,b):
_tmp =(((a & 255) * 555 ) //16 ) % 256
result = chr(_tmp ^ b)
return result
def decrypt(target):
key = ""... |
import mysql.connector as my
import chart_studio.plotly as py
import matplotlib.pyplot as go
import numpy as np
import pandas as pd
db=my.connect(host='localhost',user='root',password='1234',database='population_projection')
#print(db.connection_id)
key=db.cursor()
#key.execute("insert into population... |
# -*- coding: utf-8 -*-
# 指數求取
# 計算整數a模m的指數
from .NTLCoprimalityTest import coprimalityTest
from .NTLExceptions import DefinitionError
from .NTLUtilities import jsrange
from .NTLValidations import int_check
__all__ = ['order']
nickname = 'ord'
'''Usage sample:
print('The order of 2 mod 9 is\n\... |
__author__ = "Luis David Montoya Diaz"
__copyright__ = "Copyright 2018, ISUC"
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from Apps.Tarea.views import ConsultarTarea, CrearTarea, ConsultarTodasTareas, descargarArchivo
u... |
N = int( input())
W = [0]*(N+1)
for _ in range(N):
p = int( input())
if W[p-1] >= 1:
W[p] = W[p-1]+1
if W[p] == 0:
W[p] = 1
print(N - max(W))
|
#To download input data from the CADC for the run
#get dir
#how to get directory from CADC?
wget --content-disposition http://www.canfar.phys.uvic.ca/vospace/nodes/nugrid/data/projects/mppnp/examples/mppnp_hif/e2D14.0077501.se.h5?view=data"
mv e2D14.0077501.se.h5 H5_input_scripts/
#proceed as in README
|
from django.apps import AppConfig
class UserprofilesConfig(AppConfig):
name = 'userprofiles'
verbose_name = 'Perfil de Usuario'
|
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from datetime import datetime as dt
from datetime import date, timedelta
import pandas as pd
import time
from components.functions import df_pc
import dash
import dash_bootstrap_components as dbc
################################b... |
'''
Question:1
Write a program to sort a stack using extra stack.
Input: [23,12,90,5,7]
Output: [5,7,12,23,90]
'''
def sort_stack(arr):
stack_1 = []
stack_2 = []
n = len(arr)
if len(stack_1) == 0:
stack_1.append(arr[0])
for i in range(1, n):
s1_top = stack_1[-1]
if s1_top >... |
"""
Author: Sidhin S Thomas (sidhin@trymake.com)
Copyright (c) 2017 Sibibia Technologies Pvt Ltd
All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
"""
import pycountry
from django.core.management import BaseCommand
from trymake.apps.customer.... |
######saral que 2
# number=[50,40,23,70,56,12,5,10,7]
# i=0
# list_1=[]
# count=0
# while i<len(number):
# if number[i]>=20 and number[i]<=40:
# list_1.append(number[i])
# count=count+1
# i=i+1
# print(count)
# print(list_1)
|
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import requests
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'Buscador de c... |
#!/usr/bin/env python
"""
_LoadForSubmitter_
MySQL function to load jobs for submission
"""
__all__ = []
from WMCore.Database.DBFormatter import DBFormatter
class LoadForSubmitter(DBFormatter):
"""
_LoadForSubmitter_
Custom load function for the JobSubmitter
"""
sql = """SELECT wmbs_job.id, j... |
import sys
# Check if number is a valid Hex Value
def isHex(number):
try:
int(number,16)
return True
except:
return False
# Check for valid integer
def isInt(number):
try:
int(number,10)
return True
except:
return False
# Check for expected str length
d... |
import os
import time
import sys
import socket
from java.io import File
from java.io import FileInputStream
# Stopping the servers
def stopMS(servers):
for server in servers :
cd('/ServerLifeCycleRuntimes/' + server.getName())
serverstate = get('State')
servername = server.getName()
upStatus = ["RUNNING","... |
from .params import CimageParams
from .validators import validate_search_params
from .mail import send_mail
|
import requests
from requests.adapters import HTTPAdapter
import os
from sqlitedict import SqliteDict
import hashlib
from spacy.tokens import Span
import json
import time
import diffbot_nlapi
import logging
import pathlib
from config import MODEL, NUMBER_URI_CANDIDATES, SOFT_COREF_CANDIDATES
# el_candidate has types,... |
#coding:utf-8
# from remote_operation.models import autologging
# 将顶级目录加入sys.path以导入上级模块(加入第一搜索优先级防止其他文件内有同名模块导致导入失败)
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
import setting
class EquipmentManager:
'''设备管理器,自动化管理在线的设备'''
def __init... |
#import sys
#input = sys.stdin.readline
def main():
N, A, B = map( int, input().split())
if A > B:
print(0)
return
if N == 1 and A != B:
print(0)
return
print( (A+B*(N-1)) - (A*(N-1)+B) + 1)
if __name__ == '__main__':
main()
|
import pyautogui
import webbrowser
import time
message= input("what message do you want to spam")
repeats= int(input("how many times do you want to send this message"))
delay= int(input("how many ms do you wanna wait inbetween messages"))
isLoaded= input("press enter when your discord is loaded")
print("... |
from djangorestframework.renderers import TemplateRenderer
class RefundProductRenderer(TemplateRenderer):
"""
Renderer which serializes to Table
"""
media_type = 'text/html'
format = 'html'
template = 'refunds/refund_products.html'
class RefundManagerRenderer(TemplateRenderer):
... |
factorial = int(input("enter a number"))
result = 1
for i in range(1,factorial +1):
result = result * i
print("the factorial of "+str(factorial)+" is : "+str(result))
|
import functools as ft
import random
from dataclasses import dataclass
from functools import partial
from math import isnan
import numpy as np
import scipy.stats as stats
from aenum import Enum, extend_enum
from scipy.spatial import distance as dist
import project.esn.utils as u
class Metrics(Enum):
pass
nans... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : testserver1.py
@Time : 2018/11/20 09:07:20
@Author : BaiYang
@Version : 1.0
@Contact : yang01.bai@horizon.ai
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc : 测试tcp的非阻塞模式1:使用非阻塞单任务为多个客户端服务。
'''
import random,os,time,sys
impo... |
from sklearn import datasets
iris = datasets.load_iris()
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.target).predict(iris.data)
print("Number of mislabeled points out of a total %d points : %d"
% (iris.data.shape[0],(iris.target != y_pred).sum()))
|
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
intervals.append(newInterval)
sorted(intervals, lambda key=i : i.start)
res = []
for interval in intervals:
if res:
if interval... |
"""Demonstration of the use of the :python:`Supernova` statistics object.
"""
import sacc
import firecrown.likelihood.gauss_family.statistic.supernova as sn
from firecrown.likelihood.gauss_family.gaussian import ConstGaussian
from firecrown.likelihood.likelihood import NamedParameters
def build_likelihood(params: Nam... |
# This file was automatically created by FeynRules 2.3.29
# Mathematica version: 10.2.0 for Linux x86 (64-bit) (July 28, 2015)
# Date: Tue 19 Dec 2017 19:54:36
from object_library import all_couplings, Coupling
from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot
GC_1 = Coupling(name =... |
# A string can be thought of as a list of characters.
favorite_fruit = "blueberry"
my_name = 'Bocy'
first_initial = my_name[0]
string_name[first_index:last_index]
favorite_fruit = 'blueberry'
>>> favorite_fruit[3:8]
'eberr'
>>> favorite_fruit[:4]
'blue'
>>> favorite_fruit[4:]
'berry'
>>> length = len(favorite... |
# Inheritance Versus Composition
# Inheritance is used to indicate that one class will get most or all of its features from a parent class
# Implicit Inheritance : implicit actions that happen when you define a function in the parent but not in the child.
# defining class called Parent
class Parent:
# defining ... |
import os
import sys
import datetime
board_log_dir = "/opt/tensorflow/tensorboard/" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
save_weight_file = f"/opt/tensorflow/checkpoints/{__file__.replace('/', '-').replace('.', '-').lstrip('-')}/weights"
anchor_sizes = [[[38.69415527948574, 13.210888737237196], [55... |
import tornado
from bson.objectid import ObjectId
from bson.json_util import dumps, loads
from slugify import slugify
from DataAccess import RequestHandlerPRS
class SuggestionHandler(tornado.web.RequestHandler):
def initialize(self, db):
"""
Initializes the instance with a mongodn database instance... |
import numpy as np
import random
import common_adversarial
# def overrideVariables(newVarList, code):
# var_code_split_index = code.find(" ")
# return ",".join(newVarList) + code[var_code_split_index:]
def init_deadcode_variable(code, variables):
return [("zpkjxq","zpkjxq")]
class AdversarialSearcher():
... |
from django.db import models
from myauth.models import *
from facilitators.models import *
from LandingPage.models import *
from django.utils import timezone
from datetime import timedelta
# Create your models here.
class Learners(models.Model):
Lid=models.AutoField(primary_key=True)
name=models.CharField(max... |
#!/usr/bin/env python
import sys
print "Hello", sys.argv[1]
print "{1} Hello {0}".format(sys.argv[1], "hey!")
print sys.argv
|
from behave.__main__ import main as behave_main
test = "./tests/domain/use_case/register/feature/user_register.feature"
behave_main(test)
|
class sports:
def sportsnews(self):
print("SportsNews1")
print("SportsNews1")
print("SportsNews1")
class movie:
def movienews(self):
print("MovieNews1")
print("MovieNews1")
print("MovieNews1")
class politics:
def politicsnews(self):
print("politicsnews")
print("politicsnews")
print("politicsnews... |
from Pages.MediaPages.LinksMedia import LinksMedia
import pytest
@pytest.allure.feature('Media')
@pytest.allure.story('Links media')
@pytest.mark.usefixtures('init_media_page')
class TestLinksMedia:
@pytest.allure.title('VDM-788 Links media - creating with internal link')
def test_links_internal_creating(sel... |
import function.getsend as gs_function
import function.check_picture as check_function
import function.cut as cut_function
import function.eight as eight_function
import base64
import json
from PIL import Image
if __name__ == '__main__':
get_data = gs_function.getpicture()#从接口获取图片
'''
get_data = {
"cha... |
from collections.abc import Iterable
from collections import Counter
from pygtrie import Trie
import pandas as pd
import numpy as np
import argparse
import logging
import os
import time
import sys
import csv
import glob
import types
import math
import re
import json
# ===-----------------------------------------------... |
import json
import logging
from core.base_handler import BaseHandler, arguments
from .model import TaskModel
from core.exception import ParametersError
maps = {
1: 'import task',
2: 'parse to type2',
3: 'parse to type1',
4: 'parse type1 error',
5: 'parse type2 error'
}
class TaskHandler(BaseHandle... |
import sys
import os
from scrapy.cmdline import execute
cur_dir_name = os.path.dirname(os.path.abspath(__file__))
print("current directory name = %s" % cur_dir_name)
sys.path.append(cur_dir_name)
# execute(["scrapy", "crawl", "leetcode"])
execute(["scrapy", "crawl", "acwing"])
|
# phi
initializing communication on patterns of phi
patterns of fractions
patterns of powers
|
# -*- coding: utf-8 -*-
import numpy
from PIL import ImageGrab
import pyautogui as mouseCtrl
import time
import copy
# USAGE
# python recognize_digits.py
# import the necessary packages
from imutils.perspective import four_point_transform
from imutils import contours
import imutils
import cv2
### Mouse Click on S... |
from django.db import models
from django.contrib.auth.models import User
#from test.test_imageop import MAX_LEN
class Link(models.Model):
url = models.URLField(unique=True)
class hs_test(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
link =... |
#!/usr/bin/python
#\file follow_q_traj2.py
#\brief Baxter: follow a joint angle trajectory
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Mar.16, 2016
#HOW TO MAKE SHAKING MOTION?
#cf. move_to_q2.py
'''
NOTE: run beforehand:
$ rosrun baxter_interface joint_trajectory_action_server.py
'''
... |
# forbeer.py
for bottle in range(99, 1, -1):
|
# path to the dataset
CSV_PATH = 'data/in/new_data.csv'
# column names of the data frame
COLS = ["HR", "O2Sat", "Temp", "SBP", "MAP", "DBP", "Resp", "EtCO2", "BaseExcess", "HCO3", "FiO2", "pH", "PaCO2", "SaO2"
,"AST", "BUN", "Alkalinephos", "Calcium", "Chloride", "Creatinine", "Bilirubin_direct", "Glucose", "L... |
import os
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", type=str, required=True,
help="subject's name")
args = vars(ap.parse_args())
if os.path.exists("photos"):
entries = os.listdir("photos")
if os.path.exists("dataset/{}".format(args["name"])):
dsfil... |
from django.db import models
# Create your models here.
class Subscriber(models.Model):
email = models.CharField(max_length=200)
active = models.BooleanField(default=True, blank = True, null = True)
date_subscribed = models.DateTimeField(auto_now_add=True)
def __str__(self):
return se... |
import numpy as np
from sklearn import preprocessing
# 1.2.2.01 均值移除
data = np.array([
[3, -1.5, 2, -5.4],
[0, 4, -0.3, 2.1],
[1, 3.3, -1.9, -4.3]
])
print("\nData = ", data)
data_standardized = preprocessing.scale(data)
print("\nScale = ", data_standardized)
print("\nMean = ", data_standardized.mean(axi... |
import os, sys
hostname = sys.argv[1]
response = os.system("ping -c 1 " + hostname + " > /dev/null 2>&1")
#and then check the response...
if response == 0:
print('up')
else:
print('dn')
|
import scrapy
from freelancer import FreelancerItem
from datetime import timedelta, date
import sys
class JobsSpider(scrapy.Spider):
name = 'jobs'
allowed_domains = ['www.freelancer.com/jobs/']
start_urls = ['https://www.freelancer.com/jobs//']
base_urls = 'https://www.freelancer.com/'
def __init... |
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .adminsResources import CategoryResource, ParentResource, KindResource, ProductResource
from .models import Category, Product, ParentCategory, Big, KindCategory
class ParentCategoryAdmin(ImportExportModelAdmin):
list_displ... |
import sys
import re
import json
class Project(object):
def __init__(self, height, width):
self.width = width
self.height = height
self.init_diagram(width, height)
def init_diagram(self, width, height):
self.diagram = [['.' for __ in range(width)] for _ in range(height)]
... |
import re
import sys
from datetime import datetime
from geolite2 import geolite2
import log_parser.db as db
from log_parser.classes import Cart
HOST = "https://all_to_the_bottom.com/"
DEFAULT_LOG = 'logs.txt'
DEFAULT_DATABASE = 'database.sqlite'
def main():
routine_start = datetime.now()
log_filename = sy... |
import esn
import imp
import signals
import random
SEED = 0
PATTERN_LENGTH = 1
PATTERN_PAUSE = 0.5
OUTPUT_PULSE_AMPLITUDE = 0.9
OUTPUT_PULSE_LENGTH = 0.1
WASHOUT_TIME = 10.0
TRAIN_TIME = 100.0
VARIABLE_MAGNITUDE = True
FALSE_PATTERN = True
CONNECTIVITY = 0.5
TEACHER_FORCING = False
USE_ORTHONORMAL_MATRIX = True
TRAINI... |
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem, engine
Base.metadata.bind = engine
session = sessionmaker(bind = engine)()
# Veggie Burgers
veggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')
for burger in veggieBurgers:
print(burger.id)
pri... |
import os
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.engine import URL
path_parent = os.path.abspath(os.curdir)
print(path_parent)
cwd = os.path.abspath('Excel Files/Master Files')
files = os.listdir(cwd)
print(files)
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'... |
# -*- coding: utf-8 -*-
## english dict
en = {}
en["id"] = "en"
en["menu_components"] = "Components"
en["menu_create_user"] = "Create user"
en["menu_home"] = "Home"
en["menu_login"] = "Login"
en["menu_logout"] = "Logout"
en["menu_reset"] = "Reset password"
en["menu_secure"] = "Secure Page"
en["menu_fyp"] = "Forgot yo... |
# _*_coding:utf-8_*_
# 创建用户 :chenzhengwei
# 创建日期 :2019/5/31 下午9:57
from rest_framework import serializers
from goods.models import Goods, GoodsCategory, Banner, GoodsImage
class GoodsImageSerializer(serializers.ModelSerializer):
class Meta:
model = GoodsImage
fields = ('image',)
class Categor... |
"""
LeetCode - Easy
"""
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
dictOfVowels = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4, 'A': 5, 'E': 6, 'I': 7, 'O': 8, 'U': 9}
arr_vowels = [None] * len(s)
index = 0
for i in... |
import unittest
import json
from trafficlightssimulator.crossing.graph import Graph
from trafficlightssimulator.crossing.pathfinder import PathFinder
class TestUnitPathFinder(unittest.TestCase):
def test_trivial_path(self):
trivial_crossing_filename = 'tests/crossing/data/trivial-crossing.json'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
import shutil
import subprocess
from argparse import ArgumentParser
import re
import string
import json
import codecs
from sherlock.config import *
from sherlock.flatten import flatten_scopes
from sherlock.features ... |
import threading
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import infinc
import time
import math
class SimpleClient :
def __init__(self, therm1, therm2) :
self.fig, self.ax = plt.subplots()
now = time.time()
self.lastTime = now
self.times = [time.strft... |
import sys
import labeler
import experiment
import collections
import time
def print_predictions(print_probs, model_path, input_file):
time_loading = time.time()
model = labeler.SequenceLabeler.load(model_path)
time_noloading = time.time()
config = model.config
predictions_cache = {}
id2label... |
import turtle
def draw_pattern1(pen):
for i in range(180):
pen.fd(100)
pen.right(30)
pen.fd(20)
pen.left(60)
pen.fd(50)
pen.right(30)
pen.penup()
pen.setposition(0, 0)
pen.pendown()
pen.right(2)
|
import arena
arena.init("oz.andrew.cmu.edu", "realm", "hello")
arena.Object(objType=arena.Shape.cube)
arena.handle_events()
|
import sys
import re
import json
import getopt
import traceback
import mysql.connector
from zipfile import ZipFile
from tqdm import tqdm
def main(argv):
ENV_DICT = {'p': 'prd', 's': 'stg', 'c': 'cert', 't': 'test'}
WORKING_DIR = "{}\..\\".format(__file__)
with open("{}\config.json".format(WORKING_DIR), '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.