content stringlengths 5 1.05M |
|---|
#-*- coding: utf-8 -*-
class konto:
def __init__(self,name,id,geld):
self.name = name
self.id = id
self.geld = geld
def einzahlen(z,geld):
if (geld>0):
self.geld = self.geld + geld
def auszahlen(self,geld):
if (geld<0):
self.geld = self.gel... |
import pandas as pd
import numpy as np
import re
####################################
# Currently the notebook "bayesmatch.ipynb" is
# the best version of this code.
# For now, ignore this file.
####################################
# import numpy as np
def process_name(field):
# Rules for names:
# Assu... |
#!/usr/bin/env python
import barcode
from barcode.writer import ImageWriter
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm
from egcg_core.config import cfg
from EPPs.common import SendMailEPP
class GenerateTrackingLetter(SendMailEPP):
'''Automatically generates... |
from .attenuation import correct_attenuation, correct_attenuation_HB, pia_from_kdp |
'''
VAE testing.
'''
import numpy as np
import logging
#import argparse
from common import expInterp, ensure_dir_exists
import batch
##########################################################################################
# SETUP
#####################################################################################... |
"""
Analyze the experimental results.
"""
# Author: Georgios Douzas <gdouzas@icloud.com>
# João Fonseca <jpmrfonseca@gmail.com>
# License: MIT
import sys
from os.path import join, dirname
from collections import OrderedDict
from itertools import product
import pandas as pd
import numpy as np
import matplotlib... |
#-*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns("spirit.views.topic_poll",
url(r'^update/(?P<pk>\d+)/$', 'poll_update', name='poll-update'),
url(r'^close/(?P<pk>\d+)/$', 'poll_close', name='poll-close'),
url(r'^vote/(?P<pk>\d+)/$', 'poll_vote', name='poll-vote'),
... |
# Copyright (c) 2017. Mount Sinai School of Medicine
#
# 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 o... |
# Generated by Django 2.2 on 2019-04-15 17:29
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("authentication", "0003_auto_20190415_1946")]
operations = [
migrations.CreateModel(
... |
"""Docutils Markdown parser"""
from docutils import parsers, nodes
from html.parser import HTMLParser
from markdown import markdown
from pydash import _
import re
import yaml
__all__ = ['MarkdownParser']
class MarkdownParser(parsers.Parser):
"""Docutils parser for Markdown"""
depth = 0
html_mode = Fals... |
from __future__ import annotations
import inspect
import typing
from collections import OrderedDict
from dataclasses import asdict, dataclass, field
from functools import partial, wraps
from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Type, Union, cast
from basis.configuration.graph import GraphCfg
f... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 15:23:34 2020
@author: rodri
"""
#Regras de associação
import pandas as pd
from apyori import apriori
dados = pd.read_csv('transacoes.txt', header = None) # reader para ignorar
#primeira linha
# Preciso transformar dados de dataframe para list
transacoes=[]
for i... |
#
# 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 not... |
# Generated by Django 3.0.8 on 2020-08-07 19:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20200721_0252'),
]
operations = [
migrations.AddField(
model_name='accounttier',
name='file_do... |
#!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import argparse
import os
import re
import shutil
import subprocess
import sys
parser = argparse.ArgumentParser(description="Script for library testing")
parser.add_argument(
'--toolchain',
choices=[
'libcxx',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
"""Vendor module."""
from typing import Any
from typing import Dict
from onapsdk.sdc.sdc_element import SdcElement
import onapsdk.constants as const
from onapsdk.utils.headers_creator import headers_sdc_creator
class Vendor(SdcEleme... |
import logging
from spaceone.core.manager import BaseManager
from spaceone.config.model.domain_config_model import DomainConfig
_LOGGER = logging.getLogger(__name__)
class DomainConfigManager(BaseManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.domain_config... |
# -*- coding: utf-8 -*-
# This plugins is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Authors: Yusuke Kishita <yuusuuke.kishiita@gmail.com>, Kenji Hosoda <hosoda@s-cubism.jp>
from gluon import *
# For referencing static and views from other application
import os
APP = os.path.b... |
# tear_down_and_build.py
from engine import OracleConnection
from drop_tables import drop_tables
from create_tables import create_tables
from create_views import create_views
from create_procedures import create_procedures
from insert_data import insert_csv_data_into_oracle
if __name__ == '__main__':
conn = Orac... |
"""
Demonstrate the YuMiSubscriber
Author: Jeff Mahler
"""
import IPython
import logging
import matplotlib.pyplot as plt
import numpy as np
from yumipy import YuMiSubscriber
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
subscriber = YuMiSubscriber()
subscriber.start()
# read t... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import builtins
import math
import os
import random
import time
import warnings
import pickle
import glob
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.backends.cudnn as... |
from .url_replace import url_replace # noqa
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from DNetPRO import DNetPRO
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection i... |
from icolos.utils.enums.step_enums import StepBaseEnum, StepGromacsEnum
from icolos.utils.enums.program_parameters import GromacsEnum
from icolos.core.workflow_steps.gromacs.base import StepGromacsBase
from icolos.utils.execute_external.gromacs import GromacsExecutor
from pydantic import BaseModel
from icolos.core.work... |
from SuPyModes.Geometry import Geometry, Circle
from SuPyModes.sellmeier import Fused_silica
Clad = Circle(Radi = 62.5, Position = (0,0), Index = Fused_silica(1.55))
Clad.Plot()
|
from dgl.nn.pytorch import GATConv
"""
Non-message passing framework for GAT
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.autograd import Variable
class PositionalEncoder(nn.Module):
def __init__(self, d_model,device, max_seq_len = 80):
super().__init__()
self... |
from collections import MutableMapping
class Backend(MutableMapping):
pass
|
import os, yaml, time, shutil
import logging
logger = logging.getLogger(__name__)
from evento import Event
class ConfigFile:
def __init__(self, path, options = {}):
# config
self.path = path
# attributes
self.previous_data = None
self.data = None
# events
... |
from src.data import read_raw_data, preprocess_data, get_featues, get_label
def test_raw_shape():
dframe = read_raw_data()
assert dframe.shape == (150, 5)
def test_get_features_shape():
dframe = read_raw_data()
processed = preprocess_data(dframe)
features = get_featues(processed)
label = get... |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from queries import CRUDQuery
class get_mention_metadata(CRUDQuery):
""" Get the metadata of a mention
"""
# https://knowledgestore.fbk.eu/nwr/worldcup-hackathon/mentions?id=%3Chttp%3A%2F%2Fnews.bbc.co.uk%2Fsport2%2Fhi%2Ffootb... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def determine_split_filters(apps, schema_editor):
"""Determine whether each split should be designated as filtered. New,
incoming splits are automatically filtered, but this function will
apply the fi... |
# 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 PyNetcdf4(PythonPackage):
"""Python interface to the netCDF Library."""
homepage = "h... |
# pip3 install requests Flask
from ..IOAgent import IOAgent
from abc import ABC
import socket
import platform
import subprocess
import json
import logging
module_logger = logging.getLogger('BasicUdpAgent')
class BasicUdpAgent():
def __init__(self, config):
self.logger = logging.getLogger('BasicUdpAge... |
# ------------------------------------------------------------------------------
# SublimeServer 0.3.3
# ------------------------------------------------------------------------------
__VERSION__ = "0.3.3"
import os
import sys
import sublime
import sublime_plugin
import threading
import webbrowser
import posixpath
imp... |
#Import the model
from Model import model
#Import the Packages
import tweepy
import json
from flask import Flask
#Initialize API credentials
api_key='YOUR API KEY'
api_secret='YOUR API SECRET'
access_token='YOUR ACCESS TOKEN'
access_secret='YOUR ACCESS SECRET'
#Authenticate the API
auth= tweepy.OAuthHandler(api_key... |
from openpyxl.workbook import Workbook
from openpyxl import load_workbook
fhand = open('table.txt', 'a')
wb = load_workbook("excel-files\Planning d'Examen Automne2018F.xlsx") # Selecting students
ws = wb.active
row = ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
def schedule_iteration(row):
column = 0
... |
# /*
# * Copyright (C) 2020 ACTUAL Systems, Inc.
# *
# * http://www.actualhq.com
# *
# * In collaboration with UNICEF/Giga: https://gigaconnect.org
# *
# * 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 c... |
from cli import *
import sim_core
from simics_1_8_api import *
from simics_2_0_api import *
from simics_2_2_api import *
def SIM_read_fp_register_i(cpu, reg):
return sim_core.OLD_read_fp_register_i(cpu, reg)
def SIM_read_fp_register_x(cpu, reg):
return sim_core.OLD_read_fp_register_x(cpu, reg)
def SIM_read_... |
from flask import Flask, request
from tgmsg import TelegramClient, messages
app = Flask(__name__)
client = TelegramClient('<YOUR_TOKEN>')
@client.register_message_processor()
def text_handler(incoming):
msg = messages.TextMessage(incoming.message.text)
client.send_message(msg, incoming.message.chat.id)
@ap... |
#!/usr/bin/env python
import numpy as np
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def load_date_series():
dirname = os.path.dirname(os.path.realpath(__file__))
return pd.read_csv(dirname + '/data/shampoo.csv', header=0, parse_dates=[0], index_col=0, squeeze=True)
def split... |
from db import db, Hackers as HackersModel, get_query_res, query_to_dict
from flask_restful import Api, Resource
from webargs import fields
from webargs.flaskparser import use_kwargs
api = Api()
types = {
'public_id': fields.Integer,
'team_id': fields.Integer,
'first_name': fields.String,
'last_name':... |
#__LICENSE_GOES_HERE__
import babel_mod.babelgen_ext
from util.primitives.mapping import odict
import babel.messages.pofile as pofile
import argparse
write_po = pofile.write_po
from babel.messages.catalog import Catalog, Message
from babel.messages.pofile import read_po
from genargspec import get_argspec
from path impo... |
if __name__=='__main__':
from salklib import KeyLogger
import sys
try:
sys.argv[1]
kl = KeyLogger()
except:
import tkMessageBox
tkMessageBox.showinfo("About SALK", "Sarath Kumar\nWeb:www.fb.com/sarathtvmala\nUsage:salk.exe <filename>\nUse Education purpose only\n***Quad-K... |
from design_baselines.utils import spearman
from collections import defaultdict
from tensorflow_probability import distributions as tfpd
import tensorflow as tf
class Ensemble(tf.Module):
def __init__(self,
forward_models,
forward_model_optim=tf.keras.optimizers.Adam,
... |
#!/usr/bin/python3
import time
import cv2
import numpy
import argparse
import copy
from picamera.array import PiRGBArray
from picamera import PiCamera
import RPi.GPIO as GPIO
from tm1637 import TM1637
from io import BytesIO
from PIL import Image
import mvnc.mvncapi as mvnc
from http.server import HTTPServer, BaseHTT... |
"""
Copyright (c) 2018 Intel 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 in writin... |
from django.conf.urls import url
import views as performance_views
urlpatterns = [
url(r'^$', performance_views.user_performance_index,
name="user_performance_index")
]
|
#!/usr/bin/env python
"""Communication protocol with unprivileged servers."""
import abc
import contextlib
import os
import platform
import struct
import subprocess
from typing import NamedTuple, Callable, Optional, List, BinaryIO
class Transport(abc.ABC):
"""Low-level transport protocol."""
@abc.abstractmethod... |
import os
import math
import sys
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as Func
from torch.nn import init
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.optim as optim
from torch.utils.data import Dataset
from torch.utils.dat... |
from wave1D_func1 import solver
from numpy import sin, pi
def I(x): return sin(2*x*pi/L)
def f(x,t): return 0
solutions = []
time_level_counter = 0
version = 'scalar'
N = int(sys.argv[1])
def action(u, x, t):
global time_level_counter
if time_level_counter % N == 0:
solutions.append(u.copy())
ti... |
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
import transformers
from cfg import config
class EULADataset(Dataset):
"""A wrapper class for a EULA Dataset. Contains clauses and target labels.
Args:
text (str): the EULA text
labels (list): a list of targets labe... |
import re
import statistics
from itertools import chain
class LengthStatistics:
def run(self, data):
results = []
for corpus in data:
corpus.contents = corpus.contents.strip()
sentences = [re.sub(r"[.,:;!?()[\]{\}]", "", sentence.strip()) for sentence in
... |
from typing import List
import numpy as np
import itertools
from math import cos, sin, pi
class LSystem:
def __init__(self, axiom: List[str], constants: List[str], rules: dict, render_config, rules_probs=None):
self.axiom = axiom
self.constants = constants # a variable list would be redundant (ca... |
from django_filters import rest_framework as filters
from apps.recipes.models import Ingredient
class IngredientFilter(filters.FilterSet):
title = filters.CharFilter(field_name='title', lookup_expr='icontains')
class Meta:
model = Ingredient
fields = ['title']
|
# -*- coding: utf-8 -*-
"""Paths to data."""
from pathlib import Path
# Top-level directory containing code and data (one level up)
topdir = Path(__file__).absolute().parent.parent
# Modelling results
datadir = topdir / "data"
extdatadir = Path("/media") / Path.home().parts[-1] / "Elements" / "exoplanets" / "thai" / ... |
# python imports
import sys
import os
import os.path
sys.path.append(os.getcwd())
import copy
import math
import time
import string
import random
from Tkinter import *
# tool imports
import SPADE
sys.path.append('./Tools/DetectDomains')
import DetectDomains
sys.path.append('./Tools/Selection')
import SystemSelectionDia... |
class Test:
x = 0
y = 0
z = 0
def print_x(self):
print(self.x)
def print_y(self):
print(self.y)
def print_z(self):
print(self.z)
def print_all(self):
self.print_x()
self.print_y()
self.print_z()
var = Test()
var.print_all()
|
class EntityObject:
"""
An auxiliary object that facilitates entity testing and makes the testing code more attractive
The entity object contains entity inside it
"""
_entity = None
""" The entity inside the project """
_entity_class = None
""" The entity class that is used to create ... |
from copy import deepcopy
import graphene
from django.core.exceptions import FieldDoesNotExist
from django.db.models import AutoField, CharField, ForeignKey, Model, TextField
from graphene_django.converter import convert_django_field
from ..fields import ModelID
from . import required as feature_required
def update... |
import math
import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
import torch.nn.functional as F
model_urls = {
"resnet18": "https://download.pytorch.org/models/resnet18-5c106cde.pth",
"resnet34": "https://download.py... |
# Copyright 2020-2021 Robert Schroll
# This file is part of RMfuse and is distributed under the MIT license.
import argparse
from collections import defaultdict
import errno
import io
import logging
import os
import pkg_resources
import platform
import socket
import stat
import sys
import bidict
import trio
from rmc... |
"""
* Copyright (c) 2018 Anthony Beaucamp.
*
* 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 purpose,
* inc... |
#=========================================================================
# directions.py
#=========================================================================
# Direction definitions for meshnet.
#
# Author : Cheng Tan, Yanghui Ou
# Date : Mar 10, 2019
#--------------------------------------------------------... |
import tkinter as Tk
class NavigationBar(Tk.Frame):
def __init__(self, parent):
Tk.Frame.__init__(self, parent)
self.parent = parent
def make_navbar(self):
home_page_button = Tk.Button(self, text="Homepage", command=self.parent.MainWindow.display_homepage)
graphs_button = Tk.B... |
import tensorflow as tf
from sleap.nn.data.grouping import group_examples, group_examples_iter
class DummyTfVal(object):
def __init__(self, val):
self._val = val
def numpy(self):
return self._val
def make_examples():
examples = []
def add_example(video_ind, frame_ind, x):
e... |
# Copyright (c) Facebook, Inc. and its affiliates.
import dataclasses
import logging
from collections import abc
from typing import Any
from pixellib.torchbackend.instance.utils.registry import _convert_target_to_string, locate
__all__ = ["dump_dataclass", "instantiate"]
def dump_dataclass(obj: Any):
"""
Du... |
import numpy as np
from NLG.models.RegressionModel import RegressionModel
def override(f): return f
class LinearModel(RegressionModel):
""" Simple linear approxiamation model """
@override
def __init__(self, input_dim, n_action):
self.W = np.random.randn(input_dim, n_action) / np.sqrt(input_di... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
import cmd
from psl_class import ProSafeLinux
class NetgearCMD(cmd.Cmd): # {{{
switch = ProSafeLinux()
selectedswitch = {}
discovereddata = {}
def __splitLine(self,argumentcount,line): # {{{
splitline = line.split()
if len(splitline) > argum... |
from django.apps import AppConfig
class EmploymentAgentConfig(AppConfig):
name = 'employment_agent'
|
import discord
from discord.ext import commands
import keep_alive
import sys, traceback
def get_prefix(bot, message):
# Notice how you can use spaces in prefixes. Try to keep them simple though.
prefixes = ['§']
# Check to see if we are outside of a guild. e.g DM's etc.
if not message.guild:
... |
#!/usr/bin/env python3
# -*- encoding=utf-8 -*-
# description:
# author:jack
# create_time: 2018/9/17
class BasePlayerInfoContent(object):
def __init__(self):
self. data = {}
def get_data(self):
return self.data
if __name__ == '__main__':
pass |
"""
Edit:
2013-12-24 added line-ending splitting
2013-12-05 added begin/end offsets for conceptminer2
2013-11-26 added option for conceptminer2
"""
import argparse
import logging
import logging.config
from typing import List
from pytakes import Document, Dictionary, Output
from pytakes import MinerCollectio... |
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 Martin Glück. All rights reserved
# Langstrasse 4, A--2244 Spannberg, Austria. martin@mangari.org
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanze... |
#!/Users/amitani/Library/PyPy/pypy3.6-v7.3.0-osx64/bin/pypy3
import sys
input = sys.stdin.readline
# Generated by 2.2.0 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
N, Q = map(int, input().split())
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import os
curdir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ["SECRET_KEY"]
MAX_CONTENT_LENGTH = int(os.getenv("MAX_CONTENT_LENGTH", 5 * 1024 * 1024))
SQLALCHEMY_DATABASE_URI = os.getenv(
"DATABASE_URI",
"sqlite:///" + os.path.join(curdir, "db.... |
#! /usr/bin/env python
import cv2
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
ret, frame = cap.read()
if not ret:
continue
cv2.imshow('Capture Image', frame)
key_input = cv2.waitKey(1) & 0xFF
if key_input == ord('... |
import cv2
import numpy as np
cam = cv2.VideoCapture(0)
while True:
success, frame = cam.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_green = np.array([0, 100, 50])
upper_green = np.array([50, 220, 255])
mask = cv2.inRange(hsv, lower_green, upper_green)
res = ... |
from django.apps import AppConfig
class ProfileuserConfig(AppConfig):
name = 'profileuser'
|
import os
import shutil
from typing import Any, Iterable, Optional, Tuple
import packaging.version
import pkg_resources
from req_compile import utils
from req_compile.utils import filter_req, reduce_requirements
class RequirementContainer(object):
"""A container for a list of requirements"""
def __init__(s... |
# Approach:
# Just like Buy And Sell Stock 1, but here we keep track of two transactions.
# transaction1 --> minimum price at which stock1 bought
# profit1 --> best profit we can get for transaction1
# transaction2 --> minimum price at which stock2 bought, we subtract profit1 because we already have that money earned t... |
__author__ = 'Peris based on Quinn\'s scripts'
#!/usr/bin/env python
#coding: utf-8
import argparse
from subprocess import call
import os
import shutil
import glob
from Bio import SeqIO
import sys
import re #to do regular expressions
from numpy import * #to do the transposition
import numpy as np
import csv
import ra... |
import abc
from timeit import default_timer as timer
from copy import deepcopy
class Algorithm:
def __init__(self, inst, solution_class):
self.inst = inst
self.o_inst = deepcopy(inst)
self.sol = solution_class(inst.size)
def run(self):
start = timer()
self.solve(self.s... |
import torch
from torch import nn
from torch.nn import functional as F
from fvcore.nn import smooth_l1_loss
from detectron2.config import configurable
from detectron2.layers import Linear, ShapeSpec, batched_nms, cat
from detectron2.modeling.roi_heads import FastRCNNOutputLayers
from detectron2.modeling.roi_heads.fast... |
import sys
import time
import threading
from Comedy import Comedy
from Communication import CommunicationModule
from AudienceAnalyser import AudienceAnalyser
from datetime import datetime
from datetime import timedelta
from FileLogger import FileLogger
# audience size
expectedPeople = 45
# wait time for a respons... |
# Generated by Django 3.2.3 on 2021-06-01 21:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bug', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='bugmodel',
name='status',
fie... |
#!/usr/bin/env python
"""Some corpus statistics"""
import random
import litcorpt
corpusdb = litcorpt.corpus_load()
corpus = litcorpt.corpus(corpusdb)
# Naive counting
corpus_documents = len(corpus)
# Expected: 5222 (in version 0.0.6)
corpus_words = sum(True for document in corpus for word in document.split())
# E... |
#!/usr/bin/env python3
import argparse
import gmpy2
from gmpy2 import mpz
import icu
import os
import re
import sys
byte_order = 'little' # 'little' / 'big'
parser = argparse.ArgumentParser(description="Tuenti Challenge 2020 - Problem 12")
args = parser.parse_args()
contents_m1 = open('plaintext1.txt', 'rb').read()... |
# Space: O(1)
# Time: O(n)
class Solution:
def longestOnes(self, nums, k):
length = len(nums)
if length == 0: return 0
if length == 1: return 1 if k >= 1 else 0
fast, slow, res, count = 0, 0, 0, k
while fast < length:
if nums[fast] == 1:
fast += ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import baseline.Utils.utils as utils
import logging
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class AttConvLSTM(nn.Module):
def __init__(self, opts, feats_channels, feats_dim, n_layers=2,
hidden_dim=[64,16], kern... |
from cms.models.pluginmodel import CMSPlugin
from cms.models.pagemodel import Site
from django.db import models
from django.db.models.query_utils import Q
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from easy_thumbnails.fields import ThumbnailerImageField
from easy_th... |
from sys import argv
import re
# Infinity cost constant
INFINITY = 99999
graph = []
# Open the file again
file = open(argv[1], "r")
# Constants for file manipulation
greatest_node = -1
first_line = True
origin = 0
destiny = 0
for line in file:
# Reading only lines there are not comments
if not re.match("//", ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ******************************************************************************
# Argon Design Ltd. Project P9000 Argon
# (c) Copyright 2017 Argon Design Ltd. All rights reserved.
#
# Module : sjb_word_model
# Author : Steve Barlow
# $Id: create_sentence.py 18332 2017-06-1... |
from web_framework import *
def main():
server = HttpServer("webroot", "/index.html", "api")
server.start()
if __name__ == '__main__':
main()
|
from typing import List, Iterable, Union
import os
import pem
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ed25519, ed448, rsa, ec, dsa
from cryptography.hazmat.primitives.serialization import (
load_der_private_key,
load_pem_private_key,
)
from cryptography.hazmat.backen... |
from django.db import models
from django.test.testcases import TestCase
from wicked_historian.models import BaseEditHistory
from wicked_historian.utils import (
FieldDescription,
ObsoleteFieldDescription,
ReverseForeignKeyRelation,
generate_history_class,
)
from testapp.models import Book
class Gene... |
#pylint: disable=C0103,R0903
from ansi.colour.base import Graphic
# ECMA-048 standard names
reset = Graphic('0')
bold = Graphic('1')
faint = Graphic('2')
italic = Graphic('3')
underline = Graphic('4')
blink_slow = Graphic('5')
blink = Graphic('6')
n... |
def insertSort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i-1
while j >=0 and val < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = val
arr = [67, 12, 1, 6, 9]
insertSort(arr)
print(arr) |
## import modules
import pysam
import pandas as pd
import numpy as np
import re
import os
import sys
import gffpandas.gffpandas as gffpd
from Bio import SeqIO
import logging
pd.options.mode.chained_assignment = None # default='warn', this is used to remove warning from pandas chain assignment
np.seterr(divide = 'igno... |
import os
import json
import io
import kafka
import logging
import avro.io
from cassandra_db import Cassandra
logging.basicConfig(level=logging.INFO)
def read_data(msg: str, schema: dict):
bytes_reader = io.BytesIO(msg.value)
decoder = avro.io.BinaryDecoder(bytes_reader)
reader = avro.io.DatumReader(sche... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.