content stringlengths 5 1.05M |
|---|
import numpy as np
# We create a rank 1 ndarray
x = np.array([1,2,3])
# We create a 3 x 3 ndarray
Y = np.array([[1,2,3],[4,5,6],[7,8,9]])
# We create a 3 x 1 ndarray
Z = np.array([1,2,3]).reshape(3,1)
# We print x
print()
print('x = ', x)
print()
# We print Y
print()
print('Y = \n', Y)
print()
# We print Z
print... |
def args2kwargs(thrift_spec, *args):
arg_names = [item[1][1] for item in sorted(thrift_spec.items())]
return dict(zip(arg_names, args))
|
from re import match
from tests import *
def test_root(app, client):
"""Testing root path."""
r = get(client=client, path="/")
assert 200 == r.status_code
assert "/" == r.json["path"]
assert "Punch Clock v0.1.0" == r.json["message"]
assert match(
"^202[0-9]-[0-1][0-9]-[0-3][0-9] [0-9... |
"""
The goal of this rewrite is to use the existing command framework of the discord.py library.
Here is its documentation:
https://discordpy.readthedocs.io/en/latest/index.html
"""
# imports
import discord
from discord.ext import tasks, commands
import configparser
import bot_database as db
import mathParser
import ... |
"""
Variable Substitution, Multiplication, Division, Scaling
"""
#*****************************************************************************
# Copyright (C) 2007 William Stein and Jonathan Hanke
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hop... |
n=float(input("Enter the number: \t"))
if n==0 :
print("Zero\n")
elif n<0 :
print("Negative\n")
else:
print("Positive\n") |
"""
MIT License
Copyright (c) 2021 ilkergzlkkr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... |
import base64
import click
import pytest
from evernote.edam.error.ttypes import EDAMUserException
from evernote_backup import cli_app_auth, cli_app_util
from evernote_backup.cli_app_click_util import NaturalOrderGroup
from evernote_backup.cli_app_util import ProgramTerminatedError
from evernote_backup.log_util import... |
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.metrics import Metric
from sklearn.metrics import f1_score, accuracy_score
epsilon = K.epsilon()
term_code = {'begin': 1, 'inside': 2, 'outside': 0, }
idx2polarity = {0: 'background', 1: 'positive', 2... |
import html
import re
from typing import List, Optional
from flask import Blueprint, current_app, jsonify, g
from flask_apispec import use_kwargs
from webargs.flaskparser import use_args
from neo4japp.blueprints.auth import auth
from neo4japp.blueprints.projects import ProjectBaseView
from neo4japp.constants import ... |
#Betrothed Numbers
#TOOLS
def Divisors(num):
from math import sqrt as mmsq
s=set([1])
i=1
a=int(mmsq(num)+1)
while i<=a:
if(num//i==num):
i+=1
continue
if (num%i==0):
if (num//i!=i):
s.add(num//i)
s.add(i)
i... |
"""
1. Вывести все коммиты (сообщения) и подсчитать все.
1.1 Вывести сообщения длина которых больше 10 и их кол-во
"""
import sys
import requests
url = 'https://api.github.com/repos/{}/{}/commits?page1&per_page=100'.format(sys.argv[1],sys.argv[2])
response = requests.get(url,headers={'Authorization':'Token ghp_v1... |
#! /usr/bin/env python
import math
import rospy
import tf
import tf2_ros
from sensor_msgs.msg import LaserScan
from darknet_ros_msgs.msg import BoundingBox #msg that contains bounding box coordinates
from darknet_ros_msgs.msg import BoundingBoxes
# from apriltag_ros.msg import Coordinates
#rostopic echo darknet_ros/bo... |
# The myplugin module must be locatable by Python.
# If you configured CMake in the build directory ``/path/to/repo/build`` then,
# assuming you are in ``/path/to/repo``, run the tests with something like
# PYTHONPATH=./cmake-build-debug/src/pythonmodule mpiexec -n 2 python -m mpi4py -m pytest tests/
# This test i... |
from glob import glob
from typing import List
import os
import pandas as pd
import wget
class EmoDB(object):
def __init__(self,
sampling_rate: int = 16000,
num_mel_bins: int = 40,
frame_length: int = 50,
frame_shift: int = 10,
m... |
# -*- coding: utf-8 -*-
# @Author: Zeyuan Shang
# @Date: 2016-05-04 20:42:41
# @Last Modified by: Zeyuan Shang
# @Last Modified time: 2016-05-04 20:43:41
s = raw_input()
n = len(s)
player1, player2 = 0, 0
for i in xrange(len(s)):
if s[i] in "AEIOU":
player1 += n - i
else:
player2 += n - i
if player1 > playe... |
# Removing "_pilon" from fasta titles and writing the new reference ot the right position
old_fasta = '../../Output/WGS/reference_refinement/pilon_output/w303_vlte.fasta'
new_fasta = '../../Output/WGS/reference/w303_vlte.fasta'
with open(new_fasta, 'w') as outfile:
with open(old_fasta, 'r') as infile:
for l... |
import discord, os, platform, asyncio
from discord.ext import commands
import core.config
class SchedulerEvents(commands.Cog, name='scheduler_events'):
def __init__(self, bot):
self.bot = bot
if core.config.TESTING:
self.channel = self.bot.get_channel(core.config.BOT_CHANNEL)
... |
# following PEP 386, versiontools will pick it up
__version__ = (0, 1, 7, "final", 0)
|
from ._command import Command, Commands
from .mkr import MakeReportCommand
from .debug import DebugCommand |
from cadorsfeed import db
from cadorsfeed.aerodb import lookup
from flask import current_app as app
def import_blacklist():
with app.open_resource('aerodb/blacklist.txt') as blacklist:
for line in blacklist:
line = line.strip()
if not line.startswith('#') and len(line) == 3:
... |
################################################################################
#
# Package : AlphaPy
# Module : estimators
# Created : July 11, 2013
#
# Copyright 2017 ScottFree Analytics LLC
# Mark Conway & Robert D. Scott II
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not us... |
from urllib.parse import parse_qsl, urlsplit
from social_apis.exceptions.social_api_error import *
def iterator(api_method, return_pages=False, **params):
r"""Returns a generator for results of specific supported method.
Usage::
>>> from social_apis.networks.facebook import Facebook
>>> facebook ... |
# Copyright 2020 KCL-BMEIS - King's College London
# 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... |
import os
from typing import Union
import sentry_sdk
from dependency_injector import containers
from flask_cors import CORS
from sentry_sdk.integrations.flask import FlaskIntegration
from .containers.dev_container import DevAppContainer
from .containers.prod_container import ProdAppContainer
env = os.environ.get('FL... |
import pytest, os, uuid, warnings
from tenable.downloads import Downloads
from tenable.errors import *
@pytest.fixture(scope='module')
def vcr_config():
return {
'filter_headers': [
('Authorization', 'Bearer 000'),
],
}
@pytest.fixture(autouse=True, scope='module')
def dl(request,... |
from django.test import TestCase
from mock import Mock, patch, mock_open
from .dummyrunner_settings import (
c_creates_button,
c_creates_obj,
c_digs,
c_examines,
c_help,
c_idles,
c_login,
c_login_nodig,
c_logout,
c_looks,
c_moves,
c_moves_n,
c_moves_s,
c_socialize... |
# -*- coding: utf-8 -*-
from providerModules.a4kScrapers import core
class sources(core.DefaultSources):
def __init__(self, *args, **kwargs):
super(sources, self).__init__(__name__, *args, **kwargs)
def _soup_filter(self, response):
try:
response = core.json.loads(response.text)
... |
# Copyright (c) 2021 Aiven, Helsinki, Finland. https://aiven.io/
from ._utils import find_component, find_user, format_uri
from .common import ConnectionInfoError
class PGConnectionInfo:
def __init__(self, host, port, username, dbname, password, sslmode):
self.host = host
self.port = port
... |
"""
src_constants.py
holds global speedrun.com API constants
"""
from data_models import CelesteGames
from dacite import from_dict
PLATFORMS : dict = {
"PlayStation 4" : "nzelkr6q",
"Xbox One" : "o7e2mx6w",
"PC" : "8gej2n93",
"Switch" : "7m6ylw9p",
"Google Stadi... |
from envyaml import EnvYAML
from nameko.standalone.rpc import ServiceRpcProxy
from nameko.exceptions import UnknownService
config = EnvYAML('config.yml')
CC = 'bnbbtc'
STREAM = 'depth'
SPEED = '1000ms'
LIMIT = 1000
with ServiceRpcProxy('listener', config) as proxy:
try:
proxy.get_order_book(CC, LIMIT)
... |
"""
Contains the elements made out of various layers which make up the
sublayers of the model.
"""
|
# -*- coding: utf-8 -*-
"""
@Time : 2018/7/17 下午2:42
@FileName: utils.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import itertools
import multiprocessing
import pickle
import re
import numpy as np
from joblib import Parallel, delayed
from tqdm import tqdm
np.random.seed(10245)
def get_file_chars... |
from __future__ import print_function
import argparse, sys, os, warnings
import librosa
import numpy as np
from numpy import linalg as LA
import keras
from keras.models import model_from_json
if not sys.warnoptions:
warnings.simplefilter("ignore")
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
FLAGS=None
def decide_cl... |
# 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... |
import math
import random
import weakref
from build_buy import is_location_outside
from interactions.constraints import CostFunctionBase
from sims4.tuning.tunable import HasTunableFactory, AutoFactoryInit, TunableRange, TunableTuple, Tunable, OptionalTunable
import sims4.math
import socials.geometry
import terrain
cla... |
"""
API to convert Cadene's models
Supported models:
-se_resnet50
-se_resnet101
-se_resnet152
-cafferesnet101
-bninception
-fbresnet152
-resnet18
-resnet34
-resnet50
-resnet101
-resnet152
Convert and save models with cadene_to_tf
Examples:
cadene_to_tf(modelList=['se_r... |
import unittest
from ilmklib import Graph
class TestGraph(unittest.TestCase):
def test_simple_errors(self):
g = Graph()
self.assertFalse(g.is_cyclic())
g.add_vertex("a")
with self.assertRaises(Exception):
g.add_vertex("a")
self.assertFalse(g.is_cyclic())... |
#!/usr/bin/env python3
# partial implementation of EDLIN
# (c) 2019 <christian.tschudin@unibas.ch>
import re
def editor(lines):
# expects an array of lines, returns an array of lines if modified else None
modif = False
curr = 0
while True:
cmd = input('*')
if len(cmd) == 0:
... |
from functools import partial
from multipledispatch import dispatch
from webpub_manifest_parser.core.ast import (
Collection,
CollectionList,
CompactCollection,
Link,
LinkList,
Manifestlike,
Metadata,
)
from webpub_manifest_parser.core.semantic import (
ManifestSemanticError,
Seman... |
import os
import json
import random
import numpy
import csv
import traceback
import subprocess
import concurrent
import collections
import operator
import math
def convert_latency_nanos_to_millis(latencies):
return list(map(lambda x: x / 1e6, latencies))
def get_region(config, server):
for region, servers i... |
from django.urls import path
from .views import ListDonor, DetailDonor
urlpatterns = [
path('', ListDonor.as_view()),
path('<int:pk>/', DetailDonor.as_view()),
] |
# Generated by Django 2.2.13 on 2020-08-26 20:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pipeline', '0062_auto_20200825_2231'),
('pipeline', '0062_auto_20200826_1735'),
]
operations = [
]
|
from flask import Response, send_file,request, make_response
from flask_restful import Resource
import json
import pandas as pd
import pymongo
client = pymongo.MongoClient(host='127.0.0.1', port=27017)
db_list = client.list_database_names()
db = client.data
class upload(Resource):
def post(self, data_type):
... |
nome = str(input('Digite seu nome completo: ')).strip().title().split()
tamanho= int(len(nome))
print('Ola, {} {}, bem vindo(a)!!'.format(nome[0], nome[tamanho-1]))
|
from urllib.request import urlretrieve
import os
import pandas as pd
import numpy as np
from datetime import datetime
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../data'))
UCI_DATASETS = []
def _UCI(C):
UCI_DATASETS.append(C)
return C
class Dataset:
ndim_x = None
ndim... |
import os
import sys
import unittest
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
import boto_utils
from constants import TABLE_NAME
class TestDynamoProvision(unittest.TestCase):
def setUp(self) -> None:
self.dynamodb = boto_... |
# -*- coding: utf-8 -*-
# @Author : DevinYang(pistonyang@gmail.com)
import math
from torch import nn
from torch.nn.init import xavier_normal_, xavier_uniform_, \
kaiming_normal_, kaiming_uniform_, zeros_
class XavierInitializer(object):
"""Initialize a model params by Xavier.
Fills the input `Tensor` w... |
# File executed when user click on `Run` button
# Must not run any test, just run the user
if __name__ == "__main__":
import template
template.score()
|
#! /usr/bin/env python
"""
Authors: Henning O. Sorensen
Center for Fundamental Research: Metal Structures in Four Dimensions
Risoe National Laboratory for Sustainable Energy
Technical University of Denmark
Frederiksborgvej 399
DK-4000 Roskilde
email:henning.sorens... |
from typing import Tuple, Any
from sty import fg, FgRegister, rs
class Palette:
# Default palette colors
BLUE: Tuple = (5, 156, 205)
GREEN: Tuple = (51, 222, 136)
RED: Tuple = (240, 70, 87)
YELLOW: Tuple = (249, 149, 72)
ORANGE: Tuple = (232, 149, 39)
BL_HX: str = '#%02x%02x%02x' % BLUE
... |
#!/usr/bin/env python
# Copyright 2018 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.
"""Checks that the main console and subconsole configs are consistent."""
import collections
import difflib
import os
import sys
THIS... |
"""
Exercise 5
Use the Subway class below to help solve these problems.
class Subway:
fare = 2.4
def __init__(self):
self.stops = ["Alewife", "Davis", "Porter", "Harvard", "Central", "Kendall"]
self.current_stop= "Alewife"
self.direction = "south"
self.passengers = 0
self.total_fares = 0
Create ... |
# -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Cache DataBase - SqlAlchemy database definitions for caching
# © 2020 February - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affe... |
from __future__ import absolute_import
from pygments.style import Style
from pygments.token import *
COLOR_1 = '#e6dccc'
COLOR_2 = '#1e214f'
COLOR_3 = '#b5242e'
COLOR_4 = '#1e4f34'
COLOR_5 = '#537b99'
class Attest(Style):
default_style = ""
styles = {
Comment: 'italic ' + COLOR_5,
Keyword: '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: __init__.py
#
# Copyright 2021 Costas Tyfoxylos, Jenda Brands, Theodoor Scholte
#
# 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 witho... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... |
# coding=utf-8
"""
将华氏温度转换为摄氏温度
F = 1.8C + 32
Version: 0.1
Author: huijz
Date: 2020-08-21
"""
f = float(input('请输入华氏温度:'))
c = (f - 32) / 1.8
print'%.2f华氏度 = %.2f摄氏度' % (f, c)
|
import sys
import textwrap
import argparse
import numpy as np
import networkx as nx
import random
import json
from config import *
from max_circulation import *
import pickle
from functools import reduce
# generates the start and end nodes for a fixed set of topologies - hotnets/line/simple graph
def generate_workload... |
from pecan import make_app
import eventlet
from authdog import model
def setup_app(config):
model.init_model()
app_conf = dict(config.app)
eventlet_enabled = dict(config.EVENTLET).get("enabled")
if eventlet_enabled:
eventlet.monkey_patch(time=True, thread=True)
return make_app(
... |
# Interface for a "set" of cases
class CaseSet:
def __init__(self, time):
self.time = time
def __len__(self):
raise NotImplementedError()
def iterator(self):
raise NotImplementedError()
def get_time(self):
return self.time
def set_time(self, time):
self.t... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
... |
# Simple basic assignment
def main():
x = 1
|
from django.shortcuts import render
from .models import *
# Create your views here.
def image(request):
images = Image.objects.all()
location = Location.objects.all()
return render(request, 'images.html',{"images":images,"location":location})
def locations(request,location_id):
loc = Location.object... |
from advent_2021.helpers import get_input
if __name__ == "__main__":
positions = list(map(int, next(get_input()).split(",")))
print(
min(
sum(abs(position - target) for position in positions)
for target in range(min(positions), max(positions))
)
)
|
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.response import Response
from rest_... |
# coding: utf-8
import time
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class JsTools:
message_status = False
dim_status = Fal... |
'''
Use this file to store names for global permissions -- permissions
that don't belong in any particular module.
For module specific permissions, create an Enum within the module
'''
import enum
class Permissions(enum.IntEnum):
#Site admins -- always have permission to everything -- Use with caution
ADMI... |
from datetime import datetime
from SearchAlgorithms import AEstrela
from _8puzzle import puzzle
goal= [[1,2,3],[8,0,4],[7,6,5]]
def test_1():
board = [[8,1,3],[0,7,2],[6,5,4]]
state = puzzle(" ", board, 1, 0, goal)
beginning = datetime.now()
print(beginning)
algorithm = AEstrela()
result = algorithm.searc... |
# Example used along with arduino_example
import time
import serial
from watchedserial import WatchedReaderThread
PORT = "COM3"
class MyPacket(serial.threaded.FramedPacket):
def handle_packet(self, packet):
print(packet)
class MyWatchedReaderThread(WatchedReaderThread):
def handle_reconnect(self)... |
import cupy
import unittest
import warnings
import numpy
import pytest
try:
import scipy.sparse
import scipy.sparse.linalg
import scipy.stats
scipy_available = True
except ImportError:
scipy_available = False
from cupy import testing
from cupy.testing import condition
from cupyx.scipy import spars... |
import matplotlib.pyplot as plt
from shapely.geometry import *
from shapely.geometry.base import *
from hybrid.resource import (
SolarResource,
WindResource,
ElectricityPrices
)
from hybrid.layout.plot_tools import plot_shape
from hybrid.log import hybrid_logger as logger
from hybrid.keys import set_nr... |
# -*- coding: utf8 -*-fr
# pylint: disable=invalid-name
"""
ItopapiDeliveryModel is an abstraction of Organization representation on iTop
"""
from itopapi.model.prototype import ItopapiPrototype
from itopapi.model.features.hasOrganization import HasOrganization
__version__ = '1.0'
__authors__ = ['Julien Nauroy <julie... |
import pytest
from creator.studies.factories import StudyFactory
from creator.studies.models import Study
from creator.events.models import Event
from creator.tasks import setup_slack_task
def test_setup_slack_success(db, mocker, settings):
"""
Test that the setup task operates correctly when the setup succee... |
import os
import unittest
import importlib
import logging
import zipfile
from nose.tools import raises
from mock import patch, MagicMock
import datman
import datman.xnat
import datman.scanid
# Disable all logging for the duration of testing
logging.disable(logging.CRITICAL)
upload = importlib.import_module('bin.dm_... |
from typing import List, Tuple
import copy
def addGuards(lines: List[str]) -> List[List[str]]:
line_len = len(lines[0]) + 2
array = [['.'] * line_len ]
for i, line in enumerate(lines):
array.append(list('.' + line + '.'))
array.append(['.'] * line_len)
return array
def sumOfNeighbours(ar... |
# -*- coding: UTF-8 -*-
# This file is part of the jetson_stats package (https://github.com/rbonghi/jetson_stats or http://rnext.it).
# Copyright (c) 2019 Raffaello Bonghi.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published... |
#Deep pi
from scipy.spatial import distance
import imutils
from imutils.video import VideoStream
from imutils import face_utils
from threading import Thread
import time
import dlib
import cv2
from playsound import playsound
import serial
#Create alarm using thread
def create_alarm():
global alarm_status
while... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from enum import Enum
class JudgeType(Enum):
Normal = "normal"
Decimal = "decimal"
Other = "other"
class ErrorType(Enum):
Absolute = "absolute"
Relative = "relative"
AbsoluteOrRelative = "absolute_or_relative"... |
#coding: utf-8
# import logging
# import datetime
# import tornado.escape
# from config import BaseController
# from config.dmls import QUERY_STATEMENTS, USER_LIST
# class ApiQuery(BaseController):
# "/v1/query"
# def post(self):
# delta = datetime.timedelta(days=1)
# data = tornado.escape.j... |
# Copyright (C) 2020 Atsushi Togo
# All rights reserved.
#
# This file is part of phono3py.
#
# 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
# noti... |
# @lc app=leetcode id=717 lang=python3
#
# [717] 1-bit and 2-bit Characters
#
# https://leetcode.com/problems/1-bit-and-2-bit-characters/description/
#
# algorithms
# Easy (46.28%)
# Likes: 626
# Dislikes: 1604
# Total Accepted: 96.5K
# Total Submissions: 208.2K
# Testcase Example: '[1,0,0]'
#
# We have two spec... |
# -*- coding: utf-8 -*-
import remi
import remi.gui as gui
from remi.gui import *
from threading import Timer
import traceback
import time
import math
import epics
#from epics import caget, caput, cainfo
style_inheritance_dict = {'opacity':'inherit', 'overflow':'inherit', 'background-color':'inherit', 'background-ima... |
import importlib
import torch
from torch import nn
from torch.nn import functional as F
class MyModel(nn.Module):
def __init__(self, args, network):
super(MyModel, self).__init__()
self.args = args
self.encoder = network
def forward(self, images, output_type='loss'):
... |
import matplotlib.pyplot as plt
import PIL.Image
import numpy as np
import os
import random
from patch.constants import PATCH_SIZE
def _convert(im: PIL.Image):
return ((im + 1) * 127.5).astype(np.uint8)
def show(im: PIL.Image):
plt.axis('off')
plt.imshow(_convert(im), interpolation="nearest")
plt.show()
d... |
import sys
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_list=[element for element in my_list if element<5]
print(new_list)
if sys.version_info[0] >= 3:
num=int(input("Please enter a number: "))
else:
num=int(raw_input("Please enter a number: "))
newer_list=[element for element in my_list if element<num]
p... |
# Let's finish the file access project in Python.
|
import pytz
from pathlib import Path
def separate_log_file(current_timestamp, internet_connected, just_booted, ping_time):
if just_booted:
just_booted_message = "YES"
else:
just_booted_message = "NO"
now = current_timestamp.now(pytz.timezone('America/New_York'))
file_name = now.strftime... |
from ..base.command_with_args import CommandWithArgs
from ..base.argument import Argument
from pyod.models.abod import ABOD
from pyod.models.cblof import CBLOF
from pyod.models.auto_encoder import AutoEncoder
from .pyod import *
class AlgorithmCommand(CommandWithArgs):
tag = "algorithm"
patterns = [
... |
import random
import time
from secrets import token_hex
from pyramid.httpexceptions import HTTPCreated
from pyramid.view import view_defaults
from sqlalchemy.orm.exc import NoResultFound
from {{cookiecutter.project_slug}}.handlers import view_config
from {{cookiecutter.project_slug}}.handlers.auth import LoginHandler... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import datasets
from sklearn.model_selection import train_test_split
from util import load_data
from rnn_lstm import TikTokModel, prepare_datasets
from tqdm.auto impo... |
from threading import Thread, Lock
from time import sleep
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty
from .performer import Performer
from .stacktracer import *
from .backend import *
from .logger import *
from .utils import *
class Manager(object):
def __init_... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 12:23:35 2019
@author: Joule
"""
import random
from cipher import Cipher
from crypto_utils import modular_inverse
class Multiplikasjon(Cipher):
"""Krypter ved hjelp av multiplikasjons cipheret"""
def encode(self, text, key):
encoded = ''... |
import numpy as np
def test_q1_shape(df):
try:
assert df.shape[0] == 45
except AssertionError:
print("Your dataframe doesn't have the correct number of rows.")
print("Try looking back at conditional statements using loc/iloc.")
return
print("You successfully used pandas to... |
import numpy as np
import time
import copy
#np.random.seed(134213)
def smape(X, y, w):
y_pred = X @ w
n = X.shape[0]
res = .0
for y_true, y_hat in zip(y, y_pred):
res += abs(y_hat - y_true) / (abs(y_hat) + abs(y_true))
res /= n
return res
def normalize(X):
n = X.shape[0]
k ... |
# %% [markdown]
#
# # Workshop: NumPy Universal Operations and Broadcasting
#
# In this workshop we'll explore universal operations and broadcasting in more
# depth. Some of the operations used in this workshop were not presented in the
# lectures, you have to look into [the NumPy
# documentation](https://numpy.org/doc... |
#!/usr/bin/python
# coding: utf-8
from datetime import date, datetime, timedelta
from predict_functions import *
from sklearn.externals import joblib
import pandas as pd
import pymongo as pym
import re
date = datetime.strftime(datetime.utcnow() - timedelta(hours=24), '%Y-%m-%d')
fname = 'data/twitter_sentiments_{}.j... |
'''
Builder for the snapshot from smaller snapshots.
'''
from amuse.datamodel.particles import Particles
from amuse.lab import units
from amuse.units.quantities import VectorQuantity
from omtool.core.datamodel import Snapshot
class SnapshotBuilder:
'''
Builder for the snapshot from smaller snapshots.
'''
... |
fruits = ['orange', 'apple', 'banana', 'pineapple', 'coconut', 'banana']
print(fruits)
count = fruits.count('banana') # 2
print(f"There are {count} bananas")
|
from __future__ import print_function
import sublime
import sublime_plugin
import traceback
try:
from latextools_utils import get_setting
from latextools_utils.distro_utils import using_miktex
from latextools_utils.external_command import external_command
except ImportError:
from .latextools_utils imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.