text stringlengths 38 1.54M |
|---|
# Problem: Given an array of integers
# Return: The array with all zeros at the end
# Notet: Must be in-place
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
w=0
... |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0:
return ""
elif len(s) == 1:
return s
elif len(s) == 2:
if s[0] == s[1]:
return s
else: retu... |
# Homework2
import collections
# ファイル'dictionary_words.txt'を読み込み、全て小文字にしてリストdictionaryに格納
with open('dictionary_words.txt') as f:
dictionary = [s.strip().lower() for s in f.readlines()]
def find_anagram_upgraded(S):
# 各文字がいくつずつあるのか辞書にまとめる
S_count = collections.Counter(S)
# 辞書中の各単語ごとに、各文字がいくつずつあるのか数えて... |
# Converting data into RGB heatmap
import numpy as np
data = np.linspace(0,10,100)
data = np.asarray(np.meshgrid(data,data))
data = data[0]
#####
dataShape = data.shape
data = data.reshape((-1,1))
# normalizing the data
alpha = np.min(np.min(data))
beta = np.max(np.max(data))
gamma = beta -... |
"""
Created on 16 sept. 17:19 2020
@author: HaroldKS
"""
class State(object):
def __init__(self, board, latest_player=None, latest_move=None, next_player=None):
self.board = board
self._latest_player = latest_player
self._latest_move = latest_move
self._next_player = next_player... |
# -*- coding: utf-8 -*-
from Acquisition import aq_base
from plone.app.registry.testing import PLONE_APP_REGISTRY_INTEGRATION_TESTING
from plone.registry.interfaces import IRegistry
from zope.component import getUtility
import unittest2 as unittest
class TestSetup(unittest.TestCase):
layer = PLONE_APP_REGISTRY_I... |
import sys
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision
import torchvision.transforms as transforms
import wandb
from models import SimpleConvNet, MiniVGG, WideResNet, mobilenet_v2
from pytorchtools import EarlyStopping
BATCH_... |
from django.contrib import admin
from sqlModels.models import CityList
from sqlModels.models import ProvList
from sqlModels.models import CountryList
from sqlModels.models import GroupList
from sqlModels.models import IpSegDat
from sqlModels.models import NetList
from sqlModels.models import ServerGroupDat
from sqlMode... |
import psycopg2
from multiprocessing import Process, Queue
import os, signal
query1 = "INSERT INTO packet_raw (raw, time, is_training) VALUES (%s, %s, %s) RETURNING id"
query2 = "WITH row AS ({}) \
INSERT INTO packet_feat (id, {}) \
SELECT id, {} FROM row"
query3 = "WITH row AS ({}) \
I... |
import csv
def open_and_parse_retailer_extract(retailer_extract_filename):
ean_column = 15
family_group_column = 5
libelle_long_column = 17
assortment_column = 23
with open(retailer_extract_filename, "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
_ = next(csv_r... |
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import PloneSandboxLayer
from plone.app.testing import IntegrationTesting
from plone.app.testing import FunctionalTesting
from plone.app.testing import applyProfile
from zope.configuration import xmlconfig
class PolicyAcetterbeek(PloneSandboxLayer):
... |
from __future__ import absolute_import
import argparse
import sys
from urlparse import urlparse
from twisted.web import server
from twisted.internet import reactor
from structlog import get_logger
from ipd import logging
from ipd.libvirt.endpoints import TCP4LibvirtEndpoint
from ipd.metadata.utils import DomainResol... |
import os
import os.path
month_dict = {
'01':'Jan',
'02':'Feb',
'03':'Mar',
'04':'Apr',
'05':'May',
'06':'Jun',
'07':'Jul',
'08':'Aug',
'09':'Sep',
'10':'Oct',
'11':'Nov',
'12':'Dec',
}
#contains the absolute path for the directory where all the zoom recording files are
dire... |
import socket
import ast
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
email = input("Enter preferred email :")
s.sendall(email.encode())
while True:
print("\n_______________... |
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--incognito')
browser = webd... |
import feedparser
from spam_filter import SpamFilter
import re, json
class FeedAnalysis(SpamFilter):
def __init__(self, feed1, feed0, load_model):
self.load_model = load_model
if not load_model:
print("train model")
self.data_set, self.class_vec = self.load_DataSet(feed1, ... |
from sqlalchemy import create_engine
import base64
import os
from .config import db, user, enc_psswd, server
driver = 'SQL SERVER'
# if Linux
if os.name != 'nt':
driver = 'ODBC Driver 17 for SQL Server'
conn_string = f'mssql+pyodbc://{user}:{base64.b64decode(enc_psswd.encode("ascii")).decode("ascii")}@{server}/... |
def frequency(objt):
dicionario = {}
for n in objt:
keys = dicionario.keys()
if n in keys:
dicionario[n] += 1
else:
dicionario[n] = 1
return dicionario
print(frequency('google.com')) |
#!/usr/bin/env python
import rospy
import numpy as np
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
print(np.sign(-0.1)) |
#!/usr/bin/env python
# coding: utf-8
#------------------------------------------------------------------------------------------
sc
#------------------------------------------------------------------------------------------
# from __future__ import print_function
import re
import sys
from operator import add
#-... |
import bs4
import re
from datetime import date
import logging
from base_scrapper import BaseScrapper
from logger import Logger
class GetCompaniesHouse(BaseScrapper):
'''Scrape data from the Companies House website
Create an 'officer' for every member of the company listed
Thi... |
# phone_book.py
#
# Craeted by Yurij Nechaev. Copyright@ 2020. Start project at 26 april 2020.
import sys
import pickle
class Phone_Book:
def __init__(self):
self.datafile = "phone_book.dat"
self.Name = []
self.country_code = []
self.phone_number = []
def command(self):
cmd = str(input("\n Please ente... |
from plone.app.testing import PloneSandboxLayer
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import IntegrationTesting
from plone.app.testing import FunctionalTesting
from plone.testing import z2
from zope.configuration import xmlconfig
class ExampletransmogrifierLayer(PloneSandboxLayer):
... |
# coding: utf-8
"""
Knetik Platform API Documentation latest
This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
OpenAPI spec version: latest
Contact: support@knetik.com
Generated by: https://github.com/swagger-api/swagger-codeg... |
# from __future__ import print_function, unicode_literals
# from PyInquirer import prompt
#
# questions = [
# {
# 'type': 'input',
# 'name': 'first_name',
# 'message': 'What\'s your first name',
# },
# {
# 'type': 'input',
# 'name': 'age',
# 'message': r"What'... |
"""A module for working with bitmap (BMP) images."""
def write_greyscale(filename, pixel_data):
"""Writes an 8-bit greyscale BMP file.
Arguments:
filename {string} -- The name of the file to be created.
pixel_data {[2D array of numbers]} -- A recangular image stored as a sequence of rows.
... |
from flask import session
#не забывать при создании своего декоратора
from functools import wraps
def check_logged_in(func):
#для идентификации функции интерпретатором
@wraps(func)
def wrapper(*agrs, **kwargs):
if 'logged_id' in session:
return func(*agrs, **kwargs)
return 'You ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import os
import numpy as np
import pandas as pd
import face_recognition
def add_to_database (img1,img2,img3,id):
id = int(id)
database = pd.read_csv('/home/okshh/AttendanceApp/database.csv',index_col=0)
known_image = face_recognition.load_image_fil... |
a, pos, neg = input().split(), [], []
for i in a:
neg.append(int(i)) if int(i) < 0 else pos.append(int(i))
print(len(neg))
print(round(sum(pos) / len(pos), 1) if pos else "0.0") |
'''Problem 7
Write functions to find the minimum, maximum, mean, and (optionally) mode of a list of numbers.
def minimum(nums):
def maxmimum(nums):
def mean(nums):
(OPTIONAL) def mode(nums):
'''
# need a list of values, (from a end user?)
# create the list
# run it through mins, max, mean and mode - all separate... |
# https://pypi.org/project/SoundFile/
# https://www.youtube.com/watch?v=6n9ybiwnbT8
# https://pysoundfile.readthedocs.io/en/0.9.0/
# or maybe I want to use pyAudio: probably: https://people.csail.mit.edu/hubert/pyaudio/docs/
notesDict = {1: "A",
2: "A#/ Bb",
3: "B",
4: "C",
5: "C... |
def product(digits):
product = 1
for digit in digits:
product *= digit
return product
def find_largest_set(digits):
largest_set = []
current_set = []
largest_product = 0
for ch_digit in digits:
digit = int(ch_digit)
if len(largest_set) < 13:
current_set.a... |
'''
All Rights Reserved.
Copyright (c) 2017-2019, Gyrfalcon technology Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. I... |
from main.api.viewsets import ProjectViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('projects', ProjectViewSet, basename="projects") |
"""Functions for reading Runway data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import signal
import tensorflow as tf
import time
import numpy as np
from datetime import datetime
import runway as rw
import model as cl
FLAGS = tf.app.fl... |
from django.contrib import admin
from cron.models import MissionInstance, CaseInstance, CronDocumentInstance, HelpMail, CaseQuestionInstance, ChatMessage, RiddleAttempt, OperationTracker
class MissionInstanceAdmin(admin.ModelAdmin):
list_filter = ('cron', 'mission', 'progress', 'modifiedAt')
class CaseInstanceAdm... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-27 20:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app_users', '0030_auto_20170114_1610'),
('app_manag... |
from tensorflow.keras.applications import resnet50
from tensorflow.keras.layers import Dense, GlobalMaxPooling2D
from tensorflow.keras.models import Model
class ResNet:
"""
Extends the final layers of the ResNet model
"""
def __init__(self, img_dim, num_classes):
"""
:param img_dim: ex... |
(import requests json os)
(import [ConfigParser [SafeConfigParser]])
(setv parser (SafeConfigParser()))
(parser.read (os.path.join (os.path.expanduser "~") ".umbrellarc"))
(setv api_key (parser.get "weather" "api_key"))
(setv state (parser.get "weather" "state"))
(setv city (parser.get "weather" "city"))
(setv hour_c... |
import numpy as np
import matplotlib.pyplot as plt
np.set_printoptions(threshold=np.nan)
np.set_printoptions(precision=16)
#<startTeX>
# define grid mesh types
grids = {"uniform": lambda m: np.linspace(0,1,m+2),
"non-uniform": lambda m: (np.arange(0,m+2)/(m+1))**2
}
# problem parameters
def rhs(x): ... |
# Exception Handling function
def exception_handling(number1, number2, operator):
# Only digit exception
try:
int(number1)
except:
return "Error: Numbers must only contain digits."
try:
int(number2)
except:
return "Error: Numbers must only contain digits."
# More... |
import pytest
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from alibi.prototypes import ProtoSelect
from alibi.utils.kernel import EuclideanDistance
from alibi.prototypes.protoselect import cv_protoselect_euclidean
@pytest.mark.parametrize('... |
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Tuple
from pandas import DataFrame
from .exceptions import ValidationError
from .io import first_int_in_filename_key
class DataFrameValidator(ABC):
@abstractmethod
def validate(self, *, df: DataFrame):
"""Validates a sin... |
# coding=utf-8
from flask.ext import excel
from bmp.apis.base import BaseApi
from bmp.utils.user_ldap import Ldap
class Export_usersApi(BaseApi):
route = ["/users/export", "/users/export/<string:field>"]
def get(self, field=""):
result = []
field_default = {
"cn": "名",
... |
class Cliente:
def __init__(self, nome, cpf, rg, telefone, email, endereco, id_cliente=None):
self.__nome = nome
self.__cpf = cpf
self.__rg = rg
self.__telefone = telefone
self.__email = email
self.__endereco = endereco
self.__id_cliente = id_cliente
def ... |
def init_user_table_state_users(office_codes_list,db):
from models import UserParams, UserModel
state_office_codes_list = [offices for offices in office_codes_list if offices["usa_state"] != "FED"]
for state_offices in state_office_codes_list:
for office_code in state_offices["office_... |
# 근사 행렬의 가장 작은 값을 0으로 만들고자 전체 항의 값에서 작은 값을 뺍니다.
R_hat -= np.min(R_hat)
# 근사 행렬의 가장 큰 값을 5로 만들고자 5를 가장 큰 예측값(np.max(R_hat))으로 나눈 값을 곱합니다.
# 예를 들어 가장 큰 예측값이 3일 경우 3을 5로 만들기 위해서는 5/3을 곱하면 됩니다.
# 위에서 구한 값을 예측 행렬의 모든 항에 곱합니다.
R_hat *= float(5) / np.max(R_hat)
def recommend_by_user(user):
# 사용자의 ID를 입력으로 받아 그 사용자가 보지 않... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
try:
import csv
from datetime import datetime
from conf import *
from lib import logger
from lib import calcdata
except Exception as e:
print('Import error {}, check requirements.txt'.format(e))
sys.exit(1)
... |
import re
import os
import time
import shutil
import thread
import urllib2
import subprocess
from gui import settings
from gui import update_ui
from PyQt4 import QtGui,QtCore
class update_class(QtGui.QDialog,update_ui.Ui_Dialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self... |
"""Decorators."""
# region #-- imports --#
from __future__ import annotations
import functools
from .const import DiscoverMode
from .exceptions import HDHomeRunDeviceHasNoSession, HDHomeRunDeviceMustBeHTTP
# endregion
def needs_http(func):
"""Ensure that the device used the HTTP discovery method."""
@fun... |
def solution(w,h):
answer=0
if (w == h):
answer = w * h - w
return w*h-w
for i in range(min(w,h),0,-1):
if(w%i==0 and h%i==0):
answer=w*h-(w+h-i)
break
return answer
w=8
h=12
print(solution(w,h))
'''
문제 설명
가로 길이가 Wcm, 세로 길이가 Hcm인 직사각형 종이가 있습니다. 종이에... |
import numpy
def addition_using_numpy(listA,listB):
numpyArrayA = numpy.array(listA)
numpyArrayB = numpy.array(listB)
return numpyArrayA + numpyArrayB
def addition_of_normal_lists(listA,listB):
return [ x + y for x,y in zip(listA,listB)]
def addition_using_for_loops(listA,listB):
C=[]
for x... |
import random
import math
from logmodule import simLog as log
from collections import deque
class Simulation():
def __init__(self, TICKS, Lambda, L, C, K=None, tick_length=0.00001):
# Input Parameters
self.TICKS = TICKS
# Tick length - SECONDS / TICK
self.tick_length = tick_length
... |
"""
File created by Emili Zubillaga
CubaTronik Project 2017
"""
# Imported libraries into project
import serial
import serial.tools.list_ports
import time
import logging
EOL = "\n"
ser = serial.Serial()
class SerialCom:
def __init__(self):
pass
def open(self, port, baud, timeout):
... |
from django.db import models
from django_extensions.db.models import TimeStampedModel
from django_extensions.db.fields import AutoSlugField
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Country(models.Model):
title = models.CharField(_('title'), max_length=255)
slug... |
# Prompts the user to input an integer N at least equal to 10 and computes N!
# in three different ways.
import sys
from math import factorial
# Insert your code here
num = input('Input a nonnegative integer:')
try:
num = int(num)
if num < 0:
print('Incorrect input, giving up.')
else:
f... |
#coding=utf-8
import torch
from torch.autograd import Variable
from torch.backends import cudnn
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import numpy as np
import pprint
import os
import argparse
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
# f... |
class Persona:
def __init__(self, nombre, apellido, color_cabello, color_ojos, altura, sexo,edad):
self.nombre=nombre
self.apellido=apellido
self.color_cabello=color_cabello
self.color_ojos=color_ojos
self.altura=altura
self.sexo=sexo
self.edad=edad
... |
def bisection(a,b,function, tol, const): #Returns x: functionx(x) = const. [a,b] is the interval, tol is the accuracy
while (b-a)/2 > tol:
c = (a+b)/2
if function(c) == 0:
return c
if (function(c)-const)*(function(a)-const) < 0:
b = c
else:
a = c
return (a+b)/2
#Fixed point interation a... |
import matplotlib.pyplot as plt
from scipy import misc, ndimage
face=misc.face()
plt.imshow(face)
plt.show()
|
for t in range(int(input())):
n, k =map(int,input().split())
a = list(map(int,input().split()))
a.sort()
i = 0
j = n-1
flag = 'No'
while(i<j):
sums=a[i]+a[j]
if(sums==k):
flag = 'Yes'
break
elif(sums>k):
j=j-1
else:
... |
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}
dict4 = dict(dic1)
dict4.update(dic2)
dict4.update(dic3)
print(dict4)
|
# -*- coding: utf-8 -*-
from lettuce import step, world
from nose.tools import assert_equals
from gate.utils import config_files as utils
from settings import NGINX_CONF_FILE
from home.models import InstalledApp as App
TEST_FILE = "./utils/features/test"
@step(u'I have a test file open with (\d) lines')
def given_... |
#Zachary Palladino
#This program is a quiz game that gives the user multiple choice questions
print("Hello! Welcome to my quiz game! \nI am going to give you different multiple choice questions and you have to answer them correctly")
print(" ")
print("Question 1")
a=input("What is the derivative of the functio... |
import numpy as np
_coorddict = dict(west_east = 'longitude', south_north = 'latitude', Time = 'time', bottom_top = 'altitude',
west_east_stag = 'longitude', south_north_stag = 'latitude', Time_stag = 'time', bottom_top_stag = 'altitude',)
def add_cf_from_wrfioapi(ifile):
try:
for invark, ... |
import os
filepathen = './en'
filelisten = os.listdir(filepathen)
filelisten = sorted(filelisten)
print(filelisten)
filepathcn = './cn'
filelistcn = os.listdir(filepathcn)
filelistcn = sorted(filelistcn)
print(filelistcn)
print(len(filelistcn), len(filelisten))
cnfile = ""
for filename in filelistcn:
with open('... |
"""Test for my functions.
Note: because these are 'empty' functions (return None), here we just test
that the functions execute, and return None, as expected.
"""
from my_module.functions import File, FileSystem
file_system = FileSystem()
file_system.mkdir("/")
file_system.mkdir("/d1/d2/f1")
file_system.addContent... |
# List
# Built in function
# list.pop(index)
num = [1,2,3] # List of number
num.pop(0) # Remove the item in that index
print(num) # Output = [2,3]
print()
num = [1,2,3] # List of number
num.pop() # Remove the last item in that list if there is no in... |
import os.path
import shutil
from datetime import datetime
import json
from enum import Enum
from build_scripts import BASE_DIR, SITE_DIR
class PageType(Enum):
PAGE = "page"
POST = "post"
class Content:
def __init__(self, id="content", dir=None):
self.id = id
if ... |
#!/usr/bin/python
#coding:utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django import forms
from blog.models import Redis_Count,Storage_Monitor
fr... |
from erm.core.models import *
from erm.datamanager.models import *
from erm.lib.misc_utils import *
from erm.lib.api import ApiError, ERROR_CODES
from erm.core.entity_manager import *
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.query import EmptyQuerySet
from django.db import connection... |
# coding: utf-8
# In[27]:
name= input('Enter First and Last Name ')
l = name.split(' ')
l=l[::-1]
str1 = ' '.join(l)
print(str1)
# In[15]:
list1 = ['1', '2', '3']
str1 = ''.join(list1)
print(str1)
# In[10]:
mylist = ['spam', 'ham', 'eggs']
print ', '.join(mylist)
|
# -*- coding: utf-8 -*-
from platformcode import logger
from core.item import Item
from core import httptools, scrapertools, servertools, tmdb
import re
host = 'https://seriesflix.to/'
perpage = 24 # preferiblemente un múltiplo de los elementos que salen en la web (6x8=48) para que la subpaginación interna ... |
'''
Created on 2020-10-15 08:38:20
Last modified on 2020-10-15 09:00:41
@author: L. F. Pereira (lfpereira@fe.up.pt))
'''
# imports
# third-party
import numpy as np
from f3dasm.abaqus.geometry.rve import RVE2D
from f3dasm.abaqus.geometry.utils import transform_point
# object definition
class BertoldiRVE(RVE2D):
... |
import math
import random
from datetime import datetime, timezone
"""
Custom cmd-argument validation function.
The --help output produced by the argparse module
when choices for each argument were provided was
too ugly and difficult to handle for multi-param
arguments. Therefore, we only use the argparse
module for ... |
from datetime import datetime
strDateFormat = "%Y-%m-%d"
dYearDay = 365.2425
## Example 1
## strDate_01 = "2019-02-10"
## strDate_02 = "2022-11-01"
## Example 2
## strDate_01 = "2020-09-15"
## strDate_02 = "2022-03-29"
## Example 3
## strDate_01 = "2019-12-31"
## strDate_02 = "2020-01-01"
... |
#形近字字符集
import os
import shutil
wholesetdir="../ocr-dataset/hwdb/train/"
likesetdir="../ocr-dataset/hwdb/minitrain/"
likeset="日目百白旦赛塞寒桌卓焯倬淖棹琸晫啅悼绰逴婥直值置植殖者都赌堵睹绪猪诸煮署督暑躇真慎填"
for ch in likeset:
if (os.path.exists(wholesetdir+ch)):
shutil.copytree(wholesetdir+ch, likesetdir+ch)
|
import boto3
# AWS clients
dynamodb = boto3.client('dynamodb')
def close(session_attributes, fulfillment_state, message):
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
M3WebsiteParser.py
M3 webのサークルリストをcsvに変換するスクリプト
"""
from HTMLParser import HTMLParser
import urllib2
import sys
import codecs
class M3CircleListParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.is_a = False
self.is_t... |
from firebase import firebase
from datetime import datetime
from testLCD import DisplayLCD
firebase = firebase.FirebaseApplication("https://pythondbtest-d6805.firebaseio.com/", None)
def goToFireBase(data_string_firebase):
now = datetime.now()
currentDT = datetime.now()
other_data = {
'Time' ... |
from flask import Flask, render_template
a =Flask(__name__)
@a.route('/')
def index():
return render_template('user.html', name ="shawn", email = "google.com", times= 10)
a.run(debug = True) |
import os
import sys
jobdirs = []
prefix = sys.argv[1]
for thing in os.listdir('./'):
if os.path.isdir(thing) and thing[:len(prefix)]==prefix:
jobdirs.append(thing)
for job_dir in jobdirs:
os.system('cd {0}; gnuplot {1}'.format(job_dir, 'plot.gnu'))
|
from django.utils import timezone
from django.db.models import Prefetch
#
from applications.producto.models import Camiseta, Estampa
#
from .models import Sale, SaleDetail, CarShop
def procesar_venta(self, **params_venta):
# recupera la lista de productos en carrtio
productos_en_car = CarShop.objects.all()
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 15:53:24 2020
@author: svc_ccg
"""
import pandas as pd
import numpy as np
import logging
#This is the function that tries to find the insertion start and end times from the logged motor movements
def findInsertionStartStop(df, ztolerance=50):
''' Input... |
'''
A serial commonly regular expressions is listed below. It includes:
* Regular float number, like ``1.0``, ``0.9``
* Scientific float number, like ``1.0e4``
* Float number with percentage, like ``93.75%``
'''
import re
# Used to match regular float number
# For example: -0.1
reFloatNumber = re.compile('... |
# -*- coding: utf-8 -*-
{
"name": "DBA Timesheet Customization",
"author": "HashMicro/ Kunal",
"version": "1.0",
"website": "www.hashmicro.com",
"category": "timesheet",
"depends": ['hr_timesheet_sheet','hr_timesheet_invoice','hr_timesheet','dba_ar_modify','dba_expense', 'account_analytic_analys... |
def decodif(frameBinar):
#f = open("date.txt","r")
#s=[]
#while f.mode == 'r':
# f1 = f.readlines()
for x in f1:
print("IN")
#print([ bin(ord(ch))[2:].zfill(8) for ch in x ])
s=[ bin(ord(ch))[2:].zfill(8) for ch in x ]
#print(s)
detec=s[6]
for k in range (1,6):
#print(s[k])
#print(s[6]... |
# Subplots
'''
Subplots are required when we want to show two or more plots in same figure.
We can do it in two ways using two slightly different methods.
'''
# method 1
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# function to generate coordinates
def creat_plot(ptype):
# setting the... |
from tqdm import tqdm
import csv
import re
import argparse
import os
from collections import defaultdict
def get_movies_db(path):
with open(path, "r") as f:
reader = csv.reader(f)
id2movie = {}
for row in reader:
if row[0] != "index":
# separate the title into m... |
# A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost
# unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the
# digits in each number is only 1.
#
# Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum... |
# # importing the settings.py file so that we can use some of the settings.
#
# # importing some helper methods
# from apps.api.v1.utils.helpers import *
#
# # requests is module to make http requests.
#
# # we will use json to format our data before sending it to kazoo api.
#
# import pusher
#
# # get default system s... |
from cms.app_base import CMSApp
from django.utils.translation import ugettext_lazy as _
from cms.apphook_pool import apphook_pool
class WindbergRegistrationApp(CMSApp):
name = _('Registration App')
urls = ['windberg_register.urls']
apphook_pool.register(WindbergRegistrationApp) |
import tkinter as tk
import tkinter.font as tkFont
import os
import random
from tkinter.filedialog import *
from tkinter.messagebox import *
from PIL import Image #pour le score
from PIL import ImageTk #pour le score
#Romane GENSE
def selection(event):
#fonction qui séléctionne l'objet à déplacer grâc... |
import random
def game_loop():
while True:
print(paragraph_fill(paragraph_choice()))
print('Would you like to play again? Y/N')
user_in = input()
if user_in == 'N':
break
def paragraph_choice():
paragraphs = ['''
This morning I woke up to a very /1Adjective thing... |
'''Usage
python train_wavegan.py train ./train \--data_dir ./data/customdataset
Ref
https://github.com/chrisdonahue/wavegan/blob/master/train_wavegan.py
'''
import os
import time
import numpy as np
import pytorch
import dataloader
from wavegan import WaveGANGenerator, WaveGANDiscriminator
'''
Constants
'''
_F... |
from pymongo import MongoClient
from bs4 import BeautifulSoup as bs
import requests
from pprint import pprint
print('введите название вакансии:')
b = str(input())
print('введите желаемую зарплату:')
price = int(input())
client = MongoClient('localhost', 27017)
db = client['vacancies_db']
vaccol = db.vacanci... |
#!~/anaconda3/bin/python
import os
import pickle
from cg_openmm.simulation.rep_exch import *
from openmm import unit
# This example demonstrates how to post-process OpenMM replica exchange simulation energies,
# and generate individual dcd trajectories from the .nc output files.
# Replica exchange analysis data
ana... |
from mpi4py import MPI
import numpy as np
from datetime import datetime
comm = MPI.COMM_WORLD
world = comm.size
rank = comm.Get_rank()
a = np.random.randint(10, size=(5, 5))
if rank == 0:
b = np.random.randint(10, size=(5, 5))
start = datetime.now()
else:
b = None
b = comm.bcast(b, root=0)
if world == ... |
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
data = pd.read_table('crm_order_item_flow.txt', header=None)
data.columns = ['uid', 'item_id', 'brand_id', 'cate_id', 'time_id']
uid = pd.DataFrame(data.drop_duplicates(['uid'])['uid'])
Train_uid, Test_uid = train_test_split... |
import logging
logger = logging.getLogger('console')
# redirect uncaught exceptions to the logger
def log_uncaught_exceptions(exctype, value, tb,logger=logger):
logger.error('Uncaught Exception')
logger.error('Type: ' + str(exctype))
logger.error('Value:' + str(value))
logger.error('Traceback:',exc_info=(e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.