text stringlengths 38 1.54M |
|---|
from settings import *
MIDDLEWARE_CLASSES += ['joshandlyd_site.middleware.NoWWW']
DEBUG = True
CACHE_MIDDLEWARE_SECONDS = 60 * 60 * 24 * 365 * 10 # 10 Years, not correct for leaps
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 14:22:27 2021
@author: suraj
"""
import pyvista as pv
import numpy as np
import matplotlib.pyplot as plt
from pyvista import examples
from scipy.integrate import odeint
filename = f'../../../Similarity_Solution/su2.csv'
data_blasisus = np.genfr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0007_auto_20160112_2055'),
]
operations = [
migrations.AlterField(
model_name='averagecrossover',
... |
'''
RAM to store data
'''
import logging
from utils import utils
from .memory import SegfaultError
logger = logging.getLogger('hardware.memory.ram')
class RAM:
'''
Random-access memory
'''
def __init__(self, size):
self.size = size
self._content = [0] * self.size
logger.in... |
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
from matplotlib import pyplot as plt
import numpy as np
|
import logging
from wap.data_source import data_source_config
from wap.settings import db_config, ext_config
from wap.utils.db_manager import DatabaseManager
from wap.utils.redis_manager import RedisManager
from wap.events import events_config
from wap.exceptions import VariableInitError
async def dependence_init(ap... |
# -*- coding: utf-8 -*-
import logging
import re
from urllib.parse import quote_plus
from lncrawl.core.crawler import Crawler
logger = logging.getLogger(__name__)
search_url = "https://noveltoon.mobi/en/search?word=%s&source=&lock="
class NovelsRockCrawler(Crawler):
base_url = "https://noveltoon.mobi/"
def... |
from urllib.request import urlopen
from http.client import BadStatusLine
from bs4 import BeautifulSoup
import random
from django.http import Http404
# TODO allow in future for more prefixes, maybe take down restriction
WIKI_PREFIX = 'http://en.m.wikipedia.org'
WIKI_INFIX = '/wiki/'
def crawl_webpage(url):
if url... |
from tkinter import *
import random
window = Tk()
window.geometry('500x500')
xcoord=170
ycoord=150
default_password="0987"
string=""
v=StringVar()
v.set(string)
def change():
randomlist=generaterandom()
btn_0['text']=randomlist[0]
btn_1['text']=randomlist[1]
btn_2['text']=randomlist[2]
bt... |
import cv2
import numpy as np
def aHash(img):
img = cv2.resize(img, (8, 8))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
s = 0
hash_str = ''
for i in range(8):
for j in range(8):
s = s + gray[i, j]
avg = s / 64
for i in range(8):
for j in range(8):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 18:06:17 2021
@author: James
"""
import numpy as np
import scipy.sparse as sp
import src.hamiltonian as hamiltonian
import src.potential as potential
from scipy.fft import fft, ifft, fftshift, fftn, ifftn
from time import time
from src.fftSolver import tr... |
from django.db import models
class CheckIn(models.Model):
class Meta:
db_table = 'check_in'
unique_together = ('booking_ref_num', 'passenger_first_name', 'passenger_last_name', 'departure_date')
booking_ref_num = models.CharField('Booking reference number', max_length=10, null=False)
pass... |
# encoding=utf-8
from stock.io.all_stock import get_all_stockcode_in_china
def test_get_all_stockcode_in_china():
stocks=get_all_stockcode_in_china()
assert len(stocks) != 0 |
"""
Scheduling nurses
See https://developers.google.com/optimization/scheduling/employee_scheduling
"""
from ortools.sat.python import cp_model
def nurse_scheduling_with_requests():
num_nurses = 5
num_shifts = 3
num_days = 7
all_nurses = range(num_nurses)
all_shifts = range(num_shifts)
all_... |
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from apps.articles.models import Comment, Article
@receiver((post_save, post_delete), sender=Comment)
def update_article_comments_count(sender, instance, **kwargs):
count = Comment.objects.active().filter(article=ins... |
a,b = map(int, input().split())
if a != b:
s = ("Odd %d" % (max(a,b)*2))
elif a == b and (a != 0 and b != 0):
s = ("Even %d" % (a*2))
else:
s = "Not a moose"
print(s) |
from flask import Flask, render_template, url_for, flash, redirect, request
from application import app, db, bcrypt
from application.forms import RegisterationForm, LoginForm, UpdateAccountForm, Transcriptform, VideosForm
from application.models import User, Transcript, Videos #fixing the circular import error.
from fl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 15:29:06 2019
@author: bdus
this is the model for idea1 experiment 4
video frames are take part into foregrounds and backgrounds
then feed into a dual stream network respectively
the network will fusion the result in difference method
the input... |
#coding=utf-8
"""
Вспомогательные функции и классы
"""
from datetime import datetime
import json
from flask import url_for
from flask import render_template
############################################################
def str_remove_bom(str):
"""Удаляет BOM-символы в начале строки (обнаружилась проблема с шаблонами... |
print("Hello, World!)
File "<stdin>", line 1
print("Hello, World!)
^
SyntaxError: EOL while scanning string literal
>>> print("Hello", World!)
File "<stdin>", line 1
print("Hello", World!)
^
SyntaxError: invalid syntax
>>> print("Hello", World)
Traceback ... |
from .base import BasePreprocessor
import cv2
import numpy as np
class GenericPreprocessor(BasePreprocessor):
"""
A generic preprocessor that uses the CPU for its calculations.
"""
def __init__(self):
super().__init__()
def resize(self, image: np.ndarray, width: int, height: int) -> np.nd... |
import os
import sys
from pbstools import PythonJob
import sys, getopt
import numpy as np
import glob
import h5py
import time
import glob
import shutil
def main(argv):
opts, args = getopt.getopt(
argv,
[],
[
"output_folder=",
"model_file=",
"start_frame=... |
# -*- coding: utf-8 -*-
from odoo import api, models, fields, _
from odoo.tools.misc import xlwt
from odoo.http import request
import base64
import unicodedata
import StringIO
import xlsxwriter
from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
class financ... |
# -*- coding: utf-8 -*-
import time
import asyncio
async def func1(num):
print('1')
m = await func2(num)
# await asyncio.sleep(2)
# m = num * 2
print(m)
return m
async def func2(num):
# time.sleep(2)
await asyncio.sleep(2)
return num * 2
async def func3():
# a = await func1... |
from agents.ddpg.DDPGAgent import DDPGAgent
from agents.dqn.DQNAgent import DQNAgent
from agents.sac.SACAgent import SACAgent
from agents.td3.TD3Agent import TD3Agent
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#array = []
#sumatoria = 0.0
#for i in range(1, 11):
# numero = float(raw_input('Introduzca el numero ' + str(i) + ': '))
# array.append(numero)
# sumatoria += numero ** 2
#print(array)
#print(sumatoria)
|
#!/usr/bin/python3
import log
myLog = log.Log("plp.log")
myLog.add("PLP start up checks beginning")
import plpHelper
plpHelper.startupChecks(myLog)
myLog.add("PLP start up checks passed")
# imports
import pauser
import decider
tv = pauser.Pauser()
myDecider = decider.Decider()
myLog.add("PLP ready...startin... |
from .scrubbing import create_scrubbing_preproc, \
get_mov_parameters, \
get_indx
__all__ = ['create_scrubbing_preproc', \
'get_mov_parameters', \
'get_indx']
|
# !/usr/bin/env python
# coding: utf-8
'''
'''
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class MyCrypt():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC
def myencrypt(self, text):... |
from copy import copy
from smif.decision.decision import RuleBased
from smif.data_layer.data_array import DataArray
from logging import getLogger
import pandas as pd
class EnergyAgent(RuleBased):
"""A coupled power-producer/regulator decision algorithm for simulating
decision making in an energy supply model... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 19:31:48 2018
@author: Santosh Bag
"""
import sys
sys.path.append('F:\\Mrig Analytics\\Development\\mrigAnalytics\\instruments')
from instruments import termstructure as ir
from instruments import bonds as bo
from instruments import index as i
from instruments import ... |
import matplotlib.pyplot as plt
import time
import random
mylist = []
numbers = []
sec = []
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L)... |
import random
import time
from src.metier.LinkedList import LinkedList
# Afin d'avoir tout le temps les mêmes nombres aléatoires
random.seed(10)
def is_sorted(lk: LinkedList):
n = lk.get(0)
for i in range(1, lk.size()):
j = lk.get(i)
if n > j:
return False
n = j
retur... |
from fb_post_v2.interactors.storages import ReactionStorageInterface
from fb_post_v2.interactors.storages import PostStorageInterface
from fb_post_v2.interactors.presenters import PresenterInterface
class GetReactionsToPostInteractor:
def __init__(self,
post_storage: PostStorageInterface,
... |
# All edits to original document Copyright 2016 Vincent Berthiaume.
#
# Copyright 2015 The TensorFlow Authors. 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.
# You may obtain a copy of the License at
#
# ht... |
from .views import ActivityView, CreateSubmissionView, RateSubmissionView, GetSubmissionView
from django.urls import path
urlpatterns = [
path('activities/', ActivityView.as_view()),
path('activities/<int:activity_id>/submissions/', CreateSubmissionView.as_view()),
path('submissions/<int:submission_id>/'... |
import time
import atexit
import pdb
import threading
import sys
import binascii
def authCtrl_thread():
p4_pd.digest_fields_register()
print "AuthCtrl receiver registered, ready to start receiving authCtrl requests"
while True:
try:
msg = authCtrl_req_get()
authCtrl_req_process(msg)
exce... |
#!/usr/bin/python
"""
twitter_api_wrapper.py -- contains class used to interact with the Twitter API
"""
import base64
import logging
import json
import os
import requests
LOGFILE = 'topics-bcrom.log'
logging.basicConfig(filename=LOGFILE, level=logging.DEBUG)
class TwitterAPIWrapper(object):
"""
TwitterAPIWr... |
import datetime
from django.utils import timezone
import factory
from ..models import RecentActivity
class RecentActivityFactory(factory.DjangoModelFactory):
FACTORY_FOR = RecentActivity
FACTORY_DJANGO_GET_OR_CREATE = ('url',)
title = "VOXQUARTERがIndie Game Awardを獲得しました"
thumbnail = "thumbnails/recen... |
from typing import OrderedDict
import numpy as np
import torch
from torch.distributions import Normal
from scvi import _CONSTANTS
from scvi._compat import Literal
from scvi.distributions import NegativeBinomial
from scvi.module.base import BaseModuleClass, LossRecorder, auto_move_data
from scvi.nn import FCLayers
d... |
xa=float(input())
ya=float(input())
xb=float(input())
yb=float(input())
xm=float((xb+xa)/2)
ym=float((yb+ya)/2)
print(round(xm,1))
print(round(ym,1))
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Converte ficheiros texto para html estruturado, em que referência os versículos
#
import re
import logging
import sys
import argparse
import os
import codecs
__author__="Alexandre Carlos"
__date__ ="$11/Out/2012 15:34:25$"
__version__ ="0.2"
global args
LOG_FILENAME =... |
import os
BASEDIR = os.path.dirname(__file__)
VOLUMES_DIR = os.path.join(BASEDIR, "volumes")
os.mkdir(VOLUMES_DIR)
|
# import openpyxl
# wb=openpyxl.load_workbook('demo.xlsx')
# ws=wb.active
# # for r in [['%d*%d=%d'%(y,x,x*y) for y in range(1,x+1)] for x in range(1,10)]:
# # ws.append(r)
# # ws.delete_rows(1)
# # wb.save('demo.xlsx')
# for row in ws['a1:c6']:
# for c in row:
# c.value=1
# wb.save('demo.xlsx')
import... |
#!/usr/bin/python
import os
import sys
import getopt
import pandas as pd
def main(argv):
run_generator = False
num_of_stocks = 100
num_of_iterations = 10
try:
opts, args = getopt.getopt(argv, "hgs:i:", ["num_of_stocks=", "num_of_iterations="])
except getopt.GetoptError:
print('-g... |
import sys
from collections import deque
def BFS(i, j):
x = [1, 1, 1, 0, 0, -1, -1, -1]
y = [1, 0, -1, 1, -1, 1, 0, -1]
queue = deque()
queue.append((i,j))
while queue:
now = queue.popleft()
for i in range(8):
next_x = now[0] + x[i]
next_y = now[1] + y[i]
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-11-25 07:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutor', '0026_auto_20170905_2206'),
]
operations = [
migrations.AlterField(... |
'''
Created on 2020年10月24日
保存待扩展的节点
@author: dingxinlong
'''
import operator
import NODE as Node
class Open():
def __init__(self):
self.nodelist=[] #保存节点的列表
self.cmpfun = operator.attrgetter('fund','depth') #open表排序条件 估计值优先,其次是深度
def sortfun(self):
'''
对open表进行排... |
def count_path(row, column, length, matrix):
if row == length and column == length and matrix[length][length] == '.':
return 1
if row > length or column > length:
return 0
if matrix[row][column] == '.':
return count_path(row,column+1,length, matrix) + count_path(row+1,column,length, ... |
import numpy as np
from synthsonic.models.kde_quantile_tranformer import KDEQuantileTransformer
from sklearn.base import BaseEstimator
from sklearn.utils import check_array
from sklearn.utils.validation import FLOAT_DTYPES # check_is_fitted, _deprecate_positional_args
from sklearn.decomposition import PCA
from sklearn.... |
from django import forms
from django.contrib.gis.db.backend import SpatialBackend
from django.utils.translation import ugettext_lazy as _
class GeometryField(forms.Field):
"""
This is the basic form field for a Geometry. Any textual input that is
accepted by SpatialBackend.Geometry is accepted by this for... |
import tornado.web
import json
"""
TO DO:
BaseHandler class
- standard get/put/post/delete methods
- debug info decorator
Models
- define SQLAlchemy models for objects
- pass model to handler?
- how could we design that way?
"""
class TestHandler(tornado.web.RequestHandler):
def get(self):
qs_args = se... |
def scramble(str1, str2):
''' returns True if str2 can be created using letters in str1, else False'''
#9267 ms failed 7
if len(str1) < len(str2):
return False
s1 = set(str1)
s2 = set(str2)
extra = list(s1.difference(s2))
missing = list(s2.difference(s1))
if missing:
... |
from django.shortcuts import render_to_response
from django.http import HttpResponse
import subprocess
import os
def index(request):
return render_to_response('index.html',locals())
def c(request):
opt = request.GET.get('opt','')
command = "deadbeef --"+opt
subprocess.Popen(command,shell = True)
... |
__author__ = 'anngordon'
import addressbook_pb2
_TIMEOUT_SECONDS = 10
def run():
with addressbook_pb2.early_adopter_create_LookUpPerson_stub('localhost', 50051) as stub:
response = stub.LookUp(addressbook_pb2.Person(name='you', id=41247234), _TIMEOUT_SECONDS)
print "LookUpPerson client received: " + respo... |
#######################################################################################
# check_pass.py
# can be used to verify a user's login against flaskapp.db locally
# not for use with flask, just a local utility
#######################################################################################
import sqlite3... |
from django.shortcuts import render
#from .models import Ohms
from .forms import OhmsForm, MessageForm
from . import calculations
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
def home_page(request):
return render(request, 'calcs/pages/home.html', {})
# When the user wants ... |
# JSTSK-350111
# problem 1.7.py
# Cynthia Koopman
# c.koopman@jacobs-university.de
# prompt the radius and change to float
radius = input('radius =')
radius = float(radius)
# declare pi
pi = 3.14159
# compute the area
area = pi * radius * radius
#print the area
print('The area is',area) |
#!/usr/bin/env python3
###############################################################################
#
# Copyright 2019 - 2022, Thomas Lauf, Paul Beckingham, Federico Hernandez.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the... |
# -*- coding: utf-8 -*-
"""eBay requests related to revising item data. These are not read-only, and
will affect live eBay data.
"""
import redo
from ebaysdk.exception import ConnectionError
from erpnext_ebay.ebay_constants import (
EBAY_TIMEOUT, HOME_SITE_ID, REDO_ATTEMPTS, REDO_SLEEPTIME,
REDO_SLEEPSCALE, ... |
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from staticmap import StaticMap, CircleMarker, Line
import data
import os
import networkx as nx
# Inicia la conversa amb el bicing_bot
# Crea un graf de distància 100 automàticament
def start(bot, update, user_data):
data.cre... |
from scrapy.cmdline import execute
execute(['scrapy','runspider', 'booking\spiders\spider.py','-a','lang=en-us']) |
import mysql.connector #mysql driver for accesing MYSQL database
c=mysql.connector.connect(
host='localhost',
user='root',
passwd='ztech@44',
database='Employee_DATA')
cur = c.cursor()
#cur.execute('create table employee_info(id INT AUTO_INCREMENT PRIMARY KEY,name varchar(255),department varchar(255),salary int(20... |
from testflows.core import *
from testflows.asserts import error
from contextlib import contextmanager
from extended_precision_data_types.requirements import *
from extended_precision_data_types.common import *
@TestFeature
@Name("table")
@Requirements(
RQ_SRS_020_ClickHouse_Extended_Precision_Create_Table("1.0")... |
from __future__ import print_function
import os
import sys
import subprocess
r_dependencies = ["RSQLite", "plyr", "gplots", "devtools", "ggplot2"]
r_github_dependencies = ["ucd-cws/wq-heatplot"]
def set_up_r_dependencies():
import launchR # imported here because it will be installed before this is called, but won... |
from xml.sax import make_parser
from Handler import Handler
f = open('partial.xml')
hd = Handler()
saxparser = make_parser()
saxparser.setContentHandler(hd)
saxparser.setDTDHandler(hd)
saxparser.parse(f) |
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
import sys
import numpy as np
import minocore
import h5py
dat = h5py.File('/users/ndyjack/Dist_Proj/tables/1M_neurons/1M_neurons_filtered_gene_bc_matrices_h5.h5', 'r')
expr = dat['mm10/data']
|
from gmcs.utils import TDLencode
from gmcs.utils import orth_encode
from gmcs.linglib import case
from gmcs.linglib import features
def set_supertypename(auxcomp):
if auxcomp == 's':
supertypename = 's-comp-aux'
elif auxcomp == 'vp':
supertypename = 'subj-raise-aux'
else:
supertyp... |
from flask import Flask, render_template, redirect, g, url_for, flash
from flask_login import LoginManager, login_user, login_required, current_user
from flask_bcrypt import check_password_hash
import forms
import functions
import models
import airports.airportScraper
app = Flask(__name__)
app.secret_key = 'asdjkansd1... |
import RPi.GPIO as IO
import wave
pin = 27
IO.setmode(IO.BCM)
IO.setup(pin, IO.OUT)
wr = wave.open('flesh_wound.wav','rb')
nchannels, sampwidth, framerate, nframes, comptype, compname = wr.getparams()
if nchannels == 1:
frames = wr.readframes(wr.getnframes())
else:
frames = 0
byteList = []
x = 0
for s1 in lis... |
from __future__ import annotations
from typing import Literal
from prettyqt import constants, core, widgets
from prettyqt.utils import bidict
area = widgets.QAbstractScrollArea
SizeAdjustPolicyStr = Literal["content", "first_show", "ignored"]
SIZE_ADJUST_POLICY: bidict[SizeAdjustPolicyStr, area.SizeAdjustPolicy] ... |
'''
priority queue problem
First, we need to cnsider if the string that meets the requirement exist. If the most frequent element is larger than len(S)/2, then it must not exist.
Second, how to build the proposed string?
Condition1: two consecutive characters must not be the same
Condition2: The elements with high... |
# -*-coding:utf-8 -*-
"""
Created on 2015-3-22
@author: Danny<manyunkai@hotmail.com>
DannyWork Project
"""
from __future__ import unicode_literals
from django import forms
from django.contrib.auth import authenticate
from django.forms.utils import flatatt
from django.utils.html import format_html, format_html_join
f... |
########
# Please choose the scene you'd like to reconstruct in line 19. The names of measurements include 'duomino',
# 'pendulumBall' and 'waterBalloon'.
# Please set the compression ratio(Cr) in line 18. You can set Cr to be 10, 20 or 30.
########
from __future__ import absolute_import
import tensorflow as tf
impor... |
"""
The purpose of this program is to test the classify_triangles program
@author: Julio Lora
"""
from classify_triangles import *
import unittest
class TestTriangles(unittest.TestCase):
def testEquilateral(self):
self.assertEqual(classify_triangle(2,2,2),'Equilateral')
self.assertNotEqual(clas... |
import pygame, sys, random, time
from pygame.locals import *
class SpriteSheet(object):
#generic sprite sheet
#Handles Initializing a Sprite and how to grab animation frames for that sprite
#Movment of each sprite should be handled by its individual sub-class
#
def __init__(self, file_name)... |
num1 = 1000
num2 = 500
if num1 > num2:
print("num1 is bigger than num2")
if num1 > num2:
print("num1 is bigger than num2")
else
print("num2 is bigger than num1")
|
# Generated by Django 2.1.7 on 2019-03-22 19:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('equipaments', '0005_auto_20190322_1652'),
]
operations = [
migrations.AddField(
model_name='equipaments',
name='mac'... |
import pygame
import random
import numpy
pygame.init()
screenWidth = 1000
screenHeight = 600
win = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("Sorting")
clock = pygame.time.Clock()
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, ri... |
import os
import sys
import numpy as np
from PIL import Image
def get_image_from_one_sample(data, save = False, name = ""):
image_size = (28, 28)
byte_data = str(bytearray(np.reshape((data * 255.0).astype("uint8"), (28 * 28, ))))
img = Image.frombytes("L", image_size, byte_data)
if save:
default_dir = "imgs"
... |
from abaqusConstants import *
from .AnalyticSurface import AnalyticSurface
from .OdbInstanceBase import OdbInstanceBase
from .OdbMeshNode import OdbMeshNode
from .OdbRigidBody import OdbRigidBody
from .OdbSet import OdbSet
class OdbInstance(OdbInstanceBase):
def OdbRigidBody(
self,
referenceNode: ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import re
from struct import *
import usb.core
import usb.util
PRINT = False
class ScanAlone():
scale = 32767./100. #bits/mm
jump_speed = 2500. #mm/sec
mark_speed = 250. #mm/sec
laser_on_delay = 100
laser_off_delay = 100
commands_... |
#Visum.MatrixEditor.Gravitate("C:\Users\RK\Desktop\Szamerica\distances.dis","C:\Users\RK\Desktop\Szamerica\mat.fma" , "C:\Users\RK\Desktop\Szamerica\cod.cod", "$V;d2" )
# tutaj musisz zdefinowac swoje sciezki dla plikow cod dis i rezulatatu dzialania #
distance_mtx_path="C:\Users\RK\Desktop\Szamerica\dist... |
from __future__ import absolute_import
from requests import HTTPError
import json
from intuitlib.client import AuthClient
from intuitlib.migration import migrate
from intuitlib.enums import Scopes
from intuitlib.exceptions import AuthClientError
from django.shortcuts import render, redirect
from django.http import H... |
class Solution:
def minSetSize(self, arr: list[int]) -> int:
count = {}
for value in arr:
if value in count:
count[value] += 1
else:
count[value] = 1
count = sorted(count.items(), key=lambda x: x[1], reverse=True)
# print(count... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ShenjiaosuoItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
l1_title = scrapy.Field()
l2_... |
import random
#Открытые и закрытые ключи А
Ae = random.randint(1,20)
An = random.randint(1,20)
Ad = random.randint(1,20)
#А передает открытый ключ Б
Be = Ae
#1. Б выбирает случайное число Bk, вычисляется Br = Bk**Ae % An и посылает Ar A
Bk = random.randint(1,An-1)
Br = Bk ** Ae % An
Ar = Br
#2. А вычисляет Ak = ... |
# -*- coding: utf-8 -*-
# This file is part of open-tamil ngrams package
# (C) முத்தையா அண்ணாமலை 2013-2015,2017
#
# N-gram language model for Tamil letters
import codecs
import copy
import operator
import tamil
from .Corpus import Corpus
class Letters:
def __init__(self, filename):
self.letter = dict()
... |
#import urllib2
from flask import Flask, render_template, request, session, redirect, url_for
import json
app = Flask(__name__) #create instance of class
#assign following fxn to run when
#root route requested
@app.route("/")
def hello():
return 'Hello, World!'
if __name__=="__main__":
ap... |
#--------------------------
# CP460 (Fall 2019)
# Final Exam
# Do not edit this file
#--------------------------
import final
import utilities
import mod
import SDES
import matrix
import math
import random
import string
#----------------------------------------------------
# Honor Pledge
#----------------------------... |
# -*- coding: utf-8 -*-
import theano
import theano.tensor as T
from theano.tensor.extra_ops import repeat
def recurrent_layer(hidden_inpt, hidden_to_hidden, f, initial_hidden):
def step(x, hi_tm1):
h_tm1 = f(hi_tm1)
hi = T.dot(h_tm1, hidden_to_hidden) + x
return hi
# Modify the ini... |
import pika
class Server():
def __init__(self,host,exchange='',exchange_type=''):
self.host = host
self.exchange = exchange
self.exchange_type = exchange_type
self.severity = None
self.connection = pika.BlockingConnection(
pika.Connection... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OpenApiPeopleDTO import OpenApiPeopleDTO
from alipay.aop.api.domain.ApproveNodePageGroupDTO import ApproveNodePageGroupDTO
from alipay.aop.api.domain.ContractOpenApiAttachDTO import... |
from numpy import *
vet = array(eval(input("Numeros positivos: ")))
i = 0
mt = 1
n = size(vet)
while(i < n-1):
mt = mt * vet[i] * vet[i + 1]
i = i + 2
media = mt ** (n ** -1)
print(round(media, 2))
|
"""
This is to process the monthly fields into zonal mean and plot
currently, SAT ans precipitation
the model internal variability (25-t5 th percentile) and mean are both plotted
"""
import site
import os
import numpy as np
import netCDF4 as nc4
from scipy import stats
import scipy.io as sio
import math
... |
import os
import logging
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.decorators import login_required
from chemtools.constants import NUMCORES, RGROUPS, ARYL
from data.models import JobTemplate
from da... |
import sys
import os
import basic
import config
#import installDependencies
from colorama import init
from colorama import Fore as coloramaFore
from colorama import Back as coloramaBack
from colorama import Style as coloramaStyle
from colored import fore as Fore
from colored import back as Back
from colored import f... |
"""-----------------------------------------------------------------------------
Name: CreatePositionalOffset_MP.py
Purpose: Determines the positional offset of TDS line features using another
set of line features as the baseline. This tool also summarizes those results
at a grid cell level. Uses multip... |
import numpy as np
def MajorityValue(binary_targets):
num_ones = np.count_nonzero(binary_targets)
num_zeros = len(binary_targets) - num_ones
if num_ones > num_zeros:
return 1
return 0
|
import random
import itertools
import networkx as nx
from dwave_qbsolv import QBSolv
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite
import minorminer
# define (sub)problem size
solver_limit = 3
qubo_size = 4
# find embedding of subproblem-sized complete gr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.