text
stringlengths
38
1.54M
from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework_extensions.mixins import NestedViewSetMixin from surveys.serialisers.user_serialiser import UserSerialiser, GroupSerialiser class UserViewSet(NestedViewSetMixin, viewsets.Model...
import sys sys.path.append('C:\\Users\\rucku\\Desktop\\Coding Projects') print(sys.path) import my_plotly_code
for t in range(50): for i in range(t-1, max(-1, t-5-1), -1): print(i) print("BREAK\n")
import csv import time from datetime import datetime from prettytable import PrettyTable from .api import countries, country, totals, us_states def to_csv(data): fieldnames = set() for event in data: fieldnames |= event.keys() with open("%s.csv" % int(time.time()), "w", newline="") as c: ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2018-02-20 13:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("message_sender", "0016_outbound_resend")] operations = [ migrations.AlterField( ...
import torch import os from FLAlgorithms.users.useravg import UserAVG from FLAlgorithms.cluster.clusterbase import Cluster import numpy as np from logging_results import eps_logging class ClusterFedAvg(Cluster): def __init__(self, device, args, train_loader, test_loader, model, train_data_samples, cluster_total_...
import AppKit from PyObjCTools.TestSupport import TestCase, min_os_level class TestNSDraggingItem(TestCase): def test_typed_enum(self): self.assertIsTypedEnum(AppKit.NSDraggingImageComponentKey, str) @min_os_level("10.7") def testConstants10_7(self): self.assertIsInstance(AppKit.NSDraggin...
# create function, that returns number of vowels in string (includes a,e,i,o,u or A,E,I,O,U) # create function, that removes spaces (cannot use .replace method or any string method) def get_string(): word = input("what is the word?") return word def num_vowels(s): new = '' for character i...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @Created on 2020-05-24 11:28 @File:Policy_iteration.py @Author:Zhuoli Yin @Contact: yin195@purdue.edu ''' import numpy as np import gym """ Run agent in a deterministic environment, which could provide: (1) number of state (2) number of action (3) probabili...
from intcode_computer import IntcodeComputer def part1(): with open("input", "r") as data: text = data.read() comp = IntcodeComputer(text) print(comp.run_program([1])) def part2(): with open("input", "r") as data: text = data.read() comp = IntcodeComputer(text) ...
import json import os.path from typing import Dict from django.conf import settings import requests from api.lib import tmp_lib, script_logger, environment WORD_OF_THE_DAY_API_URL = "https://api.wordnik.com/v4/words.json/wordOfTheDay" CACHE_FILE_NAME = "wotd.json" if environment.is_testing(): CACHE_FILE_NAME =...
def openFile(filename): with open(filename) as infile: array = [] for line in infile.readlines(): array.append(int(line)) array = list(set(array)) return array def binsearch(array, num): i = 0 j = len(array) - 1 while i != j: mid = (i + j) // 2 ...
#!/usr/bin/env python import time import scipy import sys import numpy as np import openravepy from openravepy import * from math import * from environment_force_the_stream import * from environment_force_the_counterstream import * from environment_force_the_ray import * from environment_force_blood_stream import * fro...
import sys import os from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager from pathlib import Path store_address = 'http://' + str(sys.argv[1]) user_home = str(Path.home()).split('\\')[-1] _login = os.envir...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-02-15 08:36 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations...
c_bob = 0 for z in range(0,len(s)): if(s[z:z+3] == 'bob'): c_bob += 1 print("Number of times bob occurs is",c_bob)
import functools import logging import torch import torch.nn as nn from torch.nn import init import models.modules.architecture as arch logger = logging.getLogger('base') #################### # initialize #################### def weights_init_normal(m, std=0.02): classname = m.__class__.__name__ if classname...
from django.contrib import admin from .models import AppletRelated @admin.register(AppletRelated) class AppletRelatedAdmin(admin.ModelAdmin): list_display = ('versionNumber', 'updateTime')
# -*- coding: utf-8 -*- # # Author: Alberto Planas <aplanas@suse.com> # # Copyright 2019 SUSE LLC. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
from confy import database, env import os import sys from unipath import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).ancestor(2) PROJECT_DIR = os.path.join(BASE_DIR, 'itassets') # Add PROJECT_DIR to the system path. sys.path.insert(0, PROJECT_DIR) # Settings ...
#!/usr/bin/env python '''This script gets a list of PVS that are disconnected and then pauses those that have not connected for a specified amount of time''' import os import sys import argparse import json import datetime import requests import logging import multiplePVCheck from utils import configureLogging logge...
"""Calculate time mean statistics using data_analysis.TimeDomStats.""" import iris import iris.quickplot as qplt import matplotlib.pyplot as plt import data_analysis as da BASEDIR='/gpfs/afm/matthews/data/' #VAR_NAME='vwnd'; LEVEL=850; SOURCE='erainterim_plev_6h'#; TDOMAINID='jan7912' VAR_NAME='swpd'; LEVEL='all'; ...
import sys, os, glob, getpass #sys.path.append('/mnt/lustre/eboss/genericio/python/') #sys.path.append('../tools') import genericio as gio import numpy as np ############################# # # Input ARGUMENTS ...
from testSettings import * ########################### # Чтение файла в текст ########################## def readText(fileName, encod): f = open(fileName, 'r', encoding=encod) text = f.read() text = text.replace("\n", " ") text = text.replace("\t", " ") text = text.replace("•", " ") text = tex...
from die import Dice class Roller: def __init__(self, num_dice, dice_sides): self.num_dice = num_dice self.dice_sides = dice_sides self.dice = [] self.values = [] for _ in range(self.num_dice): self.dice.append(Dice(dice_sides)) def roll(self): for...
from django.urls import path from . import views urlpatterns = [ path('get_streamers', views.GetStreamers.as_view()), path('get_streamer', views.GetStreamer.as_view()), path('get_faq', views.GetFaq.as_view()), path('get_how_to', views.GetHowTo.as_view()), path('get_tickets', views.GetTickets.as_vie...
# Generated by Django 2.2 on 2018-06-28 03:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TestModel', '0001_initial'), ] operations = [ migrations.AddField( model_name='userinformation', name='createTime', ...
import sys mem = [0] mem_pointer = 0 input_index = 0 prog_output = "" def mem_inc(): global mem, mem_pointer if mem_pointer < 0: print("mem_pointer < 0 when incrementing") sys.exit(2) mem[mem_pointer] += 1 if mem[mem_pointer] > 255: mem[mem_pointer] = 0 def mem_dec(): glo...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : LinkedListCycle.py @Contact : 70904372cecilia@gmail.com @License : (C)Copyright 2019-2020 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/12/16 16:08 cecilia 1.0 判断链表是否存在环...
#!/usr/bin/python import vulners scandatafile = open("CVEnumbers.txt","r+") f = open("CVEdescriptions.txt", "w+") vulners_api = vulners.Vulners(api_key="LKTS0IPVW1HU9XA3EENOEDDJEKOS6VACTQ6YLSPR9L3L2TI065XWRUBP5DQLYJHO") for x in scandatafile: cve=scandatafile.readline().strip('\n\r') CVE_DATA = vulners_api.docume...
# # Установка и импорт необходимых библиотек import numpy as np import pandas as pd import matplotlib.pyplot as plt #import pickle #import scipy.io from skimage import io import csv import sys import os import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.models as M import tensorflow.kera...
""" Program to display the following pattern 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 """ for i in range(1,6): print(" ") for j in range(1,i+1): print(i,end=" ")
import os f1 = open('input.txt', 'r') f2 = open('task1_ref0.txt', 'r') d1 = f1.readlines() d2 = f2.readlines() for i in range(len(d1)): if(d1[i] == "UNK\n"): del d1[i] del d2[i] i = i - 1 print(i) f1_ = open('test.article.cut.txt', 'w') f2_ = open('test.title.cut.txt', 'w') for i in rang...
import matplotlib.pyplot as plt import numpy as np from brancher.variables import RootVariable, RandomVariable, ProbabilisticModel from brancher.standard_variables import NormalVariable, LogNormalVariable, BetaVariable from brancher import inference import brancher.functions as BF # Probabilistic model # T = 100 nu ...
def from_end(arr): value=[] for i in range(len(arr)): if i%2==1: value.append(arr[-i]) list=map(str,value) return ''.join(list) if __name__=='__main__': print(from_end([9,28,3,7,9,0]))
metadata = """ summary @ A library that makes it possible to implement a filesystem in a userspace program. homepage @ http://fuse.sourceforge.net/ license @ GPL2 src_url @ http://downloads.sourceforge.net/fuse/$fullname.tar.gz arch @ ~x86_64 """ depends = """ runtime @ sys-libs/glibc """ def configure(): conf("-...
#!/usr/bin/python3 import requests from pathlib import Path from xml.etree import ElementTree as ET import json import argparse import platform import os, sys from time import sleep import datetime as dt from writer import Writer as ww class geonames: def __init__(self, zip_code=None, geo_acct=None): self.zip_code ...
def sugar(N): for y in range((N//3)+1): for x in range((N//5)+1): if ((5*x + 3*y) == N): return x+y return -1 N = int(input()) print(sugar(N)) # before # ex) 5x + 3y=18 # m = 1 # while 1: # y = s - 5 * m # if y > 0: # if y % 3 == 0: # ...
# -*- coding: utf-8 -*- """ Created on Mon May 28 10:37:34 2018 @author: jack """ from mujoco_py import * from PID import * from Rotations import * import time import csv import math class MUJOCO(object): def __init__(self): self._pid = [PID(),PID(),PID(),PID(),PID(),PID(),PID(),PID(),PID()] ...
from setuptools import setup, find_packages setup( name="jiva", version="5.0", author="ZeOmega", author_email="info@zeomega.com", description="Jiva - Care Management Software", packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=['setuptools', ...
city_type = [("Kyiv", "Kyiv"), ("Lviv", "Lviv"), ("Odessa", "Odessa")]
# support raw data input # redo API, maybe add explicit duration, maybe remove DLPack, keep only NumPy # specify output channel_layour? # https://bugs.python.org/issue11429 # https://bugs.python.org/issue12836 # https://stackoverflow.com/questions/20439640/ffmpeg-audio-transcoding-using-libav-libraries # https://stac...
#!/usr/bin/env python # -*- coding: utf-8 -*- import redis import consul from flask import current_app def create_redis_connection(): """ 从redis连接池获取连接 :return: """ pool = redis.ConnectionPool(host=current_app.config['REDIS_HOST'], port=current_app.config['REDIS_PORT'], db=0,) r = redis.Redis(...
import time class Clock(object): def __init__(self, interval): self.time = time.time() self.interval = interval def time_elapsed(self): return time.time() - self.time def time_remaining(self): return self.interval - self.time_elapsed() def tick(self): self.time = time.time() if __name__ ==...
row, col = list(map(int, input().split())) board = [] visited = [] groups = [] for i in range(row): board.append(list(map(int, input().split()))) visited.append([0 for j in range(col)]) queue = [(0, 0)] result = 0 while len(queue) > 0: cur = queue[0] del queue[0] visited[cur[0]][cur[1]] = 1 ...
# -*- coding: utf-8 -*- """ Created on Sat Oct 27 10:30:57 2018 @author: Atul Anand """ def min_op (n, m, str1, str2) : op = [[i+j for i in range(n+1)] for j in range(m+1)] print(op) for i in range(m) : for j in range(n) : if str1[j] == str2[i] : op[i+1][j+...
import numpy as np import sys from matplotlib import pyplot as plt sys.path.append('D:\SoftwareWebApps\Python\pyQt\LogSpliceUI\\') from LateralCorr import mean_norm,get_delay from flex import FlexXY from Filters import * projectFolder=r'D:\Ameyem Office\Projects\Cairn\W1\\' log_bundle=np.load(projectFolder+'proc_logs_b...
import re from datetime import datetime, timedelta from .string_manip import getlist, getlistint from .time_util import get_relativedelta, add_to_time_input from .time_util import ti_get_hours_from_relativedelta from .time_util import ti_get_seconds_from_relativedelta from .string_template_substitution import do_strin...
''' Created on 13.09.2012 @author: Stefan This is the abstract class for presenter objects, which represent the results in different ways ''' class CPresenter(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' def printData(self, S...
#!/usr/bin/python -tt # -*- coding: utf-8 -*- print " (1)" provincias={'Madrid':['cocido'],'Sevilla': ['gazpacho', 'pescaito'], 'Alicante': ['salmonetes', 'ensalada']} print provincias print " (2) " provincias['Leon']=['morcilla', 'menestra'] provincias['CiudadReal']=['berenjenas','pisto'] print provincias...
#coding=utf8 ######################################################################## ### ### ### Created by Martin Genet, 2012-2016 ### ### ### ### University...
#!/usr/bin/env python """ The core of the hub. The hub basically: - maintains a keyword-value ("KV") dictionary, - accepts commands from Commanders and passes them onto Actors, - accepts and generates KV responses, and passes them on to interested parties. We handle the fact that we can get...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): """ Change Recording.languages from many-to-one to many-to-many. Strictly speaking, this should have been a single AlterField operation. The combination...
def gowno(): kupa = 20 print(kupa) class first(): def __init__(self, secondvalue): self.firstvalue = 10 self.secondvalue = secondvalue def props(self): self.someprop = "stringvalue" self.someprop2 = 10 self.someprop3 = 1.2
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import fields, models,api,_ _logger = logging.getLogger(__name__) class BusinessAccount(models.Model): '''Business account model description''' _name = 'business.account' _descript...
import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import optimizers import cv2 data = pd.read_csv("C:\\Users\\Daood-PC\\Desktop\\finale.csv", encoding = 'utf-8') y1 = data['st...
# -*- coding: utf-8 -*- import numpy as np import sys import pylab as plt from numpy import genfromtxt import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import os from pylab import * # General constants T_lower_limit = 19.5 # cooling starts above this temerature flh_required = 400.0 # typical flh ...
gato = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'} def muestra_gato(gato): print(f"{gato[1]} | {gato[2]} | {gato[3]}") print("--+---+--") print(f"{gato[4]} | {gato[5]} | {gato[6]}") print("--+---+--") print(f"{gato[8]} | {gato[8]} | {gato[9]}") def ju...
# Generated by Django 2.1.1 on 2018-09-23 15:58 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='IPInfo', fields=[ ('id', models.AutoField(a...
# -*- encoding: utf-8 -*- ''' __author__ = "Larry_Pavanery ''' from abstract_redis_database import AbstractRedisdb from surl.model.url import URL from surl.helpers.shared import get_index_id_url from surl.helpers.shared import length_id_url from surl.helpers.shared import root_url from surl.helpers.constants import ...
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ A protocol to calibrate the water system. In addition, to contro the lights. """ from pybpodapi.bpod import Bpod from pybpodapi.state_machine import StateMachine from pybpodapi.bpod.hardware.events import EventName from pybpodapi.bpod.hardware.output_channels ...
import itertools def isPrime(n): for i in range(2,int(n**0.5)+1): if (n%i==0): return False return True for i in (sorted([int(i) for i in [''.join(i) for i in list(itertools.permutations('1234567',7))]])[::-1]): if (isPrime(i)): print (i) break
from skimage import draw from skimage import io import numpy as np import urllib.request import json import logging import os import sys import PIL.Image import argparse #enable info logging. logging.getLogger().setLevel(logging.INFO) def poly2mask(blobs,path_to_masks_folder, h, w, label, idx, filename): mask = n...
# Visualisation import matplotlib as mpl import matplotlib.pyplot as mpl import numpy as np import pandas as pd import plotly.graph_objects as go import seaborn as sns from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix # Modelling ...
import yaml import collections # For creating ordered dictionary import json # For creating json data import os from pathlib import Path import statistics import itertools from datetime import datetime, date from pytz import timezone import calendar import random import names import Database_Ble ...
from __future__ import annotations from asyncio import AbstractEventLoop, CancelledError import functools import logging import os from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Text, Union import uuid import aiohttp from aiohttp import ClientError from rasa.core import jobs from ras...
''' Created on 06.12.2012 @author: cbalea ''' from selenium.webdriver.support.select import Select from ss.pages.base_page_ss import BasePageSS from utils.server_related import ServerRelated import time class BrowseByStandardsPageSS(BasePageSS): loadingImageXpath = "//div[@id='LoadingImage' and contains(@style,'...
class TripSection: def __init__(self, trip_id, line_id, station_from, station_to, travel_time, trip_section_id=0): self.trip_section_id = trip_section_id self.trip_id = trip_id self.line_id = line_id self.station_from = station_from self.station_to = station_...
import pygame # initiate pygame with all the modules pygame.init() # setup windows/surface # 800 width, 600 height # explicitly define to be able to refer to later display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) # define colors (RGB) black = (0,0,0) whi...
# cv2.namedWindow('road') # cap = cv2.VideoCapture('test2.mp4') # while cap.isOpened(): # _, frame = cap.read() # cv2.imshow('road', frame) # key_pressed = cv2.waitKey(1) # if key_pressed == ord('q'): # break # cap.release() # cv2.destroyAllWindows() def main_tk_thread(): global t def ...
#!/usr/bin/env checkio --domain=py run chemical-analysis # As the input you will get the chemical formula and the number N. Your task is to create a list of the chemical elements, which are in the formula in the amount of >= N. # Pay attention, that in the some formulas will be used brackets - () and [].This articlewi...
import os import json import pickle import subprocess affdex_dir = "affdex-outputs" rosbag_input_dir = 'rosbag_inputs' #os.path.exists() remaining_rosbags="" if os.path.exists("remaining_rosbags.p"): remaining_rosbags = pickle.load( open( "remaining_rosbags.p", "rb" ) ) else: with open('study_data_map.json') as jso...
""" The :py:mod:`~tdda.constraints` module provides support for constraint generation and verification for datasets, including CSV files and Pandas DataFrames. The module includes: - Tools :py:mod:`~tdda.constraints.pddiscover` for discovering constraints in Pandas DataFrames saved in :py:mod:`feather` file...
import xml.etree.cElementTree as ET from xml.dom import minidom class db(): def insertar(lista): root = ET.Element("terrenos") for i in lista: doc = ET.SubElement(root, "DTE") ET.SubElement(doc, "AUTORIZACION").text=str(i[0]) ET.SubElement(doc, "FECHA...
__version__ = "0.3.3" from .api_report import * from .bearing_seal_element import * from .disk_element import * from .materials import * from .point_mass import * from .rotor_assembly import * from .shaft_element import * from .utils import visualize_matrix
maximum = 0 f = open("../../txt/pje_0008_n.txt", "r") n = f.read() i = 0 j = len(n) - 5 while i < j: product = 1 for k in xrange(i, i+5): product = product * int(n[k]) if maximum < product: maximum = product i = i + 1 print "%d" % (maximum)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from django.contrib.flatpages.admin import FlatPageAdmin from .widgets import Editor from .models import * @admin.register(Tag) class TagAdmin(admin.ModelAdmin): ...
import datetime import django_filters import pytz from django.conf import settings from django.db.models import Q from user.models import UserTraffic, UserClickTracker class UserTrafficFilter(django_filters.FilterSet): created_at = django_filters.CharFilter(field_name='created_at', lookup_expr='icontains') ...
Set = input()[1:-1] Set = set(Set.split(', ')) if '' in Set: print(len(Set)-1) else: print(len(Set))
from django.db import models from TCCgo.apps.authentication.models import User class Topic(models.Model): title = models.CharField(max_length=150, blank=False, null=False) message = models.TextField(blank=False, null=False) date = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASC...
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def PrintFromTopToBottom(self, root): if not root: return queue = [] result = [] queue.append(root) while l...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "FeNikS" # NOC modules from noc.core.profile.base import BaseProfile class Profile(BaseProfile): name = "Sumavision.EMR"
# -*- coding: utf-8 -*- """ Created on Thu Apr 22 10:35:14 2021 @author: kasia """ from tkinter import ttk import requests, json import io import base64 import tkinter as tk from urllib.request import urlopen from PIL import ImageTk,Image import requests from PIL import Image import requests from io import BytesIO ...
import time import io import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions imp...
# -*- coding: utf-8 -*- __author__ = 'Jonathan Mulle & Austin Hurst' import os from sdl2.ext import cursor_hidden from klibs.KLEyeTracking import PYLINK_AVAILABLE from klibs.KLExceptions import EyeTrackerError from klibs.KLConstants import (EL_LEFT_EYE, EL_RIGHT_EYE, EL_BOTH_EYES, EL_NO_EYES, EL_FIXATION_START, E...
import unittest from CircleTriangle import CircleTriangle class TestEuroTriangle(unittest.TestCase): def test_regular_triangle_counts_6_bottom_row_circles_correctly(self): triangle = CircleTriangle(6) self.assertEqual(35, triangle.count_regular_triangles()) def test_regular_triangle_counts_5_...
import numpy as np, cv2 m = np.random.rand(3, 5) * 1000 // 10 reduce_sum = cv2.reduce(m, dim=0, rtype=cv2.REDUCE_SUM) # 0 - 열방향 축소 합 print(reduce_sum) reduce_avg = cv2.reduce(m, dim=1, rtype=cv2.REDUCE_AVG) # 1 - 행방향 축소 평균 reduce_max = cv2.reduce(m, dim=0, rtype=cv2.REDUCE_MAX) # 열 최대값 reduce_min = cv2.reduce(m, d...
"""A video library class.""" from typing import Sequence, Optional import csv import random from pathlib import Path from .video import Video # Helper Wrapper around CSV reader to strip whitespace from around # each item. def _csv_reader_with_strip(reader): yield from ((item.strip() for item in line) for line ...
# load primitives from file # control vocal tract # generate figures with constant control inputs at various values # save vocal tract data of utterance to file, and save output audio to file # for forcing floating point division from __future__ import division import os import numpy as np import pylab as plt from p...
import torch.nn as nn import torch # CrossEntropyLoss for Label Smoothing Regularization class CrossEntropyLoss_LSR(nn.Module): def __init__(self, device, para_LSR=0.2, weight=None): super(CrossEntropyLoss_LSR, self).__init__() self.para_LSR = para_LSR self.device = device self.log...
# encoding: utf-8 class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ letters = ''.join(set(s)) if len(s) == len(t): for c in letters: if s.count(c) != t.count(c): return Fal...
import praw import pprint import configparser import time from pprint import pprint from rexplore import db import uuid # See: https://github.com/wlindner/python-reddit-scraper/blob/master/scraper.py ''' How to insert User: init = db.initialize('../config/config.ini') init.insert_user(user) ''' # uses envir...
import json import boto3 import pandas as pd from io import StringIO from time import sleep dbclient = boto3.client("dynamodb") s3client = boto3.client("s3") table = "tweets_table" AGGREGATION_TRIGGER_BUCKET = 'aml-twitter-aggregation-trigger' def lambda_handler(event, context): highs = 0 lows = 0 table...
#!/bin/python3 # -*- coding:utf-8 -*- # author: Huxuezheng # describe: K8S V1.18 一键脚本安装 import os import subprocess import time class k8s_install(object): def __init__(self,masterip,nodeip): self.masterip = masterip self.nodeip = nodeip def initialization_shell(self): #环境初始化shell # 关闭...
import numpy as np import torch from matplotlib import pyplot as plt from CustomDatasets import LookaheadDataset from FCNetwork import instantiate_model from load_data import load_error_data, load_simulated_data device = "cuda" if torch.cuda.is_available() else "cpu" def example_inference(n_ahead=100): # load m...
import os import tensorflow as tf from keras.layers import Dense, Dropout from keras.models import Sequential # Ignore warnings regarding supported CPU instructions os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Set tensorflow logging to ignore warnings and report errors only tf.compat.v1.logging.set_verbosity(tf.compat....
import nltk import string from neo4j.v1 import GraphDatabase, basic_auth import requests driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("",""), encrypted=False) session = driver.session() default_tagger = nltk.data.load(nltk.tag._POS_TAGGER) punctuations = list(string.punctuation) stemmer = nltk.st...
""" Converts raw scrobbles table to updated scrobbles table for analysis. Converts all item_url strings to numeric item IDs """ import dbMethods import datetime import MySQLdb import MySQLdb.cursors import time import cPickle ### Set up cursors # streaming cursor, for reading full annotations table from raw database d...
""" 2.6 Задачи по материалам недели Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк, заканчивающихся строкой, содержащей только строку "end" (без кавычек) Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j равен сумме элементов пе...
"""Matchzoo toolkit for token embedding.""" import csv import typing import numpy as np import pandas as pd from matchzoo import processor_units class Embedding(object): """ Embedding class. Examples:: >>> import matchzoo as mz >>> data_pack = mz.datasets.toy.load_data() >>> pp...