text stringlengths 38 1.54M |
|---|
# Get times of all water flows for experiments and match them to the flows from the events file.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
from itertools import cycle
import os as os
from pylab import *
import datetime
data_location = '../2_Data/'
info_location = '../3_Inf... |
##
## junxonauth.py
## Author : <shekhar@inf.in>
## Started on Fri May 14 11:28:18 2010 Shashishekhar S
## $Id$
##
## Copyright (C) 2010 INFORMEDIA
## 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 Found... |
import re
import barcode
import logging
import operator
from django.core.files.storage import default_storage
from django.utils import timezone
from django.db import transaction
from django.conf import settings
from contextlib import suppress
from django.urls import reverse
from django.db.models import Q
from django.db... |
# absolute value
print(abs(-2))
# all values are true, which means either true, either not zero, either not None
print(all([1,2,3])) # true
print(all([0,1,2])) #false
# any value is true, not zero or not none
print(any([0,None,False])) # false
print(any([0,False,1])) #true
# returns ascii only representation of the... |
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if not grid or grid[0][0]==1 or grid[-1][-1]==1:
return -1
q = deque([])
q.append([0, 0, 1])
visited = set()
visited.add((0, 0))
dirs = [(-1, 0), (-1, -1), (-1, 1), ... |
# This file is part of KoreanCodecs.
#
# Copyright(C) 2002-2003 Hye-Shik Chang <perky@FreeBSD.org>.
#
# KoreanCodecs is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2 of the License, or
#... |
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.views.generic import ListView, TemplateView, FormView
from gscan.models import *
from gscan.tasks.tasks import *
from django.contrib.auth.decorators import login_required... |
import requests
from urllib.parse import urlencode
import hmac, hashlib, datetime, math, json
import traceback
from numpy import linspace
from pandas import to_numeric
from time import time
from pytz import reference
from ..utils.utils import since
from ..utils.types import *
ROOT_URL = 'https://api.binance.com/api/v3... |
from unittest.mock import patch
import pytest
from feed_proxy import conf
reader_class = conf.ConfigReader
@pytest.mark.parametrize('string,expected', [
('', tuple()),
('cookie', ('cookie',)),
('icecream chocolate', ('icecream', 'chocolate')),
(' hop hey ', ('hop', 'hey')),
('поп корн', ('поп'... |
from collections import deque
class Treenode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def addNode(self, val):
return Treenode(val)
def k_list_of_lists_btree(self, root, k):
if root is None:
... |
from bs4 import BeautifulSoup
from urllib.request import Request,urlopen
from urllib.parse import urljoin
from urllib.error import URLError
import time
import telepot
import json
import sys
import codecs
# download pip
# wget https://bootstrap.pypa.io/get-pip.py --no-check-certificate
# python -m pip install Beautif... |
import copy
import importlib
import math
import model.utils.dijakstra as dijakstra
import model.utils.dispatcher_utils as dispatcher_utils
from model.entities.vertex import Vertex
from model.entities.point import Point
import time
def run_algorithm_on_world(world, alg_name, alg_args, tpd):
vertexes = create_verte... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from contextlib import contextmanager
import threading
import tensorflow as tf
from tensorflow.python.framework import errors
from tensorflow.python.platform import tf_logging as loggin... |
import numpy as np
import pandas as pd
# IMPORTANT: DO NOT USE ANY OTHER 3RD PARTY PACKAGES
# (math, random, collections, functools, etc. are perfectly fine)
class DecisionTree:
def __init__(self):
# NOTE: Feel free add any hyperparameters
# (with defaults) as you see fit
pass
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-05 11:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('store', '0011_auto_20180405_1226'),
]
operations ... |
'''
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
ecd = sys.getdefaultencoding()
print(ecd)
'''
import pymysql as MySQLdb
import tushare as ts
import pandas as pd
import lxml.html
from lxml import etree
import re
import time
from pandas.compat import StringIO
try:
from urllib.request import urlopen, Reque... |
def score(planete, nb_satellite_reel):
while planete != -1:
phrase = "Nombre de satellite(s) de la planète " + planete + ": "
sat =int(input(phrase))
while sat - nb_satellite_reel != 0:
if sat - nb_satellite_reel >0:
print("trop haut, retente !")
sat = int(input(phrase))
if sat - nb_satell... |
'''
Created on May 5, 2013
@author: Remus
The script create swords which follow another sword.
Use Expression Editor (Windows -> Animation Editors -> Expression Editor)
Use scene "Swords.ma".
'''
import maya.cmds as mc
def lag(frame, goal, follower, lagAmount):
'''
This function move and ro... |
# Generated by Django 2.2.6 on 2020-11-04 05:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('StudentManagement', '0005_auto_20201103_2157'),
]
operations = [
migrations.AlterModelTable(
name='calificaciones',
table='c... |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
# ---------------------------------------------SCREEN SETUP-----------------------------------------------
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
# ------... |
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local[*]").setAppName("employees")
sc = SparkContext(conf = conf)
employees = [['Raffery',31], ['Jones',33], ['Heisenberg',33], ['Robinson',34], ['Smith',34]]
department = [31,33]
employees = sc.parallelize(employees)
department = sc.paralleli... |
"""ops.syncretism.io model"""
__docformat__ = "numpy"
import configparser
import logging
from typing import Dict, Tuple
import pandas as pd
import yfinance as yf
from openbb_terminal.core.config.paths import (
MISCELLANEOUS_DIRECTORY,
)
from openbb_terminal.core.session.current_user import get_current_user
from ... |
import cv2
from PIL import Image
from MessageBox import MessageBox
class ImageNegativeTransformation:
def ProcessTransformation(inputFile):
try:
im=Image.open(inputFile)
img = cv2.imread(inputFile)
cv2.imshow("Original Image",im... |
# Generated by Django 2.2.3 on 2019-09-24 22:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("main", "0019_remove_metadata_size_and_class")]
operations = [
migrations.AlterField(
model_name="worklistcolumn",
name="ordering"... |
# Questo script python permette di effettuare un'acquisizione automatica delle posizioni dei tag,
# utilizzando l'algoritmo di posizionamento della pozyx.
# La posizione dei tag determinata dall'algoritmo viene comunicata sulla linea UWB al dispositivo
# che è connesso alla porta USB del PC. Sullo schermo vengono stamp... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import MySQLdb
import json
import chardet
from jsqbmysql import dev,test
from jsqblinux import loan,debit
from cuserid import searchuid,inver
from backstage import verify
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
uid=searchuid()
#后台机审,初审... |
#!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
from django.contrib import admin
from models import Message
class MessageAdmin(admin.ModelAdmin):
list_display = ('identity', 'date', 'direction', \
'get_status_display', 'text')
list_filter = ['direction', 'status']
search... |
import folium
import pandas #to load csv file with data
data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elevation = list(data["ELEV"])
def marker_color(elevation):
if elevation < 1000:
return 'green'
elif 1000 <= elevation < 3000:
return 'orange'
els... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-02-06 09:19
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20180119_1247'),
]
... |
str_numbers = input().split()
counter = int(input())
numbers = []
for num in str_numbers:
num = int(num)
numbers.append(num)
for _ in range(counter):
numbers.remove(min(numbers))
print(numbers)
|
#!/usr/bin/python
from set1 import *
import sys, getopt, socket
BUFFER_SIZE = 2048
port=4632
host="10.101.1.10"
def checkpoint2_oracle(plaintext, sock):
if (plaintext == ""):
plaintext = "NULL"
sock.send(plaintext)
#print "Sending: " + plaintext
resp = sock.recv(BUFFER_SIZE)
#print "Recei... |
import fnmatch
import os
import pyngram;
import Distribution_Utils;
import numpy as np;
from scipy import stats;
import generateGraphs;
def GetFastaFiles(dirName, searchRe):
matches = []
for root, dirnames, filenames in os.walk(dirName):
for filename in fnmatch.filter(filenames, searchRe):
matches.app... |
# https://github.com/flaport/sax
from SiEPIC.install import install
install('sax')
def coupler(coupling=0.5):
kappa = coupling**0.5
tau = (1-coupling)**0.5
sdict = sax.reciprocal({
("in0", "out0"): tau,
("in0", "out1"): 1j*kappa,
("in1", "out0"): 1j*kappa,
("in1", "out1"):... |
"""Additionnal DDL for SQL Alchemy."""
from sqlalchemy.sql.ddl import _CreateDropBase
class _CreateDropBaseView(_CreateDropBase):
"""A base for Create and Drop View."""
def __init__(self, element, cascade=False, on=None, bind=None):
self.view = element
self.cascade = cascade
super().... |
# Copyright 2017 MDSLAB - University of Messina
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
class Path:
def __init__(self):
self.id = 0
self.edges = []
def __repr__(self):
return "\nPathid:"+str(self.id)+"\nedges:"+str(self.edges)+"\ntransponder_id:"
def __str__(self):
return "\nPathid:"+str(self.id)+"\nedges:"+str(self.edges)+"\ntransponder_id:"
|
from django.db import models
from django.http import request
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, FormView
from django.views.generic.base import View
from .models import Category, Post, Commen... |
from django.urls import path
from .views import (
comment_create_view,
comment_delete_view,
comment_update_view,
)
app_name = 'comments'
urlpatterns = [
path('create/<int:id>', comment_create_view, name='create'),
path('delete/<int:id>', comment_delete_view, name='delete'),
path('update/<int:i... |
import os.path
import zope.interface
from plone.z3cform.templates import ZopeTwoFormTemplateFactory
from plone.z3cform.interfaces import IFormWrapper
from pmr2.app.browser.layout import FormWrapper
class IShjsLayoutWrapper(IFormWrapper):
"""
The interface for the SHJS layout wrapper.
"""
path = lambda... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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 above copyright notice, this
# ... |
# In Python, a truthy value is a value that translates to True when evaluated in
# a Boolean context. All values are truthy unless they're defined as falsy.
# All falsy values are as follows:
# False
# None
# 0
# []
# {}
# ""
# Create a function that takes an argument of any data type and returns 1 if... |
from rest_framework.test import APITestCase, APIClient
from django.contrib.auth import get_user_model
class TestSetUp(APITestCase):
def setUp(self):
self.product_url = '/products/'
self.product_data = {
'product_name': 'Pant',
'description': 'Nice',
'price': 100.... |
################################################################################
# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the LICENSE file for details.
# SPDX-License-Identifier: MIT
#
# Fusion models for Atomic and molecular STructures (FAST)
# Fusion mo... |
import os
import re
import sys
from collections import defaultdict
from conans.model.ref import ConanFileReference
from conan.test_package_runner import TestPackageRunner, DockerTestPackageRunner
from conan.builds_generator import (get_linux_gcc_builds, get_visual_builds,
get_osx_a... |
print (" this process is for First Come First Serve")
size = int(raw_input("Enter How many Process you want to Enter ??"))
process = [0] * size
arrival = [0] * size
burst = [0] * size
for i in range(size):
process[i] = (raw_input("Enter process name"))
arrival[i] = int(raw_... |
#声明一个学员列表
student_list=[]
while True:
print(''''
1-添加学员姓名:
2-修改学员姓名:
3-查询学员姓名:
4-删除学员姓名:
0-退出
''')
select_number=int(input('请输入操作序号:'))
while select_number<0 or select_number>4:
select_number=int(input('输入错误,重新输入'))
if select_number==1:
name=input('请... |
import sys
from heapq import *
class StringWrapper:
def __init__(self,s):
self.s = "".join([ x for x in s if x != "\n" ])
def __eq__(self,that):
return len(self.s) == len(that.s)
def __lt__(self,that):
return len(self.s) < len(that.s)
def __gt__(self,that):
return len(self.s) > len(that.s)
def ... |
from datetime import datetime, timedelta
from typing import Any, Dict, List
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.testclient import TestClient
from jose import JWTError, jwt
from passlib.context impor... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import
import distutils.util
try:
from importlib.machinery import EXTENSION_SUFFIXES
except ImportErr... |
# it is a mian module where all the program will execute after running this module
# this module has imported two module
# Module 1 is imported to read and display
import Module_1_Read_Display_File
Module_1_Read_Display_File.readDisplayFile()
#Modile 3 is imported for the transaction of borrowing and returning part.
... |
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="Area51"
__date__ ="$Mar 9, 2011 4:10:58 AM$"
class KeyCleaner():
def unset_tweet_keys(self,content):
if content.has_key("retweeted_status"):
content["retweeted_status"] = self.unset_tweet_key... |
import sys
# Task:
# Write a MapReduce program which determines the number of hits to the site made by each different IP address
# Line example:
# 10.223.157.186 - - [15/Jul/2009:15:50:35 -0700] "GET /assets/js/lowpro.js HTTP/1.1" 200 10469
for line in sys.stdin:
data = line.strip().split(' ')
if len(data) i... |
class Heap:
heap = []
treetable = dict()
def getLeftchild(node):
return 2*node+1
def getRightchild(node):
return 2*node+2
def parent(node):
if node == 0:
return None
elif node == 1:
return 0
return int((node-1)/2)
... |
import time
from config import *
from models import *
from user import User
from position import Position
import utils
from alert_event import AlertEvent
from alert import Alert
def clear_all_data():
if input('Are you sure you want to delete everything? YES/no ') == 'YES':
for p in Position.objects():
... |
# import tkinter as tk
#
#
# # ************************
# # Scrollable Frame Class
# # ************************
# class ScrollFrame(tk.Frame):
# def __init__(self, parent):
# super().__init__(parent) # create a frame (self)
#
# self.canvas = tk.Canvas(self, borderwidth=0, background="#ffffff") # p... |
name = " kittisak "
name_1 = "KITTISAK"
name_2 = "Kittisak frank"
name_3 = "kittisak nuntasen frankygo"
name_4 = "NUNTASEN"
print(len(name))# หาความยาวของข้อความ
name.split #ลบช่องวางในข้อความ
name.lstrip #ลบช่องวางซ้าย rsptrip ลบขวา
print(name)
print(name_1.lower()) #พิมเล็ก
print(name.upper()) #พิมใหญ่
print(... |
import logging
from flask import Flask
from routes import api
FORMAT = '%(asctime)s|%(name)s|%(levelname)s|%(lineno)d|%(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
LOGGER = logging.getLogger(__name__)
app = Flask(__name__)
app.register_blueprint(api.core)
if __name__ == "__main__":
app.run(... |
import torch
print(torch.__version__)
import torch.optim as optim
import torch.utils.data as data_utils
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from pytorch_lightning.metrics import Accuracy
from network import DeepFMNet
from data_loader import CustomDataset
EPOCHS = 500
EMBEDDING_SIZE ... |
#!/usr/bin/env python3
'''
Prompt:
Let S(A) represent the sum of elements in set A of size n. We shall call it a
special sum set if for any two non-empty disjoint subsets, B and C, the
following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C the... |
from app import object_to_initialize
print("--- Object to initialize field_1 = " + object_to_initialize.field_1)
|
from bs4 import BeautifulSoup
import aiohttp
import asyncio
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/
# pip install beautifulsoup4
"""
웹 크롤링 : 검색 엔진의 구축 등을 위하여 특정한 방법으로 웹 페이지를 수집하는 프로그램
웹 스크래핑 : 웹에서 데이터를 수집하는 프로그램
"""
async def fetch(session, url, i):
print(i + 1)
async with session.get(url) ... |
# circle 클래스 생성
# 속성(변수) : 반지름 -> radius , 외부에서 속성을 참조하지 못 하도록 보호
# 기능(메서드) : 원의 둘레, 원의 넓이
import math
class Circle:
#생성자
def __init__(self, radius):
self.__radius = radius
#__radius의 getter
@property
def radius(self):
return self.__radius
#__radius의 setter
@radius.sett... |
#!/usr/bin/env python3
import sqlite3
import config
conn = sqlite3.connect(config.USERS_DB_PATH)
conn.cursor().execute('''CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL... |
from django.apps import AppConfig
class RegulatoryInfoConfig(AppConfig):
name = 'regulatory_info'
|
# Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ... |
# used Functions - unique(), create dictionary with zip
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import cm
from sklearn.model_selection import train_test_split
df = pd.read_table('class_fruit_data_with_colors.txt')
df.head(10)
# create a mapping from fruit label value to... |
from taskplus.core.shared.domain_model import DomainModel
class Task(object):
def __init__(self, name, content, status, creator, doer=None, id=None):
self.name = name
self.content = content
self.status = status
self.creator = creator
self.doer = doer
self.id = id
... |
"""inventory_manager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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')
C... |
import pydicom
import os
import numpy as np
import itertools
import glob
import argparse
import json
def normalize(x):
return x / np.sqrt(np.dot(x,x))
def readRotAndTrans(paths):
files = list(itertools.chain.from_iterable([glob.glob(path) for path in paths]))
head = [(np.array([1,0,0,0]),np.array([0,0,0]))]
... |
import random
import logging
import time
from abc import ABC, abstractmethod
from typing import Tuple, List, Dict, Any
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.patches import Ellipse
import numpy as np
from numpy import pi
import statistics
matplotlib.use('Tk... |
import pyautogui
import time
import threading
import pandas as pd
import json
import os
import shutil
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import Web... |
getal1 = float(input("Geef een getal in: "))
getal2 = float(input("Geef een getal in: "))
if getal1 < getal2:
kleinste_getal = getal1
grootste_getal = getal2
else:
kleinste_getal = getal2
grootste_getal = getal1
if kleinste_getal == 0:
antwoord = "Je kan niet delen door nul"
else:
antwoord = g... |
from shared.common_query import FilterableMixin, ArithmeticOperable, Comparable
class Aggregation:
pass
class Count(FilterableMixin, ArithmeticOperable, Comparable, Aggregation):
def reducer(self, queryset):
return len(list(queryset))
class Sum(FilterableMixin, ArithmeticOperable, Comparable, Aggr... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
#https://open.kattis.com/problems/heartrate
n=int(input())
for _ in range(n):
b,p=list(map(float,input().split()))
bmin=60/(p/(b-1))
bpm=60*b/p
bmax=60/(p/(b+1))
print(float(round(bmin,4)),float(round(bpm,4)),float(round(bmax,4)))
|
import sys
from MainWidget import MainWidget
from PyQt5 import QtWidgets
def exception_hook(exctype, value, traceback):
sys._excepthook(exctype, value, traceback)
sys.exit(1)
def main():
sys._excepthook = sys.excepthook
sys.excepthook = exception_hook
app = QtWidgets.QApplication(sys.argv)
wid... |
from django import forms
class CookieCutterForm(forms.Form):
repo_name = forms.CharField(label="Repo name")
def __init__(self, cookie, *args, **kwargs):
super(CookieCutterForm, self).__init__(*args, **kwargs)
self.cookie = cookie
if cookie.options is None:
return
... |
from skimage.filters import gabor_kernel
from skimage import io
from skimage.transform import resize
from matplotlib import pyplot as plt
import numpy as np
import math
def get_gabor_filters(inchannels, outchannels, kernel_size=(3, 3)):
delta = 1e-4
freqs = (math.pi / 2) * math.sqrt(2) ** (-np.random.randint(... |
import io
import time
import zipfile
from .zlibstream import ZlibStream
class _ZipInfoFacade(zipfile.ZipInfo):
'''
Make some fields read-only for wrapped zipfile.ZipInfo
'''
__readonly__ = (
'CRC',
'compress_size',
'file_size',
)
def __init__(self, wrapped_info):
... |
import os, sys
#os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import pandas as pd
import numpy as np
eps = 0.004
desired = {
0: 0.36239782,
1: 0.043841336,
2: 0.075268817,
3: 0.059322034,
4: 0.075268817,
5: 0.075268817,
6: 0.043841336,
7: 0.075268... |
TechT = ['TENNANT','MILLER','MAYER','WIESER','LORD-MAY',"BISHOP","LAU","CHAN","MABIOR"]
ElementT = ['Mo','Cu','B','U','Fe','Zn','Sr','S']
ContractT= ['RESEARCH','AGAT','GRASBY','SPENCER','MIRNA','MONCUR',"LORENZ","OMID"]
TypeT =['SAMPLE','STANDARD','BLANK']
SpikeT = ['NONE','SINGLE','DOUBLE','E_DOPING']
Machine = ["NEP... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 22:51:27 2020
@author: python MATLAB & GIS
"""
import datetime
import subprocess
import os
import time
from moviepy.editor import VideoFileClip
current_dir = os.getcwd()
print(current_dir)
def main():
#define clipping information
start_point = 0
du... |
import json
import urllib
import logging
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from markov_by_char import CharacterMarkovGenerator
define("port", default = 8000, help = "Run on the given port ", type = int)... |
"""Abstract Interface for a Ticket Provider"""
class TicketProvider():
def __init__(self):
raise NotImplementedError
@classmethod
def getTracker(cls, project_path):
""" Get the details from the issue tracker at path """
raise NotImplementedError
@classmethod
def getMemb... |
#!/sv/venv/T-PLE/bin/python2.7
from __future__ import print_function
from scripts.baseController import baseELOCalculations as ELOCal
import winStreakUpdate
import updateVSResults
import historicELOUpdate
def main():
accumulativeDiff = False
currentLog, winsLosses, ELOs = ELOCal.getLog(), ELOCal.getWL(), ELO... |
# Extract skill description from data.grf
FILE = 'items'
listItemsSee = []
with open(FILE) as fp:
for line in fp:
info = line.split("#")
if (len(info) > 2 and info[0] not in listItemsSee):
print("{}={}".format(info[0], info[1]))
listItemsSee.append(info[0]) |
"""
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
f = open('foo.t... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
import requests
from bs4 import BeautifulSoup
list= []
url = "http://trends24.in/india/~cloud"
sc = requests.get(url)
soup = BeautifulSoup(sc.text,"lxml")
li = soup.find_all('li')
for data in li:
list.append((data.find('a').text))
for i in list:
if(i[1]=='#'):
print(i)
print('-----... |
import numpy as np
import scipy
import imageio
def make_gif(images, fname):
imageio.mimwrite(fname, images, subrectangles=True)
print("wrote gif")
def discount(x, gamma, terminal_array=None):
if terminal_array is None:
return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]
else:
... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the d... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, JsonResponse
from django.template import loader
from django.views.decorators.csrf import csrf_exempt
from . import classifier
from . import prepare_data
from . import utils
import numpy as np
def index(request):
... |
# Generated by Django 3.1 on 2020-09-02 12:49
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("payment", "0019_auto_20200812_1101"),
]
operations = [
migrations.AlterField(
model_name="payment",
... |
import json
if __name__ == '__main__':
with open('simple_base.csv', 'w') as w:
w.write('TRIP_ID,LATITUDE,LONGITUDE\n')
with open('../data/test.csv', 'r') as f:
f.readline()
for line in f:
entries = line.strip().split('"')
print entries
tid = entries[1].strip('"')
polylines = json.loads(entr... |
from django.conf.urls import patterns,url
from blog import views
urlpatterns = patterns(
url(r'^$',views.index),
url(r'/detail/(?P<blogid>\d+)/$', views.detail),
url(r'/search/', views.search),
url(r'/searchbycategory', views.searchbycategory),
)
|
import numpy as np
import pandas as pd
import sklearn.metrics as metrics
import inference
import utils
def evaluate_audio_tagging(y_true, y_pred, threshold=-1):
"""Evaluate audio tagging performance.
Three types of scores are returned:
* Class-wise
* Macro-averaged
* Micro-averaged
T... |
# -*- coding: utf-8 -*-
# Main interface between Anki and this addon components
from anki.cards import Card
# This files is part of schedule-priority addon
# @author ricardo saturnino
# ------------------------------------------------
from .core import Feedback, AppHolder, Priority, InvalidConfiguration
from .priorit... |
numero_eleitores = int(input("Numero eleitores: "))
votos_brancos = int(input("Numero votos brancos: "))
votos_nulos = int(input("Numero votos nulos: "))
votos_validos = int(input("Numero votos validos: "))
def regra_tres(numero_eleitores,TV):
return ((TV*100)/numero_eleitores)
print("",regra_tres(n... |
import pandas as pd
import numpy as np
import sqlite3
conn = sqlite3.connect('test_tran.db')
cur = conn.cursor()
# Запрос к таблице tran (клиенты, которые в месяц осуществляют по карте траты на сумму не менее 100 тыс. рублей/
# для каждой строки получение предыдущего месяца)
cur.execute("SELECT month, id... |
import smtplib
from email.message import EmailMessage
email = EmailMessage()
email['from'] = '<Name>'
email['to'] = '<recievers_email>'
email['subject'] = '<email_subject>'
email.set_content('email_body')
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:#set up the smtp server according to your email clien... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.