text stringlengths 38 1.54M |
|---|
import numpy as np
import numpy.linalg as linalg
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
import fractions # Available in Py2.6 and Py3.0
from scipy.linalg import eigvals_banded
def approx2(c, maxd):
'Fast way using continued fractions'
return fractions.Fracti... |
# https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
# 剑指 Offer 12. 矩阵中的路径(79. 单词搜索)
from typing import List
from collections import Counter
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not board or not word:
return False
y, x = len(boar... |
from itertools import permutations
perm = permutations([0,1,2,3,4,5,6,7,8,9])
lst = list(perm)
lst.sort()
print(lst[999999]) |
#!/usr/bin/python
#This script just runs the commands we normally run by hand for the changelogs
import sys, os, time, re, string
if(len(sys.argv) != 4):
print "Invalid Args"
print "Usage - genChangelog.py <kernel branch> <date> <update>"
print "<kernel branch> - i.e. humboldt"
print "<date> - yyyymmdd i.e.... |
# -*- coding: utf-8 -*-
"""
Module to init logging.
"""
import datetime
import logging
import os
from pathlib import Path
def main_log_init(log_dir: Path, log_basefilename: str, log_level: str = "INFO"):
# Make sure the log dir exists
if not log_dir.exists():
os.makedirs(log_dir, exist_ok=True)
... |
import os
import argparse
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import pandas as pd
from model import DRL4TSP, Encoder
from tasks import vrp_init
from tasks.vrp_init import VehicleRouting... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 17:04:26 2017
Class to hold data from a single DFG acquisition. A set of DFGs may or may not
make up a full spectrum from spectrum.py.
DFG stands for 'difference frequency generation'. When collecting a broad SFG
vibrational spectrum, the IR w... |
# coding: utf-8
# Copyright (C)
# 2016 - 2019 Pinard Liu(liujianping-ok@163.com)
#
# https://www.cnblogs.com/pinard
#
# Permission given to modify the code as long as you keep this declaration at the top
#
# 用scikit-learn和... |
def first_fun(name):
print("This is my first python function")
print("Hello " + str(name))
first_fun("Prabhdeep")
first_fun(55)
def cube(num):
return num * num * num
print("After return but before call")
print("Cub of 3 is: " + str(cube(3)))
|
#!/usr/bin/env python3
"""A sparse autoencoder"""
import tensorflow.keras as keras
def sample(args):
"""Sample from variational space for output"""
mean, logvar = args
batch = keras.backend.shape(mean)[0]
dim = keras.backend.int_shape(mean)[1]
epsilon = keras.backend.random_normal(sh... |
#!/usr/bin/python
import time
import json
import qrcode
import sys
import re
import urllib
import urllib2
import xml.dom.minidom
UUIDURL = "https://login.weixin.qq.com/jslogin"
QRCODEURL = "https://login.weixin.qq.com/l/"
SCANURL = "https://login.weixin.qq.com" +\
"/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=... |
from collections import deque
N, K = map(int, input().split())
A = list(map(int, input().split()))
d = deque([A[0]])
telepote = A[0]
for i in range(K):
d.append(A[telepote-1])
if d.count(A[telepote-1]) >= 2:
break
telepote = A[telepote-1]
if len(d)>=K:
print(d[K])
else:
... |
import cbpro
import os
#API Secret Key = sFmQy9dxj1+i5OykxzB19VpHLI99ZubiDCDGKRJHlvSXrrn8yj+bnLpPpR1efZ7JB2PFfWfBAhg5t1jzlDrTuw==
class AllTestInText():
def __init__(self):
self.folder = "./log_cbpro/"
self._public_client = cbpro.PublicClient()
self._key = os.getenv("API_KEY_SANDBOX")
self._b64secret = os.... |
username= 'rashidi.lbo@gmail.com'
password = ''
server = 'smtp.gmail.com:587'
import smtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def create_msg(to_addr, from_addr='', subject=''):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['To'] = to_addr
... |
from ..tasks import images, videogame, memory, task_base
TASKS = [
videogame.VideoGame(
state_name="Level1",
scenario="scenario_repeat1", # this scenario repeats the same level
max_duration=10
* 60, # if when level completed or dead we exceed that time in secs, stop the task
... |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
# Generated by Django 2.1.4 on 2019-01-17 17:28
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('games', '0011_color_description'),
]
operations = [
migrations.RemoveField(
model_name='statistic'... |
#!/usr/bin/env python3
import unittest
from puzzle_6_2 import Graph
class TestPuzzle6_2(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
data = ["COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I",
"E)J", "J)K", "K)L", "K)YOU", "I)S... |
"""
ddupdate plugin to retrieve address from an OnHub / Google / Nest router.
See: ddupdate(8)
"""
import json
import urllib.request
from ddupdate.ddplugin import AddressPlugin, AddressError, IpAddr
# onhub.here should resolve correctly if you have this type of router
_URL = "http://onhub.here/api/v1/status"
cla... |
from State import State
from PriorityQueue import PriorityQueue
from collections import deque
class solver:
def __init__(self, StartStates, GoalStates):
self.StartStates = self.toList(StartStates)
self.GoalStates = GoalStates
def toList(self,data):
return [j for sub in data for j in su... |
import argparse
import matplotlib
matplotlib.use("Agg")
import numpy as np
import os
from core.callbacks import TrainingMonitor
from core.nn import MiniGoogLeNet
from sklearn.preprocessing import LabelBinarizer
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.datasets import cifar10
fr... |
# def soma(num, num1):
# print(num * num1)
#
#
# soma(2,6)
# class estudo1():
# pass
#
# class pessoa():
# pass
#
# p1 = pessoa()
# p2 = pessoa()
#
# print(id(p1))
# print(id(p2))
class A:
def __init__(self):
print(id(self))
A()
|
"""
This module comprises a stack of convolutional layers of arbitrary depth, with
the ability to train progressively.
"""
import abc
import argparse
import logging
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision as tv
class ProgNet(nn.Module):
def __init__(self):... |
# coding: utf-8
# In[1]:
import pandas as pd
from IPython.display import Markdown, display
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np
from sklearn import metrics
# def printmd(string):
# display(Markdown(s... |
import requests
from bs4 import BeautifulSoup
import csv
file = open("corona.csv", mode = "w", newline='')
writer = csv.writer(file)
hospital_html = requests.get('https://www.mohw.go.kr/react/popup_200128_3.html')
hospital_html.encoding = 'utf-8'
hospital_soup = BeautifulSoup(hospital_html.text, "html.parser")
tbody ... |
from django import forms
from .models import Preference
from django.core.exceptions import ValidationError
class PreferenceForm(forms.ModelForm):
class Meta:
model = Preference
fields = '__all__'
# validating some of the fields in Preference model
def clean_first_name(self):
# if... |
# Generated by Django 3.0.5 on 2020-04-23 21:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
... |
# Creating a tuple using ()
t = (1,2,6,4,0,7)
# Printing the elements of a tuple
print(t[0])
# Cannot update the values of a tuple, both tuple and string are immutable data type
# once defined a tuple element cannot be altered or manipulated
# t[0] = 74
# abc = "Amazing"
# abc[1] = 'a'
# print(abc)
t1 = () #Empty... |
# coding: utf-8
"""
NHL v3 Scores
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import uni... |
#! usr/bin/env python3
from game_of_life import App, Grid, Square
import pytest
def test_raise_exception():
with pytest.raises(Exception) as excinfo:
obj = App(1, 25, tolerance=0)
assert (
"The squares don't fit evenly on the screen. Box side_length needs to be a factor of window side_length.... |
# industry standard note: "should" store as Python style and convert to JS for front end
queue_cards = [
{
"studentName":"Athelia",
"title": "Athelia's title",
"isActive": True,
"imgUrl":"https://fellowship.hackbrightacademy.com/media/CACHE/images/staff/athelia/d3a4891536121a55505ac6... |
import re
import nltk
from sentence_transformers import SentenceTransformer, util
import numpy as np
from LexRank import degree_centrality_scores
from review_utils import *
# input: list of (review, score)
def get_summary(reviews, top_n):
reviews = set([reviews for reviews,score in reviews])
document = ' '.joi... |
var={"car":"volvo", "fruit":"apple"}
print(var["fruit"])
for f in var:
print("key: " + f + " value: " + var[f])
print()
print()
var1={"donut":["chocolate","glazed","sprinkled"]}
print(var1["donut"][0])
print("My favorite donut flavors are:", end= " ")
for f in var1["donut"]:
print(f, end=" ")
print()
print()
#Usin... |
# podstawowa wersja crawlera
import requests
# ściągamy stronę z której wyciągniemy dane
url = 'https://infoshareacademy.com/?s&city=Krakow'
response = requests.get(url)
content = response.text
# szukamy elementu z przypisaną klasą "course-title"
course_pattern = '"course-title">'
opening_tag = '<span>'
closing_tag ... |
import collections
import math
import numpy as np
#cython: linetrace=True
#cython: language_level=3
from memblock import *
#from vec4 import *
#from vec3 import *
from rotations import *
from canvas import *
from base import inverse, transform, dot, Intersection, normalize, World, scaling, EPSILON, equal
class M... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-04 22:56
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('library', '0003_auto_20171204_1153'),
]... |
'''
시뮬레이션하면서
max값 갱신
'''
answer = 0
total = 0
for _ in range(10):
o, i = map(int, input().split())
total -= o
total += i
answer = max(answer, total)
print(answer)
|
#coding=UTF-8
__metaclass__=type
from xmlrpclib import ServerProxy,Fault
from os.path import join,isfile,abspath
from SimpleXMLRPCServer import SimpleXMLRPCServer
from urlparse import urlparse
import sys
SimpleXMLRPCServer.allow_reuse_address=1
MAX_HISTORY_LENGTH=6
UNHANDLED=100
ACCESS_DENIED=200
class UnhandledQue... |
import math
def totient(n):
#To take care of illegal input
if n<1:
print("Totient of",n,"is not defined")
else:
tot = int(n)
for i in range(2, n + 1):
f = 0
#Finding factors
if n % i == 0:
for j in range(2, math.floor(math.sqrt(i)) ... |
access_template = ["switchport mode access", "switchport access vlan {}","switchport nonegotiate", "spanning-tree portfast",
"spanning-tree bpduguard enable"]
trunk_template = ["switchport trunk encapsulation dot1q", "switchport mode trunk",
"switchport trunk allowed vlan {}"]
# Get input
ifmode = raw_input("Enter ... |
# coding=utf8
import statsd
from functools import wraps
import time
import pdb
server_host = '127.0.0.1'
print('连接%s...' % server_host)
try:
gran_client = statsd.StatsClient(server_host, 8125, prefix='patae')
except Exception:
raise Exception('连接statsd失败!请检查环境配置')
print('连接statsd成功!!')
def get_client_ip(... |
from rest_framework import serializers
from core.models import FoodGroup
class FoodGroupSerializerList(serializers.ModelSerializer):
components = ""
class Meta:
model = FoodGroup
fields = [
'id',
]
class FoodGroupSerializerDetail(serializers.ModelSerializer):
compon... |
import logging
import logging.config
from functools import lru_cache
from fastapi import Depends
from core.config import config
from core.logger import LOGGING
from services.datastore import DataStore, get_data_store
from services.genre import Genre
from services.movie import Movie
from services.person import Person... |
from discomll import dataset
from discomll.classification import linear_svm
train = dataset.Data(data_tag=["http://ropot.ijs.si/data/ionosphere/train/xaaaaa.gz",
"http://ropot.ijs.si/data/ionosphere/train/xaaabj.gz"],
data_type="gzip",
generate_u... |
from django.conf.urls import url
from .views import admin_search
urlpatterns = [
url(r'^search/$', admin_search, name="search")
] |
#!/usr/bin/python
import unittest, logging
import sys, time
from voyagerTest import VoyagerTest
from voyagerBaseSuite import VoyagerTestSuiteBase
logging.basicConfig(stream=sys.stderr)
log = logging.getLogger('VoyagerSuite')
log.setLevel(logging.DEBUG)
class VoyagerXponderGlobalTests(VoyagerTestSuiteBase):
def su... |
from serif.model.mention_model import MentionModel
class EmptyMentionSetModel(MentionModel):
"""Adds empty mention set to sentence.
Depenency parses rely on having a mention set, so this could be
necessary even if you don't care about mentions."""
def __init__(self, **kwargs):
super(Em... |
#!/home/michkail/Documents/Django-project/Djangonautic/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
#!/usr/bin/env python
import dialogflow_v2
import os
import wave
from subprocess import call
import rospy
from std_msgs.msg import String
global WAVE_OUTPUT_FILENAME
polly = rospy.Publisher('polly_listen',String,queue_size = 10)
drum = rospy.Publisher('drum',String,queue_size = 10)
face = rospy.Publisher('face',Stri... |
"""
LC290 - Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern... |
from rest_framework import serializers
from .models import TypeOf, Animal, vendorName
class PhotographerSerializer(serializers.Serializer):
id = serializers.IntegerField()
url = serializers.CharField(max_length=300)
class VendorNameSerializer(serializers.ModelSerializer):
class Meta:
model = vendorName
fiel... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 23:21:46 2019
@author: S. V. Rajeenth
"""
n = int(input())
dict= {}
for i in range (n):
dict[i]=i*i
print (dict) |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2016 SEEROO IT SOLUTIONS PVT.LTD(<https://www.seeroo.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-05 23:56
from __future__ import unicode_literals
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependenc... |
dependencies = ["torch", "captum"]
VERSION = "1.0.8"
import torch
from segnet.network import SegNet
from segnet_V2.network import SegNetV2
from speed.network import VideoResNet
from depth.network import DisparityNet, URes
def segnet(pretrained=False, **kwargs):
"""
:param pretrained: Loads the model weights... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
def cnn_net(inputs,bottleneck_layer_size=128,dropout_keep_prob=0.8, is_training=True, scope='cnn_net', reuse=None):
with tf.variable_scope(sc... |
import pandas as pd
import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
import csv
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from os import listdir
from keras.preprocessing import sequence
import tensorflow as tf
from tensorflow.keras.models import Sequential
from ten... |
#Find first instance and replace
words = "It's thanksgiving day. It's my birthday,too!"
print words
print words.find("day") # finds the index position where a specific sequence starts first time in a string
words = words.replace("day", "month") # replacing all specified sequences in a string with a different sequence p... |
from flask import jsonify, request, url_for, current_app, abort
from .. import db
from ..models import Cidade, Estado
from . import api
from sqlalchemy.exc import IntegrityError
@api.route('/cidades/')
def get_cidades():
cidades = Cidade.query.all()
return jsonify({'cidades': [cidade.to_json() for cidade in ci... |
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from lib_nrf24 import NRF24
import time, sys, argparse
import spidev
from lib_protocol_shortrange import *
import os
def _BV(x):
return 1
def setupRadio(CE):
CHANNEL = 0x52 # 2.482 Hz
#POWER = NRF24.PA_MAX
POWER = NRF24.PA_HIGH
#POWER = NRF24... |
# coding=utf-8
# FRC Vision 2016
# Copyright 2016 Vinnie Magro
#
# 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... |
import os
import argparse
import uuid
import pafy
import pickle
def download_vids(options):
# mkdir
if not os.path.exists("downloaded_vids/"):
os.makedirs("downloaded_vids/")
# load data
try:
with open(args.filepath, 'rb') as f:
data = pickle.load(f)
print('Data fil... |
import argparse
import json
import matplotlib.pyplot as plt
import numpy as np
import os.path
import math
import operator
def get_g(m):
media = 1
num = 0
s=0
for i in m:
if i!= 0:
if num != 0:
media *= i
s+=1
num+=1
media = media **(1/s)
return media
def getPrecisionAndRecallCurve(idealDocumen... |
# Importing the required libaries
import pandas as pd
import numpy as np
import os
# checking the working directory
os.getcwd()
# Stating the file location
xls = pd.ExcelFile ('https://github.com/MeshalALMarzuqi/SaudiMultiplier/raw/main/SnU2016.xlsx')
# Reading the data in pandas DataFrame
df = pd.r... |
from flask import Flask, render_template
from requests import get
app = Flask(__name__)
@app.route("/")
def index():
return "Hello World!"
@app.route("/video")
def show_video():
videos = get("http://127.0.0.1:5000/api/v1/videos/").json()
return render_template("video.html", videos=vid... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 06:08:38 2018
@author: mimbres
"""
q=np.ascontiguousarray(dt_mm[:, 4:8]).view(np.uint32).flatten()
total_cnt = 0
for file_count, fpath in enumerate(glob.glob(os.path.join(TR_LOG_DATA_ROOT, "*.csv"))):
with open(fpath) as f:
cnt_this... |
import collections
import math
import numpy as np
import pandas as pd
from model.message import Message
from stats.iConvStats import IConvStats
from stats.wordsCountStats import WordsCountStats
from util import statsUtil
class ConvStatsDataframe(IConvStats):
def __init__(self, conversation):
super().__i... |
from telnetserver import TelnetServer
server = TelnetServer()
clients = []
while True:
# Make the server parse all the new events
server.update()
# For each newly connected client
for new_client in server.get_new_clients():
# Add them to the client list
clients.append(new_client)
... |
"""
Functions for the spin up simulation to obtain realistic initial conditions
"""
import sys; sys.path.append("../../build-cmake/cpp/python_binding/"); sys.path.append("../modules/");
sys.path.append("../../../CPlantBox/src/python_modules"); sys.path.append("../../../CPlantBox/");
import numpy as np
import timeit
... |
from veterinary import app
from flask import render_template, redirect, url_for, flash, request
from veterinary.forms import *
from flask_login import logout_user, login_required, current_user
from veterinary.functions.register import register_client, register_veterinarian
from veterinary.functions.utils import flash_f... |
### Standard Library Imports
from sys import *
import os
import shutil
import difflib
from datetime import datetime
### Django Imports
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
from django.contrib.gis.geos import Point
### P... |
import torch
import copy
import json
import tqdm
import random
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.optim as optim
from pandas import DataFrame
import torch.nn.functional as F
import protobuf.protobuf_modify.message1_pb2 as message
from protobuf.protobuf_modify.message1_... |
# RUN: python %s > %t
# RUN: %diff %s.expect %t
print('FOO 0x6513270e269e0d37')
print('FOO 0xc5c7fd0a6a3a450')
print('FOO 0x1818e811892f902b')
print('FOO 0x36f675cc81e74ef5')
print('FOO 0x1600a35a099950d8')
print('FOO 0x6b0d549b6f03675a')
print('FOO 0x3d9c172411e20b8f')
print('FOO 0xf21ddb66cad4a26')
print('FOO 0xfd630... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('', include('core.urls', namespace='c... |
"""
Verifies that ios watch extensions and apps are built correctly.
"""
from __future__ import print_function
import TestGyp
from XCodeDetect import XCodeDetect
test = TestGyp.TestGyp(formats=['ninja', 'xcode'], platforms=['darwin'], disable="This test is currently disabled: https://crbug.com/483696.")
if XCodeDet... |
import praw
from pymongo import MongoClient
from data import *
client = MongoClient(
'YOUR URL')
print(client.server_info())
reddit = praw.Reddit(client_id='YOUR_ID',
client_secret='YOUR_SECRET', user_agent='agent')
subreddit = 'wallstreetbets'
db = client.wallstreettexts
for comment in red... |
class Zone:
def __init__(self, zone_id):
"""Create and initialize a new zone.
a) zone_id: Id of new zone.
"""
self.zone_id = zone_id
self.points = []
self.size = 0
self.center = (0, 0)
self.entry_points = {}
def update_center(self):
... |
from behave import given, then, when
@given(u'a set of specific users')
def step_impl(context):
context.user_dict = {}
for row in context.table:
if row['department'] in context.user_dict:
context.user_dict[row['department']] = context.user_dict[row['department']] + 1
else:
... |
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
import mglearn
import pandas as pd
from sklearn.preprocessing import StandardScaler
################# matplotlib 한글 ... |
ler idade e informar se sobre alistamento: já passou, ainda não está na hora, chegou a hora
também mostrar o tempo que falta, ou que já está atrasado |
from flask import redirect
from flask import url_for
def logout(request, session):
session.clear()
return redirect(url_for('route_home')) |
#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2020-2022 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/mystic/blob/master/LICENSE
"""
Example applying mystic to skle... |
from .util import *
from .composable import *
from .pipe import *
from .infix import *
from .stream import *
from .placeholder import *
|
# !/usr/bin/env python
# encoding: utf-8
"""
SEED Platform (TM), Copyright (c) Alliance for Sustainable Energy, LLC, and other contributors.
See also https://github.com/seed-platform/seed/main/LICENSE.md
"""
from rest_framework import serializers
from seed.models import AnalysisInputFile
class AnalysisInputFileSeria... |
from utils import common
from models.caseSuite import CaseSuite
from models.testingCase import TestingCase
from models.mailSender import MailSender
from testframe.interfaceTest.tester import tester
from models.testReport import TestReport
import pymongo
from bson import ObjectId
import datetime
import requests
class ... |
#!/usr/bin/env python
def AppendPreliminaryToSummaryFile(summaryFile, PowerUnitID, tester, posVoltage, posCurrent, negVoltage, negCurrent):
lines = []
if PowerUnitID == "Right":
lines.append("----------------------------------- Summary file -------------------------------------")
lines.append("... |
import json
from django.core.serializers.json import DjangoJSONEncoder
from tastypie.serializers import Serializer
from django.http.response import HttpResponse
class PrettyJSONSerializer(Serializer):
json_indent = 2
def to_json(self, data, options=None):
options = options or {}
data... |
import pygame
from pygame.math import Vector2
class SuperAlien(object):
def __init__(self,game):
self.game = game
self.speed = 0.55
self.x = 1280
self.y = 54
self.toDestroy = False
def move(self):
self.x -= self.speed
def destroy(self):
self.toDe... |
import os
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'RbiCloud.settings'
application = get_wsgi_application()
from cloud import models
import argparse
import json
from datetime import datetime
def parse_command_line_args():
parser = argparse.ArgumentParser()
par... |
'''
Created on Oct 14, 2018
@author: Priyank007
'''
daily_Groceries = {'milk', 'eggs', 'bread','beer', 'butter', 'beer'}
print(daily_Groceries)
if 'milk' in daily_Groceries:
print("You already have milk hoss!")
else:
print("Yeah, you do need milk!") |
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
import sys
if len(sys.argv)>1:
executable_path = sys.argv[1]
else:
executable_path = "windows/chromedriver.exe"
prefix = raw_input("file prefix:")
a... |
from collections.abc import Sequence
def my_islice(seq, begin, stop, step=None):
assert isinstance(seq, Sequence)
idx = 0
while idx < stop:
if idx >= begin:
yield seq[idx]
idx += 1
if __name__ == '__main__':
# 用于从可迭代对象中创建指定切片范围内的生成器
nums = [num for num in range(100)]
... |
import stripe
import json
import copy
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import r... |
from django.conf.urls.defaults import *
urlpatterns = patterns('addition.views',
(r'^get_question$', 'get_question'),
(r'^post_answer$', 'store_answer_and_return_evaluation'),
(r'^get_dominance_questions$','dominance_question_data'),
)
|
#
# Policy interface and parametric policy classes.
#
# @contactrika
#
import numpy as np
class Policy:
def __init__(self):
pass
def get_action(self, obs, t):
pass
def get_params(self):
pass
def set_params(self, params):
pass
def resample_params(self):
p... |
import logging
from ComunioScore.db import DBConnector, DBInserter, DBFetcher
from ComunioScore.db import DBCreator, Schema, Table, Column
from ComunioScore.exceptions import DBConnectorError, DBInserterError
class DBHandler:
""" Base class DBHandler which provides database actions for subclasses
USAGE:
... |
import threading
import queue
import logging
import time
import requests
try:
from app.MFRC522.MFRC522 import MFRC522
except ImportError:
try:
from MFRC522.MFRC522 import MFRC522
except:
raise
import zmq
try:
import rfid_faker
except:
impor... |
from rest_framework import serializers
from .models import *
class PublicationSerializer(serializers.ModelSerializer):
# subgroup = SubgroupSerializer()
class Meta:
model = Publication
fields = '__all__'
class AwardSerializer(serializers.ModelSerializer):
class Meta:
model = Award... |
"""
Useful for searching information in SORTED arrays / lists.
The idea of the binary search is to use the information that the data is sorted and reduce the time complexity
from O(n) in case of linear search to O(log(n)) in case of binary search.
"""
def binary_search_recursive(arr, val):
# If the input ar... |
# Copyright (c) Microsoft 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 applicable law or agreed to in wri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.