text stringlengths 2 999k |
|---|
## OPPORTUNIST_AI
## Author: arda-guler
##
## This AI module is a simple opportunist AI (hence the name).
##
## If the country is stronger than its neighbouring enemies, it places power points to strengthen its weakest borders.
## Otherwise, it tries to place them to inland regions to protect its power points and incre... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
##########################################################################################
# Machine Environment Config
DEBUG_MODE = False
USE_CUDA = not DEBUG_MODE
CUDA_DEVICE_NUM = 0
##########################################################################################
# Path Config
import os
import sys... |
# coding=utf-8
# Copyright 2018 The Google AI Team 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 applicabl... |
from django.urls import path
from products.views import productList,productDetails,searchView
app_name = "products"
urlpatterns=[
path("", productList.as_view(), name = "productlist"),
path("item/<int:pk>", productDetails.as_view(), name = "details"),
path("search/", searchView.as_view(), name="se... |
from csv import reader
from datetime import datetime
from sys import argv
import csv
# 1. 返回一天中的时间段,0~6*24-1
# 2. 返回周几的feature 1~7
# 3. 返回月份的feature 1~12
# 4. 返回周数 1~52
# 第一个参数为输入文件
# 第二个参数为输出文件
def normalize_time_stamp(x):
return 1 - ((143 - x) / 143)
def time_zone(h, m):
return h * 6 + m // 10
filename... |
"""Iterable enum module."""
# Copyright (c) 2020-2022 ObserverOfTime
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any pu... |
import socket
Buffer_Size = 4096
class TcpNet:
def __init__(self):
self.com_socket =socket.socket()
self.Connection=self.com_socket
def Accept(self, IP, Port):
self.com_socket.bind((IP,Port))
self.com_socket.listen(10);
self.Connection, self.address = self.com_socket.acce... |
from setuptools import setup
dependencies = [
"aiter==0.13.20191203", # Used for async generator tools
"blspy==1.0", # Signature library
"chiavdf==1.0.1", # timelord and vdf verification
"chiabip158==1.0", # bip158-style wallet filters
"chiapos==0.9", # proof of space
"clvm==0.9.4",
"c... |
import pytest
pytest.importorskip('zmq')
from partd.zmq import Server, keys_to_flush, File, Client
from partd import core, Dict
from threading import Thread
from time import sleep
from contextlib import contextmanager
import pickle
import os
import shutil
def test_server():
s = Server()
try:
s.start... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 17:35:09 2016
@author: yxl
"""
from imagepy.core.engine import Tool
import numpy as np
from imagepy.core.manager import ColorManager
# from imagepy.core.draw.fill import floodfill
from skimage.morphology import flood_fill, flood
class Plugin(Tool):
title = 'Flood... |
from django.db import models
# Create your models here.
class User(models.Model):
class Meta:
db_table = "user"
id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length=100)
password = models.CharField(max_length=200)
dob = models.CharField(max_length=50)
|
import re
import torch
import torchaudio
from transformers import Wav2Vec2ForCTC, Wav2Vec2FeatureExtractor, Wav2Vec2CTCTokenizer, Wav2Vec2Processor
from tortoise.utils.audio import load_audio
def max_alignment(s1, s2, skip_character='~', record=None):
"""
A clever function that aligns s1 to s2 as best it ca... |
from django.db import models
from player.models import Player
class PerformanceTotal(models.Model):
player = models.ForeignKey(Player, on_delete=models.CASCADE, null=True, blank=True)
tournaments = models.BigIntegerField(default=0)
matches = models.BigIntegerField(default=0)
batting_innings = models.B... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEbppInvoiceFileOutputQueryModel(object):
def __init__(self):
self._invoice_code = None
self._invoice_no = None
self._scene = None
self._user_id... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree. |
N,M=list(map(int,input().split()))
S = set()
ans = 0
for i in range(N):
S.add(input())
for i in range(M):
if input() in S:
ans+=1
print(ans) |
# Copyright 2018 Canonical Ltd.
#
# 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 writin... |
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_apache_httpcomponents_client5_httpclient5",
artifact = "org.apache.httpcomponents.client5:httpclient5:5.1",
artifact_sha256 = "b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4... |
from egyptian_data_generator.helpers import Helpers
class PhoneNumber:
def generate(self):
res = {}
providers = {
"Vodafone": "100",
"Etisalat": "111",
"Orange": "122",
"Etisalat": "114",
"Orange": "120",
"Vodafone": "101",
... |
''' Handling the data io '''
import argparse
import torch
import sys
def read_vocab_idx(vocab_path):
''' build vocab '''
word2idx = {"_PAD" : 0}
with open(vocab_path) as f:
for line in f:
tokens = line.strip("\n").split("\t")
no = int(tokens[1])
word2idx[toke... |
# Copyright (c) 2020 ING Bank N.V.
#
# 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, distr... |
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above ... |
import argparse
import sys
from io import StringIO
from urs.praw_scrapers import Basic
### Function names are pretty self-explanatory, so I will not be adding comments
### above the functions.
### Includes a total of 30 tests.
class MakeArgs():
"""
Making dummy args to test Basic.py functions.
"""
... |
# Generated by Django 2.0.2 on 2018-03-05 20:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user_profiles', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='IndividualProfile',
new_name='Individual... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
import numpy as np
import os
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
def get_loss_and_accuracy(save_dir):
"""
loads scalars from training procedure saved in summaries created by gtrain
:param save_dir: same as save_dir in gtrain method
:return: dict with
... |
# Copyright 2021 Sony Group Corporation
#
# 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 i... |
import numpy as np
def accuracy(y: np.ndarray, y_prediction: np.ndarray) -> np.float32:
"""Calculates accuracy for true labels and predicted labels.
:params y: True labels.
:params y_prediction: Predicted labels.
:return: Accuracy
:raises ValueError: If true labels and predicted labels are not of... |
import discord
from discord.ext import commands
from discord.ext.commands.errors import BadArgument
class Fun(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
def setup(bot):
bot.add_cog(Fun(bot))
print(f'Cog "Fun" loaded!') |
from cereal import log
from common.numpy_fast import clip, interp
from selfdrive.controls.lib.pid import PIDController
from common.travis_checker import travis
from selfdrive.config import Conversions as CV
LongCtrlState = log.ControlsState.LongControlState
STOPPING_EGO_SPEED = 0.5
MIN_CAN_SPEED = 0.3 # TODO: parame... |
#!/usr/bin/env python3
"""Base module for the calculation modules.
"""
import inspect
import json
import logging
import os
import jsonschema
import requests
from celery import Celery, Task
from celery.worker import worker
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL")
CELERY_RESULT_BACKEND = os.environ.get("... |
import torch
import contextlib
TRAIN_DESC, VALID_DESC, TEST_DESC = ('train', 'valid', 'test')
class EarlyStopException(Exception):
pass
class LoopComponent():
r"""
Base class for loop components. Each method is a callback to be
invoked by a `TrainTestLoop` instance, which is passed as an input.
I... |
import logging
from ..utility.model import LogData
from ..utility.constant import Status, LoadDataMode
from ..event import Event
from ..utility.event import *
from ..trade.db_model import *
from ..trade.account import Trader, order_generate
class AccountEngine:
"""账户引擎"""
def __init__(
self, event_e... |
from datetime import datetime, timedelta
from enum import Enum
from simple_pid import PID
class Direction(Enum):
COOLING = "cooling"
HEATING = "heating"
class Controller:
def __init__(
self,
setpoint,
pid_kp=1,
pid_ki=0.1,
pid_kd=0.05,
power_mult=30,
... |
from Resources.resources import MessageModel
import os
def main():
c = MessageModel()
c.credencias()
c.listar_cards()
c.insert_new_cards()
c.update_atributos()
c.relatorio_geral()
c.relatorio_novas_solicitacoes()
c.relatorio_aprovados()
c.relatorio_reprovados()
c.novas_solicitac... |
import discord
from discord.ext import commands
from modules import database
from discord.utils import get
from speasier import client
import sqlite3
database = database.database
class MessageHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_mess... |
# Specialization: Google IT Automation with Python
# Course 02: Using Python to Interact with the Operating System
# Week 3 Module Part 2 Exercise 01
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Fill in the code to check if the text passed contains the vowels a, e and i,
# with exactly one occu... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy
class PluginApp(AppConfig):
name = 'pretix_fsp_mail_template'
verbose_name = 'FSP Mail Template'
class PretixPluginMeta:
name = ugettext_lazy('FSP Mail Template')
author = 'Felix Gohla'
descriptio... |
import torch
import pandas as pd
from io import BytesIO
from subprocess import check_output
from . import writing
import time
def memory(device=0):
total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory
writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_m... |
"""
__init__.py for the Uptane demo package
"""
from __future__ import unicode_literals
import uptane # Import before TUF modules; may change tuf.conf values.
import os
import tuf.formats
import tuf.repository_tool as rt
import tuf.conf
import random, string # To generate random strings for Secondary directory names
... |
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test... |
#Tower of Hanoi - Recursive Method
def hanoi(n, origem, aux, destino):
if (n == 1):
print('Mova de', origem,'para', destino, '.')
else:
hanoi(n-1, origem, destino, aux)
hanoi(1, origem, aux, destino)
hanoi(n-1, aux, origem, destino)
... |
# Copyright (c) 2021, Aakvatech and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class StagingNHIFPricePackage(Document):
pass
|
import torch
import torchvision.models as models
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from visual_net import resnet18
def batch_organize(audio_data, posi_img_data, nega_img_data):
# print("audio data: ", audio_data.shape)
(B, T, C) = audio_data.size()
audio_data_batch... |
from azureml.core.authentication import ServicePrincipalAuthentication, AzureCliAuthentication, InteractiveLoginAuthentication, AuthenticationException
import os
from dotenv import set_key, get_key
import logging
import urllib
from zipfile import ZipFile
def get_auth(env_path):
logger = logging.getLogger(__name_... |
#-*- coding:utf-8 -*-
#'''
# Created on 18-12-27 上午10:34
#
# @Author: Greg Gao(laygin)
#'''
import os
import xml.etree.ElementTree as ET
import numpy as np
import cv2
from torch.utils.data import Dataset
import torch
from config import IMAGE_MEAN
from ctpn_utils import cal_rpn
def readxml(path):
gtboxes = []
... |
# -*- coding: utf-8 -*-
'''
The service module for Mac OS X
.. versionadded:: 2016.3.0
'''
from __future__ import absolute_import
# Import python libs
import os
import re
import plistlib
from distutils.version import LooseVersion
# Import salt libs
import salt.utils
import salt.utils.decorators as decorators
from sal... |
# NOTE: I AM MODIFYING THIS FROM https://github.com/GoogleCloudPlatform/microservices-demo/blob/master/src/loadgenerator/locustfile.py
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
#!/usr/bin/env python
from setuptools import setup, find_packages
def get_long_description():
return """
Usage: crypto.py
"""
setup(
name='cryptocompare-cli',
version="0.0.1",
author='TonyChG',
author_email='antoine.chiny@inria.fr',
long_description=get_long_description(),
url='htt... |
from neutro.src.trie.trie import Trie
from neutro.src.chain.transaction import Transaction
def test_trie():
txs = []
for i in range(10):
sender = "a" + str(i)
receivers = [str(i)]
amounts = [str(i + 100)]
fee = 100 * i
txs.append(Transaction(sender, receivers, amounts, ... |
import asyncio
import logging
import sys
import time
from threading import Thread, Event
from typing import Union, List, Tuple
from asyncio import Transport, Protocol
from bs4 import BeautifulSoup
import kik_unofficial.callbacks as callbacks
import kik_unofficial.datatypes.exceptions as exceptions
import kik_unofficia... |
"""
source - defines and describes a source
"""
from domain.base import Base
class RecursiveFragment(Base):
title = None
lead = None
text = None
fragments = None
def __init__(self, identifier, title, lead=None, text=None, fragments=[]):
super().__init__(identifier)
self.tit... |
import yaml
import numpy as np
import re
import os
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import (
to_gpu, split_chunk, slice_tensors,
build_vocab, clean_strings, generate_uid,
yaml_serializable, hash_strings
)
class Net(nn.Module):
def ... |
import scrapy
from scrapy.crawler import CrawlerProcess
# this doesn't work thanks seeking alpha, would need selenium
# from nlp_articles.app.nlp import init_nlp
settings = {}
import os
class ScraperForSeekingAlpha(scrapy.Spider):
name = "seeking_alpha"
start_urls = [
"https://seekingalpha.com/market-n... |
"""
Ory APIs
Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501
The version of the OpenAPI document: v0.0.1-alpha.187
Contact: support@ory.sh
Generated by: ht... |
import unittest
from pyats.topology import loader
class TestGetShowTech(unittest.TestCase):
def test_get_show_tech(self):
tb = loader.load('testbed.yaml')
dev = tb.devices.SW1
dev.connect(mit=True)
result = dev.api.get_show_tech(remote_server='scp-1', remote_path='/tmp')
s... |
import logging
from strategy import Action
from strategy import ActionException
from strategy import BlockOrigin
class Strategy:
def __init__(self, lead_stubborn=False, equal_fork_stubborn=False, trail_stubborn=0):
self.lead_stubborn = lead_stubborn
self.equal_fork_stubborn = equal_fork_stubborn
... |
# 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 writing, software
# d... |
# hdt_iterators_test.py
# Author: Thomas MINIER - MIT License 2017-2018
from hdt import HDTDocument
path = "tests/test.hdt"
document = HDTDocument(path)
def test_basic_join():
join_iter = document.search_join([
("?s", "http://example.org/p1", "http://example.org/o001"),
("?s", "http://example.org... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def to_hot_encoding(datos,caracteristicas_categoricas):
for cat in caracteristicas_categoricas:
one_encoding=pd.get_dummies(datos[cat],prefix=cat)
datos=pd.concat([datos,one_encoding],axis=1)
del datos[cat]
r... |
#! /usr/bin/env python
#######################################################################
# Newslist $Revision$
#
# Syntax:
# newslist [ -a ]
#
# This is a program to create a directory full of HTML pages
# which between them contain links to all the newsgroups available
# on your server.
#
# The -a option ca... |
# CreateDict.py
#
# License:
#
# Copyright <2019> <Larz60+>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
"""Helpers for converting between forms.
YAML -> (Candidates, Requirements) -> Error Messages
"""
from collections import defaultdict
from packaging.requirements import Requirement
from packaging.version import Version
from zazo.api import CannotSatisfy
from .exceptions import YAMLException
def _convert_error(re... |
__author__ = "Mohamed-Rafik Bouguelia"
__license__ = "MIT"
__email__ = "mohamed-rafik.bouguelia@hh.se"
from .individual_anomaly.individual_anomaly_inductive import IndividualAnomalyInductive
from .individual_anomaly.individual_anomaly_transductive import IndividualAnomalyTransductive
from .group_anomaly import GroupAn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
try:
from pipenv.project import Project
from pipenv.utils import convert_deps_to_pip
pfile = Project().parsed_pipfile
requirements = convert_deps_to_pip(pfile['packages'], r=False)
test_requirements = convert... |
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. 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
#
# Un... |
# New sink
eg23_sink = {'name' : 'Waste',
'config' : {'Sink' : {'in_commods' : {'val' : 'Waste'}
}
}
}
# Post-LWR Facilities
# Storage facilities can take many inputs but only give one output, so unlike in EG01
# am now separating th... |
import django_tables2 as tables
from events.models import Participant
from django_tables2.export.export import TableExport
class ParticipantTable(tables.Table):
export_formats = ['csv', 'xlsx']
class Meta:
model = Participant
template_name = "django_tables2/bootstrap.html"
fields = ("n... |
#!/usr/bin/env python
import copy,re,subprocess
class Parameter:
def __init__(this, typ, name):
this.typ = typ
this.name = name
def param_choices(x):
return param_choices_internal(x.items())
def param_choices_internal(list_of_ranges):
if len(list_of_ranges) == 0:
return [{}]
... |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from lib.basics import *
from lib.prepping import get_base_data
# Showing the data
def get_country_data_to_show(date_, plots, *countries, length=1000):
"""Returns the data from day date_ for the categories and variants defined
in t... |
import asyncio
import logging
_LOGGER = logging.getLogger(__name__)
async def restart_sensor_service():
try:
cmd = asyncio.create_subprocess_exec('systemctl',
'restart',
'sensor.service',
... |
# -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import os
from pytz import utc
from datetime import timedelta
import inspect
from apscheduler.jobstores.base import JobLookupError
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Zcash developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://www.opensource.org/licenses/mit-license.php .
from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCExceptio... |
from nltk import PCFG
from PSDProduction import PSDProduction
from nltk import Nonterminal
from typing import List, Set, Dict, Tuple, Optional, Callable
class PSDG(PCFG):
def __init__(
self,
start: Nonterminal,
productions: List[PSDProduction],
calculate_leftcorners: bool = True,
... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class FindCirc(Package):
"""Find-circ is a collection of python scripts
detecting head-to-ta... |
#!/usr/bin/env python3
import nose.tools as nose
import cidrbrewer
def test_get_subnet_mask():
"""Should compute the subnet mask."""
nose.assert_equal(
cidrbrewer.get_subnet_mask(28),
'11111111111111111111111111110000')
def test_get_network_id():
"""Should compute the network ID of an ... |
#
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from os.path import dirname, join
from requests_mock import ANY, mock as requests_mock
from six import text_type
from unittest import TestCase
from octodns.provider.mythicbeasts import MythicBeastsProvider, \
add_trai... |
# 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 writing, software
# d... |
__all__ = ['search_tasks', 'find_task_by_url', 'find_task_by_url_or_path', 'find_tasks_to_download', 'find_torrent_tasks_to_download', 'find_normal_tasks_to_download', 'expand_bt_sub_tasks', 'is_url', 'is_local_bt']
import re
import os
import urllib2
import fileinput
from lixian_encoding import default_encoding
impo... |
import socket
import threading
import logging
import re
from .streaming import TCPStreamingClient
from .broadcaster import Broadcaster
import os
class HTTPRequestHandler:
"""Handles the initial connection with HTTP clients"""
def __init__(self, port):
self.header = ""
self.header += "HTTP/1.0... |
# file kfkd.py
import os
import numpy as np
from pandas.io.parsers import read_csv
from sklearn.utils import shuffle
# Implicit import needed in newer theano versions
# https://groups.google.com/forum/#!msg/lasagne-users/gEtFrC8mkms/0oNCDbSKbTkJ
import lasagne.layers.cuda_convnet
FTRAIN = '../data/training.csv'
FTES... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as w... |
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated:
c["inbox_threads"] = Thread.inbox(request.user)
c["unread_threads"] = Thread.unread(request.user)
return c
|
# -*- coding:utf-8 -*-
__author__ = 'chenjun'
import torch
import torch.nn as nn
from torch_models.layers import InteractLayer, BatchNormLayer, MLP, MLPDropout
class CNNModule(nn.Module):
"""
qa_cnn module.
"""
def __init__(self, feature_maps, filter_shape, pool_size, channels=1):
"""
... |
import boto3
import json
import pprint
pp = pprint.PrettyPrinter(width=41, compact=True)
# Create IAM client
iam = boto3.client('iam')
response = iam.list_roles()
# list all roles
def getRoles():
role_data = []
for role in response['Roles']:
role_list = {}
role_name = role['RoleName']
ro... |
import traceback
def f(e):
return traceback.format_exception_only(type(e), e)
assert f(ValueError()) == ["ValueError\n"]
assert f(ValueError(1)) == ["ValueError: 1\n"]
assert f(ValueError(1, 2)) == ["ValueError: (1, 2)\n"]
class MyExc(Exception):
pass
assert f(MyExc()) == ["MyExc\n"]
from test_traceba... |
# Generated by Django 3.0.8 on 2020-08-11 19:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# Matplotlib documentation build configuration file, created by
# sphinx-quickstart on Fri May 2 12:33:25 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are... |
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
from flask import current_app as app
MQTT_USERNAME = "admin"
MQTT_PWD = "admin"
MQTT_ID = "SERVERADMIN"
def set_switch_state(device, state):
"""Publish 0 to MQTT broker
:@state: '0' or '1'
... |
"""Module for importing data from external APIs."""
|
from shexer.core.instances.annotators.strategy_mode.base_strategy_mode import BaseStrategyMode
from shexer.core.instances.pconsts import _S, _P, _O
class AllClasesMode(BaseStrategyMode):
def __init__(self, annotator_ref):
super().__init__(annotator_ref)
def is_relevant_triple(self, a_triple):
... |
import mxnet as mx
from mxnet import autograd
from mxnet import profiler
#################### Set Profiler Config ######################
profiler.set_config(profile_all=True, aggregate_stats=True, filename='cpu_mnist_cnn_profile_output.json')
###############################################################
# Build Net... |
from mailanalyzer.detector.abstract import AbstractDetector
import os
import glob
import re
import xml.etree.cElementTree as ET
class SenderDetector(AbstractDetector):
def __init__(self):
# to be extra careful, we also add all domainRegex as valid sendernames
path = os.path.join(os.path.dirname(__file__),'domai... |
import logging
import os
import inspect
import numpy as np
from sklearn.metrics import make_scorer
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import load_boston
from smac.configspace import ConfigurationSpace
from ConfigSpace.hyperpara... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: otp.uberdog.SpeedchatRelayGlobals
NORMAL = 0
CUSTOM = 1
EMOTE = 2
PIRATES_QUEST = 3
TOONTOWN_QUEST = 4 |
# coding: UTF-8
import numpy as np
from sklearn import datasets
import chainer
from chainer import Variable,Chain
import chainer.links as L
import chainer.functions as F
import chainer.optimizers as O
# データ読み込み
iris_data = datasets.load_iris()
# print(iris_data)
# データの取り出し
x = iris_data.data.astype(np.float32) # iri... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
FloodTool2
A QGIS plugin
MyCoast FloodTool
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
b... |
# MIT License
#
# Copyright (c) 2020-2021 Parakoopa and the SkyTemple Contributors
#
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.