text stringlengths 8 6.05M |
|---|
# Generated by Django 2.0.7 on 2019-01-10 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basedata', '0048_auto_20190110_1318'),
]
operations = [
migrations.AddField(
model_name='outsource_items',
name='tot... |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import defaultdict
# couple of brute-force approaches
'''
def riddle(arr):
ln = len(arr)
res = []
#print(arr)
for l in range(1,ln+1):
tmp = []
for i in range(ln):
if i+l > ln:
... |
# Generated by Django 2.1.4 on 2019-01-14 20:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clientele', '0015_auto_20190114_2037'),
]
operations = [
migrations.AddField(
model_name='besoin',
name='ressource',... |
import time
from datetime import datetime
from random import random
import game_sound
from Score import Score
from features.feature import Feature
from field import Field
from highscorelist import Highscorelist, Highscoreentry
from painter import RGB_Field_Painter, Led_Matrix_Painter
BLACK = [0, 0, 0]
class Snake_M... |
# -*- coding: utf-8 -*-
from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField
from django.db.models import Count, Max
from django.utils.translation import ugettext_lazy as _
import datetime
from django.urls import reverse
from .settings_newsapp import ENABLE_ARCHIVE, ENABLE_CATEGORIES, N... |
import unittest
from class_methods import *
from delta import *
from dynamic import *
from indexes import *
from inheritance import *
from instance import *
from json_serialisation import *
from validation import *
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python3
import numpy as np
#import scipy.linalg
def vector_lengths(a):
return np.sqrt(np.sum(a**2, axis=1))
def main():
print(vector_lengths(np.random.randint(1, 8, (4, 5))))
if __name__ == "__main__":
main()
|
DEFAULT_SETTINGS = {
'AUTOCONFIG_URL_PREFIXES': {
'shorty': '',
},
}
SETTINGS = {
'INSTALLED_APPS': [
'django.contrib.admin',
'nuit',
],
'NUIT_GLOBAL_TITLE': 'Shorty',
'CSP_SCRIPT_SRC': (
"'self'",
"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.... |
# -*- coding: utf-8 -*-
import tkinter as tk # 使用Tkinter前需要先導入
# 第1步,產生實體object,建立視窗window
window = tk.Tk()
# 第2步,給窗口的視覺化起名字
window.title('My Window')
# 第3步,設定窗口的大小(長 * 寬)
window.geometry('500x300') # 這裡的乘是小x
# 第4步,在圖形介面上創建一個標籤label用以顯示並放置
var = tk.StringVar() # 定義一個var用來將radiobutton的值和Label的值聯繫在一起.
l = tk.Label(wi... |
lisnum = []
v = 0
while v == 0:
print ("Digite 0 para parar")
L = int(input('Insira os dados a ser acresentados a lista:'))
lisnum.append(L)
if L == 0:
lisnum.pop(0)
print(lisnum)
print ("O dado de menor valor encontrado foi", lisnum[0])
fim = lisnum... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
"""
__author__ = Hagai Hargil
"""
import attr
import numpy as np
import pandas as pd
from attr.validators import instance_of
from pysight.nd_hist_generator.movie import Movie, FrameChunk
from collections import deque, namedtuple
from typing import Tuple, Union
from numba import jit, uint8, int64
@attr.s(slots=True)
c... |
from django.db import models
class Story(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Page(models.Model):
story = models.ForeignKey(Story, on_delete=models.CASCADE)
text = models.TextField()
title = models.CharField(max_length=150)
... |
#!/usr/bin/env python
import rospy
import math
from andrewbot_msgs.msg import RobotCommand
from geometry_msgs.msg import Twist
from base_driver import BaseDriver
robot_base_pub = rospy.Publisher('andrewbot/RobotCommand', RobotCommand, queue_size=10)
robot_base = BaseDriver()
robot_command = RobotCommand()
def sent_ro... |
# Allow conans to import ConanFile from here
# to allow refactors
from conans.model.conan_file import ConanFile
from conans.model.options import Options
from conans.model.settings import Settings
from conans.client.build.cmake import CMake
from conans.client.build.meson import Meson
from conans.client.build.gcc import ... |
import doctest
from asyncio import gather, run
from math import sqrt
from async_lru import alru_cache
@alru_cache(maxsize=256)
async def fib(digit: int) -> int:
"""
>>> run(fib(10))
55
>>> run(fib(20))
6765
>>> run(fib(1))
1
"""
if digit == 0:
return 0
elif digit == ... |
from telethon import TelegramClient, sync, events
import random
import time
import threading
import asyncio
import utils
# start client with config file
params = utils.Params()
params.start_client()
print("Client runs...")
# set target users to respond
params.convert_str_targets_to_id()
params.set_targets_usernames()... |
from .redis import RedisInterface
from .utils import calc_ttl, parse_rate
from typing import Optional
class RateLimit:
def __init__(self, redis: RedisInterface):
self.redis = redis.pool
self.encoding = redis._encoding
async def _handling(
self, rate: str, key: str, value: str, incr: ... |
import sys
from collections import Counter
def has_conflict(c1, c2):
"""Return True if two rows of character table conflict."""
hasConflict = True
s1 = set(i for i, c in enumerate(c1) if c == '1')
s1c = set(i for i, c in enumerate(c1) if c == '0')
s2 = set(i for i, c in enumerate(c2) if c == '1')
... |
from selene.api import * |
N, M = map(int, input().split())
S = [ list(input()) for i in range(N)]
ans = 0
U = [ [0 for _ in range(M)] for _ in range(N)]
D = [ [0 for _ in range(M)] for _ in range(N)]
L = [ [0 for _ in range(M)] for _ in range(N)]
R = [ [0 for _ in range(M)] for _ in range(N)]
for i in range(N):
cnt = 0
for j in range(M)... |
#!/usr/bin/python
#\file inheritance_two.py
#\brief inheritance from two classes
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Jan.06, 2016
'''Define a space.
min and max should be list or None. '''
class TSpaceDef(object):
def __init__(self,dim=0,min=None,max=None):
self.D= dim
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: prog3
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (30/10-20... |
from typing import List
from .. import InvitesRepo
from ....domain.entities import Invite
class FakeInvitesRepo(InvitesRepo):
def __init__(self) -> None:
self.__invites: List[Invite] = []
def save(self, invite: Invite) -> Invite:
index = next((i for i, to_find_invite in enumerate(self.__invites) if to... |
#!/usr/bin/env python
import numpy as np
from math import *
class Atom:
def __init__(self,element,position_file,orb_pop): #define atom based on its element and a list of its valence AOs populations
#which is loaded as a list if ints, the ordering of valence oribitals
... |
import os, re
################## CHANGE HERE ONLY ##################
# Type of file that you want to update
# typeFile = PinSettingsPrg,
# IncItem,
# PropertyModelConfigurationXml,
# SignalConfigurationXml,
# HalPortBridgeV2Prg,
# All
# typeFile = "H... |
__author__ = "Micah Price"
__email__ = "98mprice@gmail.com"
import config
from keras.models import Sequential, load_model
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.utils.data_utils import get_file
from keras.optimizers import RMSprop
import praw
im... |
names = list()
votes = list()
sumVotes = 0
inFile = open('input.txt')
for line in inFile:
if len(line) < 2:
continue
else:
line = line.split()
partyName = ' '.join(line[:-1])
partyVotes = int(line[-1])
names.append(partyName)
votes.append(partyVotes)
sumVo... |
# Loaded by ~/.pdbrc, because .pdbrc can only contain pdb commands.
# Command line history.
import atexit, os, readline
histfile = os.path.expanduser("~/.var/pdb_history")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del histfile
readline... |
import time as timer
import heapq
import random
import networkx as nx
import numpy as np
import math
import matplotlib.pyplot as plt
from single_agent_planner import compute_heuristics, a_star, \
get_location, get_sum_of_cost, construct_MDD_for_agent, reconstruct_MDD, updateMDD
def detect_collision(path1, path2):
ti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_preprocessing
----------------------------------
Tests for `preprocessing` module.
"""
import pytest
from sktutor.preprocessing import (GroupByImputer, MissingValueFiller,
OverMissingThresholdDropper,
... |
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import pylab;
s = pd.Series([7,"Hesisenber",3.14,-92393929,'happy foo'], index = ['A','B','C']);
print(s); |
from django.shortcuts import render
from .models import Chef, Join
from manager.models import Restaurant
from django.http import HttpResponseRedirect
def render_orders(request, chef_id, res_id):
res = Restaurant.objects.get(id=res_id)
chef = Chef.objects.filter(restaurant=res).get(chef_id=chef_id)
joins =... |
# Generated by Django 3.2.4 on 2021-07-06 14:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pay', '0005_rename_payment_id_forms_order_id'),
]
operations = [
migrations.AddField(
model_name='forms',
name='made... |
# Generated by Django 2.2.4 on 2019-08-15 23:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0009_auto_20190815_2330'),
]
operations = [
migrations.AlterField(
model_name='pyproduct',
name='cost',
... |
import smtplib
from email.message import EmailMessage
from gsheet import authenticate
# USE THE AUTHENTICATION
client = authenticate("creds/creds.json")
# OPEN SHEET AND DO SOME MODIFICATIONS
sheet_url = "https://docs.google.com/spreadsheets/d/1DNKBYN3SQHPvjdy7eQ018t5HDaU-qDuzULcGqV5qJm8/edit#gid=408336874"
workbook ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-19 00:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('evesde', '0014_auto_20161019_0013'),
]
operations = [
migrations.AlterField... |
#!/usr/bin/python3
##生成一个六位的数字
import random
dir (random)
for i in range(6):
print (random.randint(0,9),end = "")
##随机生成1-100内的偶数
print (random.randrange(0,101,2))
##生成一个六位的数字和字母,其中第一位,第三位,第六位是随机字母
for i in range(6):
if i%2 == 0:
print (chr(random.randint(65,90)),end = "")
else:
print (i,end = "")
##生成0-4位随机... |
import math
import os
import random
import re
import sys
from dateutil.parser import parse
# Complete the time_delta function below.
def time_delta(t1, t2):
dt1 = parse(t1)
dt2 = parse(t2)
diff = int((dt1 - dt2).total_seconds())
if diff < 0:
diff = -diff
#print(diff)
return str(diff)
... |
#! /usr/bin/python
# -*- coding:UTF-8 -*-
import string
import os, sys
import glob
from PIL import Image
Model_list=['pedestrian','person','car','van','bus','trunk','motor','bicycle','awning-tricycle','tricycle']
# pedestrian, person, car, van, bus, truck, motor, bicycle, awning-tricycle, and tricycle
# 1. VEDAI 图像存储... |
__all__ = ["ex2", "setting"] |
from sys import argv, exit
# print("I know that these are the words the user typed on the command line: ", argv)
from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
alphaup = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphalow = "abcdefghijklmnopqrstuvwxyz"
new_out = ""
for letter in te... |
from queue import Queue
from unittest import TestCase
from unittest.mock import MagicMock, Mock, patch
from src.d3_network.command import Command
from src.robot.hardware.command.stm_command_definition import commands_from_stm
from src.robot.robot_controller import RobotController
class TestScenarioRobotController(Te... |
#coding:utf-8
from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from django.core.mail import send_mail
class Document(models.Model):
[...]
class Comment(models.Model):
[...]
def notify_admin(sender, instance, created, **kwargs):
'''Notify the a... |
import u12
d1 = u12.U12(serialNumber=100054654)
d2 = u12.U12(serialNumber=100035035)
print('d1')
for i in range(8):
print(d1.eAnalogIn(i))
print('d2')
for i in range(8):
print(d2.eAnalogIn(i))
|
# Python 3.x
# encoding="utf-8"
# terminal based script
# Search Archive & Folder with same name in given path
# for windows OS better run with admin rights to write results (cmd)
# or simply run archfs.py file in folder (open file)
# Author: Farid Kemyakov aka Rev3n4nt
# CoAuthor: Aziz Kemyakov aka DoomStal
import sy... |
Python2.7 安装以及安装pip
一、准备工作
1.下载Python源码包
$ wget http://python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 --no-check-certificate
2.查看是否安装make工具
$ rpm -qa|grep make
automake-1.11.1-4.el6.noarch
make-3.81-20.el6.x86_64
### 如果没有安装make工具
yum -y install gcc automake autoconf libtool make
3.查看是否安装zlib库
$ rp... |
from enum import IntEnum
from struct import pack, unpack
from attr import attr, attributes
from rv.errors import ModuleOwnershipError, PatternOwnershipError
from rv.lib.validators import in_range
from rv.modules.module import Module
class NOTE(IntEnum):
"""All notes available for patterns or mapping."""
(
... |
from numpy import pi
def deg2rad(d):
return d / 180 * pi
def rad2deg(r):
return r / pi * 180 |
"""Simulation of queuing models with simulus."""
from __future__ import absolute_import
import sys
if sys.version_info[:2] < (2, 8):
raise ImportError("QModels requires Python 2.8 and above (%d.%d detected)." %
sys.version_info[:2])
del sys
from .rng import *
from .mm1 import *
__version__... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: shoumuzyq@gmail.com
# https://shoumu.github.io
# Created on 16/2/17 23:49
def increasing_triplet(nums):
small = 9999999999
big = 9999999999
for num in nums:
if num <= small:
small = num
elif num <= big:
... |
""" Prometheus Client Metrics request handler """
from prometheus_client import multiprocess
from prometheus_client import generate_latest, CollectorRegistry, CONTENT_TYPE_LATEST
from .collect import collect_metrics
from ..web import base
class MetricsHandler(base.RequestHandler):
# NOTE: Unauthenticated due to i... |
#!/usr/bin/env python
# coding: utf-8
# In[18]:
import pandas as pd
import numpy as np
import tushare as ts
from time import sleep
import os
pro = ts.pro_api('7d1f3465439683e262b5b06a8aaefa886ea48aafe2cda73c130beb97')
#df = pro.trade_cal(exchange='', start_date='20180101', end_date='20181231')
#data = pro.stock_basi... |
from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'jimovpn.views.home', name='home'),
# ur... |
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture |
from random import randint
import datetime
x = []
counter = 0;
for num in range(0,100):
randomNumber = randint(0,10000)
x.append(randomNumber)
for j in range(0,len(x)):
minimum = x[j]
indexofmin = j
for i in range(j+1,len(x)):
if x[i] < minimum:
minimum = x[i]
indexofmin = i
temp = x[j]
x[j] = minimu... |
#imports
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
#locators and links
LOC_ADD_TO_BASKET_BUTTON = (By.CSS_SELECTOR, '[class*="btn-add-to-basket"]')
link = "http://selenium1py.pythonany... |
from memnet1 import MemNet
def main():
print("===> Building model")
model = MemNet(1, 64, 6, 6)
print(model)
if __name__ == "__main__":
main()
|
# Generated by Django 3.2.7 on 2021-10-05 02:15
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('reclamacoes', '0001_initial'),
]
operations = [
migrations.CreateModel(... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Mcal(NysolMOD_CORE):
_kwd ,_inkwd ,_outkwd = n_core.getparalist("mcal",3)
def __init__(self,*args, **kw_args) :
super(Nysol_Mcal,self).... |
import numpy as np
import matplotlib.pyplot as plt
import math
import itertools
from fnc import *
def f(x):
return (2 ** x) * ((x-1) ** 2) - 2
def f_d1(x):
return (2 ** x) * (-1 + x) * (2 - np.log(2) + x * np.log(2))
def f_d2(x):
return (2 ** x) * (2 - 4 * np.log(2) - 2 * x * (-2 + np.log(2)) * np.log... |
"""
Task 2
Input data:
Create a function which takes as input two dicts with structure mentioned above, then computes and returns the total price of stock.
"""
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}... |
# Generated by Django 2.2.4 on 2019-08-10 10:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('chandler', '0002_auto_20190810_0929'),
]
operations = [
migrations.AlterField(
model_name='cart... |
subject = ['audio&speech', 'nlp', 'vision', 'recommend']
all_subject_name = ''
# ----------------------------------------
# TODO : Concatenate all subject name.
# >>> audio&speech nlp vision recommend
for i in subject:
all_subject_name+= i+' '
print(all_subject_name)
# ----------------------------------------
if ... |
# Generated by Django 3.1.4 on 2021-01-12 04:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('products', '0003_auto_20... |
def SubArray(arr,s,n):
for i in range(n):
curr_sum=arr[i]
for j in range(i+1,n):
if(curr_sum==s):
print(i,j-1) # Bcz if condition is before the summing operation
return 1
curr_sum = curr_sum+arr[j] # summing operation
... |
import os
import pwd
import StringIO
import pandas as pd
from flask import Flask, render_template, make_response
import psycopg2
import psycopg2.extras
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.dates import DateFormatter
from matplotlib.figure import Figure
from sqlalchemy import cr... |
from setuptools import setup
setup(
name='jb-everything',
version='0.1.0',
packages=['jb_everything'],
url='https://pypi.org/project/jb-everything/',
license='MIT',
author='jeromebaum',
author_email='jerome@jeromebaum.com',
description='Large list of imports for machine learning.',
... |
import pysam
import sys
import pdb
import os
#this extracts reads that map to a valid cell (from a given list of valid barcodes) from a sorted and indexed .bam and writes them to a .sam file
#Author: Anika Neuschulz
if len(sys.argv) == 4:
ifn = sys.argv[1]
cell_barcode_file = sys.argv[2]
mapper = sys.argv... |
import sys
if __name__ == "__main__":
rl = lambda : sys.stdin.readline()
d = []
for _ in xrange(int(rl())):
input = rl().split()
n, str = int(input[0]), input[1]
d.append(str[:n-1]+str[n:])
for i, v in enumerate(d):
print i+1, v
|
class Mount:
def __init__(self, src, dst):
self.src = src
self.dst = dst
def build(self, script):
script.mount(self.src, self.dst)
|
import numpy as np
import pandas as pd
# import glob
import re
import csv
from rank_bm25 import BM25Okapi
# from nltk.corpus import stopwords
# from nltk.tokenize import word_tokenize
# from sklearn.cluster import KMeans
from modules.functions import ensureUtf
from modules.functions import clean_text
fro... |
import pandas as pd
import numpy as np
import tensorflow as tf
FEATURES = ["PassengerId" ,"Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"]
LABEL = "Survived"
FILE_TRAIN = "titanic_train.csv"
FILE_TEST = "titanic_test.csv"
FILE_PREDICT = "titanic_predictions.csv"
def input_fn(file_path... |
# Generated by Django 2.2.12 on 2020-05-02 19:10
from django.db import migrations, models
import src.incidents.models
import uuid
class Migration(migrations.Migration):
dependencies = [
('incidents', '0047_cannedresponse_sendcannedresponseworkflow'),
]
operations = [
migrations.RemoveFi... |
# -*- coding: utf-8 -*-
"""
@author: Duy Anh Philippe Pham
@date: 14/05/2021
@version: 2.00
@Recommandation: Python 3.7
@Révision : 11/06/21
@But: comparaison barycentre avancées
- Permet de comparer le barycentre avec le sujet moyen en comparant la position des maximums locaux
"""
import numpy as np
import sys
import ... |
# -*- coding: utf-8 -*-
#
# * Copyright (c) 2009-2015. Authors: see NOTICE file.
# *
# * 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... |
#!python
############################################################
##### This is a recursion example using fibonacci sequence
############################################################
def fibonacci(n):
"""fibonacci(n) returns the n-th number in the Fibonacci sequence,
which is defined with the recurren... |
import time
print('-'*65)
print('Bouncer Bot:')
print()
print('Welcome to CLUB425,the most lit club in downtown ACTvF. Before you can enter, I need you to answer some questions...')
x = input('What is your age today? ')
if x >= '21':
print('Welcome... to the club.')
if x <= '21':
print('Filthy CHILD!')
print('C... |
import PIL
import numpy as np
import numpy as np
from PIL import Image, ImageDraw
try:
import Image
except ImportError:
from PIL import Image
def shape_to_mask(img_shape, points, shape_type=None,
line_width=10, point_size=5):
mask = np.zeros(img_shape[:2], dtype=np.ui... |
#!/usr/bin/env python3
import random
print('please enter the Dice you want to roll in the Format ndx,')
print('where n is the count of dices, and x is the number of possible values of the dice, e.g. 2d6')
diceRaw = input()
diceList = diceRaw.split("d")
diceFaces = int(diceList[1])
diceCount = int(diceList[0])
diceOut ... |
#!/usr/bin/env python
## Script is used to generate training and validation datasets from sph files
from .clip import audio_clip
import argparse
parser = argparse.ArgumentParser("generate training data")
parser.add_argument("--dir", type=str, help="input folder name",
default="data")
parser.add_argument("--num", type=... |
from jinja2 import Markup
from functools import partial
from orun.db import models
from orun import app
from orun import render_template
#from orun.template.loader import select_template
def render_field(model_name, field_name, **ctx):
model = app[model_name]
field = model._meta.fields[field_name]
templat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Logic operator, 逻辑运算操作符。
"""
# 与
assert (True & True) == True
assert (True & False) == False
assert (False & True) == False
assert (False & False) == False
assert (True and True) == True
assert (True and False) == False
assert (False and True) == False
assert (False ... |
import re
import json
import logging
import pymysql
from scrapy import Spider, Request
from instagram_crawler.items import InstagramProfileItems
from instagram_crawler.user_cache import UserCache
logger = logging.getLogger(__name__)
class Instagram(Spider):
BASE_URL = "http://www.instagram.com/"
start_urls=[]... |
from django.contrib import admin
from .models import Productos, Proveedores, ContactoProveedores, TelefonosContactoProv, Servicios, Categoria, PreciosVentaServicio, PreciosVentaProducto
# Register your models here.
admin.site.register(Productos)
admin.site.register(Proveedores)
admin.site.register(ContactoProveedore... |
from pprint import pprint
import xml.dom.minidom as minidom
import xml.dom
from xml.dom.minidom import Element
from xml.dom.minidom import NodeList
from log_4_j.event import Event
from log_4_j.dom_location_info import DomLocationInfo
class DomEvent(Event):
def __init__(self, dom_element: Element) -> None:
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import math
#영어 끝말잇기
words=["tank","kick","know","wheel","land","dream","mother","robot","tank"]
#words=["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"]
#wo... |
# -*- coding: utf-8 -*-
import time
import random
from scrapy.http import HtmlResponse
from scrapy import signals
from fake_useragent import UserAgent
class MultoneSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not m... |
class Pair(object):
def __init__(self, a ,b):
self.a = a
self.b = b
def maxChainLength(arr, n):
max = 0
mcl = [1 for i in range(n)]
for i in range(1,n):
for j in range(0, i):
if (arr[i].a > arr[j].b and mcl[i] < mcl[j] + 1):
mcl[i] = mcl[j] + 1
... |
def collatz(number):
if number % 2 == 1 and number > 1:
num = 3*number + 1
print(num)
return num
elif number % 2 == 0:
num = number // 2
print(num)
return num
n = int(input('Enter a number: \n'))
while True:
n = collatz(n)
if n ==... |
from django.forms import ModelForm
from django import forms
from models import *
class ParticipanteForm(ModelForm):
class Meta:
model = Participante
class InscricaoForm(ModelForm):
class Meta:
model = Inscricao
|
# -*- coding: utf-8 -*-
def test_vehicles(fake, vehicles):
assert len(vehicles) > 1
v = vehicles[0]
assert 'Make' in v.keys()
assert 'Model' in v.keys()
def test_make(fake, makes):
make = fake.vehicle_make()
assert len(make) > 1
assert make in makes
def test_year(fake, years):
year ... |
# -*- coding:utf-8 -*-
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board: return False
if not word: return False
for i in range(len(board)):
for j in range(l... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-11-03 23:12
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('bot', '0005_auto_20161103_2107'... |
class Aircraft:
"""Represents an aircraft"""
__MIN_FUEL = 100
def __init__(self, flight_number="", code: str = None, units: str = None, range_max: int = None):
# Confirm what columns should be implemented for this Aircraft class.
self.code = code
self.units = units
self.ran... |
# %%
import os
import sys
# Local tools -----------------------------------
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'tools')) # noqa
from MEG_worker import MEG_Worker
# %%
worker = MEG_Worker(running_name='MEG_S01')
worker.pipeline(band_name='U07')
|
import numpy as np
a = np.array([[0.23875153, 0.58318603, 0.5816853, 0.19389093, 0.67800844], [0.20469368, 0.59248257, 0.38294148, 0.17688346, 0.89432704]])
b = np.array([[1, 0, 0, 0, 0], [0, 1, 0 , 0, 0]])
print(a - b)
c = (a - b)**2
print(c)
print(np.sum(c, axis=1) / 5)
print(np.mean(c, axis=1))
print(np.mean(np.su... |
# !pip install ogb
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from ogb.linkproppred import LinkPropPredDataset, Evaluator
from logger import Logger
hasGPU = torch.cuda.is_available()
def gpu(x):
return x.cuda() if hasGPU else x
clas... |
"""Miscellaneous utilities."""
from .consolidate_merge import consolidate_merge
from .strip_end import strip_end
# adapted from https://stackoverflow.com/a/31079085
__all__ = [
'consolidate_merge',
'strip_end',
]
|
import random
import copy
from matplotlib import pyplot as plt
import numpy as np
import csv
#----------------------------GLOBAL VARIABLES-----------------------#
p = 150 #population size
numR = 5 #number of rules
conLen = 6 #rule condition length
n = numR * (conLen+1) #gene size (set to num rules * condition and outp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.