text stringlengths 8 6.05M |
|---|
from django.contrib import admin
from django.urls import path,include
from home import views
urlpatterns = [
path('' , views.home,name ='home'),
path('contact', views.contact,name ='contact'),
path('aboutus',views.aboutus,name='aboutus'),
path('serach', views.serach, name='serach'),
]
|
# -*- coding: utf-8 -*-
import nltk
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
from textblob import TextBlob
from itertools import groupby
from operator import itemgetter
from collections import Counter
st = StanfordNERTagger(
'./stanford-ner/classifiers/english.all.3class.dis... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 12:38:01 2019
@author: xabuka
"""
import loading
max_features = 10000
maxlen = 100
training_samples = 1000 # We will be training on 200 samples
validation_samples = 2000 # We will be validating on 10000 samples
data_dir = '../data/SplitedPalS... |
from .tasks import Task
from .tasks import serialize_task, deserialize_task, serialize_tasks, deserialize_tasks
from .repository import Repository
|
from model.test import test
from controller.webServices import webServices
class testController():
def createTest(hill, city):
vytvorenyTest = test(1, hill, city)
def addQuestion(pointA, pointB):
webServices.findDistance(pointA, pointB)
print("Question len: " + str(test.questions.__le... |
CREATE TABLE `start` (
`id` int(11) NOT NULL,
`начало` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `start` (`id`, `начало`) VALUES
(1, 'герои '),
(2, 'предметы'),
(3, 'справочник'),
(4, 'пикер');
CREATE TABLE `simple items` (
`id` int(11) NOT NULL,
`простые предметы` varchar(100) N... |
# Generated by Django 2.2.7 on 2019-11-09 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Sneakers',
fields=[
('id_sneaker', models.A... |
# coding=utf-8
# Apache Solr 全版本任意文件读取
# Fofa:app="Apache-Solr" || app="Solr"
import requests
import json
import sys
import time
def title():
print("+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+")
print("+~~~~~~ Apache Solr 全版本任意文件读取 ~~~~~~+")
print("+~~~~~~ Use: python3 solr.py ~~~~~~+")
print("+~~~~~~ u... |
from be.model import store
import sqlite3 as sqlite
import logging
#判断商品是否还有库存
def check_num(goodsId, goodsNum):
try:
conn = store.get_db_conn()
cursor = conn.execute(
"SELECT goodsNum from goods where goodsId=?",
(goodsId),
)
row = cursor.fetchone()
... |
import unittest
import numpy
import six
from six.moves import cPickle as pickle
from smqtk.representation.data_element.memory_element import DataMemoryElement
from smqtk.representation.descriptor_element.local_elements import \
DescriptorMemoryElement
from smqtk.representation.descriptor_index.memory import Memor... |
#!/usr/bin/python2
import commands
import cgi,cgitb
print "Content-type : text/html"
print ""
cgitb.enable()
x=cgi.FieldStorage()
user=x.getvalue('usr')
password=x.getvalue('passwd')
hd=x.getvalue('hd')
#for radio button
n=x.getvalue('x')
commands.getoutput("systemctl restart httpd")
commands.getoutput("setenforce 0"... |
#!/usr/bin/python
"""
Provides ability to control the motors using two controllers on the robot.
"""
import logging
import MotorController
MODULE_LOGGER = logging.getLogger("__main__.DualMotorController")
class DualMotorController(object):
"""
Provides ability to control the motors on the robot.
"""
... |
# -*- coding: utf-8 -*-
import csv, sys, pytz, datetime
import psycopg2
import uuid, calendar
import logging
import re
def localice(date):
if date.tzinfo is not None:
return date
timezone = "America/Buenos_Aires"
tz = pytz.timezone(timezone)
local = tz.localize(date)
return local
def rep... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 13:48:17 2017
@author: dgratz
"""
from plotBeat2beatCLGrid import b2bCL
from plotSynchronyMeasure import b2bSync
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from glob import glob
import re
folders = glob('D:/sync... |
import unittest
import json
from elasticsearch import helpers, Elasticsearch, TransportError
from flask import current_app as app
import numpy as np
from app.main import db
from app.test.base import BaseTestCase
from app.main.lib.shared_models.shared_model import SharedModel
class TestSimilaryBlueprint(BaseTestCase):... |
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: convert_dots_to_bbox.py
# Author: wdf
# Date: 2019/7/18
# IDE: PyCharm
# Parameters:
# @param:
# @param:
# Return:
#
# Description:
# Usage:
#---------------... |
#for matrices and solving linear equations
import numpy as np
#future vector
F1 = np.array([1800, 900])
F2 = np.array([1100, 1500])
#b vector
B = np.array([1, 1])
#present
X = np.array([[200, 700],
[300, 100]])
for i in range(3):
#ne3awd bel B
A = np.dot(np.linalg.inv(X * B.reshape(1, 2)), F1... |
import socket
from urllib import error,request
try:
response = request.urlopen('http://zhaojiaxing.top/',timeout=0.01)
except error.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):
print('time out') |
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("/home/mmc/code/python_opencv/Books/Practical Python and OpenCV, 3rd Edition/code/images/trex.png")
cv2.imshow('platjeta', img)
img[0:100,0:100] = (0,0,255)
cv2.imshow('modified', img) |
class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self,A):
s = A.split(' ')
s = s.rstrip()
length = len(s)
if(length == 0):
return 0
if(length == 1):
return len(s[0])
else:
return len(s[length-1])... |
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtCore import QUrl
import time
from StatusCode import *
MUSIC_PATH = r'H:\Projects\PyCharmProjects\MusicPlayer\Music\排骨教主 - 牵丝戏.mp3'
# PLAYER_STATE_STOP = 0
# PLAYER_STATE_PLAY = 1
# PLAYER_STATE_PAUSE = 2
class Player():
def __init__(self):
... |
import numpy as np
## constants = {k: None, alpha: None, k_a:-, alpha_a:-, k_s:-, alpha_s:-, dmax:-, exp_type:-, p:-}
class DpwNode(object):
def __init__(self,parent,depth,constants,k,a,init_n=0):
## Tree data
self.parent = parent
self.children = []
self.exploration_type = constants['exploration_type']
#... |
import numpy as np
import pandas as pd
from KNearestNeighbor import KNearestNeighbors
#taking inputs
data=pd.read_csv('Social_Network_Ads.csv')
data['Gender'] = data['Gender'].replace({'Male': 0, 'Female': 1})
X=data.iloc[:,1:4].values
y=data.iloc[:,-1].values
print(X.shape)
print(y.shape)
#using train_test_split f... |
import random
from objects import *
sizes = [1,2,3,2,1,2,4]
class App:
def __init__(self):
self._running = True
self._display_surf = None
self.size = self.width, self.height = 800, 600
self.delta_time = 0
self.internal_clock = 0
self.last_frame_tic... |
highest_star = int(input())
current_star = 0
# Ascending
while current_star < highest_star:
current_star += 1
for star in range(1, current_star + 1):
print("*", end= "")
print()
# Desending
while highest_star > 1:
highest_star -= 1
for star_2 in range(1, highest_star + 1):
print("*"... |
import os, re, glob, sys, argparse
from string import Template
class Braced(Template):
pattern = r"""
%(delim)s{(?P<braced>%(id)s)} |
(?P<escaped>^$) |
(?P<named>^$) |
(?P<invalid>^$)
""" % dict(delim=re.escape(Template.delimiter), id=Template.idpattern)
def regen():
parser = argparse.Argu... |
import numpy as np
from cmath import sqrt
def check_limit(point, xp, yp, acc=1e-5):
""" Function that checks whether or not a point is within a certain range of an
x and y coordinate. The input parameter 'point' gives the point that has to
be checked. 'xp' and 'yp' give the coordinates to which th... |
import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext as _
# Create your models here.
class Profile(AbstractUser):
birthday = models.DateField(_('Birthday'), default=datetime.date.today)
genderlist = (
(1, 'Man'),
... |
"""This is a program to evaluate the restaurant grades of NYC establishments across New York City."""
#author: Matthew Dunn
#netID: mtd368
#date: 12/06/2015
import os
import sys
from dataloader import *
from dataanalyzer import *
from visualizer import *
def main():
try:
while True:
try:
... |
import numpy as np
def dict_mean(dict_list):
mean_dict = {}
for key in dict_list[0].keys():
value = []
for i in dict_list:
value.append(i[key])
mean_dict[key] = np.mean(value)
return mean_dict
|
import pydeck as pdk
import datetime
import bar_chart_race as bcr
import math
import altair as alt
from altair import Chart, X, Y, Axis, SortField, OpacityValue
import plotly.figure_factory as ff
import matplotlib.pyplot as plt
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pan... |
from django.shortcuts import render
from .models import Profile, Post
from django.shortcuts import get_object_or_404
from django.views import generic
from .models import Post, Profile
from django.views.generic import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortc... |
import math
cache = {}
def get_cached(x1, y1, x2, y2):
key = ','.join(str(l) for l in locals().values())
result = cache.get(key)
if not result:
result = robot_paths_recursive(x1, y1, x2, y2)
cache[key] = result
return result
def robot_paths_recursive(x1, y1, x2, y2):
if x1 > x2:
return ... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#########################################################################################
# #
# send_error_list_email.py: read the current error lists and send... |
from flask import Flask
import csv
import json
import pandas as pd
from datetime import date, timedelta
app = Flask(__name__)
class controllerAmurel:
cities = [
{
'name': 'Armazém',
'population': 8674
},
{
'name': 'Imaruí',
'population': 11672... |
#!/usr/bin/env python
import os
import subprocess
"""
Shifter, Copyright (c) 2015, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
Redistribution and use in source and binary... |
# ## PixelPingPong ##
# This animation runs 1 or many pixels from one end of a strip to the other.
#
# ### Usage ###
# Alternates has 3 optional properties
#
# * max_led - int the number of pixels you want used
# * color - (int, int, int) the color you want the pixels to be
# * additional_pixels - int the number of pix... |
#MenuTitle: Check Font
'''
Check family for GlyphsApp
~~~~~~~~~~~~~~~~~~~~~~~~~~
Check selected family passes qa.yml spec and common font errors.
Refer to README for further info.
'''
import vanilla
import os
import glob
import sys
import yaml
import re
script_path = glob.glob(r'/Users/*/Library/Application Suppor... |
from __future__ import absolute_import
# import models into model package
from .ads_provider_controllers import AdsProviderControllers
from .ads_provider_controllers_controller import AdsProviderControllersController
from .ads_provider_domains import AdsProviderDomains
from .ads_provider_domains_domain import AdsProvi... |
#!/usr/bin/env python
import numpy as np
import pickle
from glob import glob
from braindecode.experiments.load import load_model
from braindecode.experiments.experiment import create_experiment
import sys
import logging
log = logging.getLogger(__name__)
def update_result_to_new_iterator(basename):
exp = create_exp... |
# -*- coding: utf-8 -*-
"""
Garland: for unwrapping decorators.
"""
__author__ = 'Ben Lopatin'
__email__ = 'ben@wellfire.co'
__version__ = '0.3.0'
import sys
import importlib
if sys.version_info.major == 3:
from importlib import reload # Common interface
from unittest.mock import patch
else:
from mock ... |
## Guess Game 2.0
# The program will prompt the user to think of a number from 1-100. It will guess the user's
# number with provided feedback on whether their number is lower or higher than the guess.
import sys
def guessGame(ans, guess):
if ans[0] == "h" or ans[0] == "H":
offset = (guess[2] - guess... |
import numpy as np
def get_bb(seg, do_count=False):
dim = len(seg.shape)
a=np.where(seg>0)
if len(a[0])==0:
return [-1]*dim*2
out=[]
for i in range(dim):
out+=[a[i].min(), a[i].max()]
if do_count:
out+=[len(a[0])]
return out
def get_bb_all2d(seg, do_count=False, ui... |
class Solution(object):
def getRow(self, rowIndex):
"""
https://leetcode.com/problems/pascals-triangle-ii/
"""
li = []
x = l = 1
for i in range(0, rowIndex+1):
li.append(x/l)
x *= (rowIndex-i)
l *= i+1
# li += li[0:r... |
from django.shortcuts import render
from .models import Article
from django.http import Http404, HttpResponseRedirect
from django.urls import reverse
def index(request):
latest_articles_list = Article.objects.order_by('-pub_date')[:5]
return render(request, 'articles/list.html', {'latest_articles_list': lates... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-29 20:46
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):... |
import configargparse
import os
import configparser
import yaml
import sys
sys.path.append('src/')
from cnn_photon_id_parser import set_parser
# print(parser.__dir__())
# p_yaml= configargparse.ArgParser(
# config_file_parser_class=configargparse.YAMLConfigFileParser)
# p_yaml.add('-c','--config', is_config_fi... |
from django import http
from functions import get_routing_js
def routing_js(request):
"""
View to render routing js.
SHOULD NOT BE USED IN PRODUCTION
"""
response = http.HttpResponse(get_routing_js())
response['Content-Type'] = 'application/javascript'
return response
|
#!/usr/bin/env python
import sys
import glob
def handle_dir(dirname):
for f in sorted(glob.glob(dirname + "/*.log")):
# scen total-time 0.0 max-time-step 0.0 time-20-moves 0.0 total-len 0.0 subopt 0.0 valid
num_lines = 0
time = 0
subopt = 1
for line in open(f):
tokens = line.strip().split("\t")
if l... |
from .texture import BaseTexture, Material
from .decompress_ import decompress
from . import file_object, mesh, file_readers
|
#!/usr/bin/env python
# encoding: utf-8
"""
reminder.py
Created by yang.zhou on 2012-09-29.
Copyright (c) 2012 zhouyang.me. All rights reserved.
"""
import re
import logging
from rq import Queue
from redis import Redis
from models import Member, Reminder
from oauth2lib import message_request
def get_usernames(conte... |
#!/usr/bin/python3
# function that finds a peak in a list of unsorted integers.
def aux(list_of_integers, first, last):
""" recursive auxiliary function """
x = last - first
if x == 1:
if list_of_integers[first] > list_of_integers[last]:
return first
else:
return la... |
#!/usr/bin/python
#------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a cop... |
# 2017-03-11 jkang
# practice tf.case
# ref: http://web.stanford.edu/class/cs20si
import tensorflow as tf
x = tf.random_uniform([], -2, 2)
y = tf.random_uniform([], -2, 2)
def f1():
return tf.add(x, y)
def f2():
return tf.sub(x, y)
def f3():
return tf.constant(0, dtype=tf.float32)
val = tf.case({tf... |
"""import matplotlib.pyplot as plt
import numpy as np
import NSGAII
import Solution as sl
import SPEAII
import NSPSO
import Problem
import ParetoUtil as pu
import NSPSOMM
import concurrent.futures
def main():
problemlist = [Problem.UF1(),Problem.UF2(),Problem.UF3(),Problem.UF4()] #Problem.ZDT1(... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 00:00:27 2018
@author: Home
"""
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
expl = np.exp(L)
sumE = sum(expl)
result =[]
for i in expl:
... |
from aiogram import types
nazad = types.InlineKeyboardMarkup(
inline_keyboard=[
[
types.InlineKeyboardButton(text="<-- Назад", callback_data="Назад8")
]
])
|
import datetime
import calendar
import cx_Oracle
import sys
import os
from datetime import timedelta, date, time
import csv
import pandas as pd
from pandas import DataFrame
import numpy as np
from matplotlib import style
filename = 'output.csv'
target = open(filename, 'w')
#excelData = pd.ExcelFile('... |
import argparse
def arguments_parser_log_analysis():
"""Parses command-line arguments for log analysis.
Returns:
argparse.ArgumentParser: Argument parser for training
"""
parser = argparse.ArgumentParser()
parser.add_argument('--log-level', nargs='?', type=str,
def... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy as np
from math import *
x=0
f=True
z=0
def myinit():
glMatrixMode(GL_PROJECTION)
glClearColor(1,1,1,1)
glClear(GL_COLOR_BUFFER_BIT)
gluPerspective(60,1,.1,50)
gluLookAt(10,10,10,0,0,0,0,1,0)
def ... |
#!/usr/bin/env python
PACKAGE = "hektar"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("target_pot", int_t, 0, "target position for the arm", 250, 0, 1023)
exit(gen.generate(PACKAGE, "hektar", "pid"))
|
from django.db import models
from django.contrib.sitemaps import ping_google
class Project(models.Model):
title = models.CharField(max_length=200, help_text="The title of the project")
slug = models.SlugField(help_text="Slug to use in the URL for the project")
teaser = models.TextField(help_text="Short des... |
"""
functions related to creating, printing,
and evaluating tic-tac-toe boards
:author: Ian Sulley
:note: I affirm that I have carried out the attached academic endeavors with full academic honesty,
in accordance with the Union College Honor Code and the course syllabus
"""
def remove_blank_lines(list_of_strings):
... |
class Board:
flower_space = "X"
none_space = "--"
column_space = " | "
empty_space = "O"
tiles = [[]]
player_path_row_column = {}
player_path_row_column[1] = {
1: [3, 0],
2: [2, 0],
3: [1, 0],
4: [0, 0],
5: [0, 1],
6: [1, 1],
7: [2, ... |
# Generated by Django 3.0.2 on 2020-02-13 14:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Profile', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='profile',
old_name='aellido_paterno',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from analyse_immo.database import Database
from analyse_immo.bien_immo import Bien_Immo
from analyse_immo.lot import Lot
from analyse_immo.charge import Charge
from analyse_immo.credit import Credit
from analyse_immo.impots.annexe_2044 import An... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
def ROUND(a):
return int(a+0.5)
k=0
def init():
glClearColor(0.0,1.0,1.0,0.0)
glPointSize(2.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0.0,600.0,0.0,600.0)
def setPixel(x,y):
glBegin(GL_POINTS)
glVertex2i(x... |
class List(list):
def __init__(self):
super(self)
|
import config
import core_functions
import datetime
import time |
def cal_num(*args):
return sum(args), sum(args)/len(args)
Sum , Mean = cal_num(10,20,30)
print("3개의 인자 (10,20,30)")
print(f"합계 : {Sum}, 평균 : {Mean}")
Sum , Mean = cal_num(10,20,30,40,50)
print("5개의 인자 (10,20,30,40,50)")
print(f"합계 : {Sum}, 평균 : {Mean}")
|
# -*- coding: utf-8 -*-
class Solution:
def findRepeatedDnaSequences(self, s):
result = set()
if len(s) < 11:
return []
seen = set([s[:10]])
for i in range(10, len(s)):
sequence = s[i - 9 : i + 1]
if sequence in seen:
result.add(... |
from keygenerator import *
from ..translators.numberedalphabettranslator import *
import random
class NumberKeyGenerator(KeyGenerator):
def __init__(self, max_number=26, rand_func=lambda x: x ** 6, **kwargs):
"""To be used with CaesarTranslator"""
KeyGenerator.__init__(self, **kwargs)
self.max_number = max_numb... |
"""
Author: Zhen Dong
Time : 2020-09-19 23:19
"""
import torch
import torch.nn as nn
# 4ms * 15
conv1_ksize = (15, 1)
# 20 channels
conv2_ksize = (1, 20)
conv1_isize = 1
conv1_osize = 5
conv2_isize = conv1_osize
conv2_osize = 10
fc1_dropout_p = 0.3
fc2_dropout_p = 0.3
fc1_isize = 610
fc1_osize = 128
fc2_isize = f... |
import scrapy
from scrapy.loader.processors import TakeFirst
class BooksImagesItem(scrapy.Item):
file_urls = scrapy.Field()
files = scrapy.Field()
file_name = scrapy.Field(
output_processor=TakeFirst()
) |
import numpy as np
import json
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
STOP_WORDS = stopwords.words("english")
# get map from userid -> clusterid
def get_user2cluster(filepath):
with open(filepath, "r") as f:
content = f.readlines()
f.close()
user2cluster = ... |
import unittest
from katas.kyu_8.regex_count_lowercase_letters import lowercase_count
class LowercaseCountTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(lowercase_count('abc'), 3)
def test_equals_2(self):
self.assertEqual(lowercase_count('abcABC123'), 3)
def test_e... |
# Initiates the database
client = pymongo.MongoClient("mongodb+srv://dn54321:<password>@cluster0-kixdi.mongodb.net/test?retryWrites=true&w=majority")
db = client.test
|
#coding:utf-8
from moteur import *
mversion=[1.1]
titre=""
description=""
intro="debut"
fin="fin"
########
objet=Obj()
objet.nom='objet'
Endroit=Lieu()
Endroit.nom='endroit'
Endroit.objs.append(objet)
########
perso=Perso()
perso.nom=""
perso.lieu_actu=Endroit
print(intro)
inp("")
main(perso,objet)
inp("")
pri... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
from django.shortcuts import render
from weekapp.models import Week
def week(request):
weeks = Week.objects.all()
context = {
'weeks': weeks,
'page_title': 'weeks',
}
return render(request, 'weekapp/week.html', context) |
from daos.erequest_dao import ErequestDAOf
from entities.erequest import Erequest
from exceptions.resource_not_found import ResourceNotFound
class ErequestDaoLocal(ErequestDAOf):
id_maker = 0
erequest_table = {}
def create_request(self, erequest: Erequest) -> Erequest:
ErequestDaoLocal.id_maker +... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import Sequence
import pytest
from pants.backend.python import target_types_rules
from pants.backend.python.lint.pydocstyle.rules import P... |
#n= 3
n=input()
c=0
while n!=1:
if n%2==0:
n=n/2
else :
n=(3*n+1)/2
c=c+1
print c
|
#!thesis/DB
import mainDB
db = mainDB.db
n = db.nodes
nrs = db.nodesRes
def deleteNode(token):
old_val = n.find_one({'_id': token})
if old_val["role"] == "MASTER":
return "Cannot remove master node"
n.delete_one({'_id': token})
mainDB.removeNodeReplicaSet(old_val)
nrs.delete_one({'_id': ... |
from django.db import models
class NetworkElement(models.Model):
ne_name = models.CharField(max_length=100)
ne_type = models.CharField(max_length=100)
ring_name = models.CharField(max_length=100)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-20 17:19
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
result = 0
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 1 and self.isSpecial(mat, i, j):
result += 1
... |
import unittest
import sys
# sys.path.append('../')
from src.area import Area
class AreaTest(unittest.TestCase):
def test_square_area_side_positive(self):
self.assertEquals(Area.square(8), 64)
def test_square_area_side_negative(self):
self.assertEquals(Area.square(-5), 0)
def test_squa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-30 14:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('challenges', '0001_initial'),
('participants', '000... |
class UserData(object):
@staticmethod
def populate(raw):
if not raw or not 'user' in raw:
return None
user = raw['user']
return {'id': str(user['id']),
'name': user['fullname'].encode(encoding='utf-8', errors='ignore') if 'fullname' in raw else user['username... |
import unittest
import os
import tempfile
from gmc.core.cache import store
class TestStore(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._dummy_paths = {}
cls.next_path = 0
class Dummy:
def __init__(self, force=False):
self.storage = store('/tmp', force)
def get_name(self, name='dummy'):
... |
num1,num2=float(input("num1 = ")),float(input("num2 = "))
print(num1+num2) |
import discord
from discord.ext import commands
import asyncio
import twitter
from TwitApi import TwitApi
RobId = "154732271742615553"
def post_status(message,postcmd=False):
if len(message.attachments) >= 1:
attaches = []
for item in message.attachments:
attaches.append(item["url"])
... |
"""
CCT 建模优化代码
坐标系平移旋转
作者:赵润晓
日期:2021年5月4日
"""
# 因为要使用父目录的 cctpy 所以加入
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
from cctpy import *
# X'Y'Z' 局部坐标系,因为相对于全局坐标系只有原点 location 不同,坐标轴方向采用默认值,即于全局坐标系一致
lcs = LocalCoordinateSystem(location=P3(2,2,1))
# 定义全局坐标系... |
from datetime import datetime
import re
import scrapy
URL_TEMPLATE = 'https://www.kickstarter.com/discover/advanced?term=board+game&sort=popular&page='
PAGES = 1
def replace_last(source_string, replace_what, replace_with):
head, _sep, tail = source_string.rpartition(replace_what)
return head + replace_with + ... |
import math
def isPrime(n):
#returns a prime number.
# 0,1,2 are hard coded. This is an expensive function..
prime = True
check = math.sqrt(n)
if n == 0:
return False
if n == 1:
return False
if n == 2:
... |
#!/usr/bin/env python
'''
RabbitMQ receiver. Jobs are retreived as messages and converted into
python calls.
'''
activate_this_file = "../venv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
from viewsheds import grassCommonViewpoints
from srtmsql import pointQuery , makeTranspare... |
from uc.itm import UCWrappedFunctionality
from uc.utils import wait_for
import logging
log = logging.getLogger(__name__)
class Contract(UCWrappedFunctionality):
def __init__(self, k, bits, sid, pid, channels, pump, poly, importargs):
self.ssid = sid[0]
self.n = sid[1]
self.delta = sid[2]
... |
#!/usr/bin/env python
#
#
#
"""
Froomi web media search engine, and pseudo streaming provider
Copyright (C) 2009 David Busby http://saiweb.co.uk
"""
import ConfigParser,sys,os
from time import time
class Froomi:
def __init__(self):
self.debug = False
self.confd = ''
#=================... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Iterator
from pants.option.parser import Parser
from pants.util.frozendict import FrozenDict
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.