content stringlengths 5 1.05M |
|---|
#!/bin/env python3
# MIT License
# Copyright (c) 2019-2022 Andrew Payne
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
# -*- coding: utf-8 -*-
class Shop(object):
def __init__(self, id, name, lat, lng, tags=None):
self.id = id
self.lng = lng
self.lat = lat
self.name = name
if tags is None:
tags = []
# tags should have relation to product not shop
# since the se... |
import model
from datetime import datetime
import dateutil
from datetime import date
from unittest import TestCase
from dateutil.relativedelta import relativedelta
error_locations = []
def error_dealer(storyType,definition, location):
if isinstance(location, list):
# print("yes")
loc... |
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import sqlite3
CONN_STRING = '/media/sf_VBox_Shared/CaseLaw/caselaw.db'
def get_connection():
conn = sqlite3.connect(CONN_STRING)
return conn |
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect, JsonResponse
from wye.base.constants import WorkshopStatus, Fe... |
"""
Este modulo contiene el codigo para la construccion de la GUI
"""
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import numpy as np
import sympy as sy
class GUI():
def __init__(self):
pass
def Interfaz(self):
#Crear la interfaz grafica de usuario
self.Win... |
import logging
import abc
import time
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mshoot.mshoot import MShoot
class MPCEmulation():
"""
MPC emulation is used to test an MPC strategy in a simulated
environment. Two models are required: (1) control model,
(2) ... |
# Libraries
from keras.models import Sequential # Layerları üzerine koyacağımız sıralı yapı, temel gibi düşünülebilir
from keras.layers import Conv2D, MaxPooling2D, Activation, Flatten, Dense, Dropout # Kullanılacak CNN layerları
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
import ma... |
import sys
import math
class Proportional:
def __init__(self, gain, target):
self.gain = gain
self.target = target
def error(self, value):
x, y = value
tx, ty = self.target
return math.sqrt((tx-x)**2 + (ty-y)**2)
def input(self, value):
return self.gain * s... |
# --------------------------------------------------------------------------- #
# PIECTRL Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 31 Oct 2005
# Latest Revision: 30 Nov 2009, 17.00 GMT
#
#
# TODO List/Caveats
#
# 1. Maybe Integrate The Very Nice PyOpenGL Implementation Of A PieChart Coded
... |
import pygame
import random
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = ( 0, 0, 255)
class MyEllipse(pygame.sprite.Sprite):
def __init__(self, color, width, height):
"""
Ellipse Constructor. Pass in the color of the ellipse,
a... |
from django.urls import path
from .views import about_page
urlpatterns = [
path('', about_page, name='about')
]
|
from PySide2.QtWidgets import QWidget
from PySide2.QtGui import QPixmap, QMouseEvent, Qt
from PySide2.QtCore import QRect, QTimer
from ui.interesting_ui import Ui_Interesting
class Interesting(QWidget, Ui_Interesting):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
... |
"""HADDOCK3 actions referring to refinement."""
|
import os
from django.conf import settings
from django.contrib.auth import logout as django_logout
from django.contrib.sites.models import Site
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from luna_django_commons.app.mixins imp... |
"""create table game
Revision ID: aeab08c9fd34
Revises: a81e5dd18927
Create Date: 2019-08-11 16:59:53.968757
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = 'aeab08c9fd34'
down_revision = 'a81e5dd18927'
branch_labels = None
depends_on = None
def upgrade():
... |
# -*- coding: utf-8 -*-
from mockdown.mockdown import Mockdown
class TestMockdown:
def test_exists(self, tmpdir):
m = Mockdown(tmpdir.strpath)
assert m.exists("a.txt") is False
tmpdir.join("a.txt").write("hello")
assert m.exists("a.txt") is True
def read_yaml_file(self, tmpdir... |
#!/usr/bin/env python
import chainer
from teras import training
from teras.app import App, arg
from teras.utils import git, logging
from tqdm import tqdm
import dataset
import eval as eval_module
import models
import parsers
import utils
chainer.Variable.__int__ = lambda self: int(self.data)
chainer.Variable.__floa... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... |
# Copyright (c) 2020 fortiss GmbH
#
# Authors: Julian Bernhard, Patrick Hart
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
try:
import debug_settings
except:
pass
import unittest
import numpy as np
from gym import spaces
# BARK imports
... |
# coding=utf-8
"""Generate the pickle file of 1b_corpus dataset"""
import os
import pickle
from multiprocessing import Process, Queue
from Queue import Empty # Exception raised when a Queue is empty
from time import ctime
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize as wt
def process_d... |
import unittest2 as unittest
from mock import DEFAULT, Mock, MagicMock, patch, create_autospec, call
import sys, time, re
THIS_MODULE = sys.modules[__name__]
class ClassUnderTest(object):
def __init__(self):
self._collaborator = Collaborator()
def do_something(self, foo, bar, *args, **kwargs):
... |
import torch.nn as nn
def initialize_weights(*models):
for model in models:
for module in model.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight)
if module.bias is not None:
m... |
# This is licensed under Apache-2.0 OR MIT |
from simfin.tools import account
class equalization(account):
'''
Classe permettant d'intégrer les revenus issus de la péréquation et de la formule de financement des territoires (FFT).
Parameters
----------
iprice: boolean
Switch pour intégrer ou non la croissance du niveau général des p... |
#!/bin/env python3
# Author : freeman
# Date : 2021.03.25
# Desc : This software will export by default the past year STOCK price {high, low, open, close}
# : Financialmodelingprep doesnt have all the Class-C mutual fund types.
# : yet, it is the only site with API listngs of Cryptocurrencies.
... |
from fastapi.testclient import TestClient
from depot_server.api import app
from depot_server.helper.auth import Authentication
from depot_server.model import BayInWrite, Bay
from tests.db_helper import clear_all
from tests.mock_auth import MockAuthentication, MockAuth
def test_bay(monkeypatch, motor_mock):
monke... |
"""
Radix Sort
In computer science, radix sort is a non-comparative integer sorting
algorithm that sorts data with integer keys by grouping keys by the
individual digits which share the same significant position and value.
A positional notation is required, but because integers can represent
strings of characters ... |
from django import forms
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm, UserCreationForm
from django.contrib.auth.models import User
from mainapp.models import Tickets, News, UserProfile
class NewsForm(forms.ModelForm):
class Meta:
model = News
fields = (
't... |
from flask import Flask, request, render_template
from flask_pymongo import PyMongo
from CSVtogeoJSON import convert, panda_processing
from geojson import Feature, FeatureCollection, Point
import pandas as pd
import os
import json
from flask_restful import reqparse
# Install Redis to help with caching?
#from flask_ca... |
# Copyright (c) 2019 Karl Sundequist Blomdahl <karl.sundequist.blomdahl@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the righ... |
filename = "VehiclesItaly.txt"
X = []
y = []
with open(filename, 'r') as f:
for line in f.readlines():
xt, yt = [float(i) for i in line.split(',')]
X.append(xt)
y.append(yt)
# Train/test split
num_training = int(0.8 * len(X))
num_test = len(X) - num_training
import numpy as np
# ... |
from __future__ import unicode_literals
import base64
import datetime
import hashlib
import hmac
from requests import Session
from requests.auth import AuthBase
import six
from six.moves.urllib import parse
from . import __version__, repo_url
from .exceptions import InvalidCredentials
class BelugaAPIAuth(AuthBase)... |
from .throttling import rate_limit
from . import logging
from . import in_inline
|
import os.path
pytest_plugins = [
'mypy.test.data',
]
def pytest_configure(config):
mypy_source_root = os.path.dirname(os.path.abspath(__file__))
if os.getcwd() != mypy_source_root:
os.chdir(mypy_source_root)
# This function name is special to pytest. See
# http://doc.pytest.org/en/latest/writ... |
REWARD = 10 ** 20
WEEK = 7 * 86400
LP_AMOUNT = 10 ** 18
def test_claim_no_deposit(accounts, chain, liquidity_gauge_reward, reward_contract, coin_reward):
# Fund
coin_reward._mint_for_testing(REWARD, {'from': accounts[0]})
coin_reward.transfer(reward_contract, REWARD, {'from': accounts[0]})
reward_con... |
""" Distribution specific override class for Gentoo Linux """
import pkg_resources
import zope.interface
from certbot import interfaces
from certbot_apache import apache_util
from certbot_apache import configurator
from certbot_apache import parser
@zope.interface.provider(interfaces.IPluginFactory)
class GentooCon... |
#!/bin/env python
#
# File: RDKitPerformMinimization.py
# Author: Manish Sud <msud@san.rr.com>
#
# Copyright (C) 2020 Manish Sud. All rights reserved.
#
# The functionality available in this script is implemented using RDKit, an
# open source toolkit for cheminformatics developed by Greg Landrum.
#
# This file is part ... |
from tutorial import math_func
import sys
import pytest
@pytest.mark.skipif(sys.version_info < (3, 3), \
reason="I don't want to test this.")
def test_add():
assert math_func.add(7, 3) == 10
assert math_func.add(7) == 9
assert math_func.add(5) == 7
print("hello")
@pytest.mark.number
def test_pro... |
"""
(Pseudo-) Orthogonal Linear Layers. Advantage: Jacobian determinant is unity.
"""
import torch
from bgflow.nn.flow.base import Flow
__all__ = ["PseudoOrthogonalFlow"]
# Note: OrthogonalPPPP is implemented in pppp.py
class PseudoOrthogonalFlow(Flow):
"""Linear flow W*x+b with a penalty function
pena... |
# Generated by Django 2.0.7 on 2018-07-23 10:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0010_remove_populationdetailed_code'),
('api', '0013_merge_20180723_0744'),
]
operations = [
]
|
from math import sqrt
from unravel.text.readability import BaseReadability
from unravel.text import ReadingLevel
class SimpleMeasureOfGobbledygook(BaseReadability):
"""
The SMOG grade is a measure of readability that estimates the years of education needed to understand a
piece of writing. It gives the e... |
# Copyright 2021 Testing Automated @ Università della Svizzera italiana (USI)
# All rights reserved.
# This file is part of the project SelfOracle, a misbehaviour predictor for autonomous vehicles,
# developed within the ERC project PRECRIME
# and is released under the "MIT License Agreement". Please see the LICENSE
# ... |
# Transposition Cipher Hacker
from .transposition_decryption import decrypt_message
def main():
my_message = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1
hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaetee oinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit... |
from brightics.common.repr import BrtcReprBuilder, strip_margin, pandasDF2MD, plt2MD
from brightics.function.utils import _model_dict
from brightics.common.groupby import _function_by_group
from brightics.common.utils import check_required_parameters
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
import spacy
# Import the Matcher
from spacy.matcher import Matcher
# Load a model and create the nlp object
nlp = spacy.load("en_core_web_sm")
# Add the pattern to the matcher
pattern = [{"TEXT": "iPhone"}, {"TEXT": "X"}]
# Process some text
doc = nlp("Upcoming iPhone X release date leaked")
def print_doc(doc, pa... |
import requests
import logging
import time
import json
from utils import *
class Executor():
def __init__(self):
pass
def execute(self, pre_request):
try:
for key, value in Config.static_cookies.items():
pre_request.cookies[key] = value
start = time.ti... |
"""
This module contains models in database, this module defines the
following classes:
- `ModelMixin`, base model mixin used in every other model;
- `User`, user model;
- `Chat`, chat model;
- `Message`, message model.
"""
from __future__ import annotations
from datetime import datetime ... |
# lc643.py
# LeetCode 643. Maximum Average Subarray I `E`
# 1sk | 98% | 9'
# A~0g17
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
maxsum = cursum = sum(nums[0:k])
for i in range(len(nums)-k):
cursum += nums[i+k] - nums[i]
maxsum = max(cursum, m... |
import json
import boto3
import cattrs
from src.common.constants import NEWS_STORIES_TABLE_NAME, S3_BUCKET_NAME
from src.common.enums.api_response_codes import APIResponseCodes
from src.common.models.news_story import NewsStory
from src.common.services.dynamodb import DynamoDB
from src.common.services.lambda_ import ... |
import sys
from socket import *
for line in sys.stdin:
if len(line) == 0: break
clientSocket = socket(AF_INET, SOCK_STREAM)
hostPort = 15132
host_name = "comp431bfa19"
clientSocket.connect((host_name, hostPort))
stream = clientSocket.makefile('rw')
# write the input line to the server
... |
from enum import Enum
from collections import namedtuple
class PacketProvenance(Enum):
server = 0x01
client = 0x02
class EliteAbility(Enum):
stealth = 0x0001
low_vis = 0x0002
cloak = 0x0004
het = 0x0008
warp = 0x0010
teleport = 0x0020
tractor = 0x0040
drones = 0x0080
anti_m... |
from random import randint
class Food:
def __init__(self, canvas, x, y, r=10, color="green", points=1, decay=0):
self.x = x
self.y = y
self.r = r
self.color = color
self.points = points
self.decay = decay
self.init_body(canvas)
def init_body(self, canva... |
import numpy as np
from keras import callbacks
from keras.optimizers import SGD
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
"""
This script is used to create models and determine hyperparameters
such as batch size, training epochs, and loss functions by gri... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
# Libraries
import paramiko
count = 1
def connectSSH(hostname, port, username, passFile):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
with open(passFile, "r") as f:
global count
for password in f.readlines():
password = ... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
# GN version: //ios/chrome/app
'target_name': 'ios_chrome_app',
'type'... |
import boto3
import json
import os
def lambda_handler(event, context):
bucket = os.environ['BUCKET']
path = 'batch-incoming/'
resp = boto3.client('s3').list_objects_v2(
Bucket=bucket,
Prefix=path,
MaxKeys=1000
)
keys = list()
if 'Contents' in resp:
for content... |
#!/usr/bin/env python
from __future__ import print_function
import sys,os
import re
import argparse
import logging
desc = 'Converting "contigs_report_contigs_filtered.mis_contigs.info" to a tsv table'
epi = """DESCRIPTION:
Only mis-assembly contigs will be included.
Output table columns:
*) contig ID
*) misassembly t... |
from ezcoach import Runner
from ezcoach.agent import Learner
from ezcoach.enviroment import Manifest
class RandomAlgorithm(Learner):
def __init__(self, num_episodes):
self._num_episodes = num_episodes
self._manifest: Manifest = None
def do_start_episode(self, episode: int) -> bool:
r... |
from .docs_index_generator import make_doc_index
from .log_generator import parse_md, generate_log
from bs4 import BeautifulSoup
from distutils.dir_util import copy_tree
from jinja2 import Template
from glob import glob
import janus
import mistune
import os
import re
import sys
import shutil
def parse():
parser... |
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView
from django.contrib import messages
from project.models import MenuItem, Feedback
from cart.forms import CartAddProductForm
from resto.forms import ReservationForm, ContactForm
from django.views.decorators.csrf import csrf_ex... |
from sympy import *
from sympy import simplify
from scipy.interpolate import lagrange
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#2a
def lang(x_i,y_i):
x= symbols('x')
if len(x_i)==len(y_i):
yp=0
for i in range(len(x_i)):
p=1
for j in range(len(x_i... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-02-08 16:23:16
# @Last Modified by: 何睿
# @Last Modified time: 2019-02-08 17:58:28
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.lef... |
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Assets.Objects.FText import FText
class FNavAgentSelectorCustomization:
SupportedDesc: FText
def __init__(self, reader: BinaryStream):
self.SupportedDesc = FText(reader)
|
from helpers.mockdbhelper import MockDBHelper
from flask import Flask, redirect, request, url_for, render_template
from htmlmin.main import minify
from application.mod_authentication.models import UserMix
from config import MOCK_TEST, DEBUG, APP_NAME
from helpers.dbhelper import DB as DB_CON
from helpers.loginhelper i... |
#####
# @brief Visualize a given dDCA dataset
#
# Python script to generate a SVG graph of the data of a given dDCA
# dataset via matplotlib. It generates one figure with three subplots:
# 1.) use case-related data (air/soil temperature/humidity)
# 2.) self-diagnostic data (fault indicators) & fault label
# 3.) dang... |
from . import config_folder
|
import logging
from datetime import datetime, timedelta
from src.models import TrackTrendingScore, TrendingParam, AggregateIntervalPlay
from src.utils.db_session import get_db
from src.tasks.generate_trending import generate_trending
from src.trending_strategies.aSPET_trending_tracks_strategy import (
TrendingTrac... |
class VulnerabilityNotTrigger(Exception):
pass
class ExecutionError(Exception):
pass
class AbnormalGDBBehavior(Exception):
pass
class InvalidCPU(Exception):
pass |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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... |
from . import dcosauth
from . import dcosawsstack
from . import dcosawssg
from . import dcosdnsalias
|
import bayesnewton
import objax
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
from sklearn.preprocessing import StandardScaler
from convertbng.util import convert_bng
import time
def datetime_to_epoch(datetime):
"""
Converts a datetime to a number
... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import subprocess
import tempfile
from base64 import b64encode
from django.conf import settings
from django.utils.encoding import force_text
import six
from PIL import Image
import olympia.core.logger
from olympia.lib.safe_xml import lxml
log = olympia.core.logger.getLogger('z.versions.utils')
def w... |
n = int(input("Enter n: "))
x = int(input("Enter x: "))
power = 0
z = 0
st = ""
while n >= 1:
while x**power <= n:
power += 1
z = power - 1
n = n - x**z
st = "+" + str(x) + "^" + str(z) + st
power = 0
print(st)
|
# Binary Tree Level Order Traversal - Breadth First Search 1
# Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
... |
from dns.resolver import Resolver, query, NXDOMAIN
import dns.query
from dns.exception import Timeout
from dns.message import make_query
from dns.rdatatype import NS
import socket
from random import choice
def get_zone_nameservers(zone):
nss = []
for answer in query(zone, 'NS'):
nss.append(socket.getho... |
# -*- coding: utf-8 -*-
import uuid
URL_TEMPLATE = "{scheme}://{domain}/{path}"
def get_uuid_from_query_params(request, param):
"""
return uuid from a given queryset after parsing it.
"""
param_field = request.query_params.get(param, None)
if param_field:
try:
return uuid... |
#!/usr/bin/env python
NAME = 'NAXSI (NBS Systems)'
def is_waf(self):
# Sometimes naxsi waf returns 'x-data-origin: naxsi/waf'
if self.matchheader(('X-Data-Origin', r'^naxsi(.*)?')):
return True
# Found samples returning 'server: naxsi/2.0'
if self.matchheader(('server', r'naxsi(.*)?')):
retur... |
from justgood import imjustgood
api = imjustgood("YOUR_APIKEY_HERE")
data = api.youtubedl("https://youtu.be/kJQP7kiw5Fk")
print(data)
# EXAMPLE GET CERTAIN ATTRIBUTES
result = "Title : {}".format(data["result"]["title"])
result += "\nAuthor : {}".format(data["result"]["author"])
result += "\nDuration : {}".format(d... |
from datadog_custom_logger.handler import DatadogCustomLogHandler
import logging |
import falcon
import json
class Home:
def on_get(self, req, res):
hello = {
'hello': 'world'
}
res.data = json.dumps(hello).encode('utf-8')
res.status = falcon.HTTP_200
|
import codecs
import re
import os
import sys
try:
from setuptools import setup
except:
print('please install setuptools via pip:')
print(' <pip_exe> install setuptools')
sys.exit(-1)
def find_version(*file_paths):
version_file = codecs.open(os.path.join(os.path.abspath(
os.path.dirname(__file__))... |
"""
All function stubs that make up a muFAT run are implemented here. Essentially,
a 'stub' is any function that when called once inside a run performs any number
of tasks, while hiding the underlying nitty gritty details of mucking about with
muvee's COM interfaces.
All of these function stubs will be imported ... |
from utils.default import factor_db
from utils.spark_app import MovieDataApp
spark = MovieDataApp().spark
def get_match_id():
# movie_play有的aid对应多个qid,以aid去重
ys_df = spark.sql("select qid, aid ys_id, cid from {}.movie_play".format(factor_db)).dropDuplicates(['ys_id'])
# db_asset_source这个表aid有重复的,去重
o... |
import os.path
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.exceptions import InvalidSign... |
from django import forms
from .models import Detail, Calc, Comment, FurnitureInCalc
class DetailForm(forms.ModelForm):
"""Форма для работы с деталями."""
class Meta:
model = Detail
exclude = [""]
class CommentForm(forms.ModelForm):
"""Форма для работы с коментариями."""
class Meta:
... |
from flask import Blueprint, render_template, redirect, url_for
from app.forms.property import LandingAddressForm
from app.models.address import Address
from app.models.property import Property
bp = Blueprint('landing', __name__)
@bp.route('/', methods=['GET', 'POST'])
def index():
form = LandingAddressForm()
... |
# Generated by Django 4.0 on 2021-12-18 20:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(a... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
import main
import json
import logging
import os
import urllib
import webapp2
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
f... |
# Generated by Django 3.0.4 on 2021-01-12 10:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scout', '0004_auto_20200417_1034'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='sampling_techni... |
######################################
# File Name : mqtt_message
#
# Author : Thomas Kost, some edits by Nico
#
# Date: October 24, 2020
#
# Breif : file generalizing sending and recieving of MQTT messages
#
######################################
import json
import paho.mqtt.client as mqtt
import time
imp... |
from cs50 import get_string
from sys import exit
# Function for checking digits
def checkDigits(number):
revNumber = number[::-1]
total = 0
for i in range(countDigits):
oddStep = (i % 2 == 1)
currentDigit = int(revNumber[i])
# Add the sum of digits of double the number for ev... |
from biomaj2galaxy.config import get_instance
gi = get_instance('local')
def setup_package():
global gi
|
#!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... |
"""
read_sides extracts the sides from strings provided.
proper nomenclature of using sides in Maya is _l_ or l_, _L_, L_, left_ or _left, Left_, and _Left.
Each class supports iteration and __getitem__ extraction.
"""
# import standard modules
import json
import os
import re
# define local variables
sides_file = os.p... |
#!/usr/bin/env python
import sys
def load_program(filename):
with open(filename, 'rb') as f:
return [l.strip().split() for l in f.readlines()]
def execute(prog, pc, registers):
cmd = prog[pc]
print 'Executing', cmd
inst = cmd[0]
if inst == 'cpy':
x = cmd[1]
if x in registe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.