content
stringlengths
5
1.05M
import os from pathlib import Path from tempfile import TemporaryDirectory from typing import TYPE_CHECKING from ..cloudpath import CloudPath, NoStatError, register_path_class if TYPE_CHECKING: from .gsclient import GSClient @register_path_class("gs") class GSPath(CloudPath): """Class for representing and ...
""" Distributions based on circuits with independent inputs. """ from __future__ import division from dit import Distribution import dit def Unq(): """ A distribution with unique information. """ pmf = [1/4] * 4 outcomes = [ ('a', 'b', 'ab'), ('a', 'B', 'aB'), ('A', 'b', '...
from models import User, Post # delete user from post, user where post.user_id = user.id query = (Post & User).delete(User) # mysql supports; sqlite3 dosenot support
import asyncio import pytest from . import assert_browsing_context pytestmark = pytest.mark.asyncio CONTEXT_CREATED_EVENT = "browsingContext.contextCreated" async def test_not_unsubscribed(bidi_session, current_session): await bidi_session.session.subscribe(events=[CONTEXT_CREATED_EVENT]) await bidi_sessi...
#! /usr/bin/env python import sys eps = '<epsilon>' spa = '<space>' phi = '<phi>' rho = '<rho>' unk = '<unk>' cost = 1 def make_lexicon(ifile): s = 2 for line in ifile: word, label = line.split() if int(label) <= 1: continue # epsilon for i, letter in enumerate(word): ...
import atexit import os import tempfile import unittest from pyramid.compat import PY3 if PY3: # pragma: no cover import builtins as __builtin__ else: import __builtin__ class TestPServeCommand(unittest.TestCase): def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO() ...
def test_sum_two_correctly(): assert 2 + 2 == 4 def test_sum_two_incorrectly(): # Expected to fail. Replace by # assert 3 + 3 == 6 assert 3 + 3 == 5
import os,sys,json currentpath = sys.path[0] root = os.path.dirname(currentpath) re = os.listdir(root) if 'json' in re: json_path = root + '\\json' else: json_path = os.path.dirname(root) + '\\json' def set_config(key,value): with open(json_path + '\\config.json','r') as config_file: config = json...
import contextlib import io import json import os import sys import textwrap from peru.async_helpers import raises_gathered import peru.cache import peru.compat import peru.error import peru.main from peru.parser import DEFAULT_PERU_FILE_NAME import peru.rule import peru.scope import shared from shared import run_per...
# Get instance import instaloader import json L = instaloader.Instaloader(max_connection_attempts=0) # Login or load session username = '' password = '' L.login(username, password) # (login) # Obtain profile metadata instagram_target = '' profile = instaloader.Profile.from_username(L.context, ins...
""" This module combines schema and yaml parser into one, to provide better error messages through a single entrypoint `load`. Used for parsing dvc.yaml, dvc.lock and .dvc files. Not to be confused with strictyaml, a python library with similar motivations. """ from typing import TYPE_CHECKING, Any, Callable, List, T...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Timer.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QMessageBox class Ui_For...
import math import params MASS = params.STAR_MASS accuracy = params.accuracy # Radius in cm def sonic_radius(t): return 2.0e11 * 2e6 / t * MASS # Sound speed in km/s def sound_speed(t): return 180 * math.sqrt(t / 2.0e6) def right_part(r, t): rs = sonic_radius(t) return 4.0 * math.log(1.0 * r / r...
import numpy as np import openmdao.api as om from openmdao.test_suite.components.sellar import SellarDis1, SellarDis2 class SellarMDAConnect(om.Group): def setup(self): cycle = self.add_subsystem('cycle', om.Group(), promotes_inputs=['x', 'z']) cycle.add_subsystem('d1', SellarDis1(), promotes_in...
from abc import ABC, abstractmethod import queue class Sort(ABC): def __init__(self, array): self.array = array.copy() self.steps = queue.Queue() @abstractmethod def sort(self): pass def swap(self, i, j): self.steps.put((i, j)) self.array[i], self.array[j] = s...
### Util library for general file handling def replaceTextInFile(filepath, oldText, newText): """Replace all occurrences of some text in plaintext file with some other text. filepath -- the path of the plaintext file\n oldText -- the text to replace\n newText -- the text to implement\n """ fi...
import os ROOT_DIR = os.path.split(os.path.dirname(os.path.abspath(os.getcwd())))[0] PROJECT_DIR = os.path.dirname(os.path.abspath(os.getcwd())) def create_tax_level_files(tax_level_name, replacements_dict, fold): for root, dirs, files in os.walk(os.path.join(ROOT_DIR, "data", "GME", "finest", fold)): f...
from fastapi import APIRouter from src.handler.getinformationbyconfig.contract.request import Params from src.handler.getinformationbyconfig.handler import Handler as HandlerInformationByConfig information_router = APIRouter() @information_router.get("/information/config/{language}/{config_name}") async def informa...
N = 4 board = [input() for _ in range(4)] for i in range(N): for j in range(N): cand = [] if j + 2 < N: cand.append([board[i][j+k] for k in range(3)]) if i + 2 < N: cand.append([board[i+k][j] for k in range(3)]) if i + 2 < N and j + 2 < N: cand.app...
expected_output = {"mac_aging_time": 120}
import cv2 from numpy import expand_dims from keras.models import load_model from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from matplotlib import pyplot from matplotlib.patches import Rectangle from keras import backend as bak import numpy as np import os bak.clear_se...
#!/usr/bin/env python3 import numpy import pyscf.pbc.gto as gto from pyscf.pbc import scf, dft import h5py import sys cell = gto.Cell() cell.verbose = 5 alat0 = 3.6 cell.a = (numpy.ones((3,3))-numpy.eye(3))*alat0 / 2.0 cell.atom = (('C',0,0,0),('C',numpy.array([0.25,0.25,0.25])*alat0)) cell.basis = 'gth-szv' cell.pse...
import os import csv # CSVfile pathway budget_csv = os.path.join('..', 'Resources', 'budget_data.csv') #Initializing the variables total_months = 0 total_revenue = 0 changes = [] date_tally = [] greatest_increase = 0 greatest_increase_month = 0 greatest_decrease = 0 greatest_decrease_month = 0 # ...
import os import glob import shutil import unittest from inspect import getfile, currentframe import autoload.vim_python_test_runner as sut class VimTestRunnerForDjangoTests(unittest.TestCase): def setUp(self): dirs_to_make = [ "/tmp/project_app_only/example_app1/tests/", "/tmp/project_app_n...
#! /usr/bin/env python3 """Create a TAGS file dla Python programs, usable przy GNU Emacs. usage: eptags pyfiles... The output TAGS file jest usable przy Emacs version 18, 19, 20. Tagged are: - functions (even inside other defs albo classes) - classes eptags warns about files it cannot open. eptags will nie give wa...
""" widgets_layout component """ from zoom import DynamicComponent class WidgetsLayout(DynamicComponent): pass
from pytest import raises from riotcli.main import RiotCliTest def test_riotcli(): # test riotcli without any subcommands or arguments with RiotCliTest() as app: app.run() assert app.exit_code == 0 def test_riotcli_debug(): # test that debug mode is functional argv = ['--debug'] ...
import array as arr numa = arr.array('i',[1,2,3,4,5]) numb = arr.array('i',[10,20,30,40,50,60,70,80]) nummc = numa+numb print(nummc)
import sys import boto3 import requests from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job from pyspark.sql.functions import col, expr, when, round from pyspark.sql.types import LongTy...
# -*- coding: utf-8 -*- """ Created on Mon Jan 22 11:05:33 2018 @author: jhodges This file contains classes and functions to read MODIS Level 3 data and locate multiple data tiles onto a single larger grid. Results can be queried from the database or a specific time. If a static query time is given, the best estimat...
# -*- coding: utf-8 -*- from gos.executable_containers import ExecutableContainer class Pipeline(ExecutableContainer): entries_type_names = None type_name = "pipeline"
from collections import defaultdict import mock from searx.engines import google_images from searx.testing import SearxTestCase class TestGoogleImagesEngine(SearxTestCase): def test_request(self): query = 'test_query' dicto = defaultdict(dict) dicto['pageno'] = 1 dicto['safesearch...
import numpy as np import pandas as pd import cPickle as pickle import os import scipy.io as sio import matplotlib matplotlib.use('Agg') import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams.update({'font.size': 20}) def calc_sprns_by_range_and_plot(r_data,inds_range,sp_flag): rshape = np.shape(r_...
import unittest from Solutions import Lesson15 class CountDistinctSlicesTests(unittest.TestCase): def test_count_distinct_slices_example_01(self): m = 6 a = [3, 4, 5, 5, 2] res = Lesson15.count_distinct_slices(m, a) self.assertEqual(9, res)
"""Define tests for the Airzone coordinator.""" from unittest.mock import patch from aioairzone.exceptions import AirzoneError from homeassistant.components.airzone.const import DOMAIN from homeassistant.components.airzone.coordinator import SCAN_INTERVAL from homeassistant.const import STATE_UNAVAILABLE from homeas...
# Generated by Django 3.1.11 on 2021-06-08 07:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20210608_1047'), ('schools', '0003_auto_20210530_1028'), ...
for row in range(4): for col in range(4): if col%3==0 and row<3 or row==3 and col>0: print('*', end = ' ') else: print(' ', end = ' ') print()
# =============================================================================== # @file: human_perception.py # @note: This script is for model design of human perception of movement # @author: Ziga Miklosic # @date: 13.01.2021 # @brief: Evaluation of human movement perception model base on # "...
import json import boto3 import re import os import sys import compare_output from . import s3_compares # to by pass initial setting of default values def extract_from_text(text): if 'compare' in text and text.count('in') > 1: return False else: return True def main(text): regionList = [...
import pandas as pd import numpy as np df=pd.read_csv("C:/Users/Rui/Desktop/test-DEseq2.csv") df['sign']=np.where(df['log2FoldChange']>0, 1, -1) df['metric']=-np.log10(df['padj'])*df['sign'] df2=df[['Unnamed: 0', 'metric']] df2=df2.fillna(value=0) df3=df2.sort(columns='metric') df3.to_csv("file.rnk", sep='\t'...
from threading import Timer import logging import time def thread_work(): logging.debug("Поехали!") if __name__=="__main__": logging.basicConfig( level=logging.DEBUG, format='(%(threadName)-10s) %(message)s', ) my_timer1 = Timer(0.3, thread_work) my_timer1.setName("MyTreadTimer-1"...
# import the opencv library import cv2 import numpy as np import blindfold_solver2 def get_color(colors): blue = colors[0, 1, 1] red = colors[1, 1, 1] yellow = colors[2, 1, 1] orange = colors[3, 1, 1] white = colors[4, 1, 1] green = colors[5, 1, 1] f_c = [] color_options = 'bry...
from matplotlib import pyplot, dates from csv import reader from dateutil import parser with open('table_amzn.csv', 'r') as f: data = list(reader(f)) price = [i[5] for i in data[1::]] time = [parser.parse(i[0]) for i in data[1::]] pyplot.plot(time, price) pyplot.show()
from hokusai.lib.command import command from hokusai.lib.common import print_green, print_red from hokusai.lib.exceptions import HokusaiError from hokusai.services.ecr import ECR, ClientError @command() def retag(tag_to_change, tag_to_match): ecr = ECR() if not ecr.project_repo_exists(): raise HokusaiError("P...
import unittest import datetime from pyalgotrade.broker import optbroker from pyalgotrade import broker as stockbroker from pyalgotrade.broker.optbroker import optfillstrategy from pyalgotrade.broker import fillstrategy as stockfillstrategy from pyalgotrade.broker.optbroker import optbacktesting import broker_backtes...
# sql/functions.py # Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from .. import types as sqltypes, schema from .expression import ( ClauseList, Fu...
import os from flask import current_app, url_for from . import core @core.app_context_processor def inject_variables(): return dict(SSL=current_app.config['SSL']) @core.app_template_filter('strftime') def _jinja2_filter_datetime(date, fmt=None): if date is None: return '-' native = date.replace(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 8 21:04:40 2021 @author: katie """ import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt import svd_tools_copy as svdt import scipy as sp import scipy.sparse from PIL import Image ''' Embed a watermark in using the Liu & ...
from scrapy.item import Field, Item class DefaultsItem(Item): """ DefaultsItem - Item with default values. Adds default value support for unset Field values. Example: MyItem(DefaultsItem): url = Field(default='http://example.com/') id = Field(default=0) text = Field(default=None) """ def __geti...
# munmap.py import gc import os import sys import time from arm_ds.debugger_v1 import Debugger from arm_ds.debugger_v1 import DebugException import config import memory import mmu # obtain current execution state debugger = Debugger() execution_state = debugger.getCurrentExecutionContext() def ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: def recur(L, R): # 左右子树都为空 if not L and not R: ...
from __future__ import division, print_function import os, sys import ROOT from PhysicsTools.NanoAODTools.postprocessing.framework.postprocessor import PostProcessor from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object from PhysicsTools.NanoAODTools.postprocessing.framework.event...
# solve for easy reference from .inference_model import ( MyoPINN, FullPINN, CombinedPINN, MeshPINN, FullMeshPINN, )
a=10 b=a print(id(a)) print(type(a)) print(id(b)) print(type(b)) print(a is b) a=a+1 print(id(a)) print(id(b)) print(a is b) print(a) print(b) x=[1,2,3] y=x print(id(x)) print(id(y)) print(x is y) y.pop() print(y) print(x) x.append("hola") print(y) print(x is y) #CUANDO YO IGUALO DOS OBJETOS INMUTABLES Y CAMBIO UNO...
new_file = open("tiles.txt", "w") with open("map3.txt", "r") as f: for line in f: for character in line: if character == "1": new_file.write("simple_grass ") elif character == "\n": new_file.write("\n") else: new_file.write...
import math import numpy as np import gym import torch from sacPD import PolicyNet from tqdm import tqdm torch.manual_seed(2021) np.random.seed(2021) sigma = 0.1 PI = math.pi lr_pi = 0.0005 epoch = 1000 # options: 1000, 0 ckpt_path = 'checkpoints/ep-%d.pt' % epoch max_speed = 8.0 ''' state: cos(theta), sin(...
from .routes import Layout_Detector_BLUEPRINT from .routes import Layout_Detector_BLUEPRINT_WF #from .documentstructure import DOCUMENTSTRUCTURE_BLUEPRINT
import numpy as np from copy import deepcopy from sys import exit from PreFRBLE.file_system import * from PreFRBLE.label import * class Scenario: """ class object to define a physical scenario. Either full LoS or individual model For individual host redshift or as expected to be observed by telescope...
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visual...
#!/usr/bin/env python # # manage.py 用于启动程序以及其他的程序任务 import os # from flask import Flask # from flask_sqlalchemy import SQLAlchemy from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from flask_debugtoolbar import DebugToolbarExtension app.config.from_object(os.en...
import random as rnd def qLearning(self, start, goal): q_table = [] qInit(q_table, self.world, goal) printQTable(q_table) printRewards(q_table) alpha = 1 gamma = .8 for i in range(1000): y = rnd.randint(0, len(q_table)-1) x = rnd.randint(0, len(q_table[y])-1) while(s...
""" A cache of recently created operations. """ class OperationsCache(dict): """ A cache of recently created operations """ def __init__(self, size=256): """ Creates new OperationsCache. Args: size: An integer specifying the maximum size of the cache. """ super(OperationsCache, self).__init...
# -------------------------------------------------------------------# # Released under the MIT license (https://opensource.org/licenses/MIT) # Contact: mrinal.haloi11@gmail.com # Enhancement Copyright 2016, Mrinal Haloi # -------------------------------------------------------------------# import tensorflow as tf from...
from flask import Blueprint from flask_restful import Resource, Api from coalaip import CoalaIp, entities from coalaip_bigchaindb.plugin import Plugin from web.utils import get_bigchaindb_api_url coalaip = CoalaIp(Plugin(get_bigchaindb_api_url())) work_views = Blueprint('work_views', __name__) work_api = Api(work_v...
""" @author - Anirudh Sharma """ from typing import List def fourSum(nums: List[int], target: int) -> List[List[int]]: # Resultant list quadruplets = list() # Base condition if nums is None or len(nums) < 4: return quadruplets # Sort the array nums.sort() # Length of the array ...
from rest_framework import generics from .serializers import AuthorDetailSerializer from .serializers import AuthorListSerializer from .models import Author class AuthorCreateView(generics.CreateAPIView): serializer_class = AuthorDetailSerializer class AuthorListView(generics.ListAPIView): serializer_class ...
import numpy as np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from scipy.sparse import csc_matrix def pr_curve_writer(label, pred): a=len(label) b=380000 curve_resolution=10000 linspace=np.linspace(0.0000, 1.0, curve_resolution,endpoint=True, dtype=np.float64) TPR_...
## -*- coding: utf-8 -*- import markdown as md def preprocessing(s): """ Returns string where \\ is replaced by \\\ so that latex new lines work """ return s.replace(r'\\', r'\\\\') def md_to_html(text_md): """ Returns HTML string The input string should be of the raw 'r' type """ ...
#! python3 """ This progam displays the visual component of a pathfinding program. The program allows users to click on squares to color them in and create obstacles for a pathfinding algorithm to work around. """ import sys import random import pygame from pygame.locals import * from algorithms.dijkstra import Dijks...
#Desafio 024: Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "Santo". #MODO 1: Resolução pessoal - Cobre todas as possibilidades. city = str(input('Nos informe a cidade onde você nasceu, por gentileza. ')).upper() #O split já exclui os espaços iniciais e finais, logo, não prec...
from os import system from time import sleep def print_all_playlist(spotifyObject, user): _ = system('clear') all_playlist = spotifyObject.user_playlists(user["id"], limit=50) items = all_playlist["items"] compteur = 0 print("{0:2} | {1:80} | {2:20}".format('N°', 'Name', 'Owner')) print(f'{"-"...
'''Refaça o DESAFIO 35 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: – EQUILÁTERO: todos os lados iguais – ISÓSCELES: dois lados iguais, um diferente – ESCALENO: todos os lados diferentes''' primeiro = float(input('Primeiro segmento: ')) segundo = float(input('Segundo segmento:...
from collections import OrderedDict import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table from dash_docs import reusable_components as rc from dash_docs import datasets Display = rc.CreateDisplay({ 'dash_table': dash_table, 'html': html, 'df': dataset...
"""Defines the class for a node health check task""" from __future__ import unicode_literals import datetime from django.conf import settings from job.tasks.base_task import AtomicCounter from job.tasks.node_task import NodeTask from node.resources.node_resources import NodeResources from node.resources.resource imp...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-13 02:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0004_label'), ] operations = [ migrations.AlterField( mod...
# Copyright (c) 2021 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...
""" Generate Dataset 1. Converting video to frames 2. Extracting features 3. Getting change points 4. User Summary ( for evaluation ) """ import os, sys sys.path.append('../') from networks.CNN import ResNet from utils.KTS.cpd_auto import cpd_auto from tqdm import tqdm import math import cv2 impor...
DEBUG = True SECRET_KEY = 'GUOLABHOMECEH8SNH20A0MU9060USDWEXVSYCL515UWCN409TLBKHCTQDIFEH36CE' # make sure to change this
import pytest from discopy import Word from discopy.rigid import Diagram, Id from lambeq.core.types import AtomicType from lambeq.reader import cups_reader, spiders_reader @pytest.fixture def sentence(): return 'This is a sentence' @pytest.fixture def words(sentence): words = sentence.split() assert l...
import torch import torch.nn as nn import torch.nn.functional as F class NetOneHot(nn.Module): def __init__(self, output_dim, annotator_num, text_embedding_dim=768, **kwargs): super().__init__() self.text_embedding_dim = text_embedding_dim self.fc1 = nn.Linear(text_embedding_dim + annotato...
import requests, boto3, asyncio, math async def upload_s3_async(init, end, i, url, bucket, key, s3, mpu): print(f'Upload {i}') # download do pedaço do arquivo r = requests.get(url, headers={'Range':f'bytes={init}-{end}'}) #upload para o S3 return s3.upload_part(Bucket=bucket, Key=key, PartNumb...
from django.shortcuts import render import datetime from .models import EnergyUsage, Event, Laptop from django.db.models import Avg, Max, Min from django.http import HttpResponse from django.utils import timezone from django.core import serializers from .EpicesParser import EpicesParser from django.utils.dateparse impo...
# Copyright 2015 Google 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 the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
"""Test configuration fragment replacement.""" import pytest from dictator.validators.replace import ( FragmentReplace, AutoFragmentReplace, FragmentError, ) from dictator.validators.lists import SubListValidator from dictator.config import validate_config def test_fragment_replace(): """Test manual ...
import os import matplotlib.pyplot as plt import pandas as pd import streamlit as st import SimpleITK as sitk def dir_selector(folder_path='.'): dirnames = [d for d in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, d))] selected_folder = st.sidebar.selectbox('Select a folder', dirnames) ...
from pathlib import Path from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase from django.urls import reverse from .forms import CommentForm from .models import User, Webpage, Template, Comment USERNAME = 'haha69420' PASSWORD = 'foobar < xyzz...
from userinput import userinput import pytest def test_ip(monkeypatch): monkeypatch.setattr('builtins.input', lambda x: "127.0.0.1") assert userinput("user_input", validator="ip", cache=False) monkeypatch.setattr('builtins.input', lambda x: "") with pytest.raises(ValueError): userinput("user_i...
# coding: utf-8 import os import sys import re import time from pyspark import SparkConf, SparkContext # 重要 from pyspark.sql import SQLContext # import pandas as pd reload(sys) sys.setdefaultencoding("utf-8") # 0 add the envs # part0 重要 if "SPARK_HOME" not in os.envir...
import json import sys from unittest.mock import MagicMock import pytest import Browser.keywords as interaction from Browser.keywords import PlaywrightState WARN_MESSAGE = ( "WARNING RobotFramework:logger.py:95 Direct assignment of values as 'secret' is deprecated. " "Use special variable syntax to resolve ...
# # Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates # # 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 ap...
#!/usr/bin/python3 import getpass import os import re import json import yaml import shutil import subprocess import threading def clone_or_update_conan_center_index(): if not os.path.exists("conan-center-index"): os.system("/bin/bash -c \"git clone https://github.com/conan-io/conan-center-index\"") e...
while True: try: S = input() res = "" for k in S: o = ord(k) if o >= 65 and o <= 90: # A to Z o += 13 if o > 90: o = o - 90 + 64 res += chr(o) elif o >= 97 and o <= 122: # a to z o += 13 if o > 122: o = o - 122 + 96 res += chr(o) else: res += k print(res) ...
from __future__ import print_function, absolute_import import os import gc import sys import time import h5py import scipy import datetime import argparse import os.path as osp import oneflow as flow import oneflow.nn as nn import shutil import oneflow.typing as tp from typing import Tuple import oneflow.math as math i...
import ast import numpy as np import pandas as pd import torch from sklearn.metrics.pairwise import cosine_similarity def similarity(dataset, number_of_recommendations=3): IRI = extractIRI(dataset) id = extractIDs(IRI) all_datasets_ids = [3392, 3403, 3407, 3405, 3388, 3390, 3386, 3512, 3510, 3508, 3176, 3...
import select import socket import sys import signal import argparse import threading from utils import * SERVER_HOST = 'localhost' stop_thread = False def get_and_send(client): while not stop_thread: data = sys.stdin.readline().strip() if data: send(client.sock, data) s...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/settings/master/pokemon/encounter_attributes.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message ...
from itertools import islice, chain def iter_chunks(iterable, size): """Splits an iterable into even sized chunks""" iterator = iter(iterable) for first in iterator: yield chain([first], islice(iterator, size - 1)) def utax_format(ranks, lineage, empty_patt): return ','.join('{}:{}'.format(...
import unittest from compress import compress class Test_Case_Compress(unittest.TestCase): def test_compress(self): self.assertEqual(compress('aabcccccaaa'), 'a2b1c5a3') self.assertEqual(compress('abc'), 'abc') self.assertEqual(compress('AbC'), 'AbC') self.assertEqual(compress('aAbB...
# Copyright 2016 # Drewan Tech, LLC # ALL RIGHTS RESERVED from flask import (Flask, render_template, request, flash) from os import urandom app = Flask(__name__) app.secret_key = urandom(32) @app.route('/', methods=['GET', 'POST']) def index(): if reques...
import os import uvicorn from fastapi import FastAPI from app.api.v1.api_router import api_router app = FastAPI() app.include_router(api_router) if __name__ == "__main__": debug: bool = True if os.getenv("ENV", "dev") == "dev" else False port: int = int(os.getenv("PORT", 8000)) uvicorn.run(app, host="0...