text string | size int64 | token_count int64 |
|---|---|---|
from typing import Union
from scipy.spatial.qhull import Delaunay
from shapely.geometry import LineString
from subsurface.structs.base_structures import StructuredData
import numpy as np
try:
import segyio
segyio_imported = True
except ImportError:
segyio_imported = False
def read_in_segy(filepath: str, ... | 2,394 | 783 |
#生成器的创建,区分迭代器、生成器、推导式、生成器表达式
l_01 = [x for x in range(10)] #列表推导式
print(l_01)
l_02 = (x for x in range(10)) #列表生成器表达式
print(l_02)
class Fib:
def __init__(self):
self.prev = 0
self.curr = 1
def __iter__(self): #Fib是迭代对象, 因为Fib实现了__iter__方法 -->类/对象
return self
def __next__(self... | 1,069 | 516 |
#!/bin/python
# should be started from project base directory
# helper script to regenerate helm chart file: partial of charts/external-dns-management/templates/deployment.yaml
import re
import os
helpFilename = "/tmp/dns-controller-manager-help.txt"
rc = os.system("make build-local && ./dns-controller-manager --he... | 2,290 | 831 |
from MDP import MDP
import unittest
class MDPTestCase(unittest.TestCase):
def test_small1(self):
lst = [['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd']]
self.__printInput(lst)
mdp = MDP(lst)
mdp.run()
# Get the result Transition Probabilities (dictionary)
tp = mdp.getTrans... | 1,353 | 509 |
# Generated by Django 2.2.10 on 2020-05-02 05:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('purchases', '0008_auto_20200430_1617'),
]
operations = [
migrations.RenameField(
model_name='itempurchase',
old_name='suppl... | 379 | 142 |
def musixmatch():
with open('musixmatch.txt', 'r') as key:
return key.readline()
| 97 | 33 |
from pylayers.gis.layout import *
from pylayers.antprop.signature import *
from pylayers.antprop.channel import *
import pylayers.signal.waveform as wvf
import networkx as nx
import numpy as np
import time
import logging
L = Layout('WHERE1_clean.ini')
#L = Layout('defstr2.ini')
try:
L.dumpr()
except:
L.build()... | 2,750 | 1,454 |
import dash
from dash import Output, Input, dcc
from dash import html
from tabs import tab1, tab2
# from tab2_callbacks import tab2_out, upload_prediction, render_graph2
import flask
server = flask.Flask(__name__) # define flask app.server
external_stylesheets = [
{
"href": "https://fonts.googleapis.com... | 2,261 | 676 |
# REMISS
for i in range(int(input())):
A,B = map(int,input().split())
if A>B: print(str(A) + " " + str(A+B))
else: print(str(B) + " " + str(A+B)) | 158 | 74 |
__copyright__ = """
Copyright (C) 2020 George N Wong
Copyright (C) 2020 Zachary J Weiner
"""
__license__ = """
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 withou... | 2,260 | 760 |
a = [1, 2, 3, 4, 5]
b = a[:3]
print(b)
print(a) | 47 | 35 |
from charset_normalizer import from_path, normalize
results = from_path('original\BIOMD0000000424\BIOMD0000000424_url.xml')
best = str(results.best())
normalize('original\BIOMD0000000424\BIOMD0000000424_url.xml')
| 216 | 105 |
import datetime
import re
from configparser import ConfigParser
from smtplib import SMTPException
from django import forms
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from djan... | 9,812 | 2,725 |
# Copyright 2020 Huawei Technologies 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 applicable law or agreed to... | 3,300 | 1,010 |
#!/usr/bin/env python3.6
# pylint: disable=C0103
"""
Metering client for S3.
"""
from .client import Meterer
class S3Meterer(Meterer):
"""
Meter an S3 bucket.
"""
s3_url_prefix = "s3://"
def __init__(self, cache, boto_session=None, cloudwatch_namespace=None):
"""
S3Meterer(cache, ... | 2,588 | 791 |
from unittest import TestCase
from evaluate import Calculator
calc = Calculator()
class TestCalculator(TestCase):
def test_evaluate_01(self):
self.assertEqual(calc.evaluate(string='127'), 127)
def test_evaluate_02(self):
self.assertEqual(calc.evaluate(string='2 + 3'), 5)
d... | 984 | 391 |
from .comment import Comment
from .line import Line
from .unknown import Unknown
from .edge import Edge
from .gap import Gap
from .custom_record import CustomRecord
from .fragment import Fragment
from .header import Header
from .segment import Segment
from . import group
| 272 | 67 |
import os
import lxml.etree as et
import pandas as pd
import numpy as np
import regex as re
def get_element_text(element):
"""
Extract text while
-skipping footnote numbers
-Adding a space before and after emphasized text
"""
head = element.text if element.tag != 'SU' else ''
child = ' '.... | 21,546 | 6,870 |
"""
Script to generate a custom list of stopwords that extend upon existing lists.
"""
import json
import spacy
from urllib.request import urlopen
from itertools import chain
def combine(*lists):
"Combine an arbitrary number of lists into a single list"
return list(chain(*lists))
def get_spacy_lemmas():
... | 3,960 | 1,348 |
'''
@author: Carl Andersson
'''
import sys
import numpy as np
import tensorflow as tf
import processdata
import time
import scipy.io
# Preformfs a custom matrix multiplication for all matrices in a batch
def batchMatMul(x: tf.Tensor, y: tf.Tensor, scope="batchMatMul"):
return tf.map_fn(lambda inx: tf.tensordo... | 10,081 | 3,691 |
# -*- coding: utf-8 -*-
# @Time : 18/12/10 上午10:27
# @Author : L_zejie
# @Site :
# @File : setup.py.py
# @Software: PyCharm Community Edition
from setuptools import setup, find_packages
setup(
name="DynamicPool",
packages=find_packages(),
version='0.14',
description="动态任务阻塞线程/进程池",
autho... | 586 | 231 |
#!/usr/bin/env py.test
"""
Test SinglyLinkedList class.
"""
import copy
import unittest
from py_alg_dat import singly_linked_list
class TestSinglyLinkedList(unittest.TestCase):
"""
Test SinglyLinkedList class.
"""
def setUp(self):
self.list1 = singly_linked_list.SinglyLinkedList()
... | 28,738 | 10,266 |
"""This module implements the MessageService
The MessageService enables sending and receiving messages
"""
import param
class MessageService(param.Parameterized):
"""The MessageService enables sending and receiving messages"""
| 243 | 57 |
import urllib.parse
import time
import hashlib
import hmac
from bravado.requests_client import Authenticator
class APIKeyAuthenticator(Authenticator):
"""?api_key authenticator.
This authenticator adds BitMEX API key support via header.
:param host: Host to authenticate for.
:param api_key: API key.
... | 2,448 | 798 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
# Load the Heroku environment.
from herokuapp.env import load_env
load_env(__file__, "{{ app_name }}")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
from django.core.management import execu... | 382 | 131 |
import unittest
import indextools
def is_prime(n):
return n > 1 and all(n % i != 0 for i in range(2, n))
class PrimeTest(unittest.TestCase):
def test_primes(self):
int_space = indextools.RangeSpace(50)
prime_space = indextools.SubSpace(int_space, is_prime)
values = (2, 3, 5, 7, 11, ... | 477 | 202 |
import base64
import pathlib
from las import Client
from lascli.util import nullable, NotProvided
def encode_avatar(avatar):
return base64.b64encode(pathlib.Path(avatar).read_bytes()).decode()
def list_users(las_client: Client, max_results, next_token):
return las_client.list_users(max_results=max_results... | 2,522 | 866 |
#!/usr/bin/env python3
def hello(**kwargs):
print(f'Hello')
if __name__ == '__main__':
hello(hello())
| 114 | 46 |
from .models import db, User
from m import Router
from m.utils import jsonify
router = Router(prefix='')
@router.route('/', methods=['POST'])
def home(ctx, request):
name = request.json().get('name')
user = User(name=name)
db.session.add(user)
try:
db.session.commit()
except Exception as ... | 619 | 211 |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. 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... | 4,609 | 1,588 |
#!/usr/bin/env python3
with open("dnsservers.txt", "r") as dnsfile:
for svr in dnsfile:
svr = svr.rstrip('\n')
if svr.endswith('org'):
with open("org-domain.txt", "a") as srvfile:
srvfile.write(svr + "\n")
elif svr.endswith('com'):
with open("com-dom... | 389 | 142 |
from cement.core.controller import CementBaseController, expose
class TowerController(CementBaseController):
class Meta:
label = 'base'
stacked_on = 'base'
stacked_type = 'nested'
description = "Tower"
@expose(hide=True)
def default(self):
self.app.args.print_help(... | 322 | 98 |
import io
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/drive.met... | 1,113 | 365 |
# -*- coding: utf-8 -*-
import os
import sys
from pyzabbix import ZabbixMetric, ZabbixSender
from lumbermill.BaseThreadedModule import BaseThreadedModule
from lumbermill.utils.Buffers import Buffer
from lumbermill.utils.Decorators import ModuleDocstringParser
from lumbermill.utils.DynamicValues import mapDynamicValue
... | 5,471 | 1,501 |
#!/usr/bin/env python2
# coding: utf-8
import logging
from collections import OrderedDict
from geventwebsocket import Resource
from geventwebsocket import WebSocketApplication
from geventwebsocket import WebSocketServer
import k3utfjson
from k3cgrouparch import account
global_value = {}
logger = logging.getLogger(... | 1,771 | 536 |
#!/usr/bin/python
#author: zhaofeng-shu33
import numpy as np
from ace_cream import ace_cream
def pearson_correlation(X,Y):
return (np.mean(X*Y, axis=0) -np.mean(X, axis = 0)* np.mean(Y, axis = 0)) / ( np.std(X, axis = 0) * np.std(Y, axis = 0))
if __name__ == '__main__':
N_SIZE = 1000
ERROR_PROBABILITY = ... | 1,171 | 533 |
#!/usr/bin/env python3
import sys
from converter import DotConverter
filter_size = int(input("Filter size? >> "))
colors = int(input("Number of colors? >> "))
dtcv = DotConverter(filter_size=filter_size, colors=colors)
path = input("File name? >> ")
dtcv.load(path)
dtcv.convert()
dtcv.show()
select = input("Save thi... | 446 | 159 |
"""Client for internal REST APIs."""
from copy import copy
from pathlib import Path
from urllib.parse import quote, urlparse
import time
import requests
from mahiru.definitions.assets import Asset
from mahiru.definitions.execution import JobResult
from mahiru.definitions.policy import Rule
from mahiru.definitions.wor... | 5,148 | 1,522 |
import numpy as np
import cv2
from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit
class ImageDataset (object):
class ImageAccessor (object):
def __init__(self, dataset):
self.dataset = dataset
def __len__(self):
return len(self.dataset.paths)
... | 4,266 | 1,376 |
# 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.
import logging
import unittest
from collections import namedtuple
from classy_vision.generic.distributed_util import set_cpu_device
from param... | 2,106 | 697 |
from pytti.LossAug import MSELoss, LatentLoss
import sys, os, gc
import argparse
import os
import cv2
import glob
import math, copy
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from PIL import Image
import imageio
import matplotlib.pyplot as plt
from pytti.Note... | 9,915 | 3,846 |
# Generated by Django 3.1.7 on 2021-03-19 15:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("track", "0021_auto_20200915_1528"),
]
operations = [
migrations.RemoveField(
model_name="track",
name="parser",
),
... | 394 | 140 |
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
res = 0
q = deque([root])
while q:
node = q.popleft()
if node.left:
if not node.left.left and not node.left.right:
res += no... | 451 | 129 |
'''
Name: color_segmentation.py
Version: 1.0
Summary: Extract plant traits (leaf area, width, height, ) by paralell processing
Author: suxing liu
Author-email: suxingliu@gmail.com
Created: 2018-09-29
USAGE:
python3 color_kmeans_vis.py -p /home/suxingliu/plant-image-analysis/sample_test/ -i 01.jpg -m 01_seg... | 6,123 | 2,060 |
import pandas as pd
import matplotlib.pyplot as plt
import pickle
df = pd.read_json('result.json',lines=True)
print(df) | 120 | 40 |
# to run the metadata validation process via some ec2 and an rds connection
| 77 | 19 |
import csv
import math
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn.cross_validation import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction import text
from sklearn import metrics
from sklearn.metrics import roc_curve,... | 5,432 | 1,927 |
from chat_manager_api.categories.base import BaseAPICategory
from chat_manager_api.models import account
class AccountAPICategory(BaseAPICategory):
def get_web_hook_info(self) -> account.GetWebHookInfo:
return self.api.make_request("account.getWebHookInfo", dataclass=account.GetWebHookInfo)
async de... | 1,108 | 359 |
import logging
from django.core.exceptions import ImproperlyConfigured
from rest_framework.exceptions import APIException
from rest_framework.views import APIView
from rest_framework.response import Response
from .checks import (
internal_services,
external_services,
)
logger = logging.getLogger('hhs_server.%s... | 1,674 | 438 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Red Hat, Inc
#
# 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 req... | 9,623 | 3,026 |
from machine import Pin
import time
from led import LED
tube_btn = Pin(21, Pin.IN, Pin.PULL_UP)
sys_led = Pin(25, Pin.OUT)
print('Blinking LED to power check (no LED? Check LED batteries and/or script).')
LED.led_blink(5)
print('Blink code finish - Listening for presses.')
while True:
first = tube_btn.value()
... | 524 | 182 |
from nipype.interfaces import utility as util
from nipype.pipeline import engine as pe
from .interfaces import dsi_studio as dsi
import nipype.interfaces.diffusion_toolkit as dtk
from nipype.algorithms.misc import Gunzip
import os.path
def create_pipeline(name="dsi_track", opt="", ensemble=""):
parameters = {'nos... | 2,285 | 709 |
"""
Sponge Knowledge Base
Remote API security
"""
def configureAccessService():
# Configure the RoleBasedAccessService.
# Simple access configuration: role -> knowledge base names regexps.
remoteApiServer.accessService.addRolesToKb({ "ROLE_ADMIN":[".*"], "ROLE_ANONYMOUS":["boot", "python"]})
# Simple... | 780 | 245 |
'''
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddd... | 753 | 246 |
import pandas as pd
from phc.easy.ocr.suggestion import (expand_array_column,
expand_medication_administrations,
frame_for_type)
sample = expand_array_column(
pd.DataFrame(
[
{
"suggestions": [
... | 8,540 | 2,403 |
import json
from bs4 import BeautifulSoup
import re
for i in range(0, 39):
with open(f'./KorQuAD/korquad2.1_train_{i}.json', 'r', encoding='utf-8') as f:
js = json.load(f)
texts = []
for i in range(len(js['data'])):
text = js['data'][i]['raw_html']
soup = BeautifulSoup(text, 'html5lib')
text =... | 482 | 202 |
from django.contrib import admin
from .models import Auction, Lot, Bid
class BidAdmin(admin.ModelAdmin):
readonly_fields = (
'user',
'auction',
'bid_amount',
'bid_time',
)
admin.site.register(Auction)
admin.site.register(Lot)
admin.site.register(Bid, BidAdmin)
| 312 | 109 |
"""Defines the application configuration for the source application"""
from __future__ import unicode_literals
from django.apps import AppConfig
class SourceConfig(AppConfig):
"""Configuration for the source app
"""
name = 'source'
label = 'source'
verbose_name = 'Source'
def ready(self):
... | 922 | 248 |
import os
from aim.web.api.utils import APIRouter # wrapper for fastapi.APIRouter
from fastapi.responses import FileResponse
from aim.web.api.projects.project import Project
general_router = APIRouter()
@general_router.get('/static-files/{path:path}/')
async def serve_static_files(path):
from aim import web
... | 1,556 | 475 |
import threading
import enum
import os
import sys
import copy
import json
import asyncio
import attr
import uuid
import functools
import datetime
import multiprocessing
from time import monotonic
import time
import copy
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from async_timeout i... | 38,441 | 10,971 |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory"
" containing %r. It appears you've customized things.\n"
"You'll have to... | 549 | 178 |
import os
import sys
import shutil
import asyncio
import aioboto3
from glob import glob
from PIL import Image
from fnmatch import fnmatch
from src.secrets import (
SPACES_REGION,
SPACES_BUCKET,
SPACES_PREFIX,
SPACES_ENDPOINT_URL,
SPACES_ACCESS_KEY,
SPACES_SECRET_KEY
)
from src.format import (... | 3,981 | 1,220 |
import re
import operator
from collections import namedtuple
SCHEMA_TYPES = {'str', 'int', 'bool'}
ROWID_KEY = '_rowid'
class Literal(namedtuple('Literal', 'value')):
@classmethod
def eval_value(cls, value):
if not isinstance(value, str):
raise ValueError(f"Parameter {value} must be a str... | 17,599 | 5,918 |
""" Cisco_IOS_XR_ipv4_telnet_mgmt_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR ipv4\-telnet\-mgmt package configuration.
This module contains definitions
for the following management objects\:
telnet\: Global Telnet configuration commands
Copyright (c) 2013\-2016 by Cisco Systems, I... | 6,318 | 2,052 |
"""
A module for calculating the relationship (or distance) between 2 strings.
Namely:
- edit_distance()
- needleman_wunsch()
- align()
- coverage()
"""
from typing import Callable, Tuple, List
from enum import IntEnum
from operator import itemgetter
from functools import lru_cache
import unittest
cl... | 7,027 | 2,334 |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import math
import datetime
import time
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
class Indicators():
def __init__(self, dataframe, params = []):
self.dataframe = dataframe
self.params = params
... | 10,391 | 3,864 |
# -*- coding: utf-8 -*-
"""
Showcases input / output *IES TM-27-14* spectral data XML files related
examples.
"""
import os
import colour
from colour.utilities import message_box
RESOURCES_DIRECTORY = os.path.join(os.path.dirname(__file__), 'resources')
message_box('"IES TM-27-14" Spectral Data "XML" File IO')
mes... | 1,785 | 650 |
from .Announce import get_announce, announce_to_txt
from .Torrent import get_torrent_file, parse_torrent_file
from .Tracker import get_peerlist, save_peerlist | 158 | 55 |
# Copyright 2021 The OpenBytes Team. 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 appl... | 2,577 | 815 |
"""
Name : c14_11_rainbow_callMaxOn2_viaSimulation.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : Yuxing Yan
Date : 6/6/2017
email : yany@canisius.edu
paulyxy@hotmail.com
"""
import scipy as sp
from scipy import zeros, sqrt, shape
#
sp.rand... | 1,505 | 638 |
from db_repo import *
mydb=database_flaskr()
rows=mydb.yatraWPA() | 67 | 29 |
import os
from os.path import join
INVESTIGATE = False # Records coverages and saves them. Generates a plot in the end. Do not use with automate.
TEST_OUTSIDE_FUZZER = False # Runs FATE as standalone (1+1) EA
BLACKBOX = True and TEST_OUTSIDE_FUZZER # Disables white-box information such as thresholds and feat imp.
F... | 13,823 | 5,544 |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring,unused-import,reimported
import io
import json
import pytest # type: ignore
import xmllint_map_html.cli as cli
import xmllint_map_html.xmllint_map_html as xmh
def test_main_ok_minimal(capsys):
job = ['']
report_expected = ''
assert cli.main(arg... | 417 | 159 |
import os
# import json
from scipy.io import loadmat
import argparse
import mat4py
import h5py
import json_tricks as json
parser = argparse.ArgumentParser(description="Convert .mat to .json file")
parser.add_argument("-ddir", "--data_dir", type=str, default="",
help="Data directory of .mat files")
... | 1,668 | 536 |
import sys
import re
import math
with open(sys.argv[1]) as test_cases:
for test in test_cases:
t = re.findall("[+-]?\d+", test)
nums = [int(x) for x in t]
print int(math.sqrt((nums[0]-nums[2]) * (nums[0]-nums[2]) + (nums[1]-nums[3]) * (nums[1]-nums[3]))) | 261 | 131 |
import logging
from functools import partial
from typing import Any, Callable, Dict, Optional, Sequence, Union
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow_provider_kafka.hooks.producer import KafkaProducerHook
from airflow_provider_kafka.shared_utils import get... | 4,606 | 1,244 |
"""Test is_boundary_not_x_monotone method in WeightedPointBoundary."""
# Standard
from typing import List, Any
from random import randint
# Models
from voronoi_diagrams.models import (
WeightedSite,
WeightedPointBisector,
WeightedPointBoundary,
)
# Math
from decimal import Decimal
class TestWeightedPoin... | 2,171 | 726 |
import os
import torchvision
import torchvision.models as models
from src.core.config import config
class Model():
def __init__(self, model=None, classes=None, device=None):
""" Initializes a model that is predefined or manually added.
Most models are taked from Pytorch's torchvision. These model... | 1,202 | 329 |
# 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 or agreed to i... | 46,242 | 12,288 |
#!/usr/bin/env python
'''
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")... | 1,768 | 534 |
from europython import hello
hello("Alisa")
| 44 | 13 |
#!/usr/bin/env python3
import sys
import csv
import datetime
import math
from tabulate import tabulate
import scipy.stats as st
from tqdm import tqdm
import numpy as np
np.seterr(all='ignore')
def isfloat(val):
try:
val = float(val)
if math.isnan(val):
return False
return ... | 8,587 | 2,954 |
import os
import shutil
from modulefinder import ModuleFinder
def main():
temp_dir = "package_temp"
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
os.makedirs(temp_dir)
for py in ["index.py", "notifier.py"]:
src, dst = py, os.path.join(temp_dir, py)
print("copy '%s' to '... | 1,446 | 505 |
import numpy as np
def flip_axis(x_in, axis):
x_out = np.zeros(x_in.shape, dtype=x_in.dtype)
for i, x in enumerate(x_in):
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x_out[i] = x.swapaxes(0, axis)
return x_out
def flip_axis_fra(x, flipping_axis):
pattern = [flipping_... | 894 | 371 |
##-*****************************************************************************
##
## Copyright (c) 2009-2011,
## Sony Pictures Imageworks, Inc. and
## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
##
## All rights reserved.
##
## Redistribution and use in source and binary forms, with... | 6,932 | 2,577 |
# -*- coding: utf-8 -*-
#
# 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, software
... | 3,625 | 996 |
""" Defines the Note repository """
import random
import string
import time
import bcrypt
from sqlalchemy.orm import load_only
from werkzeug.exceptions import Forbidden, UnprocessableEntity
from models import Note
class NoteRepository:
@staticmethod
def create(user, notebook_id, title, content):
""... | 1,635 | 482 |
'''tzinfo timezone information for Africa/Ndjamena.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Ndjamena(DstTzInfo):
'''Africa/Ndjamena timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Ndjamena'
... | 575 | 283 |
import logging
import os
import shutil
import tempfile
from git import Repo
from .ast_analysis import _get_all_names, _get_all_func_names, _generate_trees
from .ntlk_analysis import _get_verbs_from_function_name, _get_nouns_from_function_name
from .utils import _get_count_most_common, _get_converted_names, _convert_t... | 5,988 | 1,769 |
import pandas as pd
from fuzzywuzzy import process
import Levenshtein as lev
import numpy as np
import openpyxl
# -----------------------code for first csv file-------------------------------------------
buyer_df = pd.read_csv("./results/CD_21_05/final2.csv", usecols=['PRODUCTS','UNITS', 'BATCHES', 'EXPIRY'])
# aggreg... | 2,482 | 973 |
import numpy as np
# Place a random ship on the given board of the given length, making sure it does not intersect
# with anything in no_intersect
def place_random_ship(board, length, no_intersect):
placed = False
while not placed:
vertical = bool(np.random.randint(0, 2)) # Gives us a random boolean
... | 2,719 | 857 |
import base64
import hashlib
import ldap
import logging
import time
from assemblyline.common.str_utils import safe_str
from assemblyline_ui.config import config, CLASSIFICATION
from assemblyline_ui.helper.user import get_dynamic_classification
from assemblyline_ui.http_exceptions import AuthenticationException
log = ... | 8,449 | 2,563 |
#!/usr/bin/env python2.7
from __future__ import absolute_import
import sys
def run_dbwriter(argv):
from tangos import parallel_tasks, core
from tangos.tools.property_writer import PropertyWriter
writer = PropertyWriter()
writer.parse_command_line(argv)
parallel_tasks.launch(writer.run_calculation_... | 537 | 171 |
from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from base64 import b64encode
class Pet:
db = 'pawfosterfamily'
def __init__(self,data):
self.id = data['id']
self.img = data['img']
self.name = data['name']
self.age = data['age']
self.f... | 3,107 | 1,049 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v6/proto/resources/shared_set.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.p... | 11,046 | 4,184 |
import wallycore as wally
from . import exceptions
from gaservices.utils import h2b
wordlist_ = wally.bip39_get_wordlist('en')
wordlist = [wally.bip39_get_word(wordlist_, i) for i in range(2048)]
def seed_from_mnemonic(mnemonic_or_hex_seed):
"""Return seed, mnemonic given an input string
mnemonic_or_hex_se... | 2,722 | 999 |
def elastic_rate(
hv,
hs,
v,
s,
rho,
mu,
nx,
dx,
order,
t,
y,
r0,
r1,
tau0_1,
tau0_2,
tauN_1,
tauN_2,
type_0,
forcing,
):
# we compute rates that will be used for Runge-Kutta time-stepping
#
import first_derivative_sbp_operators
... | 4,838 | 2,229 |
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
# Basic model functions
def pdf(x_i, sigma_i=1, mu=0):
"""Returns the marginal (population) pdf of X_i ~ Normal(mu, sigma_i^2)."""
return st.norm.pdf(x_i, scale=sigma_i, loc=mu)
def stable_rs(r):
"""Calculates r_s from r unde... | 16,752 | 5,634 |
# coding: UTF-8
import torch
from tqdm import tqdm
import time
from datetime import timedelta
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
PAD, CLS = '[PAD]', '[CLS]' # padding符号, bert中综合信息符号
class FocalLoss(nn.Module):
"""smo
This is a implemen... | 6,661 | 2,189 |
# -*- coding: utf-8 -*-
"""补充 8105 中汉字的拼音数据"""
from collections import namedtuple
import re
import sys
from pyquery import PyQuery
import requests
re_pinyin = re.compile(r'拼音:(?P<pinyin>\S+) ')
re_code = re.compile(r'统一码\w?:(?P<code>\S+) ')
re_alternate = re.compile(r'异体字:\s+?(?P<alternate>\S+)')
HanziInfo = namedtup... | 2,596 | 908 |