text
stringlengths
8
6.05M
#!/usr/bin/env python ''' views.py: part of singularity package ''' from singularity.package import list_package, load_package, package from singularity.utils import zip_up, read_file, write_file from singularity.cli import Singularity import SimpleHTTPServer import SocketServer import webbrowser import tempfile imp...
import pip def install(package): pip.main(['install', package]) install('mutagen') #install('gTTS') #from gtts import gTTS from mutagen.mp3 import MP3
import os from os import listdir import io import json from distutils.version import StrictVersion from PIL import Image, ImageTk import urllib2 """This only works for Python Version 2.7 for now. This checks the version and if its newer then downloads the file and displays changes since the previous versio...
# Need something to reprocess data import glob, os # Look in final.old for cases os.chdir("final.old") cases = glob.glob("*") os.chdir("..") for case in cases: print "Processing Case %s" % (case,) # Symlink data in from thumper os.system("ln -s /thumper/mred/postprocess/data/%s data/%s" % (case,case)) # Run...
import fitbit from fitbit import gather_keys_oauth2 as Oauth2 import pandas as pd import numpy as np import datetime from datetime import timedelta import sys import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import json import requests import time import Keys import mat...
#!/usr/bin/python """ Simple HTTP server to be used as an internal, non-authorized notification email gateway. Using multipart with curl: $ curl -X POST http://localhost:1396/ -F subject="SUBJECT" -F body="BODY" Using postdata with wget: $ wget http://localhost:1396/ --post-data "SUBJECT;BODY" """ import cgi fr...
globalVar = "Global Scope" print("Global Variable called from outside class before class call:",globalVar) class FirstClass(): classVar = 10 print("Global Variable called from inside class:",globalVar) #Here self is the instance of the class def class_meth(self): print("Type is", type(self)) ...
from autodisc.representations.static.statisticsrepresentation import StatisticRepresentation from autodisc.representations.static.pytorchnnrepresentation.pytorchnnrepresentation import PytorchNNRepresentation import autodisc.representations.static.pytorchnnrepresentation
def parse(data): num = 0 output = [] for x in data: if x=='s': num = num ** 2 elif x=='i': num += 1 elif x=='d': num -= 1 elif x=='o': output.append(num) return output ''' Write a simple parser that will parse and run Dea...
"""Core components of the policy daemon.""" from asgiref.sync import sync_to_async import asyncio import concurrent.futures from email.message import EmailMessage import logging import aiosmtplib from dateutil.relativedelta import relativedelta from redis import asyncio as aioredis from django.conf import settings f...
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Contact(models.Model): name = models.CharField(u'名前',max_length=50) content = models.TextField(u'内容', max_length=1000) created_at = models.DateTimeField(u'問い合わせ日時', default=datetime.now) def __unicode__(self): ...
import smtplib, ssl from email.message import EmailMessage msg = EmailMessage() msg.set_content("Your_Message") msg["Subject"] = "Graphics Card" msg["From"] = "Your_Email" msg["To"] = "" context=ssl.create_default_context() with smtplib.SMTP("smtp.google.com", port=28) as smtp: smtp.starttls(context=context) ...
''' Projeto: Repositório de senhas. -> Este é um programa de gerenciamento de senhas não seguro. Porém eferece uma demonstração básica de como esses programas funcionam. -> Livro: Automatize tarefas maçantes com Python - AL Sweigart (pag 180). -> Aluno: João Pedro M. Riuto''' #! python 3 import sys...
import os from bsm.util import safe_rmdir from bsm.logger import get_logger _logger = get_logger() def run(param): clean_dirs = param['config_package'].get('clean', []) ['build', 'download', 'source', 'log'] for d in clean_dirs: if d in ['source', 'build']: dir_path = param['config_p...
# -*- coding: utf-8 -*- import unittest from unittest import TestCase import boto.s3.connection from boto.s3.key import Key import urllib, urllib2 import StringIO s3_cred = { 'host': 'precise64', 'port': 8000, #'port': 80, 'access_key':'4WLAD43EZZ64EPK1CIRO', 'secret_k...
def getModifiedArray(length, updates): rtn_list = [0] * (length + 1) for update in updates: rtn_list[update[0]] += update[2] rtn_list[update[1] + 1] -= update[2] for i in xrange(1, length): rtn_list[i] += rtn_list[i - 1] return rtn_list[:-1] print(getModifiedArray(5, [[1, 3, 2],[2, 4, 3],[0, 2, -2]])...
from __future__ import absolute_import from collections import defaultdict import grequests from celery import shared_task from django.conf import settings from documentos.helpers import split_document from documentos.models import Frame from gerente.datatxt_helpers import Datatxt from pruebas.helpers import compute...
# -*- coding: utf-8 -*- """ Created on Thu Aug 8 14:51:06 2019 @author: kanchana """ import numpy as np A = np.random.rand(9,10) print(A) m = A.shape[0] n = A.shape[1] i = 0 j = 0 jb = [] while i <= m-1 and j <= n-1: #print( A[i:m,j].size) if A[i:m,j].size == 0 : b...
import db_query def get_action(hand, stack, last_opponent_action, position, db): push_stack_value = db_query.get_valid_stack_value_to_push(hand, db) data = [stack] if int(stack) <= push_stack_value: data.insert(0, 'push') return data elif last_opponent_action == 'limp' and position == ...
import re testdata = [ ["byr", 1920], ["byr", 1921], ["byr", 2001], ["byr", 2001], ["iyr", 2010], ["iyr", 2011], ["iyr", 2019], ["iyr", 2020], ["eyr", 2020], ["eyr", 2021], ["eyr", 2029], ["eyr", 2030], ["hgt", "150cm"], ["hgt", "151cm"], ["hgt", "193cm"], ["hgt", "59in"],["hgt", "60in"], ["hgt", "76in...
# -*- coding: utf-8 -*- import operator import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import Rule from jarvis_scraper.items import JarvisScraperItem from jarvis_scraper.nlp.lib import get_distance class JarvisScraperSpider(scrapy.Spider): name = 'jarvis_scraper' start_url...
import itertools with open('input.txt') as my_file: input = my_file.readline() input_list = [int(s) for s in input] def pattern_maker(mask_length, repeat_count): base_pattern = [0, 1, 0, -1] pattern_block = list(itertools.chain. from_iterable(itertools.repeat(x, repeat_count) ...
__all__ = ["client", "collectables", "metrics", "cnfparse"]
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals import os import sys sys.path.append(os.curdir) SITEURL = '' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = True OUTPUT_PATH = '/out...
''' Created on Feb 2, 2016 @author: henry ''' # Accept number from user and determine if it is odd or EVEN_ODD num = input("Enter a number: ") mod = num % 2 if mod > 0: print("This is an odd number.") else: print("This is an even number.")
""" Members resource implementation. """ from typing import Optional, Union from pyyoutube.resources.base_resource import Resource from pyyoutube.models import MemberListResponse from pyyoutube.utils.params_checker import enf_parts, enf_comma_separated class MembersResource(Resource): """A member resource r...
############################################################################ # LOGISTIC REGRESSION # # Note: NJUST Machine Learning Assignment. # # Optimization: Grediant Descent (GD), Stochastic Grediant Descent(SGD). # # Author...
# Generated by Django 2.1.7 on 2019-03-10 15:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('milliard', '0010_player'), ] operations = [ migrations.AlterField( model_name='player', name='count_correct_answers'...
from django.apps import AppConfig class InvestAdminAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.invest_admin_app'
from django import forms from .models import NoticeDev from django_summernote.fields import SummernoteTextFormField, SummernoteTextField from django_summernote.widgets import SummernoteWidget # 공지사항 및 개발로그 게시판 글쓰기 폼 class BoardWriteForm(forms.ModelForm): noticedev_title = forms.CharField( max_length=128, ...
import socket import tkinter import threading import random import tkinter.messagebox Ip = '127.0.0.1' Port = 50007 ServerAddr = (Ip, Port) Port = random.randint(50008, 60000) client_addr = ('127.0.0.1', Port) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(client_addr) Channel = '0' UserName = '0' # 表...
# memo: camera center is located 32.0mm left of pickup center, y=220mm import json import cv2 import numpy as np import math from socket import * import time # physical limit Xlimit = [0, 240] Ylimit = [0, 259] #Zlimit = [0, 160] #[mm] Zlimit = [0, 800] #-------------------------------------------------------- globa...
import urllib.request from urllib.request import Request, urlopen import csv from bs4 import BeautifulSoup from teamURLs import teamurls, teamNames def writeStats(url, name): quote_page = url user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46' # get the HTML page of...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('insumos', '0001_initial'), ] operations = [ migrations.CreateModel( name='Checklist', fields=[ (...
#!/usr/bin/python import os import sys def clean(fname): print('cleaning %s' % fname) with open(fname, 'rt') as f: lines = f.readlines() newlines = [] for line in lines: if line.startswith('glossaryText:') or line.startswith('conceptRef:'): pass else: ...
# -- Project information ----------------------------------------------------- project = 'LUNA' copyright = '2020 Great Scott Gadgets' author = 'Katherine J. Temkin' # -- General configuration --------------------------------------------------- master_doc = 'index' extensions = [ 'sphinx.ext.autodoc', 'sph...
class Solution(object): def reverse(self, n): """ :type x: int :rtype: int """ rev = 0 negative = False # reverse the int # taking care of negative cases if n < 0: negative = True n = abs(n) # reversing the numb...
from __future__ import print_function import re from inspect import isfunction from collections import defaultdict from . import uff_pb2 as uff_pb from .data import FieldType, create_data from .exceptions import UffException def _resolve_ref(field, referenced_data): field_type = field.WhichOneof("data_oneof") ...
from absl import app, flags, logging from absl.flags import FLAGS import numpy as np from yolov3.models import YoloV3 from yolov3.utils import load_darknet_weights import tensorflow as tf flags.DEFINE_string('weights', './data/yolov3.wiegthts', 'path to weights file') flags.DEFINE_string('output', './checkpoints/yolov...
from flask import Flask, render_template from flask_sockets import Sockets import random import json import algo import info app = Flask(__name__, static_url_path='') sockets = Sockets(app) ## Load Data ## main_data = info.main() ############### @app.route('/') def index(): return render_template('index.html...
"""AppConfig for dmarc.""" from django.apps import AppConfig from modoboa.dmarc.forms import load_settings class DmarcConfig(AppConfig): """App configuration.""" name = "modoboa.dmarc" verbose_name = "Modoboa DMARC tools" def ready(self): load_settings() from . import handlers
class Node: def __init__(self,value): self.value=value self.link=None class List: def __init__(self): self.header=None def insert(self,value): new=Node(value) if(self.header==None): self.header=new return ptr=self.head...
import cv2 import numpy as np from shapely.geometry import Polygon from functions.homography_validation import all_inliers_in_the_polygon, \ out_area_ratio from functions.plot_manager import save_two_polygons, save_window, save_inliers from functions.window_functions import window_filter, \ get_continually_dis...
from mod_base import* class Raw(Command): """Send raw data to the irc server.""" def run(self, win, user, data, caller=None): if data == None: return False self.bot.SendRaw(data) return True module = { "class": Raw, "type": MOD_COMMAND, "level": 5, "zone":IR...
import sys import os f = open("C:/Users/user/Documents/atCoderProblem/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- d,n = map(int,input().split()) if n <= 99: print(100 ** d * n) else: print(100 ** d * 101)
""" config.py Microsimulation config for mulit-LAD MPI simulation """ import numpy as np import glob import neworder # define some global variables describing where the starting population and the parameters of the dynamics come from initial_populations = glob.glob("examples/people_multi/data/ssm_*_MSOA11_ppp_2011.cs...
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved. # This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing. import os, math, signal, unittest, shutil, time, sys, random import pexpect MENU_DELAY = 0.4 def sign(x): if x < 0: return -1 elif x ...
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
t1 = () #빈 튜플 t2 = (1, ) #요소를 하나만 저장할 때 ,를 붙여줍니다. t3 = (1, 2, 3) t4 = 1 ,2 ,3 #파이썬에서 요소들 사이에 ,를 넣어주면 튜플 선언 t4 = "송", "진", "우" t5 = (1, 2, ("ab", "cd"), ["list1", "list2"]) #리스트처럼 모든 자료형 저장가능 print(t1) print(t2) print(t3) print(t4) print(t5) #바뀌지 않는 데이터를 저장할 때 사용하는 자료형 : 튜플 song = ("O형", "황인", "남성") # son...
# Generated by Django 2.2.13 on 2020-07-03 16:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0012_auto_20200702_1624'), ] operations = [ migrations.CreateModel( name='Fronts', fields=[ ...
__author__ = 'c.mayo'
def global_estimate(estimates): best,worst,avg = 0,0,0 for x in estimates: best += x[0] worst += x[1] avg += sum(x) return (best,avg/2,worst) ''' Lately, feature requests have been piling up and you need a way to make global estimates of the time it would take to implement them al...
import json import tornado from tornado import gen, web from extensions import TumblrMixin from handlers.base import BaseHandler class AuthLoginHandler(BaseHandler, TumblrMixin): @tornado.web.asynchronous @tornado.gen.coroutine def get(self): try: self.require_setting("tumblr_consumer_...
#!/usr/bin/env python3 # Simulation of the children's game "Hoot Owl Hoot". The game involves simple # decision making, which provides an opportunity to simulate and compare # strategies. import attr import pprint import random import time from enum import Enum NEST = 888 ORIG_BOARD = "YGOBP RBPRY GBORP YGOBP RGYOB...
############################################################################## # # NAME: srmmetrics.py # # FACILITY: SAM (Service Availability Monitoring) # # COPYRIGHT: # Copyright (c) 2009, Members of the EGEE Collaboration. # http://www.eu-egee.org/partners/ # Licensed under the Apa...
from spack import * import glob import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class Geant4G4ndl(Package): url = "http://cmsrep.cern.ch/cmssw/repos/cms/SOURCES/slc7_amd64_gcc700/external/geant4-G4NDL/4.5/G4NDL.4.5.tar.gz" ...
#!/usr/bin/env python import rospy from week2.srv import velocity, velocityResponse def handle_rad_req(req): return velocityResponse(1/req.radius) def return_rad(): rospy.init_node('ang_vel_service_node') s = rospy.Service('compute_ang_vel', velocity, handle_rad_req) rospy.loginfo('Available for co...
import re from typing import List import requests from nio import MatrixRoom import aiosqlite from dors import command_hook, HookMessage, Jenny, startup_hook @startup_hook() async def __setup_db(bot: Jenny): async with aiosqlite.connect("./balance.db") as db: await db.execute("CREATE TABLE IF NOT EXISTS...
# given a matrix of words and a dictionary # [ # [ 'c, 'a', 't', 'e' ] # [ 'a', 'r', 't', 's' ] # [ 'r', 'e', 'n', 't' ] # ] # # find all words: horizontal, veritcal and diagonal # # e.g. cat, ate, at, a, car, are, est, rent, arts, art def find_words_in_matrix(): # lets compose first pass words = set() de...
# -*- coding: utf-8 -*- import wx import numpy as np import matplotlib matplotlib.use("WXAgg") from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar from matplotlib.ticker import MultipleLocator, ...
if __name__ == '__main__': N = int(input()) lista = [] for i in range(0, N): comando = input() comando = comando.split() if (comando[0] == "insert"): lista.insert(int(comando[1]), int(comando[2])) elif (comando[0] == "print"): print(lista) elif...
#!/home/blue/tf2/bin/python import os import pandas as pd from functools import partial import numpy as np import SimpleITK as sitk # to read nii files from sklearn.model_selection import train_test_split import pickle import random #================ Environment variables ================ os.environ['TF_CPP_MIN_LOG_LEV...
"""Managers for OAuth models""" from __future__ import absolute_import from readthedocs.privacy.loader import RelatedUserQuerySet class RemoteRepositoryQuerySet(RelatedUserQuerySet): pass class RemoteOrganizationQuerySet(RelatedUserQuerySet): pass
from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework.permissions import AllowAny from rest_framework import mixins from .models import View, Component from .serializers import ComponentSerializer, ViewSerializer class ComponentViewSet(mixins.RetrieveModelMixin, viewse...
import unittest from katas.kyu_6.give_me_diamond import diamond class DiamondTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(diamond(3), ' *\n***\n *\n') def test_none(self): self.assertIsNone(diamond(6)) def test_none_2(self): self.assertIsNone(diamond(-1))...
#!/usr/bin/env python # -*- coding: utf-8 -*- import allure def test_attach_text(): allure.attach("这是一个纯文本", name="这是测试文本附件", attachment_type=allure.attachment_type.TEXT) def test_attach_html(): allure.attach("<body>这是一段html块</body>", name="这是测试html附件", attachment_type=allure.attachment_type.HTML) def test_a...
import copy from django.test import TestCase from core.tests.test_helpers import ADDRESS_EXAMPLE_DATA from custom_auth.forms import ClientUserCreationForm from custom_auth.tests.test_helpers import create_client_example from inquiry.forms import InquiryHomeForm, InquiryFirstForm, WizardClientUserCreationForm from inq...
# Author:ambiguoustexture # Date: 2020-02-05 from itertools import groupby file = 'hightemp.txt' lines = open(file).readlines() items = list(line.split('\t')[0] for line in lines) items.sort() res = [(item, len(list(group))) for item, group in groupby(items)] res.sort(key = lambda item : item[1], reverse = True) f...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 以后每天早上都吃了前一天剩下的一半零一个。 到第10天早上想再吃时,见只剩下一个桃子了。 求第一天共摘了多少。 程序分析:采取逆向思维的方法,从后往前推断。 """ tmp = 1 print tmp for i in range(1, 10, 1): tmp = (tmp + 1) * 2 print tmp
from django.urls import path from quotes.api.views import QuoteDetailAPIview, QuoteListCreateAPIView urlpatterns = [ path("quotes/", QuoteListCreateAPIView.as_view(), name="quote-list"), path("quotes/<int:pk>/", QuoteDetailAPIview.as_view(), name="quote-detail") ]
"""Implementation of treadmill admin ldap CLI schema plugin. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import codecs import click import pkg_resources import six from treadmill import cli from treadmill im...
import os import numpy as np import json import cv2 import torch basicPath = os.sys.path[0] trainPath = os.path.join(basicPath, "Classification\\Data\\Train") testPath = os.path.join(basicPath, "Classification\\Data\\Test") classList = ['i2', 'i4', 'i5', 'io', 'ip', 'p11', 'p23', 'p26', 'p5', 'pl30', ...
from flask import render_template, flash, request from flask_login import login_user, logout_user, current_user from models.Modelos import Usuario from flask_sqlalchemy import SQLAlchemy from flask_login import login_required import sys db = SQLAlchemy() ''' Función que se ejecuta al entrar a la página de inicio de s...
# -*- coding: utf-8 -*- import sys from c_answers import RunAnswer from kivy.app import App # kivy.require("1.9.1") from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty, StringProperty # NOTA !!!! cambiar la ruta para llamara el archivo de la vista dialog_qu...
# Programming project 1 - Zain Malik #import math module import math # print statements that state purpose of this program print("") print("Welcome to Osprey car rentals.") print("This program will make car rental calculations for you.\n") print("At the prompts, please enter the following:") print("\tYour custo...
''' Francesco Giovanelli - March 2019 Utils for generator and discriminator networks ''' import pandas as pd import math import numpy as np import tensorflow as tf import keras from keras import backend as K from keras.models import Model from keras.layers import * from keras.utils import to_categorical from kera...
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ users_str = input('Введите строку из нескольких слов, рахделенных пробелами: ') tmp = users_str.split(...
# Copyright (c) 2018 Amdocs # # 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 agree...
__author__ = 'Justin' import googlemaps from random import choice import geojson import networkx as nx import math from datetime import datetime import gmapsKeys from geopy.distance import vincenty as latlondist # Load API Keys APIkeys = gmapsKeys.keys('keys.txt','keyusages.txt','keydates.txt',2500) key = APIkeys.g...
import random import cal_time ls = list(range(100000)) random.shuffle(ls) @cal_time.run_time def shell_sort(ls): d=len(ls)//2 while d>=1: for i in range(d,len(ls)): tmp=ls[i] while i-d>=0 and tmp<ls[i-d]: ls[i]=ls[i-d] i-=d ls[i]=tmp ...
from django.contrib import admin from django.urls import path from .views import * app_name = "home" urlpatterns = [ path('',HomeView.as_view(),name = 'home'), path('product/<slug>',ProductDetailView.as_view(),name = 'product'), path('search', SearchView.as_view(), name='search'), path('category/<slug>...
def corrections(x): if x > 0: return '{} is more than zero.'.format(x) return '{} is equal to or less than zero.'.format(x) ''' Correct this code so that it takes one argument, x, and returns "x is more than zero" if x is positive (and nonzero), and otherwise, returns "x is equal to or less than zero....
from tkinter import * from tkinter import ttk from PIL import Image, ImageTk #import Image, ImageTk root = Tk() content = ttk.Frame(root, padding=(3,3,12,12)) imageFrame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100) imagePILPath = '/home/yuanchueh/Documents/git/measureFromImage/car.png' ...
# Generated by Django 3.0.6 on 2020-05-07 10:32 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='post', opt...
from django.views.decorators.csrf import ensure_csrf_cookie from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django.shortcuts import render_to_response, RequestContext
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-02-01 15:50 from __future__ import unicode_literals from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dep...
#!/usr/local/bin/python3 import os import re import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from download import app if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) if len(sys.argv) > 1: cmd = sys.argv[1] if cmd == 'test' ...
#In Python, you can use a built-in function "reversed", # which will return a new list with reversed data, or call a .reverse() method, # which will modify the original list and return it. a=["apple","bat","cat"] print(a) c=a.reverse() print(a)
s = input() if s.count('1') % 2 == 0: s += '0' else: s += '1' print(s)
# -*- coding: utf-8 -*- """Module responsible for setting up and handling API endpoints""" from geopy.distance import great_circle from flask import abort, jsonify, make_response from flask_restful import Resource, reqparse, fields, marshal from tour.database import db from tour.extensions import auth from tour.publi...
import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor import sklearn.model_selection data = pd.read_csv('/data-out/abalone.csv') data.replace({'Sex': {'M': 1, 'F': -1, 'I': 0}}, inplace=True) y = data['Rings'] X = data.drop(columns=['Rings']) anw = '' for k in range(1, 51): cl...
import os from PIL import Image import numpy as np import random import re import tensorflow as tf from augmentationHelper import get_random_augment SPLIT_FACTOR = "$" def image_name(image_path): regex = ".*[\\/|\\\](.*)[\\/|\\\](.*).jpg" m = re.match(regex, image_path) return m.group(1) + "_" + m.gro...
#ipconfig getifaddr en0 get just my local ip for mac #hostname -I get just my local ip for linux import subprocess import time HOST_AND_HOSTNAME = {} HOST_AND_MAC = {} CURRENT_IP = "" GATWAY = "" def get_local_ip(): global CURRENT_IP global GATWAY out = subprocess.Popen(['ipconfig','getif...
# JTSK-350112 # raise_exc.py # Taiyr Begeyev # t.begeyev@jacobs-university.de # three different exception classes derived from Exception class OwnException1(Exception): pass class OwnException2(Exception): pass class OwnException3(Exception): pass def something(choice): """ Throw exceptions depending on t...
import os # basedir = os.path.abspath(os.path.dirname(__file__)) # /home/mushcat/webnotebook class config: """docstring for config""" SECRET_KEY = os.environ.get('SECRET_KEY') or "r4Nd0mS5cRe7" SQLALCHEMY_TRACK_MODIFICATIONS = True REMEMBER_COOKIE_DURATION = 86400 @staticmethod def init_app(app): pass class...
DATE_FMT = "%Y-%m-%d" YEAR_FMT = "%Y" START_DATE_HELP_STRING = "The start date for the data download in format 'YYYY-MM-DD'" END_DATE_HELP_STRING = "The end date for the data download in format 'YYYY-MM-DD'" FILE_PATH_HELP_STRING = "The file path to store the downloaded data. Must include filename and .pkl file extensi...
"""This is a substantially improved version of the older Interpreter.py demo It creates a simple GUI JPython console window with simple history as well as the ability to interupt running code (with the ESC key). Like Interpreter.py, this is still just a demo, and needs substantial work before serious use. """ class C:...
from Cython.Build import cythonize from distutils.core import setup setup(name="Hello world app", ext_modules=cythonize("hello_world.pyx") )
#!/usr/bin/env python # this is modified csdata.py from __future__ import print_function import fastjet as fj import fjcontrib import fjext import fjtools import tqdm import argparse import os import numpy as np import array import copy import random import uproot import pandas as pd import time from pyjetty.mputi...
""" Copyright (C) 2020 SunSpec Alliance 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, merg...