text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
# encoding: utf-8
# Copyright 2014 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
#
# deploy.py - Deploy the IPDA site into operations
import argparse, sys, logging, os, os.path, re, subprocess, pwd, urllib2, contextlib, tempfile, tarfile, str... | 17,580 | 6,097 |
from re import match
with open("input.txt") as x:
lines = x.read().strip().split("\n\n")
lines = [line.replace("\n", " ") for line in lines]
valid = 0
fields = {
'byr': lambda x: 1920 <= int(x) <= 2002,
'iyr': lambda x: 2010 <= int(x) <= 2020,
'eyr': lambda x: 2020 <= int(x) <= 2030,
... | 884 | 368 |
"""Test ImageNet pretrained DenseNet"""
import cv2
import numpy as np
from tensorflow.keras.optimizers import SGD
import tensorflow.keras.backend as K
# We only test DenseNet-121 in this script for demo purpose
from densenet121 import DenseNet
im = cv2.resize(cv2.imread('resources/cat.jpg'), (224, 224)).astype(np.f... | 1,321 | 554 |
from django.urls.base import reverse
from rest_framework import status
from global_id.urls import app_name
from core.tests.utils import BaseCaller
from ..creators import create_guid
def guid_detail_url(guid=None):
return reverse(f"{app_name}:guid-detail",
kwargs={'guid': guid or create_guid().... | 713 | 218 |
from simulation import *
def relu(ctx: SimulationContext, x: Connection):
relu1 = ctx.max(x, ctx.variable(0))
return relu1 | 132 | 46 |
class MicromagneticModell:
def __init__(self, name, Ms, calc):
self.name = name
self.Ms = Ms
self.field = None
self.calc = calc
def __str__(self):
return "AbstractMicromagneticModell(name={})".format(self.name)
def relax(self):
self.calc.relax(self)
def... | 1,126 | 425 |
#!/usr/bin/python
# This file is a part of the OpenSurgSim project.
# Copyright 2012-2015, SimQuest Solutions 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.o... | 7,225 | 2,505 |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField,BooleanField
from flask_wtf.file import FileAllowed,FileRequired,FileField
from wtforms.validators import DataRequired,Length,EqualTo,Email,ValidationError
from App.models import User
from App.extensions import file
class Regist... | 2,848 | 1,158 |
import shade
# Initialize and turn on debug logging
shade.simple_logging(debug=True)
for cloud_name, region_name in [
('my-vexxhost', 'ca-ymq-1'),
('my-citycloud', 'Buf1'),
('my-internap', 'ams01')]:
# Initialize cloud
cloud = shade.openstack_cloud(cloud=cloud_name, region_name=region_... | 443 | 149 |
# eventually we will have a proper config
ANONYMIZATION_THRESHOLD = 10
WAREHOUSE_URI = 'postgres://localhost'
WAGE_RECORD_URI = 'postgres://localhost'
| 151 | 57 |
#!/usr/bin/env python3
import json
import yaml
result = {}
with open('app/static/greenhalos-style.json') as json_file:
data = json.load(json_file)
for layer in data['layers']:
if 'source-layer' in layer:
minzoom = layer.get('minzoom', 0)
maxzoom = layer.get('maxzoom', 24)
... | 837 | 247 |
# Data and Code Container (DCC) format by Cervi
import typing
def is_int(var):
try:
int(var)
return True
except ValueError:
return False
def is_float(var):
try:
float(var)
return True
except ValueError:
return False
def is_hex(var):
try:
... | 14,203 | 3,852 |
#!/usr/bin/python
# Copyright (c) 2015, Richard Maw
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHO... | 4,245 | 1,579 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Class that manages a UQtie application's stylesheet
There are advantages and disadvantages to Qt stylesheets, Qt settings, and
Qt Style. They aren't mutually exclusive, and they don't all play together
either.
This module attempts to make it possible to use a stylesheet w... | 10,333 | 2,978 |
__author__ = 'Anonymous'
import time
import csv
import os.path
import pyclick
from pyclick.utils.YandexRelPredChallengeParser import YandexRelPredChallengeParser
from pyclick.utils.Utils import Utils
from pyclick.click_models.Evaluation import LogLikelihood, Perplexity
from pyclick.click_models.UBM import UBM
from py... | 7,104 | 2,202 |
"""
Дефинирайте фуннкция `is_even`, която приема число и върща `True` ако числото е
четно и `False` в противен случай.
>>> is_even(4)
True
>>> is_even(5)
False
"""
def is_even(number):
raise Exception('Not implemented')
| 242 | 100 |
##########################################################################
# NSAp - Copyright (C) CEA, 2013
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########... | 2,165 | 688 |
# Generated by Django 2.0 on 2018-08-25 14:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("events", "0042_allow_team_without_country")]
operations = [
migrations.RemoveField(model_name="team", name="is_premium"),
migrations.RemoveField(model_name... | 505 | 173 |
from hypatia import Model,Plotter
#%%
utopia = Model(
path = 'sets',
mode = 'Planning'
)
#%%
#utopia.create_data_excels(
# path = r'parameters'
#)
#%%
utopia.read_input_data(
path = r'parameters'
)
#%%
utopia.run(
solver = 'scipy',
verbosity = True,
)
#%%
utopia.to_csv(path='results')
#%%
#uto... | 1,904 | 663 |
""" Example module """
def java_maker(*args, **kwargs):
""" Make you a java """
java_library(*args, **kwargs)
| 119 | 37 |
"""
Base settings to build other settings files upon.
"""
from pathlib import Path
import environ
env = environ.Env()
# GENERAL
# -------------------------------------------------------------------------
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
PROJECT_NAME = "process_status_monitoring"
... | 3,600 | 1,042 |
#import all the libraries required
import csv, pickle, numpy as np, os
from sentence_transformers import SentenceTransformer, util
#Virtual Agent Model
class VAModel():
def __init__(self):
self.model = SentenceTransformer("stsb-mpnet-base-v2") #load pretrained model
self.qa = dict()
self.emb... | 2,039 | 589 |
from typing import Callable
import hashlib
import zlib
def __common(n: int, h: Callable, digest_size: int, b=0) -> float:
assert b <= digest_size
if b == 0:
return int.from_bytes(h(n.to_bytes(8, "big")).digest(), 'big') / 2**digest_size
else:
return (int.from_bytes(h(n.to_bytes(8, "big")).... | 2,703 | 1,360 |
import abc
from typing import List
from utils.datatypes import Source
class DataLoaderInterface(object):
@abc.abstractmethod
def get_name() -> str:
'''Returns an internal name for this loader'''
raise NotImplementedError("users must define a name for this loader")
@staticmethod
@abc.... | 793 | 208 |
N = int(input().strip())
names = []
for _ in range(N):
name,email = input().strip().split(' ')
name,email = [str(name),str(email)]
if email.endswith("@gmail.com"):
names.append(name)
names.sort()
for n in names:
print(n)
| 247 | 90 |
from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser
try:
from .etoken import token
except:
from etoken import token
import re
namespace = globals()
recurSearcher = set()
PrimaryDefList = AstParser([Ref('FieldDef'), SeqParser([LiteralParser(',... | 4,176 | 1,395 |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
data_edoSiguiente = [[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],
[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],
[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],
[1, 2, 3, 4],[1... | 4,128 | 1,605 |
import heapq
class Solution:
"""
@param matrix: a matrix of integers
@param k: An integer
@return: the kth smallest number in the matrix
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
Example
样例 1:
输入:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
k = 4
输出: 5
... | 1,794 | 759 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import struct
import asyncio
from io import BytesIO
from .base import TAsyncTransportBase, readall
from .buffered import TAsyncBufferedTransport
class TAsyncFramedTransport(TAsyncTransportBase):
"""Class that wraps another transport and frames its ... | 2,158 | 652 |
import pytest
import os
import requests
from habanero import exceptions, Crossref
from requests.exceptions import HTTPError
cr = Crossref()
@pytest.mark.vcr
def test_funders():
"funders - basic test"
res = cr.funders(limit=2)
assert dict == res.__class__
assert dict == res["message"].__class__
as... | 3,493 | 1,334 |
from fastapi import APIRouter, Depends
from starlette.responses import Response
from ... import TimeseriesFactory
from ...algorithm import DbDtAlgorithm
from .DataApiQuery import DataApiQuery
from .data import format_timeseries, get_data_factory, get_data_query, get_timeseries
router = APIRouter()
@router.get("/al... | 812 | 246 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 1,478 | 430 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 Michael Bittencourt <mchl.bittencourt@gmail.com>
#
# Distributed under terms of the MIT license.
"""
"""
from ncl.abstractelement import AbstractElement
class Property(AbstractElement):
def __init__(self, name, value=None, exte... | 598 | 202 |
import _recurrence_map
import numpy as np
def poincare_map(ts, ts2=None, threshold=0.1):
rec_dist = poincare_recurrence_dist(ts, ts2)
return (rec_dist < threshold).astype(int)
def poincare_recurrence_dist(ts, ts2=None):
if ts2 is None:
return _recurrence_map.recurrence_map(ts, ts)
else:
... | 372 | 141 |
import cv2
import math
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy import ndimage
from utils import ValueInvert
# TO-DO: Refactor this with np.nonzero??
def find_center_image(img):
left = 0
right = img.shape[1] - 1
empty_left = True
empty_right = True
for col in rang... | 2,755 | 983 |
import numpy as np
from collections import namedtuple, deque
import random
Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward', 'not_done'))
class ReplayBuffer(object):
def __init__(self, capacity):
self.memory = deque([], maxlen=capacity)
def push(self, *ar... | 1,223 | 385 |
from struct import pack, unpack
import binascii
import socket
HOST = '192.168.0.10'
PORT = 1337
BUFF_SIZE = 1024
START_TOKEN = "init"
DONE_TOKEN = "done"
FAIL_TOKEN = "fail"
def create_test_application(load_addr=0x08002000, size=64*1024):
'''
Creates a test application that simply returns to the boo... | 4,109 | 1,451 |
#!/usr/bin/env python
INTERVALS = [1, 60, 3600, 86400, 604800, 2419200, 29030400]
NAMES = [('second', 'seconds'),
('minute', 'minutes'),
('hour', 'hours'),
('day', 'days'),
('week', 'weeks'),
('month', 'months'),
('year', 'years')]
def humanize_time(amou... | 1,264 | 517 |
# -*- coding: utf-8 -*-
"""Generate random data for your tests."""
__all__ = (
'gen_alpha',
'gen_alphanumeric',
'gen_boolean',
'gen_choice',
'gen_cjk',
'gen_cyrillic',
'gen_date',
'gen_datetime',
'gen_email',
'gen_html',
'gen_integer',
'gen_ipaddr',
'gen_iplum',
... | 27,010 | 8,738 |
import gc
import pandas as pd
from application.application import Application
from clean_data.maker import Maker
from do_data.config import Columns
from do_data.getter import Reader
from do_data.joiner import Joiner
from do_data.writer import Writer
from do_data.config import Columns
from analyze_data.utils import Ut... | 2,614 | 992 |
from retrieval.hybrid.hybrid_base import HybridRetrieval, HybridLogisticRetrieval
from retrieval.hybrid.hybrid import TfidfDprBert, AtireBm25DprBert, LogisticTfidfDprBert, LogisticAtireBm25DprBert
| 197 | 81 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def upper_print(f):
def wrapper(*args, **kwargs):
f(*[i.upper() if hasattr(i, 'upper') else i for i in args], **kwargs)
return wrapper
if __name__ == '__main__':
text = 'hello world!'
print(text) # hello world!
ol... | 455 | 172 |
# SPDX-License-Identifier: MIT
# Copyright (c) 2022 MBition GmbH
from dataclasses import dataclass, field
from typing import List, Literal, Optional
from .nameditemlist import NamedItemList
from .utils import read_description_from_odx
UnitGroupCategory = Literal["COUNTRY", "EQUIV-UNITS"]
@dataclass
class PhysicalD... | 10,182 | 3,328 |
import os
from test import test_support
# Skip this test if _tkinter does not exist.
test_support.import_module('_tkinter')
this_dir = os.path.dirname(os.path.abspath(__file__))
lib_tk_test = os.path.abspath(os.path.join(this_dir, '..', 'lib-tk', 'test'))
with test_support.DirsOnSysPath(lib_tk_test):
i... | 562 | 221 |
from flask_wtf import FlaskForm
from wtforms import StringField,BooleanField,PasswordField,SubmitField
from wtforms.validators import Email,Required,EqualTo
from wtforms import ValidationError
from ..models import User
class LoginForm(FlaskForm):
email = StringField("enter your email adress",validators = [Require... | 1,254 | 341 |
if __name__ == '__main__':
# Check correct price prediction
price_input_path = 'tests/data/Price_Simple.csv'
price_input = open(price_input_path, 'r').read().splitlines()[0].split(';')
price_prediction = open('price_prediction.csv', 'r').read().splitlines()[0].split(';')
assert price_input == price_... | 992 | 346 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import APIClient
from ralph_a... | 4,421 | 1,334 |
"""
Copyright (2010-2014) INCUBAID BVBA
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, so... | 57,419 | 15,989 |
from distutils.core import setup
import glob
from setuptools import setup
def read_md(file_name):
try:
from pypandoc import convert
return convert(file_name, 'rest')
except:
return ''
setup(
name='clickmodels',
version='2.0.0',
author='Jiaxin Mao',
packages=['clickmode... | 647 | 201 |
#!/usr/bin/python2.6
# (c) [2013] LinkedIn Corp. 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 applicable ... | 3,227 | 886 |
from django.db import models
from lbworkflow.models import BaseWFObj
class Purchase(BaseWFObj):
title = models.CharField("Title", max_length=255)
reason = models.CharField("Reason", max_length=255)
def __str__(self):
return self.reason
class Item(models.Model):
purchase = models.ForeignKey... | 626 | 208 |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author : KDr2
# BohuTANG @2012
#
import sys
import random
import string
import time
import nessdb
def gen_random_str(len):
return ''.join([random.choice('abcdefghijklmnoprstuvwyxzABCDEFGHIJKLMNOPRSTUVWXYZ') for i in range(len)])
def ness_open(db_name):
return nessdb.Ne... | 900 | 431 |
from sanic import Request, Sanic
from sanic.response import text
from sanic_ext import openapi
from sanic_ext.extensions.openapi.definitions import ExternalDocumentation
from utils import get_spec
def test_external_docs(app: Sanic):
@app.route("/test0")
@openapi.document("http://example.com/more", "Find more... | 1,588 | 475 |
#!/usr/bin/env python
'''
Sets up websocket server support to run the server in one HTML page and the client in another HTML page. Each connects to a websocket server, which we relay together, so the two pages think they are connected to each other (see websocket_bi tests in emscripten).
Instructions for websocket ne... | 2,472 | 838 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | 13,106 | 4,406 |
import pickle
import matplotlib.pyplot as plt
import matplotlib as mpl
#mpl.use('pdf')
import itertools
import numpy as np
from datetime import datetime
import torch
from torch import nn
from torch import optim
import os
import sys
import pandas as pd
from utils.utilities import meter
from utils import make_histos
fro... | 7,106 | 3,118 |
# Copyright 2019-2021 Cambridge Quantum Computing
#
# 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 a... | 13,195 | 4,857 |
# terrascript/data/nomad.py
import terrascript
class nomad_acl_policy(terrascript.Data):
pass
class nomad_acl_token(terrascript.Data):
pass
class nomad_deployments(terrascript.Data):
pass
class nomad_job(terrascript.Data):
pass
class nomad_namespaces(terrascript.Data):
pass
class nomad_... | 506 | 203 |
import json
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
def before_all(context):
context.peer_queue = None
class DummyPeeringHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfi... | 690 | 215 |
print('===== DESAFIO 041 =====')
nascimento = int(input('Digite o ano q vc nasceu: '))
idade = 2021 - nascimento
print(f'vc tem {idade} anos')
if idade <= 9:
print('vc é um nadador mirim')
elif idade > 9 and idade <= 14:
print('vc é um nadador infantil')
elif idade > 14 and idade <= 19:
print('vc é um na... | 456 | 184 |
"""
django:
https://docs.djangoproject.com/en/3.0/ref/settings/#allowed-hosts
"""
from ..env import env
ALLOWED_HOSTS = env("HCAP__ALLOWED_HOSTS", default=[])
| 165 | 66 |
'''
FileName:
Author:KWJ(kyson)
UpdateTime:2016/10/10
Introduction:
'''
from __future__ import division
import copy
from operator import attrgetter
from ryu.base import app_manager
from ryu.base.app_manager import lookup_service_brick
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATC... | 16,677 | 5,340 |
#coding: utf-8
#date: 2018/7/30 19:07
#author: zhou_le
# 求1000以下3和5的倍数之和
print(sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])) | 146 | 97 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorboard/uploader/proto/server_info.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor a... | 19,502 | 7,155 |
"""
Hypothesis data generator helpers.
"""
from datetime import datetime
from hypothesis import strategies as st
from hypothesis.extra.dateutil import timezones as dateutil_timezones
from hypothesis.extra.pytz import timezones as pytz_timezones
from pandas.compat import is_platform_windows
import pandas as pd
from ... | 2,192 | 853 |
# Generated by Django 2.2.4 on 2019-09-12 13:26
from django.db import migrations
INDUSTRY_NAMES = (
'Advanced manufacturing',
'Aerospace',
'Agri-technology',
'Automotive',
'Biotechnology',
'Cleantech',
'Construction ',
'Consumer products',
'Cyber security',
'E-commerce',
'... | 1,397 | 519 |
# coding: utf-8
# Copyright 2013 The Font Bakery 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 re... | 4,656 | 1,514 |
"""Module for regex components."""
from .regexconfig import RegexConfig
__all__ = ["RegexConfig"]
| 100 | 29 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-26 12:31
from __future__ import unicode_literals
import json
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('annotations', '0005_auto_20170826_1424'),
... | 1,968 | 528 |
import os
import statistics
import sys
def get_mean_std(out_csv):
with open(out_csv) as f:
lines = f.readlines()
tests = dict()
for t in lines[1:]:
t = t.split(",")
test_name = t[0].strip()
opt = float(t[2].strip())
tests[test_name] = tests.get(test_name, list()) + [... | 1,778 | 650 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--rn152", action="store_true", default=False,
help="Train a larger ResNet-152 model instead of ResNet-50")
parser.add_argument("--rn50v2", action="store_true", default=False,
help="Train ResNet-50 V2 model in... | 12,686 | 4,645 |
# Copyright Evan Hazlett and 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 or agreed to ... | 5,591 | 1,619 |
rows = []
try:
while True:
rows.append(int(input()))
except EOFError:
pass
rows.sort()
goal = 2020
l = 0
r = len(rows) - 1
while rows[l] + rows[r] != goal and l < r:
if rows[l] + rows[r] < goal:
l += 1
else:
r -= 1
if rows[l] + rows[r] == goal:
print(rows[l] * rows[r])
e... | 343 | 151 |
"""
Cast admin URL patterns
"""
from django.urls import path
from . import views
_s = '<slug:slug>/'
urlpatterns = [
path(_s, views.cast_admin, name='cast_admin'),
path(_s+'section/new/', views.section_new, name='cast_section_new'),
path(_s+'section/<int:pk>/edit/', views.section_edit, name='cast_section... | 1,543 | 531 |
__version__ = '0.159.0'
| 24 | 15 |
from redbot.core.commands import Context
class SilentContext(Context):
async def send(self, content: str = None, **kwargs):
pass
| 143 | 42 |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 21:33:56 2022
@author: mahfuz
"""
from glob import glob
import nibabel as nif
import numpy as np
input_path_lables = r'C:\Users\mahfu\Desktop\Codes\nifiti_files\lables\*'
imput_labels = glob(input_path_lables)
for patient in imput_labels:
nifti_file = nif.load(... | 545 | 230 |
from typing import Mapping
import pax.tasks.registry as registry
import regex as re
import torch
from pax.tasks.datasets.api import Batch
from pax.tasks.models.api import Buffers, Model, Params, Tuple
from pax.tasks.tasks.api import Task
DEFAULT_DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
... | 4,873 | 1,610 |
def mostrar(n='', g=''):
if n == '':
n = '<desconhecido>'
if not g.isnumeric():
g = 0
return f'O jogador {n} fez {g} gol(s) no campeonato'
# Main
nome = input('Nome do Jogador: ').title()
gols = input('Número de Gols: ')
print(mostrar(nome, gols))
| 278 | 115 |
import mock
import os
import pandas as pd
from datetime import datetime
from flexmock import flexmock
from sportsipy import utils
from sportsipy.constants import HOME
from sportsipy.ncaab.constants import BOXSCORES_URL, SCHEDULE_URL
from sportsipy.ncaab.boxscore import Boxscore, Boxscores
MONTH = 1
YEAR = 2020
BOXSC... | 57,678 | 18,028 |
from .conftest import TestTimeouts
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConnectionError
class TestElasticsearch(TestTimeouts):
def test_connect(self):
with self.raises(ConnectionError):
Elasticsearch([self.connect_url()], timeout=1).cluster.health()
... | 458 | 125 |
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from mediasync.conf import msettings
import mediasync
import time
class Command(BaseCommand):
help = "Sync local media with remote client"
args = '[options]'
requires_model_validation = False
... | 1,179 | 340 |
import numpy as np
from coptim.function import Function
class Rosenbrock(Function):
def eval(self, x):
assert len(x) == 2, '2 dimensional input only.'
return 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2
def gradient(self, x):
assert len(x) == 2, '2 dimensional input only.'
... | 751 | 331 |
#!/usr/bin/python
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep
PORT_NUMBER = 8080
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','image/png')
self.end_headers()
with o... | 601 | 218 |
from typing import (
NamedTuple,
)
from lahja import (
BaseEvent,
)
class RawMeasureEntry(NamedTuple):
sent_at: float
received_at: float
class CrunchedMeasureEntry(NamedTuple):
sent_at: float
received_at: float
duration: float
class PerfMeasureEvent(BaseEvent):
def __init__(self,... | 868 | 284 |
from django.urls import path
from . import views
urlpatterns = [
path('nba/', views.PlayerListView.as_view(), name='nba-list-page'),
path('nba/<int:id>/', views.PlayerDetailView.as_view(), name='nba-detail-page'),
path('nba/search/', views.PlayerSearch.as_view(), name='nba-search-page'),
path('nfl/', v... | 531 | 197 |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello(request):
return HttpResponse("Hello world")
def date(request, year, month, day):
return HttpResponse({
year: year,
month: month,
day: day
})
| 292 | 83 |
#loop
bottles = 99
while (bottles > 0):
if (bottles > 1):
print bottles, "bottles of root beer on the wall", bottles, "bottles of root beer"
print "Take one down pass it around,", bottles, "bottles of root beer on the wall"
else:
print bottles, "bottles of root beer on... | 404 | 148 |
# Deep Learning applique a l'imagerie Compton avec les donnees du satellite INTEGRAL
# Hackatlon AstroInfo 2021
##___ Importations
import numpy as np
import matplotlib.pyplot as plt
import Utilitaires_Compton as compton
import pickle as pkl
from os import listdir
from sys import setrecursionlimit
# ___ Constantes... | 6,574 | 2,658 |
# Generated by Django 2.2.1 on 2019-05-22 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('insta', '0002_pictures'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', m... | 641 | 198 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import enum
import json
import os
import plistlib
import subprocess
import time
import tools
import requests
python_script_debug_enable = False # 是否开启debug模式 用于测试脚本
pwd = os.getcwd() # 当前文件的路径
ios_project_path = os.path.abspath(os.path.dirname(
pwd) + os.path.sep... | 15,134 | 5,149 |
import typing
def _find_type_origin(type_hint):
actual_type = typing.get_origin(type_hint) or type_hint
if isinstance(actual_type, typing._SpecialForm):
# case of typing.Union[…]
for origins in map(_find_type_origin, typing.get_args(type_hint)):
yield from origins
else:
... | 798 | 241 |
# -*- coding: utf-8 -*-
from lauschgeraet.args import args, LG_NS_MODE
import subprocess
import os
import sys
import logging
import netns
log = logging.getLogger(__name__)
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
TEST = os.path.exists('testing')
TEST_STATE = {
"l... | 5,128 | 1,762 |
import pdfplumber
import re
import csv
from tqdm import tqdm
print('(When entering file paths on windows, use \'/\' in the place of \'\\\')')
pdf_path = input('Enter the file path of the 1099 pdf:\n')
# open up the pdf file, keep trying until user enters valid file
valid_pdf = False
while not valid_pdf:
try:
pdf =... | 4,476 | 1,655 |
# Generated by Django 3.2.9 on 2021-12-13 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('awards', '0004_auto_20211213_1253'),
]
operations = [
migrations.RenameField(
model_name='rating',
old_name='avg_rate',
... | 365 | 139 |
import torch
import torch.nn as nn
import torch.nn.functional as F
def _make_residual(channels): # Nawid- Performs a 3x3 convolution followed by a 1x1 convolution - The 3x3 convolution is padded and so the overall shape is the same.
return nn.Sequential(
nn.ReLU(),
nn.Conv2d(channels, channels, 3, ... | 3,955 | 1,429 |
import os
import csv
import librosa
import numpy as np
import pandas as pd
from spider.featurization.audio_featurization import AudioFeaturization
# Read the test data csv
csv_file='data/testAudioData.csv'
df = pd.read_csv(csv_file)
# Read in the audio data specified by the csv
data = []
for idx, row in df.iterrows()... | 863 | 289 |
class Telecom:
def __init__(self, contact_db_id, system, value, use, rank, period):
self.contact_db_id = contact_db_id
self.system = system
self.value = value
self.use = use
self.rank = rank
self.period = period
def get_contact_db_id(self):
return self.contact_db_id
def get_system(self):
return se... | 497 | 196 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of ... | 7,617 | 2,440 |
# kasutaja sisestab 3 numbrit
number1 = int(input("Sisesta esimene arv: "))
number2 = int(input("Sisesta teine arv: "))
number3 = int(input("Sisesta kolmas arv: "))
# funktsioon, mis tagastab kolmes sisestatud arvust suurima
def largest(number1, number2, number3):
biggest = 0
if number1 > biggest:
big... | 524 | 187 |