content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import json
import discord
from discord.ext import commands
from utils import get_color
import datetime
class Modlogs(commands.Cog):
def __init__(self, bot):
self.bot = bot
with open("./bot_config/logging/modlogs_channels.json", "r") as modlogsFile:
self.modlogsFile = json.load(modlog... | python |
import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
from tahoe_idp.tests.magiclink_fixtures import user # NOQA: F401
User = get_user_model()
@pytest.mark.django_db
def test_studio_login_must_be_authenticated(client, settings): # NOQA: F811
url = reverse('studio_login')... | python |
UI_INTERACTIONS = {
'learn-more': {
'interaction_type': 'click',
'element_location': 'ct_menu_tree',
'element_name': 'ct_learn_more_btn',
'icon_name': 'document',
'color': 'yellow',
'cta_text': 'Learn More'
},
'advanced-metrics': {
'interaction_type': ... | python |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... | python |
from django.views.generic import (
ListView,
CreateView,
UpdateView,
DeleteView,
DetailView,
)
from django.urls import reverse_lazy
from .models import Todo
class ListTodosView(ListView):
model = Todo
class DetailTodoView(DetailView):
model = Todo
class CreateTodoView(CreateView):
... | python |
import sys
import bpy
import threading
from .signal import Signal
from .utils import find_first_view3d
class AnimationController:
'''Provides an interface to Blender's animation system with fine-grained callbacks.
To play nice with Blender, blendtorch provides a callback based class for interacting
wi... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 11:01:58 2021
@author: root
"""
import sklearn
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import torch.nn.functional as F
import torch.nn as n... | python |
from django.apps import AppConfig
class MetricConfig(AppConfig):
label = "metric"
name = "edd.metric"
verbose_name = "Metric"
def ready(self):
# make sure to load/register all the signal handlers
from . import signals # noqa: F401
| python |
from scipy.misc.common import logsumexp
from kameleon_rks.densities.gaussian import sample_gaussian, \
log_gaussian_pdf_multiple
from kameleon_rks.proposals.ProposalBase import ProposalBase
import kameleon_rks.samplers.tools
from kameleon_rks.tools.covariance_updates import log_weights_to_lmbdas, \
update_mean... | python |
__copyright__ = 'Copyright(c) Gordon Elliott 2017'
"""
"""
from enum import IntEnum
from a_tuin.metadata import (
ObjectFieldGroupBase,
StringField,
ObjectReferenceField,
Collection,
DescriptionField,
IntField,
IntEnumField,
)
class PPSStatus(IntEnum):
Requested = 1
Provided = ... | python |
"""
Tools for segmenting positional AIS messages into continuous tracks.
Includes a CLI plugin for `gpsdio` to run the algorithm.
"""
from gpsdio_segment.segment import BadSegment
from gpsdio_segment.segment import Segment
from gpsdio_segment.core import Segmentizer
__version__ = '0.20.2'
__author__ = 'Paul Woods'... | python |
# -*- coding: utf-8 -*-
"""
A utility library for interfacing with the SRF-08 and SRF-10 ultrasonic
rangefinders.
http://www.robot-electronics.co.uk/htm/srf08tech.shtml
http://www.robot-electronics.co.uk/htm/srf10tech.htm
Utilizes I2C library for reads and writes.
The MIT License (MIT)
Copyright (c) 2015 Martin Clemo... | python |
import sys
import time
from datetime import timedelta, datetime as dt
from monthdelta import monthdelta
import holidays
import re
import threading
import inspect
from contextlib import contextmanager
import traceback
import logging
# default logging configuration
# logging.captureWarnings(True)
LOG_FORMATTER = loggin... | python |
token = '1271828065:AAFCFSuz_vX71bxzZSdhLSLhUnUgwWc0t-k' | python |
###########################
#
# #764 Asymmetric Diophantine Equation - Project Euler
# https://projecteuler.net/problem=764
#
# Code by Kevin Marciniak
#
###########################
| python |
## What is Lambda : anonymous function or function without name
## Usecase is you can pass a function as an argument, quick function
# def double(num):
# x = num + num
# return x
# print(double(6))
# lambda num: num + num
# x = lambda a : a + 10
# print(x(5))
#Example 2
# my_list = [1, 5, 4, 6, 8, 11, 3... | python |
"""
Utility functions for dealing with NER tagging.
"""
import logging
logger = logging.getLogger('stanza')
def is_basic_scheme(all_tags):
"""
Check if a basic tagging scheme is used. Return True if so.
Args:
all_tags: a list of NER tags
Returns:
True if the tagging scheme does not ... | python |
from dataclasses import dataclass
from typing import Callable
import torch
Logits = torch.FloatTensor
@dataclass
class Sample:
logits: Logits
tokens: torch.LongTensor
Sampler = Callable[[Logits], Sample]
def standard(temperature: float = 1.0) -> Sampler:
def sample(logits: Logits) -> Sample:
... | python |
from numpy import NaN
import pandas as pd
import requests
import math
import re
from bs4 import BeautifulSoup
class Propertypro:
"""
web-scraper tool for scraping data on propertypro.ng
Parameters:
num_samples (int): The number of samples of data to be scraped.
location (list): list... | python |
from oslo_log import log as logging
from oslo_messaging import RemoteError
from nca47.api.controllers.v1 import base
from nca47.api.controllers.v1 import tools
from nca47.common.exception import NonExistParam
from nca47.common.exception import ParamFormatError
from nca47.common.exception import ParamNull
from nca47.com... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from layers import *
from layers.modules.l2norm import L2Norm
from data import *
import os
import math
#from vis_features import plot_features
class ResNet(nn.Module):
def __init__(self, block, layers, num_class... | python |
"""
This module defines views used in CRUD operations on articles.
"""
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.permissions import (
AllowAny, IsAuthenticatedOrReadOnly, IsAuthenticated
)
from rest_framework.serializers import ValidationError
from ... | python |
from .dynamo import DynamoClient
from .s3 import S3Client
| python |
#! python3
# -*- encoding: utf-8 -*-
'''
Current module: rman.app.rm_task.models
Rough version history:
v1.0 Original version to use
********************************************************************
@AUTHOR: Administrator-Bruce Luo(罗科峰)
MAIL: luokefeng@163.com
RCS: rman.app.rm_task.models,... | python |
#!/usr/bin/python3.3
# -*- coding: utf-8 -*-
# core.py
# Functions:
# [X] loading servers details
# [X] loading servers config (in which is found username, etc.)
# [ ] logging to disk commands and status
# [ ] loading and providing configuration e.g. is_enabled()
# [ ] provides ini reading interface
import ... | python |
##############################################################
# Customer Issue Prediction Model
#-------------------------------------------------------------
# Author : Alisa Ai
#
##############################################################
import dash
import dash_core_components as dcc
import dash_html_components ... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | python |
import pytest
import pandas
@pytest.fixture(scope="session")
def events():
return pandas.read_pickle("tests/data/events_pickle.pkl")
| python |
## https://weinbe58.github.io/QuSpin/examples/example7.html
## https://weinbe58.github.io/QuSpin/examples/example15.html
## https://weinbe58.github.io/QuSpin/examples/user-basis_example0.html
## https://weinbe58.github.io/QuSpin/user_basis.html
## https://weinbe58.github.io/QuSpin/generated/quspin.basis.spin_basis_1d.h... | python |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTest(TestCase):
def test_creat_user_email_succesful(self):
email='hello.com'
password='123123'
user =get_user_model().objects.create_user(
email=email,
password=password
)
... | python |
""" Itertools examples """
import itertools
import collections
import operator
import os
# itertools.count can provide an infinite counter.
for i in itertools.count(step=1):
print i
if i == 20: break
# itertools.cycle cycles through an iterator
# Will keep printing 'python'
for i,j in enumerate(itertool... | python |
# Generated by Django 3.1.7 on 2021-09-06 20:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('upload', '0004_auto_20210623_2006'),
]
operations = [
migrations.AlterField(
model_name='thumbnails',
name='large',
... | python |
# ------------------------------------------------------------------
# Step 1: import scipy and pyamg packages
# ------------------------------------------------------------------
import numpy as np
import pyamg
import matplotlib.pyplot as plt
# ------------------------------------------------------------------
# Step... | python |
import os
import shutil
import wget
import json
import logging
import tempfile
import traceback
import xml.etree.ElementTree as ET
import networkx as nx
from pml import *
#logging.basicConfig(level=logging.INFO)
def get_file(file, delete_on_exit = []):
# due to current limitations of DMC, allow shortened URLs... | python |
a= int(input("input an interger:"))
n1=int("%s" % a)
n2=int("%s%s" % (a,a))
n3=int("%s%s%s" % (a,a,a))
print(n1+n2+n3) | python |
#PROGRAMA PARA CALCULAR AS DIMENSÕES DE UMA SAPATA DE DIVISA
import math
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-= OTIMIZAÇÃO DE SAPATA DE DIVISA =-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print("Utilize sempre PONTO (.) NÃO VÍRGULA (,)")
lado_A = float(input("Qual o Tamanho do Lado A? "))
lado_B = float(input("Qual o Taman... | python |
from math import e
import pandas as pd
from core.mallows import Mallows
from core.patterns import ItemPref, Pattern, PATTERN_SEP
def get_itempref_of_2_succ_3_succ_m(m=10) -> ItemPref:
return ItemPref({i: {i + 1} for i in range(1, m - 1)})
def get_test_case_of_itempref(pid=0):
row = pd.read_csv('data/test_... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, ... | python |
currency = [10000, 5000, 2000, 1000, 500, 200, 100, 25, 10, 5, 1]
for _ in range(int(input())):
money = input()
money = int(money[:-3] + money[-2:])
out = ""
for c in currency:
out += str(money // c)
money %= c
print(out) | python |
import tkinter as tk
from tkinter import Frame, Button, PanedWindow, Text
from tkinter import X, Y, BOTH
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib import pyplot as plt
class MatplotlibWindow(object):
def __init__(self,root):
... | python |
import csv
with open(str(input('Arquivo .csv Airodump-ng: '))) as arquivoCsv:
print('\n Rede Senha')
try:
reader = csv.reader(arquivoCsv)
for linha in reader:
if not linha: # Verifica se a lista está vazia
pass
else:
if linha[... | python |
from .node_base import NodeBase
from .exceptions import NodeRegistrationError, NodeNotFoundError
class NodeFactory(object):
def __init__(self) -> None:
super().__init__()
self._nodes = {}
self._names = {}
def registerNode(self, node: NodeBase):
if node is None:
raise ValueError('node param i... | python |
import asyncio
import hikari
import tanjun
from hikari.interactions.base_interactions import ResponseType
from hikari.messages import ButtonStyle
from hikari_testing.bot.client import Client
component = tanjun.Component()
@component.with_slash_command
@tanjun.as_slash_command("paginate", "Paginate through a list o... | python |
# Holly Zhang sp20-516-233 E.Multipass.2
# testing code
p = Provider()
# TestMultipass.test_provider_run_os
r1 = p.run(command="uname -a", executor="os")
print(r1)
#Linux cloudmesh 4.15.0-74-generic #84-Ubuntu SMP Thu Dec 19 08:06:28 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
# TestMultipass.test_provider_run_live
r2 ... | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014 Cloudwatt
# 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/l... | python |
# Date : 03/31/2020
# Author : mcalyer
# Module : scanse_control.py
# Description : Code to explore Scanse LIDAR capabilites
# Python : 2.7
# Version : 0.2
# References :
#
# 1. Scanse User Manual V1.0 , 04/20/2017
# 2. Scanse sweep-ardunio source
# 3. sweep-sdk-1.30_... | python |
from re import findall,IGNORECASE
for _ in range(int(input())):
s=input()
f=sorted(findall(r'[bcdfghjklmnpqrstvwxyz]+',s,IGNORECASE),key=lambda x: len(x),reverse=True)
print(f'{s} nao eh facil') if len(f[0])>=3 else print(f'{s} eh facil')
| python |
__author__ = 'Wenju Sun'
import
"""
This script tries to download given file via http and given the final status summary
"""
MAX_VALUE=10
MIN_VALUE=0
WARN_VALUE=0
CRITICAL_VALUE=0
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATUS_TEXT='OK'
STATUS_CODE=STATE_OK
murl="http://dl-... | python |
from pathlib import Path
import pytest
from seq2rel.training.callbacks.concatenation_augmentation import ConcatenationAugmentationCallback
class TestConcatenationAugmentationCallback:
def test_aug_frac_value_error(self) -> None:
with pytest.raises(ValueError):
_ = ConcatenationAugmentationCal... | python |
from fastai import *
from fastai.vision import *
path = Path('../data/')
tfms = get_transforms(flip_vert=True)
np.random.seed(352)
data = ImageDataBunch.from_folder(path, valid_pct=0.2, ds_tfms=tfms, size=224).normalize(imagenet_stats)
data.show_batch(3, figsize=(15, 11))
# create a learner based on a pretrained den... | python |
from click import ClickException, echo
class ProfileBuilderException(ClickException):
"""Base exceptions for all Profile Builder Exceptions"""
class Abort(ProfileBuilderException):
"""Abort the build"""
def show(self, **kwargs):
echo(self.format_message())
class ConfigurationError(ProfileBuild... | python |
# -*- coding:utf-8 -*-
"""
目标:能够使用多线程实现同时接收多个客户端的多条信息
1.TCP服务器端
(1) 实现指定端口监听
(2) 实现服务器端地址重用,避免"Address in use"错误。
(3) 能够支持多个客户端连接.
(4) 能够支持支持不同的客户端同时收发消息(开启子线程)
(5) 服务器端主动关闭服务器,子线程随之结束.
"""
# 1. 该程序可以支持多客户端连接.
# 2. 该程序可以支持多客户端同时发送消息.
# 1. 导入模块
import socket
import threading
def recv_msg(new_client_socket,ip_port):... | python |
from __future__ import unicode_literals
import datetime
import itertools
from django.test import TestCase
from django.db import IntegrityError
from django.db.models import Prefetch
from modelcluster.models import get_all_child_relations
from modelcluster.queryset import FakeQuerySet
from tests.models import Band, B... | python |
import functools
import tornado.options
def define_options(option_parser):
# Debugging
option_parser.define(
'debug', default=False, type=bool,
help="Turn on autoreload and log to stderr",
callback=functools.partial(enable_debug, option_parser),
group='Debugging')
def conf... | python |
from django.urls import path
from . import books_views
urlpatterns = [
path('books/', books_views.index, name='books'),
]
| python |
""" Game API for Pacman """
import random
from collections import defaultdict
from abc import ABC, abstractmethod
import math
import mcts
import copy
import torch as tr
import pacman_net as pn
import pacman_data as pd
import numpy as np
class Node(ABC):
directionsDic = [[1,0], [0,1], [-1,0], [0,-1]]
@abstrac... | python |
import streamlit as st
import pandas as pd
from tfidf import get_vocab_idf
st.title('Binary Classification')
st.write("This app shows the featurization created from delta tf-idf for binary classification.")
# Sidebar
with st.sidebar.header('1. Upload your CSV data'):
uploaded_file = st.sidebar.file_uploader("Up... | python |
from country_assignment import assign_countries_by_priority
from data_processing.player_data import PlayerData
from flask import (Flask, redirect, render_template, request, url_for, flash)
import os
from pathlib import Path
import argparse
import uuid
app = Flask(__name__)
app.secret_key = os.urandom(24)
unique_coun... | python |
from pynterviews.mutants import mutants
def test_positive():
dna = ["CTGAGA",
"CTGAGC",
"TATTGT",
"AGAGAG",
"CCCCTA",
"TCACTG"]
result = mutants(dna)
assert result
def test_negative():
dna = ["CTGAGA",
"CTGAGC",
"TATTGT",
... | python |
def Bisection_Method(equation, a, b, given_error): # function, boundaries, Es
li_a = deque() # a
li_b = deque() # b
li_c = deque() # x root -> c
li_fc = deque() # f(xr)
li_fa = deque() # f(a)
li_fb = deque() # f(b)
li_Ea = deque() # estimated error
data = {
'Xl': li_... | python |
from django.urls import path
app_name = 'profiles'
urlpatterns = []
| python |
import os
if os.getenv('HEROKU') is not None:
from .prod import *
elif os.getenv('TRAVIS') is not None:
from test import *
else:
from base import *
| python |
"""
1. Верхняя одежда
1.1. #куртки
1.2. #кофты
1.3. #майки
1.4. #футболки
1.5. #рубашки
1.6. #шапки
1.7. #кепки
2. Нижняя одежда
2.1. #брюки
2.2. #шорты
2.3. #ремни
2.4. #болье
2.5. #носки
3. Костюмы
3.1. #спортивные
3.2. #класические
4. Обувь
4.1. #красовки
4.2. #кеды
4.3. #ботинки
4.4. #туфли
5.Аксесуары
5.1. #рю... | python |
# Copyright 2014 CloudFounders NV
#
# 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 writ... | python |
import os
import pandas as pd
os.chdir('/Users/forrestbadgley/Documents/DataScience/git/NUCHI201801DATA4-Class-Repository-DATA/MWS/Homework/03-Python/Instructions/PyPoll/raw_data')
csv_path = "election_data_1.csv"
csv_path2 = "election_data_2.csv"
elect1_df = pd.read_csv(csv_path)
elect2_df = pd.read_csv(csv_path2)... | python |
import re
from pyhanlp import *
# def Tokenizer(sent, stopwords=None):
# pat = re.compile(r'[0-9!"#$%&\'()*+,-./:;<=>?@—,。:★、¥…【】()《》?“”‘’!\[\\\]^_`{|}~\u3000]+')
# tokens = [t.word for t in HanLP.segment(sent)]
# tokens = [re.sub(pat, r'', t).strip() for t in tokens]
# tokens = [t for t in tokens if... | python |
import numpy as np
from seisflows.tools.array import uniquerows
from seisflows.tools.code import Struct
from seisflows.tools.io import BinaryReader, mychar, mysize
from seisflows.seistools.shared import SeisStruct
from seisflows.seistools.segy.headers import \
SEGY_TAPE_LABEL, SEGY_BINARY_HEADER, SEGY_TRACE_HEADE... | python |
import sys
import torch
import numpy as np
sys.path.append('../')
from models import networks
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--model-in-file',help='file path to generator model to export (.pth file)',required=True)
parser.add_argument('--model-out-file',help='file path to expor... | python |
def parse_line(line, extraction_map):
print("---------parsing line------")
key = get_key_for_line(line)
extraction_guide = extraction_map[key]
obj = get_blank_line_object()
flag = special_line_case(key)
answer_flag = special_answer_case(key)
if (flag == True):
line = escape_undersco... | python |
from matplotlib.offsetbox import AnchoredText
import numpy as np
import matplotlib.pyplot as plt
from iminuit import Minuit, describe
from iminuit.util import make_func_code
class Chi2Reg: # This class is like Chi2Regression but takes into account dx
# this part defines the variables the class will use
... | python |
import socket
HOST, PORT = "localhost", 9999
msg = b'\x16\x04\x04\x01\xfd 94193A04010020B8'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("localhost", 33000))
s.sendto(msg, (HOST, PORT))
| python |
from ..model_tests_utils import (
status_codes,
DELETE,
PUT,
POST,
GET,
ERROR,
random_model_dict,
check_status_code,
compare_data
)
from core.models import (
Inventory,
Actor,
Status
)
inventory_test_data = {}
inventory_tests = [
##----TEST 0----##
# creates 6 actors
# ... | python |
from utils import utils
day = 18
tD = """
2 * 3 + (4 * 5)
5 + (8 * 3 + 9 + 3 * 4 * 3)
5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
"""
tA1 = 26 + 437 + 12240 + 13632
tA2 = 46 + 1445 + 669060 + 23340
class Calculator:
def __init__(self, pattern):
self.pattern ... | python |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 核心思路
# 这题是 add_two_numbers_II_q445.py 的特例版本,做法更简单
# 另,这题没说不能修改原链表,所以可以先reverse,变成低位在前
# 处理之后再 reverse 回去
class Solution(object):
def plusOne(self, head):
"""
:type... | python |
# Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... | python |
# 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 appli... | python |
#! /bin/false
import weblogic
import javax.xml
import java.io.FileInputStream as fis
import java.io.FileOutputStream as fos
import os
import shutil
import java.io.BufferedReader as BR
import java.lang.System.in as Sin
import java.io.InputStreamReader as isr
import java.lang.System.out.print as jprint
import weblogi... | python |
from niaaml.classifiers.classifier import Classifier
from niaaml.utilities import MinMax
from niaaml.utilities import ParameterDefinition
from sklearn.tree import DecisionTreeClassifier as DTC
import numpy as np
import warnings
from sklearn.exceptions import ChangedBehaviorWarning, ConvergenceWarning, DataConversionWa... | python |
#!/usr/bin/python
#
# Script implementing the multiplicative rules from the following
# article:
#
# J.-L. Durrieu, G. Richard, B. David and C. Fevotte
# Source/Filter Model for Unsupervised Main Melody
# Extraction From Polyphonic Audio Signals
# IEEE Transactions on Audio, Speech and Language Processing
# Vol. 18, ... | python |
import sys
import os
import torch
from helen.modules.python.TextColor import TextColor
from helen.modules.python.models.predict_cpu import predict_cpu
from helen.modules.python.models.predict_gpu import predict_gpu
from helen.modules.python.FileManager import FileManager
from os.path import isfile, join
from os import ... | python |
from dpconverge.data_set import DataSet
import numpy as np
n_features = 2
points_per_feature = 100
centers = [[2, 2], [4, 4]]
ds = DataSet(parameter_count=2)
n_samples = 500
outer_circ_x = 1.0 + np.cos(np.linspace(0, np.pi, n_samples)) / 2
outer_circ_y = 0.5 + np.sin(np.linspace(0, np.pi, n_samples))
X = np.vstack... | python |
# Generated by Django 3.1.1 on 2020-09-16 15:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('erp', '0091_auto_20200914_1720'),
('erp', '0091_auto_20200914_1638'),
]
operations = [
]
| python |
"""Montrer dans le widget
Revision ID: 8b4768bb1336
Revises: dc85620e95c3
Create Date: 2021-04-12 17:24:31.906506
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8b4768bb1336'
down_revision = 'dc85620e95c3'
branch_labels = None
depends_on = None
def upgrade(... | python |
def helper(s, k, maxstr, ctr):
# print("YES")
if k == 0 or ctr == len(s):
return
n = len(s)
maxx = s[ctr]
for i in range(ctr+1, n):
if int(maxx) < int(s[i]):
maxx = s[i]
if maxx != s[ctr]:
k -= 1
for j in range(n-1, ctr, -1):
if int(... | python |
# # -*- coding: utf-8 -*-
# import scrapy
#
# import re
#
# class A55Spider(scrapy.Spider):
# name = '55'
# allowed_domains = ['fsx.sxxz.gov.cn']
# start_urls = ['http://fsx.sxxz.gov.cn/fsxzw/zwgk/xxgkzn/']
#
# def parse(self, response):
# navi_list = response.xpath('//ul[@class="item-nav"]//@hr... | python |
# Pop() -> Remove um elemento do endereço especifícado.
lista_4 = [10,9,8,7,5,6,4,2,3,1,2,3]
print(lista_4)
lista_4.pop(2)
print(lista_4)
lista_4.pop(-1)
print(lista_4) | python |
from typing import List, Union
import numpy as np
def get_test_function_method_min(n: int, a: List[List[float]], c: List[List[float]],
p: List[List[float]], b: List[float]):
"""
Функция-замыкание, генерирует и возвращает тестовую функцию, применяя метод Фельдбаума,
т. е.... | python |
from typing import cast, Mapping, Any, List, Tuple
from .models import PortExpenses, Port
def parse_port_expenses(json: Mapping[str, Any]) -> PortExpenses:
return PortExpenses(
cast(int, json.get("PortId")),
cast(int, json.get("PortCanal")),
cast(int, json.get("Towage")),
... | python |
from typing import Callable
from rx import operators as ops
from rx.core import Observable, pipe
from rx.core.typing import Predicate
def _all(predicate: Predicate) -> Callable[[Observable], Observable]:
filtering = ops.filter(lambda v: not predicate(v))
mapping = ops.map(lambda b: not b)
some = ops.som... | python |
import uuid
from datetime import datetime
from os import path
from sqlalchemy.orm.scoping import scoped_session
import factory
import factory.fuzzy
from app.extensions import db
from tests.status_code_gen import *
from app.api.applications.models.application import Application
from app.api.document_manager.models.doc... | python |
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, BatchNormalization, ReLU
class Decoder(Model):
def __init__(self, channels):
super().__init__()
self.conv1 = Conv2D(channels[0], 3, padding='SAME', use_bias=False)
self.bn1 = Batch... | python |
import os
from typing import List, Tuple
from urllib.request import urlopen
from discord.ext import commands
from blurpo.func import database, send_embed, wrap
def basename(path: str) -> Tuple[str, str]:
# Get file's basename from url
# eg. https://website.com/index.html -> (index.html, index)
return (b... | python |
#!/usr/bin/env python
# Copyright (C) 2017 Udacity Inc.
#
# This file is part of Robotic Arm: Pick and Place project for Udacity
# Robotics nano-degree program
#
# All Rights Reserved.
# Author: Harsh Pandya
# import modules
import rospy
import tf
from kuka_arm.srv import *
from trajectory_msgs.msg import JointTraje... | python |
import codecs
import os
from hacktools import common
import constants
import game
def run(data, copybin=False, analyze=False):
infile = data + "extract/arm9.bin"
outfile = data + "repack/arm9.bin"
fontdata = data + "font_data.bin"
dictionarydata = data + "dictionary.asm"
binfile = data + "bin_inpu... | python |
import time
import random
currentBot = 1
from threadly import Threadly
def worker(**kwargs):
botID = kwargs["botID"]
resultsQ = kwargs["resultsQ"]
time.sleep(random.randint(1,15))
resultsQ.put({"botID":botID, "time":time.time()})
def workerKwargs():
global currentBot
tosend = {"botID":"bot {}... | python |
"""
Searching for optimal parameters.
"""
from section1_video5_data import get_data
from sklearn import model_selection
from xgboost import XGBClassifier
seed=123
# Load prepared data
X, Y = get_data('../data/video1_diabetes.csv')
# Build our single model
c = XGBClassifier(random_state=seed)
#n_trees = range(500, 1... | python |
import numpy as np
from pytest import mark
from numpy.testing import assert_allclose
@mark.plots
def test_transition_map(init_plots):
axes_data = init_plots.plot_transition_map(cagr=False, full_frontier=False).lines[0].get_data()
values = np.genfromtxt('data/test_transition_map.csv', delimiter=',')
assert... | python |
import time
from membase.api.rest_client import RestConnection, Bucket
from membase.helper.rebalance_helper import RebalanceHelper
from memcached.helper.data_helper import MemcachedClientHelper
from basetestcase import BaseTestCase
from mc_bin_client import MemcachedError
from couchbase_helper.documentgenerator import ... | python |
# -*- coding: utf-8 -*-
{
'name': "Odoo Cogito Move Mutual",
'summary': "",
'author': "CogitoWEB",
'description': "Odoo Cogito move mutual",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# for the full l... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.