content stringlengths 5 1.05M |
|---|
"""
Code obtained from https://github.com/kmkolasinski/deep-learning-notes/blob/master/max-normed-optimizer/src/callbacks.py
"""
from typing import List, Dict
import keras
_DEFAULT_METRICS = {
"losses": ["loss", "val_loss"],
"accuracies": ["acc", "val_acc"]
}
class AggregateMetricsOnBatchEnd(keras.callbacks... |
from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.UML.interactions.interaction import InteractionItem
from gaphor.UML.interactions.lifeline import LifelineItem
from gaphor.UML.interactions.message import MessageItem
@Group.register(InteractionItem, LifelineItem)
class InteractionLifelineGroup(Abstr... |
import engineApi
import broadcasts
import requests
import time
from beem.account import Account
hashkingsApi = 'https://hashkings.xyz'
def get_towers(account):
print(" Getting list of towers for account...")
propquery = {}
propquery['account'] = account
propquery['properties.TYPE'] = "water"
result = engine... |
import os
from setuptools import setup
requires = []
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8').read()
setup(
# Basic package information:
name='pythonish-validator',
version='0.5.1',
py_modules=('pythonish_validator',),
# Packaging opti... |
from rest_framework import serializers
from .models import Aluno, Curso
class AlunoSerializer(serializers.ModelSerializer):
class Meta:
model = Aluno
fields = '__all__'
class CursoSerializer(serializers.ModelSerializer):
class Meta:
model = Curso
fields = '__all__'
|
"""Used to communicate with iobeam's Imports API"""
from iobeam.endpoints import service
from iobeam.http import request
from iobeam.utils import utils
class ImportService(service.EndpointService):
"""Communicates with the backend and exposes available Imports API methods."""
_BATCH_SIZE = 1000 # max # of p... |
from skills_ml.storage import ModelStorage, FSStore
from skills_ml.job_postings.common_schema import JobPostingCollectionSample
from skills_ml.job_postings.filtering import JobPostingFilterer
from skills_ml.algorithms.embedding.models import Word2VecModel
from skills_ml.algorithms.preprocessing import IterablePipeli... |
from scimitar.core.modules.BaseModules import PreExecutionModule
class HeaderModule( PreExecutionModule ):
def __init__( self, run ):
PreExecutionModule.__init__( self, "Header Module", 1, run )
def getScriptContribution( self ):
contribution = "# ***** PreExecution: Print Log Header *****\n"
... |
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200, unique=True)
pub_date = models.DateTimeField("date published", auto_now_add=True)
def __str__(self):
return self.question
|
# -*- coding: utf-8 -*-
"""
@author: TK
<checkdata.py>: inital data upload-- clean and tidy up etc for further analysis. Output: new .csv to be uploaded elsewhere.
>>>> Norlys ET -- Quant exercise <<<<
One of your colleagues have discovered a trading strategy that looks to be quite profitable. The... |
from __future__ import print_function
import os
import sys
import time
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from matplotlib import pyplot as plt
from scipy.ndimage.interpolation import rotate
from torchvisi... |
from maestro_api.db.models.workspace import Workspace
from maestro_api.db.models.user import User, UserRole
from maestro_api.db.repo.run import RunRepository
from maestro_api.db.models.run import Run
from maestro_api.db.models.run_configuration import RunConfiguration
from maestro_api.libs.flask.utils import (
js... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 th... |
# Factory-like class for mortgage options
class MortgageOptions:
def __init__(self,kind,**inputOptions):
self.set_default_options()
self.set_kind_options(kind = kind)
self.set_input_options(**inputOptions)
def set_default_options(self):
self.optionList = dict()
self.optionList['commonDefaul... |
from __future__ import annotations
from typing import *
import distro
from metapkg.targets import base as targets
from metapkg.targets import generic
from metapkg.targets import deb
from metapkg.targets import rpm
from . import build as linbuild
class LinuxGenericTarget(generic.GenericTarget, targets.LinuxTarget):... |
import carim.configuration.omega.config
|
from regraph.tree import child_from_path
def _get_father_id(hie, top, path_to_graph):
path_list = [s for s in path_to_graph.split("/") if s and not s.isspace()]
if path_list == []:
raise ValueError("/ is not a valid name")
else:
graph_id = path_list[-1]
parent_id = child_from_path(... |
teste = list()
pessoas = list()
teste.append('Mauro')
teste.append(24)
pessoas.append(teste[:])
teste[0] = 'Maria'
teste[1] = 30
pessoas.append(teste[:])
print(pessoas)
pessoas = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
for p in pessoas:
print(f'{p[0]} tem {p[1]} anos de idade')
pessoas =... |
# Import dependencies
import os
import csv
# Declare Variables
total_votes = 0
khan_votes = 0
correy_votes = 0
li_votes = 0
otooley_votes = 0
# Assign file location with the pathlib library
csvpath = os.path.join('Resources', 'election_data.csv')
# Open csv in default read mode with context manager
with open(csvpa... |
# Using readliness()
file1 = open('directions.txt', 'r')
Lines = file1.readlines()
# ******************************************
# PART 2 - Aim
# In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0.
# What do you get if you multiply your final horizontal po... |
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
from rest_framework.serializers import ModelSerializer, SerializerMethodField
from game.models import Game
class GameSerializer(ModelSerializer):
score = SerializerMethodField(method_name="get_score")
class Meta:
model = Game
fields = ("name", "... |
import copy
import matplotlib.pyplot as plt
import numpy
import pdb
import accelerated_functions as af
import constants as c
from Boundaries.inner_1D_rectangular import Inner_1D_Rectangular
from solver import location_indexes_inv
from Species.species import Species
from timing import Timing
#Inner_1D_HET (Inherits f... |
#!/usr/bin/python
##
## MPlot PlotPanel: a wx.Panel for 2D line plotting, using matplotlib
##
import sys
import time
import os
import wx
from threading import Thread
import numpy as np
import matplotlib
import matplotlib.cm as cmap
from matplotlib.figure import Figure
from matplotlib.gridspec import GridSpec
from mat... |
from django.urls import path
from .views import (
HomeView, NewCampaignView, NewPageView, DeletePageView,
CopyJsCode, AllPageView, TrafficCounter
)
app_name = 'analytics'
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('add-campaign/', NewCampaignView.as_view(), name='new-campaign'),
... |
# coding: utf-8
""" Misc utility functions """
from __future__ import (division, print_function, absolute_import,
unicode_literals)
from six import string_types
import numpy as np
from .robust_polyfit import gaussfit
from scipy import interpolate, signal, stats
import emcee
import time
from a... |
# Dictionary of Block Names (name, label, and category)
blocknames = [{"name": "motion_movesteps", "label": "Move Steps", "category": "motion"}, {"name": "motion_turnright", "label": "Turn Right", "category": "motion"}, {"name": "motion_turnleft", "label": "Turn Left", "category": "motion"},
{"name": "motion_goto"... |
# Code to parse ENSDF format following the manual instructions
# https://www.nndc.bnl.gov/nndcscr/documents/ensdf/ensdf-manual.pdf
# Here the structure of the file should be replicated by a class that
# contains analogous substructure to that of the file
# Files general info:
# - An ENSDF is a collection of 'datase... |
#Author: Andrzej Serwotka
from tkinter import *
from tkinter import ttk
from pathlib import Path
import shlex
import subprocess
import _thread
import os
root = Tk()
root.minsize(width=640, height=480)
root.maxsize(width=640, height=480)
filedropboxuploader = open('dropbox_uploader_path.txt', 'r')
dropboks_app_path =... |
from typing import Optional, Tuple, List
def has_diffs(
file_a: str,
file_b: str,
ignore_comments: Optional[List[str]] = None,
ignore_blocks: Optional[List[Tuple[str, str]]] = None,
ignore_blank_lines: bool = True,
) -> bool:
"""
This function compares the two ASCII files at the given path... |
import json
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard.api import sds_controller as api
from openstack_dashboard.dashboards.sdscontroller import exce... |
#! python3
# rackMultipleWeights.py - Input (the number for rep max, the weight for rep max from previous number, reps for each set separated by spaces) Output- weight and how much per side.
import sys, logging
#Set Up Logging
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.DEBUG,... |
# Copyright 2013-2022 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 Coinutils(AutotoolsPackage):
"""CoinUtils is an open-source collection of classes and help... |
"""
Given a m x n grid filled with non-negative numbers, find a path from top left
to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1... |
# Statistics
from collections import defaultdict, Counter
num_friends = [100,49,41,40,25,21,21,19,19,18,18,16,15,15,15,15,14,14,13,13,13,13,12,12,11,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,6... |
from beacon.nn.module import Module
from beacon.functional import functions as F
from abc import abstractmethod
class PoolingLayer(Module):
@abstractmethod
def __init__(self, kernel, stride=None, padding=(0,0)):
"""
Represents abstract pooling layer.
"""
super().__init__()
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import rasterio
from rasterio.errors import NodataShadowWarning, NotGeoreferencedWarning
from affine import Affine
import pytest
def gen_rpcs():
with rasterio.open('tests/data/RGB.byte.rpc.vrt') as src:
return src.rpcs
def test_nodata_shadow():
assert str(NodataShadowWarning()) == (
"The dat... |
#!/usr/bin/env python3
import pdb
import sys
# ABC = AB^AC
# (ABC^AJ).a = (j.c - j.b) a.a + (j.a - j.c) b.a + (j.b - j.a) c.a, for j = b or c
segment_fmt = "{j}a_aa"
plane_fmt = ""
edge_fmt = "{j}a * {b}a_{c}a + {j}{b} * {c}a_aa - {j}{c} * {b}a_aa"
# These checks must be negative and not positive, as in the cheat sh... |
# coding: utf-8
# In[1]:
from pathlib import Path
# In[2]:
homedir = Path(Path.cwd()).parent
raw_data_dir = homedir / 'data/raw'
reports_dir = homedir / 'reports'
# In[3]:
import sys
sys.path.append(str(homedir))
# In[4]:
import cufflinks as cf
import plotly.offline as py
import plotly.graph_objs as go
cf... |
# -*- coding: utf-8 -*-
import re
from twisted.internet import defer, reactor
import bnw.core.base
# please don't remove the group from the regexp - it is used in
# bnw/xmpp/parser_simplified.py
USER_RE = ur'@?([0-9A-Za-z_-]+)'
MESSAGE_RE = r'#?([0-9A-Za-z]+)'
COMMENT_RE = r'#?([0-9A-Za-z]+(?:#|/)[0-9A-Za-z]+)'
MESSA... |
#! /usr/bin/env python
"""
This script finds clusters in group FFX (MNI space, smoothed), and then outputs
the peaks within a specified ROI as a csv file.
"""
import numpy as np
import glob
import os
import os.path as op
from scipy import stats
import nibabel as nib
import pandas as pd
from moss import locator
fro... |
#Example of extracting data from a website that is not designed to do so
#you have to figure out the url of the page class, ids etc,.
#if myhome.ie change the design of the site, this program should be updated.
import requests
import csv
from bs4 import BeautifulSoup
page = requests.get("https://www.myhome.ie/residenti... |
"""Provides configuration utilities for using the filters."""
from __future__ import absolute_import
from inspect import getmembers
from inspect import isfunction
from . import datetimes
from . import filters
from . import munging
from . import random
def _get_funcs(module):
"""Extract all functions from a mod... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import pywt
import tensorflow as tf
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from sklearn.metrics import mean_absolute_error, mean_squared_er... |
#Python
from typing import Optional
from enum import Enum
#Pydantic
from pydantic import BaseModel, Field
#FastAPI
from fastapi import FastAPI
from fastapi import Body, Query, Path
app = FastAPI()
#Models
class HairColor(Enum):
white = "White"
brown = "Brown"
black = "Black"
blonde = "Blonde"
r... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import os
import subprocess
import time
from collections import defaultdict, deque
import datetime
import pickle
from packaging import version
fro... |
import unittest
from fortranformat._input import input as _input
from fortranformat._lexer import lexer as _lexer
from fortranformat._parser import parser as _parser
import fortranformat.config as config
class MultiEditDescriptorTests(unittest.TestCase):
def setUp(self):
config.reset()
def test_1(... |
import unittest
from neo.rawio.elanrawio import ElanRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestElanRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = ElanRawIO
entities_to_test = [
'elan/File_elan_1.eeg'
]
entities_to_download = [
'elan',
... |
import numpy
import six
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
class EmbedIDFunction(function_node.FunctionNode):
def __init__(self, ignore_label=None):
self.ignore_label = ignore_label
def ... |
from dotdict import dotdict
class Plugin(object):
def process(self, path, http_history):
if self._path_contains(path, 'items'):
self.process_item(dotdict(http_history))
return True
def process_item(self, item):
raise NotImplementedError
def _path_contains(self, path,... |
"""
## Twitter Celebrity Matcher - Streamlit App
This app is a tool to match celebrities from Twitter with their respective tweets.
Author: [Ahmed Shahriar Sakib](https://www.linkedin.com/in/ahmedshahriar)
Source: [Github](https://github.com/ahmedshahriar/TwitterCelebrityMatcher)
"""
import streamlit as st
from app... |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2019, T-Systems International
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
"""
Programming for linguists
Implementation of the class Rhombus
"""
from shapes.square import Square
class Rhombus(Square):
"""
A class for rhombi
"""
def __init__(self, uid: int, length: int, sin: float):
self.sin = sin
super().__init__(uid, length)
def get_area(self):
... |
import argparse
import os
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
from src.data import load_data, load_params, save_as_csv
def main(train_path, test_path,
output_dir):
"""Build features
TODO- Currently a placeholder script... |
from search_api.constants.charge_id import ChargeId
from search_api.exceptions import ApplicationError
import re
# TODO(This service is duplicated in the maintain-api any changes here should be mirrored there.)
# TODO(Once the infrastructure is in place this service should be moved into a module and imported into thi... |
try:
from typing import TypedDict
except ImportError:
from typing_extensions import TypedDict
configuration = TypedDict(
"configuration", {"running": str, "candidate": str, "startup": str}
)
alive = TypedDict("alive", {"is_alive": bool})
facts = TypedDict(
"facts",
{
"os_version": str,
... |
class MatrixChainMultiplication(object):
def __init__(self, *seq):
self.seq = seq
self.assureSeqValid(seq)
def run(self):
if not self.seq:
return 0
seq, seqlen = self.seq, len(self.seq)
dp = self.dp = [[0] * (seqlen+1) for _ in xrange(seqlen+1)]
for ssl in xrange(1, seqlen+1): # for all subsequence... |
from django.urls import path, include
from django.urls.resolvers import URLPattern
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('dashboard/', views.dashboard, name='dashboard'),
path('save/', views.save, name='save'),
path('save-attendance/', views.save_to_database, nam... |
from django.test import TestCase
from msgvis.apps.dimensions import models, registry
class DimensionRegistryTest(TestCase):
"""Test the dimension registry"""
def test_registry_contains_dimension(self):
"""The registry should have some dimensions"""
time = registry.get_dimension('time')
... |
#! /usr/local/bin/python3
import codecs
import csv
from argparse import ArgumentParser
from collections import namedtuple
from datetime import date
from pathlib import Path
_sessions = {'10': ('1', 'WIN'), # WIN
'20': ('2', '1'), # SPR
'58': ('6', '1'), # Summer 8 Week
'... |
import json
import nltk
import re
#import emoji
from nltk.sentiment.vader import SentimentIntensityAnalyzer
posi=0
nega=0
neut=0
with open('Alice_through_the_looking_glass.json',encoding='utf-8',errors='ignore') as json_file:
data = json.load(json_file)
sid = SentimentIntensityAnalyzer()
com... |
from io import BytesIO
import os
import base64
import textwrap
from PIL import ImageFont
from rdkit import Chem
from rdkit.Chem import Draw
from dash import Dash
import plotly.express as px
from dash import dcc, html, Input, Output, no_update
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
def a... |
# Copyright 2017 Google Inc.
#
# 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, ... |
from django.conf import settings
from django.db.models.query import Q
from django.http import Http404, HttpResponseRedirect
from django.forms.models import inlineformset_factory
from django.shortcuts import get_object_or_404, render_to_response, render
from django.template import RequestContext
from django.views.generi... |
from .threads_thread_id_invitations_route import ThreadsThreadIdInvitationsRoute
|
import nengo
import numpy as np
import math
def a_gt_b():
a_gt = nengo.Network()
with a_gt:
if_gt_than = nengo.Ensemble(50, dimensions=2, intercepts=nengo.dists.Uniform(0.9, 1.0))
bg_re_enc = nengo.Ensemble(256, dimensions=2)
bg = nengo.networks.BasalGanglia(dimensions=2)
in_a ... |
def main():
n = int(input())
for i in range(n):
a, b = map(int, input().split())
print(a + b)
if __name__ == 'main':
main()
|
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.geometry._core import subtract_vectors
from compas.geometry._core import subtract_vectors_xy
from compas.geometry._core import cross_vectors
from compas.geometry._core import cross_vectors_xy
from c... |
import re
from abc import abstractmethod, ABCMeta
from collections import defaultdict
from functools import partial
import numpy as np
import tables
from astropy.time import Time
from astropy.units import Quantity
import ctapipe
from ctapipe.core import Component
__all__ = ['TableWriter',
'TableReader',
... |
"""The init file for the blackjack package."""
from .cards import Card
from .cards import InvalidSuit
from .cards import InvalidFace
from .decks import Deck
from .decks import InvalidDeckSize
from .decks import InvalidDeckDraw
from .people import Person
from .people import InvalidPersonName
from .people import InvalidC... |
import sublime
import sublime_plugin
"""Generate fully qualified class name
1. If string does not start with a backslash, search 'Result' in 'use'
2. If not found, join the string with a 'namespace'
"""
def getFullyQualifiedClassName(view, string, selection = False):
# If string starts with a backslash - do noth... |
from aws_cdk import (core as cdk,
aws_ec2 as ec2,
)
# For consistency with other languages, `cdk` is the preferred import name for
# the CDK's core module. The following line also imports it as `core` for use
# with examples from the CDK Developer's Guide, which are in the pr... |
#!/usr/bin/python
from HAT import IAQ_DAC43608
from HAT import IAQ_Mux
from third_party import Adafruit_ADS1x15
from enum import Enum
import time
class AnalogPortController:
adc = None
dac = None
mux = None
A0 = 0
A1 = 0
A2 = 0
A3 = 0
A4 = 0
A5 = 0
GAIN = 1
de... |
from .fcn_head import FCNHead
from .psp_head import PSPHead
from .uper_head import UPerHead
__all__ = ['FCNHead', 'PSPHead']
|
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
'''
Adaptable parameters and methods, functionality and API
'''
import numpy as np
# %% Adaptable methods
class adaptable_method():
'''
Base class for methods / parameters that are selected / updated as part of an adaptive scheme
'''
name = 'adaptable item'
def __init__(self):
self.hit... |
SOS_token = 0
EOS_token = 1
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.index2word = {SOS_token: 'SOS', EOS_token: 'EOS'}
self.word2count = {}
self.n_words = 2
def add_sentence(self, sentence):
for word in sentence.split(' '... |
#!/usr/bin/env python
"""
WorkQueue PolicyInterface
"""
from builtins import object
import logging
from copy import deepcopy
class PolicyInterface(object):
"""Interface for policies"""
def __init__(self, **args):
self.logger = args.pop('logger') if args.get('logger') else logging.getLogger()
... |
from django.test import TestCase, Client
from django.contrib.auth.models import User, Group
from django.contrib.auth.hashers import check_password
from django.urls import reverse
client = Client()
# Create your tests here.
class ApiTest(TestCase):
""" Test module for API """
def setUp(self):
User.objects.create_u... |
# 필터링 제너레이터 함수의 예
import itertools
def vowel(c):
return c.lower() in 'aeiou'
list(filter(vowel, 'Aardvark')) # ['A', 'a', 'a']
list(itertools.filterfalse(vowel, 'Aardvark')) # ['r', 'd', 'v', 'r', 'k']
list(itertools.takewhile(vowel, 'Aardvark')) # ['A', 'a'] ; 거짓이 등장하면 생성안함
list(itertools.dropwhile(vowel, 'Aardv... |
import numpy as np
import math
from collections import Counter
from util.batchers import get_pred_target_split
def bleu(stats):
"""Compute BLEU given n-gram statistics"""
if len(list(filter(lambda x: x == 0, stats))) > 0:
return 0
(c, r) = stats[:2]
log_bleu_perc = sum([math.log(float(x)/y) fo... |
from django.views.generic import TemplateView
from django.core.urlresolvers import reverse
from ..models import LogEntry
from ..util import paginate
class EventLogView(TemplateView):
template_name = 'students/events_log.html'
def get_context_data(self, **kwargs):
context = super(EventLogView, self).g... |
from .test_aes import *
from .test_key import *
from .test_state import *
from .test_utils import *
from .test_avalanche_and_time import *
|
from __future__ import absolute_import
import torch
import torch.nn.functional as F
from torch.nn.modules import Module
from torch.nn.parameter import Parameter
from torch.nn.modules.utils import _pair as pair
from torch.nn import init
import numpy as np
class group_lasso_Dense(Module):
"""Implementation of TFL reg... |
class A20:
pass
|
import tensorflow as tf
import cPickle as pickle
import numpy as np
from supercell_new import LSTMCell
from RL_brain import PolicyGradient
batch_size = 100
time_step = 11
rnn_size = 200
learning_rate = 0.001
epoch = 200
n_actions = 10
train_set = np.array(pickle.load(open('num_train10_1.pkl', 'rb')))
test_set = np.ar... |
# Original: https://www.youtube.com/channel/UC4JX40jDee_tINbkjycV4Sg
# Edited: https://github.com/rafaelurben
# Imports
import pygame
from time import sleep
from random import randint
# Relative Imports
from .coordinates import calculate_relative_pos, coord_distance, coord_angle
# Classes
class Player():
play... |
# Copyright (c) 2013 Molly White
#
# 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, distrib... |
##############################################################################
# Copyright (c) 2015 Ericsson AB 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... |
import copy
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from .grad_utils import *
from collections import deque
import logging
class DDPG... |
# Copyright (c) 2014 OpenStack Foundation.
# 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... |
from django import template
from submit.constants import ReviewResponse
from submit.forms import submit_form_factory
from submit.models import Submit
register = template.Library()
@register.inclusion_tag('submit/parts/submit_form.html')
def submit_form(receiver, redirect, user, caption=None):
"""
Renders su... |
import logging
from flask import jsonify, request, Blueprint
from marshmallow import Schema, fields, ValidationError, validate
from api.hue import HueClient
log = logging.getLogger(__name__)
bp = Blueprint('hue_api', __name__, url_prefix="/hue")
class ActionSchema(Schema):
on = fields.Boolean()
bri = fiel... |
import setuptools
with open('README.rst') as fp:
long_description = fp.read()
setuptools.setup(
name='symplectic',
license='MIT',
description="symplectic: generating blogs",
long_description=long_description,
use_incremental=True,
setup_requires=['incremental'],
author="Moshe Zadka",
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Libermatic and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import money_in_words
from erpnext.controllers.accounts_controller import AccountsController
from erpnext.accounts.general_... |
import model.hook
import model.cli
history=[]
def add_history(message):
global history
history.append({"que":message["string"],"ans":message["return"]})
def get_history():
global history
return history
model.hook.add_hook_fast("RRCore.Model.After.FuncRunning",add_history)
model.cli.command_registry(... |
import pathlib
from setuptools import setup
BASE_DIR = pathlib.Path(__file__).parent
README = (BASE_DIR / "README.md").read_text()
setup(
name="rudie-pomodoro-tracker",
version="0.1.0",
description="Pomodoro tracker with CLI interface.",
long_description=README,
long_description_content_type="tex... |
from RestrictedPython import compile_restricted_exec
# Zipline API
from zipline import run_algorithm
# Dataframe
import pandas as pd
# Data frame to JSON
from .allowed_imports import GLOBAL_FIELDS
# Logging
from backend.api.logger import Logger
from backend.api.create_response import create_json_response
from .fil... |
import time
from datetime import datetime
from functools import partial
from typing import AnyStr, Dict, Union, List, Any
from app.utils import status
from app.utils.constants import APP_NAME, DATETIME_FORMAT
class ResponseMaker(object):
"""
Class containing methods to construct response as output for APIs
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2018-03-04 11:02
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('timetable', '0001_initial'),
]
operations = [
migrations.RemoveField(
mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.