text stringlengths 38 1.54M |
|---|
import tensorflow as tf
import numpy as np
class PolicyGradient(object):
def __init__(self,
n_actions,
n_features,
learning_rate=0.01,
reward_decay=0.9,
output_graph=False,):
self.n_features = n_features
self.n_actions ... |
from bs4 import BeautifulSoup
import requests
import threading
import urllib
import random
import time
import json
# цена, ниже которой тебе необходимо вносить предмет в список частообновляемых
price_for_update = 100
# каждые сколько минут обновлять итемы которые имеют цену ниже цены указанной выше
minutes_... |
# Copyright (C) 2013-2014 Computer Sciences 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 a... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
from proxy_spider.items import Proxy
from service.proxy.proxy import blocking_proxy_sr... |
# cording: utf-8
import cv2
import math
import numpy as np
file_src = 'img_01.jpg'
file_dst = 'file/dst.jpg'
img_src = cv2.imread(file_src , 1)
cv2.namedWindow('src')
cv2.namedWindow('dst')
#ここに核となる処理を記述する
#img_dst = cv2.flip(img_src, flipCode = 0) #垂直反転
size = tuple(np.array([img_src.shape[1], img_src.shape[0]]... |
import numpy as np
from lanehelper import line_finding
from ImageUtils import *
from Line import Line, calc_curvature
#/// \Tracks lane lines on images or a video stream using techniques like Sobel operation,
#/// \color thresholding and sliding histogram.
class LaneDetector(line_finding):
def __init__(self, ... |
from pathlib import Path
import tensorflow as tf
import numpy as np
import tensorflow.keras as keras
def get_network():
pool_size = (2, 2)
kernel_size = (3, 3)
input_shape = (60, 41, 2)
num_classes = 10
keras.backend.clear_session()
model = keras.models.Sequential()
model.add(tf.keras.lay... |
# -*- encoding: utf-8 -*-
from tl.parser.context import Context
from tl.bnf import Language
from tl import ast
class Parser(object):
_context = None
def parse(self, filename):
context = Context(filename)
main_scope = context.beginScope(
ast.SCOPE_TYPES['package'],
nam... |
#!/opt/murmanov/bin/python
import paramiko
import time
import smtplib
vpnlist = "/opt/NetAutomation/vyos/VPN-LIST-FULL"
result = ""
hostnames = [line.rstrip('\n') for line in open(vpnlist)]
def disable_paging(contact_shell):
'''Disable paging'''
contact_shell.send("set terminal length 0\n")
time.sleep(1... |
#===============================================================================
# Plot_IT_File.py
# Python script for plotting the data from the IT Curve files that were generated by the IV Curve text files
# created by the "Tapping_IV_browser - log - 4Gfit copy - Modified for Saving IV Files.vi" LabVIEW Program.
# Op... |
from django.db import models
from user_profile.models import UserProfile
class WalkingTrackerSession(models.Model):
user_profile = models.ForeignKey(UserProfile, related_name="sessions", on_delete=models.CASCADE)
start_date_time = models.DateTimeField()
end_date_time = models.DateTimeField()
class Walk... |
import numpy as np
import re
import pickle
import os
#============================================ CREATE DICTIONARY ==================================
# used to store the captions list w.r.t to image_name as key.
captions_dict = {}
# open the file in read mode.
with open('captions.txt','r') as f:
for line... |
from testflows.core import *
from testflows.asserts import values, error, snapshot
from window_functions.requirements import *
from window_functions.tests.common import *
@TestOutline(Scenario)
@Examples("func", [
("count(salary)",),
("min(salary)",),
("max(salary)",),
("sum(salary)",),
("avg(salary)",... |
import csv
import numpy as np
import math
FILE = '../logs/StAT-paper.csv'
# note that bins are in log space
def getBins():
delta = 0.1
return np.arange(-.3, 1.0 + delta, step=delta)
def getIndex(bins, v):
if v < bins[0]:
return 0
if v > bins[-1]:
raise Exception('value out of range: ', v, bins[-1])
# who ca... |
# -*- coding: utf-8 -*-
# @Author: Jie Yang
# @Date: 2017-10-17 16:47:32
# @Last Modified by: Jie Yang, Contact: jieynlp@gmail.com
# @Last Modified time: 2017-12-06 23:24:42
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class CNN(nn.Modul... |
#
# Copyright (c) 2015, Prometheus Research, LLC
#
import sys
from rex.core import Error
from rex.ctl import RexTask, argument, option, log
from .introspect import get_table_description
from .load import import_tabular_data
from .marshal import FILE_FORMATS, FILE_FORMAT_CSV, make_template
__all__ = (
'Tabular... |
import flask
import sqlalchemy
from ruddock import auth_utils
from ruddock import email_templates
from ruddock import email_utils
from ruddock import misc_utils
from ruddock import validation_utils
def get_user_data(user_id):
"""Returns user data for the create account form."""
query = sqlalchemy.text("""
SEL... |
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
arr=list(s)
n= len(arr)
arr2=[]
arr2[:]=arr[::-1]
# print(arr)
# print(arr2)
t=[[0 for i in range(n+1)] for j in range(n+1)]
maxi=0
a,b=0,0
for i in range(1,n+1):
... |
a=float(input("area:"))
if(a >= 0 and a <= 100):
valor = a* 2+ 100
elif (a >= 10 and a <= 250):
valor = a * 1.80+ 150
elif(a>=100 and a <= 2500):
valor= a * 1.50 + 200
elif (a >= 2500 and a <= 10000 ):
valor = a* 1.50+250
else:
valor = a*1.20+250
print(round(valor, 2))
|
from page.search_Yahoo import SearchYahooPage
from page.result_Yahoo import ResultYahooPage
def test_search_yahoo(browser):
PHRASE = 'Hitruk'
search_page = SearchYahooPage(browser)
search_page.load_page()
search_page.input_phrase(PHRASE)
result_page = ResultYahooPage(browser)
assert result_... |
f = open('mbox-short.txt', "r")
lines=f.read().splitlines()
count=0
for line in lines:
if line[0:5]=="From ":
count=count+1
line_list=line.split()
print(line_list[1])
print('Number of lines is '+str(count)) |
'''
Run main ETL application process
'''
import wmt_etl.run as job
def main():
'''Main application entrypoint'''
job.run()
if __name__ == '__main__':
main()
|
import os
import json
import uuid
import unittest
from pyserver.core import *
TEST_HELLO = """Hello, {{name}}"""
TEST_HELLO_JSON = """{\"message\": "Hello, {{name}}"}"""
TEST_TEMPLATES = [
dict(name="hello.html", content=TEST_HELLO),
dict(name="hello.json", content=TEST_HELLO_JSON),
]
class T... |
#coding: utf-8
import math
import heapq
import bisect
import numpy as np
from collections import Counter, deque
#from scipy.misc import comb
H,W = map(int, input().split())
if H%3 == 0:
print(0)
elif W%3 == 0:
print(0)
else:
ans = H*W
A = [0]*3
for i in range(1,H):
A[0] = i*W
A[1] ... |
from project.core.model import save_models
from project.utils.directories import Info as info
from project.utils.data_helper import save_data
from project.utils.services import timestamp
from tensorflow.python.keras.utils import to_categorical
from tqdm.auto import tqdm
import numpy as np
def train(epochs, full_model... |
#PRAPHULL KUMAR (204271732)
#LAKSHMAN KRISHNAMOORTHY (604354810)
#ATHARAV (504271368)
#This script will read all answer details from each question url
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import Elemen... |
from entityEvaluator import get_cosine
from entityEvaluator import text_to_vector
# actualList={}
# estimatedList={}
entitylist=['model','brand','onlinestore','number','amount_of_money']
# actualList['person']=['Victor Charles Goldbloom','Alton Goldbloom','Goldbloom','Annie Ballon']
# actualList['Location']=['Mont... |
from csv import DictReader
def find_user(first_name, last_name):
with open("users.csv") as file:
csv_reader = DictReader(file)
for (index, user) in enumerate(csv_reader):
if user['First Name'] == first_name and user['Last Name'] == last_name:
print(index)
... |
"""File to vector function"""
from input_functions import *
from nlp_functions import *
# from random import random
def file_to_vector(file_name):
"""takes file_name and creates vector out of it"""
output_vector = {}
line_clusters = line_cluster(split_meta_data(file_to_list(file_name))[1])
# vect_appe... |
# Norton Pengra - npengra317@gmail.com
import io
import os
import csv
import asyncio
import argparse
import requests
import concurrent.futures
from urllib.parse import urlparse
from bs4 import BeautifulSoup
VERBOSE = False
def debug(*args, **kwargs):
if VERBOSE:
print(*args, **kwargs)
class LinkCheck... |
# Copyright (c) 2014--2019 Muhammad Yousefnezhad
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... |
from os import path,makedirs
import json
from MyAccounting.attributes import *
from MyAccounting.externaldata import cb
import datetime
class engine():
__slots__ ='config_path','config_empty','config','config_filename','driver'
def __init__(self, config_path:str):
self.config_filename='MyAccounting... |
# coding=utf-8
from navigation.views import HomeNavigationView, NavigationDetailView
from .models import Page
class PageDetailView(NavigationDetailView):
model = Page
trail_parent = HomeNavigationView
def get_trail_nodes(self):
trail = super(PageDetailView, self).get_trail_nodes()
return ... |
#create code to show where you are during the day using 3 variables
time = 100
place_of_work = "Manchester"
town_of_home = "Rossendale"
if time > 1800 or time < 800:
print("I am in " + town_of_home)
elif time >= 900 and time <= 1700:
print("I am in " + place_of_work)
else:
print("I am commuting... |
#!/bin/env python
import glob
datapath = '/scratch/02727/cdw2854/cellProject/shortReads/tophat/mergedBam'
resultpath = '/scratch/02727/cdw2854/cellProject/shortReads/tophat/mergedBam/uniqueBam'
for bam in glob.glob(datapath + '/*bam'):
samplename = bam.split('/')[-1].split('.')[0]
command = 'samtools view -b... |
import sys
import os
import logging
import time
import signal
import argparse
import errno
import functools
import asyncio
import aiohttp
from stagehand import web, logger, tvdb, __version__
from stagehand.manager import Manager
from stagehand.config import config
from stagehand.toolbox import singleton
from stagehan... |
import sys, os
import unittest
sys.path.append(os.path.abspath('../'))
from housinginsights.ingestion.DataReader import DataReader
from housinginsights.tools import dbtools
from housinginsights.ingestion import DataReader, ManifestReader
from housinginsights.ingestion import CSVWriter, DataReader
from housinginsights... |
#files
#operations
#1.read r
#2.write w
#3.append a
#file reference
#--------------
#f=open("file path","name of operation")
|
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
FLAG_MAP = {
'add': ADDITION,
'edit': CHANGE,
'delete': DELETION,
}
# logs any action on a database record to django's adm... |
# -*- mode: python -*-
# vi: set ft=python :
load("@drake//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "common_robotics_utilities",
srcs = [
"src/common_robotics_utilities/base64_helpers.cpp",
"src/common_robotics_utilities/c... |
#!/usr/bin/env python
import sys
import getopt
from subprocess import Popen, PIPE
from math import log10
import re
from os import kill
from signal import alarm, signal, SIGALRM, SIGKILL, SIGQUIT
from reportlab.graphics.charts.legends import TotalAnnotator
def run(args, cwd=None, shell=False, kill_tree=True, timeout=... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/12/17 05:31'
from heima_chuanzhi.advance.num import *
print(num)
# print(_num2) # cannot use
# print(__num3) # cannot use |
# Generated by Django 3.1.7 on 2021-03-10 04:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('report', '0001_initial'),
('patient', '0001_initial'),
]
operations = [
migrati... |
# Write your tests here. Based on several users' opinion pytest is the right choice: http://pytest.org/latest/
import myproject
import re
#----------------------------------------------------------------------
def test_version():
m = re.match('^(\d+)\.(\d+)\.(\d+)$', myproject.__version__)
assert m != None
... |
from utilities.Funciones import verificarLlave
class Dosis:
def __init__(self):
self.id = ""
self.animal = ""
self.medicamento = ""
self.enfermedad = ""
self.rangoPeso = ""
self.dosis = ""
self.STATUS = {"borrar": False, "actualizar": [False, {}, "idAnterior"... |
class Stack:
def __init__(self):
self.stack = []
def __str__(self):
return '[' + ', '.join(str(e) for e in self.stack) + ']'
def push(self, value):
self.stack.append(value)
def pop(self):
try:
to_return = self.stack[len(self.stack)-1]
del self.s... |
# Generated by Django 3.0.5 on 2020-04-09 00:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='game',
name='away_score',
... |
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS pracownicy (
id INTEGER PRIMARY KEY,
imie varchar(250) NOT NULL,
nazwisko varchar(250) NOT NULL,
stanowisko varchar(250) NOT NULL,
email varchar(250) NOT NULL,
... |
POLICY_KEYWORDS = {
"A Safe and Fair City": [
"safe and fair city",
"safe",
"public safety",
"safety",
"nypd",
"police",
"cops",
"crime",
"violence interrupter",
"violence",
"commissioner",
"justice",
"eric garne... |
# The data we need to retrieve.
# The total number of votes cast
# A complete list of candidates who received votes
# The percentage of votes each candidate won
# The winner of the election based on popular votes
import datetime
now=datetime.datetime.now()
print("The time right now is",now)
import os
import csv
file_to... |
from rest_framework import serializers
from blog.models import Category, Tag, Post
class CategorySerializer(serializers.ModelSerializer):
class Meta:
fields = ('name', 'created_at')
model = Category
class TagSerializer(serializers.ModelSerializer):
class Meta:
fields = ('name', 'c... |
import sys
INT_LIMIT = 65535
def andi(a, b):
return a & b
def ori(a, b):
return a | b
def lsli(a, b):
return a << b
def lsri(a, b):
return a >> b
def comi(a):
return INT_LIMIT - a
try:
with open(sys.argv[1]) as fileInput:
#Take each line from fileInput and split it up at ... |
species(
label = 'C=C[CH]CC[O](18939)',
structure = SMILES('[CH2]C=CCC[O]'),
E0 = (164.829,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2783.33,2816.67,2850,1425,1450,1225,1275,1270,1340,700,800,300,400,2995,3025,975,1000,1300,1375,400,500,1630,1680,3000,3100,440,815,1455,1000,245.... |
from typing import Dict, Optional, Union, Tuple, List
import yaml
import sys
TieredDict = Dict[str, Union[Optional[str], 'TieredDict']]
def tiered_extract(db: TieredDict) -> List[Tuple[List[str], str]]:
"""From a nested dictionary, return a list of (key_path, values)
of the deepest level."""
out = []
for name... |
import logging
import traceback
import xmltodict
LOGGER = logging.getLogger()
class BadMessageHandler:
def __init__(self, component_name, sqs_client, bad_message_queue_url, input_queue_arn):
self.sqs_client = sqs_client
self.bad_message_queue_url = bad_message_queue_url
self.input_queue... |
import unittest
import monkey
class TestMonkey(unittest.TestCase):
def test_get_random_text(self):
text = monkey.get_random_text(10)
self.assertTrue(isinstance(text, str))
self.assertEqual(len(text), 10)
text = monkey.get_random_text(0)
self.assertEqual(text, "")
s... |
from base_api_model import *
class User(BaseApiModel):
pass
if __name__ == '__main__':
b = User({'name': 'Waldo', 'email': 'uribe.fache@gmail.com'})
print b.save() |
#!/usr/bin/env python
from __future__ import division, print_function
from optparse import OptionParser
import sys
hasFFTW = bool('@FFTW3_LIBRARY@')
parser = OptionParser()
parser.add_option("--version", action = 'store_true',
help = "output version (@vigra_version@)")
#parser.add_option("--targe... |
from scipy.linalg import expm
from scipy.sparse import csc_matrix
from angular_momentum import j_x, css_ground
def hamiltonian_oat(n, sqeezing_angle = 0):
return sqeezing_angle / 2 * (j_x(n) * j_x(n))
def unitary_oat(n, sqeezing_angle = 0):
m = -1j * hamiltonian_oat(n, sqeezing_angle=sqeezing_angle)
m ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import math
# import datetime as dt
metric_list = ['users', 'usersNew', 'usersOld', 'sessions', 'sessionsNew', 'sessionsOld', 'sessionsBounce',
'sessionsNoBounce', 'avgSessionDuration', 'pageviews', ... |
class Node:
def __init__(self, k, v):
self.val = v
self.key = k
self.pre = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capa = capacity
self.keys = {}
self.head = Node(0,0)
self.tail = Node(0,0)
self.hea... |
import torch.nn as nn
import torch
def get_loss_function(config):
try:
if config['type'] == "Charbonnier":
loss = L1_Charbonnier_loss(size_average=config['size_average'],
batch_average=config['batch_average'])
elif config['type'] == "Euclidean":
... |
# -*- coding: utf-8 -*-
"""
Leetcode utility module
Created on Sun Nov 11 11:50:34 2018
@author: Arthur Dysart
Miscellaneous functions and classes for Leetcode exercises.
"""
## REQUIRED MODULES
from collections import deque
## MODULE DEFINITIONS
class TreeNode:
"""
Manage Node objects for... |
# -*- coding: utf-8 -*-
from Products.CMFCore.utils import getToolByName
from plone.app.upgrade.utils import loadMigrationProfile
import logging
logger = logging.getLogger('plone.app.upgrade')
TOOLS_TO_REMOVE = ['portal_actionicons',
'portal_calendar',
'portal_interface',
... |
try:
import json
except ImportError:
import simplejson as json
import base64
import hashlib
import logging
import urllib
import httplib2
from django.conf import settings
from django.contrib.auth.models import User
log = logging.getLogger(__name__)
DEFAULT_HTTP_TIMEOUT = 5
DEFAULT_VERIFICATION_URL = 'https:... |
import numpy as np
from core import estadistica # RGB2Gray
from core import etiquetar # Etiquetar elementos imagen binaria
from core import morfo # Aplicar operaciones morfológicas
from core import common # Operaciones comunes
from matplotlib import pyplot as plt
from scipy.misc import imsave
plt.axis("off")
I... |
"""
Copyright 2013 Steven Diamond
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, software... |
# Importation librairie
import lcddriver
from time import sleep
import rfid
# Chargement du driver lcddriver
display = lcddriver.lcd()
def bonjour(stop_event, arg):
sleep(0.01)# certaine fois ça place a cause d'une erreur sur les pins
display.lcd_clear();
while not stop_event.wait(1):
display.lcd_d... |
#-*- coding: utf-8 -*-
import logging
log = logging.getLogger('ready_menu')
from cocos.director import director
from cocos.menu import *
from cocos.scene import Scene
#from lookup import BuildLookupTable, SortByName
import config
import constants
class ReadyMenu( Menu ):
def __init__(self):
super( Ready... |
from time import sleep
nome = ''
idade = []
sexo = ['M', 'F']
homens = 0
mulheres = 0
hvelho = 0
hveio = ''
m20 = 0
for c in range(1, 5):
print('='*10, 'DADOS DA {}ª PESSOA'.format(c), '='*10)
nome = str(input('Qual o nome? ')).strip()
inpuidade = int(input('Qual a idade? '))
idade += [inpuidade]
si... |
# Question 17:
# Write a Program to accept ‘n’ numbers and store all prime numbers in an array and display the array.
class Prime:
def check(self, p):
print("Prime numbers are\n")
for self.x in p:
self.flag = 0
for self.i in range(2, self.x):
if (sel... |
# _*_ coding: utf-8 _*_
from rest_framework import serializers
from blog.models import Post, Author, Tag
# serializer 类需要继承 serializers.Serializer,
# 然后实现父类的 update,create 方法
class PostSerializer(serializers.Serializer):
# 声明需要被序列化和反序列化的字段,同 model 的字段,
# 字段名注意需要同 model 字段同名
title = serializers... |
"""Project default for pytest"""
import os
import tempfile
import pytest
import re
import requests
from astropy.tests.plugins.display import PYTEST_HEADER_MODULES
from astropy.tests.helper import enable_deprecations_as_exceptions
# Uncomment the following line to treat all DeprecationWarnings as exceptions
enable_dep... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('auta/', views.SeznamAutView.as_view(), name='auta_list'),
path('autazak/', views.SeznamAutProZakView.as_view(), name='autazak_list'),
path('zakaznici/', views.SeznamZakaznikuView.a... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
categorydata = [
{
'name': 'Dress',
'subcate': [
{'name': 'Dress', 'items': ['Homecoming Dresses', 'Ball Gown Dresses', 'Formal Dresses', 'Designer Dresses',
'Fast... |
from unittest import TestCase
from copy import deepcopy
from app.questionnaires import Questionnaires
RAW_DATA = [
{
'id': 'foo',
'topics': [{
'topic': 'bar',
'questions': [
{
'label': 'baz',
'question': 'Deciding when... |
{
"targets": [
{
"target_name": "native-example",
"sources": [ "native-example.cc" ],
'conditions': [
[ 'OS!="win"', {
"cflags+": [ "-std=c++11" ],
"cflags_c+": [ "-std=c++11" ],
"cflags_cc+": [ "-std=c++11" ],
}]
]
}
]
} |
#-----------------------------------------------------------------------------------------------------------------
#Include libraries
#-----------------------------------------------------------------------------------------------------------------
import sys, getopt
import shutil
import subprocess
import os
import ran... |
#!/usr/bin/env python
import json
import math
import os
import sys
import re
import numpy as np
import pandas as pd
from datetime import datetime
if(len(sys.argv) <= 1):
print("No Excel File given!", flush=True)
sys.exit(1)
excel_data = sys.argv[1]
df = pd.read_excel(excel_data, header=1, usecols="A:I", skip... |
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from urllib.request import urlopen
from zipfile import ZipFile
def provide_PPMI_dataset(paths_dict={}, target_size=(109,91), batch_size=32):
def get_data_generators(paths_dict, batch_size, target_size):
'''
... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from .forms import CommentForm, PostForm
from .models import Follow, Gro... |
def solution(a, b):
if max(a) < min(b):
return 'No War'
else:
return 'War'
def main():
n, m, x, y = [int(i) for i in raw_input().strip().split()]
a = [x] + [int(i) for i in raw_input().strip().split()]
b = [y] + [int(i) for i in raw_input().strip().split()]
print(solution(a, b))... |
def sumdiags(n): # return the sum of the diagonals for a clockwise spiral of size n*n
diaglen = int(((n - 1) / 2) + 1)
ur, ul, dr, dl = 0, 0, 0, 0
for n in range(2, diaglen + 1):
ur += (n * n * 4) - (4 * n) + 1
dr += (n * n * 4) - (10 * n) + 7
ul += (n * n * 4) - (6 * n) + 3
... |
# -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2016-06-19 00:33:22
# @Last Modified by: yancz1989
# @Last Modified time: 2016-06-19 00:33:22
|
from config import chrome_path
from selenium import webdriver
import math
import time
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
def select_value():
try:
link = 'http://suninjuly.github.io/execute_script.html'
browser = webdriver.Chrome(chrome_path)
browser.maximize_... |
import pygame, os
pygame.image.load("")
LEFT=-1
RIGHT=1
FRONT=0
def bouncing_image(direction):
if direction==LEFT:
pygame.image.load(os.path.join('assets','front-deflated'))
pygame.time.delay(10)
pygame.image.load(os.path.join('assets','front-rount'))
pygame.time.delay(100)
... |
# Django
from django.conf import settings as _settings
def settings(request):
return {"settings": _settings}
def messages(request):
if hasattr(request, "_messages"):
messages = request._messages
else:
messages = []
return {"messages": messages}
|
import numpy as np
import matplotlib.pyplot as plt
import random
import pdb
'''
Monte Carlo simulation of the following problem:
If you make x% of your free throws in basketball, and you take y shots in a row, what's
the most likely maximum streak?
I'd like to get a closed-form answer, but I can't figure out how... |
import numpy as np
import mpi4py.MPI as MPI
import sys
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
if rank == 0:
x = np.linspace(0, 100, 11)
else:
x = None
# local
if rank == 2:
x_local = np.zeros(9)
else:
x_local = np.zeros(1)
# scatter
if rank == 0:
print("Scatter")
co... |
import operator
import functools
from utils import gctf_data_path
from utils import ComplexEncoder
import json
from pyspark.sql import DataFrame
from pyspark.sql import Column
import os
from pyspark.sql import SparkSession
from utils import read_tensor_data_from_hdfs
from pyspark.sql import functions as PysparkSQLFunct... |
"""
Module for dataset projection into pipelines. Defines transfer objects
returned from pipelines
"""
__author__ = "Elisha Yadgaran"
from abc import ABCMeta, abstractmethod
from typing import Optional
import numpy as np
import pandas as pd
from simpleml.datasets.base_dataset import Dataset
from simpleml.datasets.... |
import os
import matplotlib.pyplot as plt
from TB2J.spinham.spin_api import SpinModel
from TB2J.io_exchange.io_exchange import SpinIO
from TB2J.io_exchange.io_txt import write_Jq_info
from ase.dft.kpoints import monkhorst_pack
from ase.cell import Cell
import numpy as np
from TB2J import __version__
def write_emin(**k... |
__all__ = [
'PaginationSchema'
]
from marshmallow import fields, Schema, validate
class PaginationSchema(Schema):
page = fields.Integer(
missing=0,
validate=[
validate.Range(min=0)
]
)
per_page = fields.Integer(
missing=None,
validate=[
... |
from __future__ import print_function
#import tensorflow as tf
#import tensorflow.keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import matplotlib.pypl... |
import numpy as n
import ROOT as r
import math as m
from array import array
Training_Energies = n.array([10,20,30,40,50])
TrainPath = "/afs/cern.ch/user/r/rastein/TMVAFacility/TMVA_BDT_"
TrainType = "pi0_vs_photon_half2ndLayer_"
TrainMethod = "BDT_"
unit = "GeV"
def ExtractBGRejection(S, Energies):
Pi0Rej = []
... |
# Kør Main først for at hente de nødvendige dataframes
# Portfolios siger top - low til at lave LS. Så positiv skal have orderes asc så dem med flest kommer i top. Modsat for negativ.
# Først, lave portfølje til at teste sentiment returns
import Functions
import pandas as pd
dfPositiveSentimentPortfolios = Functions.s... |
from test import *
from utils.utils import *
from dataloader import *
from pathlib import Path
from torch.autograd import Variable
import pickle
from test_functions import detection_test
from loss_functions import *
parser = ArgumentParser()
parser.add_argument('--config', type=str, default='configs/config.yaml', help... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 09:30:59 2021
@author: Caven
"""
# The read4 API is already defined for you.
# def read4(buf4: List[str]) -> int:
class Solution(object):
def __init__(self):
self.q = []
def read(self, buf, n):
i = 0
while i < n:
... |
# -*- coding:utf-8 -*-
import logging
from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import validators
from django import forms as django_forms
from django.core.urlresolvers import reverse
from django.forms.utils import from_current_timezone
from openstack_das... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.