text stringlengths 38 1.54M |
|---|
import os
import math
import torch
import torch.nn as nn
import numpy as np
def cnn_block(im_height, im_width, input_channels, channels, kernels, strides, paddings, activation, last_act, batchnorm, **kwargs):
"""
building blocks for a convnet.
each block is in form of:
Conv2d
... |
from __future__ import print_function
from __future__ import absolute_import
import json, urllib2, os, sys
from bs4 import BeautifulSoup
## MainPageGenerator class is used for generating main page that contains domain trees (Analysis, Calibration and Alignment, Core, DAQ etc.)
class MainPageGenerator:
## Construc... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 27 13:49:12 2016
@author: jingyan
"""
def Priyanka_toy(array, N):
array = sorted(array)
count = 1
i = 1
weight = array[0] + 4
while i < N:
if array[i] <= weight:
i += 1
else:
count += 1
weight =... |
#作者:HP
#日期:2020-03-20 20:48
#文件:test_http_request
import unittest
from tools.http_request import HttpRequest
from tools.get_data import GetData
from ddt import ddt,data #
from tools.do_excel import DoExcel
from tools.project_path import *
from tools.my_log import MyLog
my_logger=MyLog()
test_data=DoExcel.get_data(... |
from django.http import HttpResponseRedirect
from django.shortcuts import render
from projet.forms.inscription import Inscription
from hashlib import md5
def index(request):
return render(request, 'projet/formulaire.html', {'form' : Inscription({})})
def valider(request):
if request.method=='POST':
formulaire=I... |
from django.urls import path, include, re_path
from . import views
urlpatterns = [
path('', views.index),
path('projects', views.index),
path('<int:project_id>/datasets', views.index),
path('<int:project_id>/<int:dataset_id>/annotator', views.index),
]
|
from .client_latency_test import ClientLatencyTest
from .server_latency_test import ServerLatencyTest
|
from .component import *
from .afterbody import *
from .centreFuselage import *
from .engine import *
from .fuselage import *
from .horizontalStabilizer import *
from .nose import *
from .primitives import *
from .verticalStabilizer import *
from .wing import *
import numpy as np
class Aircraft(Component):
def __ini... |
from django.db import models
from django.utils import timezone
class ModelBase(models.Model):
name = models.CharField(max_length=40)
detail = models.CharField(max_length=280)
def __str__(self):
return self.name
class APD(ModelBase):
class Meta:
verbose_name = "Alat Pelindung Diri"
... |
import numpy as np
from utils import *
class STATISTICS:
def __init__(self, val, count):
self.Value = val
self.Count = count
self.Mean = val
self.Variance = 0.
self.Min = 0.
self.Max = 0.
def SetValue(self, val):
self.Value = val
def ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import yaml
from . import Tools
class Config(Tools):
"""analyze confige file with yaml
"""
def __init__(self, config_path):
"""init Config object
Args: configPath: string,and path of config file
Return: None
"""... |
# -*- coding:utf8 -*-
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from users import views
urlpatterns = (
url(r'user_detail/$', views.UserDetail.as_view()),
url(r'user_list/$', views.UserList.as_view())... |
// https://leetcode.com/problems/two-sum-iii-data-structure-design
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {}
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
... |
with open('day11.txt') as f:
c = list(map(int, f.readline().split(',')))
# Opcodes
ADD = 1
MULTIPLY = 2
STORE = 3
DUMP = 4
JT = 5
JF = 6
LT = 7
EQ = 8
RB = 9
HALT = 99
class IntCode:
def __init__(self):
self.code = c[:]
self.ip = 0
self.rb = 0
self.out = 0
self.halt... |
# Imports
import numpy as np
import matplotlib.pyplot as plt
# Within group iteration procedure (weighted diamond difference)
def InnerIteration(a, mu, sig_t, sig_s, q_e, N, psi_group1, psi_group2, psi_group3, group, converge):
# Initialize new center fluxes arrays for the curret group
psi_new = np.zeros((N,6... |
def vowel():
str="We are going to calculate the no of vowels."
vow="aeiouAEIOU"
count=0;
for character in str:
if character in vow:
count+=1
print(character)
print("No. of vowels in string: ",count)
vowel();
|
import sys
import argparse
import inspect
from pprint import pprint
try:
import docstring_parser
except ModuleNotFoundError:
class docstring_parser:
def __init__(self):
self.short_description = ""
self.long_description = ""
self.params = []
@classmethod... |
"""
定义一个XuZhu类,继承于童姥。虚竹宅心仁厚不想打架。所以虚竹只有一个read(念经)的方法。每次调用都会打印“罪过罪过”
加入模块化改造
希望各位同学在此基础上可以添加自己的“freestyle”哦
"""
# 定义XuZhu类,继承于童姥
from practice.python_oo.tonglao import TongLao
class XuZhu(TongLao):
# 定义read方法
def read(self):
print("罪过罪过")
# 类的实例化
XZ = XuZhu(1000, 1000)
XZ.read()
|
from .models import Vertical
from .serializers import VerticalSerializer
from rest_framework import viewsets
class VerticalViewSet(viewsets.ModelViewSet):
queryset = Vertical.objects.all()
serializer_class = VerticalSerializer
|
# Generated by Django 3.1.5 on 2021-02-02 09:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_auto_20210202_1731'),
]
operations = [
migrations.CreateModel(
name='PostBlogModel... |
import re
import time
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
def scrape_text(soup):
"""
現在のページからレビューテキストを取得する関数
:param soup: bs4.BeautifulSoup, html
:return: list, レビューテキスト
"""
target_htmls = soup.find_all("div", class_="text_content")
text = []
... |
import pytest
from txkoji import Connection
from txkoji.channel import Channel
from txkoji.tests.util import FakeProxy
import pytest_twisted
class TestGetChannel(object):
@pytest.fixture
def channel(self, monkeypatch):
# To create this fixture file:
# cbs call getChannel 2 \
# --jso... |
import random
import os, sys
import string
import subprocess
import time
def generate_tests(qty):
tests = []
tests.append(str(start_size))
for i in range(0, qty):
a = random.random()
size = random.randrange(1, str_length, 1)
letters = string.ascii_lowercase
if a >= 0.7:
... |
# Generated by Django 3.2 on 2021-04-28 10:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AnalysisApp', '0006_auto_20210428_1039'),
]
operations = [
migrations.AlterField(
model_name='polen',
name='AnalysisDa... |
# -*- coding:utf-8 -*-
from enum import Enum
class TinkerErrorCode(Enum):
MISSING_PARAMETER = 0
UNKNOWN_COMMAND = 1
RESERVED_COMMAND = 2
DUPLICATED_COMMAND = 3
SEND_MSG_ERROR = 4
LOGIN_ERROR = 5
GET_UUID_ERROR = 6
SYNC_ERROR = 7
SYNC_CHECK_ERROR = 8
SYNC_HOST_CHECK_ERROR = 9
... |
import os,csv
path = r"C:\Users\a7825\Desktop\工作空间\语音数据\CSJ\WAV\正解文\zhengjie_1"
#包含语音文件的文件夹的路劲
for name in os.listdir(path):
path_1 = os.path.join(path,name)
dakai = open(path_1, 'r', encoding='utf-8')
txtwenjian = csv.reader(dakai)
b = [i for i in txtwenjian]
b_1 = []
for y in b:... |
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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.... |
from myapp.models import Bike
from django.views.generic.detail import DetailView
class BikeDetailView(DetailView):
model = Bike
template_name = 'bike_detail.html'
from django.views.generic import ListView
class BikeListView(ListView):
model = Bike
paginate_by = 3
#queryset=Bike.objects.filter(type... |
# coding: utf-8
from random import randint
def game():
s= randint(1,1000)
i=-1
while i!=s:
i=int(input('請猜一個1~1000間的數字:'))
if i>s:
print('太大了,找小一點喔~')
elif i==s:
print('恭喜你~~答對了!')
else:
print('太小啦,再找大一點吧')
play=True
while play:
game()... |
import random
score = 10
randomNumber = random.randint(1,10)
while True:
userNumberInput = int(input('Guess : '))
if userNumberInput == randomNumber:
print("Congratulation you guessed it right! your score is" + str(score))
else:
print('better luck next time')
score -= 1 |
import json, gzip, re, requests
with gzip.open('jawiki-country.json.gz', 'rt') as f:
text = '\n'.join([json.loads(l)['text'] for l in f.readlines() if json.loads(l)['title'] == 'イギリス'])
text = re.compile(r'^\{\{基礎情報.*?$.*?^\}\}$', re.MULTILINE + re.DOTALL).findall(text)[0]
pattern = r'\'{2,5}(.*?)(\1)|\[\[(?:[^:\]]... |
# uncompyle6 version 3.3.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\_Framework\ModeSelectorComponent.py
# Compiled at: 2018-11-30 15:48:1... |
from dataentry.models import BorderStation
def border_stations_processor(request):
border_stations = BorderStation.objects.order_by('station_name')
return {'border_stations': border_stations}
|
a = [1,2,3,4]
result = []
for i in a :
result.append(i*3)
print(result)
##################################
a = [1,2,3,4]
result = [num * 3 for num in a]
print(result)
##################################
a = [1,2,3,4]
result = [num * 3 for num in a if num % 2 ==0]
print(result)
'''
[리스트 내포 문법]
표현식 for 항목 in ... |
NumList = []
total = 0
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
for j in range(Number):
total = total + NumList[j]
print("\n The Sum of All Elem... |
# -*- coding: utf-8 -*-
import pytest
import ffmpeg
from ffmpeg.formatctx import *
from ffmpeg.lib import *
from fractions import Fraction
#from ffmpeg.error import FFMPEGException, AVERROR_STREAM_NOT_FOUND
from pprint import pprint as pp
id_h264 = avcodec.AV_CODEC_ID_H264
@pytest.fixture(scope='module')
def setup(... |
#!/usr/bin/env python
# coding: utf-8
# ## Black Light, White Light
# Zumi can recognize simple colors. In this demo, we will control Zumi using black and white cards.
#
# ### Step 1: Setup
# <div>
# <br/><p>In Jupyter Notebook, code is written inside boxes called "cells". You can run a cell by clicking on it, then c... |
import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
txt="onionionspl"
pat="onions"
# Knuth Moris Parth
def computeLPSarray(LPS, pat, m):
length=0;
i=1;
LPS[0]=0
while(i<m):
if(pat[length]==pat[i]):
length+=1;
i+=1;
LPS[i]=length#this will below increament of length
else:... |
from room import Room
from player import Player
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': R... |
import urllib
import gzip
def get_data(contract_name, date, prefix='CTP', saved_filename=''):
url = 'https://s3.amazonaws.com/wanlitech-data/polled/1s/' + date + '/' + prefix + '/' + contract_name + '.top.gz'
print(url)
zfile_name = ''
if saved_filename == '':
zfile_name = zfile_name + contract... |
# Generated by Django 2.0.2 on 2018-07-07 09:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gutlife_app', '0011_auto_20180707_0944'),
]
operations = [
migrations.AlterField(
model_name='bmlog',
name='time',
... |
#test for expression retargeting
#testA is the expression embedding folder, testB is the face model folder
import os
from v2eNet import v2e
from utils.gridModel import gridModel
import numpy as np
import cv2
from utils.dataPreprocess import deDataNormalizeDelta
import torch
from utils.faceData import faceD... |
class Restaurant():
"""A class representing a restaurant"""
def __init__(self, name, cuisineType):
"""Initialize the restaurant"""
self.name = name
self.cuisineType = cuisineType
def describeRestaurant(self):
"""Display a summary of the restaurant"""
print (f"{self.n... |
from kappa.dao.DAO import DAO
from kappa.dao import ConnectionManager
from kappa.models.ImageModel import ImageModel
from kappa.controllers.FaceVectorController import FaceVectorController
from kappa.controllers.ObjectVectorController import ObjectVectorController
from kappa.dao.ObjectVectorDAO import ObjectVector... |
import speech_recognition as sr
import os
import sys
import re
import webbrowser
import smtplib
import requests
import subprocess
from pyowm import OWM
import youtube_dl
import urllib.request
import json
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import wikipedia
import random
from time i... |
def fibonacci_sum(n: int)->int:
def fibonacci_sum_helper(n: int, acc: int, prev: int, curr: int)->int:
if n == 1:
return acc
elif n == 2:
return acc + curr
else:
return fibonacci_sum_helper(n - 1, acc + curr, curr, prev + curr)
return fibon... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:module:
========
Prints a report of incidents, happened through connection to service, by\
ip and username.
:arguments: module get optional argument - minimal number of incidents per\
one user. If not, all icdinets will be printed.
:task:
======
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class NotifyConfig(AppConfig):
name = "notify"
label = "notify"
verbose_name = "站内消息"
|
from path import open
from path import set
def main():
matrixfile = open.import_file()
matrix = open.get_matrix(matrixfile)
set.printmatrix(matrix)
print"\n"
print open.get_startpoint(matrixfile)
print open.get_endpoint(matrixfile)
if __name__ == '__main__':
main() |
from TravelingSalesmanProblem import TSP
from deap import tools, base, algorithms, creator
import array, random
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from eaSimple_withElitism import eaSimpleWithElitism
TSP_NAME = "bayg29"
tsp = TSP(TSP_NAME)
# Genetic Constants
MAX_GENERATION = 250... |
import torch
import torch.nn.functional as F
from model.base_builder import BaseBuilder
from model.backbone.efficientnet import EfficientNetB0
import model.backbone.resnet_atrous as res_atr
from model.neck.co_neck import UCR, Adjust
from model.head.co_head import ManHead, CoDWRPN
from model.loss.rpn_loss import select_... |
from re import *
import urllib.request
import sys
def find_emails(text):
return findall(r"[a-zA-Z0-9\&\~._%\*\?\{\}+-]+@[a-zA-Z\&\~\_.-]+\.[a-zA-Z]{2,4}", text)
def url2html(url):
with urllib.request.urlopen(url) as f:
return f.read().decode('utf-8') #only the first 1000 symbols, if the text is to ... |
http_messages = {
200 : 'OK'
}
def __build_info(status):
return f"HTTP/1.1 {str(status)} {http_messages[status]}\r\n"
def build_info(status,content):
response = f"HTTP/1.1 {str(status)} {http_messages[status]}\r\n"
response += f"Content-Length: {str(len(content))}\r\n"
return response
def build_... |
def getRank(num):
return [6,6,5,4,3,2,1][num]
def solution(lottos, win_nums):
winNum = set(win_nums)
mnCnt = len(list(filter(lambda x: x in winNum, lottos)))
mxCnt = mnCnt + lottos.count(0)
return list(map(getRank, [mxCnt, mnCnt]))
def main():
lottos = [44, 1, 0, 0, 31, 25]
win_nums = [31,... |
import numpy as np
import sys
sys.path.insert(0, '../../../network')
from neuralNetwork import network
import matplotlib
matplotlib.use("TKAGG")
import matplotlib.pyplot as plt
class creature(object):
"""docstring for creature"""
def __init__(self, brain = None):
super(creature, self).__init__()
... |
import boto3
import paho.mqtt.client as mqtt
mqttc = mqtt.Client()
def SendMsg():
client = boto3.client("sns", "us-east-1")
phone = "+919702007220"
phone1 = "+XX"
EndMsg = "Hi Mummy Send Using AWS SNS"
Msg = client.publish(PhoneNumber=phone, Message=EndMsg)
Msg1 = client.publish(Phon... |
#!/usr/bin/env fontforge -script
import pickle
import fontforge
import psMat
IPA_FONT = "ipagp.ttf"
PATCH_FONT = "textar-patch.otf"
MSPG_GLYPH_DATA = "mspg_glyph_data.pickle"
OUTPUT_FILE = "textar.sfd"
def scale(glyph, scalex, scaley):
glyph.transform(psMat.scale(scalex, scaley))
def move(glyph, x, y):
gl... |
from flask import Flask
from flask import request
app = Flask(__name__) #instancia: nuevo objeto
@app.route('/')
def index():
return 'Bienvenido'
@app.route('/PlayApps_201810')
def PlayApps_201810():
return 'PlayApps_201810'
@app.route('/PlayApps_201811')
def PlayApps_201811():
return 'PlayApps_201811'
@app.rou... |
import enum
import attr
import bitstruct
import crcmod
import structattr
from structattr.types import UInt, Enum, Bool, Zero, One, FixedPointSInt
from typing import Union
crc_func = crcmod.mkCrcFun(0x11021, initCrc=0, xorOut=0, rev=False)
class ElcobusFrame:
__slots__ = ()
@classmethod
def from_bytes(... |
from ui.tests.TestBase import TestBase
from ui.models import Turn
class TestMoves(TestBase):
def testSingleMove(self):
turn = Turn.objects.get(pk=1)
# verify units
self.assertUnit(turn, 'Germany', 'Army', 'Spain')
self.assertNoUnit(turn, 'Poland')
# set comma... |
from types import SimpleNamespace
from hwtypes.adt import Enum, Product, TaggedUnion, Sum
from hwtypes.adt_util import rebind_type
from peak import family_closure
from . import family
@family_closure(family)
def ISA_fc(family):
Bit = family.Bit
BitVector = family.BitVector
Idx = family.Idx
Word =... |
import discord
import asyncio
import os
from CryptoniteFunctions import MessageHandler
print("Creating bot client...")
client = discord.Client()
print("Creation completed.")
@client.event
async def on_ready():
print("Bot name: " + client.user.name + "\n Bot ID: " + client.user.id)
print("Ready to receive... |
#!/usr/bin/python3
from pyrob.api import *
@task
def task_8_2():
if wall_is_above()==True or wall_is_beneath()==True:
usl=1
while usl==1:
if (wall_is_above()==True and wall_is_beneath()==False) or (wall_is_above()==False and wall_is_beneath()==True):
fill_cell()
if wall_is_on_the_right()==False:
move_r... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from timer_app.forms.topic import TopicForm
from timer_app.models import Topic
@login_required
def create_and_list_topic(request):
topics = Topic.objects.filter(user=request.user)
context = {
'form... |
from authentication import views
from django.urls import include, re_path
from django.views.generic.base import RedirectView
urlpatterns = [
# include external frameworks urls
re_path(r'^auth/', include('rest_framework_social_oauth2.urls')),
re_path(r'^', include('registration.backends.hmac.urls')),
# cus... |
import webapp2
import string
from xml.dom.minidom import parseString
from google.appengine.ext.webapp import template
from google.appengine.api import users
from site.utils import admin_required
from blog.models import Article
class BlogHandler(webapp2.RequestHandler):
def main(self):
""" Handle reques... |
from keras.layers import Input, merge, Dropout, Dense, Flatten, Activation
from keras.layers.convolutional import MaxPooling2D, Convolution2D, AveragePooling2D
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras import backend as K
from keras.utils.data_utils import get_... |
# -*- coding: utf-8 -*-
# Copyright (c) St. Anne's University Hospital in Brno. International Clinical
# Research Center, Biomedical Engineering. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# Std imports
# Third pary imports
import numpy as np
from scipy.stats impor... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from .models import Teacher, User, Student, Thesis
class StudentSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = ('first_name', 'last_name','u... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# %%06e04634dc02a21685ae0bf1dca0dadbeff3eb0758082e61fcd2304ae19ba69e7afda013125c5f1d3138487a150f61a0118734169f4c28e12ecbf82c7b0f3873%%
SCRIPT_DEBUG_MODE = False
#
# Standard imports
#
import sys
import os
import platform
import argparse
import json
import datetime
now ... |
"""
Tests for SimEngine.Mote.sf
"""
import types
import pytest
import test_utils as u
import SimEngine.Mote.MoteDefines as d
from SimEngine import SimLog
from SimEngine import SimEngine
# =========================== helpers =========================================
def set_app_traffic_rate(sim_engine, app_pkPeriod... |
# -*- coding:utf-8 -*-
#爬取糗事百科段子
import urllib
import urllib2
import re
# page = 1
def scanQiushi(page):
url = 'http://www.qiushibaike.com/hot/page/' + str(page)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
try:
request = urllib2.Reques... |
from Combat import Enemy, Combat
from Player import Player, Weapon, Armour
from bestiary import bastard_sword, quarterstaff
player = Player("Hrothgar")
player.add_item(bastard_sword)
player.add_item(quarterstaff)
player.add_item(Armour("Leather Leggings", "", 1, "leggings"))
player.equip("sword")
rand_encounter = Co... |
# -*- coding: utf-8 -*-
"""
@author: Chris Lucas
"""
import os
from flask import Flask, render_template
from flask_restplus import Api
from apis import find_spots, periods, photos, search
from core import db
app = Flask(__name__)
app.config['SWAGGER_UI_DOC_EXPANSION'] = 'list'
app.config['RESTPLUS_VALIDATE'] = Tr... |
"""
Module containing tests for the Params class
"""
import pathlib
import pytest
from micone.config import ParamsSet
from micone.config.params import Params
@pytest.mark.usefixtures("pipeline_settings", "example_pipelines")
class TestParamsSet:
""" Tests for ParamsSet class """
def test_init(self, pi... |
__author__ = 'yury'
# A palindrome is a string that is written the same forward as it is in reverse.
# Write a method to return the longest palindrome in a given string.
# Example: "yzzy" == solution("xyzzy")
def is_palindrome(x):
return x == x[::-1]
def each_cons(x, size):
return [x[i:i+size] for i in ra... |
# Generated by Django 3.0.5 on 2020-07-03 16:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('login', '0005_auto_20200703_1623'),
]
operations = [
migrations.RemoveField(
model_name='tableuser',
name='table_user_col_cr... |
import cv2
image = cv2.imread ("C:/Users/User/Desktop/python/photo.jpg", 3)
cv2.imshow("Title", resize)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
import random
"""
Number Guesser Program
This is an example of how to use variables to
keep track of information in a program that
also makes use of loops
"""
def main():
count = 1
lower = 1
upper = 100
num = random.randint(lower, upper)
while True:
indicator = input(f"Is your number {n... |
#
# this is a contrived example designed to teach variable scoping behavior.
#
# usage:
#
# opsmop apply content/var_scoping.py
#
# ==============================================================================
from opsmop.core.easy import *
# ======================================================================... |
# Generated by Django 3.2.3 on 2021-05-23 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='eventdetails',
name='Locatio... |
from sys import stdin
def main():
print(sum([int(is_valid(line)) for line in stdin]))
def is_valid(line):
parts = line.split()
i1, i2 = map(int_decrement, parts[0].split("-"))
char = parts[1][0]
password = parts[2]
return int((password[i1] == char) != (password[i2] == char))
def int_decrem... |
# my code
a = 1
b = 2
c = 3
# sums
d = a + b
print(a, b, d)
print('Summe aus a und b:', d)
print('Summe aus c und b:', c+b)
print('Summe aus a und c:', a+c)
# code is from Christine Greif
# date 18.6.21
# nicht auf git
print('Das ist noch nicht auf git') |
import serial
from time import sleep
class test:
def __init__(self):
try:
self.ser = serial.Serial("/dev/ttyACM2", 9600)
except:
print("ERROR: Cannot connect to serial port")
self.current = [0,1500,1500]
def setSpeed(self, left, right):
self.current[1... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import registration_form
from django.contrib.auth import logout
from django.contrib.auth import authenticate
# try to login the user
def login(request):
email_addr = request.POST.get( 'last_name', '' )
password =... |
# Import the pandas library
import pandas as pd
# Read the provided customer data CSV file
customer_df = pd.read_csv("C:/Users/anipb/Desktop/CustomerList.csv")
# Display the customer data
print(customer_df)
# Find customers from Georgia and from the USA
print("Example for AND operator")
print(customer_df.loc[(custom... |
from z3 import *
IC = BoolVector('IC', 3)
x, y = Ints('x y')
s = Solver()
s.add(Implies(IC[0], x > 10),
Implies(IC[0], y > x),
Implies(IC[1], y < 5),
Implies(IC[2], y > 0))
print s.check(IC)
print s.unsat_core()
print IC
#for uc in s.unsat_core():
#print simplify(uc == 'IC__1')
# print simplify... |
"""Definitions for the components for models participating in the framework.
A "component" is a functional unit that performs a specific step in
the coupled model processing pipeline. Generally, a component will
correspond to one of the models being coupled, but components can also
implement utility processes, such a... |
#!/usr/bin/env python
import ROOT
from rootpy.utils import asrootpy
from rootpy.plotting import Canvas, Legend, HistStack
from FinalStateAnalysis.Utilities.AnalysisPlotter import styling,samplestyles
import rootpy.io as io
import FinalStateAnalysis.StatTools.poisson as poisson
# This stuff is just so we can get match... |
# coding=utf-8
import json
from pymongo import MongoClient
# 数据库的连接
import files
from files import save
client = MongoClient('localhost', 27017)
db = client.panda
table_chengshi = db.chengshi
# 更新最后一条微博的id,不建议使用
def update_last_blog_id():
data = table_chengshi.find().limit(1).sort([('_id', -1)])
for d in d... |
import socket
UDP_IP= "10.160.108.101"
UDP_PORT= 5005
MESSAGE="?"
MESSAGE2="cinema"
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
print("Message recu: ", data.decode())
sock.sendto(MESSAGE2.encode(), (UDP_IP, UDP_PORT))
data, ad... |
from django.contrib import admin
from teacherAvaluation.models import *
admin.site.register(Degree)
admin.site.register(Subject)
admin.site.register(Teacher)
admin.site.register(Evaluation)
|
from enum import Enum
class EnvironmentsRetrieveExpand(str, Enum):
ENVIRONMENTAPPLICATION = "environment.application"
ENVIRONMENTAWS_ECS_SERVICES = "environment.aws_ecs_services"
ENVIRONMENTDEPLOYMENTS = "environment.deployments"
def __str__(self) -> str:
return str(self.value)
|
def calculatemin(stack):
counter = 0
print('new stack')
if checktrue(stack):
return counter
else:
for i in xrange(len(stack)-1, -1, -1):
#print(stack[i])
print(i, stack[i])
if stack[i] == '-':
stack = flippartialstack(stack, i)
... |
from DataBase import *
from navigator import *
import matplotlib.pyplot as plt
f = open("DataBase.txt", "r+")
DB = TDataBase(f)
DB.pull()
CG = CoursesGraph(DB)
print CG.get_optimal_path([1], [3,4])
#pos=nx.circular_layout(CG.Graph) # positions for all nodes
#
## nodes
#nx.draw_networkx_nodes(CG.Graph,pos,... |
from abc import ABC, abstractmethod
class BroadcastContract(ABC):
@abstractmethod
def ssl(self):
pass
@abstractmethod
def channel(self):
pass
|
"""
Posterior Predictive check with Maximum Mean Discrepancy (MMD).
Introduction:
-------------
TATTER (Two-sAmple TesT EstimatoR) is equipped with a posterior predictive check that allows
the users to study the goodness of a data generative model vs. an observed data. This module employ
MMD, KL, KS test to compute th... |
import re,urllib
import urllib.request
u=urllib.request.urlopen("https://www.findandtrace.com/mobile-phone-number-database/Andhra-Pradesh/IDEA")
print(type(u))
r=u.read()
r=re.findall(r"[9]{1}[0-9]{9}",str(r))
for i in r:
print(i)
|
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
def encode_cat_feature_using_targets(feature_train, targets, feature_test, use_loo=False, alpha=1.0):
# Compute smoothed mean of targets for each category in feature_train
target_means = targ... |
import cv2
import time
import numpy as np
import sys
import imutils
from sklearn.cluster import KMeans
# cap = cv2.VideoCapture('inside2.m4v')
# cap = cv2.VideoCapture(0)
cap = cv2.VideoCapture('inside4.m4v')
fil = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (300,168))
i =0
while(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.