text string | size int64 | token_count int64 |
|---|---|---|
import numpy as np
import torch
import torchvision
import torchvision.transforms as T
from PIL import Image
#transform dictionary format pass in the class
# {'implenmented string': True}
class Transform(object):
def __init__(self, preprocess_dict, device):
self.implemented_list = self.implenmented()
... | 2,640 | 771 |
# import pyfiglet module
import pyfiglet
result = pyfiglet.figlet_format("Sai Ashish", font = "slant")
print(result)
| 120 | 43 |
# -*- coding: utf-8 -*-
import urllib
import hashlib
import urllib2
import logging
import os,sys
import base64
from datetime import datetime
import json
import logging
import urllib
class AliPayConfig(object):
"""
支付宝 公共配置
"""
APP_ID = '' #appid
precreate_GATEWAY="https://openapi.alipay.com/gatew... | 10,110 | 3,734 |
import FWCore.ParameterSet.Config as cms
genericTriggerEventFlag4fullTracker = cms.PSet(
andOr = cms.bool( False ),
dcsInputTag = cms.InputTag( "scalersRawToDigi" ),
dcsRecordInputTag = cms.InputTag("onlineMetaDataDigis"),
dcsPartitions = cms.vint32 ( 24, 25, 26, 27, 28, 29 ),
andOrDcs = ... | 3,658 | 1,527 |
import os
import multiprocessing
from pathlib import Path
from joblib import Parallel, delayed
import numpy as np
import desispec.io
import desispec.fluxcalibration
# TODO: Parallelization should be done in the target dimension if decided to run on all targets
def _preprocess_sky_frame(
night, exp, petal, fiber,... | 4,557 | 1,531 |
'''
Description:
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. ... | 2,232 | 793 |
import logging, good
from tornado import web
from ..base import Api_handler, Level
class Handler(Api_handler):
__schema__ = good.Schema({
str: [{
'message': good.All(str, good.Length(min=0, max=200)),
good.Optional('min_amount'): good.All(good.Coerce(int), good.Range(min=0, max=100... | 1,778 | 515 |
# -*- coding: iso-8859-1 -*-
# Copyright 2010 Pepijn de Vos
#
# 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... | 1,119 | 349 |
from rest_framework import (viewsets, mixins, status, response)
from rest_framework.decorators import detail_route
from . import (serializers, models, constants)
class InvalidStringException(Exception):
pass
def str_to_const(string):
_s = string.upper()
if _s == 'ROCK':
return constants.ROCK
... | 1,342 | 390 |
import os as _os
_os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow import keras as _keras
def model_v1(input_shape: tuple):
model = _keras.Sequential()
model.add(_keras.layers.LSTM(64, input_shape=input_shape, activation='relu', return_sequences=True))
model.add(_keras.layers.Dropout(0.3))
mode... | 576 | 215 |
import sys
import time
import cv2
import keyboard
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from config import *
from detector import *
import json
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
# Set up environment
QtWidgets.QMainWindow.__init_... | 4,989 | 1,569 |
#! -*- coding: utf-8 -*-
# 测试代码可用性: 提取特征
import torch
from bert4torch.models import build_transformer_model
from bert4torch.tokenizers import Tokenizer
root_model_path = "F:/Projects/pretrain_ckpt/bert/[google_tf_base]--chinese_L-12_H-768_A-12"
vocab_path = root_model_path + "/vocab.txt"
config_path = root_model_path... | 1,304 | 764 |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 05:46:07 2018
@author: uqdbond1
"""
import numpy as np
import re
import pylab as plt
import os, sys
np.set_printoptions(linewidth=1000)
#==============================================================================
#
#==============================================... | 4,472 | 1,733 |
import hashlib
import pdb
import pytest
from base64 import b64encode
from datetime import timedelta
from hashlib import sha1, sha256, blake2b
from uuid import uuid4
from werkzeug.http import http_date
import arrow
import requests
from flask import g
from rdflib import Graph
from rdflib.compare import isomorphic
from... | 72,911 | 24,192 |
#! /usr/bin/python3.6
"""
Example 26:
Prompt the user to select a product and get it's bounding box parameters
.. warning:
Currently there must be NO other existing Measure Inertias saved
ANYWHERE in your product tree as these may be returned and not
product you have selected.
"... | 2,040 | 678 |
#!/usr/bin/env python3
# CGI script to extract content of AU as WARC and report result
# in JSON as specified in WASAPI
from warcio.warcwriter import WARCWriter
from warcio.statusandheaders import StatusAndHeaders
from argparse import ArgumentParser
import requests
import json
import tempfile
import re
import cgi
i... | 7,060 | 2,159 |
# Copyright © 2017-2019 Elizabeth Myers. All rights reserved.
# This file is part of the taillight project. See LICENSE in the root
# directory for licensing information.
"""The top level module contains a few constants needed throughout taillight,
the base exception for all taillight errors (for easier catching by h... | 1,082 | 345 |
#!/usr/bin/python
# Function definition is here
def folio2solr(folioReg):
#folioReg is the dictonary
##Checar campos problematicos
#contributors
if len(folioReg['contributors']): #diferente de zero
auxContributors = folioReg['contributors'][0]['name']
else:
auxContributors = []
... | 1,504 | 484 |
import unittest
from unittest.mock import patch, MagicMock
import os
import logging
from git.exc import GitCommandError
from git import Repo
from civis_jupyter_notebooks.git_utils import CivisGit, CivisGitError
REPO_URL = 'http://www.github.com/civisanalytics.foo.git'
REPO_MOUNT_PATH = '/root/work'
GIT_REPO_REF = 'ma... | 2,399 | 853 |
import hashlib
import secrets
from uuid import uuid4
import rulez
from morpfw.crud import Collection, Model, Schema
from ..app import App
from .schema import APIKeySchema
class APIKeyModel(Model):
schema = APIKeySchema
update_view_enabled = False
@property
def client_id(self):
return self["... | 1,527 | 470 |
""" Skeleton class for creating, accessing different attributes for a skelton.
"""
import numpy as np
class Skeleton():
def __init__(self, XYZ = None, edges = None , labels = None):
self._XYZ = XYZ if XYZ is not None else np.empty((0,3))
self._edges = edges if edges is not None else []
self._labels = la... | 3,417 | 1,190 |
#!/usr/bin/env/python
# -*- coding:utf-8 -*-
# Author:guoyuhang
import json
from com.request import aclRequest
from com.config.config import Config
from com.model import acl
""" 处理把response返回的dict对象中内容处理后放到acl对象数组中 """
class AclDao(object):
def __init__(self) :
self.aclList = []
self.aclReq = acl... | 1,233 | 439 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* Copyright (C) 2017 Hendrik van Essen
*
* This file is subject to the terms and conditions of the MIT License
* See the file LICENSE in the top level directory for more details.
"""
from __future__ import absolute_import, print_function, unicode_literals
import ... | 6,044 | 1,494 |
"""
benchmark.py: this script performs a benchmark based on hyper-parameters tuning (grid-search).
For details see main README.md.
"""
if __name__ == "__main__":
import argparse
from experiments.src import tune_hyper
from experiments.src.benchmarking.benchmarking_benchmark_results import benchmark_result
... | 970 | 268 |
from tornado import websocket, web, ioloop
import json
import time
clients = []
class SocketHandler(websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self, key=None):
self.key = key
if self not in clients:
clients.append(self)
def on_cl... | 916 | 295 |
import sys
import os.path
import logging
import json
import geojson
import types
import mapzen.whosonfirst.export
import mapzen.whosonfirst.placetypes
import mapzen.whosonfirst.sources
import mapzen.whosonfirst.utils
class reporter:
def __init__(self):
self._debug_ = []
self._info_ = []
... | 11,410 | 3,261 |
"""
Deep Q network,
Using:
Tensorflow: 1.0
gym: 0.7.3
"""
import gym
import numpy as np
from my_DQN_brain import DeepQNetwork
import matplotlib.pyplot as plt
env = gym.make('CartPole-v0')
env = env.unwrapped
print(env.action_space)
print(env.observation_space)
print(env.observation_space.high)
print(env.observatio... | 2,072 | 745 |
def bubble_sort(int_list):
for i in range(0, len(int_list)):
if (i == 0):
pass
elif int_list[i] < int_list[i-1]:
int_list[i], int_list[i-1] = int_list[i-1], int_list[i]
print('lol')
print(int_list)
print(int_list)
| 283 | 112 |
# Credit to GPflow
import tensorflow as tf
def base_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, q_sqrt=None, white=False, return_Lm=False):
"""
Given a g1 and g2, and distribution p and q such that
p(g2) = N(g2;0,Kmm)
p(g1) = N(g1;0,Knn)
p(g1|g2) = N(g1;0,Knm)
And
q(g2) = N(g... | 4,098 | 1,549 |
def aFunc(a):
return abs(a)
| 32 | 15 |
# queue item action
ACTION_ADD = "add"
ACTION_DEL = "del"
# server type field
SERVER_TYPE_RATIO = "server_type_ratio"
# vm deployment way
VM_DEPLOYMENT_SINGLE = 0
VM_DEPLOYMENT_DOUBLE = 1
# vm node name
VM_NODE_A = "A"
VM_NODE_B = "B"
VM_NODE_AB = "AB"
# common
NULL_STRING = ""
ZERO_NUM = 0
MIN_VALUE_INITIAL = 1000... | 389 | 186 |
extensions = dict(
extensions = dict(
validate_params="""
# Required maps for different names params, including deprecated params
.gbm.map <- c("x" = "ignored_columns",
"y" = "response_column")
"""
),
set_required_params="""
parms$training_frame <- training_frame
args <- .verify_dataxy... | 1,075 | 402 |
import torch
from .utils import NdSpec
from .utils.validation import check_axes
def random_crop(x: torch.Tensor, axes, size, *, generator: torch.Generator = None):
axes = check_axes(x, axes)
size = NdSpec(size, item_shape=[])
idx = [slice(None)] * x.ndim
for i, a in enumerate(axes):
length = ... | 1,788 | 619 |
from .fixtures import foo_file
from libextract.core import parse_html, pipeline
def test_parse_html(foo_file):
etree = parse_html(foo_file, encoding='ascii')
divs = etree.xpath('//body/article/div')
for node in divs:
assert node.tag == 'div'
assert node.text == 'foo.'
assert len(divs... | 523 | 185 |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 14:36:56 2020
@author: user
"""
import glob
import os
import pickle
import shutil
import time
from flask import request
from flask import Flask
import argparse
import os
import glob
from predict_jersey_number import detect_person_jersey_no, load_objdetection, load_n... | 5,868 | 1,848 |
from bs4 import BeautifulSoup
import requests
url = "https://www.nseindia.com/live_market/dynaContent/live_analysis/gainers/niftyGainers1.json"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data)
print soup | 224 | 87 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-05 15:46
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ui', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name... | 382 | 137 |
from django.db import models
# main page posts
class IndexCards(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=64)
paragraph = models.CharField(max_length=256)
observation = models.CharField(max_length=128)
image_link = models.CharField(max_length=512)
... | 422 | 137 |
from .EmbThread import EmbThread
def get_thread_set():
return [
EmbThreadHus("#000000", "Black", "026"),
EmbThreadHus("#0000e7", "Blue", "005"),
EmbThreadHus("#00c600", "Green", "002"),
EmbThreadHus("#ff0000", "Red", "014"),
EmbThreadHus("#840084", "Purple", "008")... | 1,929 | 809 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 25,479 | 7,052 |
from typing import Union
import requests
from requests_html import HTMLSession, HTMLResponse, HTML
from scylla.loggings import logger
class Worker:
def __init__(self):
"""Initialize the worker object
"""
self.session = HTMLSession()
def get_html(self, url: str, render_js: bool = ... | 1,140 | 306 |
from pathlib import Path
import shutil
import vak
HERE = Path(__file__).parent
# convention is that all the config.ini files in setup_scripts/ that should be
# run when setting up for development have filenames of the form `setup_*_config.ini'
# e.g., 'setup_learncurve_config.ini'
PREP_CONFIGS_TO_RUN = HERE.glob('set... | 852 | 304 |
from git import Repo
class Github:
def __init__(self, files, msg, LOGGER, config):
self.files = files
self.msg = msg
self.LOGGER = LOGGER
self.config = config
def git_add(self):
try:
repo = Repo(self.config)
for file in self.files:
... | 1,810 | 532 |
import praw
import os
channel_ids = [742799267294609448]
# add 743486931836338267
def reddit_access(file):
try:
reddit = praw.Reddit(username=os.environ["USERNAME"],
password=os.environ["PASSWORD"],
client_id=os.environ["CLIENT_ID"],
... | 614 | 200 |
import cv2 as cv
import numpy as np
from tensorflow.keras.models import load_model
model=load_model('facial.h5')
cv.ocl.setUseOpenCL(False)
dic={0:"Angry",1:"Disgusted",2:"Fearful",3:"Happy",4:"Neutral",5:"Sad",6:"Surprised"}
cap=cv.VideoCapture(0)
while True:
ret,frame=cap.read()
if not ret:
... | 1,172 | 520 |
# Copyright (c) 2022 PaddlePaddle 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 appli... | 24,060 | 8,494 |
import pygame
import json
from json import JSONEncoder
from .gui_element.button import Button
from .gui_element.element import Element
from .gui_element.toggleable_element import ToggleableElement
from .gui_element.popup import Popup
from .gui_element.element_group import ElementGroup
from .gui_element.text_ele... | 10,800 | 3,200 |
from __future__ import absolute_import
from __future__ import unicode_literals
from bazaar.listings.stores.strategies import DefaultStoreStrategy
class Store1(DefaultStoreStrategy):
def get_store_name(self):
return "Store 1"
class Store2(DefaultStoreStrategy):
def get_store_name(self):
retu... | 333 | 101 |
# Copyright 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 required by applicable law or agreed to in writing... | 2,918 | 831 |
#!/usr/bin/env python
import argparse
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import multiagent.scenarios as scenarios
from multiagent.environment import MultiAgentEnv
from multiagent.policy import InteractivePolicy
if __name__ == '__main__':
parser = argparse.ArgumentParser(des... | 1,645 | 482 |
import numpy as np
import sys
sys.path.append('../')
import events
import vector_calcs
import find_events
from itertools import combinations
"""
@author(s): Nathan Heidt
This handles single and multiview triangulation of events
TODO:
-
CHANGELOG:
-
"""
class Triangulator(object):
def __init__(self, ... | 2,456 | 806 |
#!/usr/bin/env python3
# The MIT License
# Copyright (c) 2016 Estonian Information System Authority (RIA), Population Register Centre (VRK)
#
# 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 ... | 21,311 | 6,094 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from rest_framework.routers import DefaultRouter
from djangocms_rest_api.views import PageViewSet, PlaceHolderViewSet, PluginViewSet
router = DefaultRouter()
router.register(r'pages', PageViewSet, 'page')
router.register... | 452 | 140 |
"""
Tasks to be invoked via "poetry run".
Any task added here must also be specified as a "script" in pyproject.toml.
"""
import os
import subprocess
import sys
from typing import List, Union
repo_root = os.path.dirname(__file__)
def _command(command: Union[List[str], str], shell: bool = False):
command_exit_c... | 1,130 | 388 |
#!/usr/bin/env python
__author__ = 'Sergei F. Kliver'
import argparse
from MACE.Parsers.VCF import CollectionVCF
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", action="store", dest="input", required=True,
help="Input vcf file with variants")
parser.add_argument("-o", "--o... | 731 | 232 |
import unittest
class SemanticAnalyzerTestCase(unittest.TestCase):
def analyze(self, text):
from interpreter.lexical_analysis.lexer import Lexer
from interpreter.syntax_analysis.parser import Parser
from interpreter.semantic_analysis.analyzer import SemanticAnalyzer
lexer = Lexer(t... | 1,227 | 351 |
import ast
from ast import Assign, Load, Module, Name, Print, Store
node_map = {
'Assignment': dict(pynode='Assign',
mappers={'targets': 'node', 'value': 'expr'},
types={'left': 'list'},
args={'ctx': ast.Store(lineno=0, col_offset=0)}),
'Ech... | 2,176 | 690 |
import settings
from ali1688scraperbrowser import ScraperBrowser
from bs4 import BeautifulSoup
import datetime
from functools import reduce
import re
def get_attr_content(aa, bb):
cc = []
for a in aa:
for b in bb:
ctemp = []
tmp0 = a[0] + ',' + b[0]
ctemp.append(tmp... | 8,178 | 2,713 |
import pandas as pd
import numpy as np
belga_train_path = '../../../../datasets/belgas/belgas_relabelled.csv'
logos_train_path = '../../../../datasets/LogosInTheWild-v2/LogosClean/commonformat/ImageSets/logos_top_train.csv'
flickr_train_path = '../../../../datasets/FlickrLogos_47/flickr_train_labels.csv'
belga_t... | 2,454 | 1,002 |
import ctypes as ct
import math
import pdb
import platform
if platform.system() == 'Windows':
_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv.dll')
else:
_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv.so')
def convUp(images, filters, targets, numModulesX, paddingStart, moduleStride, numImgColors, numGroups=1... | 7,327 | 2,728 |
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
def home(request: HttpRequest) -> HttpResponse:
if request.user.is_authenticated:
return render(request, 'home.html', {'user': request.user})
return HttpResponse("Login to see this page")
| 292 | 79 |
""" Generic monkey patching functions for doing it (mostly) safely """
import logging
import inspect
from types import MethodType, ModuleType
from collections import abc
from importlib import import_module
from importlib.util import resolve_name
from contextlib import suppress
__all__ = ['patchy', 'super_patchy']
lo... | 10,579 | 2,898 |
import sys
import os
import numpy as np
import helper
fname = sys.argv[1]
stats = ['parent', 'frontier', 'TileInOffsets', 'TileSources', 'Totals']
stypes = ['Tensor', 'Offchip']
data = {}
# collect data
for stat in stats:
data[stat] = {}
for stype in stypes:
data[stat][stype] = helper.getData(fname... | 569 | 191 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="home"),
path('listsiswa', views.siswa_view, name="list-siswa"),
path('addsiswa', views.add_siswa, name="add-siswa"),
path('editsiswa/<int:id>', views.edit_siswa, name="edit-siswa"),
path('deletesiswa/<int:i... | 369 | 146 |
#!/usr/bin/env python3
# coding=utf-8
import argparse
import logging
import os
import numpy as np
import pandas as pd
import string
PRONOUN2GENDER = {
'he': 'male', 'him': 'male', 'his': 'male',
'she': 'female', 'her': 'female', 'hers': 'female'}
GENDER2NAME = {
'female': (
('Mary', 'Alice'),
... | 3,909 | 1,273 |
#!/usr/bin/env python
import sys
from time import sleep
import blinkt
for i in range(256):
blinkt.set_all(i, i, i)
sys.stdout.write("%3d" % i)
blinkt.show()
sleep(0.1)
| 185 | 79 |
from typing import Callable
from .utilities import get_fixture
def exclude_fixtures(*fixtures_classes_or_accessors):
def decorator(function: Callable):
def wrapper(*args, **kwargs):
for fixture_class_or_accessor in fixtures_classes_or_accessors:
if isinstance(fixture_class_or_... | 732 | 207 |
name = "text" # Имя магазина
token = "text" # Токен бота
admin_id = 777777777 # ID администратора
channel = "@text" # Адрес канала с новостями
op = "@text" # Юзернейм оператора
token_qiwi = "text"
qiwi = "number" # Номер Qiwi кошелька
bitcoin = "text" # Адрес биткоин
logo_stick = "text" # Код стикера
s... | 378 | 179 |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 27 10:13:22 2021
@author: LeonardoDiasdaRosa
"""
from pyspark.sql import SparkSession
from pyspark.sql import functions as func
## Data
DATA_PATH = '../data/'
FILE = "book.txt"
data = DATA_PATH + FILE
# Create a SparkSession
spark = SparkSession.builder.appName("WordC... | 725 | 263 |
#!/bin/python3
"""
pdf内の単純表をjsonに変換します。
# python3 table.pdf -o out.json
出力するjsonの形式は以下の通りです。
[
{page:int,data:[parsed tables]},...
]
テーブルはテーブルの行毎に1列づつ、セル内の行毎に配列で格納します。
"""
#%%
from datetime import date
from tqdm import tqdm
from logging import addLevelName
import os,sys
sys.path.ap... | 2,606 | 1,046 |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2020
# Chenglin Ning, chenglinning@gmain.com
import logging
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy import create_engine
from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool
from s... | 1,795 | 562 |
import cv2
from skimage.transform import resize
import os
from demo import key_pressed
if __name__ == '__main__':
frame_dim = 256
vid = cv2.VideoCapture(0)
width = 1920
height = 1080
vid.set(cv2.CAP_PROP_FRAME_WIDTH, width)
vid.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
capname = "cap"
# cv... | 2,909 | 998 |
import binascii
import os
from django.conf import settings
from fallballapp.meta_data import data
from fallballapp.utils import get_app_username
def load_data(apps, schema_editor):
user_admin, created = apps.get_model('auth', 'User').objects.get_or_create(
username='admin',
password='pbkdf2_sha2... | 2,824 | 855 |
'''
Created on Mar 7, 2011
@author: johnsalvatier
'''
class CompoundStep(object):
"""Step method composed of a list of several other step methods applied in sequence."""
def __init__(self, methods):
self.methods = list(methods)
self.generates_stats = any(method.generates_stats for method in ... | 1,417 | 383 |
# MANY-TO-MANY RELATIONSHIPS IN SQL
#! MANY-TO-MANY
# até agr só vimos one-to-many ou many-to-one relationships
#* um exemplo são diferentes livros que são escritos por diferentes autores
#* -------- ----------
#* | BOOKS | <==> | AUTHORS |
#* -------- ----------
#* Nesse caso adicionamos... | 2,221 | 800 |
# Generated by Django 3.2.5 on 2022-02-02 00:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('english', '0005_auto_20220201_2343'),
]
operations = [
migrations.AlterField(
model_name='english',
name='tag',
... | 426 | 156 |
import utils.constants as const
animal_scores = {
const.DOG: 100,
const.CAT: 300
}
def get_animal_score(animal_name):
if animal_name in animal_scores:
return animal_scores[animal_name]
return const.DEFAULT_ANIMAL_SCORE
| 247 | 99 |
'''
Created on 25 Aug, 2020
@author: ABD
Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comments_896976.json (Sum ends with 62)
'''
import urllib.request, urllib.parse, urllib.error
import ssl
import json
ctx = ssl.create_default_context()
... | 674 | 275 |
#! /usr/bin/env python
import rospy
import actionlib
from strands_tweets.msg import SendTweetAction, SendTweetGoal, GrabImageThenTweetAction, GrabImageThenTweetResult
from sensor_msgs.msg import Image
class ImageTweeter(object):
def __init__(self) :
rospy.loginfo('Waiting for strands_tweets'... | 2,027 | 660 |
# Avoided iterarion using filter function and added put and delete operation
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
items = []
class Item(Resource):
def get(self, name):
item = next(filter(lambda x: x['name'] == name, items), None)
... | 1,876 | 575 |
"""
Testing functionality of reseting when no other node is resetting.
Node 0 has gone through a reset without needing it and ended up in phase 1 with RST_PAIR.
Node 0 shall catch up with the other nodes in view (2,2)
"""
# standard
import asyncio
import logging
from copy import deepcopy
# local
from . import helper... | 3,287 | 1,020 |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from models import *
from utils import progress_bar
from loss ... | 4,723 | 1,796 |
"""
We test an initialization pattern for z3c.saconfig where the metadata
is set up in an event handler.
Let's first grok things::
>>> grok.testing.grok('megrok.rdb.meta')
>>> grok.testing.grok(__name__)
We start using the database now::
>>> session = rdb.Session()
Let's start using the database now::
>>>... | 2,327 | 770 |
from types import TracebackType
from typing import Optional, Type
from redis import StrictRedis
from typing_extensions import Literal
from foundation.locks import AlreadyLocked, Lock
class RedisLock(Lock):
LOCK_VALUE = "LOCKED"
def __init__(self, redis: StrictRedis, name: str, timeout: int = 30) -> None:
... | 841 | 255 |
"""
Bitwarden crypto functions.
Yes, this code is UGLY, The bitwarden documentation is either
missing, inconsistent or confusing.
This needs a refactor, but unknown if I will get to it before I move back to rust
where this code probably should live for reals.
See tests/test_bitwarden.py if you want to make sense of... | 7,124 | 2,605 |
#
# GenPROTO by Emanuele Ruffaldi 2009
# v1 2009/12/05
#
# TODO:
# - nicer Simulink layout
# - hash as annotation or as output
# - encoder id > 256 in particular using extended encoding (lsb+msb)
# - Alternative: XVR encoding of an array
# - Support for new types
import hashlib
def fixref(x):
if type(... | 12,624 | 5,081 |
from rlkit.samplers.data_collector import VAEWrappedEnvPathCollector
from rlkit.visualization.video import VideoSaveFunction
from rlkit.torch.her.her import HERTrainer
from rlkit.torch.sac.policies import MakeDeterministic
from rlkit.torch.sac.sac import SACTrainer
from rlkit.torch.vae.online_vae_algorithm import Onlin... | 44,776 | 14,830 |
# Simple wrapper for data preparation
#
# Input: ADNI data as pandas dataframe
# Output: Modified dataframe
# * handle missing data: remove individuals with missing demographics?
# * stables and progressors (clinical diagnosis)
#
# Author: Neil Oxtoby, UCL, January 2018
# Translated and modified from earlier MAT... | 2,200 | 819 |
#!/router/bin/python
#from rpc_exceptions import RPCExceptionHandler, WrappedRPCError
from jsonrpclib import Fault, ProtocolError, AppError
class RPCError(Exception):
"""
This is the general RPC error exception class from which :exc:`trex_exceptions.TRexException` inherits.
Every exception in this clas... | 5,237 | 1,444 |
import logging
import numpy as np
import scipy.stats
def mean_confidence_interval(data, confidence=0.95):
n = len(data)
m, se = np.mean(data), scipy.stats.sem(data)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
def print_latency_stats(data, ident, log=False):
npdata =... | 1,319 | 535 |
"""Common imports used by other modules in this package.
They are collected here so we can switch between PySide6, PySide2 and PyQt5
depending on what's installed.
A specific Qt package can be specified in the pyxll.cfg file by setting
'qt' in the JUPYTER section, eg::
[JUPYTER]
qt = PyQt5
"""
import logging... | 2,038 | 663 |
# coding=utf-8
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... | 2,852 | 866 |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/collective/collective.recipe.beanstalkd
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import pa... | 2,160 | 661 |
# -*- encoding: utf-8 -*-
'''
@File : LGNN.py
@Time : 2021/03/26 16:55:20
@Author : Fei gao
@Contact : feig@mail.bnu.edu.cn
BNU, Beijing, China
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class LGNN_layer(nn.Module):
def __init__(self, size_Fa,
s... | 5,187 | 1,948 |
import random
if __name__ == '__main__':
""" the seeder module creates sample data using the given template
the template is in the seeder_data file,
it specifies the attributes and values our data has
output: data.csv
"""
# read template
with open("Cloud/storage/data/seeder_da... | 1,682 | 525 |
#
# @lc app=leetcode id=78 lang=python3
#
# [78] Subsets
#
# @lc code=start
from typing import List
import itertools
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
sz = len(nums)
ret = [[]]
cnt = 1
while cnt <= sz:
idx = list(itertools.combination... | 485 | 176 |
"""
백준 1546번 : 평균
"""
number = int(input( ))
scores = list(map(int, input( ).split( )))
temp = -1
for score in scores:
if score > temp:
temp = score
whole = sum(scores)
print((whole * 100 / temp) / number) | 220 | 103 |
import copy
import crcmod
from opendbc.can.can_define import CANDefine
from selfdrive.car.tesla.values import CANBUS
class TeslaCAN:
def __init__(self, dbc_name, packer):
self.can_define = CANDefine(dbc_name)
self.packer = packer
self.crc = crcmod.mkCrcFun(0x11d, initCrc=0x00, rev=False, xorOut=0xff)
... | 1,406 | 570 |
# This script will switch UV Set between "map1" and "atlasmap".
# Useage:
# Select meshes and run this script
import maya.cmds as cmds
def uvsetTgl():
shape_node = cmds.ls(sl=True, fl=True, dag=True, type='shape')
current_uvset = cmds.polyUVSet(shape_node[0],q=True, currentUVSet=True)
for shape in shap... | 888 | 339 |
#!/usr/bin/env python
import filecmp
import os
import sys
import unittest
class AcceptanceTests(unittest.TestCase):
@classmethod
def add_test(cls, dirpath, filename):
basename = os.path.splitext(filename)[0]
if dirpath.startswith('./'):
dirpath = dirpath[2:]
if dirpath.end... | 2,480 | 577 |