text
stringlengths
38
1.54M
import boto3 from typing import Dict import traceback from search_task import search_task_by_id from schema import UpdateTask from datetime import datetime def update_task(user_id: str, task: UpdateTask) -> bool: """ DynamoDB内のタスクを更新 """ is_task_exists = search_task_by_id(user_id, task.task_id) if...
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
import os import sys import pylons import pylons.configuration as configuration from beaker.cache import CacheManager from beaker.middleware import SessionMiddleware from paste.fixture import TestApp from paste.registry import RegistryManager from paste.deploy.converters import asbool from pylons import url from pylon...
""" Created on Oct 20, 2013 @author: Ofra """ from util import Pair class PropositionLayer(object): """ A class for an PropositionLayer in a level of the graph. The layer contains a list of propositions (Proposition objects) and a list of mutex propositions (Pair objects) """ def __init__(s...
import numpy as np import cv2 img=cv2.imread("lena.jpg", 1) img=np.zeros([512,512,3], np.uint8) #create image with numpy arrays img=cv2.line(img, (0,0), (255,255), (0,0,255), 10) img=cv2.arrowedLine(img, (0,255), (380,55), (0,180,255), 10) img=cv2.rectangle(img, (384,0), (510,128), (0,0,255), 5) img=cv2.circ...
#Swapping value using tuple concept x = 10 y = 11 #we learn tuple x, y = (y, x) print("x", x) print("y", y)
import odsh_parser import odsh_lib import json blk = odsh_parser.parse(''' ls / && echo "OK" ls /niwf3w4y3nxif4 || echo "Failed" ls / | grep etc ''') print(json.dumps(blk.build())) exec_blk = odsh_lib.Block(blk.build()) engine = odsh_lib.Engine() engine.eval_block(exec_blk)
import sys sys.path.append('..') from winnie.util.singletons import Singleton class Singletest: __metaclass__ = Singleton def __init__(self, text): self.text=text def write(self): print self.text
def even_number(start, end): count = 0 number_list = [] type = input("From OR Between : ").lower() if type == "from": end += 1 elif type == "between": end -= 2 for number in range(start, end): if number % 2 == 0: number_list.append(number) ...
import string import sys N=0x5851F42D4C957F2DL mask=2**64-1 mask32=2**32-1 def swap(arr, a, b): arr[a], arr[b] = arr[b], arr[a] # Rotate right: 0b1001 --> 0b1100 ror = lambda val, r_bits, max_bits: \ ((val & (2**max_bits-1)) >> r_bits%max_bits) | \ (val << (max_bits-(r_bits%max_bits)) & (2**ma...
# Generated by Django 3.0.4 on 2020-04-11 06:22 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0016_auto_20200403_0628'), ('services_manager', '0008_auto_20200406_1259'), ] operations = [ ...
import json from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import numpy as np import os def pushData(value): now = datetime.now() timeNow = now.strftime("%d/%m/%Y, %H:%M:%S") with open("data.json", "r+") as file: data = json.load(file) a = {value: 1, "...
from TruthTable import TruthTable def get_extra_cols(): num_extra_cols = -1 while num_extra_cols < 0: try: num_extra_cols = int(input("How many additional columns do you need? ")) while num_extra_cols < 0: num_extra_cols = int(input("The number of additional colum...
# -*- coding=gbk -*- import sys, getopt import re import os from os.path import isfile, join, isdir, getsize def is_video(filename): houzhui_list = [".mp4", ".avi", ".mkv", ".flv", ".rmvb", ".wmv"] for houzhui in houzhui_list: if filename.endswith(houzhui): return True return False ...
import argparse import time import math import numpy as np import sklearn.metrics as sk import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import data import model from utils_lm import batchify, get_batch, repackage_hidden # go through rigamaroo to do ..utils.displ...
from django.conf.urls import url from django.contrib import admin from django.urls import path, include, re_path from django.contrib.auth import views as auth_views from core.views import * urlpatterns = [ # path('admin/', admin.site.urls), path('', index.as_view(), name='index'), path('account/', includ...
from django.contrib import admin # Register your models here. from .models import Motif, CommentLike, Comment admin.site.register(Motif) admin.site.register(Comment) admin.site.register(CommentLike)
import cv2 as cv import json import os import pickle as pkl import ffmpeg import argparse parser = argparse.ArgumentParser( description="Collect the frames from video.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument('--mode', default='train', ...
import FWCore.ParameterSet.Config as cms ######################################## # Command line argument parsing ######################################## import FWCore.ParameterSet.VarParsing as VarParsing options = VarParsing.VarParsing ('analysis') options.register ('crab', 0, # default value ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils import count_divisors, triangle_numbers def pe12(sub=500): """ What is the value of the first triangle number to have over five hundred divisors? >>> pe12() 76576500 """ for t in triangle_numbers(): c = count_divisors(t) ...
my_var = "hello" print(my_var[0]) for cc in my_var: print(cc) my_list = [10,20,30,40,50] for num in my_list: print(num) user_want_number = True while user_want_number == True: print(10) user_input= input("Do you want to print again (y/n)") if(user_input == 'n'): user_want_number = False...
def solution(inp): return if __name__ == "__main__": with open('x.in') as f: inp = f.readlines() #with open('7.in') as f: #inp = f.read().strip().split('\n\n') #inp = [l.strip() for l in inp] #inp = [int(l.strip()) for l in inp] #inp = [l.strip().split(':') for l in inp] pri...
''' Created on 2016. 10. 26. 다중 상속 : 순서가 중요 ''' class Tiger: data = '호랑이 세상' def Cry(self): print('호랑이 어흥!!!') def Eat(self): print('맹수는 고기를 먹음') class Lion: def Cry(self): print('사자는 으르렁!!!!!!') def Hobby(self): print('백수의 왕은 낮잠이 취미') cl...
"""# -*- coding: binary -*- require 'msf/core/plugin' =begin require 'active_record' # # This monkeypatch can help to diagnose errors involving connection pool # exhaustion and other strange ActiveRecord including errors like: # # DEPRECATION WARNING: Database connections will not be closed automatically, please clo...
import numpy as np def port_return(weights_m, mu_m): return np.dot(np.transpose(weights_m), mu_m) def calculate_mu(return_data): """ Calculates the Mu matrix for the securities :param return_data: the data frame containing the returns :return: returns an array containing the arithmetic ...
# -*- coding: utf-8 -*- from __future__ import division import numpy as np import matplotlib.pyplot as plt # 정규분포를 따르는 합성데이터 생성함수 정의 def generate_normal(n_samples, train_test_ratio=0.8, seed=2019): np.random.seed(seed) n = n_samples // 2 n_train = int(n * train_test_ratio) X1 = np.random.normal(loc=1...
from io import BytesIO import os import unittest from fontTools.misc.textTools import bytesjoin, tobytes from fontTools.misc.xmlWriter import XMLWriter HEADER = b'<?xml version="1.0" encoding="UTF-8"?>\n' class TestXMLWriter(unittest.TestCase): def test_comment_escaped(self): writer = XMLWriter(BytesIO()) write...
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup(name='beautifulsoupselect', version='0.2', description='Simple wrapper to integrate BeautifulSoup and soupselect.py in a single package', url='http://github.com/sbma44/beautifulsoupselect', ...
''' Main run script for TracPy system. ''' from __future__ import absolute_import import numpy as np from tracpy.time_class import Time # from . import tracpy.time_class as Time def run(tp, date, lon0, lat0, T0=None, U=None, V=None): """ some variables are not specifically called because f2py is hides t...
import random import sys width = 4 # TODO: verify that the user gave exactly width characters def main(): hidden = list(map(str, random.sample(range(10), width))) print(f"Hidden numbers: {hidden}") while True: inp = input("Guess a number: (e.g. 1234) or x to eXit. ") if inp == 'x' or inp ...
import crossmod from crossmod.tasks.data_table_updater import perform_update from celery.schedules import crontab @crossmod.celery.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Update data table banned_at_utc, banned_by columns at 00:00 on Tuesday, Thursday and Saturday sender.add_pe...
radius=float(input("enter the number")) PI=3.14 circumference=PI*radius print("circumfrence of the circle is :%2f"%circumference)
COUNTY_MAP = { 'Albany' : 36001, 'Allegany' : 36003, 'Bronx' : 36005, 'Broome' : 36007, 'Capital Region' : 36001, 'Cattaraugus' : 36009, 'Cayuga' : 36011, 'Chautauqua' : 36013, 'Chemung' : 36015, 'Chenango' : 36017, 'Clinton' : 36019, 'Columbia' : 36021, 'Cortland' : ...
#!/usr/local/bin/python3 import git repo = git.Repo("~/src/freebsd-ports") commits = list(repo.iter_commits("3bd153c2494182bb89915e6fc9222288c154285f..HEAD")) for commit in commits[::-1]: print(commit.hexsha)
from get_data_without_box.get_movie_info import get_details_without_box import requests import time #功能:抓取没有票房信息的电影数据 #解释:要先从网页上看爬网页的套路 # 常量定义 # 访问JSON API的headers headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaS...
# Solving mazes with thinning A* heuristic from maze_gen import * from search import DFS, BFS, AStarE, AStarM import matplotlib.pyplot as plt from tkinter import * from tkinter import ttk import timeit as tm import random import math import copy import numpy as np DEBUG = 0 # function to generate a thinned/easier ve...
import numpy as np from astropy.io import fits from matplotlib import pyplot as plt from matplotlib import colors import scipy.stats # Inputs: # folder: path to where the .fits files are, e.g. '2016jul14/' # start, end: range of indices of images, e.g. 95,96 # assumes that the filenames look like e.g...
import random from math import exp from collections import defaultdict from cheat_game_server import Game from cheat_game_server import Player, Human from cheat_game_server import Claim, Take_Card, Cheat, Call_Cheat from cheat_game_server import Rank, Suit, Card class Agent(Player): def __init__(self, name): ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-05-06 11:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('chat', '0002_auto_20190427_2356'), ] operations =...
import sys # Utils to compile .py to .pyc inside zip file # XXX: this is implementation detail of .pyc, copied from py_compile.py. # Unfortunately, there is no way that I know of to write the bytecode into a # string to be used by ZipFile (using compiler is way too slow). Also, the # py_compile code has not changed mu...
from django.contrib import admin from mytest.models import users # Register your models here. class usersAdmin(admin.ModelAdmin): list_display=('uid', 'question') admin.site.register(users, usersAdmin)
Import('debug') env = Environment(CCFLAGS=['-O9', '-std=c++0x'], CPPPATH=['#netsight/src/include']) if debug: env.Append(CCFLAGS='-g') env.Append(CPPDEFINES='DEBUG') src_files = ['main.cc', 'netsight.cc', 'path_table.cc'] lib_deps = [] lib_paths = [] lib_deps.append('netsightlib') lib_pa...
import pytest from datasciencebox.core.settings import Settings def test_required_bare_fields(): settings = Settings() assert settings['CLOUD'] == 'bare' with pytest.raises(AssertionError): settings.validate_fields() settings['NODES'] = [] settings['USERNAME'] = 'root' settings['KE...
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import View, TemplateView, CreateView, UpdateView, FormView, ListView, RedirectView from django.template import RequestContext from django.shortcuts import render, redirect from .models import * from .forms import * from django.urls im...
# Generated by Django 3.2.3 on 2021-06-13 18:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('courses', '0002_alter_language_options'), ] operations = [ migrations.CreateModel( ...
import pandas as pd import numpy as np from tqdm import tqdm import re import jieba import jieba.analyse alldoc = pd.read_csv('../data/all_docs.txt',sep='\001',header=None) alldoc.columns = ['id','title','doc'] train = pd.read_csv('../data/train_docs_keywords.txt',sep='\t',header=None) train.columns = ['id','label'] tr...
# -*- coding: utf-8 -*- """ Created on Tue May 25 17:00:50 2021 @author: L01268185 """ import numpy as np data = np.arange(25).reshape(5,5) temp=data[[0],:] temp2=data[[1],:] data[[0],:]=temp2 data[[1],:]=temp print(data) data[[0,1],:] = data[[1,0],:] print(data) print() data = np.ara...
import math def MergeSort(unsorted_list): if len(unsorted_list) > 1: left_half = unsorted_list[: math.floor(len(unsorted_list)/2)] right_half = unsorted_list[math.floor(len(unsorted_list)/2):] MergeSort(left_half) MergeSort(right_half) i, j, k = 0,0,0 while i<len(left...
# -*- coding: utf-8 -*- # @Time : 2021/5/9 7:05 下午 # @Author : AI悦创 # @FileName: lst_code.py # @Software: PyCharm # @Blog :http://www.aiyc.top # @公众号 :AI悦创 personal_info = ['aiyc', '男'] personal_info.append(1.74) personal_info.insert(1, 28) personal_info[1] = 36 personal_info[0:2] = ['aiyc', 35] print(personal...
"""" input name and age, create dictionary with name and age add to users.append() wrote array to json """ import json users = [] while True: name = input("Enter your name:") age = input("Enter your age: ") user = {'name': name, 'age': age} users.append(user) with open('users.json','w') as file_obje...
#!/usr/bin/env python # -*- coding: utf-8 -*- import time class Timer(object): """ A timer for measure runing time. """ def __init__(self): self.start_time = time.time() self.end_time = None def end(self): """ Stop the timer. """ self.end_time = ti...
import pygame RED = (255, 0, 0) class Hurdle: def __init__(self, screen): self.screen = screen self.x = 610 self.y = 200 self.width = 10 self.height = 50 def draw(self): pygame.draw.rect(self.screen, RED, [self.x, self.y, self.width, self.height]) ...
''' Created on Sep 6, 2015 @author: hugosenari ''' from circuits import Component, Event class AMusicPlayer(Component): def started(self, component): print("Hi") def stopped(self, *args, **kwd): print("See ya!") def new_setup(self): print('Nice to meet you') ...
"""Interval estimation""" import numpy as np from scipy.optimize import toms748 from pyhf import get_backend from pyhf.infer import hypotest __all__ = ["upper_limit", "linear_grid_scan", "toms748_scan"] def __dir__(): return __all__ def _interp(x, xp, fp): tb, _ = get_backend() return tb.astensor(np.i...
"""Open a connection with specified settings""" import serial # # # last modified : 2015-08-06 class PortFormat(object): """Holds the details of the format of the serial connection: baud rate, number of bits, etc. """ #default timeout values in seconds DEF_TIMEOUT = 10 def __init__(self,name=0,...
#%% from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf #%% #importa o dataset -> .train .test .validation #imagens 28x28 -> 784 pixels #dataset trei...
#Concatenation - joining strings print("Iraj") print("Spam" + 'eggs') print("1"+"1") ##out of the way - concatenate number with string #wrong-print("spam"+1+"egg") print("spam"+ str(1)+"egg") #Multiply strings print("spam " * 3) ##What is the output of print(3*'7') ##Using inplace operators x = "spam" print(x) x...
#pcb = process control block class PCB: def __init__(self, identificador, cantInst, nomPrograma): self.pid = identificador self.pc = 0 #cantidad de instrucciones ejecutadas self.estado = "new" self.cantInst = cantInst self.baseDirection = 0 #self.prioridad =...
#!/usr/bin/python import importlib import json import re import requests import sys import traceback sys.path.insert(0, 'challenges') test_data = { 'challenge_1': { 'inputs': [('49276d206b696c6c696e6720796f757220627261696e206c696b65206' '120706f69736f6e6f7573206d757368726f6f6d')], ...
import sys from pathlib import Path try: import wclib except ImportError: # wclib may not be in the path because of the architecture # of all the challenges and the fact that there are many # way to run them (through the showcase, or on their own) ROOT_FOLDER = Path(__file__).parent.parent.parent ...
import os from ImagePreprocessing import ReadExpoTimes, ReadTrainingData from ComputeTrainingExamples import ComputeTrainingExamples import Constants import numpy as np from joblib import Parallel, delayed import multiprocessing from contextlib import closing import h5py from ModelUtilities import list_all_files_sorted...
import os import FileUtils #fileName = "datafile.txt" #input ("Enter file name ") fileName = FileUtils.selectOpenFile ("Select data file to open", "Read File Example") if fileName == None: #user pressed cancel/X os._exit(0) #check if the file actually exists before trying to open the file if os.path.isfile (fi...
from django.http import HttpResponse from django.shortcuts import render, redirect from blog.models import Cursos, RedesSociales, Proyecto, Menu, Contacto, Categoria from blog.forms import ContactoForm from datetime import datetime # Create your views here. def index(request): cursos = Cursos.objects.order_by('i...
def get_profile_details_event_list(): return [{'value': 'active_suspend_reason', 'text': 'Active/Suspend Reason'}, {'value': 'acquiring_sales_executive_id', 'text': 'Agent - Acquiring Sales Executive'}, {'value': 'bank_branch_area', 'text': 'Agent - Bank Branch Area'}, {'value': ...
import time from adp_movie import Insertmovie, Existmovie from adp_staff import Insertstaff, Existstaff def Selemoviedetail(code, driver): Isexistmovie = Existmovie(code) if Isexistmovie == True: return d_url = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code={0}' driver.get(d_url.for...
from rest_framework import status from rest_framework.generics import GenericAPIView from rest_framework.response import Response from project.apps.Currency.models import Currency from rest_framework_api_key.permissions import HasAPIKey from project.api.v1.serializer import ExchangeRateSerializer from project.api.tasks...
''' 34. 「AのB」 2つの名詞が「の」で連結されている名詞句を抽出せよ. ''' from knock30 import get_morpheme_list noun_phrases = [] for s in get_morpheme_list("neko.txt.mecab"): for i in range(len(s) - 2): if s[i]['pos'] == '名詞' and \ s[i+1]['surface'] == 'の' and \ s[i+2]['pos'] == '名詞': noun_phrases.ap...
#!/usr/bin/env python ''' A Zenity GUI on top of the droid functions ''' import sys,os try: import PyZenity as zen except ImportError: print 'No PyZenity, do "sudo easy_install pyzenity"' sys.exit(1) import droid def start_server(): 'Start the server if needed' pid,err = droid.server_pid() if ...
import time import math import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from sklearn import metrics from tensorflow import keras from tensorflow.python.keras import layers, backend from tensorflow.python.keras.initializers import Constant from tensorflow.python.keras.prepr...
import logging, sys, signal, time, json, os, pytweening, threading from collections import deque from lib.vhWindows import vhWindows from lib.vhSockets import vhSockets from lib.vhUI import vhUI logging.basicConfig(stream=sys.stdout, level=logging.INFO) #logger = logging.getLogger(__name__) #logger.setLevel(logging.DE...
import pyqrcode from pyzbar.pyzbar import decode from PIL import Image from tkinter.filedialog import * while True: choice = int(input("Enter 1 to generate QR code and 2 to read QR code: ")) if choice == 1: text = input("Enter the text you want to convert into QR code: ") qr = pyqrcode.create(...
from typing import List from typing import Optional import rubik ############################################################################ #Invarient Documentation: # #Our invarient is that the list frontier is full of elements we have yet to # visit, but are near points that we have visited so long as it's empty,...
import unittest import zserio from testutils import getZserioApi class StructureArrayParamTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "functions.zs").structure_array_param cls.CHILD_BIT_SIZE = 19 cls.CHILDREN = [cls.api.ChildStructure.fr...
from flask_sqlalchemy import SQLAlchemy from flask_seeder import generator db = SQLAlchemy() def seed_database(User): for index in range(250): db.session.add( User(name=generate_name()) ) db.session.commit() def generate_name(): return f"{generator.Name().generate()} {genera...
from gui import client_app import winsound def main(): root = client_app.Root(None, client_app.Game()) root.title("Dungeon Hero") myapp = client_app.App(root) myapp.mainloop() if __name__ == "__main__": main()
#-*- encoding: utf-8 -*- from django.test import TestCase from zhidewen.tests.models.base import ModelTestCase from zhidewen.models import Answer from django.utils import timezone class TestAnswer(ModelTestCase): def setUp(self): self.user = self.create_user('test') self.q = self.create_question...
from __future__ import absolute_import import os from test.syncbase import TestPithosSyncBase import pithossync class TestClone(TestPithosSyncBase): # TODO: assert that remote folder does not exists causes an error during clone # TODO: assert that local permission denied during clone fails correctly def test_emp...
# Copyright 2020 StreamSets 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.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- c = \ """ PyIconv.py - Prosty 'front-end' do programu iconv Copyright (C) 2003 Rafał 'jjhop' Kotusiewicz "Rafał Kotusiewicz" <jjhop@randal.qp.pl> http://randal.qp.pl/_projects/PyIconv/index.php This program is free software; you can redistribute it and/or ...
from rest_framework import serializers from .models import CallService,Rider,StateRider,StatusOrder,Menu,Market,FoodOption,Option,Order,Food,Drink,Snack class CallServiceSerializer(serializers.ModelSerializer): class Meta : model = CallService fields = ('id','name','username','password','status') ...
import socket import time class ClientError(Exception): pass class Client: def __init__(self,host,port,timeout = None): self.socket = socket.create_connection((host,port), timeout) def send(self,msg): try: self.socket.sendall(msg.encode("utf8")) except socket.error as error: raise ClientError("Error...
""" -*- coding: utf-8 -*- @author: omerkocadayi https://github.com/omerkocadayi https://www.linkedin.com/in/omerkocadayi/ """ import cv2 #img2 = cv2.imread("750x750_siyah.jpg") img = cv2.imread("750x750.jpg",0) """ resmi img degiskenine atadik. '0' parametresi direkt olarak siyah-beyaza gecis ya...
#coding:utf-8 import sys import re input_file=sys.argv[1] output_file=sys.argv[2] output=open(output_file,"w") output.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format("sequence_id","primer_left","primer_right","seq_info_left","seq_info_right","tm_left","tm_right","gc_left","gc_right","product_size")) # input_fil...
import contextlib import functools import torch _module_settings = {} @contextlib.contextmanager def set_module_settings(**kwargs): global _module_settings old_module_settings = _module_settings.copy() try: for key in kwargs: if key not in _module_settings: _module_set...
# coding=utf8 import tensorflow as tf def softmax_with_mask(tensor, mask): """ Calculate Softmax with mask :param tensor: [shape1, shape2] :param mask: [shape1, shape2] :return: """ exp_tensor = tf.exp(tensor) masked_exp_tensor = tf.multiply(exp_tensor, mask) total = tf.reshape(...
from table import Table from sklearn.decomposition import TruncatedSVD from sklearn.metrics.pairwise import cosine_similarity def _default(*args, **opt): return 1 class PageRanker: _sims = None _svd = None _sim_table = {} _np_table = {} _v_table = {} def __init__(self, tab, sim=0, bm25...
""" =========================== Plots with different scales =========================== Demonstrate how to do two plots on the same axes with different left and right scales. The trick is to use *two different axes* that share the same *x* axis. You can use separate `matplotlib.ticker` formatters and locators as desi...
# Please edit this list and import only required elements import webnotes from webnotes.model.doc import Document from webnotes.model.doclist import getlist from webnotes.model.code import get_obj from webnotes import session, form, is_testing, msgprint, errprint sql = webnotes.conn.sql convert_to_lists = webnotes.co...
"""Initial migration Revision ID: e421475dba3c Revises: Create Date: 2021-06-22 18:26:28.255632 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e421475dba3c' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ...
import torch import torch.nn as nn import torch.nn.functional as F class BasicConv(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True): super(BasicConv, self).__init__() self.out_channels = out_planes if bn: ...
def openData(doc): text = open(doc, 'r') text = text.read() return text def saveData(doc, data): text = open(doc, 'w') text = text.write(data) def parse(doc): text = openData(doc) lines = text.split('\n') heights = [] weights = [] for line in lines: components = line.spli...
#! /usr/bin/env python import sys import os import argparse import cv2 import rospy import roslib from std_msgs.msg import String, Float32MultiArray #from ar_track_alvar_msgs.msg import AlvarMarker, AlvarMarkers from sensor_msgs.msg import Image from geometry_msgs.msg import Twist from cv_bridge import CvBridge, CvBrid...
#!/usr/bin/env python # coding=utf-8 from __future__ import unicode_literals, absolute_import, print_function, division import sopel.module import sys import os moduledir = os.path.dirname(__file__) shareddir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) sys.path.append(shareddir) from BotShared import ...
import pandas as pd import os import numpy as np from sklearn.utils import resample df = pd.read_csv(os.path.abspath('dataset.csv'),header=None) y = df.iloc[:, 11].values X = df.iloc[:, :11].values #class 1과 0의 비율을 1:1로 upsampling함. 총 9040개의 데이터를 사용함. X_upsampled, y_upsampled = resample(X[y == 1], y[y == 1], replace=Tr...
import sys, sqlite3, getpass from prettytable import PrettyTable # Connection with the database dbConnection = sqlite3.connect(r"C:\\Users\\samjo\\documents\\sqlite\\SgrStore.db") dbCursor = dbConnection.cursor() # Get the username from environment variables (only for modifying update records) currentUser = getpas...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-13 20:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quiz', '0012_question_multiple_instances'), ] operations = [ migrations.Add...
print('MICHELL\'S TINY ADVENTURE 2!') print('upstairs or into Kitchen?') usr = str(input('>')) while True: if usr == 'Kitchen' or usr == 'back' or usr == 'downstairs': print('refrigerator or go "back"') usr = str(input('>')) print('use if 1 = ', usr) if usr == 'refrigerator': ...
from termcolor import colored papelaria = ( "Lapis", 1.70, "Borracha", 0.5, "Estojo", 20.50, "Esquadro Metalico", 3.70 ) #print(f"\033[1;32m{'LISTA DE PREÇOS':=^44}\033[m") print(f"\033[1;32m{'LISTA DE PREÇOS':=^44}") for i in range(int(len(papelaria)/2)): item = papelaria[2*i] ...
import numpy as np x = np.array([-1.0, 1.0, 2.0]) print("x 값",x) # 넘파일 배열에 부등호 연산을 수행하면 bool 배열이 생성 y = x > 0 print("y 값",y) y = y.astype(np.int) print("int 형으로 변환",y)
import os import json import python_http_client host = "https://api.sendgrid.com" api_key = os.environ.get('SENDGRID_API_KEY') request_headers = { "Authorization": 'Bearer {0}'.format(api_key) } version = 3 # we could also use client.version(3) client = python_http_client.Client(host=host, ...