text
stringlengths
38
1.54M
class CReader(object): def __init__(self): self._fobj = None self._fpos = 0 def is_eof(self): self._fobj.seek(self._fpos) return self._fobj.readline() == "" def set_file(self, filename): if self._fobj: self._fobj.close() self._fobj = open(filename, "r") self._fpos = self._fobj.tell() def ...
""" Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com 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, m...
import math import sys from scipy.spatial import distance import sys # detect the traid in topic evolution # according to TKDE15-Traid Closure Pattern Analysis and Prediction # There are two kinds of open Traid, and 1 kind of close Traid class TraidDetect(object): """docstring for TraidDetect""" def __init__(s...
#!/usr/bin/env python #Author: Cedric Flamant import numpy as np from rotmat import rotation_matrix as RM from meas import * def ang2pos(head_pos,angles): """ Input => head_pos: (x,y,z) position of the head angles: 2d array of theta,phi for each of the following (in order): -...
import os from flask import abort, Flask, jsonify, request from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity) from flask_jwt_extended import JWTManager import requests app = Flask(__name__) ##### EMPTY ### ## # @app.route('/', me...
""" Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag). """ """ controle = 0 acumulador = 0 contador = 0 while con...
# Generated by Django 2.1.7 on 2019-03-07 00:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0002_item_rentabilidade'), ] operations = [ migrations.AlterField( model_name='item', name='preco_digitado_p...
# we can have two parameters in open or close # 1st parameter is filename and the other is which operation we have to perform - read,write,append # file= open("test.txt","r") opening file in a read mode # x= file.read() # print(x) ## Writing into the file # file= open("test.txt","w") # # y=file.write("i am nipun ...
def printCombination(arr, n, r): data = [0] * r; combinationUtil(arr, data, 0, n - 1, 0, r) def combinationUtil(arr, data, start, end, index, r): if index == r: for j in range(r): print(data[j], end=" ") print() return i = start for j in range(i, end+1): ...
import xlwt file = xlwt.Workbook() table = file.add_sheet('sheet name',cell_overwrite_ok=True) table.write(1, 1, 'text') file.save("test1.xls")
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-03 07:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pay', '0025_safe_check_status'), ] operations = [ migrations.AddField( ...
from pyAudioAnalysis import audioBasicIO from pyAudioAnalysis import ShortTermFeatures from pyAudioAnalysis import MidTermFeatures from glob import glob #TODO ''' Add number of Features Add types of Features ''' data_dir = "C:/Users/MADHUKAR/Desktop/test/abc/*.wav" audio_files = glob(data_dir) for filename in range(...
''' William Cawley Gelling 201077658 Assignment 4 Bank Accounts ''' from random import randint import datetime class BasicAccount(): ''' Basic account is the account to be used for individules for the company/Bank ''' #incremented when a bank account is made. noOfAc = 0 ...
base62_alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def base10_to_base62(number, accumulator): quotient = number // 62 remainder = number % 62 base62_remainder = base62_alphabet[remainder] if quotient == 0: return base62_remainder + accumulator else: ...
# -*- coding: utf-8 -*- import json import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours STATES = [ 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', '...
import numpy as np from nltk.tokenize import wordpunct_tokenize import math import collections from collections import Counter from models.classic.stopword import load_stopwords class LMClassifierEx: def __init__(self, tokenizer=wordpunct_tokenize, stemmer=None): self.tokenizer = tokenizer self.a...
import os import eyed3 import hashlib import time from db import Master, getitem directory = 'C:/Users/jordan.oh/Music/music' files = os.listdir(directory) total = len(files) fl = 1 for filename in files: path = os.path.join(directory, filename) print(path) file = eyed3.load(path=path) print('file load...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('formacion', '0037_revisioninterventoriadocentesoporte_revisioninterventoriaescuelaticsoporte'), ] operations = [ migrations....
import tweepy from tweepy import OAuthHandler class Myauth: consumer_key = 'O6SiTAkcuTLBahfSNaESbdjDb' consumer_secret = 'WsI4HkMKaKNE2BzHLep7BFckYl9d93onFFTkMqtZsxbn63JCSw' access_token = '2868107255-jyI0ASuGgzovt9wGfUMNm0Nsrlx6sM1nDMALrNT' access_secret = 'vLjG4JvjE7t27JnhqFEQiZXjawTplVXZImxEY5rfLO...
"""core URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vi...
import sys import argparse from psp import Pv from PyQt4 import QtCore, QtGui import time NBeamSeq = 16 dstsel = ['Include','DontCare'] bmsel = ['D%u'%i for i in range(NBeamSeq)] evtsel = ['Fixed Rate','AC Rate','Sequence'] fixedRates = ['929kHz','71.4kHz','10.2kHz','1.02kHz','102Hz','10.2Hz','1.02Hz']...
import nltk import random from nltk import word_tokenize import pickle from nltk.classify.scikitlearn import SklearnClassifier from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.linear_model import LogisticRegression, SGDClassifier from sklearn.svm import SVC, LinearSVC, NuSVC from nltk...
#!/usr/bin/env python import ROOT import os import argparse import shutil from StopsDilepton.tools.user import analysis_results, plot_directory argParser = argparse.ArgumentParser(description = "Argument parser") argParser.add_argument('--logLevel', action='store', default='INFO', nargs='?',...
from django.contrib import admin # Register your models here. from .models import * admin.site.register(Card_Type) admin.site.register(Card) admin.site.register(Player) admin.site.register(Turn) admin.site.register(Game) admin.site.register(Registred) admin.site.register(Board)
#!/usr/bin/python import argparse import sys import logging import settings from modules.SqliScanner import SqliScanner logging.basicConfig(stream=sys.stdout, level=settings.DEBUG_LEVEL) logger = logging.getLogger(__name__) # This program check if a website is vulnerable to SQL injection (wiki: https://en.wikipedi...
from pprint import pprint import yaml import datetime import uuid import sys,os,getpass import subprocess as sp import numpy as np def generate_working_dirname(run_directory): s = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") s += "_{}".format(uuid.uuid4()) return run_directory + s def get_execu...
import cv2 import numpy as np import os preds=np.load('Data/preds6.npy') num_v=np.load('Data/time_list_visual6.npy') num_t=np.load('Data/time_list_tactile6.npy') widths=np.load('Data/widths6.npy') forces=np.load('Data/forces6.npy') fps=30 path='Data/visual_6_recording/' size=(1920,1080) video = cv2.VideoWriter("Video...
import pickle import requests import json data = requests.get("https://newsapi.org/v2/top-headlines?country=in&apiKey=88ddf65370f54fab8dc8d09503f7339e").text data_dict = json.loads(data) #It will parse art = data_dict['articles'] #It will fetch the aricles key value with open ("Topheadlines.pkl","wb...
from django.db import models import uuid # Create your models here. class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(unique=True,max_length=50) password = models.CharField(max_length=50) def __str__(self): return ...
from imageIO import * from FFT import * from cmath import * import os def compress(filename="lena.mn",output_filename="lena",compression_factor=.5): '''Writes a compressed mnc file. The number of values kept is the (orginal number)*(compression_factor). This version of the compression function acts on square i...
import csv import os import pandas as pd import sys sys.path.append("..") # Adds higher directory to python modules path. from classes import Images # append files together this is used because run1 and run2 are processed through afni at the same time # supply a list of files and an out file name def append(filelist,...
import unittest import read_locations import sqlite3 class TestMediaType(unittest.TestCase): def setUp(self): self.movie = 'Lilith asdf (1964)' self.for_video = 'Lights Out (2008) (V)' self.for_tv = "Life's Other Side (2007) (TV)" self.tv_series = '"100 Greatest Discoveries" (2004)'...
import os import ui_modules BASE_DIR = os.path.dirname(__file__) options = { 'port':8888, } settings = { 'template_path':os.path.join(BASE_DIR, "templates"), "static_path": os.path.join(os.path.dirname(__file__), "static"), 'xsrf_cookies':True, 'debug':True, #'ui_modules':ui_modules, "xsr...
import json import requests from PIL import Image from time import sleep from .CJYDemo import use_cjy from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expe...
import random class XGen: rows = 0 connected_comp = 1 data = [] temp = [] linked_nodes = [] def __init__(self, rows, linked_nodes, connected_comp=1): self.connected_comp = connected_comp self.rows = rows self.linked_nodes = linked_nodes def add_nodes(self, s, e): ...
'''Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid?''' gridSize = [20,20] def recPath(gridSize): if gridSize == [0,0]: return 1 paths = 0 if gridSi...
#Capital Gains Tax (CGT) - Individuals #CGT is payable by individuals on thier taxable gains. #If there is an increase in value on disposal, there is a chargeable gain (a fall in value results in an allowable loss). #Chargeable disposals include sale, gift or loss/destruction of an asset or part of an asset. #Exempt di...
import pygame pygame.init() screen = pygame.display.set_mode((500,500)) pygame.display.set_caption("My first game") clock = pygame.time.Clock() done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done=True
# Copyright (c) 2009 ActiveState Software Inc. # See http://www.activestate.com/activepython/license/ for licensing # information. import os import sys import logging from pypm.client.base import PyPMFeature, ImagePythonEnvironment from pypm.client.fs import Extractor LOG = logging.getLogger(__name__) class Fixer(...
# Jeffrey Martinez CSC110 - 01 Airline Flight Schedule Program # Dipippo # 29 April 2015 #------------------------------------------------------------------------------- # Description of the program: # This program reads through a large data file with flight information # for all direct flights from Providence to Orla...
#!/usr/bin/python3 import subprocess import shlex import requests import argparse parser = argparse.ArgumentParser() parser.add_argument('--dev', default=False, action='store_true', help="Run the script on the dev") args = parser.parse_args() if args.dev: url = "https://freshmaker.dev.engineering.redhat.com/api/1...
# -*- coding: utf-8 -*- """ Created on Mon Mar 15 19:50:08 2021 @author: sethn """ # Import modules import gdal import pyproj import numpy as np import scipy.interpolate as interpolate def geotiff_read(infile): """ Function to read a Geotiff file and convert to numpy array. """ # Allow GDAL to throw...
from disjoint_set import DisjointSet def get_correlated_columns(corr_mat, thresh=0.8): corr_abs = corr_mat.abs() corr_vals = corr_abs.values col_names = corr_mat.columns # get correlated pairs corr_pairs = [] for i in range(len(corr_vals) - 1): for j in range(i + 1, len(corr_vals)): ...
from django.shortcuts import render def about(request): return_data = {} return render(request, 'frontend/about.html', return_data)
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ # strip text from string str = str.strip() # initialize value to return integer = 0 # set flag to signify whether or not we need to add a negative sign ...
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * from django.conf import settings from dictionary.models import Term from dictionary.forms import TermForm from wiki import views from dictionary import views as dictviews try: WIKI_URL_RE = settings.WIKI_URL_RE except AttributeError: WIKI_URL_RE...
#!/usr/bin/env python from lndynamic import LNDynamic import natsort with open(r"/home/hme/commands.txt") as hpass: lines = hpass.readlines() api = LNDynamic(lines[0].rstrip('\n'), lines[1].rstrip('\n')) results = api.request('vm', 'list') f= open(r"/home/hme/inventory_lunanode" ,"w+") hfile= open(r"/home/hme/us...
import logging import numpy as np import torch from csrank import FETAObjectRanker from iorank.training.object_ranker_trainer import ObjectRankerTrainer from iorank.util.util import get_device class FETARanker: def __init__(self, n_objects, n_object_features, add_zeroth_order_model=False, n_hidden=2, n_units=8, ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @File : rest01.py # @Author : CHIN # @Time : 2021-01-24 from flask import Flask,make_response,jsonify,abort,request from flask_restful import Api,Resource from flask_httpauth import HTTPBasicAuth app = Flask(__name__) api = Api(app=app) auth = HTTPBasicAuth() @au...
import asyncio import time import os import requests def fetch(url): """ Make the request and return the results """ start_time = time.monotonic() r = requests.get(url) request_time = time.monotonic() - start_time return {"status_code": r.status_code, "request_time": request_time} async def work...
# coding: utf-8 from dext.common.meta_relations import objects as meta_relations_objects class MetaType(meta_relations_objects.MetaType): __slots__ = () TYPE_CAPTION = NotImplemented def __init__(self, **kwargs): super(MetaType, self).__init__(**kwargs) caption = NotImplemented url = No...
################################################################################## # Written/Modified by Karl Tomecek 05/31/2019 # # Program Name: server.py # # Week 4 Assignment ...
import re from django.template import RequestContext from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseNotFound from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.models...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 22/07/2014 @author: HP ''' from Postresql import Database from Fichero import Fichero def crear_tabla_noticias(db): nombre_tabla = "Noticias" lista_columnas = ["ID", "Titulo", "Noticia", "Fecha", "Autor"] lista_valor = ["INT PRIMARY KEY", "CHAR(...
from setup_django import * import os import shutil def check(ds): pass if __name__ == "__main__": with open('datasets_in_psql_to_republish') as r: datasets = [line.strip() for line in r] with open('timeseries_error_dataset_ids') as r: ts_errors = [line.strip() for line in r] for...
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from accounting.models import * from panel.forms import * @login_required def panel(request): if request.method == 'GET': user = request.user profile = Profile.object...
# break and continue 2 python keyword when put them inside loop. import math cars = ["ok","ok","ok","faulty","ok","ok","ok"] for status in cars: if status == "faulty": print("Found Faulty Car, Skipping...") continue #print("Stopping the Production Line!!!") #break print(f"This car is {status}") p...
import plotly.express as px from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score import pandas as pd df = pd.read_csv('Admission_Predict.csv') toefl_score = df['TOEFL Score'].tolist() result = df['GRE Score'].toli...
# -*- coding: UTF-8 -*- from django.conf.urls.defaults import * from ebook import models from ebook import views urlpatterns = patterns('', url(r'^$', views.index, name='product_idx'), #timeline hot list url(r'^hot/$', views.hot, name='product_hot'), #timeline recommend list url(r'^recommen...
import tensorflow as tf import functools import numpy as np def lazy_property(function): attribute = '_' + function.__name__ @property @functools.wraps(function) def wrapper(self): if not hasattr(self, attribute): setattr(self, attribute, function(self)) return getattr(self...
#!/usr/bin/env python2 from ddnet import * serverAddresses = [ ("62.173.150.210", 8303, "ddrace.tk") , ("62.173.150.210", 8304, "ddrace.tk") , ("62.173.150.210", 8305, "ddrace.tk") , ("62.173.150.210", 8306, "ddrace.tk") ] printStatus("KOnATbl4", [], serverAddresses, True)
import numpy as np import struct from ckc.utils import ckc_params from prospect.sources import StarBasis def write_binary(z, logg, logt, sps, outroot='test', zsolar=0.0134, **extras): """Convert a *flat* hdf5 spectral data file to the binary format appropriate for FSPS, interpolating the hdf spectra to target...
import json from typing import List, Tuple import boto3 from botocore.client import BaseClient from logger.decorator import lambda_auto_logging from logger.my_logger import MyLogger from utils.lambda_tool import get_environ_values from utils.s3_tool import ( create_key_of_eorzea_database_merged_item, create_k...
import matlab.engine import os import argparse import sys if __name__ == "__main__": # Parse CLI arguments # When --help or no args are given, print this help usage_text = ( "" "python demo.py --rgb_img <path/to/rgb/image> --depth_img <path/to/depth/image> --correspondence_img <path/to/cor...
import cherrypy import device_db class DeviceDataWebService(object): @cherrypy.tools.accept(media='application/json') @cherrypy.expose def index(self, brand=None, model=None, os=None, osVersion=None): if not brand: return "" return device_db.new_device_data(brand, model, devic...
from service_charge import ServiceCharge class AddServiceCharge(object): def __init__(self, memberId, date, amount, db): self.memberId = memberId self.date = date self.amount = amount self.db = db def execute(self): sc = ServiceCharge(self.date, self.amount) e =...
import commands from pymongo import MongoClient import toml import logging import random from random import randint import re import os import time import commands import json import pdb import requests, json import sys import urllib global reg, enabled_value, apii, E_value,impr_1, impr_n with open("/var/chandni-chowk...
from odoo import fields,models,api,_ class BookingConfigSettings(models.Model): _name ="booking.order.settings" pre_booking = fields.Integer(string="Pre Booking time",required=True) post_booking = fields.Integer(String="Post Booking time",required=True)
# coding=utf-8 import os, sys, cx_Oracle, smtplib, datetime, csv, zipfile from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication def input_verify(fmdate, todate, output_type): #用户输入验证模块 db = cx_Oracle.connect('name/psw@*****') sq...
#!/bin/python #https://www.hackerrank.com/challenges/mars-exploration import sys s = raw_input().strip() count=0 i=0 while i<len(s): S,O,S1=s[i],s[i+1],s[i+2] count = count + (1 if S!='S' else 0) count = count + (1 if O!='O' else 0) count = count + (1 if S1!='S' else 0) i=i+3 print count
t = 12345, 54321, 'hello!' print(t) u = t, (1,2,3,4,5) print(u) #元组在输出时总是有括号的,以便于正确表达嵌套结构。在输入时可能有或没有括号, 不过括号通常是必须的(如果元组是更大的表达式的一部分
from django.urls import path from . import views urlpatterns = [ path('',views.index,name = 'approvalView'), path('<int:object_id>/', views.pending, name='pending'), path('<int:object_id>/approved', views.approved, name='approve'), path('<int:object_id>/reval', views.reval, name='reval'), ]
import pandas as pd grades = pd.Series([87,100,94]) myarray = pd.Series(98.6, range(3)) ''' print(myarray) print(grades[0]) print(grades.describe()) ''' grades = pd.Series([87,100,94],index=['Wally','Eva','Sam']) print(grades) grades = pd.Series({'Wally':87, 'Eva':100, 'Sam':94}) print(grades) hardware = pd.S...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过pywin32库,通过调用本地windows API的方式实现抓取功能 屏幕抓取器利用windows图形设备接口(GDI)获取抓取屏幕时必须的参数,如屏幕大小分辨率等信息。 """ import selenium import win32gui import win32ui import win32con import win32api
import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, ge...
啊实打实asdfsadfasdfsfasdfsa苏打 sadfsd asd fasd fasdasdf asdf sadfsdasd 啊实打xiao asdasd asd asd as苏打 heelo woorlld asd as
# -*- coding: utf-8 -*- ''' Created on May 29, 2012 @author: feralvam ''' def position(argcand): """ Indicates whether the word occurs before(0) or after(1) the target verb """ verb_pos = argcand["verb"]["address"] arg_pos = argcand["info"]["address"] if arg_pos < verb_pos: ...
# -------------- import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # Code starts here df = pd.read_csv(path) print(df.head()) print(df.info()) cols = ['INCOME','HOME_VAL','BLUEBOOK','OLDCLAIM','CLM_AMT'] for col in cols: ...
from django.contrib import admin from .models import (Promotion) admin.site.register(Promotion) # Register your models here.
#!/usr/bin/env python import multiprocessing import time def func(name): print 'start process' time.sleep(2) return name.upper() if __name__ == '__main__': results = [] p = multiprocessing.Pool(5) for i in range(7): res = p.apply_async(func,args=('kel',)) results.append(res) ...
import socket #get ips - dynamically - from ensemble #assign ranges server = ['127.0.0.1', '127.0.0.1', '127.0.0.1'] port = [6066, 6067, 6068] s = ["" , "", ""] for i in range(0,3) : s[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s[i].connect((server[i],port[i])) while True: comman...
from collections import defaultdict slownik = defaultdict(int) # po wpisaniu defaultdict() podkreśli się na czerwono, wtedy robimy # lewy Alt+Enter i na samej górze pojawi się "from collections import defaultdict print(slownik) print(slownik['ala']) print(slownik) slownik['kot']...
from sqlalchemy import ( Column, Index, Integer, Text, String, ForeignKey, ) from .meta import ( Base, DBSession, ) from sqlalchemy.orm import relationship, backref class Cliente(Base): __tablename__ = 'clientes' id = Column(Integer, primary_key=True) RFC = Column(String(20))...
#!/usr/bin/env python # -*- coding: utf-8 -*- from settings import RPI as geometry from src import RunManager, start_gui, particles #remove distracting particles particles.TABLE.pop("Kohlenstoff") particles.TABLE.pop("Elektron") particles.TABLE.pop("Alpha") particles.TABLE.pop("Gamma") particles.TABLE.pop("Muon") parti...
from enum import Enum class Platform(Enum): IOS = "iOS" ANDROID = "Android" H5 = "H5" MP = "Mp" class SdkType(Enum): IOS = "iOS" ANDROID = "Android" H5 = "H5" MP = "Mp" class Network(Enum): N_3G = "3G" N_4G = "4G" N_5G = "5G" N_WIFI = "wifi" class Os(Enum): IOS = ...
from django.db import models from django.utils import timezone class Encuesta(models.Model): autor = models.ForeignKey('auth.User') nombre = models.CharField(max_length=200) fecha_creacion = models.DateTimeField( blank=True, null=True) universo = models.IntegerField(defa...
import pandas as pd def readDataFromExcel(path, option, request, columnList): # 数据中不包含列名 # df = pd.read_excel(path, sheet_name=0, header=None, skiprows=1) df = pd.read_excel(path, sheet_name=0) df = df[df[option] == request].loc[:, columnList] return df
from ROOT import TH1D, TFile, TCanvas, gStyle, gPad, TLegend gStyle.SetOptStat(0) cann = TCanvas("cann","cann") cann1 = TCanvas("cann1","cann1") canp = TCanvas("canp","canp") canp1 = TCanvas("canp1","canp1") cann.cd() gPad.SetLogy(1) CanvasTitle = "Monday" FilenameTitle = "Monday" #Monday file_WINE = TFile("win...
import os from datetime import datetime, timedelta from functools import wraps def list_files(dirname, filter=['.json']): result = [] for maindir, subdir, file_name_list in os.walk(dirname): for filename in file_name_list: apath = os.path.join(maindir, filename) ext = o...
import imaplib import socket import re class ImapGmailClient: IMAP_HOST = 'imap.gmail.com' def __init__(self, login, password): socket.setdefaulttimeout(10) self.username = login self.password = password self.authorized = False self.imap = imaplib.IMAP4_SSL(self.IMAP_HOST) def __del__(self): self.imap...
import cv2 import rects import utils class Face(object): """Data on facial features: face, eyes, nose, mouth""" def __init__(self): self.face_rect = None self.left_eye_rect = None self.right_eye_rect = None self.nose_rect = None self.mouth_rect = None class FaceTrack...
from django.db import models class TextStatementModel(models.Model): statement_text = models.CharField(max_length=500, blank=False, null = False) statement_author = models.CharField(max_length=500, blank=False, null=True) statement_source = models.ForeignKey('TextSatementSourceModel', on_delete=models.CA...
#!/usr/bin/env python import unittest import detect_pointer_in_rect class TestPointerDetection(unittest.TestCase): def setUp(self): if(__name__=="__main__"): test_pointer_detection()
# Starter code for Homework 4 # %% # Import the modules we will use import os import numpy as np import pandas as pd import matplotlib.pyplot as plt # %% # ** MODIFY ** # Set the file name and path to where you have stored the data filename = 'streamflow_week4.txt' filepath = os.path.join('../data', filename) print(o...
from django.contrib.gis.db import models from django.core.cache import cache # Create your models here. class Trip(models.Model): # class Meta: # db_table = 'taxi_trip_timescale' vendorID = models.SmallIntegerField(null=True,blank=True) pickupTime = models.DateTimeField(null=True,blank=True) dro...
import argparse import os from cira.labs.leat.structs.Bunch import Bunch def parse_args(): argument_parser = argparse.ArgumentParser(prog="le-at") create_arguments(argument_parser) args = argument_parser.parse_args() print(args) args = args_to_bunch(args) print(args) return args def cre...
from WMCore.Configuration import Configuration step = 'lhe' part = 'p3' config = Configuration() config.section_('General') config.General.requestName = '_'.join(['ttjets_dl', step, part]) config.section_('JobType') config.JobType.pluginName = 'PrivateMC' config.JobType.psetName = 'configs/ttjets_dl_lhe.py' config....
import mdtraj.io as io import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) rcParams['axes.linewidth'] = 3 rcParams.update({'font.size': 20}) # load tICA object ti = io.loadh('tica_l20.h5') vecs = ti['components'] cov = ti['covariance'] # ca...
def plot_defaced(bids_dir, subject_label, session=None, t2w=None): """ Plot brainmask created from original non-defaced image on defaced image to evaluate defacing performance. Parameters ---------- bids_dir : str Path to BIDS root directory. subject_label : str Label of sub...
from flask import Flask,redirect,url_for,render_template,request import jwt # import request as request # from flask_jwt import JWT, jwt_required, current_identity import flask_sijax as simpleajax import sqlite3 as sql app = Flask(__name__) # app.config['SECRET_KEY'] = 'super-secret' @app.route('/createtable/<tablenam...