content stringlengths 5 1.05M |
|---|
from dataclasses import dataclass
from enum import Enum
@dataclass(frozen=True)
class Meta:
reporter: str
from_domain: str
dkim_domain: str
spf_domain: str
class Disposition(Enum):
NONE_VALUE = "none"
QUARANTINE = "quarantine"
REJECT = "reject"
@dataclass(frozen=True)
class DmarcResult... |
from pathlib import Path
import sys
import logging
import pytest
from germanetpy.germanet import Germanet
import numpy as np
from lxml import etree as ET
from germanetpy.synset import ConRel
logger = logging.getLogger('logging_test_synset')
d = str(Path(__file__).parent.parent) + "/data"
try:
germanet_data = Germa... |
#! /usr/bin/python
import unittest
import application.bootstrap
from application.models.IsgGurbaniDb import IsgGurbaniDb
class test_IsgGurbaniDb(unittest.TestCase):
_object = None
def setUp(self):
self._object = IsgGurbaniDb(application.bootstrap.config)
def test_first_letter_search(self):
... |
"""
Copyright 2019 Brain Electrophysiology Laboratory Company LLC
Licensed under the ApacheLicense, Version 2.0(the "License");
you may not use this module 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 ... |
#!/usr/bin/python
# -*- coding: latin-1 -*-
import csv
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse, FormRequest
from scrapy.utils.url import urljoin_rfc
from scrapy.utils.response import get_base_url
from product_spiders.it... |
#!/usr/bin/env python3
"""
Python 3 examples using Numbers
Author: Miguel Rentes
https://github.com/rentes/python3-code-snippets/blob/master/core_datatypes/numbers/numbers.py
Python version: 3.7.2
"""
result = 123 + 456 # Integer Addition
print(result) # Result: 579
print(type(result)) # result is an ob... |
# Copyright (c) 2017 Huawei Technologies Co., Ltd.
# 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
#
# ... |
import angr
from angr.sim_type import SimTypeString
class strcpy(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, dst, src):
self.argument_types = {0: self.ty_ptr(SimTypeString()),
1: self.ty_ptr(SimTypeString())}
self.return_type = self.ty_ptr(... |
#!/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.
r"""
References
.. [Zhe2019hogp]
S. Zhe, W. Xing, and R. M. Kirby. Scalable high-order gaussian process regression... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
import os
import sys
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
# -- Load Single-Sourced Config --------------- --- -- -
path = Path(__file__, '../../config.py').resolve()
spec = s... |
from functools import wraps
import numpy as np
def _extract_from_singleton_iterable(inputs):
if len(inputs) == 1:
return inputs[0]
return tuple(inputs)
def _get_random_row_idxes(num_rows, subsampling_scheme, random_state):
if subsampling_scheme is None:
return range(num_rows)
elif i... |
import json
import random
import redis
import time
LIST_KEY = "jobs"
r = redis.Redis(decode_responses = True)
while True:
print("Checking for jobs...")
pipeline = r.pipeline()
pipeline.brpop(LIST_KEY, timeout = 5)
pipeline.llen(LIST_KEY)
results = pipeline.execute()
next_job = results[0... |
while True:
c, m = map(int, input().split())
if c == m == 0:
break
ans = c + m
ans = str(ans)
ans = ans.replace("0", "")
print(int(ans)) |
# All imports needed to run the loading functions
# import ...
from slogger import slogger
import os
# Add any functions you need to load the required data here.
# These could be functions that pull lists of static files
# from the app repo, or from S3, or database queries or whatever.
def get_menu_options():
"""... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
def ClassifierSerializer(o):
if isinstance(o, Classifier):
return o.name
return o
class Classifier(models.Model):
name = models.CharField(max_length=255, primary_key=True)
class Meta:
verbose_name = _... |
import pdeapp
import numpy as np
#def gencode(app):
param = np.array([1.0]);
xdg = np.array([0.0, 0.0]);
udg = np.array([2.0, 2.0, 2.0]);
odg = np.array([0.0]);
wdg = np.array([0.0]);
uinf = np.array([0.0]);
time = np.array([0.0]);
print(pdeapp.flux(xdg, udg, odg, wdg, uinf, param, time))
#Flux = getattr(pdeapp, ... |
import numpy as np
from copy import deepcopy
class batch_provider:
def __init__(self, data, batchsize, num_negSamples = 2, seed = 1231245):
'''
Helper class to provide data in batches with negative examples.
data: Training data triples
batchsize: size of the mini-batches
nu... |
# 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 ... |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
from boardfarm import lib
from boardfarm.devices import prompt
from boardfarm.tests import rootfs_boot
class Sysupgrade(rootfs_boot.RootFSBootTest):
... |
import os
import numpy as np
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
def create_directory(directory):
for i in range(len(directory.split('/'))):
if directory.split('/')[i] != '':
sub_dic ='/'.join(directory.split('/')[:(i+1)])
if not os.path.exists(sub_dic)... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... |
from django.db import models
from django.contrib.auth.models import User
class Address(models.Model):
address_string = models.CharField(max_length = 200, verbose_name = 'Адрес')
phone = models.CharField(max_length = 30, verbose_name = 'Телефон')
email = models.CharField(max_length = 30, verbose_name = 'email адрес')... |
import classla
class NER_classla():
def __init__(self):
classla.download('sr')
self.nlp = classla.Pipeline('sr')
def perform_NER(self, text):
doc = self.nlp(text)
result = []
for ent in doc.to_dict()[0][0]:
result.append({'text': ent["text"], "NER": ent["ne... |
# Escrever um programa que leia 20 elementos numéricos inteiros negativos em uma matriz A do tipo vetor. Construir uma matriz B de mesmo tipo e dimensão, em que cada elemento deve ser o valor positivo do elemento correspondente da matriz A. Desta forma, se em A[1] estiver armazenado o elemento -3, deve estar em B[1] o... |
from __future__ import absolute_import, division, print_function
import os
import matplotlib.pyplot as plt
from vivarium.core.composition import set_axes
from vivarium.library.dict_utils import get_value_from_path
def plot_diauxic_shift(timeseries, settings={}, out_dir='out'):
external_path = settings.get('ext... |
# -*- coding: utf-8 -*-
"""
database paging services module.
"""
from pyrin.application.services import get_component
from pyrin.database.paging import DatabasePagingPackage
def extract_paging_params(values):
"""
extracts paging parameters from given dict and returns them as a new dict.
the values will ... |
import datetime
import arrow
from typing import List
def is_leap_year(years: int):
"""
if year is a leap year
"""
assert isinstance(years, int), "Integer required."
if ((years % 4 == 0 and years % 100 != 0) or (years % 400 == 0)):
days_sum = 366
return days_sum
else:
... |
from django import forms
from django.core.validators import RegexValidator
# from phonenumber_field.formfields import PhoneNumberField
SHARING_FREQUENCY_CHOICES = [
("one_time", "One-Time Collection"),
("bene_action", "Only when beneficiaries take a specific action"),
("daily", "Data is shared with third-... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import json
import sys
def main():
if (len(sys.argv) < 2) or sys.argv[1] == "--help":
print(
""""Usage: join_scripts.py JSON_FILE1...
Example:
join_scripts.py script1.json script2.json > joined_file.json
"""
)
sys.exit(1)
... |
# Generated by Django 2.2.6 on 2021-01-07 07:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('clientes', '0002_venda_nfe_emitida'),
]
operations = [
migrations.RemoveField(
model_name='vend... |
import torch
from tqc.functions import quantile_huber_loss_f
from tqc import DEVICE
class Trainer(object):
def __init__(
self,
*,
actor,
critic,
critic_target,
discount,
tau,
top_quantiles_to_drop,
target_... |
#-*-coding:utf-8-*-
# date:2020-03-02
# Author: X.li
# function: inference & eval CenterNet only support resnet backbone
import os
import glob
import cv2
import numpy as np
import time
import shutil
import torch
import json
import matplotlib.pyplot as plt
from data_iterator import LoadImagesAndLabels
from models.decod... |
"""
评估指标模块
"""
import numpy as np
import abc
from matrixslow.core import Node
class Metrics(Node):
"""
评估指标算子抽象基类
"""
def __init__(self, *parents, **kargs):
# 默认情况下,metrics节点不需要保存
kargs['need_save'] = kargs.get('nees_save', False)
super().__init__(*parents, *... |
#!/usr/bin/env python3
#
# pushbullet-notify
#
# (c) 2016 Daniel Jankowski
import os
import json
import argparse
import urllib.parse
import urllib.request
CONFIG_PATH = '~/.pushbullet-notify.conf'
def send_push(title, message, access_token, iden):
# Do this for every device to inform mutliple devices
for ... |
import pyserial
import time
import paho.mqtt.client as mqtt
import json
import uuid
import smbus
import math
from datetime import datetime
#opening serial port
ser=serial.Serial('/dev/ttyACM0')
#Set the variables for connecting to the iot service
broker = ""
deviceId="arduino" #you can give the address as default al... |
import json
import os
import logging
import platform
import subprocess
import sys
import time
from urllib import quote
from urlparse import urlparse
from assemblyline.al.common.service_utils import get_merged_svc_config
from assemblyline.al.common.transport import ftp, local, http
from assemblyline.common.importing i... |
from types import FunctionType
from typing import (
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
cast,
)
from graphql import is_named_type, value_from_ast_untyped
from graphql.execution.values import get_argument_values
from graphql.language import Directi... |
# -*- coding: utf-8 -*-
import pytest
from django.test import override_settings
from shuup.admin.views.wizard import WizardView
from shuup.testing import factories
from shuup.testing.utils import apply_request_middleware
@pytest.mark.django_db
def test_wizard_pane(rf, admin_user, settings):
with override_settings... |
import numpy as np
import scipy.stats as st
import scipy.special as scps
from scipy.optimize import minimize
from functools import partial
import utils
import random
from math import factorial
class MertonPricer():
"""
European option Merton pricer
"""
def __init__(self):
#Parameters
... |
###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... |
from direct.distributed import DistributedObject
class HolidayManager(DistributedObject.DistributedObject):
__module__ = __name__
#+++ okay decompyling
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import operator
import uuid
from functools import reduce
from itertools import chain
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.models import ADDITION, CHANGE, LogEntry
from django.contrib.auth.decorat... |
"""Read and Write STL Binary and ASCII Files."""
#
# import struct
#
#
# def load(inputfile):
# pass
#
#
# def dump(outputfile):
# struct.pack('<I', bboxe_count * 12)
# for bbox in bboxes:
# minx = bbox.Min.X
# miny = bbox.Min.Y
# minz = bbox.Min.Z
# maxx = bbox.Max.X
# ... |
import re
import typing
from docstring import sum_numbers
def test_sum_numbers():
doc = f"\n{sum_numbers.__doc__.strip()}"
# for some lines allow variable content after colon
for line in (
r"Sums numbers",
r" :param numbers: \S.*?\n",
r" :type numbers: list",
r" ... |
from flask import Flask,render_template
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
app= Flask(__name__)
app.config['SECRET_KEY']='mysecretkey'
class InfoForm(FlaskForm):
breed=StringField("What breed are you?")
submit= SubmitField('Submit')
@app.route('/',methods=['GET','... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class FullTwoThinningNet(nn.Module):
def __init__(self, n, max_threshold, inner1_size=None, inner2_size=None, hidden_size=64,
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")):
super(FullTwoThinningNet,... |
MenuBackground = 'phase_3/maps/loading_bg_clouds.jpg'
GameLogo = 'phase_3/maps/toontown-logo.png'
GuiModel = loader.loadModel('phase_3/models/gui/pick_a_toon_gui')
Settings_Open = 'phase_3/audio/sfx/panorama_settings_slide_in_01.ogg'
Settings_Close = 'phase_3/audio/sfx/panorama_settings_slide_out_01.ogg' |
"""
Utilities for working with DynamoDB.
- :func:`.marshall`
- :func:`.unmarshal`
This module contains some helpers that make working with the
Amazon DynamoDB API a little less painful. Data is encoded as
`AttributeValue`_ structures in the JSON payloads and this module
defines functions that will handle the transco... |
# -*- coding: utf-8 -*-
"""
MQTTクライアントの基底オブジェクトを提供する。
paho-mqttパッケージを使用しているため、利用する場合は
インストールが必要となる。
"""
import os
import json
import yaml
import paho.mqtt.client as mqtt
class BaseClient:
"""
MQTTクライアント基底クラス。
本クラスはpublisher、subscriber両方の機能を内包しているため、
どちらかの機能に特化したサブクラスを作成することを推奨する。
"""
def __ini... |
# Type of the value
x = 7
print('x is {}'.format(x))
print(type(x))
# String Type
x = 'seven'.upper()
print('x is {}'.format(x))
print(type(x))
## F -strings
a = 8
b = 9
x = f'seven {a} {b}'
print('x is {}'.format(x))
print(type(x))
### OR
x = 'seven {} {}'.format(8,9)
print('x is {}'.format(x))
print(type(x))
... |
from sys import exit, argv
from cs50 import SQL
import csv
# check for valadity of command line arguments
if len(argv) != 2:
print("usage: import.py characters.csv")
exit(1)
name = []
# initiate connection with database students.db
db = SQL("sqlite:///students.db")
# open the csv file provided at commandline... |
# -*- coding: utf-8 -*-
from simmate.database.base_data_types import table_column, DatabaseTable
from django.apps import apps as django_apps
from prefect import Client
from prefect.utilities.graphql import with_args
import plotly.graph_objects as plotly_go
class EvolutionarySearch(DatabaseTable):
"""
This... |
from all_imports import *
hashtag = '#100daysofcodechallenge'
tweetnumber = 10
tweets = tweepy.Cursor(api.search, hashtag).items(tweetnumber)
def searchBot():
for tweet in tweets:
try:
tweet.retweet()
api.create_favorite(tweet.id)
api.update_status('@' + tweet.entities... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-03 13:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('unlocode', '0008_locchangetags'),
]
operations = [
... |
from itertools import permutations
def is_valid(permutation):
# Loes woont niet op de bovenste verdieping.
# Niels woont niet op de bovenste verdieping.
if permutation[4] == 'L' or permutation[4] == 'N':
return False
# Marja woont niet op de begane grond.
# Niels woont niet op de begane g... |
import pickle
import numpy as np
from collections import Counter
# load pubmed paper data that is also in S2
with open('data/pubmed_s2_data.pickle', 'rb') as f:
pubmed_s2_data = pickle.load(f)
with open('data/pubmed_s2_id_maps.pickle', 'rb') as f:
s2id_to_pmid, pmid_to_s2id = pickle.load(f)
# import mesh
# ... |
# Time: O(n)
# Space: O(n)
# 838 weekly contest 85 5/19/2018
# There are N dominoes in a line, and we place each domino vertically upright.
#
# In the beginning,
# we simultaneously push some of the dominoes either to the left or
# to the right.
#
# After each second,
# each domino that is falling to the left pushes... |
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class PostPagination(PageNumberPagination):
page_size = 50 # default size if no size parameter passed
page_size_query_param = 'size'
page_query_param = 'page'
def get_paginated_response(self... |
# (c) 2019 Francis Taylor
# This code is licensed under the MIT license (see LICENSE for details)
# This code is provided as a guide for learning. Please do not copy it blindly.
import math
# cos(x) - x^3 = 0
# x_(n+1) = x_n - f(x_n)/[dy/dx]
# abs(x_n) < 1.0e-12
x_old = 0
x_new = 1
def newton(x_old):
'''This f... |
from django.contrib import admin
from django.urls import path,include
from .views import ReportFormView
urlpatterns = [
path('', ReportFormView.as_view(), name='report'),
]
|
from django.conf import settings
from django.contrib import auth
from django.contrib.sites.models import Site
from django.shortcuts import redirect
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponseForbidden
from raygun4py.middleware.django import Provider
class HerokuDe... |
# Generated by Django 2.1.1 on 2018-09-16 07:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('lw2', '0016_auto_20180916_0310'),
]
operations = [
migrations.DeleteModel(... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
"""
Copyright (c) 2022 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... |
#!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# 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 ag... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 21 11:37:29 2022
@author: debangshu
"""
import requests
from bs4 import BeautifulSoup
def format_title(title):
title=title.lower()
title_tokens=title.split(' ')
title='-'.join(title_tokens)
return title
def find_movie(title):
try:
... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and pyth... |
import numpy as np
import socket
from npsocket_sn import SocketNumpyArray
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenario
from math import *
import time
class Scenario(BaseScenario):
def __init__(self):
self.sock_sender = SocketNumpyArray()
self.sock... |
import os
import yaml
from ddb.utils.process import run
class DockerUtils:
"""
A set of tools to manipulate docker using docker and docker-compose system commands
"""
@staticmethod
def service_up(name: str = None):
"""
Execute docker-compose up -d
:param name: the name of... |
# Copyright 2013-2018 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 RClusterprofiler(RPackage):
"""This package implements methods to analyze and visualize fu... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# print("something")
# In[2]:
print("something")
# # Heading 1
# # Heading 2
# # Heading 3
# In[6]:
a=5
print(a)
# In[7]:
b=2
print(B*B*B)
# In[8]:
print(b*b*b)
# In[ ]:
|
#----- Importar biblioteca do Mysql
import MySQLdb
from model.pessoa import Pessoa
class PessoaDao:
#----- Configurar a conexão
conexao = MySQLdb.connect(host='localhost', database='aulabd', user='root', passwd='')
#----- Salva o cursor da conexão em uma variável
cursor = conexao.cursor()
def ... |
# Copyright (c) 2011-2013, Alexander Kulakov
#
# 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, publ... |
__all__ = ['Degrees', 'Hours', 'Rad', 'arcsin', 'arccos', 'arctan', 'pi']
import numpy as np
from functools import lru_cache
from pylightcurve.errors import *
def _break_seconds(seconds):
seconds = float(seconds)
seconds_int = int(seconds)
seconds_dec = int(str(seconds).split('.')[1])
a = int(sec... |
#!/usr/bin/env python
"""
Subrequests to do things like range requests, content negotiation checks,
and validation.
This is the base class for all subrequests.
"""
from abc import ABCMeta, abstractmethod
from configparser import SectionProxy
from typing import List, Tuple, Type, Union, TYPE_CHECKING
from redbot.res... |
input1 = 0xe
input2 = 0x21
while (input1 <=0x9886):
input2+=0x1
input1+=0x41
print input2
|
#!/usr/bin/env python
import os
import sys
import argparse
import time
import zipfile
from subprocess import Popen, PIPE, STDOUT
from pdfminer.high_level import extract_text
from haystack import Finder
from haystack.indexing.cleaning import clean_wiki_text
from haystack.indexing.utils import convert_files_to_dicts, f... |
import pygame # Required for rendering the screen
class Renderer:
"""
Handles the rendering actions of the game the free up Game for logic
"""
def __init__(self, screenSize):
"""
Initializes the render class
"""
self.backgroundColor = 0, 0, 0
self.setScreen(screenSize)
def render(self, map, entities)... |
from PIL import Image
import pytesseract
im = Image.open('myimage.jpg')
print(pytesseract.image_to_string(im))
|
import numpy as np
def prof_weight_compute(list_probe_filenames,start_layer,last_layer,y_train2):
"""
Key function that computes the per sample weights based on probe classifier confidences from various layers. It averages the probe
confidences of the layers.
Parmeters:
list_probe_filenames (List of strings):... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pyglet
from .data import *
class Resource(object):
def init(self):
pyglet.resource.path = data.get_subdirs('resources')
self.load_fonts(data.get_all_list(['FONTS']))
def load_fonts(self, fonts):
if fonts is not None:
for font in fonts:
... |
# Generated by Django 2.1.5 on 2019-01-25 17:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0007_choice_feature_text'),
]
operations = [
migrations.CreateModel(
name='ShoppingCart',
fields=[
... |
'''Amino acid usage: Reads and Clones
1/ Sequence logo for each length
2/ ttests: each length, each position (or pair of positions):
usage of the specific aa (or aas) in group1 cmp with group2
'''
|
from email.policy import default
from lib2to3.pgen2 import grammar
from lark import Lark,Token
from lark.tree import pydot__tree_to_png
from lark import Transformer
from numpy import isin
class transforma_lista(Transformer):
def start(self,items):
output = {}
output["len"] = len(items[1])
output['mostfre... |
# Advent of Code 2020
# Day 5
from boarding_pass import BoardingPass
from pathlib import Path
# input
with open(Path(__file__).parent / "input.txt") as f:
inp = BoardingPass.parse_bpasses(f.read())
# part 1
# Find the highest seat ID.
def part_1():
return max(b_pass.id for b_pass in inp)
print(f"Part 1: ... |
# This script cleans, compacts and groups DNS records for Alexa1m domains by name and date.
#
# Command to run this script on the CTIT cluster:
# $ spark-submit --master yarn --deploy-mode cluster --num-executors 300 src/data/spark/restructure_alexa1m_data.py
from pyspark import SparkContext
from pyspark.sql import SQ... |
#!/usr/bin/env python3
from ..bit import Bit
from ..pin import Pin
from ..ic import IC
from .andic import AndIC
from .notic import NotIC
class NandIC(IC):
def __init__(self):
super().__init__(2, 1)
self.andgate = AndIC()
self.notgate = NotIC()
def run()
|
from flask import request, Response
from threading import Thread
from models import Node, Pod
from utils import debug
import clustertools
import apiserver
import traceback
import requests
import random
import params
import time
import sys
EXCLUDED_HEADERS = ['content-encoding', 'content-length', 'transfer-encoding',... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class TextLoss(nn.Module):
def __init__(self):
super().__init__()
@staticmethod
def ohem(predict, target, train_mask, negative_ratio=3.):
pos = (target * train_mask).byte()
neg = ((1 - target) * train_mask).byte()... |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it trains on the PubMed dataset.
The default hyperparameters give a good quality representation without grid search.
"""
parser = argparse.ArgumentParser(description = "Run .")
parser.add_argu... |
from behave import fixture
@fixture
def init_cluster(context):
context.execute_steps(u"""
Given the database is not running
And a working directory of the test as '/tmp/concourse_cluster'
And the user runs command "rm -rf ~/gpAdminLogs/gpinitsystem*"
And a cluster is created with mirro... |
#!/usr/bin/env python3
#
# Copyright 2019 ROBOTIS 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 applicabl... |
import os.path
# Paths and dataset folder structure
DATASET_PATH = os.path.join(os.pardir, 'moving-sprites-dataset', 'dataset')
DATASET_TRAINING_PATH = os.path.join(DATASET_PATH, 'training')
DATASET_VALIDATION_PATH = os.path.join(DATASET_PATH, 'validation')
DATASET_TEST_PATH = os.path.join(DATASET_PATH, 'test')
DATAS... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0023_alter_page_revision_on_delete_behaviour'),
]
operations = [
migrations.Create... |
#!/usr/bin/env python
#
# A python package for interpreting METAR and SPECI weather reports.
#
# US conventions for METAR/SPECI reports are described in chapter 12 of
# the Federal Meteorological Handbook No.1. (FMH-1 1995),issued by NOAA.
# See <http://metar.noaa.gov/>
#
# International conventions for the ME... |
#!/usr/bin/env python3
"""
FastQC - A quality control analysis tool for high throughput sequencing data
https://github.com/s-andrews/FastQC
"""
import os
import re
from paleomix.common.command import AtomicCmd, InputFile, OutputFile
from paleomix.common.versions import Requirement
from paleomix.node import CommandNod... |
ResponseSchema = {
'$schema': 'http://json-schema.org/draft-07/schema#',
'type': 'object',
'properties': {
'status': {
'type': 'integer',
'minimum': 100,
'maximum': 699
}
},
'required': ['status']
}
|
# Generated by Django 2.1 on 2018-08-23 22:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('callapi', '0002_auto_20180820_2123'),
]
operations = [
migrations.AddField(
model_name='callrecord',
name='source',
... |
import sqlalchemy
from sqlalchemy import create_engine,text
import os
from sqlalchemy.orm import Session,sessionmaker
# SQL Alchemy Version Check
print(sqlalchemy.__version__) # 1.4.27
# SQL Alchmey Engine Oluştur ve İlgili Veri Tabanına Bağla
# print(os.getcwd())
dbUrl = "sqlite+pysqlite:///" + os.getcwd() + "\\... |
import sqlite3
import requests
import time
import logging
import random
from flask import Flask, jsonify
import elasticapm
from elasticapm.contrib.flask import ElasticAPM
from elasticapm.handlers.logging import LoggingHandler
names = ['ruan', 'stefan', 'philip', 'norman',
'frank', 'pete', 'johnny', 'peter', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.