text
stringlengths
38
1.54M
from folio import Folio proj = Folio(__name__, source_path='viewer', jinja_extensions=['content_object_tag.ContentObjectTagExtension']) proj.build()
import FWCore.ParameterSet.Config as cms siPixelRawData = cms.EDProducer("SiPixelDigiToRaw", Timing = cms.untracked.bool(False), InputLabel = cms.InputTag("simSiPixelDigis") )
DEBUG = 0 TRACE = 0 def set_debug_level(level): global DEBUG global TRACE if level == 1 or level == "debug" or level == "Debug" or level == "DEBUG" or level == "d" or level == "D": DEBUG = 1 TRACE = 0 print("DEBUG switched on.") elif level == 2: DEBUG = 1 TRACE ...
from __future__ import absolute_import, division, print_function import pytest from drms.utils import ( _pd_to_datetime_coerce, _pd_to_numeric_coerce, _split_arg, _extract_series_name) # test_pd_to_datetime # test_pd_to_numeric @pytest.mark.parametrize('in_obj, expected', [ ('', []), ('asd', ['asd'...
import tkinter as tk import tkinter.ttk as ttk from gui.parameters.filter_parameters import FilterParameters from model.interface import get_interfaces class InterfacePage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self....
import numpy as np def test_op_maxpool(ugraph): with ugraph.begin_construction(): tensor_x, = ugraph.add_op( np.random.rand(10, 256, 256, 5), op_type='Const', name='x' ) tensor_out, = ugraph.add_op( tensor_x, op_type='MaxPool', ...
import roslib; roslib.load_manifest('george') import rospy ############################################################################################### ############################################################################################### class RobotDescription(): ############################...
# coding=utf-8 from distutils.core import setup from setuptools import find_packages import zsh_history_to_fish def get_readme(): with open('README.md') as readme_file: return readme_file.read() setup( name='zsh-history-to-fish', version=zsh_history_to_fish.__version__, description=zsh_his...
from locators import Catalog, Alert from .BasePage import BasePage class AdminProducts(BasePage): def open(self): """Открытие панели администратора""" self._open("/admin") return self def open_product_page(self): self._click(Catalog.navigation.catalog_outs) self._clic...
import bcrypt from psql import query, query_no_fetch, make_safe #needed to hash the password (makes it more secure) salt = bcrypt.gensalt() def register_user(uname, psword, name, street, postal, city, country): """ Input: Strings (Username, Password, Name, Street, Postal, City, Country) Check...
# --------------------------------------------------------------------------- # hydrology_processing.py # # Description: Pulls three feature classes of data from downloaded Geodatabases on # hydrology: NHDArea, NHDFlowline, and NHD Waterbody. This data will be # pulled from all the SubRegions ...
#------------------------------------------------------------- if __name__ == "__main__": import tempfile import os from anuga.shallow_water import Domain, Reflective_boundary, \ Dirichlet_boundary from anuga.pmesh.mesh_interface impor...
a=((10,20,30),[40,50,60],(70,80,90)) print(a) for p in a: print(p,type(p)) a[1][1]=100 print(a)
from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env('DJANGO_SECRET_KEY', de...
# coding: utf-8 # In[1]: get_ipython().run_line_magic('load_ext', 'google.cloud.bigquery') # In[6]: get_ipython().run_cell_magic('bigquery', 'top_five_states ', 'SELECT\n state AS state,\n COUNT(1) AS birth_count\nFROM `bigquery-public-data.samples.natality`\nGROUP BY state\nORDER BY birth_count DESC\nLIM...
#!/usr/bin/env python3 import os import pandas as pd import sklearn from asm_parser import AsmParser from utils import search_path from sklearn.externals import joblib from sklearn.pipeline import Pipeline import keras import word2vec from keras.models import Sequential ALL_VULS = ['Underflow','Overflow','Multisig','C...
import numpy as np from pandas import DataFrame, datetime, concat,read_csv, Series from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from math import sqrt from sklearn.preprocessing import MinMaxScaler from statsmodels.stats.diagnostic import acorr_ljungbox from statsmodels.tsa.statto...
from django.db.models.signals import pre_save from django.dispatch import receiver from group.models import Group @receiver(pre_save, sender=Group) def group_capitalize(sender, instance, **kwargs): instance.first_name = instance.first_name.capitalize() instance.last_name = instance.last_name.capitalize()
# -*- coding: utf-8 -*- import json import requests import pandas as pd import xmltodict import re """ Client ID: dj00aiZpPUlMRXp5U0loQmRXWiZzPWNvbnN1bWVyc2VjcmV0Jng9NTM- シークレット: qU7QwCYwqbQShh7Z6166pLeW2uAmyIOIJ7XxvDLJ """ CLIENT_ID = "dj00aiZpPUlMRXp5U0loQmRXWiZzPWNvbnN1bWVyc2VjcmV0Jng9NTM-" SECRET = "qU7Qw...
#!/usr/bin/env python import sys from collections import defaultdict from tabulate import tabulate count = defaultdict(int) for line in open(sys.argv[1]): words = line.split('/') model = words[1].split('-') cat = model[0][0] + model[2][0] if cat not in count: count[cat] = 0 count[cat] += 1...
#-*- coding:utf-8 -*- import json import time import datetime from sensitive_user_portrait.extensions import user_datastore from sensitive_user_portrait.time_utils import ts2datetime, ts2date from flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect, make_response from flask.ext.s...
import abc from typing import Iterator, Tuple, Optional, Type, NamedTuple, Union, Callable """ We define `__all__` variable in order to set which names will be imported when writing (from another file): >>> from framework.graph_search.graph_problem_interface import * """ __all__ = ['GraphProblemState', 'GraphProblem'...
def test_palindrome(cara): cara_original = cara # cara = cara.strip() # cara = cara.lower() # cara = cara.split(" ") # cara = "".join(cara) cara = "".join(cara.strip().lower().split(" ")) tmp = "" for i in range(len(cara),0,-1): tmp += cara[i-1] if tmp == cara: prin...
""" Napisz program obliczający średnią wartość temperatury w danym tygodniu na podstawie temperatur wprowadzonych przez użytkownika. """ suma_temperatur = 0 numer_dnia = 1 LICZBA_DNI_TYGODNIA = 7 while numer_dnia <= LICZBA_DNI_TYGODNIA: suma_temperatur += int(input(f"Podaj temperaturę z dnia {numer_dnia}: ")) ...
"""Tests for respite.views.""" from datetime import datetime from nose.tools import * from django.conf import settings from django.test.client import Client from . import monkeys from .project.app.models import Article, Author import json client = Client() def setup(): Article.objects.create( title = ...
from SPARQLWrapper import SPARQLWrapper, JSON import json from config import settings import urllib2 class ExperimentalCondition: def __init__(self,host,uri): self.host = host self.uri = uri try: #raise urllib2.URLError('Testing') sparql = SPARQLWrapper(host) ...
#FUNCTIONS def hello(): print("Hello!") hello() def add(x, y): result = x + y print(result) add(58, 83) def names(name): print(f"Hello {name}") names("Bob") def divide(dividend, divisor): if divisor != 0: print(dividend / divisor) else: print("Can't divide by 0") divide(5...
''' Usage: "Usage: python getUserRepeatDist.py <path-to-tweets-pickle-dir>" Behavior: plots the number of tweets per user in our data set. ''' import cPickle import os import sys import time from collections import Counter import numpy as np import matplotlib.pyplot as plt directory_name = "partitioned-tweets/twee...
import os import json from struct import unpack import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() file_path = tkFileDialog.askopenfilename() hoff = 0 buff = '' units = {} def rao(offset, size): return buff[offset:offset+size] def read_instance(offset): position = unpack("<fff", rao(offset, 1...
from selenium import webdriver import time import unittest import HtmlTestRunner class suite(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome('chromedriver.exe') def test_busqueda(self): self.driver.get("https://www.google.com/") self.busqueda = self.driver.find_ele...
# MIT License # # Copyright (c) 2022 Quandela # # 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, pub...
# from tensorflow import keras ## keras backend for amd gpu --> IS ACTUALLY SLOWER THAN CPU ON 2015 iMac # import os # os.environ["KERAS_BACKEND"] = "plaidml.keras.backend" # import keras # from keras import backend as K # from keras.models import Sequential # from keras.layers import Dense, Dropout, Activation, Flatt...
# #Copyright (c) 2018 Jie Zheng # from e3net.inventory.invt_base import get_inventory_base from e3net.common.e3exception import e3_exception from e3net.common.e3exception import E3_EXCEPTION_IN_USE from e3net.common.e3exception import E3_EXCEPTION_NOT_FOUND from e3net.common.e3exception import E3_EXCEPTION_INVALID_ARGU...
import cv2 import numpy as np def make_points(image, line): slope, intercept = lines y1 = int(image.shape[0]) y2 = int(y1*3/5) x1 = int((y1-intercept)/slope) x2 = int((y2-intercept)/slope) return [[x1, y1, x2, y2]] def average_slope_intercept(image, lines): left_fit = [] r...
# ---------------------------------------------------------------------------- # GS Nodegraph Copyright 2019-2021 by Noah Rahm and contributors # # 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...
from web.url.url import addURLToList,printURLList from web.views import MainView from web.views import AbortView def loadurllist(): #GET URL addURLToList(r'main(\/)?$','GET',MainView.MainView) addURLToList(r'faveicon.ico(\/)?$','GET',AbortView.AbortView404) addURLToList(r'signup(\/)?$','GET',MainView....
# section02-1 # 파이썬 크롤링 기초 # urllib 사용법 및 기본 스크랩핑 import urllib.request as req # 파일 url img_url = "https://newsimg.hankookilbo.com/cms/articlerelease/2019/04/29/201904291390027161_3.jpg" html_url = "https://google.com" # 다운 받을 경로 save_path1 = "c:/Users/win7/Documents/GitHub/Crawling_Study/save_folder/test1.jpg" save...
from .cell import Cell from collections import deque class Phenotype: def __init__(self, input_coords, output_coords, genome): self.genome = genome egg = Cell(0, 0, 1, 1, 1, {}, {}, genome) self.inputs = [ Cell(x, y, 0, 0, 0, {}, {egg: 1}, None) for x, y in input_coords ...
def update_matrix(matrix): res = matrix for row in range(len(matrix)): for col in range(len(matrix[0])): if matrix[row][col] == 1: res[row][col] = dfs(matrix, row, col) return res def dfs(matrix, row, col): if row < 0 or col < 0 or row >= len(matrix) or col >= len...
from __future__ import absolute_import from __future__ import unicode_literals import mock import pytest from git_code_debt.list_metrics import color from git_code_debt.list_metrics import CYAN from git_code_debt.list_metrics import main from git_code_debt.list_metrics import NORMAL from git_code_debt.util.compat imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging, os log_file = os.getenv('PYTHON_LOG') logging.basicConfig(filename=log_file, filemode='a', level=logging.DEBUG) logger = logging.getLogger('basic_logging')
import math import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error, mean_absolute_percentage_error def symmetric_mean_absolute_percentage_error(actual, forecast): F = np.array(forecast) A = np.array(actual) return 100 / max(len(A), len(F)) * np.sum(2 * np.abs(F - A) / (np.a...
import csv from django.core.files.storage import FileSystemStorage import datetime from django.db.models import Q from django.shortcuts import redirect, render from django.views.generic import TemplateView, FormView, DetailView from application.forms import CreateDispatcherApplicationsForm, ApplicationByCommissionerC...
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accom...
from abc import ABC from input_data import InputData from result import ResultData class Solver(ABC): name:str=None def __call__(self, data:InputData)->ResultData: pass
"""Add TestCase.step_id Revision ID: 3265d2120c82 Revises: 21c9439330f Create Date: 2014-04-02 15:26:58.967387 """ # revision identifiers, used by Alembic. revision = '3265d2120c82' down_revision = '21c9439330f' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('test', sa.Column('ste...
from __future__ import absolute_import import numpy as np import tensorflow as tf import collections import cv2 from realsafe.attack.base import Attack from realsafe.model import Classifier from realsafe.attack.utils import mean_square_distance as distance class Evolutionary(Attack): """ l_2 optimized ...
import pandas.util.testing as tm import pyspark.sql.functions as F import pytest from pyspark.sql.window import Window from pytest import param import ibis pytest.importorskip('pyspark') pytestmark = pytest.mark.pyspark @pytest.mark.parametrize( ('ibis_window', 'spark_range'), [ param( i...
def nejdelsi_slovo (a): max = 'j' for i in a.split(): if len(a) > max: max = i return max a = str('se dodo, dodose') nejdelsi_slovo(a.split(' '))
#!/usr/bin/env python3 import sys morse = {'a': ".-", 'b': "-...", 'c': "-.-.", 'd': "-..", 'e': ".", 'f': "..-.", 'g': "--.", 'h': "....", 'i': "..", 'j': ".---", 'k': "-.-", 'l': ".-..", 'm': "--", 'n': "-.", 'o': "---", 'p': ".--.", 'q': "--.-", 'r': ".-.", 's': "...", 't...
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm from . import utils def get_homepage(request): """Рендерит домашнюю страницу""" return render(request, 'learning_logs/index.html') @log...
from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from clubkit.shop.models import Product from clubkit.clubs.models import ClubInfo from .cart import Cart, CartPackage from .forms import CartAddProductForm from clubkit.clubs.models import Packages @...
''' Calcular o valor de k, considerando que f,L,Q,ΔH,ϑ são dados de entrada e g=9.81 (gravidade) e ε=0.000002. D=8fLQ2π2gΔH−−−−−−−√5 Rey=4QπDϑ k=0.25[log10(ε3.7D+5.74Rey0.9)]2 ENTRADA: A entrada f,L,Q,ΔH,ϑ deve ser solicitada nesta ordem. Lembrando que g=9.81 e ε=0.000002 e π são constantes e NÃO devem ser pedidos c...
from stark.service.v1 import StarkHandler from django.conf.urls import url from django.shortcuts import render, reverse, HttpResponse, redirect from django.utils.safestring import mark_safe from django.http import JsonResponse from django.conf import settings from manage_system import models from stark.forms.forms impo...
from setuptools import setup setup(name='factory', version='0.0.1', install_requires=['gym', 'simpy']#And any other dependencies required )
import sys import readConf as rc import readData as rd import handleData as hd import FPrecommendation as fpr import ALSrecommendation as alsr import KMEANSrecommendation as kmeansr from pyspark import SparkConf, SparkContext """ this func is the entry of the whole application """ if __name__ == '__main__': "...
#!/bin/python3 def minTime(machines, goal): left = goal // len(machines) right = max(machines) * goal while left < right: mid = left + (right - left) // 2 if sum(mid // m for m in machines) < goal: left = mid + 1 else: right = mid return left // C++ long...
#!/usr/bin/python3 import requests def urlpull(): #usrpull is variable from part1 #for now define usrpull as pikachu for testing usrpull = 'pikachu' pokemon = requests.get('https://pokeapi.co/api/v2/pokemon/' + usrpull) link = pokemon.json()['sprites']['front_default'] print (link) urlpull()
# -*- encoding: utf-8 -*- ############################################################################## # # Vikasa Infinity Anugrah, PT # Copyright (c) 2011 - 2013 Vikasa Infinity Anugrah <http://www.infi-nity.com> # # This program is free software: you can redistribute it and/or modify # it under the term...
import re from core.msfActionModule import msfActionModule from core.keystore import KeyStore as kb from core.utils import Utils class scan_msf_smbuserenum(msfActionModule): def __init__(self, config, display, lock): super(scan_msf_smbuserenum, self).__init__(config, display, lock) self.title = "...
import requests import uuid from django.shortcuts import get_object_or_404 from rest_framework import viewsets, status from users.models import Profile, UserRelationship from users.api.serializers import FullProfileSerializer, UserRelationshipSerializer, CondensedProfileSerializer, ProfileSerializer from rest_framework...
# -*- coding: utf-8 -*- """ sports_dataset_frame.py """ from data.sports_dataset_frame_player import SportsDatasetFramePlayer class SportsDatasetFrame(): """ SportsDatasetFrame """ def __init__(self, match_status_id: int, frame_id: int, history_id: int, ball_x: float, ball_y: float, ...
# -*- coding:utf-8 -*- from functools import partial import sys import uuid import time import json import datetime from PySide2 import QtCore from PySide2.QtCore import Slot from PySide2.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QGroupBox, QLabel, QComboBox, QLineEdit, QGridL...
import tkinter as tk from PIL import Image, ImageTk, ImageDraw from .picture_button import Button import numpy as np class MainPictureComponent(tk.Label): def __init__(self, master, image, file): tk.Label.__init__(self, master = master, width = 180, height = 200, image = image, padx=10, pady=10, borderwid...
''' This script allows you to input x amount of digits to form a "ticket" (list of those numbers) and check how many times you have to generate another list of 4 numbers (won_ticket) to match yours. Other words = lotteries have pretty bad rates, I'd say. I left the value extra low, for demo purposes''' from random imp...
#take a file name as command line argument, count how many times each word appears in the file and prints the world #that appears the most #如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么呢? # 需要模块:sys # 参数个数:len(sys.argv) import sys def read_file(file_path): file_to_read= open(file_path, "r") # 读成char的...
""" What are the results of the following operations? Why? 1.5 + 2 1.5 // 2.0 1.5 / 2.0 1.5 ** 2 1 / 2 -3 // 2 """
print("Importing helpers...") from mp3helpers import * print("Importing other stuff...") from collections import defaultdict, OrderedDict from time import time import copy import numpy as np from sklearn.naive_bayes import BernoulliNB, MultinomialNB import sys print("Done importing...") chunk = 1000 lenDict = 50000 st...
# !/usr/bin/env python # coding=utf-8 """ Graphs for lecture 4, plot solution to an ODE """ from __future__ import print_function import sys import numpy as np from scipy.integrate import odeint from scipy.optimize import fsolve from common import make_fig, GOOD_RET __author__ = 'hbmayes' # noinspection PyUnusedL...
from copy import deepcopy, copy from sqlalchemy_dao import Dao from werkzeug.exceptions import NotFound from schema import Articles, DB, Categories # aggiunta gestione categorie class ArticlesDAO(object): def __init__(self): self.dao = Dao(DB) def find_all(self): with self.dao.create_sessi...
# coding: utf-8 """ Yagna Market API ## Yagna Market The Yagna Market is a core component of the Yagna Network, which enables computational Offers and Demands circulation. The Market is open for all entities willing to buy computations (Demands) or monetize computational resources (Offers). ## Yagna Market A...
# coding:utf-8 import serial, commands import time import re from binascii import hexlify, unhexlify from struct import pack, unpack import math import codecs class UCam(object): """ an interface to communicate with a uCam-II camera over a UART serial connection. """ def __init__(self): #...
# -*- coding: utf-8 -*- """ Created on Fri Jun 26 22:04:04 2020 @author: giles """ import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import transforms import random import shutil import open3d as o3d def get_object_T_camera(x: float, y: float, z: float) ...
# the test process for the spongebob character classifier from services.data_preprocessor_service import DataPreprocessorService from classifiers.spongebob_character_classifier import SpongebobCharacterClassifier from models import data_model, fully_connected_layer_model, activation_layer_model class SpongebobCharac...
# balance = 4213 # annualInterestRate = 0.2 # monthlyPaymentRate = 0.04 balance = 4842 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 monthlyInterestRate = annualInterestRate / 12.0 totalPaid = 0 for i in range(1, 13): minimumMonthlyPayment = monthlyPaymentRate * balance monthlyUnpaidBalance = balance - ...
from flask import Flask, render_template, url_for, request, session, redirect from flask.helpers import flash from flask_pymongo import PyMongo import bcrypt app = Flask(__name__) app.config["BUNDLE_ERRORS"] = True app.secret_key = 'mysecret' app.config['MONGO_DBNAME'] = 'Fatema' app.config['MONGO_URI'] = 'mongodb+sr...
################################### #_SIMPLE PYTHON CALCULATOR PROGRAM_# ################################### ################# #Basic Functions# ################# # ADDITION def add(x, y): return x + y # SUBTRACTION def sub(x, y): return x - y # MULTIPLICATION def mult(x, y): return x * y # DIVISI...
#-*- coding: utf-8 -*- import urllib2, simplejson, urllib BASE_URL = "http://app.tsogu.ru/shedule_new/bin/groups.py" def get_group_code(gname): gname = urllib2.quote(gname.encode('utf-8')) r = urllib2.urlopen("%s?act=groupcode&groupname=%s"%(BASE_URL, gname)).read() return simplejson.loads(r) def get_timetable(gc...
"""Abstract Task class.""" import abc from typing import Any class Task(abc.ABC): """ Abstract Task class. A task is one of a list of independent execution tasks that are submitted to the execution engine to be executed using the execute() method, commonly in parallel. """ def __init__(s...
""" This script makes a short version of a typical data file exported from ultravision. Note that the resulting file has been manually edited to fix the # of scan and index points in the headers... """ from packages import utils import pandas as pd from os.path import join from pandas.io.common import EmptyDataError N...
from controllers.historyController import HistoryController import sys import logging if __name__ == "__main__": log = logging.getLogger("log") log.addHandler(logging.FileHandler("log.log", "a")) log.setLevel(logging.DEBUG) history = HistoryController(log) if len(sys.argv) == 2 and sys.argv[1] ==...
import jieba import csv txt = open("all_out.txt", "r").read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) == 1: #排除单个字符的分词结果 continue else: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(1000...
from django.contrib import admin from .models import Organization, Moderator, Subscription, Event, EvalForm admin.site.register(Organization) admin.site.register(Moderator) admin.site.register(Subscription) admin.site.register(Event) admin.site.register(EvalForm)
import random Symbol = 'QWERTYUIOPASDFGHJKLZXCVBNMqwerty()uiopasdfghjklzxcvbnm123456789!@#$%^&*' print(''' ______________ Password Maker ______________''') Chars_Password = int(input('How many passwords do you need?')) Chars_Count = int(input('How many characters in your password?')) print('This is Your Passwor...
from setuptools import find_packages, setup VERSION = "0.0.0" REQUIRED_PACKAGES = [] with open("requirements.txt", "r") as reqs_txt_file: REQUIRED_PACKAGES = [line.strip() for line in reqs_txt_file] REQUIRED_DEV_PACKAGES = [] with open("requirements-dev.txt", "r") as reqs_dev_txt_file: REQUIRED_DEV_PACKAGES ...
# Mobin Anandwala # 04/24/2017 # This is a conversion to read data from the data port using Python 3.6 import http.client import urllib.parse # Exosite Information Exosite_Server = 'm2.exosite.com' Exosite_URL = '/api:v1/stack/alias' Exosite_CIK = 'f7302c574a9cb0a195100ddbe3ca98cf80d08634' Exosite_Header =...
num = int(input('Enter n value : ')) print('The prime numbers are : ') for i in range(2,num+1): for j in range(2,int((i/2)+1)): if i%j == 0: break else: print(i)
import FWCore.ParameterSet.Config as cms from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCAL_noise_fC as _HGCAL_noise_fC HGCAL_noise_fC = _HGCAL_noise_fC.clone()
""" Author: LRP Date: 13-03-2015 """ import contfit # from degradespec import degrader import bestfit import numpy as np # This is supposed to be the only function to call! # Then this function calls everything from it def rsgjanal(ospec, owave, ores, mspec, quiet=True): """ Trimmed spectra, nothi...
from django import forms class RecipeForm(forms.Form): recipe = forms.CharField(label='recipe_name', max_length=100) amount_cal = forms.CharField('amount_cal', max_length=10) time = forms.DecimalField(min(0)) ingredients = forms.TextInput() def __unicode__(self): return self.recipe
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostbyname(socket.gethostname()) port = 8883 s.connect((host, port)) #msg2 = (s.recv(1024)).decode("utf-8") with open('sample.txt', 'w') as f: while True: print('receiving data...') data = s.recv(1024).decode('ascii') pri...
## 329. Longest Increasing Path in a Matrix # # Given an integer matrix, find the length of the longest increasing path. # # From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). # # Example 1: # ...
# -*- coding: utf-8 -*- """ Google Earth file output example required simplekml module. if you didn't install simplekml, execute the following command. > pip install simplekml """ from OpenVerne import IIP import numpy as np import pandas as pd import simplekml import warnings warnings.filterwarnings('ignore') if __...
from typing import List from hummingbot.client.config.config_helpers import ClientConfigAdapter, get_connector_class from hummingbot.client.settings import AllConnectorSettings from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import PaperTradeExchange from hummingbot.core.data_type.order_book_tracke...
from typing import Tuple, Any from jax import numpy as jnp, random from flax import linen as nn from survae.distributions import Distribution from survae.utils import * from functools import partial from jax.scipy.stats import norm import ipdb class StandardNormal(nn.Module, Distribution): @classmethod def l...
name= input ("What is your name?") day= input("what day is today?") print("Hello, " + name + "! Happy " + day + "!") print("Hello, {}! Happy {}!".format(name,day))
#!/usr/bin/env python import sys,os,getopt,urllib,httplib,time try: import json except ImportError: import simplejson as json #DBS-3 imports from dbs.apis.dbsClient import * from sso_auth import Login OUTPUT='/afs/cern.ch/user/m/mtaze/TransferTeam/deletion_campaign/out/' # arguments datasetRegexList=None tr...
import numpy as np import matplotlib.pyplot as plt import os from keras_utils import save_step_prediction try: import tensorflow as tf from tensorflow.keras.models import Sequential, load_model, Model from tensorflow.keras.layers import Input, Add, Flatten, Conv2D, MaxPooling2D, Activation, Dropout, Dense,\...
import os from flask import ( Flask, flash, render_template, redirect, request, session, url_for) from flask_pymongo import PyMongo from bson.objectid import ObjectId from slugify import slugify from werkzeug.security import generate_password_hash, check_password_hash if os.path.exists("env.py"): import env...
# -*- coding: utf-8 -*- ''' Self-Balancing Binary Search Trees Height = max(LeftSubTreeHeight, RightSubTreeHeight) + 1 Balanced = LeftSubTreeBalance - RightSubTreeBalance abs(Balance) <= 1 - tree is balanced Balance < 0 - tree is left heavy Balance >= 2 - tree is right heavy https://www.youtube.com/watch?v=vRwi_Uc...