text stringlengths 8 6.05M |
|---|
#!usr/bin/env python2
import numpy as np
from matplotlib import pyplot as plt
# Paso = (max-min)/(N) -> N=2^B
#A = 1.2 # amplitude of signal
# quantization stepsize
#n = 2000 # number of samples
#x -> entrada
#Q ->paso del cuantizador
#N -> numero de niveles
#B -> numero de bits
#xq = floor(x*(2^B-1)/(max{x}-min{x... |
import redis
def get_from_db(key):
client = redis.StrictRedis()
flight_data = client.get(key)
return flight_data
def add_to_db(key, value):
client = redis.StrictRedis()
client.set(key, value)
|
#
# @lc app=leetcode.cn id=121 lang=python3
#
# [121] 买卖股票的最佳时机
#
# @lc code=start
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# """
# DP table
# """
# n = len(prices)
# dp = [[None, None]] * n
# for i in range(n):
# if i == 0:
... |
class Node:
def init(self, val):
self.right = None
self.data = val
self.left = None
# your task is to complete this function
# function should print the level order traversal of the binary tree in spiral order
# Note: You aren't required to print a new line after every test case
def printSp... |
urunler = {
'Elma': {
'fiyat': 5,
'miktar': 3
},
'Armut': {
'fiyat': 7,
'miktar': 9
},
'Mandalina': {
'fiyat': 4,
'miktar': 6
},
'Kiraz': {
'fiyat': 8,
'miktar': 1
},
}
cebimdekiPara = 100
sepet = {}
def sepeteUrunEkle(ur... |
"""API v2 tests."""
from django.urls import reverse
from modoboa.lib.tests import ModoAPITestCase
class TransportViewSetTestCase(ModoAPITestCase):
def test_list(self):
url = reverse("v2:transport-list")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
backends... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# We are given an array A of positive integers, and two positive integers L and R (L <= R).
# Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element
# in that subarray is at least L and at most R.
# Example :
# Input:
# A = [... |
import time
from zimsoap import utils
from zimsoap import zobjects
from zimsoap.rest import AdminRESTClient
from zimsoap.exceptions import DomainHasNoPreAuthKey
from zimsoap.client import ZimbraAbstractClient
from . import methods
class ZimbraAdminClient(
ZimbraAbstractClient,
methods.accounts.Metho... |
from unittest import TestCase, main
from tempfile import gettempdir
import svtools.lsort as lsort
class Test_lsort(TestCase):
def test_parser(self):
parser = lsort.command_parser()
args = parser.parse_args('file1 file2 file3'.split())
self.assertEqual(args.vcf_files, ['file1', 'file2', 'fi... |
limite = int(input("Ingrese el limite fraccionario de pi"))
cont=0
pi=0
for l in range (1, limite+1, 2):
frac = 4/l
cont=cont+1
if cont%2==1:
pi=pi+frac
else:
pi=pi-frac
print(pi)
print(pi)
|
grocery_list = ["Fish", "tomato", 'Apples']
print("tomato" in grocery_list)
grocery_dict = {"fish":1, "tomato":6, 'Apples':3}
print("tomato" in grocery_dict.keys()) # También puede ser: ("tomato" in grocery_dict), pero sólo busca en la parte de 'keys'
|
#!/usr/bin/python
# Copyright (c) 2018 Thanos Poulos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... |
import sys
import numpy as np
log_file = sys.argv[1]
n_files = int(sys.argv[2])
fds = [0]*n_files
cn_file = 0
ts = {}
lustre_dir = "/global/cscratch1/sd/monarin/testxtc2/hsd/smalldata"
bb_dir = "/var/opt/cray/dws/mounts/batch/psana2_hsd_16718487_striped_scratch/hsd/smalldata"
with open(sys.argv[1], "r") as f:
f... |
t = int(input())
l = list(map(int, input().split(' ')))
cont = 0
for c in range(len(l)):
if l[c] == t:
cont += 1
print(cont) |
from vcenter_connect import get_all_disknumbers,remove_disc
virtualmachine_name = raw_input("enter virtual machine name:")
all_disks_numbers = get_all_disknumbers(virtualmachine_name)
print "All disks number avaliable:"
print ",".join(map(str,all_disks_numbers))
selected_disk_number = int(raw_input("Selec a disk number... |
# created by xibai
import tkinter as tk
window = tk.Tk()
window.title('JJ GUI')
window.geometry('500x300')
var = tk.StringVar()
var.set('你是猪头')
l = tk.Label(window,textvariable=var,bg='green',font=('Arial,12'),width=60,height=1)
l.pack()
on_hit = False
def hit_me():
global on_hit
if on_hit == False:
v... |
import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateCryptoCoinone(object):
"""
"""
def __init__(self):
"""
"""
... |
import sys
import os
f = open("C:/Users/user/Documents/python/atcoder/ABC053/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
import math
x = int(input())
temp = x // 11
move = temp * 2
if x % 11 == 0:
pass
else:
move += 1
if x % 11 > 6:
move += 1
print(move)
|
import DivisibleBy
## This is the universal code used by both addition and subtraction
## It gets all necessary info to solve either problem
## NOTE: This is not a standalone program, just contains info to be called elsewhere
## Gets the coeffecients of the quadratic in the order of ax^2, bx, c
def GetNumbers():
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 21:14:41 2018
@author: PPAGACZ
"""
from packets import *
class ForecastPipe(IPipe):
def runFilter(self):
if(ForecastPipe.checkConditions(self.data)):
ForecastFilter.process(self)
def checkConditions(data):
return True |
from django.utils import timezone
from borg_utils.singleton import SingletonMetaclass,Singleton
class PublishStatusMetaclass(SingletonMetaclass):
"""
A metaclass for Publish Status class
"""
_classes = []
def __init__(cls,name,base,dct):
"""
cache all publish status classes.
... |
import bpy
import math
from utils import printf, start, end
def insert():
C = bpy.context
cl = C.scene.cursor_location
start()
x = math.trunc(cl[0])
y = math.trunc(cl[1])
printf("x")
printf(x)
printf(y)
end()
# insert()
|
''' Retrieve publications from Scopus APIs and add them to the database.
'''
import os
import sys
import requests
import time
import xml.etree.ElementTree as et
import re
import json
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalch... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import logout
from .forms import AdminKelolaRegistrationForm
from perwakilan_penghuni.forms import PerwakilanPenghuniForm
from account.forms import RegisterForm, LoginForm
from django.db import transaction
from perwakilan_penghuni... |
line = 'asdf fjdk; afed, fjek,asdf, foo'
import re
print re.split(r'[;,\s]\s*', line)
fields = re.split(r'(;|,|\s)\s*', line)
print fields
values = fields[::2]
print values
delimiters = fields[1::2] + ['']
print delimiters
print ''.join(v+d for v,d in zip(values, delimiters))
print re.split(r'(?:,|;|\s)\s*... |
from pyalgotrade.broker.backtesting import TradePercentage
from pyalgotrade.broker.fillstrategy import DefaultStrategy
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
class mystrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):... |
import re
import logging
logger = logging.getLogger(__name__)
class ParserException(BaseException):
pass
class IrcMessage:
prefix = None
command = None
params = []
def __str__(self):
ret = ""
if self.prefix is not None:
ret += ":%s " % self.prefix
ret += "%s "... |
from __future__ import division
import numpy as np
import numpy.random as npr
from svae.util import add, scale, rand_dir_like, contract
from svae.svae import make_gradfun
EPS, RTOL, ATOL = 1e-4, 1e-4, 1e-6
def grad_check(fun, gradfun, arg, eps=EPS, rtol=RTOL, atol=ATOL, rng=None):
def scalar_nd(f, x, eps):
... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that bundles that have no 'sources' (pure resource containers) work.
"""
import TestGyp
import sys
if sys.platform == 'darwi... |
from django.core.management import BaseCommand
import time
from random import randint
from channels import Group
from threading import Thread, Lock, active_count
import socket
from django.http import HttpResponse
from django.shortcuts import render,redirect,HttpResponseRedirect,HttpResponse
#from django.contrib.ses... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# 下面理清楚一些数学概念:
# 因数:一个数,如果存在可以被它整除的数,则这些数都是该数的因数。
# 规定0没有因数,1的因数是1,其他的比如4的因数有“1”、“2”、“4
# 因子:一个数,如果存在可以被它整除的数且这些数不包括它本身,则这些书都是该数的因子。
# 规定0没有因子,1的因子是1,其他的比如4的因子有“1”、“2”
# 质因子:一个数,如果可以分解成n个质数相乘,则n个质数成为该数的质因子。
# 规定0和1没有质因子,质数的质因子为其本身
# 完数:一个数的因子之和等于它本身,则该数为完数。
# 1. Given a n... |
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
ping = discord.Embed(
color = 0xffff00,
description = f'⏳ | {round(self.client.latency * 1000)... |
import requests
import json
def received_message(event, token):
sender_id = event['sender']['id']
recipient_id = event['recipient']['id']
time_message = event['timestamp']
message = event['message']
text = message['text']
typing = typing_message(sender_id)
call_send_API(typi... |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import click
from wadeb... |
# Generated by Django 2.1.4 on 2018-12-19 11:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='contacts',
name='created_time',
... |
# Alarms are a special sort of signal, where your program asks the OS to notify it
# after some period of time has elapsed.
import signal
import time
def received_alarm(signum, stack):
print 'Alarm:', time.ctime()
# Call received_alarm in 2 seconds.
signal.signal(signal.SIGALRM, received_alarm)
signal.alarm(2)
... |
#encoding=utf-8
import cv2
import numpy as ny #别名
img = cv2.imread("./images/bear.jpg")
w = img.shape[0]
h = img.shape[1]
#平移图像
#创建一个变换矩阵
#平移:x轴正方向(1,0) 100, y轴正方向(0,1)50
M = ny.float32([[1, 0, 100], [0, 1, 50]])
dst = cv2.warpAffine(img, M, (w, h))#平移图像
cv2.imshow("Hello", dst)
cv2.imshow("HelloCV", img)
#旋转图像
#创建旋转... |
def format_solution(d, p, s):
return f"Day {d:1} (part {p}):\t{s}"
|
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from sklearn.metrics import r2_score
y = np.array([2.632214144151, 3.272355, 2.7607268, 3.4447693, 3.6799583, 3.5055826, 2.9330038, 2.8568107, 3.3276575, 2.8926306, 2.7319663, 3.5326295, 3.160792, 2.8481617, 3.2420505, 3.0637345, 3.0162536,... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join
class ProductLoader(ItemLoader):
default_out... |
from collections import Counter
from collections import OrderedDict
from sklearn.model_selection import train_test_split
player_reference = {}
pattern_reference = OrderedDict()
# data generation
print("Data generation")
x_train = []
x_test = []
y_train = []
y_test = []
with open('data/trainlight.csv', 'r') as file:... |
"""
stringjumble.py
Author: Eamon
Credit: stack overflow
Assignment:string jumble
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With wo... |
import numpy as np
from sklearn.tree import DecisionTreeClassifier
import pandas as pn
data = pn.read_csv('./DATA/titanic.csv', index_col='PassengerId')
data_for_tree = pn.DataFrame(data, columns=['Pclass','Fare','Age','Sex','Survived']).dropna()
# data.dropna()
surv = pn.DataFrame(data_for_tree, columns=['Survived'... |
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseForbidden
from list_app.models import Entry, List
from list_app.forms import EntryForm, ListForm
from django.contrib.auth.models import User
from django.contrib.auth.decorator... |
from rest_framework import serializers
from .models import Users, Blog, Comment
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ('firstname', 'lastname', 'emailid', 'mobile', 'username', 'password',
'security_question','security_answer')
clas... |
from django.db import models
# Create your models here.
class Produto (models.Model):
nome = models.CharField("Nome", max_length=100, unique=True)
def __str__(self):
return self.nome
class InformacaoPedido (models.Model):
cidade = models.CharField("Cidade", max_length=500)
quantidadePessoa ... |
from flask_restplus import Resource, Api
from .. import api
from server.operation.register import Register
import server.event as event
import server.operation as operation
import server.document as document
ns = api.namespace('RestoreList', description="列表")
class ExportRestoreList(Resource):
"""列表模块
... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
import data.climate.window_generator as wg
# https://www.tensorflow.org/tutorials/structured_data/time_series
mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False
train_df = pd.read_csv("jena_cli... |
from agagd_core.models import Chapters, Country, Game, Member, MembersRegions, Membership
from django.contrib import admin
class MemberAdmin(admin.ModelAdmin):
list_display = ('member_id', 'full_name', 'join_date', 'chapter', 'chapter_id')
admin.site.register(Chapters)
admin.site.register(Country)
admin.site.reg... |
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
qomolo_robot_id = os.environ.get("QOMOLO_ROBOT_ID","id")
def generate_launch_description():
ld = LaunchDescription()
config = os.path.join(
get_package_... |
from flask import Flask
from flask import jsonify
import requests
app = Flask(__name__)
# This is for Elastic Beanstalk
application = app
@app.route('/')
def index():
return 'Hello, world'
@app.route('/weather')
def weather():
response = requests.get('http://wttr.in/Vantaa?format=j1')
return respons... |
import datetime
import string
import random
from django.contrib.auth.models import User
from django.db.models import Model, CharField, ForeignKey, CASCADE, IntegerField, DateField, TextField, ImageField, \
OneToOneField, BooleanField
from image_cropping import ImageRatioField
def random_generator(size=16, chars=... |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from api import views
router = DefaultRouter()
router.register(r'blog', views.BlogViewSet, base_name='blog')
urlpatterns = [
url(r'^', include(router.urls)),
]
|
def function(a, b, c):
print(a, b, c)
function(1, 2, 3)
function(c=6, a=4, b=5) # arguments matching by name
|
"""
Написать функцию is_prime, принимающую 1 аргумент — число от 2 до 1000,
и возвращающую True, если оно простое, и False - иначе.
"""
def is_prime(x):
if x < 2 or x > 1000:
return f'Number is out of range from 2 to 1000'
else:
for i in range(2, x):
if x % i == 0:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 1 14:05:28 2019
@author: Xi Yu
"""
import tensorflow as tf
import numpy as np
import pandas as pd
#import tensorflow.contrib.eager as tfe
print(tf.__version__)
print(tf.__git_version__)
tf.compat.v1.enable_eager_execution()
#%%
# set data dimensions
K = 3
V = 5
D = ... |
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
print("Some implementation!")
def display_values(self):
pass
def walk(self):
pass
def jump(self):
pass
class Dog(Animal):
def __init__(self):
self.name = ... |
class Book:
def __init__(self, year, name, author):
self.year = year
self.name = name
self.author = author
self.reviews = []
def __eq__(self, other):
if [self.year, self.name, self.author] == [other.year, other.name, other.author]:
print(True)
else:
... |
#!/usr/bin/env python
import os, sys, os.path
from collections import defaultdict
from pixelterm.xtermcolors import xterm_colors
from PIL import Image, PngImagePlugin
try:
import re2 as re
except:
import re
def parse_escape_sequence(seq):
codes = list(map(int, seq[2:-1].split(';')))
fg, bg = None, None
i = 0
wh... |
from common.run_method import RunMethod
import allure
@allure.step("极师通/获取学生所有班级")
def student_class_getAllClass_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:retur... |
# coding=utf-8
import os
import sys
import unittest
from time import sleep
from selenium import webdriver
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.initData import init
from webTest_pro.common.model.baseActionAdd import user_login, add_model
from webTest_pro.common.model.baseActionModify... |
# Optional: debug mode
DEBUG = True
TEMPLATE_DEBUG = True
# Location of routes (main app.py file)
ROOT_URLCONF = 'app'
# Secret key is required by Django
SECRET_KEY = 'r*ll9mlx=d)cko4gp03ms%+tmq51+dlyo06gl2$xbt$w=7$=_8'
|
import tkinter as tk
from tkinter import *
from tkinter import ttk
import cfg_common
import cls_CalibPH
LARGE_FONT= ("Verdana", 12)
class PageAnalogProbes(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.parent = parent
self.controller = controller
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Importing packages
import pandas as pd
import numpy as np
import seaborn as sns
import textstat as ts
from nltk.corpus import stopwords
from textblob import Word
from textblob import TextBlob
stop = stopwords.words('english')
# In[2]:
#Importing Raw Data
reviews_d... |
class Solution(object):
def reverseString(self, s):
up = 0
down = len(s) - 1
sList = list(s)
while up <= down:
tmp = sList[up]
sList[up] = sList[down]
sList[down] = tmp
up += 1
down -= 1
return ''.join(sList)
... |
from scipy import interpolate
from common import *
import csv
class dive_record_set(object):
"""
Provide an interface to retrieve a set of depth / temp records and do
stuff with them. If the given start and end datetime objects are naive,
we'll assume they're in the local time zone as defined in config... |
"""
Generate some stats data so that if we run mypaas.stats locally,
we have some data to look at, even if it's fake :)
"""
import os
import time
import random
import datetime
from mypaas.stats import Monitor
def generate_test_data(filename, ndays=10):
"""Generate test data to test the get_data() and website.""... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
import argparse
import time
import os
from six.moves import cPickle
from model import Model
from utils import TextLoader,NumpyLoader
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--save_dir', type=str, def... |
from sympy.ntheory import totient
limit = 1000001
solution = 0
print(sum(totient(n) for n in range(2, limit))) |
# coding=utf-8
import random
import shutil
import sys
import tempfile
import unittest
from threading import Thread
import uuid
from persistqueue.sqlackqueue import (
SQLiteAckQueue,
FILOSQLiteAckQueue,
UniqueAckQ,
)
from persistqueue import Empty
class SQLite3AckQueueTest(unittest.TestCase):
def set... |
#File Name:- Disk_Check.py
#Service Name:- Disk size
#Purpose: To return the status of Disk Check Qualification criteria.
#Author Name: Roy Bright
#Create Date: 2/Apr/2018
#Modifed By:- Roy Bright
#Last Modify Date: 2/Apr/2019
#Current Version: 1.1
#Summary of Last Change: N/A
#Arguments: Drive/File system name and Min... |
import gen_strat
import strategy
import util
#util.saveProcessedFromYahoo.download = False
#where = gen_strat.historical()
strategy.multi("history")
|
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by... |
import pytest
from ethereum.tools.tester import TransactionFailed
def test_submit_block_valid_key_should_succeed(ethtester, testlang):
submitter = testlang.accounts[0]
assert testlang.root_chain.nextChildBlock() == 1000
blknum = testlang.submit_block([], submitter)
block_info = testlang.root_chain.bl... |
"""src URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
import random,string
field = string.letters
def getletters():
return ''.join(random.sample(field,4))
def connection():
return '-'.join(getletters() for i in range(4))
def generate(n):
for i in range(n):
yield connection()
print(generate(20))
with open('/Users/jiawei/python/py/yanzheng.txt',... |
#!/usr/bin/env python2
import tempfile, subprocess, shutil
from xmlinterface import JobPraser
class Editor(object):
@staticmethod
def edit_commands(filepath):
job = JobPraser(filepath)
#List with files objects
tempfiles = []
#List with files names for vim
templist = [... |
from restic.repo import Repo
from restic.snapshot import Snapshot
from restic.core import version, self_update, generate
from restic.config import restic_bin
from restic.test import test_all
|
# print(run.meta)
# run.kmeans(channels=['FSC-A', 'SSC-A', 'FSC-H', 'FSC-W', 'SSC-H', 'SSC-W', 'FITC-A', 'FITC-H', 'PE-A', 'PE-H', 'PE-Cy7-A', 'PE-Cy7-H', 'UV1-A', 'UV1-H', 'UV2-A', 'UV2-H', 'APC-Cy7-A', 'APC-Cy7-H', 'APC-A', 'APC-H', 'PE-Cy5-A', 'PE-Cy5-H'], logx=False, logy=True, transpose=False, nclusters=5)
# ru... |
from pywinauto.application import Application
from PIL import Image
from pywinauto import win32structures
import os
class imgproc():
def __init__(self):
self.nowdir = os.getcwd()
def capture(cls):
im = self.dlg.capture_as_image()
im.save("{}\\temp\\main.png".format(self.... |
import random
from random import choice
class Ability:
def __init__(self, name, attackStrength):
self.name = name
self.attackStrength = attackStrength
pass
def attack(self):
randomAttack = random.randint(0, self.attackStrength)
return randomAttack
if __name__ == "... |
#!/usr/bin/env python
"""
@author: Jean-Lou Dupont
"""
__author__ = "Jean-Lou Dupont"
__email = "python (at) jldupont.com"
__fileid = "$Id$"
import os
import sys
from pyjld.os import safe_mkdir, copyFiles, copyUpdatedFiles, safe_copytree
from pyjld.builder import copyEggs, makeEggReleaseDir
from py... |
# coding: utf-8
####################################
#RSSを取得する例
####################################
#.NET Frameworkのクラスライブラリを使う宣言
import clr
#XML関連の参照設定とインポート
clr.AddReference("System.Xml")
from System.Xml import *
#RSSを取得
doc = XmlDocument()
doc.Load("http://codezine.jp/rss/new/20/index.xml")
#デー... |
'''
Once decided which asset, if the asset is worth it and how much to buy/sell,
Theses strategies decide the best way to implement the action
'''
import pandas as pd
from src.functions.trends import moving_average
def twap(df):
'''
time weighted average price
effect, reduce impact on market
avg(open,c... |
from karbar.models import *
class Madadkar(MyUser):
employment_date = models.DateField(null=True, blank=True)
class Receipt(models.Model):
madadkar = models.ForeignKey(Madadkar, on_delete=models.CASCADE)
hamyar = models.ForeignKey('hamyar.Hamyar', on_delete=models.CASCADE)
madadju = models.ForeignKe... |
from .package_analyzer import PackageAnalyzer
from xml.etree.cElementTree import parse
from xml.etree.cElementTree import ParseError
import os
import logging
class ManifestXmlAnalyzer(PackageAnalyzer):
"""
Analyzer plug-in that analyzes manifest.xml (rosbuild) package files.
"""
def analyze_file(self... |
import pwd
import grp
import os
def chown(path, user, recursive=True):
uid = pwd.getpwnam(user).pw_uid
gid = grp.getgrnam(user).gr_gid
os.chown(path, uid, gid)
if recursive:
for root, dirs, files in os.walk(path):
for momo in dirs:
os.chown(os.path.join(root, momo), ... |
l,u=list(map(int,input().split()))
i=l
res=0
while(res==0):
if(i%l==0 and i%u==0):
res=i
else:
i+=1
print(res)
|
aa = "a"
b = a + "b" # 字串連接, b 會等於 "ab"
c = a * 3 # 字串重複三倍, c 會等於 "aaa"
# 檔名: exp_demo05.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
import os
import torchvision as tv
import numpy as np
from PIL import Image
def get_dataset(args, transform_train, transform_test):
if args.validation_exp == "True":
temp_dataset = Cifar10Train(args, train=True, transform=transform_train, download = args.download)
train_indexes, val_indexes = trai... |
import unittest
from katas.kyu_6.dubstep import song_decoder
class SongDecoderTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(song_decoder('AWUBBWUBC'), 'A B C')
def test_equals_2(self):
self.assertEqual(song_decoder('AWUBWUBWUBBWUBWUBWUBC'), 'A B C')
def test_equal... |
# Generated by Django 2.1 on 2018-08-12 20:58
import colossus.storage
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(setting... |
from collections import defaultdict
from operator import itemgetter
def solution(genres, plays):
count_list = defaultdict(int)
total_list = defaultdict(list)
for song_id, genre, play in zip(counter(), genres, plays):
count_list[genre] += play
total_list[genre].append((-play, song_id))
... |
#!/bin/python3
import os
import sys
import urllib.request
import urllib.parse
import json
import time
import datetime
sys.path.append(os.path.join(os.path.dirname(__file__), 'djangorm'))
import djangorm
from db.models import Cache
threshold = datetime.datetime.now() + datetime.timedelta(days=-7)
def search_online(pkg... |
class PID:
def __init__(self, Kp_in=-1.0, Ki_in=-1.0, Kd_in=-1.0, rate_in=-1.0):
# Variable to set the rate
self.rate = rate_in
# Calculate the time between intervals
self.dt = 1.0/self.rate
# Setting the PID parameters
self.Kp = Kp_in
self.Ki = Ki_in
self.Kd = Kd_in
# Variable... |
# script to convert yaml data file into json file
# original yaml map data comes from https://github.com/whoenig/libMultiRobotPlanning
import yaml
import json
import os
def convert_yaml_into_json(yaml_file_path, json_file_path):
with open(yaml_file_path) as fp:
yaml_map = yaml.load(fp)
json_map = {}
... |
import cv2
classificador = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml')
imagem = cv2.imread('pessoas//mprj-01.JPG')
imagemCinza = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)
facesDetectadas = classificador.detectMultiScale(imagemCinza, scaleFactor=1.05, minNeighbors=11, minSize=(10,10))
print(... |
def bubblesort(array):
"""
Inputs : array (list)
Outputs : array (list) - sorted lowest to highest
Description : sorts the array 'array' from lowest to highest
using bubblesort algorithm
"""
# have to check at most length of array
for i in range(len(array)):
... |
import maya.standalone
import os
import sys
# Start Maya in batch mode
maya.standalone.initialize(name='python')
from maya import cmds
os.environ["PYMEL_SKIP_MEL_INIT"] = "1"
#print os.environ["PYMEL_SKIP_MEL_INIT"]
import pymel.core as pm
import shutil
def load_script():
print sys.argv[3]
cmds.workspace... |
# Generated by Django 3.0.8 on 2020-08-17 19:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fhstore', '0003_auto_20200802_1823'),
]
operations = [
migrations.AddField(
model_name='order',
name='status',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.