text stringlengths 38 1.54M |
|---|
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import Image, Emoji, ImageEmojiRelationship
from .serializers import *
@api_view(['GET'])
def all_images_list(request):
data = Image.objects.all()
serializer = ImageSerializer(
data,
cont... |
from sqlobject import *
class IcsSQLObject(SQLObject):
uuid = StringCol(unique=True, varchar=True, length=36)
def get_identifier(self):
return self.uuid
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'frmMASGDCGUI.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_frmMASGDC(object):
def setupUi(self, frmMASGDC):
frmMASGD... |
last = 1
next_ = 1
fib = [1]
n = int(input())
for _ in range(n-1):
last, next_ = next_, last + next_
fib.append(last)
for i, el in enumerate(reversed(fib)):
if i == (len(fib) - 1):
print(el)
break
print(el, end=' ')
|
import pygame
SCREENWIDTH = 756
SCREENHEIGHT = 650
pygame.init()
screen = pygame.display.set_mode([SCREENWIDTH, SCREENHEIGHT])
pygame.display.set_caption("Create chick")
keepGoing = True
chick_img = pygame.image.load("images/chick.png")
BG = pygame.image.load("images/background.png")
chick_lose = pygame.image.load... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-15 13:09
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app_sourcing', '0010_auto_20180515_2108'),
]
operations = [
migrations.AlterUniqueT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""《算法导论》 123页
选择算法"""
from a_swap import swap
from p095_quick_sort import quick_sort
def median(lst):
"""return the small median of list"""
tmp_lst = lst.copy()
quick_sort(tmp_lst)
return tmp_lst[(len(lst)-1) // 2]
def partition(lst, median_value... |
import pyparsing as pyp
import math
import operator
import datetime
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
__author__='Paul Mc... |
class Trap(object):
"""Handle state of trap, trigger it, calculate and return effect.
* Holzbalken
* Vereister See
"""
def __init__(self, effect):
self.effect = effect
def snap(self):
pass
|
# -*- coding: utf-8 -*-
"""
@Time : 2020-09-09 16:59
@Author : QDY
@FileName: 164. 最大间距.py
@Software: PyCharm
"""
"""
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
示例1:
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
示例2:
输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
说明:
你可以假设数组中所... |
import json
from collections import defaultdict
with open("./resources/plenarprotokolle/group_1/splitted/mdb.json") as f:
mdb = json.load(f)
print(f"mdb file contains a total of {len(mdb)}")
mdb = {
k: v
for k, v in mdb.items()
if "debug_info" in v}
print(f"mdb file contains ... |
class Solution:
def longestPalindrome(self, s: str) -> str:
s1 = "#"
j = 0
length = 0
res = ""
# 把奇数偶数字符串都变成奇数的
for i in range(len(s)):
s1 = s1 + s[i] +"#"
# 对n个中心依次求解,保存最长的对应的中心和一半的长度
for i in range(len(s1)):
temp = ... |
'''
Just a file containing some of the plotting functions used by the notebook
'''
import numpy as np
import matplotlib.pylab as plt
import Node
#function to plot the nodes generated by the algorithm
def plot_nodes_astar(node_list, ymin = None, ymax = None):
L = 0.5
#Add limits if necessary
if ymin != Non... |
# Generated by Django 3.0.8 on 2020-12-04 05:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('aplication', '0004_matricula'),
]
operations = [
migrations.AddField(
model_name='cupon',
... |
"""
Copyright (C) 2021 Patrick Maloney
"""
import unittest
from python_meteorologist import forecast as fc
class ForecastTest(unittest.TestCase):
def test_missing_user_agent(self):
with self.assertRaises(TypeError) as context:
fc.Forecaster()
self.assertTrue('User Agent is required.'... |
#coding=utf-8
'''
Created on 2017年8月20日
@author: tjx
'''
import os
import re
import time
def add_meta_data(filename,line):
with open(filename, 'r+') as f:
print "Begin to process {0}".format(filename)
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
... |
class Pbs:
"""Class to setup PBS runs in various ways"""
# class variables shared by all instances
def __init__(self, hostFile='hosts', startDir=''):
"""
Stuff
"""
import os
from datetime import datetime
# instance variables unique to each instance
... |
from pylab import *
myfont = matplotlib.font_manager.FontProperties(fname='微软雅黑.ttf')
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
class Line(object):
def __init__(self,label,capacity):
self.label = label
self.capacity = capacity
self.x_list = []
self.y_list = ... |
import signal
import sys
# For Python 2.X.X
if (sys.version_info[0] == 2):
import openmoc
import _openmoc_cuda
from openmoc_cuda import *
# For Python 3.X.X
else:
import openmoc.openmoc as openmoc
import _openmoc_cuda
from openmoc.cuda.openmoc_cuda import *
# Tell Python to recognize CTRL+C an... |
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets import ViewletBase
SITES_TO_PUBLISH = [{'title': 'plone.de', 'url': 'http://plone.de'},
{'title': 'plone.es', 'url': 'http://plone.es'},
{'title': 'plone.fr', 'url': 'http://pl... |
'''
Question: You have two numbers represented by a linked list where each node contains a single digit. The digits are
stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers
and returns the sum as a linked list.
Example:
Input: 7 1 6
5 9... |
from tkinter import Tk, Label, Button, IntVar, DISABLED, NORMAL
from itertools import cycle
from sklearn.utils import shuffle
from PIL import ImageTk, Image
import numpy as np
import pandas as pd
from time import sleep
class Bridge:
def __init__(self, gui=True):
self.root = Tk()
self.gui = gui
... |
import requests,time, urllib, urllib2, httplib, json, pymongo
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
req=requests.get('https://www.meneame.net/')
soup=BeautifulSoup(req.text,"html5lib")
container_clics=soup.body.find_next('div', {'id': 'container'})
newswrap_clics=cont... |
from random import randint
bingo = randint(0,100)
n = 0
loop = True
while loop :
num = int(input("Input A Number (0-100) = "))
if num < bingo :
print("It's to small")
n+=1
elif num > bingo :
print("It's to big")
n+=1
elif n == bingo :
print("Bingo")
lo... |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import tensorflow as tf
from tensorflow import keras
from tqdm import tqdm
from tensorflow.keras.utils import plot_model
# Dataset location
train_csv = "/home/resl/Dev/Datasets/APTOS-2019-Blindness-Detection-Dataset... |
# Use this to find the theoretically perfect level of TIR1 expressions
from matplotlib import pyplot as plt
import numpy as np
import math
from scipy.integrate import odeint
import random
def find_index_from_time(t_obs,time,start_index=0):
i=start_index
while i+1<len(t_obs):
if t_obs[i+1]>time:... |
# -*- coding: utf-8 -*-
import re
a = {7:['s001','s002','s027']}
for idx in a:
if 'S027'.lower() in a[idx]:
print(idx)
break
print(a)
b = []
c = b[0]
print(c) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-15 18:35
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
... |
# Sprite Animation
# Running Bunny
# This program draws an animated spiral sprite.
import simplegui
import math
import random
# Global Variables
canvas_width = 200
canvas_height = 200
image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/week8-bunny_sprite.png")
image_size = [1... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 - 2013 Vikasa Infinity Anugrah <http://www.infi-nity.com>
#
# This program is free software: you can redistribute it and/or modify
# it u... |
import cv2
import numpy as np
import hand_detection_module as hdm
import fingers as fing
cam = cv2.VideoCapture(0)
cam.set(3,640)
cam.set(4,480)
detector = hdm.Handdetector(mindetection=0.5)
imgcanvas = np.zeros((480,640,3),np.uint8)
tips = [4,8,12,16,20]
draw_col = (255,0,255)
brush_thick = 15
eraser_th... |
from collections import defaultdict
import pandas as pd
import math
teams = {'ANA': 'Anaheim Ducks', 'ARI': 'Arizona Coyotes', 'BOS': 'Boston Bruins', 'BUF': 'Buffalo Sabres', 'CGY': 'Calgary Flames', 'CAR': 'Carolina Hurricanes', 'CHI': 'Chicago Blackhawks', 'COL': 'Colorado Avalanche', 'CBJ': 'Columbus Blue Jackets'... |
from necrobot.botbase import cmd_seedgen
from necrobot.botbase import cmd_admin
from necrobot.botbase.botchannel import BotChannel
from necrobot.race import cmd_racemake
from necrobot.race import cmd_racestats
# from necrobot.speedrun import cmd_speedrun
# from necrobot.ladder import cmd_ladder
from necrobot.botbase im... |
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""Purpose: Inserts a new interval into a set of
non-overlapping intervals, merging intervals when
necessary.
"""
intervals.append(newInterval)
intervals.sort()
... |
#Copyright 2006 DR0ID <dr0id@bluewin.ch> http://mypage.bluewin.ch/DR0ID
#
#
#
"""
Allow to draw some gradients relatively easy.
"""
__author__ = "$Author: DR0ID $"
__version__= "$Revision: 18 $"
__date__ = "$Date: 2006-10-03 14:01:03 +0200 (Di, 03 Okt 2006) $"
import pygame
import math
def gradient(surface,
... |
#!/usr/bin/env python3
"""
Script to make daily values from the IMERG 30-minute images
It sums the precipitation, converts to mm, and averages the QIND
The -8888000 (undetect) are set to 0
"""
import os
import gdal
import numpy as np
def absolute_file_paths(directory):
result = []
for dirpath, _, _filenames i... |
import tensorflow as tf
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
import math
import json
import sys
import keras
from keras.layers import Input, Dense, Conv2D, Max... |
"""This is a trivial example of a gitrepo-based profile; The profile source code and other software, documentation, etc. are stored in in a publicly accessible GIT repository (say, github.com). When you instantiate this profile, the repository is cloned to all of the nodes in your experiment, to `/local/repository`.... |
# 8 Score, challenge, conclusion
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
car_width = 80
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
road = (160, 160, 160)
obstacles = []
gameDisplay = pygame.display.set_mode((disp... |
from wtforms import Form, StringField, IntegerField,FileField
from wtforms.validators import Length, NumberRange, DataRequired, Regexp
class SearchForm(Form):
q = StringField(validators=[Length(min=1, max=30), DataRequired()])
page = IntegerField(validators=[NumberRange(min=1, max=30)], default=1)
class Dr... |
from datetime import datetime
import logging
from django.core.management.base import BaseCommand
from aids.services.contacts import extract_aids_contact_info
class Command(BaseCommand):
"""
Find the emails and phone numbers of aids contacts.
"""
def handle(self, *args, **options):
start_time... |
from selenium import webdriver
import time
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
passing_flag=0
def check_page(driver, keyword):
#find all iframes on the page
iframes = driver.find_elements_by_tag_name("iframe")
frames = []
failing_counter = 0
for i in iframes:
... |
from flask import jsonify, Blueprint, url_for
from flask_restful import Resource, Api, reqparse, inputs, fields, marshal, marshal_with
from passlib.apps import custom_app_context as pwd_context
from application import models
from application import (
db, JWTManager, jwt_required, create_access_token,
get_jw... |
# -*- coding: utf-8 -*-
import traceback
import random
import config
from s3 import S3, FakeFile
from mp_tasks import Tasks
from utils import login, get_accounts
from logwrapper import logger
def create_account(suffix, session):
name = config.ACCOUNT_PREFIX + str(suffix)
url = 'https://' + config.HOST + ':8... |
# -*- coding: utf-8 -*-
import click
import glob
import pandas as pd
import math
import json
from urllib.request import urlopen
import glob
import numpy as np
#Build pipe:
def STILT_converter(df,min_year,max_year,save_base_name):
"""
Converts a dataframe containing LATITUDE LONGITUDE Stackheight, CHEMICAL an... |
# Generated by Django 2.2.13 on 2020-07-07 12:31
from django.contrib.postgres.operations import CreateExtension
import django.contrib.gis.db.models.fields
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0074_auto_20200701_0939'),
]
opera... |
#============================================================================================#
# Copyright: JarvisLee
# Date: 2020/11/25
# File Name: Trainer.py
# Description: This file is used to training the model.
#=======================================================================... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('all')
def test_installed_packages(host):
lsof = host.package("lsof")
assert lsof.is_installed
git = host.package("git")
assert git.i... |
from rest_framework import serializers
from .models import Professor, Departamento, Curso, Disciplina, Turma, Avaliacao
class ProfessorSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Professor
fields = '__all__'
class DepartamentoSerializer(serializers.HyperlinkedModelSeria... |
#!/usr/bin/env python
##############################################################################
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
################################... |
from abc import ABC, abstractmethod
class Computadoras(ABC):
@abstractmethod
def __init__(self):
self.tipo = Tipo
self.caracteristicas = None
class PC(Computadoras):
print("Dipositivo de gama alta")
class Laptop(Computadoras):
print("Modelo perteneciente a Apple")
class Tipo... |
#!/usr/bin/env python
# coding=utf-8
import os
import sys
os.chdir('/usr/local/bluedon/')
if '/usr/local/bluedon/' not in sys.path:
sys.path.append('/usr/local/bluedon/')
import json
import time
import psutil
from db.config import fetchone_sql as fetch3306
from utils.log_logger import rLog_dbg, rLog_err
from rep... |
# We use the GeoManager as the main object manager for Permit
from django.contrib.gis.db.models import GeoManager
# We use the SearchManager as a secondary manager
from djorm_pgfulltext.models import SearchManager
# Other imports required by these managers are:
from djorm_pgfulltext.fields import VectorField
from djang... |
from django.conf.urls import url
from commodity.views import commodity_list, comcategory, speedFood, recharge, hongbao, city, village, tidings, detail
urlpatterns = [
url('^commodity_list/$',commodity_list,name='琳琅的店'),
url('^comcategory/(?P<class_id>\d*)_{1}(?P<order>\d?)$',comcategory,name='商品分类'),
url(... |
"""
The seq2science configuration/preprocessing is split into four parts:
* generic: all logic not related to any specific workflows
* workflows: all logic related to specific workflows
* explain: all logic necessary to make an explanation of what has/will be done
* logging: all logic related to logging to stdout/file
... |
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("Kobe_stats.csv")
data = pd.DataFrame()
data["Season"] = pd.to_datetime(df["Season"])
data["PTS"] = df["PTS"]
sns.set()
sns.relplot(x="Season", y="PTS", data=data, kind="line")
plt.xlim("1995", "2015")
plt.show()
|
""" Simulation classes that handle variations of discrete-time replicator dynamics
Classes:
:py:class:`DiscreteReplicatorDynamics`
implements generic discrete time replicator dynamics
Functions:
:py:func:`initial_set_handler`
Default handler for 'initial set' events
:py:func:`generation_rep... |
import torch
import torch.nn as nn
import torchvision.models as models
import random
random.seed(0)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class EncoderCNN(nn.Module):
def __init__(self, encoded_image_size=14):
super(EncoderCNN, self).__init__()
resnet = models.res... |
# -*- coding: utf-8 -*-
"""
다차원 배열의 넘파이 계산 기초
"""
import numpy as np
# 1차원 배열 A
A = np.array([1, 2, 3, 4])
print("== A ==")
print(np.ndim(A)) # 배열의 차원 수를 확인하는 함수
print(A.shape) # 배열의 형상 확인 원소의 개수를 알 수 있다. 단, tuple형태로 반환
# 2차원 배열 B
B = np.array([[1, 2], [3, 4], [5, 6]])
print("== B ==")
print(np.ndim(B))
print(B.... |
"""
Cazador file/cloud service investigator objects module.
This portion of the module handles the simple object types expected as the
result of a Cazador operation.
Created: 08/24/2016
Creator: Nathan Palmer
"""
import hashlib
import re
class CazFile:
"""Simple file metadata object."""
def __init__(self, ... |
from matplotlib import pyplot as plt
import os
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import numpy as np
import cv2
from ssd_vgg import SSD_VGG
from ssd_mobilenetv2 import SSD_MobileNetV2
from ssd_mobilenetv3 import SSD_MobileNetV3
import argparse
pa... |
#!/usr/bin/env python
import sys, re
key = "i hope in the next ten years there would be no other farewell letter brilliant than this one"
def decrypt(content):
encrypted = re.sub("\s", "", content).split(",")
decrypted = "".join([chr(int(encrypted[i]) ^ ord(key[i % len(key)])) for i in range(len(encrypted))]... |
from __future__ import absolute_import, unicode_literals
from django_ppf.celery import app
from assistant.utils import (
update_prices,
import_parameters_form_prom,
parse_mizol,
)
from assistant.utils import make_xml, make_xlsx_for_prom
@app.task(name='assistant.update_mizol_prices_task')
def update_mizol... |
from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__)
@app.route('/store_file', methods=['post'])
def store_file():
file_name = request.form.get('filename')
if not file_name or ("." not in file_name):
return
file_content = request.form.get('content')
with o... |
from heapq import heappush, heappop
INF = float("inf")
v_num, e_num, r = list(map(int, input().split()))
edges_l = [[] for _ in range(v_num)]
dist_l = [INF for _ in range(v_num)]
for _ in range(e_num):
s, t, dist = map(int, input().split())
edges_l[s].append((t, dist))
que = []
heappush(que, (0, r))
dist_l... |
# -*- coding: utf-8 -*-
"""Class for the ogs KINETRIC REACTION file."""
from ogs5py.fileclasses.base import BlockFile
class KRC(BlockFile):
"""
Class for the ogs KINETRIC REACTION file.
Parameters
----------
task_root : str, optional
Path to the destiny model folder.
Default: cwd+... |
# Code from Tutorial
# https://machinelearningmastery.com/machine-learning-in-python-step-by-step/
# Load libraries
import pandas
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import ... |
import os
import subprocess
import re
from colour import Color
import json
sourceDir = "source_videos"
def generateThumbs():
for vid in os.listdir(sourceDir):
fileParts = re.search('Samurai\.Jack\.S(\d*)E(\d*)\.(\w*)\.(.*)\.avi', vid)
season = fileParts.group(1)
episode = fileParts.group(2)
chapter ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mongoengine import *
# Create your models here.
from src.common.libraries.customdocument import CustomDocument
class Feedback(CustomDocument):
Name = StringField()
PhoneNumber = StringField()
Email = EmailField()
Subject = StringF... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('messagebook', '0004_auto_20151005_1104'),
]
operations = [
migrations.AlterField(
model_name='message',
... |
import streamlit as st
import torch
import pickle
import os
from pathlib import Path
import yaml
import time
from seal import Ciphertext, \
Decryptor, \
Encryptor, \
EncryptionParameters, \
Evaluator, \
IntegerEncoder, \
FractionalEncoder, \
KeyGenerator, \
MemoryPoolHandle, \
Plain... |
from sqlalchemy import and_
from changes.config import db
from changes.constants import Result, Status
from changes.models.build import Build
from changes.models.job import Job
from changes.models.jobplan import JobPlan
from changes.models.plan import Plan
from changes.models.project import Project
from changes.utils.... |
"""
Simple wrapper class for pyvirtualdisplay to standardize init options
"""
import logging
from xvfbwrapper import Xvfb
log = logging.getLogger("datafeeds")
class VirtualDisplay:
def __init__(self):
self._display = Xvfb(width=1900, height=1200)
def __enter__(self):
self.start()
re... |
class Character:
def __init__(self, name, player, st, hp_adjust, ht, fp_adjust, iq, will_adjust, er):
hp = st+hp_adjust
fp = ht+fp_adjust
will = iq+will_adjust
self.name=name
self.player=player
self.st=st
self.ht=ht
self.fp=fp
self.hp=hp
... |
empty_dict = {};
print(empty_dict);
bierce = {
"day":"A period",
"positive":"Mistaken",
"misfortune":"The Kin"
};
print(bierce);
lol = [['a','b'],['c','d'],['e','f']];
print(dict(lol));
pythons = {
'Chapman': 'Graham',
'Cleese': 'John',
'Idle': 'Eric',
'Jones': 'Terry',
'Palin': 'M... |
# Each product has a name, base price, and tax rate. There should also be a method to calculate and return the product's
# total price based on the base price and tax rate.
class Product:
"""
This class represents a retail product. It has a name, a base price, and a tax rate
"""
def __init__(self,name... |
# Generated by Django 3.1.7 on 2021-05-05 03:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('restaurantApp', '0013_auto_20210503_1159'),
]
operations = [
migrations.RemoveField(
model_name... |
# Generated by Django 2.2.6 on 2020-03-09 20:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('slobg_app', '0006_auto_20200309_1949'),
]
operations = [
migrations.RemoveField(
model_name='profil... |
from collections import deque
que = deque()
counter = 0
class Collatz:
def __init__(self,value,parent):
self.value = value
if parent != None:
self.level = 1 + parent.level
else:
self.level = 1
self.parent = parent
lengths = [0 for _ in xrange(int(1E6))]
root... |
#!/usr/bin/env python
#
# pKa - various programs and scripts for pKa value analysis, calculation and redesign
# Copyright (C) 2010 Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.osv import osv
from openerp import http
from openerp.http import request
from openerp.addons.web.controllers.main import serialize_exception,content_disposition
def Ordenar_Lista(UnaLista, UnCampo, UnOrden):
for x in range(0, len... |
import numpy as np
import xarray as xr
# Gerando arquivo NetCDF da média da Tmax mensal para abrir no programa
# "ParaView", disponível em https://www.paraview.org/
# Baseado em: https://www.youtube.com/watch?v=xdrcMi_FB8Q
# abrindo arquivos Tmax "nc"
var_xr = xr.open_mfdataset('/home/alexandre/Dropbox/grade_2020/dat... |
@staticmethod
def trim(raw_text):
return raw_text.strip().replace(",", "").replace("\n","").replace("\t","") |
# Compute and print powerball numbers.
###################################################
# Powerball function
# Student should enter function on the next lines.
import random
def powerball():
print "Today's numbers are "+str(random.randrange(0,60))+",",
print str(random.randrange(0,60))+",",str(random.rand... |
from soa import devices, signalprocessing, analyse, distort_tf
from soa.optimisation import PSO, run_test
import numpy as np
import multiprocessing
import pickle
from scipy import signal
import os
import matplotlib.pyplot as plt
# set dir to save data
directory = '../../data/'
# init basic params
num_points_list = ... |
import requests
import json
headers = {
'content-type': "application/json",
'accept': "application/json",
'authorization': "Bearer Nj0ZHCvwlweSSml3Iyydbj3kSD_eK0WiSTixdOh7ng4"
}
# getting all contacts
def get_contact():
response = requests.get(
"https://api.sandbox.split.cash/contacts", heade... |
'''
This file will test and evaluate all of our current selection techniques,
and display them (ideally) on a single graph
'''
import os
from os.path import isdir, isfile, join
from os import listdir
import argparse
import matplotlib.pyplot as plt
import numpy as np
import train_al
def run_benchmark(iterations=10,bat... |
import getopt
import sys
import time
def usage():
print '''Usage:
-h: Show help infomation
-l: Show all table in hbase
-t {table} show table descriptors
-t {table} -k {key} : show cell
-t {table} -k {key} -c {column} : show the coulmn
-t {table} -k {key} -c {column} -v {version} :show more ... |
class Person:
def __init__(self, n, s):
self.name = n
self.surname = s
self.qualification = 1
def show_person(self):
description = (self.name + " " + self.surname +". Qualification is: " +str(self.qualification))
print(description)
p1 = Person("Ted", "Karlson")
p1.show_p... |
num1 = int(input('Digite o número 1: '))
num2 = int(input('Digite o número 2: '))
num3 = int(input('Digite o número 3: '))
menor = num1
if num2 < num1 and num2 < num3:
menor = num2
if num3 < num1 and num3 < num2:
menor = num3
maior = num1
if num2 > num1 and num2 > num3:
maior = num2
if num3> num1 and num3... |
def flag(arr):
start, end = 0, len(arr) - 1
cur = 0
while cur <= end:
if arr[cur] == 0:
arr[cur], arr[start] = arr[start], arr[cur]
cur += 1
start += 1
elif arr[cur] == 1:
cur += 1
elif arr[cur]== 2:
arr[cur], arr[end] = arr[end], arr[cur]
end -= 1
def main():
a... |
"""
Base classes for biomolecules
"""
import numpy as np
from ..templates.aminoacids import templates_aa, one_to_three_aa
from ..templates.glycans import templates_gl, one_to_three_gl
from ..ff import compute_neighbors, LJ
from ..pdbIO import _dump_pdb
from ..visualization.view3d import _view3d
class Biomolecule(... |
import socket
import pandas as pd
import numpy as np
from watch_gst_stream import watch_stream
frames = []
steer_cmds = []
host = '192.168.1.120'
port = 9001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def append_frame(image_arr):
s.sendall(b'next')
steer = tuple(s.recv(1024... |
from doorman import models
class ConfigManager(object):
def __init__(self):
pass
def __setattr__(self, key, value):
pass
def __getattr__(self, item):
pass
config = ConfigManager()
|
from django.db import models
import uuid
class Category(models.Model):
name = models.CharField(max_length=200)
class Product(models.Model):
uuid = models.UUIDField(default=uuid.uuid4,primary_key=True)
name = models.CharField(max_length=200)
description = models.TextField()
price = models.Decimal... |
import ee
from time import sleep
ee.Initialize()
SHIFT_BEFORE = 60
def main ():
# Load in the pre-processed GLAD alerts
glad_alerts = ee.Image('users/JohnBKilbride/SERVIR/real_time_monitoring/glad_alerts_2019_to_2020')
# Get the projection that is needed for the study area
projection = ee.P... |
"""Secure client implementation
This is a skeleton file for you to build your secure file store client.
Fill in the methods for the class Client per the project specification.
You may add additional functions and classes as desired, as long as your
Client class conforms to the specification. Be sure to test against ... |
a = 1
b= 1
n = 54
m = 27
for i in range(m):
a = a * (n - i)
b = b * (i+ 1)
#c = a//b
#print("%d" %c)
d = 1
for i in range(1,n+1):
d *= i
aa = a
for i in range(1,1000):
f = d / aa
print("%.2f %d" %(f,i))
aa *= a
|
# encoding: utf-8
from functools import wraps
from validator import validate as validator_validate
from flask import jsonify, wrappers, request
from .response import *
from .pagination import PaginatedDataView
def handle_exception(decorated):
@wraps(decorated)
def inner(*args, **kwargs):
try:
... |
import random
import numpy as np
import matplotlib.pyplot as plt
import csv
def rand_seed(m, b, num=2):
# create empty list
x_coor = []
y_coor = []
label = []
# positive and negtive point number
pos_num = int(num / 2)
neg_num = num - pos_num
# random create point
for i in range(po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.