text
stringlengths
38
1.54M
from setuptools import setup from os import path import re def read(fname): return open(path.join(path.dirname(__file__), fname)).read() setup( name='eepro', version='0.2.0', author='Daniel Grießhaber', author_email='dangrie158@gmail.com', url='https://github.com/dangrie158/EEPROgraMmer', ...
import tweepy import textblob consumer_key = 'insert consumer key here' consumer_secret = 'insert consumer secret here' access_token = 'insert access token here' access_secret = 'insert access secret here' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_...
#pylint: skip-file import mock import re from util import VigilanceTestCase class ConfigurationParserTest(VigilanceTestCase): def setUp(self): super(ConfigurationParserTest, self).setUp() global ConfigurationParsingError from vigilance.error import ConfigurationParsingError from vi...
import cv2, pickle import matplotlib.pyplot as plt import numpy as np import pandas as pd import os, glob import tensorflow as tf import time from keras.models import Sequential from keras import losses, regularizers from keras.layers import Dense, Dropout, Activation, Flatten, Lambda from keras.layers import Conv2D...
# Binary Search using Python # Array a # Left l, Right r def BinarySearch(a, l, r, item): if r >= l: mid = (r + l) // 2 if a[mid] == item: return mid elif a[mid] > item: return BinarySearch(a, l, mid - 1, item) else: return BinarySea...
import jwt import time import logging import sqlite3 as sqlite from flask import jsonify, json from be.model import error from be.model import db_conn import sqlalchemy import initialize_db import base64 # encode a json string like: # { # "user_id": [user name], # "terminal": [terminal code], # ...
class Port: def __init__(self, side, position, port_type, value_name): assert side in ["left", "right", "top", "bottom"], "Assert port side is acceptable value" assert port_type in ["input", "output"], "Assert port type is acceptable value" assert isinstance(position, int) or isinstance(pos...
#nhn godo #핵심 소스코드의 설명을 주석으로 작성하면 평가에 큰 도움이 됩니다. def solution(goods): goods = sorted(goods) if sum(goods)<50: return sum(goods) if goods[0]>=50: return sum(goods)-30 if goods[0]+goods[1]>=50 and goods[1]<50 and goods[2]>50: return sum(goods)-20 e...
"""hiwi_stunden URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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') Clas...
from django.contrib import admin from django_rest_template.apps.user.models import DashboardSection, VenueViewerType admin.site.register(DashboardSection) admin.site.register(VenueViewerType)
import django __version__ = "0.10.0" if django.VERSION < (3, 2): default_app_config = "django_dramatiq.apps.DjangoDramatiqConfig"
# Client import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((socket.gethostname(),1620)) msg=s.recv(1024) print(msg.decode("utf-8"))
def decode_sym(str): str = int(str) symbols = { 10 : '+', 11 : '-', 12 : '*', 13 : '/', } return symbols.get(str,str)
from GCDFunction import gcd n1 = eval(input()) n2 = eval(input()) print("the greatest common divisor for ", n1, "and", n2, "is", gcd(n1, n2))
from django.db import models from datetime import datetime import uuid class pubganalyticData(models.Model): requester = models.CharField(max_length = 100, null = False) pubg_name = models.CharField(max_length = 100, null = False, default = "") requested = models.DateTimeField("Date requested", default=datetime.n...
import numpy as np import pandas as pd import math import os.path import matplotlib.pyplot as plt import mplleaflet def load_day(day): header = ['timestamp', 'line_id', 'direction', 'jrny_patt_id', 'time_frame', 'journey_id', 'operator', 'congestion', 'lon', 'lat', 'delay', 'block_id', 'vehicle_id',...
class Dog: def __init__(self,variety,gender): print("开始初始化") self.variety=variety self.gender=gender print("初始化结束") wangcai=Dog("金毛","雄性") print("wangcai的品种:{}".format(wangcai.variety)) print("wangcai的性别:{}".format(wangcai.gender)) wangcai.name="wangcai" wangcai.age=1 print("name ={}...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library from builtins import str from . import config standard_library.install_aliases() class RedfishException(Exce...
from django.db import models from django.contrib import admin from django.contrib.auth.models import User class Task(models.Model): task_title = models.CharField(max_length=200, null=True) task_description = models.TextField(max_length=3000, null=True) assigned_to = models.ManyToManyField(User, through="A...
def calc_factorial(n: int): if n == 0: return 1 fact = n if n < 0: raise ValueError('factorial is not defined for negative numbers!') if isinstance(n, float): raise ValueError('factorial only accepts fixed-point numbers!') for i in range(1, n, 1): fact *= i retur...
import argparse import re import subprocess import sys def is_port_used(port): cmd = 'netstat -ntlp | grep "%s"' % port p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) out, _ = p.communicate() matches = re.findall return True if matches else False: def main(): parser...
try: # cli version from cli import main except ImportError: # vs code version from .cli import main main()
# Functions that would be used to create the topography of the neuraal net # The neurons and weights are taken as matrices # Neurons are 1D arrays or lists of the dimension 1 X col import numpy as np import pandas as pa def collectData (sheet_name): """ Returns an array (numpy) of the input data from the excel s...
import numpy as np import pandas as pd import torch import os from pytorch_transformers import BertTokenizer, BertForSequenceClassification, BertConfig, BertModel import torch.nn.functional as F import sys def load_checkpoint(model, ckpt): if ckpt is None: print("empty checkpoint!") sys.exit(-1) ...
from typing import List from base.tree.tree_node import TreeNode class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return mid = len(nums) // 2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) ...
# file: iothreading.py # author: Conner Brown # date: 5/10/2017 # update: 6/6/2017 # brief: implement input and output capture with threading. perform primary analysis: onset detection, filtering # status: add deconvolution filter, improve onset detection algorithm, python style guide import sounddevi...
""" Wrappers for Wynncraft "territory" API """ __all__ = [ 'territory' ] from typing import Union from Wrappers.util import api_call def territory(name: str) -> Union[dict, None]: """ 1) gets data 2) checks for errors (codes 400, 429, anything except 200) 3) decodes json and assi...
from django.shortcuts import render from django.views.generic import TemplateView from MySite.forms import ContactForm from django.contrib.auth import logout as auth_logout from django.http import HttpResponseRedirect from django.urls import reverse def madadkarhome(request): return render(request, "madadkar/home...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import logging from django.conf import settings from urllib.parse import urlencode, parse_qs import urllib.parse from urllib.request import urlopen from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData from .exceptions import QQAPIEr...
from django.db import models from django.contrib.auth.models import User from django.conf import settings from utility.country_codes import COUNTRY_CHOICES from ra.base.models import EntityModel, TransactionModel, TransactionItemModel, QuantitativeTransactionItemModel # Create your models here. class BaseModel(models...
# import sys to get more detailed Python exception info import sys # import the connect library for psycopg2 from psycopg2 import connect # import the error handling libraries for psycopg2 from psycopg2 import OperationalError, errorcodes, errors # define a function that handles and parses psycopg2 exceptions def p...
# noinspection PyUnresolvedReferences from mininet.topo import Topo # Topology # c1 c2 # | | # 1: 1: # h1---2:s1:3---2:s2:3---h2 # :4 # | # :2 # c3---1:s3:3--h3 class MyTopo(Topo): def __init__(self, **opts): Topo.__init__(self, **opts) ...
import socket import _main with open('config.ini', "r") as f: if f.mode == 'r': for line in f: exec(line) else: print('Error reading settings') def pslisten(): global c s.listen(5) c, addrs = s.accept() print('CONNECTED: ', addrs) main = _main.Main(dir) s = sock...
from django.shortcuts import render from rest_framework import viewsets from .models import Task from .serializers import TaskSerializer #inherithing viewsets from rest_framework class TaskView(viewsets.ModelViewSet): #Pre standar methods in APIs: Get, Put, Delete queryset = Task.objects.all() #Gets all Task ...
from channels.routing import ProtocolTypeRouter # For enabling DASH live features application = ProtocolTypeRouter({ })
#!/usr/bin/python3 # four function calculator in python def add(a, b) return a+b def subtract (a,b): return a-b def multiply (a,b) return a*b; def divide (a,b): try; return a/b except ZeroDivisionError print "Division not possible ", end=' '); return False def calculate(a, b, op): if (op ==...
from PIL import Image import sys if len(sys.argv) !=2: exit(f"Usage: {sys.argv[0]} FILENAME") in_file = sys.argv[1] img = Image.open(in_file) print(img.size) # a tuple print(img.size[0]) # width print(img.size[1]) # height print(sys.getsizeof(img)) # The size of the variable print(sys.getsizeof(img.tobytes()...
import os import sys import logging from yapsy.IPlugin import IPlugin _config = { 'pluginmodname': 'Dummy', 'pluginname': 'Dummy Plugin', 'version': '0.1a', 'created_date': '20130805', 'author':'James E. Hung', 'email':'jim@notional-labs.com' } class Dummy(IPlugin): def getRequirements(self): reqs ...
from flask import Flask, flash, session from pitho.Config import conn class LoginModel(): def logincheck(self, data): db = conn.connection.cursor() db.execute("select * from users where email=%s and password=%s", (data.get("youremail"), data.get("password"))) row = db.fetchone() #db.commit(); if row != Non...
# -*- coding: utf-8 -*- from odoo import api, models, _ class studentdetailenrolmentreport(models.AbstractModel): _name = 'report.atts_student_fields.report_student_nationality_enrolment' @api.multi def _student_nationality(self, date): nationality_dict = [] total_asd=total_imid=tota...
## FinGraph -- fingraph_functions.py # std lib imports import pandas as pd import matplotlib.pyplot as plt from pandas_datareader import data as pdr import fix_yahoo_finance as yf # project imports from fingraph_classes import StochasticOscillator, MACD # select ggplot style for matplotlib import matplotlib matplotl...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from tracing.value import histogram_unittest from tracing.value.diagnostics import diagnostic from tracing.value.diagnostics import generic_...
import cv2 import json from statistics import mean import time import os from tqdm import tqdm import numpy as np from yolov4.tf import YOLOv4 base_path = "../" def impactDetection(frame, yolo): frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) frame = cv2.resize(frame, yolo.input_size, in...
import pygame from pygame.locals import * from macros import * import random from utils import * import math class Ball: def __init__(self): self.dx = 0 self.dy = 0 self.x = display_width/2 self.y = display_height/2 self.accel = BALL_INITIAL_ACCELERATION self.radius ...
from .models import BookModel from django.contrib import admin @admin.register(BookModel) class BookAdmin(admin.ModelAdmin): readonly_fields = ('error_field_example',) list_display = ('author', 'title', 'subject',) fields = ('author', 'title', 'subject', 'error_field_example',) def error_field_examp...
# -*- coding: utf-8 -*- from sys import argv from os import listdir, remove, path from PIL import Image import imagehash src_folder = argv[1] dic = {} count = 0 for src_file in listdir(src_folder): if src_file == '.DS_Store': continue image = Image.open(path.join(src_folder, src_file)) h = str...
import json import io from pytest import raises MOCK_APIKEY = "not" MOCK_PARAMS = { "credentials": { "password": MOCK_APIKEY } } BASE_URL = "https://apiv2.phishup.co" def util_load_json(path): with io.open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read()) def test_in...
''' Created on Jul 20, 2014 @author: ppx10 ''' from random import randint from _operator import xor from operator import mod import sys class MinHash(object): ''' classdocs ''' def __init__(self, hashCnt=200): ''' Constructor ''' self.randomNums = [randint(-sys.maxsi...
import sys import unittest from pathlib import Path from gryml.cli import init_parser from gryml.core import Gryml class ExtendStrategyTest(unittest.TestCase): def setUp(self): self.parser = init_parser() self.path = Path(__file__).parent.resolve() self.gryml = Gryml() def test_simp...
# coding: utf-8 import re import os import json import scrapy from scrapy.conf import settings from multimedia_crawler.items import MultimediaCrawlerItem from multimedia_crawler.players.youku_player import YouKuPlayer from multimedia_crawler.players.qq_player import QQPlayer from multimedia_crawler.players.bilibili_...
import pandas as pd import json class VideoDataLoader: def __init__(self): self.country_codes = ["US", "CA", "DE", "FR", "GB", "IN", "KR", "MX", "RU"] self.root_path = "data/" self.category_dict = self.categories_dict() def load_data(self): ''' Load YouTube data int...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the ...
from requests.backlight.config.backlight_config_get import endpoint_backlight_config_get from requests.backlight.config.backlight_config_post import endpoint_backlight_config_post from requests.backlight.config.backlight_config_restart import endpoint_backlight_restart_service from requests.backlight.on_off.backlight_o...
# # Logistic Regression using Gradient Descent import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.preprocessing import PolynomialFeatures # ## Import Data Set train_data = pd.read_csv('micro_data_train.csv') train_data.head() train_data.info() train_data.describe() test_data = pd...
## # Module providing scan functionality # # Copyright 2015 Arend van Spriel <aspriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # ...
#!/usr/bin/python # # Show the main interfaces of the three sensor classes # # from time import sleep from altimu.lsm6ds33 import LSM6DS33 imu = LSM6DS33() # Accelerometer and Gyroscope imu.enable() # Must be enabled before use! # Accelerometer is set to 4g max scale by default # These interfaces...
if __name__ == "__main__": n = int(input()) lis = list(map(int, input().strip().split(' '))) s = lis.count(1) st = [0] * s i = 0 # print(s, st) for x in range(len(lis)): if x == 0: st[i] += 1 continue if lis[x] == 1: i += 1 st...
from rebase.common.database import DB, PermissionMixin class Contract(DB.Model, PermissionMixin): __pluralname__ = 'contracts' id = DB.Column(DB.Integer, DB.ForeignKey('bid.id', ondelete='CASCADE'), primary_key=True) def __init__(self, bid): from rebase.models import Work self.bid = bid...
if __name__ == '__main__': lst=[] marklist=[] for i in range(int(input())): for i in range(1): x=input() y=float(input()) marklist.append(y) sublist=[x,y] lst.append(sublist) def removeDuplicate(lst): # using naive method ...
#!/usr/bin/python # Dtpart in python :-D # Exigo partition autolayout handler redone in python v 0.0.2 # By letme0ut ( letme0ut@exigo.distrotalk.net ). # This code and software is licensed under the BSD License. # For more details, see the LICENSE file in the source directory, # or http://www.opensource.org/licenses/bs...
# Generated by Django 2.0.3 on 2018-08-18 00:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Institutos', '0012_auto_20180614_2020'), ] operations = [ migrations.AddField( model_name='mensaje', name='leido', ...
#!/usr/bin/env python # coding: utf-8 from keras import backend as K import keras import cv2 from Utils import * import tensorflow as tf import numpy as np from keras.models import model_from_json import matplotlib.pyplot as plt from keras.preprocessing.image import load_img, img_to_array import os import imageio imp...
'''Author - MD ELIOUS ALI MONDAL Created - 28/5/2017''' #approximation via cubic splines from sined import xi from sined import yi ai = yi[:] x = float(input('Enter the value of x : ')) j = 0 for i in range(len(xi)): if x > xi[i]: if x < xi[i+1]: j = i else: ...
import pandas as pd import numpy as np import time class ConvertVariables(): def __init__(self, conversion_dict): """ name: function name conversion_dict: dtypes and columns """ self.name = 'ConvertVariables' self.conversion_dict = conversion_dict def convert_d...
from __future__ import absolute_import # encoding: UTF-8 from tml.web_tools.translator import BaseTranslation author = 'xepa4ep' class Translation(BaseTranslation): """ Basic translation class """ def get_language_from_request(self, request, cookie_handler, config): locale = None locale = re...
from __future__ import print_function import json import numpy as np import tensorflow as tf import os tf.reset_default_graph() def load(filename): print("Loading", filename ,"...") f = open(filename, "r") data = json.load(f) f.close() x_input=np.array(data["x_input"]) re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python script to convert Forex files into different formats (e.g. FXT/HST/HCC). from struct import pack, pack_into, calcsize import argparse import bstruct import csv import datetime import mmap import os import re import sys import time class Spinner: """Displays...
@Subroutine def ExSkillInit(): Unknown11091(10) Unknown30065(0) @Subroutine def InvSkillInit(): Unknown30065(100) @Subroutine def PartnerSkillInit(): AttackP1(70) Unknown11042(1) @State def Invincible_Obj(): def upon_IMMEDIATE(): Unknown2010() Unknown4011(3) Unknown40...
from django.contrib import admin from django.urls import path from home import views admin.site.site_header = "Nitin Ice Cream Admin" admin.site.site_title = "Nitin Ice Cream Admin Portal" admin.site.index_title = "Welcome to Nitin Ice Creams" urlpatterns = [ path("", views.index, name='home'), path("about", ...
#-*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import JsonResponse from django.utils import timezone from django.utils.html import format_html from django.template.loader import render_to_string from jiboia.forms.atividade_forms import AtividadeCreateForm, AtividadeStarForm from ...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): profile_picture = models.ImageField(upload_to = 'profile_pictures/', blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) bio = models.TextField(max_le...
# -*- coding: utf-8 -*- # create by Aramis import requests from scrapy.selector import Selector url1 = 'https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_9286217699096966359%22%7D&n_type=0&p_from=1' url2 = 'http://ip.zxinc.org/ipquery/?ip=136.110.14.107' url3 = 'http://www.guangyuanol.cn/...
from django.core.serializers import serialize from django.db.models.query import QuerySet from django.utils import simplejson from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter('get_class') def get_class(ob): return ob.__class__.__name__ @regi...
ez_dict = {'birthdate': '1946-06-14', 'party': 'Republican', 'gender': 'M', 'identifiers': { 'twitter': 'realDonaldTrump', 'fec': 'P80001571', }, 'name': {'first': 'Donald', 'last': 'Trump'}, 'birthplace': {'state': 'NY', 'city': 'New Yor...
import numpy as np, uuid import devhgcaltruth as ht def plotly_tree(tree, colorwheel=None, noinfo=False, draw_tracks=True): import plotly.graph_objects as go data = [] info = {} if colorwheel is None: colorwheel = ht.IDColor() all_hits = tree.nphits_recursively() all_energy = all_hits[:,3] ...
#!venv/bin/python # -*- coding: utf-8 -*- def username_checker(self): chooser = 0 while len(self.user_list) > 0 and chooser < len(self.user_list): self.current_user = self.user_list[chooser]["user"]["username"] self.current_id = self.user_list[chooser]["user"]["id"] for index in range(le...
from copy import copy from utils.hanoi import * from randomHanoi.randomHanoi import start_random from hillclimbing.hillclimbing import start_hill_climbing import timeit # get user input number_of_pegs = int(input("Number of pegs: ")) number_of_pieces = int(input("Number of pieces: ")) # get and print initial state ...
import numpy as np def colors(): return "#"+"".join(np.random.choice(list('abcdef123456789'), 6))
# 2.Dados 2 números naturais p e q, # calcule o valor se p≥q, ou # caso contrário. # p ! # q ! p−q ! # q ! # p! q−p ! # def fatorial(n): # for i in range(n, 1, -1): # n = n * (i - 1); # return n def fatorial(n): if n == 0 or n == 1: return 1 else: n = n * ...
import numpy as np import cv2 from PIL import ImageGrab import math import time while(True): ##############take screen and turn it to numpy array > > color is not real img = ImageGrab.grab(bbox=(0, 0, 666, 768)) #x, y, w, h img_np = np.array(img) #################################convert the numpy arr...
# -*- coding: utf-8 -*- # date: 2021/11/1 # Project: Numpy_Pandas_Notes # File Name: 4数组索引和切片.py # Description: # Author: Anefuer_kpl # Email: 374774222@qq.com import numpy as np t1 = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(t1) print('====================取行=========================') print(t1[1]) # 取第二行 # 取连续多行 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'jczetta' SITENAME = u'let\'s live on a spaceship' SITEURL = '' PATH = 'content' TIMEZONE = 'USA/New York' DEFAULT_LANG = u'en' # Added to specify theme THEME = "pelican-themes/waterspill-en" # Feed generation is usu...
# make-descriptors-csv-file.py: creates a csv file with descriptor values import os import sys import chemkit if len(sys.argv) < 4: print 'usage: ' + sys.argv[0] + ' [INPUT_FILENAME] [OUTPUT_FILENAME] [DESCRIPTORS...]' input_filename = sys.argv[1] output_filename = sys.argv[2] # read input file input_file = che...
name = "Andres" lastname = "Santana" print("Hello my name is :") print(name) print(lastname) age = 41 print("I am: ") print(age) #age = 42 print("years old!") #print(age) print("Goodbye!")
from skimage import data from gui import NumpytoPIL from PIL import Image def NumpytoPIL(npImg): """Helper function to convert numpy.ndarray formatted image to PIL format for processing. Args: npImg (numpy.ndarray): the image to be converted """ rescale_out = exposure.rescale_intensity(np...
PROJECT_DIR="./chatbot-intents/" OUTPUT_DIR=PROJECT_DIR+"/outputs/" DATA_DIR=PROJECT_DIR+"/data/"
""" Tests foodgenerator.generator """ from foodgenerator import generator def test_generate_products(): vals = [val for val in generator.generate_products(100)] assert vals single = vals[50] assert single.name assert single.category in ['FOOD', 'DRINK', 'OTHER'] assert int(single.priceInCent...
#IMPORTANDO O WEBDRIVER DO CHROME import self as self from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.alert import Alert from selenium.webdriver.support.ui import Select import time import select #VINCULANDO O NAVEGADOR A VARIAVEL driver = web...
""" The script is used to check the data quality which defined in xxx.json @Author : Zhang Kai Ming @Date: '2018-09-12 16:38:00.966214' """ import json import pymssql from collections import Counter class MSSQL: """ 定义MSSQL类及查询方法 """ def __init__(self, host, user, pwd, db): self.host = host ...
""" Name : 4375OS_07_19_risk_return_graph.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : yany@canisius.edu paulyxy@hotmail.com """ import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotl...
# -*- coding: UTF-8 -*- from django.contrib import admin from models import Grade, Subject, Teacher, Pupil, School, Staff, Achievement class SchoolAdmin(admin.ModelAdmin): list_display = ('name',) fields = ('name', 'prefix') class GradeAdmin(admin.ModelAdmin): list_display = ('long_name',) ordering =...
""" Test what happens when you increase the number of training examples. In particular, in increasing the number of particles at the edges of the distribution. """ import sys sys.path.append("/home/lls/mlhalos_code") import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import AdaBoos...
import numpy as np class PopulateCBSAData(object): """ This is an optional add-on class for reader.py. It adds - CBSA (Core Based Statistical Area) code - optionally the CBSA name - optionally the boolean that is False if the zip and state passed in do not agree. to the data set. ...
''' Created on Mar 29, 2012 @author: Sol ''' import doctest def algorithmX(reversed_sets, sets, solution=[]): if not reversed_sets: yield list(solution) else: c = min(reversed_sets, key=lambda c: len(reversed_sets[c])) for r in reversed_sets[c]: solution.append(s...
from string import ascii_lowercase ct = [] str1 = "" def rotate(text, key): index = 0 for j in range(len(text)): for i in range(len(ascii_lowercase)): if ascii_lowercase[i] == text[j]: if (i+key) > 25: new_key = (i+key)-26 ct.append(as...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ================== Views on resources ================== The Napix views allow the resources to be presented differently. By default, a JSON presentation of the resource is returned. When a resource implements views, it can return different formats. For example, it c...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: fzk # @Time 12:16 import re from werkzeug.security import generate_password_hash, check_password_hash from flask_login.mixins import UserMixin from sqlalchemy import Column, Integer, String, DECIMAL, Date, Boolean, Float from app.models.base import BaseModel from ...
from dragonfly import MappingRule from castervoice.lib.actions import Key from castervoice.lib.ctrl.mgr.rule_details import RuleDetails from castervoice.lib.merge.state.short import R class TmuxRule(MappingRule): mapping = { "pane close": R(Key("c-b, x")), "pane split vertical": R(Key("c-b, perc...
########### IMPORT ########### from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, ForeignKey, desc from sqlalchemy import Column, Integer, String, Date, Text, Float, Boolean, DateTime, BigInteger from sqlalchemy.orm import sessionmaker, scoped_session, relationship, backref fr...
from __future__ import absolute_import import ast import inspect import keyword import linecache import os import re import sys import traceback from .context import PY3 from .encoding import ENCODING, to_byte, to_unicode PIPE_CHAR = u'\u2502' CAP_CHAR = u'\u2514' try: PIPE_CHAR.encode(ENCODING) except UnicodeE...