content stringlengths 5 1.05M |
|---|
import os
import random
import cherrypy
from snake_board import SnakeBoard
import numpy as np
"""
This is a simple Battlesnake server written in Python.
For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md
"""
class Battlesnake(object):
def __init__(self):
self.board... |
import torch
def make_optimizer(Cfg, model):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
lr = Cfg.BASE_LR
weight_decay = Cfg.WEIGHT_DECAY
if "bias" in key:
lr = Cfg.BASE_LR * Cfg.BIAS_LR_FACTOR
... |
# -*- coding: utf-8 -*-
from django.db.models import permalink, signals
from google.appengine.ext import db
from google.appengine.ext.db import Model as DBModel
from django.contrib.auth.models import User
from google.appengine.api import memcache
import urllib, hashlib
from ragendja.dbutils import cleanup_relations
cl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 18:14:26 2021
@author: @hk_nien
"""
import matplotlib.pyplot as plt
import scipy.signal
import numpy as np
import pandas as pd
import tools
import nlcovidstats as nlcs
nlcs.init_data(autoupdate=True)
df1, _npop = nlcs.get_region_data('Neder... |
x = input('Digite algo: ')
print(f'O tipo primitivo desse valor é {type(x)}.')
print(f'Só tem espaços? {x.isspace()}')
print(f'É um número? {x.isnumeric()}')
print(f'É alfabético? {x.isalpha()}')
print(f'É alfanumérico? {x.isalnum()}')
print(f'Está em maiúsculas? {x.isupper()}')
print(f'Está em minúsculas? {x.islower()... |
# pylint: disable=no-member,invalid-name,unused-argument
import ObjectListView
import wx
from ninjalooter import config
from ninjalooter import models
class KillTimesFrame(wx.Window):
def __init__(self, parent: wx.Notebook, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
parent.GetPar... |
from collections import OrderedDict
class Solution:
def kWeakestRows(self, mat: list, k: int) -> list:
rows = {i: mat[i] for i in range(len(mat))}
# life is short, use python
rows = OrderedDict(sorted(rows.items(), key=lambda kv: sum(kv[1])))
return list(rows.keys())[:k]
if __nam... |
#!/bin/python
# This script will mimics SNPSNAP for matching a set of input snps.
#
#
#
# Abin Abraham
# created on: 2019-12-31 12:08:19
import os
import sys
import time
import argparse
import numpy as np
import pandas as pd
from datetime import datetime
from functools import partial
from multiprocessing import Po... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
## Based on some other dudes' work.
## I have made this an api instead of a script.
# I will add scripting functionality to this again. in if __name__ == '__main__'
import os
import sys
if sys.version_info[0] != 3 or sys.version_info[1] < 2:
print('This version works with Python version 3.2 and above but not Pyth... |
"""Main WTPython file.
This file parses the command line arguments, runs your program,
and then displays solutions for errors if they occur.
"""
from __future__ import annotations
import argparse
import os.path
import runpy
import sys
import textwrap
from typing import Optional
import pyperclip
from rich import prin... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2019-2020 Latona. All rights reserved.
__all__ = ["command", "udp_packet", "decoder"]
from .command import *
|
# -*- coding: utf-8 -*-
"""
media info handlers module.
"""
from pyrin.packaging.base import Package
class MediaInfoHandlersPackage(Package):
"""
media info handlers package class.
"""
NAME = __name__
|
n = int(input('Digite um número '))
print('Analisando o valor {}, o dobro é {} o triplo é {} e a raiz é {:.2f}'.format(n,(n*2),(n*3),(n**(1/2)))) |
from RLTest import Env
from sqlalchemy import create_engine
from sqlalchemy.sql import text
import time
import subprocess
import signal
from threading import Thread
MYSQL_DB = 1
ORACLESQL_DB = 2
class Background(object):
"""
A context manager that fires a TimeExpired exception if it does not
return within... |
N = int(input())
S, T = map(str, input().split())
ans = ""
for i in range(N):
ans += S[i] + T[i]
print(ans) |
import sys, os.path as path
import json
import os
import requests
import grpc
import time
from concurrent import futures
sys.path.append("./athene_grpc/service_spec")
import athenefnc_pb2_grpc as pb2_grpc
import athenefnc_pb2 as pb2
from resutils import *
server_port = os.environ['SERVICE_PORT'] # port ATHENE servi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 16:20:59 2021
@author: bloisejuli
"""
# plotear_temperaturas.py
#%%
# Ejercicio 5.9:
# Escribí una función plotear_temperaturas() en un archivo plotear_temperaturas.py que lea el archivo de datos temperaturas.npy
import numpy as np
import m... |
"""
© Michael Widrich, Markus Hofmarcher, 2017
"""
import sys
import progressbar
import numpy as np
import tensorflow as tf
from collections import OrderedDict
from TeLL.utility.misc import custom_tensorflow_histogram, check_kill_file
from TeLL.utility.timer import Timer
from TeLL.utility.workingdir import Workspace
... |
import numpy as np
import cvxpy as cvx
import operator
from mlclas.svm.rankingsvm_models import *
from mlclas.neural.bpmll_models import ThresholdFunction
from mlclas.utils import check_feature_input, check_target_input
from mlclas.stats import Normalizer, RankResults
class RankingSVM:
"""
RankingSVM algorith... |
# -*- coding: utf-8 -*-
# 这是没有GUI欢迎界面的游戏后端, 不需安装EasyGui即可运行
from config import *
from warrior import *
from socket import *
import threading
import sys
import json
from time import sleep, time
import queue
# 用于同步
flag = [-1]
# 此处定义了游戏所用到的全局变量
# 服务器地址
HOST = '' # 此处输入服务器ip
# HOST = 'localhost' #本地运... |
import unittest
from tempsdb.database import create_database, Database
from tempsdb.exceptions import DoesNotExist
class TestDatabase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.db = create_database('my_db')
def test_checkpoint(self):
self.db.checkpoint()
def t... |
# -*- coding: utf-8 -*-
import hashlib
import json
import re
import time
from scrapy import log
from gjqyxyxxcxxt.database.my_redis import UniqRedis
class RepeatHandle(object):
rdb = UniqRedis().conn()
def repeat_query(self, url):
key = hashlib.md5(url).hexdigest()
return self.rdb.get(key)
... |
import numpy as np
from matplotlib import rc
import matplotlib.pyplot as plt
def dadt_f2(a_a0, e_0):
return 2 * a_a0 ** 1.5 * (1 - e_0**2 / a_a0**1.5)**.5
def dadt_fT(a_a0, e_0):
return 2 * a_a0 ** 1.5 * (1 - .25 * e_0**2 / a_a0)
def main():
# http://matplotlib.org/users/pgf.html#custom-preamble
#... |
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date Author Notes
# 2019-06-13 SummerGift first version
#
import network
wlan = network.WLAN(network.STA_IF)
wlan.scan()
wlan.connect("rtthread", "02188888888")
wlan.isconnected... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.externally_triggered_job_params_externally_triggered_sbt_params
class ExternallyTriggeredJobParams(object):
"""Implementation of the 'ExternallyTriggeredJobParams' model.
Message to capture any additional backup par... |
# Generated by Django 3.1 on 2020-09-29 21:42
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('app', '0023_auto_20200930_0101'),
]
operations = [
migrations.AddField(
model_name='jumbotron',
name='fu... |
import pytest
from urlshortener import create_app
from urlshortener.models import URLEntry
@pytest.fixture
def client():
yield create_app(testing=True).test_client()
# make sure we clear the database when we're done
URLEntry.objects.delete()
def test_home(client):
res = client.get('/')
assert re... |
#!/usr/bin/python
import setuptools
from setuptools import setup, find_packages
install_requires = [
'cmdln',
'python-ldap',
'SQLAlchemy == 0.5.5'
]
setup(name='vyvyan',
author='david kovach',
author_email='dave@devopsadvice.com',
description='vyvyan helps you manage users',
... |
import time
import threading
import serial
import parameter
class Rs232Connection(threading.Thread):
exit = True
stop = True
try:
__ser = serial.Serial(
port='/dev/ttyS0', # Open RPI buit-in serial port
baudrate=9600,
parity=serial.PARITY_NONE,
... |
from sys import stdin
def orde(numeros):
izq,mit,der=[],[],[]
i = 0
if len(numeros)>1:
piv=numeros[0]
while len(numeros) > i:
if piv<numeros[i]:
izq.append(numeros[i])
i = i+1
elif piv>numeros[i]:
der.append(numeros[i])
... |
import os
from cltk.utils.file_operations import open_pickle
from nltk.tokenize.punkt import PunktLanguageVars, PunktTrainer, PunktSentenceTokenizer
from progress_bar import print_progress_bar
from extract_features import parse_tess, file_parsers
PunktLanguageVars.sent_end_chars = ('.', ';', ';')
PunktLanguageVars.int... |
#coding: utf-8
from django.db import models
from django.shortcuts import redirect
import datetime
import markdown
from django.contrib import admin
class Song(models.Model):
name = models.CharField(max_length = 20)
song_pic= models.CharField(max_length=200,null=True,blank=True)
song_url= models.CharFiel... |
#!/usr/bin/env python3
from enum import Enum
import re
import socket
import logging
from collections import namedtuple
SVDRP_CMD_LF = '\r\n'
response_data = namedtuple('ResponseData', 'Code Separator Value')
SVDRP_EMPTY_RESPONSE = ""
_LOGGER = logging.getLogger(__name__)
class SVDRP_COMMANDS(str, Enum):
QUIT ... |
from invoke import task
@task
def clean(c, docs=False, bytecode=False, extra=''):
patterns = ['build']
if docs:
patterns.append('docs/_build')
if bytecode:
patterns.append('**/*.pyc')
if extra:
patterns.append(extra)
for pattern in patterns:
c.run("rm -rf {}".format(... |
from qdep.internal.common import *
from qdep.internal.prf import *
version = "1.1.1"
def prfgen(script_path, qmake="qmake", data_dir=None):
if data_dir is not None:
prf_path = data_dir
else:
qmake_res = sub_run([qmake, "-query", "QT_HOST_DATA"], check=True, stdout=subprocess.PIPE, encoding="UTF-8")
prf_path... |
# -*- coding: utf-8 -*-
# Copyright 2009-2015 Yelp and Contributors
#
# 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 appli... |
from .. import lib as web
from ..auth import group, expose_for
from ...config import conf
from ... import db
from traceback import format_exc as traceback
from datetime import datetime, timedelta
@web.show_in_nav_for(1, 'tags')
class LogPage:
@expose_for(group.guest)
def default(self, logid=None, siteid=No... |
import pytest
from xsugar import ureg, Experiment, match_theory_data
from sciparse import assert_equal_qt, assert_allclose_qt, assertDataDictEqual
from numpy.testing import assert_equal
from sugarplot import assert_figures_equal, plt, Figure
import pandas as pd
import numpy as np
import os
@pytest.fixture
def sim_exp(... |
#!/usr/bin/python
import math
class YieldCurve:
# Python constructor
def __init__(self, rate):
self.rate = rate
# zero coupon bond
def discount(self, T):
return math.exp(-self.rate*T)
|
"""Solution for day1 problem."""
import itertools
from typing import IO
def single_calibration(change_file: IO[str]) -> int:
"""Part 1."""
frequency = 0
for line in change_file:
frequency += int(line)
return frequency
def find_calibration(change_file: IO[str]) -> int:
"""Part 2."""
... |
# coding=utf-8
# Marcelo Ambrosio de Goes
# marcelogoes@gmail.com
# 2022-04-09
# 100 Days of Code: The Complete Python Pro Bootcamp for 2022
# Day 52 - Instagram Follower Bot Account
from instagram_follower_bot import InstagramBot
import os
INSTAGRAM_USER = os.getenv("INSTAGRAM_USER")
INSTAGRAM_PASSWORD = os.getenv(... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v4/proto/services/operating_system_version_constant_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor... |
from wiktionary.WiktionaryExtension import WiktionaryExtension
if __name__ == '__main__':
WiktionaryExtension().run() |
from pyvirtualdisplay.xephyr import XephyrDisplay
from pyvirtualdisplay.xvfb import XvfbDisplay
from pyvirtualdisplay.xvnc import XvncDisplay
_class_map = {"xvfb": XvfbDisplay, "xvnc": XvncDisplay, "xephyr": XephyrDisplay}
class Display(object):
"""
Proxy class
:param color_depth: [8, 16, 24, 32]
:p... |
from utils import commands_util
from services import commands_handler
from configs.tweepy import API
def status_handler(status):
command_stack = commands_util.get_command_stack(status.text)
message = commands_handler.execute_command_stack(
command_stack,
status.author.id_str
)
print(me... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any
from draugr.writers.writer import Writer
__author__ = "Christian Heider Nielsen"
__doc__ = """
Created on 27/04/2019
@author: cnheider
"""
__all__ = ["MockWriter"]
class MockWriter(Writer):
""" """
def _close(self, exc_type=None, exc_v... |
#!/usr/bin/env python2
# Python 2
#
# Problem: I'm trying to add context to a generic and unexpected exception while
# keeping the original traceback and exception information
#
import sys
def this_throws():
return 1/0
#this_throws()
# this doesn't work
#try:
# this_throws()
#except Exception as e... |
from datetime import datetime, timedelta
from typing import Optional
from ..admin import AdminFieldsetMixin
__all__ = [
"TitleAdminFieldsetMixin", "DescriptionAdminFieldsetMixin",
]
class TitleAdminFieldsetMixin(AdminFieldsetMixin):
def get_readonly_fields(self, obj=None, **_) -> Optional[str]:
# If... |
from django.core.management.base import BaseCommand, CommandError
from credocommon.models import User, Team, Detection, Device, Ping
from random import choice, random, randint
from time import time
import string
import base64
PARTICLE_IMG = """
iVBORw0KGgoAAAANSUhEUgAAABQAAAAaCAAAAACS6COhAAAZQXpUWHRSYXcgcHJvZmlsZSB0e... |
#!/usr/bin/env python
import sys
from canaryd.subprocess import CalledProcessError, get_command_output
# Run once an hour, smartctl can be intensive
# CANARYD_INTERVAL = 3600
SMART_RETURN_BITS = {
0: False, # command line parse error
1: 'device open failed',
2: 'SMART command failed',
3: 'disk fail... |
from lines_pol_gui import MainWindow
from PyQt5.QtWidgets import QApplication
def main():
app = QApplication([])
mainWindow: MainWindow = MainWindow()
mainWindow.getWindow().show()
app.exec_()
if __name__ == "__main__":
main() |
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from utils import exceptions
urlpatterns = [
path("", include("modules.home.urls")),
path(
"favicon.ico",
RedirectView.as_view(url=f"{settings.S... |
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2021 Theodor Amariucai and EASE Lab
#
# 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 ... |
import sys
sys.path.insert(0,'../')
from util import *
import numpy as np
#import cv2
import tensorflow as tf
from numpy import *
import matplotlib as mlp
mlp.use('Agg')
from skimage import color
from skimage import io
from collections import Counter
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridsp... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2020- Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length = 60)
description = models.TextField()
image = models.ImageField(upload_to='images/')
url = models.CharField(max_length = 60)
user = ... |
o = input()
a = int(input())
b = int(input())
def calculator(operator, n1, n2):
OPERATIONS_DICT = {
'multiply': lambda x = n1, y = n2: x * y,
'divide': lambda x = n1, y = n2: x / y,
'add': lambda x = n1, y = n2: x + y,
'subtract': lambda x = n1, y = n2: x - y
}
return f'{OP... |
# Copyright (c) 2020 PaddlePaddle Authors. 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
#
# Unless required by appl... |
import wtforms
from ..application import actions
class RenameNetwork(wtforms.Form):
name = wtforms.TextField(
'New Name',
description="Enter a new name for the network."
)
class RenameNetworkAction(actions.Action):
label = "Rename Network"
form_class = RenameNetwork
NETWORK_ACTION... |
#!/usr/local/bin/python3
import os, time, sys, json
pipe_name = 'pipe_test'
def child( ):
pipeout = os.open(pipe_name, os.O_WRONLY)
counter = 0
while True:
time.sleep(1)
os.write(pipeout, 'Number %03d\n' % counter)
counter = (counter+1) % 5
def parent( ):
pipein = open(pipe_na... |
# -*- coding: utf-8 -*-
"""Hosts functionality relating to generation of user projects."""
from pathlib import Path
from typing import Any, Iterator, List, Optional, Type
from boltons.queueutils import PriorityQueue
from micropy.config import Config, DictConfigSource
from micropy.logger import Log, ServiceLog
from ... |
import tanjun
from avgamah.core import Client
from . import times, zodiac_signs
rashifal_component = tanjun.Component()
@rashifal_component.with_slash_command
@tanjun.with_str_slash_option(
"duration",
"Duration of the rashifal you wanna see",
choices=[time for time in times.values()],
)
@tanjun.with_s... |
from stagecraft.apps.dashboards.admin.dashboard import DashboardAdmin
|
import unittest
import inspect
from pathlib import Path
import json
import requests
from pymongo import MongoClient
from common import (
CONFIG_PATH,
HTTP_API_ROOT,
run_environment
)
from http_test_helpers import (
get_predictors_names_list,
get_datasources_names,
get_integrations_names
)
co... |
from .context_event_extension import context_event
from .context_init_extension import context_init
from .context_request_extension import context_request
from .store import store |
#! /bin/python3
import csv
import requests
import os
# Downloads the Banque de France forex rates and transforms them to align with
# revolut-stocks format.
url = "http://webstat.banque-france.fr/fr/downloadFile.do?id=5385698&exportType=csv"
with open("forex_rates.csv", 'wb') as forex_file:
r = requests.get(u... |
"""ws-create-user - creating users from command line."""
import getpass
import os
import sys
import transaction
from websauna.system.devop.cmdline import init_websauna
from websauna.system.user.events import UserCreated
from websauna.system.user.models import Group
from websauna.system.user.utils import get_user_clas... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Plot configuration."""
import logging
from typing import Any, Callable, Dict, List, Optional
import numpy as np
from bokeh import palettes
fro... |
#Section 1: Terminology
# 1) What is a recursive function?
# A function which would call it self.
#
#
# 2) What happens if there is no base case defined in a recursive function?
# The recursive funcion would go on forever.
#
#
# 3) What is the first thing to consider when designing a recursive function?
# When would th... |
from __future__ import print_function
import argparse
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
from keras.models import Model
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Dense, GlobalMaxPooling2D, BatchNormalization, Dropout, ReLU
from kera... |
from time import sleep
def maior(*num):
cont = maior = 0
print("\n Analisando os valores passador...")
for valor in num:
print(f"{valor}", end="", flush=True)
sleep(0.2)
maior(2, 4, 8, 9, 0)
maior(4, 7, 0)
maior(1, 1, 2) |
from flask import Flask, request, redirect, render_template
import cgi
import os
app = Flask(__name__)
app.config['DEBUG'] = True # displays runtime errors in the browser, too
@app.route("/")
def index():
return render_template('hello_form.html')
@app.route("/hello", methods=["POST"])
def hello():
first... |
import sklearn.decomposition as skd
__all__ = [
"transform",
]
def transform(data_inp, **kwargs):
pca_model = skd.PCA(**kwargs)
pca_model.fit(data_inp)
|
# This script modifies Dopamine with the original copyright note:
#
# Copyright 2018 The Dopamine 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/lice... |
# coding: utf-8
"""Utils functions used in knoema spider.
"""
from bs4 import BeautifulSoup
from pprint import pprint
import pandas as pd
import json, os
def get_resource_path(path):
dir_path = os.path.dirname(__file__)
dir_path = dir_path if dir_path else os.getcwd()
return os.path.join(dir_path, path)
... |
# Binary Tree Search Algorithm
def binary_tree_search(item_sought, current_node):
if current_node == None:
return False
else:
if item_sought == current_node:
return True
else:
if item_sought < current_node:
if current_node.left != None:
return binary_tree_search(item_sought, current_node.left)
... |
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.shortcuts import get_object_or_404
from rest_framework import generics, serializers
from tower import ugettext_lazy as _lazy
from kitsune.products.models import Product, Topic
from kitsune.sumo.api impor... |
import re
import pandas as pd
bids_pattern = "(sub-[A-Za-z0-9]*)_(ses-[A-Za-z0-9]*_)?(task-[A-Za-z0-9]*_)(acq-[A-Za-z0-9]*_)?(ce-[A-Za-z0-9]*_)?(rec-[A-Za-z0-9]*_)?(dir-[A-Za-z0-9]*_)?(run-[0-9]*_)?(mod-[A-Za-z0-9]*_)?(echo-[0-9]*_)?(recording-[A-Za-z0-9]*_)?(proc-[A-Za-z0-9]*_)?(space-[A-Za-z0-9]*_)?(split-[A-Za-z0-9... |
# Array Index & Element Equality
def index_equals_value_search(arr):
l, r = 0, len(arr)
while l < r:
mid = (l+r)//2
if arr[mid] < mid:
l = mid+1
else:
r = mid
if arr[l] == l:
return l
return -1 |
def is_prime(number):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
return 0
else:
return 1
else:
return 0
def print_primes(low, hi):
b = 0
for i in range(low, hi):
b += is_prime(i)
return b
for i in rang... |
from model.contact import Contact
testdata = [
Contact(firstname="firstname1", lastname="lastname1",
address="address1", home="home1", mobile="mobile1",
work="work1", phone2="phone21", email="email11",
email2="email21", email3="email31"),
Contact(firstname="firstname2", las... |
import HTMLParser
parser = HTMLParser.HTMLParser()
def parseHtml(text):
if not text:
None
else:
try:
return parser.unescape(text)
except UnicodeDecodeError:
return "Failed to parse text: {0}".format(text)
|
import abc
import numpy as np
from abc import ABC
# The abstract penalty function which has a function update
class Penalty(ABC):
def __init__(self, lambda_lasso, weight_vec, Sigma, n):
self.lambda_lasso = lambda_lasso
self.weight_vec = weight_vec
self.Sigma = Sigma
@abc.abstractmeth... |
"""=============================================================
c:/Users/COTTRILLAD/1work/Python/djcode/apps/fn_portal/fn_portal/tests/integraion_tests/test_sample_detail.py
Created: 25 May 2020 14:29:10
DESCRIPTION:
The sample detail page uses the 'fn_portal/sample_detail.html'
template and should include ba... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from app.models import Channel, Playlist, SubmittedPlaylist
class ChannelAdmin(admin.ModelAdmin):
list_display = ['title', 'duration', 'group', 'user', 'created_at']
search_fields = ['... |
#pylint: disable = line-too-long
from pykey.m60 import M60
from pykey.loader import KB_Loader
from pykey.processor import KB_Processor
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
class Layer:
""" Class representing a layer, for which we have a set
of macro sequences or keycodes"""
def... |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozure... |
# Copyright 2021 Gina Häußge & Octoprint contributors
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but ... |
# -*- coding: utf-8 -*-
from .mixtures import (CollapsedConjugateGaussianMixture,
ConjugateGaussianMixture, NonconjugateGaussianMixture)
from .processes import DP, MFM
|
"""
Hyper-parameter optimization through randomized search, GP-based, and GCP-based.
"""
# Author: Sebastien Dubois
# for ALFA Group, CSAIL, MIT
# The MIT License (MIT)
# Copyright (c) 2015 Sebastien Dubois
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and asso... |
import enum
class PARSING_MAP(enum.Enum):
train_info = [
'txtGoAbrdDt', 'txtGoStartCode', 'txtGoEndCode', 'selGoTrain',
'selGoRoom', 'txtGoHour', 'txtGoTrnNo', 'useSeatFlg', 'useServiceFlg',
'selGoSeat', 'selGoSeat1', 'selGoSeat2', 'txtPsgCnt1', 'txtPsgCnt2',
'selGoService', 'h_trn... |
"""
Each corpus-specific files handle
reading of files as well as
calling functions from Filter and Parser
"""
import os
import io
import json
import argparse
import logging
from util import rephrase
from os.path import join as pjoin
from parser import depparse_ssplit, setup_corenlp
from cfg import DISCOURSE_MARKER_... |
from flask import Flask, request, Response, render_template
from flask import send_file
from maya_widget import get_data
import pathlib
import io
app = Flask(__name__)
current_path = pathlib.Path().absolute()
@app.route('/api/post', methods=['POST'])
def post_api():
data = request.json
user_weight = int(dat... |
# Generated by Django 2.2.3 on 2020-06-12 14:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tran', '0042_auto_20200612_1356'),
]
operations = [
migrations.AddField(
model_name='brand',
name='icon',
... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import time
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from backend.firebase_db_util import post_feed, get_last_feeds, get_reddit_url, update_desc, is_enabled, delete_feed
from backend.fcm_util import send_fcm
from ba... |
import numpy
from typing import List
from skipi.util import is_number, vslice
PRINT_PRECISION = 3
class Domain:
def __init__(self, x_min: float, x_max: float, npts: int = 3):
self._xmin = x_min
self._xmax = x_max
self._npts = npts
self._dom = None
def get(self):
if... |
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
output = [(num, nums.count(num)) for num in set(nums)]
s_output = sorted(output, key=lambda x: x[1], reverse=True)
return list(map(lambda x: x[0], s_output))[:k] |
from b_cfn_custom_api_key_authorizer_test.integration.infrastructure.main_stack import MainStack
from b_cfn_custom_api_key_authorizer_test.integration.util.lambda_invoke import LambdaInvoke
def test_FUNCTION_validator_WITH_valid_api_keys_EXPECT_response_valid(api_keys):
function = MainStack.get_output(MainStack.V... |
from typing import Callable
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
from sqlalchemy.orm.session import Session
from app.core.config import settings
engine = create_engine(
settings.SQLALCHEMY_DATABASE,
pool_pre_ping=True,
connect_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.