text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
from girder_large_image.girder_tilesource import GirderTileSource
from . import DeepzoomFileTileSource
class DeepzoomGirderTileSource(DeepzoomFileTileSource, GirderTileSource):
"""
Deepzoom large_image tile source for Girder.
Provides tile access to Girder items with a Deepzoom ... | 522 | 176 |
# -*- coding: utf-8 -*-
from ppchartrenderer import *
from ppticketsperuserday import *
#from pphierarchicalrenderer import *
from ppreportrenderer import *
from ppgroupstatsrenderer import *
| 194 | 65 |
"""
# Copyright 2022 Red Hat
#
# 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 agr... | 2,674 | 815 |
#!/usr/bin/python
# author: Jan Hybs
import cihpc.core.structures as structures_init
from cihpc.cfg.config import global_configuration
from cihpc.core.structures.project_step_collect import ProjectStepCollect
from cihpc.core.structures.project_step_container import ProjectStepContainer
from cihpc.core.structures.proje... | 3,735 | 1,028 |
__all__ = ["parse_dimension"]
from typing import List
from maha.parsers.rules import (
RULE_DURATION,
RULE_NAME,
RULE_NUMERAL,
RULE_ORDINAL,
RULE_TIME,
)
from maha.parsers.templates import Dimension, DimensionType
from maha.rexy import Expression
def parse_dimension(
text: str,
amount_of... | 3,747 | 1,085 |
#!/usr/bin/env python
import argparse
import json
import math
import os
import re
import shutil
import sys
import tempfile
import pcbnew
from lxml import etree
default_style = {
"copper": "#417e5a",
"board": "#4ca06c",
"silk": "#f0f0f0",
"pads": "#b5ae30",
"outline": "#000000"
}
class SvgPathIte... | 16,854 | 5,469 |
import os
from pathlib import Path
from shutil import copyfile
from lib.common.selector import Selector
from lib.common.etypes import Etype, Index
from lib.common.exceptions import SelectorIndexError
BASE = Path("/mtriage")
class Local(Selector):
"""A simple selector for importing local files into mtriage.
It ... | 2,189 | 766 |
# Generated by Django 3.0.7 on 2020-11-18 01:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='datasetuploadmodel',
name='dataset_type',... | 620 | 214 |
import logging
import sys
sys.path.insert(0, '../')
import config
from tensorflow.python.tools import inspect_checkpoint as chkp
import tensorflow as tf
import numpy as np
import random
logging.basicConfig(filename=config.logFile,level=config.logLevelPlayer, format='%(asctime)s %(message)s')
... | 11,335 | 3,855 |
from maestro_api.libs.extended.enum import ExtendedEnum
from mongoengine import StringField
from maestro_api.db.mixins import CreatedUpdatedDocumentMixin
from maestro_api.libs.datetime import strftime
class AgentStatus(ExtendedEnum):
"""
Agents sends their status from time to time.
If Agent stop sending s... | 1,096 | 347 |
from django.core.management.base import BaseCommand
from ...apps.podcasts.models import Podcast
class Command(BaseCommand):
help = "Load initial data"
def handle(self, *args, **options):
verbose = (options['verbosity'] > 0)
if verbose:
self.stdout.write('Fetching all RSS feeds.\n... | 521 | 161 |
#!python3
"""
A context for running functions with a time-limit.
Throws an exception if the function does not finish within the limit.
USAGE:
with time_limit(10):
foo()
NOTE: This does not work on Windows. See:
https://stackoverflow.com/a/8420498/827927
"""
import signal
import contextlib
class TimeoutExceptio... | 1,003 | 329 |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login as UserLogin, logout as UserLogout, authenticate
from django.contrib import messages
from .models import *
from .verification import sendVerificationEmail
#SUGGESTED TO USE CLA... | 4,969 | 1,363 |
import os
import re
import sys
from posix import listdir
from shutil import copyfile
from pathlib import Path
import numpy as np
from PIL import Image
from skimage.transform import resize
import utils.image_io
TAG_FLOAT = 202021.25
TAG_CHAR = 'PIEH'
name="shaman_3"
if len(sys.argv) > 1:
name = str(sys.argv[1])
... | 5,476 | 2,206 |
# Copyright 2016 Thomas C. Hudson
# Governed by the license described in LICENSE.txt
import libtcodpy as libtcod
import cProfile
import scipy.spatial.kdtree
import config
import algebra
import map
import log
from components import *
import miscellany
import bestiary
import ai
import actions
import spells
import quest... | 24,684 | 9,105 |
# Copyright 2018 ZTE Corporation.
#
# 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 ... | 7,307 | 2,312 |
from unittest import mock
import freezegun
import pytest
@pytest.fixture
def target():
from maidchan.tasks import お屋敷のお仕事をする
return お屋敷のお仕事をする
@pytest.mark.parametrize(
"text, expected",
[
("メイドちゃん!褒めて!", "<@00000000>さん!すごーい!"),
("メイドちゃん!私を褒めて!", "<@00000000>さん!すごーい!"),
("メ... | 5,877 | 2,932 |
from __future__ import annotations
import ast
import asyncio
import itertools
import weakref
from collections import OrderedDict
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterable,
List,
N... | 65,821 | 16,649 |
import tkinter
from util import Variable_Slider_Widget
class Graph(tkinter.Toplevel):
PLOTTER_SIZE = (400, 400)
PLOTTER_WIDTH, PLOTTER_HEIGHT = PLOTTER_SIZE
BACKGROUND_COLOUR = "#ffffff"
POINTS_COLOUR = "#000000"
POINTS_OFFSET = PLOTTER_SIZE[0] // 2, PLOTTER_SIZE[1] // 2
def __init__(self,... | 2,513 | 900 |
"""
FLI.camera.py
Object-oriented interface for handling FLI USB cameras
author: Craig Wm. Versek, Yankee Environmental Systems
author_email: cwv@yesinc.com
"""
__author__ = 'Craig Wm. Versek'
__date__ = '2012-08-08'
import sys, time, warnings
try:
from collections import OrderedDict
except Impor... | 10,275 | 3,480 |
# we can use Segment Tree 24 and Segment Tree 31 and combine them.
class SegmentTree1: # add arithmetic progressions
def __init__(self, n):
self.size = 1
while self.size < n:
self.size *= 2
self.NO_OPERATION = (0, 0) # it should be neutral with respect to op_modify
... | 4,388 | 1,974 |
from terra_sdk.client.lcd import LCDClient, PaginationOptions
terra = LCDClient(
url="https://pisco-lcd.terra.dev/",
chain_id="pisco-1",
)
pagOpt = PaginationOptions(limit=2, count_total=True)
def test_allowances():
result, _ = terra.feegrant.allowances(
"terra17lmam6zguazs5q5u6z5mmx76uj63gldns... | 761 | 348 |
# Used for user-selected sort order
from letter_sentiment.custom_sentiment import get_custom_sentiments
DATE = 'DATE'
RELEVANCE = 'RELEVANCE'
SENTIMENT = 'SENTIMENT'
def get_selected_sentiment_id(filter_value):
if not filter_value.startswith(SENTIMENT):
return 0
sentiment_id = int(filter_value.strip... | 586 | 193 |
"""Internet packet basic
Simple operations like performing checksums and swapping byte orders.
"""
# Copyright 1997, Corporation for National Research Initiatives
# written by Jeremy Hylton, jeremy@cnri.reston.va.us
#from _ip import *
import array
import struct
from socket import htons, ntohs
def cksum(s):
if len(... | 1,419 | 653 |
# Generated by Django 2.1.1 on 2018-09-29 10:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0008_auto_20180928_1244'),
]
operations = [
migrations.AlterField(
model_name='product',
name='image',
... | 445 | 160 |
from model.group import Group
from random import randrange
def test_modify_first_groop(app):
if app.group.count() == 0:
app.group.create(Group(name="qweqwe", header="qweqwe", footer="qweqwe"))
old_groups = app.group.get_group_list()
index = randrange(len(old_groups))
group = Group(name="1", h... | 1,865 | 703 |
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, starting_vertex, end_vertex):
self.graph[starting_vertex].append(end_vertex)
def dfs(self, starting_vertex):
visitedVertices = defaultdict(bool)
v... | 946 | 322 |
# -*- coding: utf-8 -*-
#
import codecs
import os
from docx import Document
from docx.shared import Inches, Pt, RGBColor
import abstractRenderer
#
# Renders to Word .docx
#
class Renderer(abstractRenderer.AbstractRenderer):
def __init__(self, inputDir, outputDir, outputName, config):
abstractRe... | 7,312 | 2,421 |
import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('csvs', type=argparse.FileType('r'), nargs='+')
parser.add_argument('-out', type=argparse.FileType('w'), default='out.csv')
args = parser.parse_args()
pd.concat([pd.read_csv(f, sep='\t') for f in args.csvs],
axis=0).to_... | 357 | 128 |
#!/usr/bin/env python3
"""PyTest tests for the generate_histogram_plot.py module.
"""
import os
import sys
sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'amoebaelib')) # Customize.
from generate_histogram_plot import \
generate_histogram, \
generate_double_histogram, \
autolabel_bars, \
generate_bar_chart
... | 1,867 | 609 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle
import json
import numpy as np
import math
import cv2
import os
import random
import matplotlib.pyplot as plt
from pyquaternion import Quaternion
import pycocotools.coco as coco
# DATA_PATH = '..... | 10,149 | 3,833 |
def c():
return "HappyFilmore"
| 36 | 16 |
"""Scripts for second stage of labelling - ear and tail segmentations"""
from vis.utils import *
from dataset_production.mturk_processor import *
from scipy.ndimage import center_of_mass as COM
from matplotlib import colors
def extract_colours(rgb_array):
"""Given an array of (r,g,b) values, returns list of unique ... | 14,355 | 6,052 |
import pandas as pd
savename = "prefecture_city.csv"
savedf = False
for num in range(1, 48):
strnum = '{0:02d}'.format(num)
filename = "prefecture{}.txt".format(strnum)
df = pd.read_csv(filename, sep='|', skiprows=[1])
df.columns = ["nan0", 'prefecture_name', 'prefecture_code',
... | 664 | 277 |
from unittest.mock import patch
from funcy.funcs import identity
from extras.models import IXAPI
from utils.testing import ViewTestCases
class IXAPITestCase(ViewTestCases.PrimaryObjectViewTestCase):
model = IXAPI
test_bulk_edit_objects = None
@classmethod
def setUpTestData(cls):
IXAPI.obje... | 2,396 | 743 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from refinery.units.obfuscation import Deobfuscator
from refinery.units.obfuscation.ps1 import Ps1StringLiterals
class deob_ps1_escape(Deobfuscator):
def deobfuscate(self, data):
strlit = Ps1StringLiterals(data)
@strlit.outside
def... | 405 | 164 |
import warnings
import math
from typing import Optional, TypeVar
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import Module
from torch.nn import init
from torch.nn.parameter import Parameter
import torchshard
from .. import functional as F
from ...distributed import get_world_size, get_... | 7,399 | 2,198 |
from django import forms
from .models import Profile,Post,Neighbourhood,Business
from django.contrib.auth.models import User
class UpdateProfileForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['user','neighbourhood']
class NewHoodForm(forms.ModelForm):
class Meta:
model ... | 635 | 181 |
inputs = [[-14, -5], [13, 13], [20, 23], [-19, -11], [-9, -16], [21, 27], [-49, 15], [26, 13], [-46, 5], [-34, -1],
[11, 15], [-49, 0], [-22, -16], [19, 28], [-12, -8], [-13, -19], [-41, 8], [-11, -6], [-25, -9], [-18, -3]]
| 234 | 157 |
# pylint: disable=old-style-class, line-too-long
from NiaPy.tests.test_algorithm import AlgorithmTestCase, MyBenchmark
from NiaPy.algorithms.basic import BatAlgorithm
class BATestCase(AlgorithmTestCase):
def test_parameter_type(self):
d = BatAlgorithm.typeParameters()
self.assertTrue(d['Qmax'](10... | 1,639 | 686 |
from unittest import defaultTestLoader, TextTestRunner
import sys
suite = defaultTestLoader.discover(start_dir=".")
result = TextTestRunner(verbosity=2, buffer=True).run(suite)
sys.exit(0 if result.wasSuccessful() else 1)
| 223 | 70 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base class that defines Artella Shot for Solstice
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
import logging
import artellapi... | 3,104 | 925 |
"""Fixtures for integration tests."""
from pytest import fixture
@fixture(scope="module")
def test_bucket():
"""Create an S3 bucket for integration tests."""
import boto3
bucket_name = 'boto3-paginator-integration-test'
s3_client = boto3.client('s3')
_ = s3_client.create_bucket(Bucket=bucket_na... | 764 | 252 |
#!/usr/bin/env python
'''
Generate compilable .osl files from .mx templates
Adam Martinez
TODO: Some functionalization in place, can it be expanded?
Add ability to specify shader and shader type to compile to osl
Is there a more compact representation of the BUILD_DICT we can employ?
'''
import os
imp... | 17,094 | 6,216 |
from UCTB.dataset import NodeTrafficLoader
from UCTB.model import HM
from UCTB.evaluation import metric
from UCTB.utils import save_predict_in_dataset
data_loader = NodeTrafficLoader(dataset='Bike', city='NYC', closeness_len=0, period_len=0, trend_len=4,
with_lm=False, normalize=F... | 782 | 268 |
#
# proxy_model.py
#
# This source file is part of the FoundationDB open source project
#
# Copyright 2013-2020 Apple Inc. and the FoundationDB 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 o... | 14,764 | 4,667 |
#! /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
# "... | 2,808 | 837 |
# Generated by Django 2.0.1 on 2018-10-15 14:44
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_countries.fields
import security.models
import timezone_field.fields
import u... | 6,010 | 1,442 |
"""
ALL Query для GraphQL.
"""
import logging
import datetime
import graphene
from graphql import GraphQLError
from .types import (
AccountTestType, TestCaseType, StartTestType
)
from ..models import (
AccountTest, TestCase, Test
)
logger = logging.getLogger(__name__)
class RootQuery(graphene.AbstractType... | 4,857 | 1,505 |
from Bio import pairwise2
from Bio import SeqIO
from Bio.SubsMat.MatrixInfo import blosum62
s = 'PLEASANTLY'
t = 'MEANLY'
a = pairwise2.align.globalds(s, t, blosum62, -5, -5)
print(pairwise2.format_alignment(*a[0]))
| 218 | 95 |
def findmin(angka):
return min(angka)
| 42 | 17 |
# Copyright 2018-2019 SourceOptics Project Contributors
#
# 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... | 4,547 | 1,359 |
import random
import requests
from mitsbot_globals import bingAPIKey, animals, animalFilter, addEventListener
from discordHelpers import sendImageEmbed
async def getImage(searchTerm, imageType):
randomPage = random.randint(0, 200)
searchURL = "https://api.bing.microsoft.com/v7.0/images/search"
headers = ... | 2,820 | 798 |
import json
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
class QueryData():
CONFIG_FILE = "./config.json"
def __init__(self):
self.readConfigFile()
self.createInfluxClient()
def readConfigFile(self):
try:
with open(self.CONFIG_FILE, 'r... | 2,020 | 614 |
import os
import shutil
def get_instance(configuration):
return Filesystem(configuration)
class Filesystem:
def __init__(self, configuration):
if "filesystem" not in configuration:
raise KeyError("Filesystem not found in configuration")
if "location" not in configuration['filesyste... | 1,839 | 509 |
from omniscient.base.constants import *
from omniscient.base.logger import Log
from elasticsearch import Elasticsearch, helpers
import json
logger = Log("info")
class ESTripleStore(object):
"""
Triple store backend.
"""
def __init__(self, host, port, settings):
self.es = Elasticsearch(['{}:{}'.format(hos... | 2,049 | 692 |
from CommandTemplate import CommandTemplate
import GlobalStore
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['joinserver']
helptext = "Makes me join a server, if it's preconfigured."
adminOnly = True
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext =... | 1,223 | 390 |
from django.core.urlresolvers import reverse_lazy
from .models import PComment as Comment
from .forms import PCommentForm as CommentForm
def get_model():
"""
Return the model to use for commenting.
"""
return Comment
def get_form():
"""
Return the form to use for commenting.
"""
retur... | 398 | 114 |
from multiprocessing import Process
from panoptes.utils import error
def on_enter(event_data):
"""Take an observation image.
This state is responsible for taking the actual observation image.
"""
pocs = event_data.model
current_obs = pocs.observatory.current_observation
pocs.say(f"🔭🔭 I'm ... | 1,361 | 413 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 23 00:54:08 2019
@author: nelson
"""
import tensorflow_datasets.public_api as tfds
import os
import tensorflow as tf
classes = [{'name': 'road' , 'color': [128, 64,128]},
{'name': 'sidewalk' , 'color': [244, 35,232]},
... | 4,183 | 1,409 |
"""Utility functions."""
import os.path
import logging
import numpy as np
from jicbioimage.core.image import MicroscopyCollection
from jicbioimage.core.transform import transformation
from jicbioimage.core.io import (
AutoWrite,
FileBackend,
DataManager,
_md5_hexdigest_from_file,
)
from jicbioimage.t... | 4,697 | 1,618 |
from django.utils.html import strip_tags
def highlightingapply():
def highlight(self, text_block):
if not text_block:
return ''
self.text_block = strip_tags(text_block)
highlight_locations = self.find_highlightable_words()
found = False
for k, v in highlight_lo... | 831 | 232 |
#!/usr/bin/env python3
import unittest
from unittest import TestCase
import learn2learn as l2l
import numpy as np
from numpy.testing import assert_array_equal
from learn2learn.data import MetaDataset
from .util_datasets import TestDatasets
class TestMetaDataset(TestCase):
@classmethod
def setUpClass(cls) -... | 5,242 | 1,699 |
#!/usr/bin/python3
import logging
import sys
import threading
from gpiozero import LED, Button
from signal import pause
class Shutter:
UP = 'open'
DOWN = 'close'
STOP = 'stop'
name = None
logger = None
buttonUp = None
buttonDown = None
relayUp = None
relayDown = None
timeout ... | 4,974 | 1,514 |
# Generated by Django 2.2.4 on 2019-09-04 13:15
from django.db import migrations
def forward(apps, schema_editor):
Entry = apps.get_model('registration.entry')
Group = apps.get_model('bhs.group')
Chart = apps.get_model('bhs.chart')
es = Entry.objects.all()
for e in es:
try:
g ... | 1,094 | 379 |
# print("请输入一个正整数:", end=' ')
n = int(input("请输入一个正整数:"))
i = 0
digits = [] # 列表 list
while (n >= 10 ** i):
# digit = int(n % 10 ** (i + 1) / 10 ** i)
digit = n % 10 ** (i + 1) // 10 ** i # 取出每一位数字
#digits.insert(0, digit)
digits.append(digit)
i += 1
print("每位为%s" % digits)
len = len(... | 416 | 220 |
import json
import sys
import re
class BufferedWriter():
def __init__(self, txt='', max_len=80, out=sys.stdout):
self._txt = txt
self._len = len(txt)
self._max_len = max_len
self._out = out
def write(self, txt, force=False):
"""Write some text. If the line were to go b... | 3,469 | 1,016 |
#used as a configuration file
def fan:
pin = 4
dependencies = [“python3”,”gpiozero”]
| 91 | 34 |
"""
Contains various helper function related to CADS framework.
"""
import os
import errno
import pickle
from nameparser import HumanName
#pylint:disable=raising-bad-type
def ensure_directory(directory):
"""
Create the directories along the provided directory path that do not exist.
"""
directory = os.... | 6,742 | 2,031 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ibase_plugin import IBasePlugin
from abc import ABCMeta, abstractmethod
class IFunctionFactoryPlugin(IBasePlugin):
"""
Base class for all plugins of type Function. We call it Function adapter.
"""
__metaclass__ = ABCMeta
def __init__(self):
... | 1,974 | 562 |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 6 16:59:19 2016
@author: tvzyl
"""
import data
from sklearn.datasets import make_spd_matrix
from pandas import DataFrame
from numpy import mean, diag, eye, rot90, dot, array, abs
from numpy import zeros, ones, arange
from numpy.random import uniform
from scipy.stats ... | 17,459 | 6,877 |
#!/usr/bin/python3
import easy_print_101
| 41 | 18 |
import os
import glob
import random
from processing_functions import misc as msc
from shutil import copyfile
# define the number of samples you want
n_samples = 50
imgsPath = os.environ['HOME']+'/data/extracted_images/2019-07-11-16-21-46/ngr'
out_path = os.environ['HOME']+'/data/extracted_images/samples/'+msc.find... | 675 | 263 |
#!/usr/bin/env python3
# This script compares AppGene files for similiarty
# Run this script in terminal / command line to see the usage of arguments.
import os
import argparse
from sklearn.feature_extraction.text import HashingVectorizer
import json
import re
from sklearn.metrics.pairwise import cosine_similarity
im... | 16,626 | 4,678 |
#coding=utf-8
from jqdatasdk import *
class JQSDK_Connect:
def __init__(self):
#auth('18818273592','Chenmin585858') #账号是申请时所填写的手机号;密码为聚宽官网登录密码,新申请用户默认为手机号后6位
auth('15821295829', 'Niuniuniu2020')
#auth('13816896174', '896174')
def get_query_count(self):
return get_query_count(... | 328 | 195 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fixture import FixtureRGB
import math
import time
import numpy as np
def rel_diff(cur, ref) -> float:
if ref == 0:
return cur
return (ref - cur) / ref
def get_max_index(array):
max_index = 0
for i in range(len(array)):
if array[i] ... | 4,561 | 1,731 |
__all__ = [
'get_config_profile',
'get_default_accounts_profile',
'get_default_deterministic_analysis_settings',
'get_default_exposure_profile',
'get_default_fm_aggregation_profile',
'get_default_unified_profile',
'get_loc_dtypes',
'get_acc_dtypes',
'get_scope_dtypes',
'get_info_... | 3,880 | 1,535 |
n = int(input('Digite um número: '))
d = n * 2
t = n * 3
r = n ** (1/2)
print('O dobro de \033[4;31m{}\033[m vale \033[34m{}\033[m. '.format(n, d))
print('O triplo de \033[4;33m{}\033[m vale \033[36m{}\033[m. '.format(n, t))
print('A raíz quadrada de \033[4;35m{}\033[m é igual a \033[32m{:.2f}\033[m. '.format(n, r))
| 318 | 190 |
import requests
import json
from environs import Env
from django.http import HttpResponse, HttpResponseBadRequest, HttpRequest
from django.views.decorators.csrf import csrf_exempt, csrf_protect
env = Env()
@csrf_exempt
# @api_view(['POST'])
def request_access_token(request):
client_secret = env.str("GOOGLE_CLIENT... | 1,107 | 353 |
# 30 while문을 이용 100이상10000미만 5의배수 합구하기
number = 100
isloot = True
sumnum = 0
while isloot:
if number >= 10000:
isloot = False
sumnum += number
number += 5
print(sumnum)
# 34 화씨(F)를 섭씨(c)로 변환하는 프로그램 작성
# 섭씨 = (100/180) x (화씨 - 32)
F = 0
C = 0
isloot = True
while isloot:
F = int(input('섭씨로... | 555 | 396 |
def is_price_in_budget(price):
if price > 100 or price < 500:
is_in_budget = True
else:
is_in_budget = False
return is_in_budget
| 157 | 64 |
from Point_t import Point_t
from Leg import *
import math
class Line_t(Leg):
"""Classe représentant une ligne"""
def __init__(self, coo_tulpe_start, coo_tulpe_end, id):
Leg.__init__(self, id) #classe mere leg
self._point_start = Point_t(coo_tulpe_start) #point start du leg
se... | 747 | 294 |
import numpy as np
import pickle as pkl
import os
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
from latex_utils import latexify
baseline = "indiv"
methods = [
# "epo",
# "pmtl",
"linscalar",
# "gradnorm",
"gradortho",
"grad... | 6,344 | 2,378 |
import random
import factory
from django.utils import timezone
from api.addresses.tests.factories import AddressFactory
from api.organisations import models
from api.organisations.enums import OrganisationType, OrganisationStatus
from api.organisations.tests.providers import OrganisationProvider
factory.Faker.add_pr... | 1,849 | 519 |
from collections import OrderedDict
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.utils.urls import remove_query_param, replace_query_param
class HeaderLimitOffsetPagination(LimitOffsetPagination):
def paginate_queryset(self, queryset... | 2,187 | 595 |
from sanskrit_parser.generator.pratyaya import * # noqa: F403, F401
from sanskrit_parser.generator.dhatu import * # noqa: F403, F401
from sanskrit_parser.generator.pratipadika import * # noqa: F403, F401
from sanskrit_parser.base.sanskrit_base import DEVANAGARI
from sanskrit_parser.generator.sutras_yaml import sutra... | 462 | 194 |
#! /usr/bin/env python
from setuptools import setup, find_packages
setup(
name='txt2svg',
license="MIT",
version="0.1",
description='A tool for generating svg images from plain text files.',
url='https://github.com/CD3/txt2svg',
author='C.D. Clark III',
packages=find_packages(),
instal... | 444 | 152 |
from blog.models import Comment, Post
from django.contrib import admin
# Register your models here.
admin.site.register(Post)
admin.site.register(Comment)
| 157 | 44 |
import numpy as np
import tensorflow as tf
import elbow.util as util
from elbow import ConditionalDistribution
import scipy.stats
from elbow.gaussian_messages import MVGaussianMeanCov, reverse_message, forward_message
from elbow.parameterization import unconstrained, psd_matrix, psd_diagonal
class LinearGaussian(C... | 12,076 | 3,660 |
"""
Date: 2022.04.03 16:48:45
LastEditors: Rustle Karl
LastEditTime: 2022.04.03 20:21:38
"""
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 9090))
server.listen(50000)
while True:
client, client_address = server.accept()
client.send("OK")
| 300 | 147 |
from django.conf.urls import patterns, url
from nutrition import views
from django.views.generic import ListView
urlpatterns = [
url(r'^nutrition/ITEM/$', views.AddCommentList.as_view()),
url(r'^nutrition/ITEM/(?P<pk>[0-9]+)/$', views.AddCommentDetail.as_view()),
url(r'^nutrition/item/$', views.ItemList.as_... | 458 | 169 |
#desafio 55: maior e menor da sequência usando lista []
pessoas = [] #lista vazia
for c in range(1, 6):
peso = float(input(f'Peso da {c}ª pessoa: '))
pessoas = pessoas + [peso] #lista += [peso] #add os valores de peso na lista
print('><'*15)
print(f'\33[33m O Maior peso lido foi: {max(pessoas)}') #máximo va... | 413 | 177 |
import numpy as np
x1 = 1
x2 = 1
def sigm(x): return 1 / (1 + np.exp(-x))
# input
a0 = 1
a1 = x1
a2 = x2
# w input - layer 1
w01 = 1
w02 = 0.5
w11 = 1
w12 = 0
w21 = -1
w22 = 0.5
# layer 1
zh1 = (w01 * a0) + (w11 * a1) + (w21 * a2)
zh2 = (w02 * a0) + (w12 * a1) + (w22 * a2)
print(f"zh1 = {round(zh1, 2)}")
print... | 627 | 403 |
from store.user import User
from store import ModelStore as DataStore
from game import Game
from core.dotdict import DotDict
from server import EventServer
import sys
def prnt(obj, k):
def f(model, key, func):
print obj + ':' + k + ' -> ' + model[k]
return f
def server_main():
print ... | 1,659 | 622 |
## polyfilt.py
## This is my implementation of polyfilt.m
## Polyphase implementation of a filter
## using Python libraries numpy, scipy
##
## The main reference that I'll use is
## Gilbert Strang, and Kevin Amaratunga. 18.327 Wavelets, Filter Banks and Applications, Spring 2003. (Massachusetts Institute of Technology... | 5,164 | 1,352 |
import os
import json
def load_config_file(config_path):
if config_path is not None and os.path.isfile(config_path):
with open(config_path, "r") as config_file:
return json.load(config_file)
else:
return {}
class Config:
# Database configuration
db_host = "127.0.0.1"
... | 2,716 | 820 |
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... | 6,913 | 2,117 |
from src.model.catalogo_curso import CatalogoCurso
from src.model.curso import Curso
from src.model.materia import Materia
class TestCatalogo:
curso = "marcenaria"
materia_1 = "prego"
materia_2 = "parafuso"
materia_3 = "martelo"
def setup_method(self, method):
self.catalogo = CatalogoCur... | 2,139 | 769 |
"""Exceptions raised by TinyMongo."""
class TinyMongoError(Exception):
"""Base class for all TinyMongo exceptions."""
class ConnectionFailure(TinyMongoError):
"""Raised when a connection to the database file cannot be made or is lost.
"""
class ConfigurationError(TinyMongoError):
"""Raised when so... | 1,664 | 426 |
import os
import time
import json
import numpy as np
import pandas as pd
from supervised.automl import AutoML
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from pmlb import fetch_data, classification_dataset_names
results... | 2,149 | 753 |