text string | size int64 | token_count int64 |
|---|---|---|
"""
Modeled largely after
https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py
Also, the github version draws with replacement, while I modified to not use replacement
Also, reference here for how to play blackjack
"""
from typing import Dict, List, Tuple
import gym
import numpy as np
from gym imp... | 6,058 | 1,972 |
from functools import partial
from dragn.dice.die_and_roller import roller
D4 = partial(roller, 4)
D6 = partial(roller, 6)
D8 = partial(roller, 8)
D10 = partial(roller, 10)
D12 = partial(roller, 12)
D20 = partial(roller, 20)
| 228 | 99 |
from setuptools import setup
from pip.req import parse_requirements
from pip.download import PipSession
setup(
name='apnsend',
version='0.1',
description='apnsend is a tool to test your APNS certificate, key and token.',
py_modules=['apnsend'],
install_requires=[
str(req.req) for req in par... | 472 | 149 |
import json
from abc import ABC, abstractmethod
from typing import Optional
from aiohttp import ClientResponse as Response
from .mechanisms.fetch import IFetchMechanism
from .models.request import IRestRequest
from ..errors.fetching_errors import FetchMechanismFailed
from ..utils.logging_utils import IMonitorLogger, ... | 7,159 | 2,035 |
#
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def iterative(head):
... | 773 | 221 |
'''Module to test default template tags such as if, for, with, include, etc.
'''
import unittest
from lighty.templates import Template
from lighty.templates.loaders import FSLoader
class DefaultTagsTestCase(unittest.TestCase):
"""Test case for if template tag
"""
def assertResult(self, name, result, val... | 2,521 | 700 |
# Author: Niels Nuyttens <niels@nannyml.com>
#
# License: Apache Software License 2.0
"""Unit tests for the calibration module."""
import numpy as np
import pandas as pd
import pytest
from nannyml.calibration import IsotonicCalibrator, _get_bin_index_edges, needs_calibration
from nannyml.exceptions import Invali... | 3,038 | 1,346 |
import copy
import nltk
import json
from gensim.models import KeyedVectors
import h5py
import numpy as np
from torch import nn
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
def load_feature(filename, dataset='ActivityNet'):
if dataset == 'ActivityNet':
with ... | 3,962 | 1,421 |
"""Tests for the forms of the ``aps_purchasing`` app."""
import os
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils.timezone import now
from ..forms import QuotationUploadForm
from ..models import MPN, Price, Quotation, Q... | 2,654 | 779 |
# test_read_embark_fields_json_file.py 2/18/19 sm
""" test read_embark_fields_json_file.py """
import json
import unittest
# add parent directory to path
import os
import inspect
import sys
CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(
inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTD... | 1,839 | 568 |
"""This file is the results window"""
import sys
sys.path.insert(0, 'menu/')
sys.path.insert(1, 'util/')
sys.path.insert(2, 'sim/')
import tkinter as tk
import menu
import import_jobs as ij
import validate_jobs as validate
import show_results as sr
import export_results as xr
import compare_sim
import con... | 8,928 | 3,830 |
# -*- coding: utf-8 -*-
from importlib import import_module
import os
import sys
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
APP_NAME = 'server'
SYS_DIRS = [
'lib',
]
# add directories to sys path
for dir in SYS_DIRS + [APP_NAME]:
sys.path.insert(1, os.path.join(BASE_PATH, dir))
# register flas... | 539 | 202 |
print(present("Py-Kurs", "am Di in der 5.", "dem FSR-Kurssystem"))
| 67 | 29 |
"""
Representation Processor
============
These are core classes of representation processor.
Repr Processor: the basic representation processor
- Event Processor
"""
import numpy as np
from abc import ABC, abstractmethod
import pretty_midi as pyd
class ReprProcessor(ABC):
"""Abstract base class severing as... | 9,440 | 2,699 |
import ccp_api
import pytest
from .test_ccp_api import Base_ccp_api_Test
class TestProducts(Base_ccp_api_Test):
@pytest.fixture
def products_wsdl(self, file_fixture):
return file_fixture("products", "wsdl.xml")
@pytest.fixture
def product_by_ID_response(self, file_fixture):
return fi... | 5,521 | 1,862 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@IDE :PyCharm
@Project :yjcL
@USER :yanyin
@File :Float.py
@Author :yujiecong
@Date :2021/9/1 16:19
'''
from restart.TokenyjcL.Token import Token_yjcL
class Float_yjcL(Token_yjcL):
def __init__(self,valueDict):
super(Float_yjcL, self)... | 340 | 148 |
#!/usr/bin/env python3
# adaptation du script FXCM pour XTB
##
debug = 1 ## DEBUG ENABLED OR DISABLED
from XTBApi.api import *
import time
import pandas as pd
import datetime as dt
import talib.abstract as ta
## Maths modules
import pyti.bollinger_bands as bb
from pyti.relative_strength_index import rela... | 19,461 | 6,507 |
"""The InterUSS Platform Data Node storage API server.
This flexible and distributed system is used to connect multiple USSs operating
in the same general area to share safety information while protecting the
privacy of USSs, businesses, operator and consumers. The system is focused on
facilitating communication among... | 23,609 | 6,929 |
junk_image1 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\xf4\x00\x00\x01v\x08\x00\x00\x00\x00\xbd\xc55\x85\x00\x00\x07\xcaIDATx\x01\xec\xd9m\xeb\xd2P\x1c\xc6\xf1\xff\xfb\x7f)g\xe1)oB\x0ef\x92\xe2\xcd\n\x94\xac\xa8\x19Ef\xa93l\xd8\xb4:n\xfe\xba\xda\xa6\xab\xe7\xff\'\x1e\xaf/x\xcdm\x0f?0\x06\xbb\xdb\xb2\x9b\xebn+... | 32,069 | 27,772 |
'''
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the... | 1,342 | 403 |
from django.shortcuts import render
from django.views import View
class LoginView(View):
def get(self,request):
return render(request,'login.html')
| 162 | 46 |
import browser
import re
import datetime
from bs4 import BeautifulSoup, NavigableString
RX_OCCUPATION = re.compile(r"([0-9]+)/([0-9]+)")
RX_TIME = re.compile(r"([0-9]{2}:[0-9]{2})-([0-9]{2}:[0-9]{2})")
RX_FULLDATE = re.compile(r"[a-z]{2} ([0-9]{2}) ([a-z]{3}) ([0-9]{4})")
MONTHS = ["jan", "feb", "maa", "apr", "mei"... | 6,417 | 2,037 |
import numpy as np
from sklearn.neighbors import NearestNeighbors
import cv2
def estimate_normals(p, k=20):
neigh = NearestNeighbors(n_neighbors=k)
neigh.fit(p)
distances, indices = neigh.kneighbors(return_distance=True)
dp = (p[indices] - p[:,None])
U, s, V = np.linalg.svd(dp.transpose(0,2,1))
... | 10,805 | 3,951 |
# 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 ... | 20,393 | 6,262 |
import json
import re
import os
import pkg_resources
import zipfile
import shutil
import xml.etree.ElementTree as ET
from django.conf import settings
from django.template import Context, Template
from webob import Response
from xblock.core import XBlock
from xblock.fields import Scope, String, Float, Boolean, Dict
fr... | 9,501 | 2,797 |
"""
**Speech to Text (STT) engine**
Converts the user speech (audio) into text.
"""
import threading
import traceback
import speech_recognition as sr
from src import settings
from src.core.modules import log, tts, replying
def setup() -> None:
"""
Initializes the STT engine
Steps:
1. Creates a... | 4,861 | 1,432 |
from QrCode import *
# Sert pour tester sur un même pc à la fois la génération du QrCode et la lecture de celui ci
if __name__ == '__main__':
sync_other_device_QrCode()
sync_this_device_QrCode() | 203 | 70 |
import unittest
import sqlparse
from sqlparse import tokens as T
from sqlparse.sql import (Identifier,
Statement, Token,
TokenList)
from context import (
extract_from_clause, extract_where_clause, tokenize) # , fused)
from context import (
Query, Join, Tabl... | 7,289 | 2,508 |
# coding: utf-8
'''
name: PHPCMS v9.6.1 任意文件下载
author: Anka9080
description: 过滤函数不严谨导致任意文件下载。
'''
import sys
import requests
import re
def poc(target):
print('第一次请求,获取 cookie_siteid ')
url = target +'index.php?m=wap&c=index&a=init&siteid=1'
s = requests.Session()
r = s.get(url)
cookie_siteid = r.h... | 1,356 | 616 |
import re
from utils.output import KeyValueOutput
ERRORS_RE = [re.compile('Unhandled exception "(.*?)"'),
re.compile('traceback', re.IGNORECASE),
re.compile('w3af-crash'),
re.compile('scan was able to continue by ignoring those'),
re.compile('The scan will stop')]
... | 1,493 | 426 |
class MaximumAverageSubarrayI:
"""
https://leetcode-cn.com/problems/maximum-average-subarray-i/
"""
def findMaxAverage(self, nums: List[int], k: int) -> float:
| 196 | 75 |
#! /usr/bin/python3
#
# Usage:
#
# path/to/script$ python3 __main__.py -c <config_file>
#
# Will create 'YYYY_MM_DD_STREAMNAME_PLAYLIST.txt' file
# which will contain currently captured song
#
# HH:MM Interpret - Song Name
#
# To capture whole playlist you have to
# make crontab scheldule or widows/mac equivalen... | 5,925 | 1,910 |
# Problem Set 4B
# Name: Gyalpo Dongo
# Collaborators:
# Time Spent: 9:00
# Late Days Used: 1
import string
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings ... | 14,341 | 4,288 |
import cartography.intel.gcp.compute
import tests.data.gcp.compute
TEST_UPDATE_TAG = 123456789
def _ensure_local_neo4j_has_test_instance_data(neo4j_session):
cartography.intel.gcp.compute.load_gcp_instances(
neo4j_session,
tests.data.gcp.compute.TRANSFORMED_GCP_INSTANCES,
TEST_UPDATE_TAG... | 13,996 | 5,157 |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 6,208 | 2,041 |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... | 3,895 | 1,158 |
def mark(**kwargs):
print(f"Получил аргументы {kwargs}")
def decorator(func):
print(f"добавляем атрибуты функции {kwargs}")
for name, value in kwargs.items():
setattr(func, name, value)
return func
decorator.data = kwargs
return decorator
def mark_2(**kwargs_mark)... | 662 | 211 |
"""
Extraction utilities and supporting functions
Some operations are used frequently or repeated enough to be factored out.
Note that SQL can be used via the POORSQL_BINARY_PATH
Download the binary from http://architectshack.com/PoorMansTSqlFormatter.ashx
It's a phenominal utility that brilliantly normaliz... | 5,087 | 1,865 |
'''import sys
import operator
from Bio.Seq import Seq
try:
from Bio.Alphabet import generic_dna, IUPAC
Bio_Alphabet = True
except ImportError:
Bio_Alphabet = None
# usages of generic_dna, IUPAC are not supported in Biopython 1.78 (September 2020).
print(f"The installed BioPython is a new version tha... | 12,203 | 4,320 |
import FWCore.ParameterSet.Config as cms
def customiseCommon(process):
#####################################################################################################
####
#### Top level replaces for handling strange scenarios of early collisions
####
## TRACKING:
process.newSeedFr... | 4,915 | 1,391 |
## TODO: insert your ShapeNetCore.v2, textures, training and testing background paths
# NOTE that HDF5 is not generated here, to convert the dataset to HDF5 use dataloaders/conversion.py
g_datasets_path = '/mnt/lascar/rozumden/dataset'
g_shapenet_path = g_datasets_path + '/ShapeNetv2/ShapeNetCore.v2'
g_textures_path ... | 4,838 | 2,365 |
# -*- coding:utf-8 -*-
import numpy
import numpy.random
import numpy.linalg
from . import svd
def svd_init(matrix, dim, seed=None):
u, s, v = svd.svd(matrix, dim)
ss = numpy.sqrt(numpy.diag(s))
return numpy.maximum(0.001, u.dot(ss)), numpy.maximum(0.001, ss.dot(v))
def random_init(matrix, dim, seed=Non... | 3,094 | 1,177 |
import datetime
import datetime
from altair.vegalite.v4.schema.core import Legend
import pandas
from pandas.core.frame import DataFrame
import streamlit as st
import time
import bubbletea
st.header("LIVEPEER Stake Movement")
urlvars = bubbletea.parse_url_var([{'key':'startdate','type':'datetime'}, {'key':'enddate','t... | 6,052 | 2,077 |
from vaccine_feed_ingest.utils import match
def test_is_concordance_similar(full_location, minimal_location, vial_location):
assert match.is_concordance_similar(full_location, vial_location)
assert not match.is_concordance_similar(minimal_location, vial_location)
def test_is_address_similar(full_location, ... | 956 | 302 |
# Copyright (c) 2013, University of Liverpool
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 ... | 2,201 | 688 |
#!/usr/bin/python3
import sklearn
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn import tree
from sklearn.metrics import accuracy_score
#loading iris
iris=load_iris()
#traning flowers.features is stored in i... | 1,072 | 398 |
#!/usr/bin/env python
def humanize(n, base=10, digits=1, unit=''):
'''convert a floating point number to a human-readable format
Parameters
----------
n : float or str
number to convert, it can a string representation of
a floating point number
base : int
base to use, eith... | 2,762 | 917 |
import os
import PIL
import torch
from glob import glob
from torch.utils.data import DataLoader
from torchvision.transforms.functional import pil_to_tensor
class Latent(torch.utils.data.Dataset):
def __init__(self, dir_name, transforms=None):
# dataset 디렉토리를 기반으로 parse.data_train, test에 따라서
# 각각 다... | 1,337 | 655 |
def count_vowel(line):
return len([c for c in line if c in "aeiou"])
def is_vowelly(line):
return count_vowel(line) > 2
def is_doublly(line):
return len(
[line[i] for i in range(len(line) - 1) if line[i] == line[i + 1]])
def is_valid(line):
return not sum(c in line for c in ['ab', 'cd', 'p... | 1,069 | 394 |
#!/usr/bin/python
# update languages.py from pycountry
import os
import codecs
import pycountry
basepath = os.path.dirname(os.path.dirname(__file__))
def main():
"""Update language information in dosagelib/languages.py."""
fn =os.path.join(basepath, 'dosagelib', 'languages.py')
encoding = 'utf-8'
with... | 876 | 321 |
import tensorflow as tf
x = tf.Variable(0, name='x')
model = tf.global_variables_initializer()
with tf.Session() as session:
for i in range(5):
session.run(model)
x = x + 1
print(session.run(x))
x = tf.Variable(0., name='x')
threshold = tf.constant(5.)
model = tf.glob... | 531 | 199 |
try:
num = 5 / 0
except:
print("An error occured")
raise | 59 | 27 |
"""Berechnet die mündliche Note"""
import csv
with open('bewertung.csv', encoding='utf-8', mode='r') as bewertung:
TABELLE = []
DATA = csv.reader(bewertung, delimiter=',')
for row in DATA:
TABELLE.append([element.strip() for element in row])
OUTPUT = [TABELLE[0] + ["Note"]]
del TABELLE[0]
... | 732 | 284 |
from unittest import TestCase
from leetcodepy.edit_distance import *
solution1 = Solution1()
word11 = "horse"
word12 = "ros"
expected1 = 3
word21 = "intention"
word22 = "execution"
expected2 = 5
class TestEditDistance(TestCase):
def test1(self):
self.assertEqual(expected1, solution1.minDistance(wo... | 410 | 149 |
def index(self, value):
"""
Return index of the first child containing the specified value.
:param str value: text value to look for
:returns: index of the first child containing the specified value
:rtype: int
:raises ValueError: if the value is not found
"""
self.logger.info('getting ... | 805 | 229 |
#!/usr/bin/python3
import operator
import sys
import json
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "./"))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../"))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../"))
sys.pat... | 2,724 | 769 |
#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup
import json
import urllib
import urllib2
import re
import time
import os.path
def getgoogleurl(search,siteurl=False):
search = search.encode("utf-8")
if siteurl==False:
return 'http://www.google.com/search?q='+urllib.quote_plus(search)
... | 3,746 | 1,278 |
from exchangelib.errors import (
ErrorAccessDenied,
ErrorFolderNotFound,
ErrorInvalidOperation,
ErrorItemNotFound,
ErrorNoPublicFolderReplicaAvailable,
)
from exchangelib.properties import EWSElement
from .common import EWSTest
class CommonTest(EWSTest):
def test_magic(self):
self.ass... | 3,703 | 973 |
import os
from datetime import datetime
from pathlib import Path
from pydantic import EmailStr
def send_dummy_mail(subject: str, message: str, to: EmailStr):
current_path = os.getcwd()
filename = f'{datetime.now().timestamp()} - {subject}.txt'
email_text = f'''Subject: {subject}
From: no-reply@email.com
T... | 735 | 246 |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 17:06:09 2018
@author: v-beshi
"""
import pyodbc
import pandas as pd
def get_agg_data():
con=pyodbc.connect('DRIVER={SQL Server};SERVER=ServerName;DATABASE=DB;UID=ID;PWD=Password')
raw_data=pd.read_sql('select * from dbo.BitcoinTradeHistory',con)
raw_d... | 3,540 | 1,622 |
import numpy as np
import pandas as pd
import pyomo.environ as pyo
import mpisppy.utils.sputils as sputils
from mpisppy.opt.ef import ExtensiveForm
from pathlib import Path
import os
import sys
path_root = Path(os.path.abspath(__file__)).parents[2]
sys.path.append(str(path_root))
from bloodbank_rl.environments.plat... | 16,692 | 5,011 |
import random
import json
class TTTGame(object):
def __init__(self):
self._board = [0] * 9
self._end = False
with open('learning.json', 'r') as f:
self._state = json.loads(f.read())
self._alpha = 0.05
def judge(self, state):
if (sum(state[0: 3]) == 3 or \
sum(state[3: 6]) == 3 or \
sum(state[6::]... | 3,623 | 1,636 |
str1 = ' Happy Life '
str2= ' Happy Life '
if (str1.strip()== str2.strip()):
print("Same")
else:
print("Not same")
# same | 141 | 60 |
# -*- coding: utf-8 -*-
"""Text Analytic (Emotion) - load_only.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ec4JMQZ5zoj-PB_a0mUkJWRKotgQSd9f
"""
"""
Text Analytic (Emotion) with TensorFlow
Copyright 2020 I Made Agus Dwi Suarjaya
... | 2,601 | 921 |
# Imports
import socket # Communication
import threading # Communication with multiple users at once
import pickle # Serialising data
import hashlib # Hashing passwords
from Crypto.Cipher import AES # AES encryption algorithms
from Crypto.Random import get_random_bytes # For generating random keys and nonces... | 13,160 | 3,468 |
# server backend
server = 'cherrypy'
# debug error messages
debug = False
# auto-reload
reloader = False
# database url
db_url = 'sqlite:///devmine/db/devmine.db'
# echo database engine messages
db_echo = False
| 215 | 71 |
# generate 500 screens.
import random
objs = []
for i in range(500):
go_to = random.choice([2,3])
for j in range(go_to):
new_obj = {'name': 'non_exist', 'RBs': [], 'set': 'memory', 'analog': i}
width = round(random.random()*20)
hight = round(random.random()*10)
x = round(rando... | 1,279 | 538 |
import asyncio
import json
import os
import shutil
import typing
from datetime import datetime, timezone, timedelta
from matplotlib import pyplot as plt
import cv2
import country_converter as coco
import flag
import requests
import discord
from bot.api import APIClient
from bot.log import get_logger
from bot.utils.co... | 46,269 | 14,720 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2014, Ocean Systems Laboratory, Heriot-Watt University, UK.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follow... | 4,535 | 1,562 |
from social_friends_finder.backends import BaseFriendsProvider
from social_friends_finder.utils import setting
if not setting("SOCIAL_FRIENDS_USING_ALLAUTH", False):
from social_auth.backends.contrib.vk import VKOAuth2Backend
USING_ALLAUTH = False
else:
from allauth.socialaccount.models import SocialToken, ... | 1,605 | 475 |
default_app_config = 'tests.cms_bundles.apps.AppConfig'
| 56 | 22 |
data_simpleJobCreateParams = {
"name": "TestJob",
"repetitionInterval": "HOURLY:03",
"command": "ls",
"enabled": True
}
data_simpleManualJobCreateParams = {
"name": "TestJob",
"repetitionInterval": "",
"command": "ls",
"enabled": False
}
data_simpleJobCreateExpRes = {
"guid": 'IGNORE',
"name": da... | 2,543 | 832 |
from nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction
from nltk import word_tokenize
# import language_evaluation
from typing import List
from collections import defaultdict, Counter
import re
import math
import sys
def mean(lst):
return sum(lst) / len(lst)
def _calc_ngram_dict(tok... | 8,228 | 3,271 |
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packed)
def get_url(packet):
return (packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path).decode("utf-8")
def get_login_info(packet):
if packet.haslayer... | 896 | 298 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from typing import NoReturn
import cv2 as cv
import numpy as np
from numpy import mat
import xml.etree.ElementTree as ET
import math
camera_angle = 315
camera_intrinsic = {
# # 相机内参矩阵
# 相机内参矩阵 matlab 求得
"camera_matrix": [871.08632815... | 3,705 | 1,825 |
#!/usr/bin/python
import os
from log import Log
from enum import IntEnum, unique
from grammar import Grammar
from automaton import FiniteAutomaton
@unique
class Command(IntEnum):
GRAMMAR_READ = 1
GRAMMAR_DISPLAY = 2
GRAMMAR_VERIFY = 3
AUTOMATON_READ = 4
AUTOMATON_DISPLAY = 5
CONVERT_RG_TO_FA... | 5,004 | 1,498 |
distancia = int(input('Digite a distancia de sua viagem: '))
if distancia <= 200:
preco = distancia * 0.50
print(preco)
else:
preco = distancia * 0.40
print(preco)
| 180 | 74 |
import sys
import subprocess
import os
from numpy import asarray
#triangle_path = os.path.join( "C:\\Users\\Mai\\Dropbox\\Research\\Deformation\\src\\py\\triangle", "triangle.exe")
triangle_path = os.path.join( os.path.dirname( __file__ ), "triangle", "triangle" )
if not os.path.exists( triangle_path ):
raise Imp... | 7,947 | 2,603 |
from . import SpecValidator
BaremetalSpec = {
'EDB-RA-1': {
'ssh_user': SpecValidator(type='string', default=None),
'pg_data': SpecValidator(type='string', default=None),
'pg_wal': SpecValidator(type='string', default=None),
'postgres_server_1': {
'name': SpecValidator(t... | 4,559 | 1,367 |
import numpy as np
import time
import argparse
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy import special
from tqdm import tqdm
from scipy.optimize import curve_fit
from utils.build_hist import build_hist
class SS_Charge:
"""
read calibration data and ... | 2,382 | 863 |
# python /usr/bin/env/python
# /// The Exoplanet Pocketknife
# /// Scott D. Hull, The Ohio State University 2015-2017
# /// All usage must include proper citation and a link to the Github repository
# /// https://github.com/ScottHull/Exoplanet-Pocketknife
import os, csv, time, sys, shutil, subprocess
from threading ... | 97,747 | 37,439 |
#!/usr/bin/env python
'''Exctact element of green's function'''
import argparse
import sys
import numpy
import os
import pandas as pd
import json
_script_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(_script_dir, 'analysis'))
import matplotlib.pyplot as plt
# from pauxy.analysis.extract... | 4,074 | 1,222 |
import glob
import os
import albumentations as A
import kaggle
import numpy as np
import PIL
import pytorch_lightning as pl
import torch
from albumentations.pytorch import ToTensorV2
from torch.utils.data import random_split
from torch.utils.data.dataloader import DataLoader
from utils import show_images
def get_tr... | 12,854 | 4,397 |
import sys
input = sys.stdin.readline
from collections import deque
def bfs(v):
dp = [-1 for _ in range(V+1)]
dp[v] = 0
q = deque()
q.append(v)
while q:
cv = q.popleft()
for nc,nv in tree[cv]:
if dp[nv] == -1: # 아직 들르지 않았다면,
dp[nv] = dp[cv] + nc
... | 663 | 383 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ##### TONTgBotContract Config
# Edit starts here
TgBotAPIKey = 'xxxx:yyyy' # API Keythat you get from @BotFather
tg = 11111 # Your id, you can get it by sending command /id to bot @TONTgIDBot
# Edit ends here
tonoscli = '/opt/tonos-cli/target/release/tonos-cli' # P... | 997 | 398 |
#!/usr/bin/env python3
"""
Pandoc filter to change each relative URL to absolute
"""
from panflute import run_filter, Str, Header, Image, Math, Link, RawInline
import sys
import re
base_raw_url = 'https://raw.githubusercontent.com/illinois-cs241/coursebook/master/'
class NoAltTagException(Exception):
pass
def ... | 1,624 | 474 |
#
# Copyright (c) 2022, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
import sys
import glob
sys.path.insert(0, '..')
import numpy as np
import matplotlib
import matp... | 8,793 | 3,200 |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12808.py
# Description: UVa Online Judge - 12808
# =============================================================================
import math... | 758 | 303 |
import os
import jinja2
import networkx as nx
from ..utils import Logger
from math import ceil, floor
from ..model import Segment
#Add function to Segments that generates unique names for internal nodes
#Function is specific for halide backend, hence it is added here and not in the original definition of Segment
def h... | 4,377 | 1,245 |
from plasmapy.utils.pytest_helpers.pytest_helpers import (
assert_can_handle_nparray,
run_test,
run_test_equivalent_calls,
)
| 137 | 55 |
import enum
class ParameterTypes(enum.Enum):
"""
Defines types for parameters. These types may be used in the specification of allowed parameters within the
individual attack classes. The type is used to verify the validity of the given value.
"""
TYPE_IP_ADDRESS = 0
TYPE_MAC_ADDRESS = 1
T... | 664 | 247 |
from utils.error_with_arrows import *
##### ERRORS ########
class Error:
def __init__(self, initial_pos, final_pos, error_class, details):
self.initial_pos = initial_pos
self.final_pos = final_pos
self.error_class= error_class
self.details= details
def error_string(self):
... | 1,984 | 597 |
import asyncio
import asyncpg
VALUES = [
356091260429402122,
"Why are you reading",
9164,
6000000,
14,
0,
0,
0,
463318425901596672,
"https://i.imgur.com/LRV2QCK.png",
15306,
["Paragon", "White Sorcerer"],
0,
0,
647,
"Leader",
None,
0,
"10.0",... | 2,062 | 920 |
from nmigen import *
from nmigen.asserts import Assert
from nmigen.cli import main_parser, main_runner
__all__ = ["Counter"]
"""
Simple counter with formal verification
See slides 50-60 in
https://zipcpu.com/tutorial/class-verilog.pdf
"""
class Counter(Elaboratable):
def __init__(self, fv_mode = False):
self.fv_m... | 1,112 | 472 |
import json
import requests
from regru_cloudapi.utils import Errors
class CloudAPI(object):
def __init__(self, token=None):
self.token = token
self.api_url = 'https://api.cloudvps.reg.ru/v1'
self.HEADERS = {'Content-Type': 'application/json'}
if self.token is not None:
... | 10,524 | 3,380 |
#!/usr/bin/python3
import urllib.request
import os
import gzip
DOWNLOAD_URL='http://yann.lecun.com/exdb/mnist/'
file_list=[ 'train-images-idx3-ubyte', 'train-labels-idx1-ubyte', 't10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte' ]
for name in file_list:
if not os.path.exists( name ):
gz_name= name + '.gz'... | 731 | 280 |
import random
from common import *
class test_a64_tbnz(TemplateTest):
def gen_rand(self):
regs = list(set(GPREGS) - {'x0', 'w0'})
while True:
yield {'insn' : random.choice(['tbz', 'tbnz']),
'reg' : random.choice(regs),
'bit' : random.randint(... | 2,651 | 915 |
# 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 u... | 6,943 | 2,281 |
from django.db import models
class Province(models.Model):
name = models.CharField(max_length=50, help_text="Name of the province")
| 138 | 42 |
import sqlalchemy as sa
from flask import jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
import csv
from sqlalchemy.sql.expression import false
from backend import app, db
from backend.models import Label, LabelValue, Project
from .helper_functions import (
check_admin,
check_a... | 7,512 | 2,307 |