text string | size int64 | token_count int64 |
|---|---|---|
import torch
from torch import nn
import torch.optim as optim
import torch.multiprocessing as mp
import numpy as np
import time
class MPManager(object):
def __init__(self, num_workers):
"""
manage a single-instruction-multiple-data (SIMD) scheme
:param int num_workers: The number of proces... | 875 | 248 |
# Link class
class Link:
## Constructor ##
def __init__(self, text = "None", url = "None", status_code = 000): # Not the keyword 'None' so it will still print something
# Dictionary of URL-related content
self.text = text
self.url = url
self.status_code = status_code
# ... | 1,766 | 519 |
import tensorflow as tf
from tensorflow.keras.layers import Layer, Dense, Reshape, Embedding, Concatenate, Conv2D
from tensorflow.keras.models import Model
import numpy as np
class SelfAttention(Model):
def __init__(self, d_model, spatial_dims, positional_encoding=True, name="self_attention"):
'''
... | 3,911 | 1,374 |
"""This module contains functionality for all the sampling methods supported in UQpy."""
import sys
import copy
import numpy as np
from scipy.spatial.distance import pdist
import scipy.stats as sp
import random
from UQpy.Distributions import *
import warnings
def init_sm(data):
###################################... | 62,335 | 16,812 |
#!/usr/bin/env python3
import argparse
import pono
import smt_switch as ss
from smt_switch.primops import And, BVAdd, BVSub, Equal, Ite
from smt_switch.sortkinds import BOOL, BV
def build_simple_alu_fts(s:ss.SmtSolver)->pono.Property:
'''
Creates a simple alu transition system
@param s - an SmtSolver from ... | 5,366 | 1,839 |
from util.util import autoregister
autoregister('lrs') | 55 | 18 |
# See also the methods already implemented we have in cm for ssh management
# I think you reimplemented things that already exists.
# see and inspect cloudmesh.common
import os
from os.path import expanduser
# see content of path_expand it does expanduser as far as I know
from cloudmesh.common.util import path_expand
... | 2,279 | 623 |
# -*- coding: utf-8 -*-#
'''
# Name: dnn_regression-keras
# Description:
# Author: super
# Date: 2020/6/2
'''
from HelperClass2.MnistImageDataReader import *
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import os
os.environ['KMP_DUPLICATE... | 1,901 | 731 |
from .train import main
| 24 | 7 |
# MIT License
# Copyright (c) 2020 Mitchell Lane
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... | 2,825 | 800 |
import csv
def save_minimal_pairs(output_filename, to_output, write_header=True):
if isinstance(output_filename, str):
outf = open(output_filename, mode='w', encoding='utf-8-sig', newline='')
needs_closed = True
else:
outf = output_filename
needs_closed = False
writer = cs... | 944 | 303 |
from typing import Callable
from jax import lax
from flax import linen as nn
class MultiTaskDense(nn.Module):
features: int
n_tasks: int
kernel_init: Callable = nn.initializers.lecun_normal()
bias_init: Callable = nn.initializers.zeros
@nn.compact
def __call__(self, inputs):
kernel = ... | 666 | 228 |
import os
import shutil
import subprocess
import sys
from pathlib import Path
from unittest import mock
import pytest
from requests import exceptions as requests_exceptions
from briefcase.console import Log
from briefcase.exceptions import BriefcaseCommandError, MissingToolError, NetworkFailure
from briefcase.integra... | 14,658 | 4,802 |
import clr
import sys
sys.path.append('C:\Program Files (x86)\IronPython 2.7\Lib')
import os
import math
clr.AddReference('acmgd')
clr.AddReference('acdbmgd')
clr.AddReference('accoremgd')
# Import references from AutoCAD
from Autodesk.AutoCAD.Runtime import *
from Autodesk.AutoCAD.ApplicationServices import *
from Aut... | 1,094 | 401 |
"""
.. module:: Katna.config
:platform: Platfrom Independent
:synopsis: This module defines some helpful configuration variables
"""
import os
# # Configuration parameters for Image class
class Image:
# default value by which image size to be reduces for processing
down_sample_factor = 8
# Debug fl... | 11,751 | 3,963 |
# -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
def closeAll():
""" closeAll()
Closes all figures.
"""
for fig in vv.BaseFigure._figures.va... | 350 | 125 |
#{{{ Import
import numpy as np
pi = np.pi
#}}}
#{{{ Snell's Law
def deflection_angle(theta, n1, n2, deg=True):
"""Calculate deflection angle according to Snell's law.
Parameters
----------
theta : float
Angle of incidence.
n1 : float
Refractive index of the first medium.
n2 : ... | 15,423 | 5,215 |
from . import preprocess | 24 | 6 |
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
n... | 865 | 310 |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | 1,918 | 555 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-01-18 15:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('aggregator', '0032_auto_20190118_1720'),
]
operations = [
# migrations.RenameField(
... | 451 | 172 |
import ntpath
from lead2gold.tools.tool import Tool
from lead2gold.util import pwm2consensus
from lead2gold.util import sequence2pwm
from lead2gold.motif import Motif
class EMD(Tool):
"""Class implementing a EMD search tool motif convertor.
"""
toolName = "EMD"
def __init__(self):
"""Initialize all class attr... | 1,793 | 762 |
# -*- coding: utf-8 -*-
"""Manages custom event formatter helpers."""
class FormattersManager(object):
"""Custom event formatter helpers manager."""
_custom_formatter_helpers = {}
@classmethod
def GetEventFormatterHelper(cls, identifier):
"""Retrieves a custom event formatter helper.
Args:
id... | 1,915 | 526 |
# ======================================================================== #
#
# Copyright (c) 2017 - 2020 scVAE 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.apac... | 2,814 | 966 |
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}'
template_close = template_open.replace('{{#','{{/')
kibana_url = (
"{{ctx.metadata.kibana_url}}/app/kibana#/discover?"
"_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,"
"index:'metr... | 5,137 | 1,772 |
#!/usr/bin/env python
"""
ZetCode wxPython tutorial
In this example, we create a wx.ListBox widget.
author: Jan Bodnar
website: www.zetcode.com
last modified: July 2020
"""
import wx
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
... | 2,504 | 1,002 |
'''
Collect results in Quantum ESPRESSO
'''
import sys
import numpy as np
from pymatgen.core import Structure
from . import structure as qe_structure
from ... import utility
from ...IO import pkl_data
from ...IO import read_input as rin
def collect_qe(current_id, work_path):
# ---------- check optimization in ... | 11,210 | 3,510 |
import json
from django.db import connection
from elasticsearch import Elasticsearch
from jobs.models import Job
es_client = Elasticsearch('http://localhost:9200')
def run():
# Create Index
es_client.indices.create(index='jobs')
# Put Mapping
with open("jobs/job.json", "r") as fp:
es_clien... | 778 | 259 |
import warnings
from . import DealFormat
from .. import dto
class BRIFormat(DealFormat):
number_warning = '.bri file format assumes consequent deal numbers from 1'
@property
def suffix(self):
return '.bri'
def parse_content(self, content):
warnings.warn(self.number_warning)
d... | 2,543 | 779 |
import src.sudoku_solver as sudoku_solver
from src.sudoku import Sudoku
correct_sudoku = Sudoku([[9, 5, 7, 6, 1, 3, 2, 8, 4], [4, 8, 3, 2, 5, 7, 1, 9, 6], [6, 1, 2, 8, 4, 9, 5, 3, 7],
[1, 7, 8, 3, 6, 4, 9, 5, 2], [5, 2, 4, 9, 7, 1, 3, 6, 8], [3, 6, 9, 5, 2, 8, 7, 4, 1],
... | 1,766 | 1,107 |
"""Serializers Alquileres"""
#Django REST Framework
from rest_framework import serializers
#Model
from maquinaria.alquileres.models import Alquiler
from maquinaria.maquinas.models import Maquina
class AlquilerModelSerializer(serializers.ModelSerializer):
"""Modelo Serializer de Cliente"""
class Meta:
"""Clase ... | 599 | 242 |
#!/usr/bin/env python
#
# Test RTC_DS1307
import sys
import time
import datetime
import RTC_DS1307
# Main Program
print "Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S")
filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt"
starttime = datetime.datetime.utcnow()
ds1307 = RTC_DS1307.RTC_DS1307(2, 0x... | 660 | 295 |
#!/usr/bin/env python
#
# Created on Nov 14, 2017
# @author: aziz@avinetworks.com, jagmeet@avinetworks.com
#
# AVISDK based Script to get the status and configuration information of the Virtual Services
#
# Requires AVISDK ("pip install avisdk") and PrettyTable ("pip install PrettyTable")
# Usage:- python avi_virtual_s... | 4,536 | 1,492 |
import numpy as np
def projective(coords):
""" Convert 2D cartesian coordinates to homogeneus/projective. """
num = np.shape(coords)[0]
w = np.array([[1], ]*num)
return np.append(coords, w, axis=1)
def cartesian(coords):
""" Convert 2D homogeneus/projective coordinates to cartesian. """
ret... | 1,035 | 361 |
import torch
from tvl_backends.nvdec import nv12_to_rgb
def test_nv12_to_rgb():
w = 3840
h = 2160
nv12 = torch.empty(int(w * h * 1.5), device='cuda:0', dtype=torch.uint8)
for i in range(100):
nv12.random_(0, 256)
rgb = nv12_to_rgb(nv12, h, w)
assert rgb.shape == (3, h, w)
| 316 | 162 |
"""
dxagent.py
This file contains the core of dxagent
@author: K.Edeline
"""
import sched
import time
import signal
import importlib
from .constants import AGENT_INPUT_PERIOD
from .core.ios import IOManager
from .core.daemon import Daemon
from .input.sysinfo import SysInfo
from .input.bm_input import BMWatcher
... | 3,289 | 1,072 |
from django.db import models
from django.utils import timezone
import os
#BLOGS
class BlogPost(models.Model):
author=models.CharField(max_length=200)
role=models.CharField(max_length=200)
image=models.ImageField(upload_to='blogMedia/')
title=models.CharField(max_length=200)
displayText=models.Te... | 2,410 | 798 |
import requests
import json
import os
from github import Github
BASE = """---
id: default_repositories
title: Default repositories
description: "Default repositories in HACS"
---
<!-- The content of this file is autogenerated during build with script/generate_default_repositories.py -->
"""
github = Github(os.environ... | 1,794 | 558 |
import sys
import typing
def main() -> typing.NoReturn:
n = int(input())
(*t,) = map(int, sys.stdin.read().split())
print(min(t))
main()
| 164 | 70 |
import csv
import sys
#This program was written in Python 3.6.3 by Henry Caushi. You are free to use it for any reason, without my permission, without having to inform myself or anyone else
#This program was was written to aid other programs, by providing a list of all event IDs so that they appear only once
#List o... | 748 | 241 |
c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
| 268 | 100 |
#!/usr/bin/env python
from setuptools import setup
setup(name='django-s3file', use_scm_version=True)
| 102 | 37 |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#440. K-th Smallest in Lexicographical Order
#Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
#Note: 1 ... | 668 | 268 |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
complement = {}
out = []
for i,n in enumerate(nums):
complement[target-n] = i
for i,n in enumerate(nums):
idx = complement.get(n, None)
if idx != None and idx !... | 1,055 | 343 |
import logging
import traceback
import peewee
from flask import request
from east.exceptions import *
from app import app, db
print('TESTING')
class DummyLogger:
def log(self, *args):
pass
def error(self, *args):
pass
logger = DummyLogger()
# logger = logging.getLogger(__name__)
@app.er... | 1,255 | 435 |
import argparse
import os
import math
# import time
import numpy as np
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
import progressbar
from waymo_open_dataset.utils import range_image_utils
from waymo_open_dataset.utils import transform_utils
from waymo_open_dataset.utils import test_utils
from ... | 28,438 | 8,787 |
# -*- coding: utf-8 -*-
#
# Copyright 2019 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... | 1,924 | 575 |
#!/usr/bin/env python
import argparse
import pandas as pd
def main(input_file,output):
pd_data = pd.read_csv(input_file, sep = "\t" )
import pdb
pd_data['last'] = pd_data['FID']
for i in pd_data.index:
pd_data.loc[i,'FID'] = "{}:{}".format(pd_data.loc[i,'FID'],pd_data.loc[i,'IID'])
... | 865 | 311 |
import pytest
import requests
import unittest
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
# giving pytest ac... | 1,288 | 383 |
import collections
import schematics
from export_util import (
template as tpl,
value as val
)
class Normalizer:
"""
Normalizer object formats data into ordered rows using provided template. Templates are building
using `export_lib.template` functionality. First what should be passed into nomral... | 18,923 | 4,738 |
from gwinc.ifo.noises import *
class aLIGO(nb.Budget):
name = "Advanced LIGO"
noises = [
QuantumVacuum,
Seismic,
Newtonian,
SuspensionThermal,
CoatingBrownian,
CoatingThermoOptic,
SubstrateBrownian,
SubstrateThermoElastic,
ExcessGas,
... | 324 | 122 |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 13:52:52 2022
@author: sarangbhagwat
"""
from biorefineries.TAL.system_TAL_adsorption_glucose import *
from matplotlib import pyplot as plt
import numpy as np
column = AC401
#%% Across regeneration fluid velocity and cycle time
def MPSP_at_adsorption_design(v, t):
... | 8,397 | 3,578 |
#To solve Rat in a maze problem using backtracking
#initializing the size of the maze and soution matrix
N = 4
solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ]
def is_safe(maze, x, y ):
'''A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
'''
i... | 1,700 | 688 |
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
import time
import skimage.draw
import image_data
import image_processing as ip
if __name__ == "__main__":
movgen = image_data.all_movies()
for em,movie in enumerate(movgen):
framegen = image_data.all_frames(movie)
... | 1,014 | 378 |
import numpy as np
def bin_to_dec(bin_str):
"""Convert a string of bits to decimal."""
result = 0
for i, bit in enumerate(bin_str[::-1]):
result += int(bit) * 2**i
return result
if __name__ == "__main__":
data = []
with open("input", 'r') as file:
for line in file:
... | 875 | 321 |
from m5stack import *
from m5stack_ui import *
from uiflow import *
from ble import ble_uart
import face
screen = M5Screen()
screen.clean_screen()
screen.set_screen_bg_color(0x000000)
mb_click = None
rb_click = None
lb_click = None
snd_val = None
st_mode = None
stval = None
prval = None
faces_encode = face.get(face... | 5,535 | 2,820 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import shutil
import argparse
import subprocess
import numpy as np
import contextlib
import onnx
from cvi_toolkit.utils.mlir_shell import *
from cvi_toolkit.utils.intermediate_file import IntermediateFile
@contextlib.contextmanager
def pushd(new_dir):
previous... | 6,250 | 2,142 |
import os
import webapp2
import data
import datetime
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.api import images
from google.appengine.api import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import ndb... | 12,181 | 3,588 |
from polyphony import testbench
class C:
def __init__(self, x):
self.x = x
class D:
def __init__(self, c):
self.c = c
def alias02(x):
c0 = C(x)
c1 = C(x*x)
d = D(c0)
result0 = d.c.x == x
d.c = c1
result1 = d.c.x == x*x
c1.x = 0
result2 = d.c.x == 0
d.c = c0... | 500 | 223 |
import inspect
import os
import sys
from random import choice
from typing import List
__author__ = "GLNB"
__copyright__ = "GLNB"
__license__ = "mit"
try:
from .dictionaries import invisible_chars, dict_latin
except ImportError:
from dictionaries import invisible_chars, dict_latin
__location__ = os.path.join... | 7,775 | 3,201 |
for i in range(2):
print(i) # print 0 then 1
for i in range(4,6):
print (i) # print 4 then 5
"""
Explanation:
If only single argument is passed to the range method,
Python considers this argument as the end of the range and the default start value of range is 0.
So, it will print all the numbers starting from 0 an... | 443 | 133 |
#!/usr/bin/env python3
"""Count the frequency of various phrases, given the path to the Python PEPs.
In Python PEPs, the opposite of “subclass” is almost always “base class” — just remember that the builtin is named super(), not base()! Stats:
216 base class
0 child class
10 derived class
12 parent class
372 ... | 1,709 | 562 |
#!/usr/bin/env python
"""
Unit tests for Generalized One-Pass Sweep-line Algorithm
- test_regionsweep_simple
- test_regionsweep_random
"""
from typing import List
from unittest import TestCase
from sources.algorithms import \
RegionSweep, RegionSweepDebug, RegionSweepOverlaps
from sources.core import \
Re... | 2,296 | 838 |
import json
import requests
from rotkehlchen.assets.asset import Asset
from rotkehlchen.constants.timing import DEFAULT_TIMEOUT_TUPLE
from rotkehlchen.errors.misc import RemoteError
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.history.deserialization import deserialize_price
from... | 1,566 | 478 |
def game_main():
### IMPORTS ###
import colorama
from colorama import Fore
from engine import engineScript
from engine import clearScript
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
### ENGINE INITIALIZATION ###
settings = ["widt... | 505 | 172 |
import shutil
from pathlib import Path
from ..tag2label import prepare_df_from_dirs
def prepare_dataset():
shutil.rmtree('datasets', ignore_errors=True)
# dummy datasets e.g. root1 and root2
root1 = Path('datasets/root1')
root1.mkdir(parents=True, exist_ok=True)
root2 = Path('datasets/root2')
... | 1,888 | 728 |
__all__ = ['FavIcon']
from dataclasses import dataclass, field
from html import escape as html_escape
@dataclass
class FavIcon:
href: str
rel: str = "icon"
mimetype: str = "image/x-icon"
rendered: str = field(init=False, repr=False)
def __post_init__(self):
self.rendered = f'<link rel="{s... | 387 | 134 |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.urls import path
from django.views.generic import RedirectView
from .views import *
urlpatterns = [
path('', login_required(assets), name='home'),
path('assets/', login_required(assets), name='assets'),
... | 1,102 | 342 |
from pydantic import BaseModel, EmailStr, HttpUrl, ValidationError
class User(BaseModel):
email: EmailStr
website: HttpUrl
# Invalid email
try:
User(email="jdoe", website="https://www.example.com")
except ValidationError as e:
print(str(e))
# Invalid URL
try:
User(email="jdoe@example.com", web... | 616 | 213 |
""""Mock Webware Transaction class."""
from .Application import Application
class Transaction:
def __init__(self):
self._application = Application()
def application(self):
return self._application
| 226 | 57 |
import tensorflow as tf
from KENN2.layers.residual.KnowledgeEnhancer import KnowledgeEnhancer
class Kenn(tf.keras.layers.Layer):
def __init__(self, predicates, clauses, activation=lambda x: x, initial_clause_weight=0.5, save_training_data=False, **kwargs):
"""Initialize the knowledge base.
:para... | 2,517 | 723 |
# called concatenation sometimes..
str1 = 'abra, '
str2 = 'cadabra. '
str3 = 'i wanna reach out and grab ya.'
combo = str1 + str1 + str2 + str3
# you probably don't remember the song.
print(combo)
# you can also do it this way
print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round... | 518 | 178 |
from lake.top.memory_interface import MemoryPort, MemoryPortType
from lake.top.memory_controller import MemoryController
from kratos import *
from lake.attributes.config_reg_attr import ConfigRegAttr
from lake.passes.passes import lift_config_reg
from lake.modules.reg_fifo import RegFIFO
import kratos as kts
class St... | 14,756 | 4,789 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mdot_rest', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='IntendedAudience',
field... | 3,781 | 1,042 |
from functools4 import lru_cache
import pickle
import copy
class CacheData:
def __init__(self, cache=None, root=None,hit=None,full=None):
self.cache = cache
self.root = root
self.hit = hit
self.full = full
# @lru_cache(maxsize=16)
# def fib(n):
# return n
#
# for x in range(16):
# fib(x)
# p... | 1,145 | 501 |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# using naming on http://www.gslib.com/gslib_help/programs.html
import subprocess
import copy
import pandas as pd
import pygslib
import numpy as np
import os
__addcoord_par = \
""" Parameters for ADDCOORD
***********************
START O... | 4,761 | 1,490 |
import numpy as np
def validate_1d_array(x, size=None):
'''Validate type and dimensions of an object x.'''
assert isinstance(x, np.ndarray), 'Expecting a numpy array.'
assert x.ndim == 1, 'Expecting a one-dimensional array.'
if size is not None:
assert x.size == size, 'Array size is differen... | 1,254 | 395 |
import pytest
from globus_sdk import GCSAPIError, GuestCollectionDocument, MappedCollectionDocument
from tests.common import get_last_request, register_api_route_fixture_file
def test_get_collection_list(client):
register_api_route_fixture_file("gcs", "/collections", "collection_list.json")
res = client.get_... | 6,629 | 2,182 |
#!/usr/bin/env python3
import argparse
import sys
import yaml
import logging
import logging.config
from datetime import datetime
from classes import pcdm,ocr,util
from handler import ndnp
import rdflib
from rdflib import RDF
from lxml import etree as ET
from classes.exceptions import RESTAPIException, DataReadExceptio... | 4,168 | 1,142 |
import collections
class Solution:
def canDivideIntoSubsequences(self, nums: List[int], K: int) -> bool:
return len(nums) >= K * max(v for v in collections.Counter(nums).values())
| 192 | 62 |
"""
所有号码段存入192.168.70.40的mysql
"""
import os
import pymysql
# 获取指定文件夹文件列表
def get_files_name(dir):
all_filename = os.listdir(dir)
return all_filename
# 从文件中提取出号码前缀
def split_number(filename, parents_dir):
print("File name is <{}>".format(filename))
# 读取文件
with open(os.path.join(parents_dir, file... | 1,490 | 618 |
#!/usr/bin/env python
import numpy as np
from mm2d import util
class TrayRenderer(object):
def __init__(self, radius, p_te_e, p_c1e_e, p_c2e_e, P_ew_w):
self.p_lt_t = np.array([-radius, 0])
self.p_rt_t = np.array([radius, 0])
self.p_te_e = p_te_e
self.p_c1e_e = p_c1e_e
sel... | 1,788 | 929 |
from django import forms
from django.utils.translation import ugettext_lazy as _
class LoginForm(forms.Form):
email = forms.CharField(
required=True,
label=_('Email'),
max_length=100,
widget=forms.TextInput(attrs={
'placeholder': _('Your email'),
'autofocus'... | 4,435 | 1,292 |
#!/usr/bin/env python3
# coding=utf-8
"""
@Github: https://github.com/Certseeds
@Organization: SUSTech
@Author: nanoseeds
@Date: 2020-07-12 17:46:45
@LastEditors : nanoseeds
"""
""" CS305_2019F_Remake
Copyright (C) 2020 nanoseeds
CS305_2019F_Remake is free software: you can redistribute it and/or modify
... | 2,780 | 1,022 |
import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(here, '..', '..', '..', 'test_utils'))
from fixtures import event, lambda_context
| 188 | 70 |
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/capstone/")
#from FlaskApp import app as application
#application.secret_key = 'Add your secret key'
| 213 | 70 |
import sys
import os
sys.path.append(os.pardir)
import pytest
from pytz import timezone
from minette import DialogRouter, DialogService, EchoDialogService, ErrorDialogService
from minette import (
Message,
Context,
PerformanceInfo,
Priority
)
class PizzaDialogService(DialogService):
pass
class ... | 13,600 | 4,057 |
from manim2.imports import *
'''
Codigo por Miroslav Olsak
https://github.com/mkoconnor/manim
https://www.youtube.com/user/procdalsinazev/feed
'''
class ChatBubble(VMobject):
CONFIG = {
"answer_color":GREEN_B,
"response_color":BLUE_B,
"background_chat_opacity":0.95,
"background_chat_color":ORANGE,
"match_backgro... | 4,630 | 1,978 |
import requests
import json
def file_sync(target, file_name):
token = 'Schedule0350c8c75ddcd9fafdaA9738df4c9346bec48dc9c4915'
url = 'http://127.0.0.1:10011/api/v1/schedule/file_sync/'
data = {"target": target, "file_name": file_name}
r = requests.get(url, data=json.dumps(data),
header... | 1,065 | 438 |
import logging
from django.contrib import auth
from django.core.management.base import BaseCommand
from django.db import transaction
from projectroles.utils import set_user_group
User = auth.get_user_model()
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Synchronizes user groups base... | 985 | 258 |
from .base import *
SECRET_KEY = env('DJANGO_SECRET_KEY' , default='f8$t@ah-8n9fh%1@(&^or#8((8x#+h0^6!#spyf6egk1gs!si7')
DEBUG = env.bool('DJANGO_DEBUG', default=True) | 169 | 92 |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merg... | 6,667 | 1,888 |
"""
This module declares all custom exception classes.
"""
import edera.helpers
class Error(Exception):
"""
The base class for all exceptions within Edera.
"""
class ExcusableError(Error):
"""
The base class for all "excusable" errors.
They barely deserve a warning.
"""
class Undefin... | 5,973 | 1,709 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Classes for todo files.'''
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
if __debug__:
if __package__:
from . import todo_parser as _todo_parser
else:
import todo_parser as _todo_parser
if __name__ != '__main__':
__author__ = 'Loui... | 1,153 | 377 |
#!/usr/bin/env python
"""
"""
from .bpsf_keys import *
from .h5_file_ops import * | 82 | 36 |
from django_summernote.admin import SummernoteModelAdmin
from django.contrib.postgres import fields
from django_json_widget.widgets import JSONEditorWidget
from django.contrib import admin
from attendees.occasions.models import *
from attendees.whereabouts.models import *
from .models import *
# Register your models h... | 4,347 | 1,391 |
from sklearn.metrics import mean_squared_error, log_loss
from keras.models import Model
from keras.models import load_model
from keras.layers import Input, Dense
from keras.layers.recurrent import SimpleRNN
from keras.layers.merge import multiply, concatenate, add
from keras import backend as K
from keras import initia... | 27,929 | 9,451 |
#!/usr/bin/env python3
"""Initialize.
Turn full names into initials.
Source:
https://edabit.com/challenge/ANsubgd5zPGxov3u8
"""
def __initialize(name: str, period: bool=False) -> str:
"""Turn full name string into a initials string.
Private function used by initialize.
Arguments:
name {[str]}... | 1,423 | 450 |
import zengl
from defaults import defaults
from grid import grid_pipeline
from window import Window
window = Window(1280, 720)
ctx = zengl.context()
image = ctx.image(window.size, 'rgba8unorm', samples=4)
depth = ctx.image(window.size, 'depth24plus', samples=4)
image.clear_value = (0.2, 0.2, 0.2, 1.0)
ctx.includes[... | 7,038 | 4,494 |
#Funções:__________________________________________________________________
def cadastro():
resp=input(print("Deseja cadastrar alguém?"))
if resp.upper()!= "N":
while resp.upper()!= "N":
arq=open("teste.txt","a")
nome=input(print("Digite seu nome"))
arq.write("... | 1,305 | 443 |