text string | size int64 | token_count int64 |
|---|---|---|
"""
ceph_insights - command ``ceph insights``
=========================================
"""
import json
import re
from .. import CommandParser, parser
from insights.specs import Specs
@parser(Specs.ceph_insights)
class CephInsights(CommandParser):
"""
Parse the output of the ``ceph insights`` command.
At... | 3,287 | 961 |
from .q_learner import QLearner
from .coma_learner import COMALearner
from .es_learner import ESLearner
REGISTRY = {}
REGISTRY["q_learner"] = QLearner
REGISTRY["coma_learner"] = COMALearner
REGISTRY["es_learner"] = ESLearner
| 227 | 94 |
# Copyright The IETF Trust 2013-2020, All Rights Reserved
# -*- coding: utf-8 -*-
from email.message import EmailMessage
from textwrap import dedent
from traceback import format_exception, extract_tb
from django.conf import settings
from django.core.management.base import BaseCommand
from ietf.utils.mail import send... | 3,582 | 957 |
from django.urls import path
from.import views
urlpatterns = [
#ex: localhost:8080/app/
path('', views.index, name='index'),
#ex: localhost:8080/app/sumar/n1+n2/
path('sumar/<int:n1>/<int:n2>', views.sumar, name='suma'),
#ex: localhost:8080/app/sumar/n1-n2/
path('restar/<int:n1>/<int:n2>', vie... | 603 | 271 |
# generate dataset : random data in a two-dimensional space
#https://towardsdatascience.com/understanding-k-means-clustering-in-machine-learning-6a6e67336aa1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
#%matplotlib inline
def generate_x():
X = -2 * ... | 688 | 297 |
from .browserenabled import BrowserEnabled as Stere
from .page import Page
__all__ = [
"Stere",
"Page",
]
| 115 | 38 |
from antlr4 import *
from antlr4.error.ErrorListener import ErrorListener
from antlr.SBHasmLexer import SBHasmLexer
from antlr.SBHasmListener import SBHasmListener
from antlr.SBHasmParser import SBHasmParser
class MyErrorListener(ErrorListener):
def __init__(self):
super(MyErrorListener, self).__init__(... | 2,190 | 698 |
consonents = ['sch', 'squ', 'thr', 'qu', 'th', 'sc', 'sh', 'ch', 'st', 'rh']
consonents.extend('bcdfghjklmnpqrstvwxyz')
def prefix(word):
if word[:2] not in ['xr', 'yt']:
for x in consonents:
if word.startswith(x):
return (x, word[len(x):])
return ('', word)
d... | 442 | 176 |
import logging
from tools.EventGeneration import convert_date, generate_random_time, generate_random_node_id
logger = logging.getLogger(__name__.split('.')[-1])
from features.ResponseTypeFeature import ResponseTypeFeature
from features.ReplayTimeSeriesFeature import ReplayTimeSeriesFeature
import tools.Cache as Cach... | 5,315 | 1,500 |
import datetime
import math
import os
import sys
from functools import wraps
from typing import Optional, Tuple
from flee import pflee
from flee.SimulationSettings import SimulationSettings # noqa, pylint: disable=W0611
if os.getenv("FLEE_TYPE_CHECK") is not None and os.environ["FLEE_TYPE_CHECK"].lower() == "true":
... | 13,174 | 3,886 |
import os
import datetime
from json import dumps
from google.cloud import pubsub_v1
from config_speech import config as conf
from google.api_core.exceptions import AlreadyExists
class Pubsub():
def __init__(self):
PROJECT_PATH = "projects/project_name"
TOPIC_NAME = 'topic_name'
self.TOPIC... | 2,211 | 654 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'xml/alert.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... | 2,497 | 801 |
#!/usr/bin/env python
import rospy
import math
from sensor_msgs.msg import LaserScan #import des donnes laser du lidar
import time
from rplidar_ros.srv import *
class Client():
vel=None
angle_est=None
#Init
def __init__(self):
rospy.init_node('client_lidar')
def listen_angle(self):
... | 689 | 229 |
import os
import logging
from unittest import mock
from backee.parser.config_parser import parse_config
class ConfigMixin:
def __get_config_file_contents(self, filename: str):
config_file = os.path.join(
os.path.dirname(__file__), os.pardir, "resources", filename
)
with open(c... | 681 | 201 |
#from utils import ordinal
import re
from urllib.parse import quote as uriquote
import asyncio
from bs4 import BeautifulSoup
import collections
from utils.context import MoreContext
from utils.context import Location
from utils.paginator import Paginator
from utils.units import units
ordinal = lambda n: "%d%s" % (n,"t... | 2,022 | 646 |
[
[float("NaN"), float("NaN"), 73.55631426, 76.45173763],
[float("NaN"), float("NaN"), 71.11031587, 73.6557548],
[float("NaN"), float("NaN"), 11.32891221, 9.80444014],
[float("NaN"), float("NaN"), 10.27812002, 8.15602626],
[float("NaN"), float("NaN"), 21.60703222, 17.9604664],
[float("NaN"), flo... | 647 | 395 |
numbers = [float(num) for num in input().split()]
nums_dict = {}
for el in numbers:
if el not in nums_dict:
nums_dict[el] = 0
nums_dict[el] += 1
[print(f"{el:.1f} - {occurence} times") for el, occurence in nums_dict.items()] | 242 | 101 |
"""
Usage:
main.py domains list
main.py domains add [--body=<request_body>] [--file=<input_file>]
main.py users list [--domain=<domain_name>]
main.py users get [--email=<email>]
main.py users add [--body=<request_body>] [--file=<input_file>]
main.py users update [--email=<email>] [--body=<reque... | 3,021 | 925 |
#!/usr/bin/python3
import unittest
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from python.buildautomat_unit_tests import *
from python.filesystemaccess_unit_tests import *
if __name__ == '__main__':
unittest.main()
| 266 | 91 |
from django.forms import ModelForm, inlineformset_factory, BaseInlineFormSet
from . import models
class AuthorContainerForm(ModelForm):
class Meta:
model = models.AuthorContainer
exclude = ('id',)
class AuthorForm(ModelForm):
class Meta:
model = models.Author
fields = ('first... | 1,790 | 508 |
#
# Copyright (C) 2018 Pico Technology Ltd. See LICENSE file for terms.
#
| 74 | 31 |
from collections import Counter
from math import log
from tqdm import tqdm
import re
from evaluation import evaluateSet
def build_model(train_set):
hmm_model = {i:Counter() for i in 'SBME'}
trans = {'SS':0,
'SB':0,
'BM':0,
'BE':0,
'MM':0,
'ME':0,
... | 6,105 | 2,390 |
# Copyright 2018 Google Inc.
#
# 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 copyright notice,
# this list of conditions and the following disclaimer.
#
#... | 5,770 | 1,812 |
import google.auth
def get_gcreds(scopes = None):
if scopes == None:
scopes = ["https://www.googleapis.com/auth/bigquery"]
return google.auth.default(
scopes = scopes )
| 199 | 67 |
from ConfigSpace import ConfigurationSpace, CategoricalHyperparameter
import time
import warnings
import os
import numpy as np
import pickle as pkl
from sklearn.metrics.scorer import balanced_accuracy_scorer
from solnml.utils.logging_utils import get_logger
from solnml.components.evaluators.base_evaluator import _Base... | 12,312 | 3,839 |
#
# MLDB-1104-input-data-spec.py
# mldb.ai inc, 2015
# This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#
import unittest
import datetime
import random
from mldb import mldb, ResponseException
class InputDataSpecTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls... | 5,830 | 1,797 |
import os.path
from pi3d import *
from pi3d.Buffer import Buffer
from pi3d.Shape import Shape
from pi3d.Texture import Texture
CUBE_PARTS = ['front', 'right', 'top', 'bottom', 'left', 'back']
BOTTOM_INDEX = 3
def loadECfiles(path, fname, suffix='jpg', nobottom=False):
"""Helper for loading environment cube faces.
... | 6,000 | 3,006 |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from .models import Article
from .serializers import ArticleSerializer
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest... | 5,678 | 1,689 |
import random
import time
# Welcome and start
time.sleep(1)
player_name = input('Please enter your player name : ')
time.sleep(1)
print(f'Welcome to hangman game {player_name}')
# main function
def main():
global count
global word
global display
global already_guessed
global leng... | 4,101 | 1,325 |
modules_rules = {
"graphlib": (None, (3, 9)),
"test.support.socket_helper": (None, (3, 9)),
"zoneinfo": (None, (3, 9)),
}
classes_rules = {
"asyncio.BufferedProtocol": (None, (3, 7)),
"asyncio.PidfdChildWatcher": (None, (3, 9)),
"importlib.abc.Traversable": (None, (3, 9)),
"importlib.abc.Tr... | 7,601 | 3,388 |
'''Low-level API working through obscure nvapi.dll.'''
import ctypes
import typing
import sys
import collections
import enum
from .status import NvStatus, NvError, NVAPI_OK
nvapi = ctypes.CDLL('nvapi64.dll' if sys.maxsize > 2**32 else 'nvapi.dll')
_nvapi_QueryInterface = nvapi.nvapi_QueryInterface
_nvapi_QueryInter... | 48,831 | 18,971 |
#!/usr/bin/env python
"""
Generic methods used for verifying/indexing SIPs.
"""
from __future__ import absolute_import
import re
import logging
import tarfile
import hdfs
from lxml import etree
from StringIO import StringIO
# import the Celery app context
#from crawl.celery import app
#from crawl.celery import cfg
... | 5,537 | 1,712 |
from django import forms
from .models import *
class ProfileFormModel(forms.ModelForm):
class Meta:
model = Device_profile
fields = ['device_profile_file']
| 186 | 53 |
# pylint: disable=no-self-use,invalid-name
import numpy
from numpy.testing import assert_almost_equal
import keras.backend as K
from deep_qa.tensors.similarity_functions.dot_product import DotProduct
class TestDotProductSimilarityFunction:
dot_product = DotProduct(name='dot_product')
def test_initialize_weig... | 1,334 | 497 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
He copiado y modificado software ajeno. Gran parte de este script es una
modificación y/o mejora del original, por ello doy los debidos créditos al
autor del software original:
MIT License
Copyright (c) 2016 - 2017 Eduard Nikoleisen
Permission is hereb... | 8,699 | 3,451 |
#!/usr/bin/env python3
import argparse
import gc
import numpy as np
import os
import pandas as pd
import pysam
# Number of SVs to process before resetting pysam (close and re-open file). Avoids a memory leak in pysam.
PYSAM_RESET_INTERVAL = 1000
def get_read_depth(df_subset, bam_file_name, mapq, ref_filename=None)... | 8,566 | 2,986 |
#!/usr/bin/env python
# Copyright 2016-2021 IBM Corp. 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 require... | 16,017 | 5,327 |
from farm.data_handler.processor import Processor
from tokenizers.pre_tokenizers import WhitespaceSplit
from farm.data_handler.samples import (
Sample,
SampleBasket,
)
from farm.data_handler.utils import expand_labels
import ast
import numpy as np
import pandas as pd
class MTLProcessor(Processor):
def __i... | 5,991 | 1,717 |
#!/usr/bin/python
from piece import Piece
from gameNode import GameNode
from knightmovs import *
from functions import *
listPiecesWhite=[]
listPiecesBlack=[]
w1=Piece('Q',[3,1])
w2=Piece('N',[3,2])
w3=Piece('N',[4,2])
w4=Piece('B',[2,3])
listPiecesWhite.append(w1)
listPiecesWhite.append(w2)
listPiecesWhite.append(w... | 611 | 266 |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and both Actors
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRen... | 1,519 | 539 |
# Future
from __future__ import annotations
# Standard Library
from typing import Literal
ImageFormat = Literal["webp", "jpeg", "jpg", "png", "gif"]
| 152 | 47 |
#!/usr/local/anaconda/bin/python
#copyright: Zhenye Jiang, tronsupernova@outlook.com
from random import random
from tkinter import *
from copy import deepcopy
class Boggle():
'''
@param dict F
@param dict T
@param int size
@param int cellWidth
@param array clone
@param list soln
@pa... | 6,920 | 2,340 |
from copy import copy
import functools
import inspect
import sys
import traceback
from . import ansi
from .agent import Agent
def reset_global_handlers():
global HANDLERS
HANDLERS = {
"in" : { },
"out" : { },
}
reset_global_handlers()
def subscribe_to(subs):
def ... | 7,826 | 2,563 |
def bolha_curta(self, lista):
fim = len(lista)
for i in range(fim-1, 0, -1):
trocou = False
for j in range(i):
if lista[j] > lista[j+1]:
lista[j], lista[j+1] = lista[j+1], lista[j]
trocou = True
if trocou== Fal... | 347 | 113 |
# flake8: noqa
# Copyright The PyTorch Lightning team.
#
# 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... | 7,740 | 2,487 |
from bootstrapvz.base import Task
from bootstrapvz.common import phases
from bootstrapvz.common.tasks import grub
class AddVirtualConsoleGrubOutputDevice(Task):
description = 'Adding `tty0\' as output device for grub'
phase = phases.system_modification
successors = [grub.WriteGrubConfig]
@classmethod... | 423 | 131 |
# Copyright 2021 The TensorFlow 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 applicable law or agreed to ... | 12,444 | 3,716 |
import hashlib
import hmac
from satang_pro_signer import preparer
class Signer:
def __init__(self, secret: bytes):
self.secret = secret
def sign(self, obj) -> bytes:
parsed = preparer.Preparer(obj).encode()
msg = bytes(parsed, encoding='utf-8')
try:
# better perf... | 547 | 168 |
W, H = map(int, input().split())
print("4:3" if 4 * H == 3 * W else "16:9")
| 76 | 38 |
# pylint:disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
from django import forms
#-
from .base import compare_template, SimpleTestCase
class DummyForm(forms.Form):
choice1 = forms.ChoiceField(
required=False,
help_text="Optional helper text here")
ch... | 24,976 | 8,968 |
import numpy as np
import numpy.linalg as nl
from utils.general import connMat
a4_to_main = {
'body': np.array([1, 0, 9, 10, 11, 3, 4, 5, 12, 13, 14, 6, 7, 8, 17, 15, 18, 16, 19, 20], dtype=np.int64), # convert to order of openpose
'1_body': np.array([1, 0, 9, 10, 11, 3, 4, 5, 12, 13, 14, 6, 7, 8, 17, 15, 18,... | 7,826 | 4,532 |
from requests import post
from random import randint
from json import loads, dumps
import asyncio,base64,glob,json,math,urllib3,os,pathlib,random,sys,concurrent.futures,time
from tqdm import tqdm
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
urllib3.disable_warnings(urllib3.exceptions.Insecu... | 15,584 | 7,850 |
# -*- coding: utf-8 -*-
"""
Functions to install dependencies for non-standard models (e.g., Centermask2)
and get compatible Detectron2 configs for them.
"""
import sys
import subprocess
try:
from detectron2.config import get_cfg
except ModuleNotFoundError:
print('WARNING: Detectron2 not installed on (virtual?... | 3,201 | 994 |
#!/usr/bin/env python
from preprocess import get_negative_samples, get_positive_samples
from utils import init_spark
from preprocess import get_dataset_df
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit, \
Cr... | 1,870 | 534 |
# -*- coding: utf-8 -*-
import json
class OCSSSearchRunner:
"""
This runner should perform searches from ocss search logfile against elastic
"""
# define search data
search_data = []
def initialize(self, params):
# check given parameter
if "index" in params and type(params["... | 1,302 | 360 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import LiveReload
import json
import sublime
try:
from .Settings import Settings
except ValueError:
from Settings import Settings
def log(msg):
pass
class PluginFactory(type):
"""
Based on example from http://martyalchin.com/2008/jan/10/simple-plugin-f... | 8,574 | 2,291 |
# Generated by Django 3.0.4 on 2020-06-08 22:55
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('team', '0013_auto_20200608_1824'),
]
operations = [
migrations.AlterField(
model_name='profile',
... | 431 | 161 |
# Generated by Django 2.1.5 on 2019-03-22 07:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discussions', '0005_timestamped_discussions_models'),
]
operations = [
migrations.AddField(
model_name='channel',
na... | 408 | 136 |
import itertools
from typing import Mapping, Sequence, Tuple, TypeVar, Union
from exabel_data_sdk.client.api.api_client.entity_api_client import EntityApiClient
from exabel_data_sdk.client.api.data_classes.entity import Entity
from exabel_data_sdk.stubs.exabel.api.data.v1.all_pb2 import (
SearchEntitiesRequest,
... | 8,562 | 2,436 |
import torch as th
from unittest import TestCase
from pro_gan_pytorch import CustomLayers as cL
device = th.device("cuda" if th.cuda.is_available() else "cpu")
class Test_equalized_conv2d(TestCase):
def setUp(self):
self.conv_block = cL._equalized_conv2d(21, 3, k_size=(3, 3), pad=1)
# print th... | 3,808 | 1,366 |
import unittest
from django.test import TestCase
class TestQuestion(unittest.TestCasel):
def test_is_get_score(self, selected_ids):
self.assertNotEqual(all_answers = self.choice_set.filter(is_correct=True).count()
self.assertEqual(selected_correct = self.choice_set.filter(is_correct=True, id__in=s... | 511 | 156 |
"""OverwriteCheck Statement."""
from trnsystor.statement.statement import Statement
class OverwriteCheck(Statement):
"""OverwriteCheck Statement.
A common error in non standard and user written TRNSYS Type routines is
to reserve too little space in the global output array. By default, each
Type is a... | 1,482 | 406 |
import os
from serif.model.relation_mention_model import RelationMentionModel
from serif.theory.enumerated_type import Tense, Modality
# Modified from DogFoodFinderRelationMentionModel
class AIDARelationMentionModel(RelationMentionModel):
'''adds TACRED relations to TACRED entities'''
def __init__(self, mapp... | 3,012 | 910 |
from pathlib import Path
from typing import List, Optional
from jinja2 import Environment, FileSystemLoader, Template
from pydantic import BaseModel as _BaseModel
from ..base import TEMPLATE_DIR
from .base_model import BaseModel, DataModelField
from .custom_root_type import CustomRootType
from .dataclass import DataC... | 1,209 | 383 |
#!/usr/bin/env python3
# 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... | 2,313 | 942 |
import math
import gmpy2
# How many you want to find
MAX_COUNT = 500
K_COUNT = 3.7 # d = 1000 yields ~264
#for parallel C++
K_COST = 4.14 * 1e-11 # d = 5000 takes ~400s
K_FILTER_COST = 1.0 * 1e-9 # d = 5000, sieve = 30M takes 10.3s
def optimal_sieve(d, expected_cost):
non_trivial_a_b = d * 2... | 3,039 | 1,294 |
from django import forms
from django.contrib import messages
from django.db import models
from django.db import transaction
from django.http import HttpResponseRedirect, Http404
from django.utils import timezone
from django.utils.translation import gettext_lazy, pgettext_lazy
from django.views.generic import View
im... | 8,849 | 2,553 |
# Copyright [2021] [Nikolay Veld]
#
# 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... | 3,258 | 1,047 |
import json
import unittest
from copy import deepcopy
from http import HTTPStatus
from unittest.mock import call, patch
from flask import Response as FlaskResponse
from marathon import MarathonApp
from marathon.models.group import MarathonGroup
from marathon.models.task import MarathonTask
from asgard.models.account ... | 19,978 | 5,653 |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
import json
import os
from pytest import fixture
def load_file(fn):
return open(os.path.join("unit_tests", "responses", fn)).read()
@fixture
def test_config_v1():
return {"site": "airbyte-test", "site_api_key": "site_api_key", "start_date": "202... | 1,481 | 552 |
#
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
import unittest
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1_mo... | 3,855 | 1,832 |
a = float(input('digite um numero:'))
b = float(input('digite um numero:'))
c = float(input('digite um numero:'))
if a > b:
if a > c:
ma = a
if b > c:
mi = c
if c > b:
mi = b
if b > a:
if b > c:
ma = b
if a > c:
mi = c
if c > ... | 533 | 192 |
"""
1999- Nineteen Ninty Nine
1888 - Eighteen Eighty Eight
1777 - Seventeen Seventy Seven
1111 - Oneeen Onety One
Not fully huristics
"""
from num2words import num2words
def spell(N):
if N // 1_0000 ==0:
N = divmod(N, 100)
top, bot = N[0], N[1]
result = [ ]
if top == 11:
... | 699 | 268 |
import pandas as pd
import numpy as np
function2idx = {"negative": 0, "ferritin": 1, "gpcr": 2, "p450": 3, "protease": 4}
input_dir = '../data/raw/'
data_dir = '../data/processed/'
max_seq_len = 800
def read_and_concat_data():
df_cysteine = pd.read_csv(input_dir + 'uniprot-cysteine+protease+AND+reviewed_yes.tab... | 3,711 | 1,358 |
def run():
countries = {
'mexico': 122,
'colombia': 49,
'argentina': 43,
'chile': 18,
'peru': 31
}
while True:
try:
country = input(
'¿De que país quieres saber la población?: ').lower()
print(
f'La p... | 509 | 170 |
from django.apps import AppConfig
class AraAraConfig(AppConfig):
name = "Ara_Ara"
| 88 | 32 |
from ahmed-package.functions import printName | 45 | 11 |
from .FindEventsForm import *
from .StockingEventForm import *
from .XlsEventForm import *
| 91 | 28 |
#!/usr/bin/env python3
'''
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 License, or
(at your option) any later version.
This program is distributed in the hope that it will... | 9,034 | 3,314 |
import typing
import re
from .CD_relations import cardinal_relation, inverse_directions
from .regions import Region, region_union
from .expression_walker import PatternWalker
from .expressions import Constant
REFINE_OVERLAPPING = True
class RegionSolver(PatternWalker[Region]):
type_name = 'Region'
def __n... | 3,643 | 1,002 |
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.or... | 4,868 | 1,819 |
import os
import enum
import hashlib
from urllib.parse import urljoin
from flask import url_for, current_app as app
from mcarch.app import db, get_b2bucket
class StoredFile(db.Model):
"""Represents a file stored in some sort of storage medium."""
__tablename__ = 'stored_file'
id = db.Column(db.Integer, p... | 1,955 | 703 |
# Generated by Django 2.2 on 2019-05-09 06:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BusTrip',
fields=[
... | 5,142 | 1,446 |
# Generated by Django 2.2 on 2020-03-08 16:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0005_auto_20200308_1735'),
]
operations = [
migrations.AlterField(
model_name='clue',
name='paragraph1',
... | 1,181 | 354 |
import subprocess
import scipy.io.wavfile as wav
import sys
import numpy as np
# import pyaudio
import time
import wave
import os
from pydub import AudioSegment
import pafy
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_dl import YoutubeDL
dirname = os.path.dirname(os.path.abspath(__file__))
s... | 1,362 | 466 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('cms_pages', '0005_auto_20150829_1516'),
]
operations = [
migrations.AddField(
... | 1,116 | 534 |
from autorop import PwnState, arutil
from pwn import ROP
def puts(state: PwnState) -> PwnState:
"""Leak libc addresses using ``puts``.
This function leaks the libc addresses of ``__libc_start_main`` and ``puts``
using ``puts``, placing them in ``state.leaks``.
Arguments:
state: The current `... | 1,255 | 376 |
# Copyright 2013-2014 Massachusetts Open Cloud Contributors
#
# 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 applicab... | 2,515 | 804 |
import numpy as np
import matplotlib.pyplot as plt
from extract import HurricaneExtraction
#npy_file = './Data/NpyData/LIDIA/20172450002.npz'
npy_file = './Data/NpyData/IRMA/20172531622.npz'
data = HurricaneExtraction.read_extraction_data(npy_file)
data = HurricaneExtraction.normalize_using_physics(data)
for d in ... | 403 | 170 |
from urllib.request import urlopen
import json
import re
url = urlopen("https://raw.githubusercontent.com/Templarian/MaterialDesign/master/meta.json")
meta = [(i['name'], i['codepoint']) for i in json.loads(url.read()) if re.search('^weather-', i['name'])]
print('''---
esphome:
# ...
includes:
- weather_icon_... | 910 | 352 |
from __future__ import print_function
from sklearn.cross_validation import train_test_split
import pandas as pd
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.preprocessing import sequence
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dro... | 3,913 | 1,475 |
import argparse
import importlib
import os
import torch
import torch.nn as nn
import torchvision
import numpy as np
from dataset.dataset_splitter import DatasetSplitter
from dataset.transforms import TransformsGenerator
from dataset.video_dataset import VideoDataset
from evaluation.action_sampler import OneHotActionS... | 4,463 | 1,234 |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
# MAXLINEDEV - Finds max deviation from a line in an edge contour.
#
# Function finds the point of maximum deviation from a line joining the
# endpoints of an edge contour... | 2,545 | 882 |
# common functions
import sys
import json
# taken from sp_lib
def read_json_file(file_path):
try:
with open(file_path, 'r') as json_file:
readstr = json_file.read()
json_dict = json.loads(readstr)
return json_dict
except OSError as e:
print('Unable to read url js... | 997 | 323 |
# -*- encoding: utf-8 -*-
import dsl
from shapely.wkt import loads as wkt_loads
from . import FixtureTest
class SuppressHistoricalClosed(FixtureTest):
def test_cartoon_museum(self):
# Cartoon Art Museum (closed)
self.generate_fixtures(dsl.way(368173967, wkt_loads('POINT (-122.400856246311 37.786... | 1,039 | 464 |
/Learn more or give us feedback
######################################################################
# Author: Thy H. Nguyen
# TODO: Change this to your names
# Username: nguyent2
# TODO: Change this to your usernames
#
# Assignment: A06: It's in your Genes
#
# Purpose: A test suite for testing the a06_genes.py progr... | 2,454 | 832 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 11:03:51 2019
@author: ivanpauno
"""
import matplotlib.pyplot as plt
import numpy as np
def main():
# A = sqrt(10^(.1*alpha_min-1)/10^(.1*alpha_max-1))
A = np.logspace(np.log10(2), np.log10(100), num=200)
ws_array = [1.1, 1.5, 2, 3... | 1,023 | 452 |
"""
Common constants for Pipeline.
"""
AD_FIELD_NAME = 'asof_date'
ANNOUNCEMENT_FIELD_NAME = 'announcement_date'
CASH_FIELD_NAME = 'cash'
CASH_AMOUNT_FIELD_NAME = 'cash_amount'
BUYBACK_ANNOUNCEMENT_FIELD_NAME = 'buyback_date'
DAYS_SINCE_PREV = 'days_since_prev'
DAYS_SINCE_PREV_DIVIDEND_ANNOUNCEMENT = 'days_since_prev_d... | 1,090 | 502 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By : Nguyen Viet Bac - Bacnv6
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
___________________________________________________________________________... | 2,220 | 818 |
# Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string.
# Return the n copies of the whole string if the length is less than 2
s = input("Enter a string: ")
def copies(string, number):
copy = ""
for i in range(number):
copy += string[0] + strin... | 456 | 149 |