text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
'''
nbpkg defspec
'''
NBPKG_MAGIC_NUMBER = b'\x1f\x8b'
NBPKG_HEADER_MAGIC_NUMBER = '\037\213'
NBPKGINFO_MIN_NUMBER = 1000
NBPKGINFO_MAX_NUMBER = 1146
# data types definition
NBPKG_DATA_TYPE_NULL = 0
NBPKG_DATA_TYPE_CHAR = 1
NBPKG_DATA_TYPE_INT8 = 2
NBPKG_DATA_TYPE_INT16 = 3
NBPKG_DATA_TYPE_IN... | 1,984 | 958 |
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import numpy as np
from scipy.fftpack import dct, idct
from scipy import linalg as la
import torch.nn.functional as F
import logging
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return n... | 15,699 | 5,560 |
from openpyxl import load_workbook
import mysql.connector
# Excel
workbook = load_workbook('imported.xlsx')
sheet = workbook.active
values = []
for row in sheet.iter_rows(min_row=2, values_only=True):
print(row)
values.append(row)
# Database
db = mysql.connector.connect(
host='localhost',
port=3306,... | 642 | 261 |
# mypy: ignore-errors
import inspect
from typing import Tuple
import warnings
import torch
class LazyInitializationMixin:
"""A mixin for modules that lazily initialize buffers and parameters.
Unlike regular modules, subclasses of this module can initialize
buffers and parameters outside of the constru... | 7,492 | 1,858 |
# Copyright 2019 The TensorFlow Authors. 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 applica... | 7,286 | 2,417 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from copy import deepcopy
from functools import wraps
from flask import request
from src.misc.render import json_detail_render
from config.settings import YML_JSON, logger
import datetime,json
def transfer(column):
def dec(func):
@wraps(func)
... | 12,404 | 3,614 |
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. 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... | 3,303 | 1,239 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Copyright ยฉ 2014 - 2016, Sequรธmics Research, All rights reserved.
# Copyright ยฉ 2014 - 2016, Sequรธmics Corporation. All rights reserved.
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ... | 556 | 352 |
import sys
sys.path.append('./train_model')
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import numpy as np
import os
import argparse
parser = argparse.ArgumentParser(description='Adaptive Network Slimming')
parser.add_argument('-n... | 7,767 | 3,023 |
from flask import request
from ..utils.mcexceptions import AccessNotAllowedException
from . import apikeydb
from ..database.DB import DbConnection
_user_access_matrix = {}
_admins = []
def check(user, owner, project_id="Unknown"):
if not allowed(user, owner, project_id):
raise AccessNotAllowedException(p... | 2,370 | 781 |
from .server import Application | 31 | 6 |
"""Represent AWS config settings"""
import json
from typing import Iterable, Mapping
import boto3
from datetime import datetime, timedelta
from data_model import OriginAndCallingPointNames
from .config import ConfigSettings
class AwsAppConfigSettings(ConfigSettings):
"""Represent a collection of config settings... | 5,056 | 1,345 |
from timeit import timeit
from unittest import TestCase
from ..ipaparser import IPA, load
__all__ = [
'TestLoading',
]
FACTOR = 10.0
def is_much_larger(a: float, b: float) -> bool:
return a > b * FACTOR
def are_roughly_equal(a: float, b: float) -> bool:
return not is_much_larger(a, b) and not is_much... | 712 | 265 |
import logging
logging.basicConfig(level=logging.DEBUG)
def log(*a):
logging.info(' '.join(map(str, a)))
warn = logging.warn
| 142 | 55 |
#!/usr/bin/env python3
"""Named tuple example."""
from collections import namedtuple
Car = namedtuple('Car', 'color mileage')
# Our new "Car" class works as expected:
MY_CAR = Car('red', 3812.4)
print(MY_CAR.color)
print(MY_CAR.mileage)
# We get a nice string repr for free:
print(MY_CAR)
try:
MY_CAR.color = 'bl... | 511 | 179 |
"""Test Open Peer Power config flow for BleBox devices."""
from unittest.mock import DEFAULT, AsyncMock, PropertyMock, patch
import blebox_uniapi
import pytest
from openpeerpower import config_entries, data_entry_flow
from openpeerpower.components.blebox import config_flow
from openpeerpower.setup import async_setup... | 6,750 | 2,185 |
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import glob
import seaborn as sns
from PIL import Image
import glob
import tensorflow as tf
import model
os.environ['CUDA_VISIBLE_DEVICES']='0'
dataDir = '/data/jupyter/libin713/sample_IDCard'
def read_and_decode(filename,batch_size): # ่ฏปๅ
ฅdog_tr... | 3,521 | 1,251 |
from django.db import models
# Create your models here.
class DrinkType(models.Model):
created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated = models.DateTimeField(auto_now=True, blank=True, null=True)
title = models.CharField(max_length=100, null=True, blank=True)
def __s... | 779 | 255 |
## @class IntraCodec
# Module designed for encoding and decoding YUV videos using the intra-frame method
# That is considering adjacent pixels in the same frame and encoding their errors
# @author Tiago Melo 89005
# @author Joรฃo Nogueira 89262
import numpy as np
import math
from Golomb import *
from Bitstream import ... | 18,127 | 5,587 |
from effects.keyboard_effect import KeyboardEffect
from utils.lights import get_lights
from effects.candle_effect import CandleEffect
from effects.phasma_hunt_effect import PhasmaHuntEffect
from effects.audio_spectrum_effect import AudioSpectrumEffect
from effects.audio_amplitude_effect import AudioAmplitudeEffect
from... | 1,015 | 400 |
#!/usr/bin/env python
from .beamformer import BeamFormer
from .compound_beam import CompoundBeam
from .sb_generator import SBGenerator
from .simulate_sb_pattern import SBPattern
__all__ = ['BeamFormer', 'CompoundBeam', 'SBPattern', 'SBGenerator']
| 250 | 84 |
# -*- coding: utf-8 -*-
# Copyright 2019 The GraphicsFuzz Project 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | 3,090 | 1,032 |
# LOL. Hope you're not fooled by the name of this file
import sys
import os
from configparser import ConfigParser
# Note: All classes here have N801 (CapWords naming convention) disabled.
# They're intended to be singletons
class Object(object):
def __init__(self, _default=None, **kwargs):
self.__dict... | 2,266 | 730 |
from collections import OrderedDict
from pytest import approx
def test_RandomDrop():
sample = None
raise
def test_TrimToTarget():
raise
def test_ComputeCouplings():
raise
def test_ToCategorical():
raise
def test_ToTensor_sample():
raise
def test_ToTensor_label():
raise
def test_ToDis... | 379 | 125 |
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import mysql.connector
auth_manager = SpotifyClientCredentials('f3dc4f3802254be091c8d8576961bc9d', 'b51d135ad7104add8f71933197e9cc14')
sp = spotipy.Spotify(auth_manager=auth_manager)
cnx = mysql.connector.connect(user='root', password='1234',
... | 1,512 | 529 |
import socket
class DNSQuery:
def __init__(self, data):
self.data=data
self.dominio=''
tipo = (ord(data[2]) >> 3) & 15 # Opcode bits
if tipo == 0: # Standard query
ini=12
lon=ord(data[ini])
while lon != 0:
self.dominio+=data[ini+1:ini+lon+1]+'.'
... | 1,414 | 562 |
import os
import logging
from pathlib import Path
from operations import catalogue
from parsers import XMLSpecParser
class ExpressionCalculator:
"""
Processes all expression files with given extension in source directory
Assumes that all files with given extension are expression files
"""
__slots... | 5,007 | 1,282 |
from cgitb import text
import queue
from random import seed
import serial
import serial.tools.list_ports
from signal import signal, SIGINT
import sys
import threading
import time
import tkinter
from tkinter import END, W, PhotoImage, filedialog as fd, scrolledtext as sd
global fw_filename
fw_filename = ""
COM_OVERRID... | 13,239 | 4,163 |
from django.contrib import admin
# Register your models here.
from .models import UserSession
admin.site.register(UserSession) | 128 | 33 |
from math import ceil
from numpy_financial import nper, pmt, rate
from typing import List, Tuple
from .calculator import Calculator
# noinspection PyTypeChecker
class LoanCalculator(Calculator):
def __init__(self, **kwargs):
super(LoanCalculator, self).__init__(**kwargs)
self.loan = ... | 5,588 | 1,912 |
import unittest
from pydundas import Api
class TestProject(unittest.TestCase):
def test_no_syntax_error(self):
self.assertIsNotNone(Api(None).project())
| 168 | 55 |
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class BudgetMonitorRevisionReport(models.Model):
_inherit = "budget.monitor.revision.report"
project_id = fields.Many2one(comodel_name="res.project")
... | 516 | 186 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import os
import time
import argparse
import uuid
import subprocess
import sys
import datetime
import yaml
from jinja2 import Environment, FileSystemLoader, Template
import base64
import re
import thread
import threading
import random
import textwrap
import lo... | 1,975 | 637 |
from paramiko.ssh_exception import SSHException
from paramiko.ssh_exception import AuthenticationException
class NetmikoTimeoutException(SSHException):
"""SSH session timed trying to connect to the device."""
pass
class NetmikoAuthenticationException(AuthenticationException):
"""SSH authentication exce... | 611 | 140 |
import time
from bs4 import BeautifulSoup
from base import *
from db_info import *
# ๆๅปบๆ ๅฐurl->article
_url2atc = dict()
month = dict({'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6,
'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12})
class REUTERURLManager(BaseURLManager):
... | 5,793 | 1,866 |
import djclick as click
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .forms import AddOrganizerForm
from .slack_client import slack
# "Get organizers info" functions used in 'new_event' and 'copy_event' management commands.
def get_main_organizer():
"""
We're ... | 2,770 | 849 |
from .forms import * # noqa
from .talks import * # noqa
| 58 | 22 |
#!/usr/bin/env python3
import hashlib
import json
import magic
import os
import re
import subprocess
import sys
import yara
import ordlookup
import pefile
import ssdeep
import tlsh
from multiprocessing import Pool
from os.path import isdir, isfile, join, basename, abspath, dirname, realpath
from pathlib import Path
f... | 8,235 | 2,771 |
#Write a program which can compute the factorial of a given numbers.
#The results should be printed in a comma-separated sequence on a single line
number=int(input("Please Enter factorial Number: "))
j=1
fact = 1
for i in range(number,0,-1):
fact =fact*i
print(fact) | 272 | 87 |
import datetime
import json
import os
import secrets
from importlib import import_module
# PATH = 'C:\\Users\\Zadigo\\Documents\\Apps\\zemailer\\app\\core\\settings.json'
PATH = os.path.join(os.getcwd(), 'app', 'core', 'conf', 'settings.json')
def deserialize(func):
"""A decorator that deserializes objects store... | 5,598 | 1,474 |
# Copyright 2019 The TensorFlow Authors. 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 applica... | 3,510 | 1,077 |
from perses.samplers.samplers import *
| 39 | 15 |
import requests
import pymongo
from pymongo import MongoClient
import json
from bs4 import BeautifulSoup
cluster= MongoClient("mongodb+srv://admin:Rohit91138@cluster0.d4cq9.mongodb.net/Novelore?retryWrites=true&w=majority")
db=cluster["Novelore"]
collection=db["mangadex-scrap"]
url="https://mangadex.org"
dat... | 5,272 | 1,960 |
from collections import deque
class RecentCounter:
def __init__(self):
self.buffer = deque()
def ping(self, t: int) -> int:
while self.buffer and self.buffer[-1]<t-3000:
self.buffer.pop()
self.buffer.appendleft(t)
return len(self.buffer)
#Your RecentCounter object wi... | 476 | 146 |
# -*- coding: utf-8 -*-
"""Convenience visual methods"""
import numpy as np
import matplotlib.pyplot as plt
def imshow(data, title=None, show=1, cmap=None, norm=None, complex=None, abs=0,
w=None, h=None, ridge=0, ticks=1, yticks=None, aspect='auto', **kw):
kw['interpolation'] = kw.get('interpolation', ... | 3,524 | 1,485 |
from unittest import TestCase
from necrypt import Necrypt
import os
class TestNecrypt(TestCase):
def test_unique_encryption(self):
n = Necrypt(1024)
plain = 'Text'
self.assertNotEqual(n.encrypt(plain), n.encrypt(plain))
def test_encrypt_decrypt(self):
n = Necrypt(1024)
... | 1,674 | 567 |
from datetime import date, timedelta
start_100days = date(2017, 3, 30)
pybites_founded = date(2016, 12, 19)
pycon_date = date(2018, 5, 8)
def get_hundred_days_end_date():
"""Return a string of yyyy-mm-dd"""
end_date = start_100days + timedelta(days=100)
return str(end_date)
def get_days_between_pb_star... | 555 | 236 |
from logging import getLogger
from pyramid.security import ACLAllowed
from openprocurement.audit.api.constants import (
MONITORING_TIME,
ELIMINATION_PERIOD_TIME,
ELIMINATION_PERIOD_NO_VIOLATIONS_TIME,
DRAFT_STATUS,
ACTIVE_STATUS,
ADDRESSED_STATUS,
DECLINED_STATUS,
STOPPED_STATUS,
C... | 9,312 | 2,866 |
import os
import numpy as np
import pytest
from spectrum_overload import Spectrum
from mingle.utilities.spectrum_utils import load_spectrum, select_observation
@pytest.mark.parametrize("fname", ["HD30501-1-mixavg-tellcorr_1.fits", "HD30501-1-mixavg-h2otellcorr_1.fits"])
def test_load_spectrum(fname):
fname = os... | 1,224 | 477 |
from raspador import Pilot, UserInteractor, BrowserInteractor
from typing import Dict, List
class RaspadorTemplatePilot(Pilot):
config: Dict[str, any]
sign_in_wait = 3.0
def __init__(self, config: Dict[str, any], user: UserInteractor, browser: BrowserInteractor):
self.config = config
super().__init__(us... | 574 | 192 |
# ๅผๆบ้กน็ฎ https://github.com/jones2000/HQChart
import sys
import codecs
import webbrowser
from umychart_complier_jscomplier import JSComplier, SymbolOption, HQ_DATA_TYPE
from umychart_complier_jscomplier import ScriptIndexConsole, ScriptIndexItem, SymbolOption, RequestOption, HQ_DATA_TYPE, ArgumentItem
from umycha... | 9,480 | 4,023 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
some helper funcs
"""
import json
import logging
import os
import site
import subprocess
import sys
import tempfile
import exifread
from PIL import Image
PACKAGE_NAME = "einguteswerkzeug"
# --- configure logging
log = logging.getLogger(__name__)
log.setLevel(logging... | 2,778 | 916 |
import logging
import typing
from datetime import datetime
from ParadoxTrading.Engine import MarketSupplyAbstract, ReturnMarket, ReturnSettlement
from ParadoxTrading.Fetch import FetchAbstract
from ParadoxTrading.Utils import DataStruct
class InterDayOnlineMarketSupply(MarketSupplyAbstract):
def __init__(
... | 2,357 | 660 |
__author__ = 'User'
from pytest_bdd import given, when, then
from model.contact import Contact
import random
@given('a contact list')
def contact_list(db):
return db.get_contact_list()
@given('a contact with <firstname>, <lastname>, <address> and <mobilephone>')
def new_contact(firstname, lastname, address, mobi... | 2,301 | 718 |
from django.core.exceptions import ValidationError
from django.test import TestCase
from django_analyses.models.input.types.input_types import InputTypes
from tests.factories.input.types.file_input import FileInputFactory
class FileInputTestCase(TestCase):
"""
Tests for the :class:`~django_analyses.models.inp... | 1,235 | 375 |
#!/usr/bin/python
"""A concise tool for archiving video as it is recorded.
"""
import os, time, argparse
import subprocess32 as subprocess
from socket import gethostname
import dvrutils
def read_archive_config(fName):
with open(fName, 'r') as f:
flines = f.readlines()
streams = [] # [{... | 8,052 | 2,267 |
import nlp_util
def testGC():
raw_address = 'isn s.h. & rekan, somba opu 76'
result = nlp_util.genCC(raw_address)
print(result)
assert result
def test_getPair():
# label, raw = "hanief sembilan mtr -h", "kuripan hanief semb mtr -h, gajah mada, 58112"
# print(getPair(label, raw))
raw = " ... | 5,416 | 2,415 |
# -*- coding: utf-8 -*-
import logging
import tempfile
import keras
import numpy as np
from mlprimitives.utils import import_object
LOGGER = logging.getLogger(__name__)
class Sequential(object):
"""A Wrapper around Sequential Keras models with a simpler interface."""
def __getstate__(self):
state... | 2,433 | 732 |
import sys
from typing import Any
from django.conf import settings
if sys.version_info >= (3, 8):
from typing import Literal
ModeType = Literal["once", "none", "all"]
else:
ModeType = str
class Settings:
defaults = {"HIDE_COLUMNS": True, "MODE": "once"}
def get_setting(self, key: str) -> Any:... | 686 | 226 |
import os
import json
class ServerParse:
def __init__(self, directory: str) -> None:
"""Initializes class. Stores root directory to server and loads
whitelist and server name.
:param directory: directory containing all server files (configurations
saves, etc.).
:return... | 3,026 | 849 |
import os
from ...utils import CodeGenerationStrategy
from ....endpoint import Endpoint
from .....utils import TemplateGenerator
class NodeStrategy(CodeGenerationStrategy,
target='node'):
def __init__(self):
super().__init__()
self.output_dir = 'sandbox/node'
dirname =... | 2,402 | 597 |
from dumpshmamp.collectors.files import try_copyfile, file_path, mkdir
from shminspector.util.cmd import try_capture_output, is_command
def collect_docker_files(user_home_dir_path, target_dir_path, ctx):
if is_command("docker"):
ctx.logger.info("Collecting Docker information...")
mkdir(target_dir... | 2,208 | 680 |
import cv2
import numpy as np
# Normal routines
img = cv2.imread('image3.png')
scale_percent = 30 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA... | 1,185 | 533 |
# Non-abundant sums
# https://projecteuler.net/problem=23
# This actually took 5 seconds to process.
# Maybe a faster solution is present?
from math import sqrt
from collections import defaultdict
def divisors(n):
div = 0
for i in range(1, int(sqrt(n)) + 1):
if n%i == 0:
if i*i == n or n/... | 749 | 281 |
import os
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from scpca_portal.config.common import Common
class Production(Common):
INSTALLED_APPS = Common.INSTALLED_APPS
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY")
# Site
# https://docs.djangoproject.com/en/2.0/ref/setti... | 1,665 | 596 |
import gc
import math
import numpy as np
import torch
import torch.nn.functional as F
import timeit
import time
from gck_layer import GCK3x3Layer
kernel_dim = 3
def tensors_equal(a,b):
b = torch.allclose(a, b, atol=0.01)
if (b):
print('same: True')
else:
print('Same: False (diff:', ((a-b).... | 1,057 | 443 |
"""
Prepare some stats from timelines
"""
# https://docs.python.org/3.7/library/collections.html#collections.Counter
from collections import Counter
def get_timeline_stats(timeline):
"""
:type timeline list[now_playing_graph.timeline.TimelineEntry]
:rtype: dict
"""
top_artists = Counter()
top_... | 1,009 | 331 |
"""
Use GMail API to check an Inbox for new emails.
To generate the initial credentials you will need to execute this module from
python with first argument to a patch containing your API client details
and the second argument to the file where to store the credentials.
It uses the `historyID` configuration option to... | 10,197 | 2,656 |
"""Defines the version number and details of ``qusetta``."""
__all__ = (
'__version__', '__author__', '__authoremail__', '__license__',
'__sourceurl__', '__description__'
)
__version__ = "0.0.0"
__author__ = "Joseph T. Iosue"
__authoremail__ = "joe.iosue@qcware.com"
__license__ = "MIT License"
__sourceurl__ ... | 435 | 159 |
import pytest
from mock import Mock, patch
from service import get_lobbies
@patch('service.lobby_service_common.get_public_lobbies')
def test_get_lobbies(get_public_lobbies_mock):
get_public_lobbies_mock.return_value = {}
response = get_lobbies.lambda_handler({}, None)
valid_response = {'statusCode': 2... | 777 | 280 |
import pathlib
import click
from . import candeout
@click.group()
@click.argument("ifile", type=click.Path(exists=True, dir_okay=False), required=True)
@click.argument(
"ofile",
type=click.Path(exists=False, dir_okay=False, writable=True),
required=False,
)
@click.pass_context
def main(ctx, ifile, ofile... | 1,031 | 392 |
import functools
from django.contrib import messages
from django.urls import reverse
from django.shortcuts import redirect
def full_profile_required(func):
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
if (request.user
and request.user.id # FIXME test mocks mess with ... | 756 | 192 |
from flask import Flask, render_template, request, redirect, jsonify
from flask_cors import CORS, cross_origin
from datetime import datetime
from flask import Blueprint
from flask_paginate import Pagination, get_page_parameter
import botocore
import boto3
import decimal
import logging
import time
import argparse
impo... | 3,642 | 1,176 |
from downscale import DeltaDownscale
class DeltaDownscaleMM( DeltaDownscale ):
def _calc_anomalies( self ):
print('calculating anomalies')
def downscale( self, *args, **kwargs ):
print( 'downscaling...' )
# FOR RUN OF THE MIN / MAX TAS DATA:
# 1. COMPUTE DELTAS FIRST ANND WRITE TO NETCDF
# 2. USE `DeltaDownsc... | 1,279 | 530 |
import numpy as np
from mldftdat.pyscf_utils import *
from mldftdat.workflow_utils import safe_mem_cap_mb
from pyscf.dft.numint import eval_ao, make_mask
from mldftdat.density import LDA_FACTOR,\
contract21_deriv, contract21, GG_AMIN
def dtauw(rho_data):
return - get_gradient_magnitud... | 13,552 | 5,392 |
from django.apps import AppConfig
class BoxesConfig(AppConfig):
name = 'apps.boxes'
def ready(self):
import apps.boxes.signals
| 146 | 48 |
##Write a program to input from the input file a familiar greeting of any length, each word on a line. Output the greeting file you just received on a single line, the words separated by a space
#Mo file voi mode='r' de doc file
with open('05_ip.txt', 'r') as fileInp:
#Dung ham read() doc toan bo du lieu tu file
F... | 728 | 251 |
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
from optparse import OptionParser
import json
import requests
from pyzem.dvid import dvidenv
import datetime
def compute_age(d):
age = -1
if 'timestamp' in d:
t = datetime.datetime.strptime(d['timestamp']... | 15,642 | 5,377 |
import tkinter as tk
from tkinter import *
import cv2
from PIL import Image, ImageTk
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow import keras
emotion_model = keras.Sequential(
[
layers.Conv2D(32, kernel_size=(3,3), activation='relu', input_shape = (48,48,... | 3,970 | 1,652 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file
# Module with some simple but useful utilities
# - suppression of stdout/stderr
# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
# @date 2013-02-10
#
# ===========================... | 14,032 | 4,267 |
def fuel_required_single_module(mass):
fuel = int(mass / 3) - 2
return fuel if fuel > 0 else 0
def fuel_required_multiple_modules(masses):
total_fuel = 0
for mass in masses:
total_fuel += fuel_required_single_module(mass)
return total_fuel
def recursive_fuel_required_single_module(mass):... | 629 | 211 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 09 15:44:40 2020
@author: mugopala
Helper functions for tasks
"""
import os
import stat
import json
import threading
import time
import queue as stdq
import csv
from io import StringIO
from .helpers import file_reader
from . import task_consts, co... | 22,403 | 6,828 |
import webbrowser
class Movie():
""" This class provides a way to store movie related information """
# Class Variable: These are the Movies Ratings
# G: General Audiences. All ages admitted.
# PG: Parental Guidance Suggested. Some material may not be suitable for children.
# PG-13: Parents Strongly Cautioned.... | 819 | 284 |
str_xdigits = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
]
def convert_digit(value: int, base: int) -> str:
return str_xdigits[value % base]
def convert_to_val(value: int, base: int) -> str:
if value == No... | 1,365 | 543 |
from pixelstarshipsapi import PixelStarshipsApi
from run import push_context
def test_login():
pixel_starships_api = PixelStarshipsApi()
device_key, device_checksum = pixel_starships_api.generate_device()
token = pixel_starships_api.get_device_token(device_key, device_checksum)
assert isinstance(tok... | 13,914 | 4,486 |
import os
from geofeather import to_geofeather, from_geofeather
from pandas.testing import assert_frame_equal
import pytest
def test_points_geofeather(tmpdir, points_wgs84):
"""Confirm that we can round-trip points to / from feather file"""
filename = tmpdir / "points_wgs84.feather"
to_geofeather(points... | 2,776 | 1,032 |
from __future__ import annotations
import re
from enum import Enum
from emoji import EMOJI_UNICODE
from PIL import ImageFont
from typing import Final, List, NamedTuple, TYPE_CHECKING
if TYPE_CHECKING:
from .core import FontT
# This is actually way faster than it seems
_UNICODE_EMOJI_REGEX = '|'.join(map(re.es... | 4,133 | 1,471 |
# Copyright (c) 2013 OpenStack Foundation
#
# 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 ... | 53,276 | 14,388 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os.path
import uuid
from yamlfred.utils import remove_default, merge_dicts
from yamlfred.utils import Include
defaults = {
'alfred.workflow.output.notification': {
'config': {'removeextension': False, 'output': 0, 'las... | 4,524 | 1,508 |
"""
pirple/python/project2/main.py
Project #2
Create a hangman game
"""
from os import system, name
from time import sleep
from random import randint
import string
def clear_screen():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
... | 8,231 | 2,723 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import deepnlpf.log as log
from deepnlpf.core.util import Util
class PluginManager:
def __init__(self):
self.HOME = os.environ["HOME"]
self.PLUGIN_SERVER = "https://github.com/deepnlpf/"
self.PLUGIN_PATH = self.HOME + "/d... | 5,533 | 1,598 |
#
# Copyright 2017 Wooga 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, merge, publish, distribute... | 2,628 | 816 |
from django import test
from hexa.user_management.models import Membership, Team, User
from ..models import Database, DatabasePermission, Table
class PermissionTest(test.TestCase):
@classmethod
def setUpTestData(cls):
cls.DB1 = Database.objects.create(
hostname="host", username="user", p... | 2,786 | 839 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making ่้ฒธๆบไบPaaSๅนณๅฐ็คพๅบ็ (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | 1,932 | 617 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('hello', views.hello),
path('world', views.world),
path('users', views.users),
path('user/<int:user_id>', views.user),
]
| 236 | 80 |
class SimpleOpt():
def __init__(self):
self.method = 'cpgan'
self.max_epochs = 100
self.graph_type = 'ENZYMES'
self.data_dir = './data/facebook.graphs'
self.gpu = '2'
self.lr = 0.003
self.encode_size = 16
self.decode_size = 16
self.pool_size = ... | 760 | 291 |
import torch
def mean_shift(template, source, p0_zero_mean, p1_zero_mean):
template_mean = torch.eye(3).view(1, 3, 3).expand(template.size(0), 3, 3).to(template) # [B, 3, 3]
source_mean = torch.eye(3).view(1, 3, 3).expand(source.size(0), 3, 3).to(source) # [B, 3, 3]
if p0_zero_mean:
p0_m = template.mean(di... | 1,764 | 907 |
import unittest
from pyNTM import FlexModel
from pyNTM import ModelException
from pyNTM import PerformanceModel
class TestIGPShortcuts(unittest.TestCase):
def test_traffic_on_shortcut_lsps(self):
"""
Verify Interface and LSP traffic when IGP shortcuts enabled
in baseline model.
"""... | 12,449 | 5,374 |
# What will the gender ratio be after every family stops having children after
# after they have a girl and not until then.
def birth_ratio():
# Everytime a child is born, there is a 0.5 chance of the baby being male
# and 0.5 chance of the baby being a girl. So the ratio is 1:1.
return 1
| 299 | 91 |
import unittest
from pinq.transforms import identity
class predicate_true_tests(unittest.TestCase):
def test_identity_int(self):
self.assertEqual(identity(123), 123)
def test_identity_str(self):
self.assertEqual(identity("apple"), "apple")
def test_identity_list(self):
self.asse... | 376 | 131 |