text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding:utf-8 -*-
from engine.trainer import Trainer
from engine.env import Env
from data.build import build_dataloader
from engine.trainer_collection.MORAN import MORAN_Trainer
from engine.trainer_collection.GRCNN import GRCNN_Trainer
from engine.trainer_collection.RARE import RARE_Trainer
from engine.tr... | 714 | 244 |
# -*- test-case-name: xquotient.test.test_mta -*-
# Copyright (c) 2008 Divmod. See LICENSE for details.
"""
Support for SMTP servers in Quotient.
Implementations of L{twisted.mail.smtp.IMessageDeliveryFactory},
L{twisted.mail.smtp.IMessageDelivery}, and L{twisted.mail.smtp.IMessage} can be
found here. There are cla... | 21,117 | 5,773 |
# (C) Copyright 2021-2022 United States Government as represented by the Administrator of the
# National Aeronautics and Space Administration. All Rights Reserved.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# --... | 8,122 | 2,016 |
from django.urls import path, include
from glitchtip.routers import BulkSimpleRouter
from .views import UserViewSet
router = BulkSimpleRouter()
router.register(r"users", UserViewSet)
urlpatterns = [path("", include(router.urls))]
| 233 | 70 |
# Generated by Django 3.0.10 on 2020-10-01 03:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('board', '0002_board_user'),
('pin', '0002_pin_user'),
]
operations = [
migrations.AddField(
... | 499 | 177 |
# coding: utf-8
import numpy as np
def relu(x):
return np.maximum(0, x)
x = np.arange(-5.0, 5.0, 0.1)
y = relu(x)
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" %... | 414 | 179 |
def is_palindrome(num):
if num < 0:
return False
str_1 = str(abs(num))
str_2 = str_1[::-1] # save the reverse num
print(str_2)
return str_1 == str_2
print(is_palindrome(7107))
| 207 | 89 |
import unittest
from intuitquickbooks import QuickBooks
from intuitquickbooks.objects.purchaseorder import PurchaseOrder
class PurchaseOrderTests(unittest.TestCase):
def test_unicode(self):
purchase_order = PurchaseOrder()
purchase_order.TotalAmt = 1000
self.assertEquals(str(purchase_ord... | 530 | 163 |
from django.test import TestCase
from .models import Profile
from django.contrib.auth import get_user_model
from locations.models import Neighborhood, Admin
class ProfileModelTest(TestCase):
def setUp(self):
self.user1 = get_user_model().objects.create_user(username = 'testuser', email = 'test@email.com'... | 857 | 264 |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from .core import *
from .pattern import *
from .guess import *
| 109 | 42 |
"""
Use this connection to read data from a Siemens S7 PLC.
To install the snap7 package use 'pip install python-snap7'
You may need to install the repositories:
'sudo add-apt-repository ppa:gijzelaar/snap7'
'sudo apt-get update'
'sudo apt-get install libsnap7-1 libsnap7-dev'
Read the documentation to learn how to us... | 955 | 284 |
# -*- coding: utf-8 -*-
"""
Test the rejection proposal class.
"""
import numpy as np
import pytest
from unittest.mock import Mock, create_autospec, patch
from nessai.livepoint import numpy_array_to_live_points
from nessai.proposal import RejectionProposal
@pytest.fixture
def proposal():
return create_autospec(R... | 3,850 | 1,362 |
# *
import qelos as q
import torch
from functools import partial
from semparse.attention import *
import numpy as np
from semparse.trees import parse as tparse
class EncDec(torch.nn.Module):
def __init__(self, inpemb, enc, dec, **kw):
super(EncDec, self).__init__(**kw)
self.inpemb, self.enc, self.... | 13,912 | 5,109 |
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP.
# Copyright (2016-2017) Universidade Federal de Campina Grande
#
# 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
#
# ... | 29,007 | 8,835 |
#######################################################################################################
# a basic (thermal) unit commitment model, drawn from: #
# A Computationally Efficient Mixed-Integer Linear Formulation for the Thermal Unit Commitment Problem #
# Migu... | 54,525 | 17,680 |
"""Module that inports geenrate token function"""
from .generate_tokens import generate_token
from .token_required import token_required
| 137 | 34 |
def get_compiled_model(X, target, log_dir):
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
input_layer = Input(shape=(X.values.shape[1]), name='Areadata')
dense_layer_1 = Dense(64, ... | 1,972 | 695 |
from rhythmic import rhythmicDB, faultReturnHandler;
from . import configuration, scanFolder, unpackSingleFile;
def restoreFile(data):
"""
var data =
{
"file_absolute_path": absolute_path,
"model_path": window.model_path,
"model_id": window.the_model_id,
"version_number": w... | 1,712 | 472 |
import pytest
from random import randint
from num2words import WordNumeral, NumberTooLarge
@pytest.mark.parametrize("num, answer", [
(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"), (6, "six"),
(7, "seven"), (8, "eight"), (9, "nine"), (10, "ten"), (11, "eleven"),
(12, "twelve"), (13, "thirt... | 5,723 | 2,055 |
"""Contains lax GraphQlScalarDescriptors for the built-in scalar types.
Contains non-strictly validating GraphQlScalarDescriptors for the
built-in scalar types. By "non-strictly validating", we mean that
Python methods and attributes that return field values of scalar types
need not return values strictly of those sc... | 773 | 209 |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from threading import Timer
import json
import time
import urllib2
import web
# new year schedule: time -> freeform list of countries, list of countries, list of cities
schedule = [
['-14:00', 'Samoa and Christmas Island/Kiribati',
'Samoa,Chri... | 14,775 | 5,341 |
# -*- coding: utf-8 -*-
# Copyright 2016 IBM 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | 4,652 | 1,281 |
#Given the two integers, print the least of them.
a = int(input("a = ?"))
b = int(input("b = ?"))
if a < b:
print("least of them is a = %s" %a)
elif b < a:
print("least of them is b = %s" %b)
| 202 | 85 |
from pymongo import MongoClient
import psycopg2
def mongoConnection():
mongo_conn = MongoClient('mongodb://157.245.243.16:3004/?retryWrites=false')
return mongo_conn
def postgreeConnection():
sql_conn = psycopg2.connect(host='157.245.243.16', database='PROJETO_API_NEMO',
user='username', password='... | 675 | 238 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... | 13,288 | 4,186 |
# encoding: UTF-8
import vtConstant
from femasGateway import FemasGateway as gateway
gatewayName = 'FEMAS'
gatewayDisplayName = u'飞马'
gatewayType = vtConstant.GATEWAYTYPE_FUTURES
gatewayQryEnabled = True
| 206 | 82 |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getList(self):
ans = []
while self:
ans.append(str(self.val))
self = self.next
return "->".join(ans)
class Solution:
... | 795 | 251 |
import dataclasses as dto
@dto.dataclass(eq=True)
class Node:
id: int
author_name: str
author_id: int
text: str
like_count: int
parent_id: int
published_at : str | 189 | 68 |
from abc import ABC, abstractmethod
class Requester(ABC):
@abstractmethod
def get_request(self,**kwargs):
raise NotImplementedError
class Request(ABC):
__slots__ = ['_saver']
def __init__(self, saver):
self._saver = saver
def save(self, data):
return self._saver.save(data)
def __str__(self):
return s... | 1,988 | 724 |
from django.contrib import admin
from api.models import *
# Register your models here.
#class ChallengeAdmin(admin.ModelAdmin):
# """
# Sets the display settings for the challenge model in the django admin
# interface.
# """
# list_display = ('category', 'points', 'title')
admin.site.register(Chal... | 427 | 132 |
"""
This module is used for checking the project code for compliance with PEP8.
"""
import os
from pylint_af import PyLinter
if __name__ == '__main__':
PyLinter(
root_directory=os.path.dirname(os.path.dirname(__file__)),
ignored_statements={'E0401', 'E0402', 'E0611'}
).check()
| 308 | 115 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2018-03-25 18:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("profiles", "0007_auto_20170711_2025")]
operations = [
migrations.AlterField(
... | 712 | 224 |
# -*- coding: utf-8 -*-
"""
@file
@brief Some automation helpers to grab mails from students about projects.
"""
def build_mailing_list(names, domain, format="{first}.{last}@{domain}"):
"""
Infers mails from a list of names.
@param names list of strings
@param domain something li... | 1,015 | 307 |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 08:52:15 2017
@author: Yuki
"""
from PyQt5.QtGui import QFont,QIcon
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QToolBar,QAction,QMainWindow,QVBoxLayout,QWidget,QHBoxLayout,QTabWidget,QStatusBar,QTextEdit,QApplication,QWidgetAction,QMenuBar,QMenu,QT... | 10,329 | 3,478 |
import numpy as np
import sys
class screen:
'''
This class handle creating and displaying task of game screen
'''
def __init__(self,HEIGHT,WIDTH):
self.width = WIDTH
self.height = HEIGHT
self.screenarray = np.full((HEIGHT,WIDTH),' ', dtype='<U25')
def showscreen(self):
... | 1,215 | 364 |
import webbrowser
from django.shortcuts import render
# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from libs import sinaweibopy3
from mall import settings
from oauth.models impo... | 8,061 | 3,278 |
#!/usr/bin/python3
import os
import yaml
import shutil
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
from zipfile import ZipFile
_DEFAULT_EXE_NAME = 'muscle'
_ENV_VAR = 'MUSCLE_EXE'
# From my observations ...
#
# Calculation strategy:
# - First run short sequences on one thread. Sort them... | 2,434 | 809 |
import datetime
import json
import pickle
from nose.tools import eq_
import pylibmc
import _pylibmc
from pylibmc.test import make_test_client
from tests import PylibmcTestCase
from tests import get_refcounts
f_none = 0
f_pickle, f_int, f_long, f_zlib, f_text = (1 << i for i in range(5))
class SerializationMethodT... | 7,255 | 2,358 |
1.woshint
2.niyeshi
| 20 | 14 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from data.models import SkyPicture, WeatherMeasurement, RadiosondeMeasurement, MeasuringDevice
from forms import DateStationForm, DateForm
from django.shortcuts import redirect
from django.conf import settings
import numpy as ... | 20,200 | 6,631 |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""
Input/Problem:
pos/neg ints
ASSUME fits in mem
CAN have an empty array
dupes
unsorted
ASSUME not immutable
- out: 2D int ---> all poss triplets... | 2,995 | 874 |
from yaml import YAMLObject
from . import APIRequest, Info
from typing import List
class MockSetup:
def __init__(self, info: Info = None, host: str = "http://localhost:5757", basePath: str ="/", apiRequests: List[object] = []):
self.info = info
self.host = host
self.basePath = basePath
self.apiRequest... | 470 | 155 |
import random
def main():
# Check if there questions have been answered consecutively
counter = 0
while True:
if counter != 3:
numOne = random.randint(0, 10)
numTwo = random.randint(0, 10)
print("What is the addition of {} and {}".format(numOne, numTwo))
... | 830 | 213 |
n, s = raw_input(), raw_input().replace(';.';, ';';).split()
ans = 0
for _ in s:
ans += [0, 1][_ in [';TAKAHASHIKUN';,';takahashikun';,';Takahashikun';]]
print ans
| 168 | 81 |
# start the service
shoutbox = Runtime.start("shoutbox","Shoutbox") | 67 | 22 |
import sys, os
from cx_Freeze import setup, Executable
import subprocess
subprocess.call("set TCL_LIBRARY=C:\Program Files (x86)\Python35-32\tcl\tcl8.6", shell=True)
subprocess.call("set TK_LIBRARY=C:\Program Files (x86)\Python35-32\tcl\tk8.6", shell=True)
# Dependencies are automatically detected, but it might need ... | 1,213 | 429 |
import json
import logging
import os
import unittest
from structlog import wrap_logger
from response_operations_social_ui.logger_config import logger_initial_config
class TestLoggerConfig(unittest.TestCase):
def test_success(self):
os.environ['JSON_INDENT_LOGGING'] = '1'
logger_initial_config(s... | 1,804 | 529 |
import matplotlib.pyplot as plt
import numpy as np
t1 = 44.3
x1 = np.linspace(0, 5 , 5)
y1 = np.array([142 , 10, 10, 10 ,10])
# Lambda = 0.5
t2 = 2.67
x2 = np.linspace(0, 5 , 5)
y2 = np.array([142 , 14, 14, 14 ,14])
# Lambda = 2
t3 = 1.8
x3 = np.linspace(0, 5 , 5)
y3 = np.array([142 , 20, 20, 20 ,20])
# Lambda = 1... | 1,074 | 567 |
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from tensorflow.keras.layers import LayerNormalization
from tensorflow.keras.models import load_model
def get_anomaly_model():
MODEL_PATH = "weights/anomaly_model.hdf5"
return load_model(MODEL_PATH, custom_objects={'LayerNormal... | 1,671 | 623 |
"""
Prepare a dataset (specifically an orthorectified Sentinel 1 scene in BEAM-DIMAP format) for datacube indexing.
Note, this script is only an example. For production purposes, more metadata would be harvested.
The BEAM-DIMAP format (output by Sentinel Toolbox/SNAP) consists of an XML header file (.dim)
and a direc... | 5,009 | 1,565 |
from datetime import timedelta
import re
from typing import Optional, Type
import yaml
from .common import add_custom_type
TIMEDELTA_TAG = '!timedelta'
TIMEDELTA_REGEX = re.compile(
r'^((?P<weeks>\d+?)w)?((?P<days>\d+?)d)?((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?$'
)
def format_timedelta(valu... | 1,727 | 649 |
# Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the follow... | 6,619 | 2,021 |
import hashlib
import hmac
import time
from abc import ABC, abstractmethod
from typing import Optional
class BaseSecureUrlBuilder(ABC):
@abstractmethod
def build(self, uuid: str) -> str:
raise NotImplementedError
class AkamaiSecureUrlBuilder(BaseSecureUrlBuilder):
"""Akamai secure url builder.
... | 2,300 | 752 |
from .tokens import *
import numpy as np
class Lexer:
def __init__(self):
self.__digits__ = '0123456789'
self.__ops__ = '+-*/^'
self.__unary_minus_equivalent__ = [ElementToken(-1), MulOp()]
def __is_digit__(self, ch):
return self.__digits__.find(ch) >= 0
def __is_op__(sel... | 2,228 | 649 |
'''Creates the mesh for a tube lithophane'''
import FreeCAD
# import FreeCADGui
# import Mesh, Part, MeshPart
import lithophane_utils
import utils.qtutils as qtutils
from base_lithophane_processor import BaseLithophaneProcessor
class CreateGeometryBase(object):
def Activated(self):
lithophaneImage, imag... | 937 | 260 |
# Copyright (C) 2018 SignalFx, Inc. All rights reserved.
import pytest
from opentracing.mocktracer import MockTracer
from opentracing.ext import tags as ext_tags
import opentracing
from signalfx_tracing.utils import trace
class DecoratorTest(object):
@pytest.fixture(autouse=True)
def _setup_tracer(self):
... | 7,576 | 2,434 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Benjamin Milde
"""
license = '''
Copyright 2017,2018 Benjamin Milde (Language Technology, Universität Hamburg, Germany)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may ... | 13,020 | 4,426 |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | 3,685 | 1,062 |
import unittest
from rdflib.graph import Graph
from rdflib.namespace import Namespace, FOAF, RDF, RDFS, SH
from rdflib.term import URIRef
class NamespacePrefixTest(unittest.TestCase):
def test_compute_qname(self):
"""Test sequential assignment of unknown prefixes"""
g = Graph()
self.asser... | 4,579 | 1,474 |
#!/usr/bin/python3
import json
import requests
from requests.auth import HTTPBasicAuth
import os
api_url_base = "https://api.github.com/"
headers = {
"Content-Type": "application/json",
"Accept": "application/vnd.github.v3+json"
}
def Run(user, key, username, repo_details, keep_file):
# Print User det... | 6,389 | 1,941 |
import requests
import os
import json
import zipfile
data = {}
data['items'] = []
rooms = []
tours = []
cont1 = 0
cont2 = 0
cont3 = 0
cont4 = 0
cont5 = 0
cont6 = 0
cont7 = 0
cont8 = 0
cont9 = 0
contt1 = 0
contt2 = 0
contt3 = 0
contt4 = 0
path_home = "file/MuseoNavale"
path_images = "file/MuseoNavale/images"
path_audi... | 11,348 | 3,622 |
from django.apps import AppConfig
class CurrentIssuesConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "backend.landlord"
| 161 | 52 |
import re, bs4
from project.server.main.parsers.strings import get_clean_text, get_orcid
# doi 10.1093
def parse_oup(soup, doi):
res = {"doi": doi}
res.update(parse_authors(soup))
res.update(parse_abstract(soup))
return res
def parse_authors(soup):
res = {}
authors = []
affiliations = []
... | 2,702 | 887 |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import math
from helper import train_test_split
def class_dict(data):
classes = {}
for row in data:
if (row[-1] not in classes):
classes[row[-1]] = []
classes[row[-1]].append(row)
return classes
def mean_std(data):
... | 1,756 | 662 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 11:06:48 2020
@author: dopiwoo
Given an array, find the length of the smallest subarray in it which when sorted will sort the whole array.
Example 1:
Input: [1, 2, 5, 3, 7, 10, 9, 12]
Output: 5
Explanation: We need to sort only the subarray [5,... | 1,538 | 643 |
from controllers.app import app
from repository.machine_repo import machineRepository
@app.get("/machines")
def read_machines():
return machineRepository.read_machines()
@app.post("/machines/create")
def create_machines():
return machineRepository.create_machine() | 275 | 80 |
import datetime
import threading
class Job(object):
def __init__(self):
self._lock = threading.RLock()
self._messages = []
self._active = False
def start(self, method):
def task():
self._active = True
self.log('Started')
method(self)
self.log('Finished')
self._active... | 636 | 201 |
from ddd_shop.sales.models import *
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import r... | 2,269 | 665 |
import urllib3
import certifi
import json
from secrets import googleAPIKey
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where()
)
def getAPI(address):
r = http.request('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, googleAPIKey))
... | 449 | 160 |
# periodic table related functions
class InvalidAtomicNumber(Exception):
"""
Error class for invalid atomic numbers.
"""
pass
def _check_atomic_number(z:int) -> None:
"""
Checks if the atomic number provided is valid or not.
"""
if z <= 0:
raise InvalidAtomicNumber("Atomic numb... | 4,129 | 1,257 |
# Generated by Django 2.1.7 on 2019-07-06 17:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fok', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_greeted',
field... | 374 | 129 |
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
@pytest.fixture
def driver (request):
#firefox_binary= FirefoxBinary("c:\\Prog... | 729 | 228 |
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
class PingStatisticsHeaderNotFoundError(Exception):
"""
Exception raised when a ping statistics header not found in
a parsing text.
"""
class EmptyPingStatisticsError(Ex... | 418 | 124 |
# This module just contains some of the more lengthy constants used in
# samples.py that would otherwise clutter that file.
from random import randint, random
BarChartJSONSampleData = {
'label': ['label A', 'label B', 'label C', 'label D'],
'values': [
{
'label': 'date A',
'value... | 83,217 | 28,465 |
# Write a simple spellchecker that tells you if the word is spelled
# correctly. Use the dictionary in the code below; it contains the
# list of all correctly written words.
# The input format:
# A single line with the "word"
# The output format:
# If the word is spelled correctly write Correct, otherwise,
# Incorrec... | 467 | 140 |
#!/usr/bin/env python3
import requests, sys, traceback, re
from bs4 import BeautifulSoup
wurl = "https://mnb.hu/arfolyamok"
def download(url):
try:
r = requests.get(url,allow_redirects = True, timeout = 10)
wtype = r.headers.get('content-type').split(';')
if wtype[0] == "text/html" and r.... | 1,264 | 488 |
import pandas as pd
import pytest
from owid.catalog import Table
from owid.catalog.utils import underscore, underscore_table
def test_underscore():
assert (
underscore(
"`17.11.1 - Developing countries’ and least developed countries’ share of global merchandise exports (%) - TX_EXP_GBMRCH`"
... | 5,023 | 1,841 |
import apsw
from os import path
from time import time
from CONFIGURATION import *
print("\nEnter encrypted text:\n\n")
hashedinput = input()
print("\nEnter the encrytion key:\n\n")
securecode = input()
if path.isfile(securecode + ".db"):
starttime = time()
encryptedmsg = hashedinput.split()
conn=apsw.Conn... | 1,434 | 479 |
import torch
import time
import numpy as np
from torchvision import datasets, transforms, models
from torch import nn
from torch import optim
from collections import OrderedDict
import torch.nn.functional as F
import torchvision.models as models
from torch.autograd import Variable
import argparse
import json
from uti... | 5,159 | 1,697 |
import math
km = float(input('Digite a distância pretendida na viagem em km: '))
if km <= 200 :
res = km * 0.50
print('O valor da passagem da viagem mais curta é R${:.2f}'.format(res))
else:
res1 = km * 0.45
print('O valor da passagem da viagem mais longa é R${:.2f}'.format(res1)) | 297 | 119 |
#!/usr/bin/python
import jobs_common
def main():
names = jobs_common.read_known_names()
for name in names:
print(name)
if __name__ == "__main__":
main()
| 177 | 63 |
"""
from tkinter import *
from tkinter.font import Font
import random
def get_names(filename):
global all_names
all_names = []
fileIn = open(filename, encoding='utf-8', errors='replace')
for line in fileIn:
all_names.append(line.strip())
return all_names
def generate_names():
ran... | 5,716 | 2,194 |
"""
This file contains the constants used in the sapcommissions module.
"""
# Client
API_VERSION = "v2"
BASE_URL: str = "https://{tenant}-{environment}.callidusondemand.com/api"
# Endpoints
ENDPOINT_URL = "/{version}/{endpoint}"
| 231 | 81 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import open as io_open
from builtins import str
from future import standard_library
standard_library.install_aliases()
__all__ = ... | 43,135 | 13,557 |
# pylint: disable=line-too-long
""" pileup.py """
import sys
import os
import uuid
from run import Run
class Tac(Run):
""" Pileup """
def add_options(self):
""" Define options """
self.add_option("-i", "--input-file", "string", "Input file")
self.add_option("-o", "--output-dir", "string... | 5,167 | 1,597 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses the command line, discovers the appropriate benchmarks, and runs them.
Handles benchmark configuration, but all the logic for
actually running the... | 11,122 | 3,397 |
# Copyright (c) 2020 HAICOR Project Team
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from __future__ import annotations
import csv
import gzip
import json
import os
import re
import click
import igraph
from knowledge.app import CONFIG_DIRECTORY, DATA_DIRECTORY, app, da... | 5,837 | 1,736 |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2013--, biocore development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------... | 6,023 | 1,644 |
"""Role testing files using testinfra."""
def test_mariadb_service_active(host):
assert host.service('mariadb').is_running | 128 | 43 |
#encoding=utf-8
from logger import setup_logger
from utils import *
from glob import glob
from skimage import measure as m
import os
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib as mlp
sample_files = sorted(glob('/media/ksc/code/Figure 4E/AK3 is better than perfect/'))
print(sample_files)
... | 2,308 | 744 |
from ..category import Category
class Animal(Category):
def get_values(self):
return [
'ant',
'cat',
'dog',
'lizard',
'lobster',
'snake',
'whale'
]
| 216 | 70 |
from flask import Flask, request
from server.data import convert_to_image
from server.model import classify_image
app = Flask(__name__)
app.config.update(
ENV='development ')
@app.route('/', methods=['GET'])
def about():
return "Welcome to camera-server!"
@app.route('/image', methods=['POST'])
def proce... | 729 | 233 |
#!/usr/bin/env python3
# -*- coding utf-8 -*-
__Author__ ='eamon'
#多重继承
class Animal(object):
pass
class Mammal(Animal):
pass
class Bird(Animal):
pass
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
class RunnableMixIn(object):
pass
class F... | 588 | 276 |
import tex_printable
"""
Step 1:
- Create a new word list in words.txt
- Run crosswords.py to generate crosswords_out.txt
Step 2:
- Run this program to call text_printable.py to generate crossword_puzzle.text
"""
tex_printable.print_tex() | 241 | 84 |
"""Config for Fates List"""
import json
from typing import List, Dict, Union
import os
with open("config/data/discord.json") as f:
_discord_data = json.load(f)
_server_data = _discord_data["servers"]
_role_data = _discord_data["roles"]
_channel_data = _discord_data["channels"]
_oauth_data = _disc... | 3,813 | 1,312 |
import pandas as pd
import numpy as np
import tensorflow as tf
import os
from os import listdir
from os.path import isfile, join
from collections import namedtuple
from tensorflow.python.layers.core import Dense
from tensorflow.python.ops.rnn_cell_impl import _zero_state_tensors
import time
import re
from sklearn.model... | 21,731 | 6,002 |
import paths
import sims4.reload
SUPPORT_RELOADING_SCRIPTS = False and (not paths.IS_ARCHIVE and paths.SCRIPT_ROOT is not None)
SUPPORT_GSI = False
with sims4.reload.protected(globals()):
service_manager = None
if paths.SUPPORT_RELOADING_RESOURCES:
_file_change_manager = None
if SUPPORT_RELOADING_SC... | 3,856 | 1,122 |
# -*- coding: utf-8 -*-
"""
Implementation of the posterior sampling RL algorithm (PSRL), as described in
"(More) Efficient Reinforcement Learning via Posterior Sampling," by I. Osband,
B. Van Roy, and D. Russo (2013).
Unlike preference-based learning algorithms, PSRL receives numerical reward
feedback after every s... | 13,012 | 3,676 |
# Copyright (c) 2018 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 app... | 5,501 | 1,960 |
from .test_mocks import MockView
from .test_mocks import MockWindow
from .workspace import maybe_get_first_workspace_from_window
from .workspace import maybe_get_workspace_from_view
from .workspace import WorkspaceFolder
from os.path import dirname
from unittest import TestCase
class WorkspaceTest(TestCase):
def... | 2,225 | 697 |