content stringlengths 5 1.05M |
|---|
"""
:py:mod:`pymco.ssl`
-------------------
Contains SSL security provider plugin.
"""
from __future__ import print_function
import base64
import os
try:
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
except ImportError as exc:
print('You need install pycrypto for using SSL security pr... |
from shapely.geometry import Polygon
from helper import *
from pyhdf.SD import SD, SDC
from my_functions import *
class fpar_utils:
def __init__(self):
self.west = -124.457906126032
self.east = -69.2724108461701
self.north = 50.0000009955098
self.south = 30.0000009964079
self.lat_n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bson.objectid import ObjectId
import fibo
fibo.fib(1000)
print(fibo.fib2(100))
print("fibo模块名:", fibo.__name__)
name = input('Please enter your name: ')
print(name != None)
print(name is not None)
if name is not None:
print(name)
else:
print('''not a
nothi... |
#
# Copyright 2015 LinkedIn 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 required by applicable law or ... |
import random
import uuid
import os
class RandomRequest(object):
def __init__(self):
pass
def get_random_user_agent(self):
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files/supported_ios_versions.txt')) as f:
ios_versions = f.read().splitlines()
w... |
import discord
from discord.ext import commands
from modules import utils
import asyncio
import aiohttp
from http.client import responses
from typing import Optional
class Fortnite(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def get_fortnite_stats(self, name: str, platform: str) -> ... |
from .utils import run_all, run_pattern, run_list, initialize
__all__ = [
'run_all',
'run_pattern',
'run_list',
'initialize',
]
|
from bs4 import BeautifulSoup
import requests
import json
from urllib.parse import urljoin
import re
#TODO: decorate self.logged_in check
#TODO: get if user is admin
class CTFd(object):
"""
API wrapper for CTFd 2.1.2
"""
PATH_GET_CURRENT_USER = r"/api/v1/users/me"
PATH_GET_CHALLENGES = r"/api/v1... |
from constants import COLOR, COLOR_RED, COLOR_GREEN
from num_to_asin import num_to_asin
class Tote:
"""
Create Tote object with .audit() method.
"""
def __init__(self, tote_code, df_content):
"""
:param tote_code: str (e.g.: tsX... )
:param df_content: pd DataFram... |
from skimage.color import rgb2gray
from skimage.transform import resize
from skimage.io import imread, concatenate_images
import os
import numpy as np
# function for importing images from a folder
def load_images(path, input_size, output_size):
x_ = []
y_ = []
counter, totalnumber = 1, len(os.listdir(path)... |
import torch
from .transforms_rotated import bbox2delta_rotated
from ..utils import multi_apply
def bbox_target_rotated(pos_bboxes_list,
neg_bboxes_list,
pos_gt_bboxes_list,
pos_gt_labels_list,
cfg,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011, Florent Lamiraux, Thomas Moulard, JRL, CNRS/AIST
import unittest
import numpy as np
from dynamic_graph.sot.core.op_point_modifier import OpPointModifier
gaze = np.array((((1.0, 0.0, 0.0, 0.025), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.648), (0.0, 0.0, 0... |
import requests
import json
def get_practitioner(npi):
"""Returns a Practitioner Resource from Djmongo"""
url = "https://registry.npi.io/search/fhir/Practitioner.json" \
"?identifier.value=%s" % (npi)
response = requests.get(url)
try:
jr = json.loads(response.text)
if 'result... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, LABS^N
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import print_function
import os
import os.path as op
from copy import deepcopy
import warnings
from shutil import move, copy2
import subprocess
from collections import Counter... |
class Instruccion:
'''This is an abstract class'''
class CrearBD(Instruccion) :
'''
Esta clase representa la funcion para crear una base de datos solo recibe el nombre de la BD
'''
def __init__(self,reemplazar,verificacion,nombre, propietario, modo) :
self.reemplazar = reemplazar
... |
word = raw_input("Enter the word ")
word = word.lower()
file_txt = open("batman.txt", "r")
count = 0
for each in file_txt:
if word in each.lower():
count = count+1
print "The ", word ," occured ",count, " times" |
"""
Runtime: 5834 ms, faster than 34.56% of Python3 online submissions for Count Primes.
Memory Usage: 52.7 MB, less than 85.70% of Python3 online submissions for Count Primes.
"""
from typing import List
from typing import Optional
import math
class Solution:
def countPrimes(self, n: int) -> int:
if n <= ... |
#
# Copyright (c) 2021, The Board of Trustees of the Leland Stanford Junior University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above co... |
# -*- coding: utf-8 -*-
#
# Scrapy spider which extracts names for today from http://www.nimipaivat.fi.
#
# Author: Jarno Tuovinen
#
# License: MIT
#
import re
import datetime
import scrapy
from extractor.items import NamedayItem
date_pattern = re.compile('\d+')
nameday_url = "http://www.nimipaivat.fi/"
# Create URL... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
pyu40 PyQt5 tutorial
In this example, we reimplement an
event handler.
author: Jan Bodnar
website: py40.com
last edited: January 2015
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication
class Example(QWi... |
# Copyright (c) 2015-2016, The Authors and Contributors
# <see AUTHORS file>
# All rights reserved.
#
# 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 n... |
import requests
import json
def test_add_shipment():
App_URL="http://127.0.0.1:8000/shipments/"
f = open('request.json', 'r')
request_json = json.loads(f.read())
response = requests.post(App_URL,request_json)
print(response.text)
def test_list_shipments():
App_URL="http://127.0.0.1:8000/shipme... |
import os
import struct
import json
import glob
from argparse import ArgumentParser
import UnityPy
from antlr4 import *
from evAssembler import EvCmd, evAssembler
from evLexer import evLexer
from evParser import evParser
from ev_argtype import EvArgType
from ev_cmd import EvCmdType
from function_definitions import F... |
# Copyright 2019 Willian Fuks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
#!/usr/bin/env python
'''
Usage:
./noob3a.py [options]
Options:
--help -h This help.
--mktest-data=D -D D Output test-data.
'''
import numpy as np;
from struct import pack,unpack;
import os;
__dt = 'float32'
def _pint(i): return pack("i",i);
def _upint(f): return unpack("i",f.read(4))[0];
def o... |
#!/bin/env python
# 2014-4-18 created by Linxzh
# to combine additional fqfile with specific fqfile
import os
import argparse
# arguments
parser = argparse.ArgumentParser(description='Merge the fqfiles of the same sample produced by different lane', prog = 'Fqfile Merger')
parser.add_argument('-dira', type = str)
pa... |
import inspect
from django.dispatch import receiver
from django_mvc.signals import django_inited,actions_inited
class Action(object):
"""
all attr name should be lower case
"""
def __init__(self,action,tag="button",tag_body=None,tag_attrs=None,permission=None):
self.permission = permission if... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib import replay_memory
from common import GridAnnotationWindow
import Tkinter
def main():
print("Loading replay memory...")
memory = replay_memory.ReplayMemory.create_ins... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
fig, ax = plt.subplots()
# y_lim = 260000000
plt.ylim([0, 25])
plt.xlim([0, 21])
for n in range(1,21):
center ... |
#base enemy
import character
import animation
import math
import itertools
import random
import Message
class Enemy(character.Character):
def __init__(self, messageLog, currentMap):
super(Enemy, self).__init__(messageLog, currentMap)
self.minLevel = 0
self.baseDanger = 1
... |
from random import randint
print ('\n\n\nVamos jogar JOKENPÔ!!!\n\n\n')
escolha = int(input('Escolha PEDRA, PAPEL ou TESOURA:\n\n[1] PEDRA\n\n[2] PAPEL\n\n[3] TESOURA\n\nFaça a sua escolha: '))
if escolha != 1 and escolha != 2 and escolha != 3:
print('\n\nVocê escolheu: {}\nApenas números entre 1 e 3 são aceito... |
from functools import wraps
from rest_framework.response import Response
from rest_framework import status
def base_response(func):
# @wraps(func)
def response(serializer=None, data=None, **kwargs):
if serializer is not None and data is None:
data = serializer.data
elif serializer i... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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... |
import pygame
import cmath
import math as m
from pygame import *
from cmath import *
import matplotlib as mat
import numpy as np
xmax = 20
ymax = 16
inter = 1
interx = 1
tmax = 10
intert = 10
j = sqrt(-1)
WOUT_Last = [ 0, 0]
def ln(x):
try:
return log(abs(x)) - j * ( atan( x.real / ( .0000001 + x.imag... |
from tenzing.core.models import (tenzing_model, model_relation)
from tenzing.core import model_implementations
from tenzing.core import summary
from tenzing.core import plotting
|
"""
test_runner_browndye2.py
test runner_browndye2.py script(s)
"""
import os
import glob
import seekr2.tests.make_test_model as make_test_model
import seekr2.modules.common_sim_browndye2 as sim_browndye2
import seekr2.modules.runner_browndye2 as runner_browndye2
def test_runner_browndye2_b_surface_default(tmp_path... |
'''
Python program find the longest string of a given list of strings.
Input:
['cat', 'car', 'fear', 'center']
Output:
center
Input:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Output:
shatter
[[0, 4], [1, 0], [1, 3], [4, 1]]
Input:
[([1, 2, 3, 2], [], [7, 9, 2, 1, 4]),2]
Output:
[[0, 1], [0, 3], [2, 2]]
'''
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
""" unit test
"""
import numpy as np
from searchsorted import searchsorted
__all__ = ['TestSearchSorted']
class TestSearchSorted:
def test1(self):
arr = np.linspace(0, 10, 21)
value = 3.3
index = searchsorted(arr, 3.3)
assert arr[index] == 3.
if __name__ == '__main__':
test... |
#!/usr/bin/python3
'''
NAME:
lf_pdf_search.py
PURPOSE:
lf_pdf_search.py will run a pdf grep looking for specific information in pdf files
"pdfgrep -r --include 'ASA*.pdf' 'ASA End Date'"
EXAMPLE:
lf_pdf_search.py
NOTES:
1. copy lf_pdf_search.py to a directory that has the pdf information
TO DO NOTES:
'''
impor... |
from feed.spiders.spider import Spider
class AliyunfeWeeklySpider(Spider):
name = 'aliyunfeweekly'
def __init__(self):
Spider.__init__(self,
start_urls=[
'https://github.com/aliyunfe/weekly',
],
index... |
from driver import ADC
print("-------------------start adc test--------------------")
adc = ADC()
adc.open("ADC0")
value = adc.read()
print(value)
adc.close()
print("-------------------end adc test--------------------")
|
import tempfile, os
import torch
import numpy as np
import cv2
import imageio
"""
Utilities for making visualizations.
"""
def save_video(images, output_fn):
writer = imageio.get_writer(output_fn, fps=20)
for im in images:
writer.append_data(im)
writer.close()
def draw_boxes(img, boxes, grid_si... |
#!/bin/env python3
import threading
from collections import deque
from time import sleep
from rich.layout import Layout
from rich.live import Live
from console import main_console
from data_structure.host_info import HostInfo
from data_structure.imaging_metrics import ImagingMetrics
from data_structure.log_message_in... |
a,b,c=(d,e,)
|
import numpy as np
import random
class ER(object):
def __init__(self, memory_size, state_dim, action_dim, reward_dim, qpos_dim, qvel_dim, batch_size, history_length=1):
self.memory_size = memory_size
self.actions = np.random.normal(scale=0.35, size=(self.memory_size, action_dim))
self.rew... |
from setuptools import setup, find_packages
DESCRIPTION = '''\
Bob is a suite of implementations of the Scheme language in Python'''
setup(
name='bobscheme',
description=DESCRIPTION,
author="Eli Bendersky",
author_email="[email protected]",
version='1.0.0',
packages=find_packages(),
license... |
import json
from toggl.TogglPy import Toggl
from os import path, makedirs
import getopt
import sys
from datetime import datetime, timedelta
import logging
logger = logging.getLogger(__name__)
team_report_template = """
---
### Week of {0}
{1}
#### {2}"""
def user_weekly_report(directory, since, until, api_key, u... |
# Generated by Django 2.1.7 on 2019-11-08 18:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("ui", "0025_preset_id_textfield"),
]
operations = [
migrations.AddField(
model_name="collection",
name="schedule_retr... |
import typing as t
from .client import Client
from .lexicon import Lex
from .local import LocalClient
from .objects import *
from .query import exp, Expression
__title__ = "valorant"
__author__ = "frissyn"
__doc__ = "Complete Python interface for the Valorant API. Works right out of the box!"
__all__ = ["Client", "e... |
#!/pxrpythonsubst
#
# Copyright 2018 Pixar
#
# 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 t... |
"""
Your task is to complete the implementation of the functions below, which do some kind of
manipulation of linked lists (that is, you need to use the LinkedList class defined in the p0 session)
"""
from m03_sequences.p0.linked_list import LinkedList
from m03_sequences.p0.linked_list import Node
def find(L, e):
... |
from concurrent.futures.thread import ThreadPoolExecutor
import os
from pydantic import BaseSettings
from rq import Queue
import redis as rd
import logging
logger = logging.getLogger("api")
# Redis Queue for model-prediction jobs
redis = rd.Redis(host="redis", port=6379)
prediction_queue = Queue(os.getenv('NAME'), c... |
# Copyright (C) 2014 Andrea Biancini <[email protected]>.
#
# 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 appl... |
import argparse
import string
import re
import docx
REGEX = '\([a-zA-Z][^)\[\]=]*[0-9]\)'
EXCLUDE = set(string.punctuation) - set('-')
def find_reference_for_cite_regex(cite_regex):
for reference_id, reference in enumerate(references, 0):
result = re.findall(cite_regex, reference)
if result:... |
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxResults import ... |
import re
import requests
# Regexr: https://regexr.com/
# (cool site I use to real-time hack with regular expressions)
# List of URL's that I want to Regular Expression test:
urls = [
"https://cdn.shopify.com/s/files/1/0021/6504/7351/products/trick-worm-cherry-seed_608x544.jpg?v=1531854672",
"https://cdn.sh... |
#!/usr/bin/env python3
"""
script for downloading genomes from NCBI
"""
# python modules
import os
import sys
import argparse
import pandas as pd
from tqdm import tqdm
from subprocess import Popen
from glob import glob as glob
from multiprocessing import Pool
from subprocess import Popen, PIPE
def calcMD5(path, md5)... |
"""
Linear Regression model
-----------------------
A forecasting model using a linear regression of some of the target series' lags, as well as optionally some
covariate series' lags in order to obtain a forecast.
"""
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
from scipy.optimize im... |
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from rich.console import Console
from rich.traceback import install
from typing import Union, Optional
imp... |
from ast import literal_eval
from atexit import register
from contextlib import contextmanager
from flask_login import current_user
from importlib.util import module_from_spec, spec_from_file_location
from json import loads
from logging import error, info, warning
from operator import attrgetter
from os import getenv, ... |
#
# subunit: extensions to Python unittest to get test results from subprocesses.
# Copyright (C) 2005 Robert Collins <[email protected]>
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project sour... |
# -*- coding: utf-8 -*-
"""
(c) 2018 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <[email protected]>
"""
from __future__ import unicode_literals, absolute_import
import datetime
import os
import shutil
import sys
import tempfile
import time
import unittest
import pygit2
import six
from mock import ... |
def reverse(num):
return int(str(num)[::-1])
def main():
t = int(input())
for i in range(t):
a, b = raw_input().split()
a = int(a)
b = int(b)
print int(str((int(str(a)[::-1]) + int(str(b)[::-1])))[::-1])
main()
|
"""
Logger
This is a wrapper that handles logs in the system
"""
import os
import sys
from loguru import logger
# configurations for log handling
# info log configurations
logger.add(
sink=sys.stdout,
backtrace=True if os.environ.get("ENV", "development") == "development" else False,
colorize=True,
... |
from jinja2 import Environment, FileSystemLoader
ENV = Environment(loader=FileSystemLoader('.'))
template = ENV.get_template("router_template.j2")
parameters = { "hostname": "MELIH1985", "loopback10": "10.10.10.10", "loopback11": "11.11.11.11", "loopback0": "9.9.9.9", "vlan8":"8.8.8.8" }
print(template.render(router=... |
def simple_bubble_sort(l):
for j in range(1, len(l))[::-1]:
for i in range(j):
if l[i] > l[i + 1]:
l[i], l[i + 1] = l[i + 1], l[i]
def bubble_sort(l):
j = len(l) - 1
while j:
k = 0
for i in range(j):
if l[i] > l[i + 1]:
l[i], ... |
# integrations tests
# for unit tests, go to the `tests` folder of each submodules
import time
import pytest
import grpc
import numpy as np
from serving_utils import Client, PredictInput
@pytest.mark.integration
@pytest.mark.asyncio
async def test_client():
test_serving_ports = [
8501,
8502,
... |
# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x):
# 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
... |
import math
from copy import deepcopy
import networkx as nx
import numpy as np
import xxhash
import warnings
budget_eps = 1e-5
class S2VGraph(object):
def __init__(self, g):
self.num_nodes = g.number_of_nodes()
self.node_labels = np.arange(self.num_nodes)
self.all_nodes_set = set(self.nod... |
# Copyright (c) 2018, NVIDIA CORPORATION. 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 appli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Abstract: Operations on earthquake data as examples for how to use the core concept 'event'
Use Cases:
- get all locations of earthquakes with a magnitude of 4 or higher
- get all earthquakes which origin is 100 m or deeper
- get all earthquakes from 12/01/2014 00:00:... |
from ..api import get_many, ApiVersion, int_field, bool_field, date_field
from datetime import date
from typing import Iterator, List, Optional
class OckovaciZarizeni:
""" Očkovací zařízení
Datová sada poskytuje seznam očkovacích zařízení v ČR jako doplnění seznamu očkovacích míst, kde
jsou podávány očkov... |
"""
Copyright (c) 2015-2018 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import pytest
from flexmock import flexmock
import datetime
import random
import sys
import json
from osbs.build.user_params import Bui... |
import base64
from aqt.webview import AnkiWebView
def img_div(content, height):
b64_img = str(base64.b64encode(content), 'utf-8')
style = f"max-height:{height};width:auto"
return f'<img id="graph" style="{style}" src="data:image/png;base64,{b64_img}"></img>'
def error_div(detail: str) -> str:
retur... |
from setuptools import find_packages, setup
setup(
name='blns',
version='0.1.7',
url='https://github.com/danggrianto/big-list-of-naughty-strings',
license='MIT',
author='Daniel Anggrianto',
author_email='[email protected]',
description='Big List of Naughty String. Forked from https://gi... |
from django import template
register = template.Library()
@register.filter(name='ordinal')
def ordinal(value):
""" Cardinal to ordinal conversion for the edition field """
try:
digit = int(value)
except:
return value.split(' ')[0]
if digit < 1:
return digit
if digit % 100 ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
from scout.protocol import *
from scout.SteerByWire import * |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: [email protected]
*
"""
n=int(input())
a=sorted(map(int,input().split()))
print(min([sum(abs(x-y)for x,y in zip(a,range(i,n+1,2)))for i in[1,2]])) |
from ...os_v3_hek.defs.matg import *
|
"""
attempt two at kata found here
https://www.codewars.com/kata/the-road-kill-detective/train/python
"""
def road_kill(photo):
ANIMALS = ['aardvark', 'alligator', 'armadillo', 'antelope', 'baboon', 'bear', 'bobcat', 'butterfly', 'cat', 'camel', 'cow', 'chameleon', 'dog', 'dolphin', 'duck', 'dragonfly', 'eagle', '... |
n = int(input())
a = [int(i) for i in input().split()]
a_with_index = []
for i, v in enumerate(a):
a_with_index.append((v, str(i + 1)))
print(' '.join(v[1] for v in sorted(a_with_index)))
|
print ('Enter Your Name')
person = input()
print ('Hello ' + person)
|
from lib2to3 import fixer_base, pytree, patcomp
from lib2to3.pgen2 import token
from lib2to3.fixer_util import Leaf
"""
Fixes:
str
into:
unicode
"""
class FixStr(fixer_base.BaseFix):
PATTERN = """
'str'
"""
def transform(self, node, results):
node.value = 'unicode'
return... |
import datetime
import logging
from shapely.wkt import loads
logger = logging.getLogger(__name__)
def create_s1_product_specs(product_type='*', polarisation='*', beam='*'):
'''A helper function to create a scihub API compliant product specs string
Args:
product_type (str): the product type to look ... |
import json
import sys
import re
from difflib import SequenceMatcher
class HelsinkiGeocoder():
def __init__(self, addr_datafile, filter_func=None):
self.filter_func = filter_func
self.load_data(addr_datafile)
self.pattern = re.compile("^([^\d^/]*)(\s*[-\d]*)(\s*[A-ö]*)")
def argsort(se... |
#!/usr/bin/env python
from argparse import ArgumentParser
from pathlib import Path
from shutil import move
from sys import stderr
import regex as re
remap_dict = {}
remap_dict['cross-lingual'] = {}
remap_dict['cross-lingual']['e'] = 'i'
remap_dict['cross-lingual']['ʋ'] = 'v'
parser = ArgumentParser(
descrip... |
# this is a script for generating all text representaions in ./DATA file.
# This is for accelerating the code.
from all_representations import all_text_representation
from clusters import cluster, DA_icsi_list
# All scenario based extractive summaries in AMI
DA_ami_list = [i+1 for i in range(151)]
for j in [9, 24, 1... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 11:25:42 2020
@author: ted
"""
import numpy as np
import pandas as pd
import os
import xarray as xr
dirname = os.path.dirname(__file__)
ARfilepath = os.path.join(dirname, 'ars_6h_daily_0to70S_100Eto120W_025025_197909to201808')
Rainfall_path = os.path.join... |
# -*- coding: utf-8 -*-
#
# rtk.tests.fmea.TestCause.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 Andrew Rowland andrew.rowland <AT> reliaqual <DOT> com
"""Test class for testing the Cause class."""
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(dirna... |
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from ledger.accounts import models
from django.contrib.auth.models import Group
from ledgergw import models as ledgergw_models
from ledgergw import common
from django.db.models import Q
import json
import ipaddress
... |
import enum
import os
import glob
import re
# ディレクトリーを選んでください
while True:
print("""Which directory?
Example: .""")
# C:\muzudho\picture\2021-08-pg
path = input()
os.chdir(path)
# フィル名を一覧します
print(f"""Current directory: {os.getcwd()}
Files
-----""")
files = glob.glob("./*")
... |
import pytest
from flask import Flask
from pynamodb.connection.base import Connection
from flask_pynamodb import PynamoDB
def test_invalid_app_at_init():
with pytest.raises(TypeError) as err:
PynamoDB("invalid app instance")
assert str(err.value) == "Invalid Flask app instance."
def test_invalid_a... |
import argparse
import itertools
import logging
import os
import random
import sys
from timeit import default_timer as timer
import pandas as pd
import psutil
import pyklb
import compress_zarr
def build_compressors(threads):
# We only have 2 choices
codecs = ["bzip2", "zlib"]
opts = []
for c, t in i... |
import inspect
from decorator import decorator
import torch
from torch import nn
from torchdrug import data
class cached_property(property):
"""
Cache the property once computed.
"""
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __get__(self, obj, ... |
#Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
Get the median models
Input a list of clones
Compute the probability of observing each clone
'''
import os
import sys
import numbers
import re
from math import log10, factorial
import cPickle as pickle
import gzip
import numpy a... |
# REFERENCE (python requests): https://realpython.com/python-requests/
# REFERENCE (Hacker News API): https://github.com/HackerNews/API
print("Hacker News CLI by Topher Pedersen")
print("loading...")
from lxml import html
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup
story_content ... |
import copy
import datetime
import logging
from .config import config
from .fetch.federal_holidays import FederalHolidays
from .fetch.fixed_feasts import FixedFeasts
from .fetch.floating_feasts import FloatingFeasts
from .fetch.moveable_feasts import MoveableFeasts
from .season import YearIterator
from .static import ... |
# import pandas, numpy, and matplotlib
import pandas as pd
from feature_engine.encoding import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_regression,\
mutual_info_regression
pd.set_option('dis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.