content stringlengths 5 1.05M |
|---|
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from actions.api_v1.api import api_router
app = FastAPI(
title="FLIP API",
description="This API provides a REST interface to FLIP CLI.",
)
origins = [
"http://localhost",
"http://localhost:3000",
"http://127.0.0.1... |
import os
import json
import requests
from jinja2 import Template
def get_events():
"""Get the latest events from the API."""
response = requests.get('https://polisen.se/H4S-2018-handelser.json')
response.encoding = 'utf-8-sig'
data = json.loads(response.text)
return data[:50]
def convert_event... |
class Vegetation:
def __init__(self, x, y, emoji):
self.x = x
self.y = y
self.life_force = 10
self.emoji = emoji
@property
def coord(self):
return self.x, self.y
def move(self):
self.life_force = 0.9 * self.life_force
def eaten(self):
self.l... |
import urllib, json, os, pyowm
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/', methods=['POST'])
def webhook():
req = request.get_json()
json.dumps(req, indent=4)
res = processRequest(req)
... |
import json
import os
import numpy as np
from constants import data_pool_path
class FileWriter:
def __init__(self, filename, content):
self.fname = filename
self.content = content
def writeFile(self):
try:
with open(self.fname, 'w+') as f:
f.write(self.cont... |
import discord
from discord.ext import commands
import getanime as ga
from pages import EmbedPaginator
class Anime(commands.Cog):
def __init__(self, client):
self.client = client
# Events
@commands.Cog.listener()
async def on_ready(self):
print('The Anime cog was successfully loaded!'... |
import tkinter as tk
from tkinter import filedialog
import os
import cv2
import sys
import cv2 #opencv itself
import common #some useful opencv functions
import numpy as np # matrix manipulations
import imutils
from matplotlib import pyplot as plt # this lets you draw inline pictures in the notebooks
import r... |
#!/usr/bin/env python3
import argparse
import json
import sys
import langdet
parser = argparse.ArgumentParser(description='Create language detection models')
parser.add_argument('filename', type=str,
help='Text file to process')
parser.add_argument('--ngramSize', type=int, default=3,
... |
#!/usr/bin/env python3
import requests
def get_content(url):
paste_info = {
'site': 'bpaste',
'url': url,
}
# NOTE: http://stackoverflow.com/a/18579484/3716299
base_url = "https://bpaste.net/raw/%s"
paste_id = url.split('/')[-1]
content_url = base_url % paste_id
respons... |
def wc(file_):
"""Takes an absolute file path/name, calculates the number of
lines/words/chars, and returns a string of these numbers + file, e.g.:
3 12 60 /tmp/somefile
(both tabs and spaces are allowed as separator)"""
with open(file_) as f:
text = f.read()
filename =... |
# -*- coding: utf-8 -*-
import os
import re
import sounddevice as sd
from utils import read_wav, write_wav
import numpy as np
from threading import Thread
import argparse
class DeviceNotFoundError(Exception):
pass
def record_target(file_path, length, fs, channels=2, append=False):
"""Records audio and writ... |
"""
Game screen where we show the game.
"""
from threading import Thread
from enum import Enum
import pygame
from map import Map
from .screen import Screen
from consts import Screens, MAP_FOLDER, IMAGE_FOLDER
from config import CONFIG
from player import Player
from bot import Bot
from gui import Button, ButtonState
f... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SorterLauncher.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.... |
from django.apps import AppConfig
class ComunicadosConfig(AppConfig):
name = 'comunicados'
|
# Part of a temporary placeholder for a CN object
import socketserver,socket
class MYTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{}:{} wrote: ".format(self.client_address[0],self.client_address[1]))
print(self.data)
... |
# -*- coding:utf-8 -*-
# This file is adapted from the torchvision library at
# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
# 2020.6.29-Changed for Modular-NAS search space.
# Huawei Technologies Co., Ltd. <linyunfeng5@huawei.com>
# Copyright 2020 Huawei Technologies Co., Ltd.
... |
# Generated by Django 2.2.11 on 2020-03-18 20:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stock_wallet', '0008_auto_20200318_2104'),
]
operations = [
migrations.RenameModel(
old_name='Record',
new_name='PurchasedS... |
# Print N reverse
# https://www.acmicpc.net/problem/2742
print('\n'.join(list(map(str, [x for x in range(int(input()), 0, -1)]))))
|
class Solution:
def frequencySort(self, s: str) -> str:
counter = collections.Counter(s)
return ''.join(sorted(list(s), key=lambda x: (counter[x], x), reverse=True))
|
def saveColors(cube, positions, clusters, orientation):
# White red green
if orientation == 'wr':
# White
for i, facelet in enumerate(clusters[0]):
x = 2 - positions[1][i]
y = 2 - positions[0][i]
if cube[0][x][y] == None:
cube[0][x][y] = [facel... |
#!/usr/bin/env python3
#
# Copyright (C) 2021 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import sys, os
import logging
import subprocess # nosec
import lxml.etree
import argparse
from importlib import import_module
from cpuparser import parse_cpuid, get_online_cpu_ids
script_d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'lib'))
from splunklib.searchcommands import \
dispatch, StreamingCommand, Configuration, Option, validators
from splunklib.six import PY3, text_type
if PY3:
from emai... |
# Copyright 2017 the GPflow authors.
#
# 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
#
# Unless required by applicable law or agreed to in writi... |
import torch
from torch import optim
from ..models.epic.feature_model import feature_model
def load_model(num_classes, input_frame_length):
#class_counts = (num_classes,352)
class_counts = num_classes
segment_count = input_frame_length
model = feature_model(input_frame_length*10*7, num_layers = 10, n... |
#!/usr/bin/env python
import click
import youtube
from .description import description
@click.group()
def channel():
'Channel commands'
@channel.command(help='Get your channel stats')
def stats():
me = youtube.get_me()
print()
print('Subscribers: ' + youtube.colors.green + youtube.commify(me['statist... |
def _prepare_sequence(sequence):
symbol_map = {
'x': 'х',
'X': 'X',
'y': 'у',
'—': '-',
'“': '«',
'‘': '«',
'”': '»',
'’': '»',
'😆': '😄',
'😊': '😄',
'😑': '😄',
'😔': '😄',
'😉': '😄',
'❗': '😄',
... |
# base class
class Base(object):
def __init__(self, x):
self.x = x
class Derived(Base):
def __init__(self, x, y):
# sending the x value up to base class
super(Derived, self).__init__(x)
self.y = y
def printD(self):
print(self.x + " " + self.y)
d = Derived("hi",... |
from django.urls import path
from . import views
app_name = 'polls'
# urlpatterns = [
# path('',views.index,name='index'),#/polls/
# path('<int:question_id>/',views.detail,name='detail'),#/polls/5/
# path('<int:question_id>/results/',views.results,name='results'),#/polls/5/results/
# path('<i... |
# Copyright 2020-2021 Dynatrace LLC
#
# 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
#
# Unless required by applicable law or agreed to in wr... |
from flask import render_template
from app import auth
from app import app
from flask import render_template,flash,url_for,redirect,request
from forms import RegistrationForm,LoginForm
from flask_login import login_required
# @auth.route('auth/login')
# def login():
# return render_template('home.html')
# @auth.r... |
''' 015 Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais
ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por Km rodado '''
d = int(input('Quantos dias foi alugado? '))
t = d * 60 # 60 reais o dia
km = ... |
import random
import string
import random
import pytest
import quanguru.classes.base as qbase #pylint: disable=import-error
def randString(N):
return str(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)))
strings = [randString(random.randint(1, 10)) for _ in range(random.randint(4, ... |
from google.protobuf.json_format import MessageToDict
from grpc.messages import data_pb2
import config
from authentication.auth import ProtectedResource
from flask import request, abort
import os
from werkzeug.utils import secure_filename
from filters.data_filter import DataFilter
from utils.data_reader import get_data... |
__all__ = ['baz', 'foo', 'Bar']
def foo():
pass
class Bar:
pass
def baz():
pass
def qux():
pass
class Quux:
pass
def foobar():
pass
|
import random
from django.views.generic.base import TemplateView
from honest_ab.api import get_experiment_bin
from honest_ab.binning_functions.base import HONEST_AB_COOKIE_KEY, HONEST_AB_SKIP_TYPE
class FakeObject(object):
def __init__(self, pk=None):
self.pk = pk if pk else random.randint(1, 1000000)
... |
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f'Hello! I am {self.name} and I am {self.age} years old!')
def speak(self):
print('I dont know what I say!')
class Cat(Pet):
def __init__(self, name, age, color):
su... |
import mss
import mss.tools
from window import quicktime_values
with mss.mss() as sct:
#1334x750
#left=x, top=y de inicio de la imagen, cuadrante 4 en plano
monitor = {"top": 400, "left": 800, "width": 375, "height": 200}
import time
import cv2
import mss
import numpy
with mss.mss() as sct:
# ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chipyapp', '0003_auto_20151104_0221'),
]
operations = [
migrations.RenameField(
model_name='datatype',
... |
import can
can0 = can.ThreadSafeBus(channel = 'vcan0', bustype = 'socketcan_ctypes')
while(True):
val = input('Button: ')
msg = can.Message(arbitration_id=0x3C4, data=[], is_extended_id=False)
if val == 'vol-up':
msg = can.Message(arbitration_id=0x3C4, data=[0x80, 0x00], is_extended_id=False)
... |
#
# Git-Fork Repositories plugin
# More info at https://github.com/fran-f/keypirinha-git-fork
#
# pylint: disable=C, import-error, relative-beyond-top-level
import keypirinha as kp
import keypirinha_util as kpu
from .lib.ForkWrapper import ForkWrapper
class Repositories(kp.Plugin):
"""
Add catal... |
import time
import math
from numba import jit, njit
from contextlib import contextmanager
@njit(cache=True)
def square(x):
return x ** 2
@jit(nopython=True, cache=True)
def pythagorean_theorem(x, y):
return math.sqrt(square(x) + square(y))
def pythagorus(x, y):
return math.sqrt(x**2 + y**2)
@context... |
from django.urls import path
from .views import *
urlpatterns=[
path('product_detail/<int:product_id>/',ProductDetailView.as_view(),name='product_detail'),
path('score/<int:product_id>/',RatePostView.as_view(),name='score')
] |
import os
import pandas as pd
from activitysim.core import inject
from activitysim.core import pipeline
from activitysim.core.config import setting
from .utils import setup_working_dir
def test_example():
setup_working_dir('example')
# importing asimtbm also registers injectibles
import asimtbm
a... |
import pytest
from easytxt import parse_text
from tests.factory import features_samples, sentences_samples
from tests.parsers import test_table
features_test_text = "- color: Black - material: Aluminium"
test_text_sentences = "first sentence! - second sentence. Third"
test_text_sentences_v2 = (
"Features: <ul><l... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 14:05:10 2013
@author: Jeff Hendricks
Web Page Experiments Solutions
"""
import scipy as sp
import bandit_solution as bs
from matplotlib import pyplot as plt
#Problem 1
#simulates one day of web page experiments. Returns the weights used that day
#and also returns ... |
'''
molecool.io package
configure access to subpackage functions
'''
from .pdb import open_pdb
from .xyz import open_xyz, write_xyz
|
"""
Work with references in the database
"""
import asyncio
import datetime
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import pymongo
from aiohttp import ClientConnectorError
from aiohttp.web import Request
from motor.motor_asyncio import AsyncIOMotorClientSession
from... |
from collections import OrderedDict
import torch.nn as nn
class SmallCNN(nn.Module):
def __init__(self, drop=0.5):
super(SmallCNN, self).__init__()
self.num_channels = 1
self.num_labels = 10
activ = nn.ReLU(True)
self.feature_extractor = nn.Sequential(OrderedDict([
... |
import os
import sys
import json
import argparse
from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv": [sys.executable, "-m", "cqljupyter", "-f", "{connection_file}"],
"display_name": "CQL",
"language": "CQL"... |
from tqdm import tqdm
import math, sys, os, random
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from argparse import ArgumentParser
import torch
from torch.optim import Adam
from torch.nn.functional import binary_cross_entropy, relu
from torch.nn import Conv2d, ConvTran... |
import modcolmesh
from modcolmesh import coltype
import modmesh
from modmesh import D3DDECLTYPE, D3DDECLUSAGE
import modVec3
from modVec3 import Vec3
class ColBox(modcolmesh.ColMesh):
def __init__(self):
modcolmesh.ColMesh.__init__(self)
self._create_header()
self._create_geoms()
... |
from datetime import datetime, timedelta
from os import PathLike
from pathlib import Path
from typing import List
from .timelog_io import TimelogIO
import pandas as pd
class TextIO(TimelogIO):
def __init__(self, act_folder: Path):
self.activity_folder = act_folder
self.act_list_path = self.activi... |
import simulation
import datetime
import sys
from simulation.common.helpers import timeit
"""
Description: Given a constant driving speed, find the range at the speed
before the battery runs out [speed -> distance]
"""
# TODO: make it so that previous values are logged into a numpy array and maybe written to an npz f... |
class Color:
"""
Representation of an element on the game board.
"""
def __init__(self, name):
"""
Create a new board item.
:param name: Hexadecimal representation of the color, e.g. 'FFFFFF'.
"""
self.name = name
def is_empty(self):
"""
A C... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
class Meta:
verbose_name_plural = "CustomUser"
|
"""Main module."""
def ingredients(count):
"""Prints ingredients for making `count` arepas.
F-string of original code"""
print(f'{count*0.1} cups arepa flour')
print(f'{count*0.1} cups cheese')
print(f'{count*0.025} cups water')
|
#from leagueRules import Stats, Points
#from logging import *
from stats import Stats
class Player():
"""
This class is intended to be used as an abstract class for all player subclasses (e.g. Quarter-
back). The primary purpose of this class is to organize common implementation details for
payer sub c... |
import argparse
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.autograd import grad
import torchvision
from torchvision import datasets, transforms
from torchvision.utils import save_image
import torchvision.models as models
import inversefed... |
"""
TO PRODUCE CANDIDATES FROM CDIPS LCS
----------
Merges steps 2-5 of "HOWTO.md". Goes from cdips-pipeline light curves to
period-finding results.
After running, you need to manually tune the SNR distribution for which you
consider objects, in `do_initial_period_finding`.
USAGE:
python -u lc_thru_periodfinding... |
import os
import argparse
import logging
import shutil
import torch
import torch.nn as nn
import numpy as np
from transformers import AutoTokenizer
from transformers.optimization import AdamW
from tensorboardX import SummaryWriter
from src.models.albert_for_linreg.utils import load_and_cache_dataset, load_coeffs
fro... |
# -*- coding: utf-8 -*-
__url = 'https://www.podnapisi.net'
def build_search_requests(core, service_name, meta):
params = {
'keywords': meta.title if meta.is_movie else meta.tvshow,
'language': core.utils.get_lang_ids(meta.languages, core.kodi.xbmc.ISO_639_1),
}
if meta.is_tvshow:
... |
import re
from decimal import *
import psycopg2 as pg2
stop_words = {
<<<<<<< HEAD
" unsigned ": " ",
" UNSIGNED ": " ",
" datetime ": " timestamp ",
" DATETIME ": " TIMESTAMP "
}
=======
" unsigned ": " ",
" UNSIGNED ": " ",
" datetime ": " timestamp ",
" DATETIME ": " TIMESTAMP "
... |
class Solution:
def reverseWords(self, s: str) -> str:
"""
1. Init array
2. Append each word to the array
3. Reverse each indiviual work in the array
4. Use join method and return array
"""
# Splits string into array by whitespace
arr = s.split()
... |
from copy import deepcopy
from struct import unpack
from .gripcontrol import is_python3, websocket_control_message
from .websocketevent import WebSocketEvent
class WebSocketContext(object):
def __init__(self, id, meta, in_events, grip_prefix=''):
self.id = id
self.in_events = in_events
self.read_index = 0
sel... |
# code -> {"name": "creaturename",
# "desc": "description",}
CREATURES = {}
SOLO_CREATURES = {}
GROUP_CREATURES = {}
with open("creatures.csv") as f:
lines = f.readlines()
for line in lines:
if line.strip() == "":
continue
parts = line.strip().split(",")
c... |
class Exception_base(Exception):
def __init__(self, q_list=None, error=None, img=None):
self.q_list = None
self.img = None
if q_list != None:
self.q_list = q_list
if error != None:
self.error = error
if img != None:
self.img = img
self.send_exception()
def send_exception(self):
if self... |
# -*- coding: utf-8 -*-
"""
@time : 2020/05/10 19:32
@author : 姚明伟
"""
from flask import Blueprint
# 创建蓝图对象
index_blu = Blueprint('index', __name__)
from .views import * |
from ast import literal_eval
dirs = {
' ': set(),
'│': {0, 2},
'─': {1, 3},
'┌': {1, 2},
'┐': {2, 3},
'└': {0, 1},
'┘': {0, 3},
}
def all_grids(side):
grids = [[]]
for row in range(side):
grids = [grid + [[]] for grid in grids]
for col in range(side):
... |
class Edge:
def __init__(self, arc, source, dest):
self.arc = arc
self.source = source
self.dest = dest
self.direction = arc.direction
# initialize without path (adjusted later); FUTURE WORK: multiple paths per edge
self.paths = [] # list of paths(=list of nodes); in... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class AverageAttention(nn.Module):
def __init__(self, vec_dim, d_k=64):
super().__init__()
self.vec_dim = vec_dim
self.d_k = d_k
self.w_q = nn.Linear(vec_dim, d_k)
self.w_k = nn.Linear(... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
class Category(models.Model):
name = models.CharField(_("Name"), max_length=255)
order = models.IntegerField(_("Display order"))
description = models.CharField... |
#!/usr/bin/env python
# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LIC... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-21 15:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('repositories', '0002_auto_20160911_1601'),
]
operations = [
migrations.AddFie... |
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from afriproperty.users.forms import UserChangeForm, UserCreationForm
from afriproperty.utils.export_as_csv import ExportCsvMixin
f... |
#!/usr/bin/env python
"""This script reads struct from C/C++ header file and output query
Author ykk
Date June 2009
"""
import sys
import getopt
import pylibopenflow.cheader as cheader
import pylibopenflow.c2py as c2py
def usage():
"""Display usage
"""
print "Usage "+sys.argv[0]+" <options> header_files.... |
import unittest
from onadata.libs.data import statistics as stats
class TestStatistics(unittest.TestCase):
def test_get_mean(self):
values = [1, 2, 3, 2, 5, 5]
result = stats.get_mean(values)
self.assertEqual(result, 3)
def test_get_min_max_range(self):
values = [1, 2, 3, 2, ... |
from django.contrib.gis.db.models import Manager, PointField
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext as _
from oscar.apps.address.abstract_models import AbstractAddress
from oscar.core.utils import slugi... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# @email : spirit_az@foxmail.com
import sys
__author__ = 'ChenLiang.Miao'
# +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ #
import os
import pathlib
import pyfastcopy
import shutil
def copy_file(path_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: slurp
ve... |
# coding: utf-8
import sqlite3
from photos_app import logger
def fetch_namedtuples(constructor, cursor: sqlite3.Cursor, boolean_columns=..., custom_columns=...):
results = []
first = True
columns = None
for row in cursor:
if first:
columns = row.keys()
values = dict(zip(co... |
hrs = int(input("Enter Hours: "))
rate = float(input("Enter Rate: "))
pay = hrs*rate
print(f"Pay: {pay}")
|
# Generated by Django 3.0.8 on 2020-11-30 17:45
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0005_application_application_location'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/env python3
import networkx as nx
import random
def sequence(n):
a, m, c = [], random.randint(0, n), n
while n > m > 0:
a.append(m)
n -= m
m = random.randint(0, n)
if n: a += [n]
return a
def two_sequence(size):
sequences = [sequence(size)]
second_sequence =... |
from django import http
def cors_middleware(get_response):
"""
If CORS preflight header, then create an empty body response (200 OK) and return it
"""
def middleware(request):
if (
request.method == "OPTIONS"
and "HTTP_ACCESS_CONTROL_REQUEST_METHOD" in request.META
... |
import os
import unittest
from merger import Merger
class MergerTest(unittest.TestCase):
def test_run(self):
merger = Merger()
actual = merger.run(os.path.join('test', 'data', 'cfg.csv'))
self.assertIsNotNone(actual)
self.assertIs(3, actual.shape[1])
|
import datetime
import os
import shutil
import sqlite3
import tempfile
import time
from django.test import SimpleTestCase
from matrixstore.build.init_db import SCHEMA_SQL, generate_dates, import_dates
from matrixstore.build.generate_filename import generate_filename
class TestGenerateFilename(SimpleTestCase):
@... |
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json
def notify_user(origin, destination, date, dic, user_list):
for user in user_list:
with open('emails_to_ping.json') as json_file:
user_info = json.load(json_file)
rece... |
# Copyright 2021-present Kensho Technologies, LLC.
import logging
from typing import List, Optional
BPE_CHAR = "▁" # character used for token boundary if BPE is used
UNK_BPE_CHAR = "▁⁇▁" # representation of unknown character in BPE
logger = logging.getLogger(__name__)
def _get_ctc_index(label_list: List[str]) ->... |
import json
from dataclasses import dataclass
from typing import Dict, Any, Optional, List
from allennlp.predictors import Predictor
VALID_ATTACKERS = ("hotflip", "input_reduction")
VALID_INTERPRETERS = ("simple_gradient", "smooth_gradient", "integrated_gradient")
@dataclass(frozen=True)
class Model:
"""
C... |
# optimzization utilties
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
import inspect
def plot_loss_trace(losses, loss_min=None, ax=None):
'''Plot loss vs number of function evals.
losses is a list of floats'''
if ax is None:
fig = plt.figure()
ax = fig.ad... |
'''
Copyright 2013 Cosnita Radu Viorel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute... |
from rest_framework import serializers
from .models import Crop, CropDetail, Buyer, Seller, User, Order
class CropSerializer(serializers.ModelSerializer):
class Meta:
model = Crop
#fields = ('category')
fields = '__all__'
class CropDetailSerializer(serializers.ModelSerializer):
class Meta:
model = CropDe... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or i... |
from bcrypt import hashpw
from eve.auth import BasicAuth
from flask import request, current_app as app
class BCryptAuthUser(BasicAuth):
def check_auth(self, email, password, allowed_roles, resource, method):
users = app.data.driver.db['user']
auth_user = users.find_one({'email': email})
re... |
#!/usr/bin/env python
import rospy
from beginner_tutorials.msg import QR
from geometry_msgs.msg import PoseWithCovarianceStamped
from geometry_msgs.msg import PoseArray
from geometry_msgs.msg import Pose
import copy
victim_pose_array = PoseArray()
victim_pose_array.header.frame_id = "map"
current_pose = Pose()
def ... |
import logging
from pathlib import Path
import grpc
from pb import resources_pb2, resources_pb2_grpc
logger = logging.getLogger(__name__)
resources_folder = Path(__file__).parent / ".." / ".." / ".." / "resources"
class Resources(resources_pb2_grpc.ResourcesServicer):
def GetTermsOfService(self, request, cont... |
import os
from flask import Flask,render_template,url_for,redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate ## pip install Flask-Migrate
from flask_login import LoginManager
login_manager= LoginManager()
app= Flask(__name__)
app.config['SECRET_KEY']= 'mykeyritesh'
#################... |
# -----------------------------------------------------------------------------
# IMPORTS
# Standard library imports
from __future__ import print_function
import unittest
from itertools import product
# Related third party imports
import numpy
# Local application/library specific imports
from py_vollib.ref_python.bl... |
# Copyright (C) 2016-2017 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology 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 Foundation, either version 3 of the License, or
# (at your optio... |
import zipper
def zip_shapefile_simple():
try:
### Inputs
input_shapefile = "C:\\Temp\\Shapefiles\\test.shp" # this dir will be searched for shapefiles
shape_zipper = zipper.ShapefileZipper() # Create Instance of Class
# By only passing an input file, an individual shapefilenam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.