text
stringlengths
38
1.54M
import torch from torch import nn import torch.nn.functional as F import torch.nn.modules.utils as module_utils import time import random class PerturbedModel: def __init__(self, model, directions): self.model = model self.directions = directions self.perturbed_layers = [] def ge...
"""is_visible and is_required for Action model Revision ID: 14b482ad5574 Revises: 333833cebe88 Create Date: 2015-01-22 12:24:56.428785 """ # revision identifiers, used by Alembic. revision = '14b482ad5574' down_revision = '333833cebe88' from alembic import op import sqlalchemy as sa def upgrade(): ### command...
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # # 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 appli...
a=raw_input("Enter any year...\n") a=int(a) if a%4==0: print "This ia a leap year" elif a%4!=0: print "This ia not a leap year" else: print "Try again"
def classify_orfs_cmd(): # This function will parse cmd input with argparse and run classify_orfs pass def classify_orfs(): pass
from django import forms from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import filesizeformat from django.conf import settings class ImpactClassForm(forms.Form): impact_class_file = forms.FileField( label="", help_text="Must be a .csv file.", ) ...
#!/usr/bin/env python3 """ diff -u neophyte1.jav neophyte2.jav --- neophyte1.jav 2016-08-05 19:09:09.935916641 -0700 +++ neophyte2.jav 2016-08-05 19:39:34.523799711 -0700 @@ -163,12 +163,12 @@ vulnerable: 804852f: PUSH EBP 8048530: MOV EBP, ESP ; EBP = ESP; - 8048532: SUB ESP, 0x3db8 ; ESP -= 0x3db8;...
import numpy as np import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt from copy import deepcopy # Reading csv dataset as it does not have header, and separated by names wine = pd.read_csv("wine.data", names = ["Class", "Alcohol", ...
import io import os import ast import functools import re import sys import textwrap from tempfile import NamedTemporaryFile from typing import Callable, Dict, List, Tuple, Union try: from argparse_dataclass import dataclass as ap_dataclass from argparse_dataclass import ArgumentParser except: ArgumentPar...
import json # Read parameter file with open('service/parameters.json', 'r') as f: parameters = json.load(f) # Tolerance is equals to 1 - similarity threshold parameters['tolerance'] = 1 - float(parameters['sim_threshold']) parameters['FEATURE_DIMENSION'] = 128
# -*- coding: utf-8 -*- from datetime import datetime from pathlib import Path from typing import List, Any from PyQt5.QtWidgets import QFormLayout, QLineEdit, QDateTimeEdit, QWidget from PyQt5.QtWidgets import QDialog from dgp.core.oid import OID from dgp.core.controllers.controller_interfaces import IAirborneContro...
from django.contrib import admin from Home.models import Workers, Employer # Register your models here. admin.site.register(Workers) admin.site.register(Employer)
# _*_ coding:utf-8 _*_ from __future__ import unicode_literals from django.apps import AppConfig class CompanysConfig(AppConfig): name = 'companys' verbose_name = u'ไผไธš'
import numpy as np class Distribution(object): ''' Base class for distribution. Useful for estimating and sampling initial state distributions ''' def fit(data): raise NotImplementedError def sample(self, n_samples=1): raise NotImplementedError @property def d...
""" este eh um client, para funcionar deve rodar: python api-server-get.py runserver [enter] """ import requests endpoint = "http://127.0.0.1:5000" rq = requests.get(endpoint) print("status-code:") print(rq.status_code) print("headers:") print(rq.headers['content-type']) print("text:") print(rq.text) print("json:") ...
""" Keep subpath handling consistent. As files should not be written outside of CWD, this is a security issue. Paths may be provided as absolute or relative, and they may be manipulated inside the storage files. So the check should happen every time a path is actually used. """ import os import pathlib from typing imp...
import random def randint(a,b): return random.randint(a,b) def dmg(STR,DEF): value = random.randint(80,120) dmg = ((value*STR) - (DEF*50))/100 if dmg <= 0: dmg = 0 return dmg
#Brute Force Apporach for Maximum Subarray def maxSubOn3(arr): maximum=0 for i in range(n): for j in range(i,n): subsum=0 for k in range(i,j): subsum+=arr[k]; maximum=max(subsum,maximum) return maximum def maxSubOn2(arr): maximum=0 for i ...
from Character import Character from Sprite import AnimatedSprite from Text import Text from Player import HPDisplay import random, pygame class Spiderboss(Character): def __init__(self, level): Character.__init__(self, "spiderboss", level) self.laser = Laser(self, level.get_camera()) self...
import discord from configs.configs import Configs PREFIX = Configs.prefijoBot COMANDO_ADD = Configs.comandoAdd COMANDO_REMOVE = Configs.comandoRemove COMANDO_NEXT = Configs.comandoNext COMANDO_DELETE = Configs.comandoDelete COMANDO_LIST = Configs.comandoList COMANDO_ALL = Configs.comandoAll COMANDO_CREATE = Configs....
from pymongo import MongoClient import pymongo class DBConnection: connection = MongoClient() db = connection['local'] def getLastMsgId(self): collection = self.db['discord_message_lookup'] res = collection.find_one() return res def addNewMsg(self, msg_dict): colle...
def strDiag (strInput): for i in range(len(strInput)): print(' '*i, strInput[i]) stringInput = input("Enter string: ") strDiag(stringInput)
import tensorflow as tf # demo1 a = tf.constant(3, name='a') with tf.Session() as sess: print(sess.run(a)) # demo2 a = tf.constant(3, name='a') b = tf.constant(4, name='b') add_op = a + b with tf.Session() as sess: print(sess.run(add_op)) # demo3 a = tf.constant([1, 2, 3], name='a') b = tf.constant([4, 5, ...
""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Constraints: 1 <= nums.length <= 3 * 104 -105 <= nums[i] <= 105 Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and co...
#You are to write program to convert degrees of Fahrenheit to Celsius. print("What is the temperature in Fahrenheit?) Fahrenheit = input ("") print((float(Fahrenheit)-32)/1.8)
import os def load_config(): mode = os.environ.get('FLASK_ENV', 'default') if mode == 'production': from config.production import ProductionConfig return ProductionConfig elif mode == 'development': from config.development import DevelopmentConfig return DevelopmentConfig ...
#### Imports #### import sys, os, argparse ######################################################################################################################################################## #### arguments #### def arguments(arg): parser = argparse.ArgumentParser() parser.add_argument("-d","--directory",dest=...
import pygame import ctypes # for pop-up window from random import shuffle, randint # for shuffling and generating random iterger from pprint import pprint # to print girid in terminal from 1-D array to 2-D array sudokuGrid = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], ...
from com.ml.objects.Detection import ObjectDetection from com.ml.utils.distance import Distance import numpy as np import os import cv2 # initialize the known distance from the camera to the object, which # in this case is 24 inches KNOWN_DISTANCE = 24.0 # initialize the known object width, which in this case, the ...
from linear import matrix import latex import robotics from sympy import symbols import math def insert(A,t): temp = A.copy() for i in range(A.n): for j in range(A.m): temp[i][j] = A[i][j].subs('t', t) return temp def solveABC(A, b): q = [] for i in range(len(b)): temp ...
#!/usr/bin/python3 import zmq import numpy as np port = 8887 context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://127.0.0.1:%s"%port) #raspberry pi ip address topicfilter=b"" socket.setsockopt(zmq.SUBSCRIBE,topicfilter) while True: string = socket.recv() #print string data = np.fromst...
# Generated by Django 2.1.7 on 2019-03-30 11:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notification', '0004_auto_20190330_1439'), ] operations = [ migrations.AddField( model_name='globalnotification', ...
# school = "Digital School" # print("Digital Crafts") # print("Digital Crafts") # print("Digital Crafts") # print("Digital Crafts") # print("Digital Crafts") # student1 = "Andrea" # student2 = "Zach" # student3 = "Michael" # student4 = "Rick" # "Good Morning" # formatting = "{} {} {} {}".format(student1, student2,...
import cv2 import numpy as np import json import re import pandas as pd import sys import glob import os import cv2 import numpy as np import json import re import pandas as pd import sys import glob import os import csv #IMAGE AND CSV FILE LOCATIONS THIS CODE ASSUMES THEY ARE IN THE SAME FOLDER json_fns = glob.glob...
# Generated by Django 3.1.7 on 2021-02-22 11:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0012_order_total'), ] operations = [ migrations.AlterField( model_name='order', name='total', f...
# Generated by Django 3.1.3 on 2020-12-12 17:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rareserverapi', '0003_auto_20201211_0140'), ] operations = [ migrations.CreateModel( name='Comm...
from utils import regex_utils from utils.log_utils import log class InsertProcessor: def __init__(self, broker, client_model, global_model): self.broker = broker self.client_model = client_model self.global_model = global_model self.log = log def _is_client_regex(self, payload...
class Solution(object): # DFS is O(2^n) # with backtracking, DFS is O(n!)~O(2^n) # DFS solution can only handle small cases(i.e.target<=25 && len(nums)<=5), due to large list memory usage of res. def combinationSum4(self, nums, target): """ :type nums: List[int] :type target: in...
from datetime import date from MEME import lista from pymongo import MongoClient fecha = date.today() mongo_data = {fecha: lista} client = MongoClient('localhost', 27017) db = client['Google_Trends'] tendencias = db[str(fecha)] tendencia = {'Top 25': lista} insertado = tendencias.insert_one(tendenc...
#!/usr/bin/env python import rospy import serial from jsk_mbzirc_board.srv import * from std_msgs.msg import Int16 class Serial_board: def __init__(self): self.T_HEADER = 'TH' self.T_TAIL = 'TT' self.Magdata = 'mag:!' self.port = '/dev/ttyTHS2' self.baud = 115200 se...
import csv import sys days = {} countlines = {} with open(sys.argv[1]) as csvfile: carsin = csv.reader(csvfile, delimiter=',') for row in carsin: countline = row[0] year = row[1] month = row[2] day = row[3] count = row[4] date = year+month+day if coun...
mqtt = { 'username': 'YourUsername', 'password': 'YourPassword', 'ip': '192.168.#.##', 'port': 1883, 'timeout': 60, 'topic' :{ 'subscribe': { 'topic_key': 'topic' }, 'publish': { 'publish_key': 'topic' } } }
""" The event module provides a system for properties and events, to let different components of an application react to each-other and to user input. In short: * The :class:`Component <flexx.event.Component>` class provides a base class which can be subclassed to create the different components of an app. * Each c...
import copy import csv import json import os from os.path import join import time from datetime import datetime from subprocess import check_output, Popen from time import sleep from mycroft import MycroftSkill, intent_file_handler from mycroft.api import DeviceApi from mycroft.configuration import Configuration from m...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-11 15:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crawl', '0002_auto_20170710_1514'), ] operations = [ migrations.CreateModel...
import tensorflow as tf #NewCheckpointReaderๅฏไปฅ่ฏปๅ–checkpointๆ–‡ไปถไธญไฟๅญ˜็š„ๆ‰€ๆœ‰ๅ˜้‡ #ๅŽ้ข็š„.indexๅ’Œ.dataๅฏไปฅ็œๅŽป reader = tf.train.NewCheckpointReader("model_saved/model.ckpt") #่Žทๅพ—ๅ˜้‡ๅ-ๅ˜้‡็ปดๅบฆ็š„ๅญ—ๅ…ธ global_variables = reader.get_variable_to_shape_map() for variable_name in global_variables: print(variable_name, global_variables[variable_name]...
from .event import Event from .exclusionregion import ExclusionRegion __all__ = (Event, ExclusionRegion)
from random import randint # When the bot receives a compliment def compliment(): message = [ 'Thank you so much!', 'Oh, you\'re too kind', 'This is why you\'re my favorite!' ] return chooseResponse(message) def giveCompliment(): message = [ 'Your smile is contagious.', 'I bet ...
""" here there are 23 exercises which is based on topics asarray(),linspace(),logspace(),basic slicing """ #!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # In[2]: #np.empty-creates uninitialized array of specified shape and dtype #np.empty(shape, dtype, order) arr1 = np.empty([2,3], dtype = i...
# coding: utf8 from django.db import models from django.contrib.auth.models import User, PermissionsMixin from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth import get_user_model # Create your models here. from django.db.models import Model from django.db.models.signals import pre_save,pos...
import os import hmac import hashlib from urllib import urlencode as _urlencode import base64 from enums.exchange import EXCHANGE from utils.exchange_utils import get_exchange_name_by_id access_keys = {} class ExchangeKey(object): def __init__(self, api_key, secret): self.api_key = api_key self....
from calculator import Calculator import unittest class TestCalculator(unittest.TestCase): # test 1 def test_calculator_add(self): result = Calculator().add(5.0,5) self.assertEqual(10.0, result) result = Calculator().add(2.0,3) self.assertEqual(5.0, result) # test 2 ...
def giveDiv(n): retar=[] for i in range(1,n//2+2): if n%i==0: retar.append(i) if retar[-1]!=n: retar.append(n) return retar n=int(input()) divar=giveDiv(n) #print(divar) s=input() for i in divar: retain=s[i:] reverse=s[:i] reverse=reverse[::-1] s=reverse+retain print(s)
from sklearn import datasets import numpy as np def get(): diabetes = datasets.load_diabetes() features = diabetes.data labels = diabetes.target return {'features': features, 'labels': labels.reshape(-1, 1)}
import os import json import re import glob ttl_files = glob.glob('src/*.ttl'); terms = {} for ttl_file in ttl_files: if not re.search('realm', ttl_file) and not re.search('phen', ttl_file): continue print(ttl_file) category = None with open(ttl_file) as origin_file: for line in origin_file: #li...
from django.urls import path from . import views urlpatterns = [ path('get_cards/', views.get_cards, name='get_cards'), path('add_cards/', views.add_cards, name='add_cards'), # path('search_cards/', views.search_cards, name='search_cards'), path('load_users/', views.load_users, name='load_users'), ]
import cv2 import numpy as np from matplotlib import pyplot as plt from src.utils.const import KEYPOINT_PAIRS BLUE_COLOR = (0, 0, 255) ORANGE_COLOR = (255, 140, 0) GREEN_COLOR = (0, 188, 0) def draw_bbox( bboxes: np.ndarray, image: np.ndarray, format='xyxy', ) -> np.ndarray: """Draw...
from django.shortcuts import render # Create your views here. def attandance(request): return render(request,"attandance/attandace_html.html")
''' Created on Nov 26, 2017 @author: ray ''' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
from django.shortcuts import render , redirect from .models import * from django.shortcuts import get_object_or_404 from .forms import PostForm ,UserSignUp ,UserLogin from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from urllib.parse import quote from django.h...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 1 19:20:21 2018 @author: Alicia """ def remove_min_from_list(mylist): if mylist: mylist.remove(min(mylist)) return mylist print(remove_min_from_list([2,1,34,23,2]))
# -*- coding: utf-8 -*- """ """ try: from collections.abc import Mapping as MappingABC except ImportError: from collections import Mapping as MappingABC from ..utilities.future_from_2 import str, object, repr_compat, unicode from ..utilities.unique import NOARG from .deep_bunch import DeepBunch class TagBunc...
import pypyodbc sql_server_conn_str = 'Driver={SQL Server Native Client 11.0};Server=172.16.3.65;Database=ArgaamPlus;Uid=argaamplususer;Pwd=argplus123$;' # sql_server_conn_str = 'Driver={SQL Server Native Client 11.0};Server=172.16.3.51;Database=argaam_analytics;Uid=argplus_user;Pwd=argplus123$;' conn = pypyodbc.conn...
#Implement a program to find the euclidean distance of two points. x1=int(input("enter x1")) y1=int(input("enter y1")) x2=int(input("enter x2")) y2=int(input("enter y2")) eq=(x2-x1)**2 eq1=(y2-y1)**2 result=(eq+eq1)**0.5 print("the euclidean distance is",result)
# ํŒ€ ๊ฒฐ์„ฑ. # ํ•™๊ต์—์„œ 0~N ๊นŒ์ง€์˜ ๋ฒˆํ˜ธ๋ฅผ ๋ถ€์—ฌํ–ˆ๋‹ค. # ํŒ€ ํ•ฉ์น˜๊ธฐ ์—ฐ์‚ฐ -> ๋‘ ํŒ€์„ ํ•ฉ์น˜๋Š” ์—ฐ์‚ฐ. # ๊ฐ™์€ ํŒ€ ์—ฌ๋ถ€ ํ™•์ธ ์—ฐ์‚ฐ ๋‘ ํ•™์ƒ์ด ๊ฐ™์€ ํŒ€์— ์†ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ์—ฐ์‚ฐ.abs # ์ด ๋ฌธ์ œ ์•„๊นŒ ๊ณ„์† ํ–ˆ๋˜ ์„œ๋กœ์†Œ ๋ฌธ์ œ๋‹ค. # N์€ ๋ฒˆํ˜ธ M์€ ์—ฐ์‚ฐ์˜ ๊ฐœ์ˆ˜ # 0 a b ๋Š” ํŒ€ ํ•ฉ์น˜๊ธฐ ์—ฐ์‚ฐ # 0 a b๋Š” ๊ฐ™์€ ํŒ€ ์—ฌ๋ถ€ ํ™•์ธ ์—ฐ์‚ฐ def find_parent(parent, x):#๋ถ€๋ชจ ๋…ธ๋“œ๋ฅผ ์ฐพ๋Š”๊ฑฐ ๋ถ€๋ชจ๋Š” ๋…ธ๋“œ๋Š” ์ž์‹๋…ธ๋“œ๋ณด๋‹ค ๋ฌด์กฐ๊ฑด ํผ. if parent[x]!=x: parent[x] = find_parent(parent, parent[x]) ...
# standard lib import sys from pdb import set_trace # 3rdparty lib from PySide2.QtWidgets import QApplication, QDialog # custom lib from ui_AddFoodItem import Ui_Dialog class MainWindow(QDialog): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(...
import re, logging from pyfiles import jsonChecker, playerController, characterController from pyfiles.db.attributes import ATTRIBUTE_NAMES def split_words(text : str) -> list: """ Breaks up a command input such as 'hello foo bar' into individual words""" command_text = text.strip() commands = command_text...
# encoding: utf-8 import sys import random from lib import keystreams def error(message): print message print "Usage: python echocrypt.py [e|d] \"message\" [keystream name]" exit(1) mode = sys.argv[1] if mode == 'e': # If the keystream to use is specified, use that one; otherwise, use a random one in the diction...
from gym.wrappers.rescale_action import RescaleAction from rltk.common.utils import import_class_from_string from gym.spaces.box import Box import gym def make_env(name: str, loader: str = "gym", **kwargs): rescale_action = kwargs.get('rescale_action', True) env = None if loader == "gym": # Base Wrapp...
# Databricks notebook source # MAGIC %md # MAGIC # Linear Regression Consulting Project # COMMAND ---------- # MAGIC %md # MAGIC Congratulations! You've been contracted by Hyundai Heavy Industries to help them build a predictive model for some ships. [Hyundai Heavy Industries](http://www.hyundai.eu/en) is one of the ...
# this program calculates the total number of times each word has been tweeted. import sys #get file path from command line argument in python infile=open(sys.argv[1],"r+") outfile=open(sys.argv[2],"w") #dictionary containing key (tweeted word) and value (total number of times each tweeted word) word_count = {} fo...
from django.db import models class ContactMessage(models.Model): title = models.CharField(max_length=100) email = models.CharField(max_length=100) detail = models.TextField(blank=True,null=True) reply = models.BooleanField(detail=False) def __str__(self): return self.title
import random import itertools import csv import os.path from timeit import default_timer as timer from Point import Point from Tour import Tour #<editor-fold desc = "Nearest Neighbor"> def doNearestNeighbor(points): start = timer() tour = nearestNeighbor(points) end = timer() print 'Nea...
# Python import unittest from copy import deepcopy from unittest.mock import Mock # ATS from pyats.topology import Device # Genie from genie.libs.ops.interface.iosxr.interface import Interface from genie.libs.ops.interface.iosxr.tests.interface_output import InterfaceOutput # nxos show_interface from genie.libs.pars...
import csv import numpy import logging import json def is_number(input): """ Check if the input is a floating point number and if the input is a real number :param input: value :return: Boolean of whether or not the value passes """ try: float(input) if numpy.isreal(float(i...
import requests import billboard_miner api_token = "Bearer BQB7Ojx2hlfuMpAJkVExFA5hdcfv1MR1k_jp7qUE_Np142Y40k-j-Ed8Cs7eeNKIp0bU0t7BzoxrqSYsoYNGqtVXE06bgW2VjHyEy5VGvKk6pN1n5kN8wzgRb7zoSLJuo3gOHn-rALAMayM-vPg" def getSongIds(song_list): base_url = "https://api.spotify.com/v1/search" headers = {"Authorization": a...
import numpy as np from bokeh.io import curdoc from bokeh.layouts import Row, WidgetBox from bokeh.models import ColumnDataSource from bokeh.models.widgets import Slider, RadioButtonGroup, Toggle from bokeh.plotting import Figure """ This plot visualizes how waves propagate by simulating the right-going and left-goin...
from collections import Counter from typing import List class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: punctuation = "!?',;." cleansed = ''.join([' ' if t in punctuation else t for t in paragraph]) cleansed_counts = Counter(cleansed.lower().split()).mos...
import webbrowser import time time_control = 0 time_total = 3 print('Current Time: '+time.ctime()) while(time_control < time_total): time.sleep(5) webbrowser.open("http://www.baidu.com") time_control += 1
# coding: utf-8 # ---------------------------------------------------------------------------- # <copyright company="Aspose" file="AsnEncodedData.py"> # Copyright (c) 2018-2019 Aspose Pty Ltd. All rights reserved. # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtain...
n=int(input()) a=[] for i in range(n): a.append(int(input())) v=min(a) b=[] for j in range(2,v+1): flag=0 for g in a: if(g%j!=0): flag=1 break if(flag==0): b.append(j) print(len(b))
# -*- coding: utf-8 -*- from qtgraph_editor import QTGraphWidgetEditor from traits.api import HasTraits, Int, Str, Instance, Dict, Array from traitsui.api import Item, View, EnumEditor, HGroup, Label from instruments.i_instrument import IInstrument import pyqtgraph as pg import numpy as np import logging logg...
import time from fake_useragent import UserAgent from retrying import retry import requests from lxml import etree from pymongo import MongoClient #้€š็”จ็ˆฌ่™ซๅŠŸ่ƒฝ class Common_Spider(object): #่Žทๅ–้šๆœบUAๅคด็š„ๆŽฅๅฃ @staticmethod def get_random_ua(): ua = UserAgent() agent = ua.random return agent ...
class GlobalVars(dict): def __new__(cls, *args, **kwargs): try: return cls.__instance except AttributeError: cls.__instance = super().__new__(cls, *args, **kwargs) cls.__instance.need_init = True return cls.__instance def __init__(self, *...
from urllib import request,parse import ssl # ssl._create_default_https_context = ssl._create_unverified_context url = "https://www.12306.cn/mormhweb" rsp = request.urlopen(url) html = rsp.read().decode() print(html)
# Generated by Django 3.1.1 on 2020-10-12 04:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0002_auto_20201012_0018'), ] operations = [ migrations.AlterField( model_name='qapair', name='question', ...
from .models import * from rest_framework import serializers # from django.db import models class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username','first_name','last_name','email'] class TeacherSerializer(serializers.ModelSerializer): # teacher_name=UserSerializer(rea...
# -*- coding: utf-8 -*- import re, sys import pywrapfst, pynini from pywrapfst import Fst sys.path.append('../../fst') from fst import fst_config, fst from fst.fst import FST, Transition epsilon = 'ฮต' marker = 'โ€ข' wildcard = 'โ–ก' segments = ['t', 'r', 'i', 's', 'u', 'm'] stem_str = '>โ€ข t rโ€ข i s t iโ€ข <' stem = fst.li...
from django.test import Client from django.urls import reverse import unittest client = Client() class TestResizeURLs(unittest.TestCase): def test_index(self): response = client.get('/') self.assertEqual(response.status_code, 200) if __name__ == '__main__': unittest.main()
import zipfile import numpy as np def extract_bits(filename): if zipfile.is_zipfile(filename): zp = zipfile.ZipFile(filename) raw_buffer = zp.read(zp.filelist[0]) bytes = np.frombuffer(raw_buffer, dtype=np.uint8) else: bytes = np.fromfile(filename, dtype=np.uint8) return np....
from multiprocessing import Pool from CellStoch import * def f(mode): m=sinIR_full() m.min_gr=0.25 resume=False m.sim_cell_lines(setting='dc',mode="n100",minimal_time_interval=0.1,max_time=30,num_of_lines=500,resume=resume,save_name='dc_fix_t6') if __name__ == '__main__': with Pool...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from SellBuy.models import CurrentUserHolding, UserShareQuantity from django.shortcuts import render from LoginRegister.models import UserDetail from django.http import JsonResponse from Helpers.utils import get_or_none from django.contrib.auth.models impo...
from tkinter import * from Point import * class Rectanguloid: def __init__(self, p1, p2): window = Tk() window.title("Rectanguloid") changeX = 25 changeY = 40 canvas = Canvas(window, width = 200, height = 250, bg = "white") canvas.pack() canvas.create_rect...
from utils import regex_utils class WhitelistMatcher: def __init__(self, model): self.model = model def get_match(self, **args) -> str: whitelist = self.model.get_whitelist(args) for whitelist_item in whitelist: if regex_utils.is_match_regex(whitelist_item.regex, args['...
import string import math import re import seq def calcscore(inscore,k,newSD): return (inscore*k + newSD)/(k+1) def sequenceOkay(strg, search=re.compile('[^aAcCgGtT]').search): """Return true if all characters are valid [aAcCgGtT] in sequence.""" return not bool(search(strg)) def TmScore(sequenc...
# Generated by Django 3.2.13 on 2022-06-28 17:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contacts_app', '0002_alter_person_unique_together'), ] operations = [ migrations.AlterModelOptions( name='person', options=...
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2018-12-27 12:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('edtech', '0003_auto_20181226_2043'), ] operations = [ migrations.AddField(...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Standard library packages. import re import sys from itertools import izip # Others. import seeq from gzopen import gzopen def trimSuffix(matcher, txt): return matcher.matchPrefix(txt, False) or '' ######## Mapping Pipeline #######################################...
# 01234567890123 parrot = "Norwegian Blue" print(parrot) print(parrot[3]) print(parrot[4]) print(parrot[9]) print(parrot[3]) print(parrot[6]) print(parrot[8]) print(parrot[-5]) print(parrot[-11]) print(parrot[-10]) print(parrot[-5]) print(parrot[-11]) print(parrot[-8]) print(parrot[-6]) ...
import metaphone def plausibleWords(incorrectWord): USengDict = open("enUS.txt","r") GBengDict = open("enGB.txt","r") phoneticDictUS = open("metaphonicDictUS.txt","r") phoneticDictGB = open("metaphonicDictGB.txt","r") temp = (metaphone.dm(incorrectWord))[0] plausibleList = [] plausibleListTemp = ...