content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
DATA = b'\x00\x00\x01X\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x... | python |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all,-execution,-papermill,-trusted
# formats: ipynb,py//py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# ... | python |
#
# inputs outputs
# single sin
# simple sim
# solution so
# a a
#
class Node:
def __init__(self, val):
self.val = val
self.children = [0] * 26
self.is_end = False
self.word_count = 1
def get_unique_prefixes(words):
root = Node(0)
root.word_count += 1
... | python |
#!/usr/bin/python3
import json
import os
from ws_sdk import WS, ws_constants, ws_utilities
import logging
import sys
SCANNER_ID = "ws-gl-int"
LICENSE_SCHEMA_V = "2.1"
DEPENDENCY_SCHEMA_V = "14.0.2"
DEPENDENCY = "dependency"
DEPENDENCY_ALERTS_BASED = "dependency_alert_based"
LICENSE = "license"
VUL_DB_URL = "https://w... | python |
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import datetime
import... | python |
# Copyright 2020 Francesco Ceccon
#
# 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 writ... | python |
from .UserRepository import destroy, get_all, get_one_user
from .AuthenticationRepository import get_one, create, forgot_password, reset_password
from .WorkoutRepository import get_all, create, get_one, delete, update_one
from .ExerciseRepository import get_all, get_one, create, update_one, delete
from .SessionReposito... | python |
import pygame, sys
from pygame.locals import QUIT
pygame.init()
display_surface = pygame.display.set_mode((400, 300))
font = pygame.font.Font(pygame.font.get_default_font(), 32)
text = font.render('Hello World', True, (0, 0, 0))
textRect = text.get_rect()
while True:
display_surface.fill((255, 255, 255))
disp... | python |
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
import cocpit
import cocpit.pic as pic
sys.path.append("../")
import multiprocessing # noqa
def create_ellipse(campaign, desired_size, file):
if campaign == "OLYMPEX":
image = pic.Ima... | python |
from rest_framework.permissions import BasePermission
class SearchPermissions(BasePermission):
"""
DRF permission class that checks that the user has at least one of the permissions in the
view_permissions attribute on the search app.
"""
is_export = False
def has_permission(self, request, v... | python |
#!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# 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 requir... | python |
import os
import json
import logging
import tba_config
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from controllers.base_controller import LoggedInHandler
from datafeeds.datafeed_fms_api import... | python |
"""
Posix platform main process.
"""
from ....base import EventBus
def run_petronia(bus: EventBus) -> int:
print("Petronia for Posix environments started.")
return 0
| python |
# Copyright (c) OpenMMLab. All rights reserved.
from .anchor import * # noqa: F401, F403
from .bbox import * # noqa: F401, F403
from .evaluation import * # noqa: F401, F403
from .patch import * # noqa: F401, F403
from .post_processing import * # noqa: F401, F403
from .visualization import * # noqa: F401, F403
| python |
#!/usr/bin/env python
#appion
from appionlib import apPrepXmipp3D
from appionlib import apDisplay
class XmippPrepML3DRefinement(apPrepXmipp3D.XmippPrep3DRefinement):
def setRefineMethod(self):
self.refinemethod = 'xmippml3d'
#=====================
if __name__ == "__main__":
app = XmippPrepML3DRefinement()
app.s... | python |
from openbiolink.graph_creation.file_processor.fileProcessor import FileProcessor
from openbiolink.graph_creation.metadata_infile import InMetaOntoUberonIsA
from openbiolink.graph_creation.types.infileType import InfileType
from openbiolink.graph_creation.types.readerType import ReaderType
class OntoUberonIsAProcesso... | python |
"""
Implements Lydian converter.
"""
alpha_to_lydian = [
(r"a", "𐤠"),
(r"b", "𐤡"),
(r"p", "𐤡"),
(r"g", "𐤢"),
(r"d", "𐤣"),
(r"e", "𐤤"),
(r"v", "𐤥"),
(r"w", "𐤥"),
(r"i", "𐤦"),
(r"y", "𐤧"),
(r"k", "𐤨"),
(r"l", "𐤩"),
(r"m", "𐤪"),
(r"n", "𐤫"),
(r"o",... | python |
# Python - 3.6.0
cookie = lambda x: f'Who ate the last cookie? It was {"Zach" if type(x) is str else "Monica" if (type(x) is float) or (type(x) is int) else "the dog"}!'
| python |
import doctest
from insights.parsers import ls_var_opt_mssql
from insights.tests import context_wrap
LS_VAR_OPT_MSSQL_WRONG_PERM = """
drwxrwx---. 5 root root 58 Apr 16 07:20 /var/opt/mssql
""".strip()
LS_VAR_OPT_MSSQL_WRONG_PERM_2 = """
drwxrwx---. 5 mssql root 58 Apr 16 07:20 /var/opt/mssql
""".strip()
LS_VAR_OPT... | python |
import os
import sys
from typing import List
import click
from ruamel.yaml import YAML
from great_expectations import DataContext
from great_expectations.checkpoint.types.checkpoint_result import CheckpointResult
from great_expectations.cli import toolkit
from great_expectations.cli.pretty_printing import cli_message... | python |
from unittest import TestCase
from countpigs import CountPigs, directcountpigs, expect_val, f, p
class TestSimulation(TestCase):
def test_direct_count_cls(self):
c = CountPigs(5)
# (n, q, m, k) = (5, 1, 3, 2)
choice = c.choice(1)
choices = c.choices(1, 3)
choose =... | python |
import torch
import torch.nn.functional as F
from torch import nn
from torchvision import models
from torch.hub import load_state_dict_from_url
from ast import literal_eval
from itertools import chain
from .utils import gram_matrix
class ContentLoss(nn.Module):
def __init__(self, mode):
super(ContentLoss, ... | python |
""" The tests in this module compare the RESPY package to the original
RESTUD code for the special cases where they overlap.
"""
from pandas.util.testing import assert_frame_equal
import pandas as pd
import numpy as np
import subprocess
import pytest
from codes.random_init import generate_random_dict
from respy.pyt... | python |
from suplemon.linelight.color_map import color_map
class Syntax:
def get_comment(self):
return ("/*", "*/")
def get_color(self, raw_line):
color = color_map["white"]
line = str(raw_line)
if line.startswith("+"):
color = color_map["green"]
elif line.startswi... | python |
import numpy as np
def read_input():
with open("input.txt", "r") as file:
return [[int(c) for c in l] for l in file.read().splitlines()]
def get_neighbors(grid, y, x, v):
neighbors = [p for p in [(y-1,x),(y+1,x),(y,x-1),(y,x+1)] \
if 0 <= p[0] < grid.shape[0] and 0 <= p[1] < grid.shape[1] and ... | python |
import nltk
import random
import feedparser
urls = {
'mlb': 'https://sports.yahoo.com/mlb/rss.xml',
'nfl': 'https://sports.yahoo.com/nfl/rss.xml',
}
feedmap = {}
stopwords = nltk.corpus.stopwords.words('english')
def featureExtractor(words):
features = {}
for word in words:
if word not in sto... | python |
class ControlConfiguration(object):
def __init__(self, control_horizon, prediction_horizon, min_diff=1e-3, max_diff=0.15, diff_decay=0.8):
self.control_horizon = control_horizon
self.prediction_horizon = prediction_horizon
self.min_diff = min_diff
self.max_diff = max_diff
s... | python |
from flexitext.utils import listify
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.current = 0
def at_end(self):
return self.peek().kind == "EOF"
def advance(self):
self.current += 1
return self.tokens[self.current - 1]
def peek(self):
... | python |
import argparse
import polyscope as ps
import pickle
import os
import numpy as np
from mmcv import Config, DictAction
from mmdet3d.datasets import build_dataloader, build_dataset
def parse_args():
parser = argparse.ArgumentParser(
description='Visualize Results')
parser.add_argument('config', help='t... | python |
from flask.ext.mail import Mail, Message
from run import mail
def sendUserEmail(to, message):
header = 'Allez Viens User Contacted You'
sendEmail([to], header, message)
def sendValidationEmail(to, url):
header = 'Allez Viens Validation'
body = "Please click <a href='" + url + "'>this link</a> to validate and edit... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: data/exercise_route2.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflect... | python |
# Created by MechAviv
# Quest ID :: 32707
# [FriendStory] Student From Another World
sm.setIntroBoxChat(1530000)
sm.setSpeakerType(3)
sm.sendNext("Hello? Hello?\r\n\r\nOkay, the magician guy said he teleported the phone to someone who can help. So, um, hi? Can you help me, maybe?")
sm.setIntroBoxChat(1530000)
sm.set... | python |
# original: https://github.com/yukuku/telebot
# modified by: Bak Yeon O @ http://bakyeono.net
# description: http://bakyeono.net/post/2015-08-24-using-telegram-bot-api.html
# github: https://github.com/bakyeono/using-telegram-bot-api
#
# 구글 앱 엔진 라이브러리 로드
from google.appengine.api import urlfetch
from google.a... | python |
from . import overworld
from . import dungeon1
from . import dungeon2
from . import dungeon3
from . import dungeon4
from . import dungeon5
from . import dungeon6
from . import dungeon7
from . import dungeon8
from . import dungeonColor
from .requirements import AND, OR, COUNT, FOUND
from .location import Loca... | python |
'''
This object reads PCL files and prepare the microarray data as training set to DAs.
The input training vector can either be a gene's expression value over all sampels, or one
microarray sample with all genes' expression value. To feed into DAs, the
standard input dataset is a two-dimensional array with each row a... | python |
from setuptools import setup
setup(
name='budget',
version='1.2.2',
packages=['budget'],
entry_points={
'console_scripts': [
'budget=budget.__main__:main'
]
})
| python |
from Jumpscale import j
def main(self):
"""
to run:
kosmos 'j.data.types.test(name="iprange")'
"""
ipv4 = j.data.types.get("iprange", default="192.168.0.0/28")
assert ipv4.default_get() == "192.168.0.0/28"
assert ipv4.check("192.168.23.255/28") == True
assert ipv4.check("192.168.23.3... | python |
from typing import Optional
from pydantic import BaseModel, Field
class CodePayload(BaseModel):
id: str = Field(..., max_length=8)
code: str
description: Optional[str] = None
| python |
# -------------------------------------------------------------
# BASE: Simple script to score points for the facebook CTF
# -------------------------------------------------------------
#
# Written by Javier (@javutin)
import time
import json
import hashlib
import logging
from BaseHTTPServer import HTTPServer, BaseHT... | python |
from collections import defaultdict
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from symposion.proposals.kinds import get_kind_slugs, get_proposal_model
from email_log.models import Email
from pycon.models import PyConP... | python |
# -*- coding: UTF-8 -*-
import fnmatch
import logging
import re
import subprocess
import uuid
from threading import Thread
from .decorators import side_effecting
from .utils import create_sha1sum_file
class Action:
"""Абстрактный класс действия.
Attributes:
name: Строка, уникальное имя действия.
... | python |
"""Update invoice check constraint
Revision ID: 49e1c8c65f59
Revises: c45d12536d7e
Create Date: 2017-03-31 02:09:55.488859
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '49e1c8c65f59'
down_revision = 'c45d12536d7e'
branch_labels = None
depends_on = None
def... | python |
# Copyright (c) 2015 Mirantis Inc.
#
# 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 writ... | python |
from converter import Parser, Converter
test_cases = [
# LENGTH
"100 kmeter nfeet",
"1 nauticalmile meter",
"1 microleague millifoot",
"13 dlea Mft",
"1 ft fur",
"100 kilometer dafeet",
"1 ft m",
"17 kilord Gin"
# DATA
"10 kbyte Mb",
"8 bit byte",
"100 GiB Mibit",
... | python |
#
# The script providing implementation of structures and functions used in
# the Novelty Search method.
#
from functools import total_ordering
# how many nearest neighbors to consider for calculating novelty score?
KNN = 15
# the maximal novelty archive size
MAXNoveltyArchiveSize = 1000
@total_ordering
class Novelt... | python |
from timeit import default_timer as timer
# from datahelpers.data_helper_ml_mulmol6_OnTheFly import DataHelperMulMol6
from datahelpers.data_helper_ml_normal import DataHelperMLNormal
from datahelpers.data_helper_ml_2chan import DataHelperML2CH
from datahelpers.data_helper_ml_mulmol6_OnTheFly import DataHelperMLFly
from... | python |
#! /usr/bin/python
# transaction_csv_cleanup.py
# for Python 3
# Searches specified folder or default download folder for exported
# bank transaction file (.csv format) & adjusts format for YNAB import
# CHANGELOG
# 2017-09-29
# ~ Merged in parameters from https://www.reddit.com/user/FinibusBonorum
# ~ ... | python |
# ***************************************************
# SERVO test for duty cycle range
#
# ProtoStax Air Quality Monitor.
# using Raspberry Pi A+, Micro Servo SG92R, RGB LED and ProtoStax Enclosure for Raspberry Pi
# --> https://www.protostax.com/products/protostax-for-raspberry-pi-a
# You can also use
# -... | python |
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore, Qt
class QRoundProgressBar(QtGui.QWidget):
StyleDonut = 1
StylePie = 2
StyleLine = 3
PositionLeft = 180
PositionTop = 90
PositionRight = 0
PositionBottom = -90
UF_VALUE = 1
UF_PERCENT = 2
UF_MAX = 4
def __init__(se... | python |
from .parser import MopacParser
| python |
# -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
from bann.b_container.states.framework.pytorch.lr_scheduler_param import LrSchAlgWr, \
create_lr_sch_json_param_output
from bann.b_container.functions.pytorch.init_framework_fun import InitNetArgs
from bann.b_container.states.framework.pytorch.optim_param... | python |
from setuptools import setup, find_packages
setup(name='pyfdam',
version='0.1',
description='Code for fitting impedance data and simulating discharge experiments',
url='http://github.com/muhammadhasyim/pyfdam',
author='Muhammad R. Hasyim',
author_email='muhammad_hasyim@berkeley.edu',
... | python |
# from __future__ import print_function, division
from tensorflow.keras.layers import Input, Dense, Flatten, Dropout, UpSampling2D, Conv2D
from tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D, LeakyReLU, MaxPooling2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.ker... | python |
# Generated by Django 3.1.1 on 2020-11-06 15:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('devices', '0006_auto_20201105_1843'),
]
operations = [
migrations.AlterField(
model_name='modbu... | python |
''' sample dream '''
from dreamer import Dream
if __name__ == "__main__":
dream = Dream(dream_type='sex')
for i in range(10):
print dream.dream()
| python |
"""
/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the New BSD License, (the "License").
******************************************************************************/
"""
import argparse
import ... | python |
import os
import pickle
if __name__ == '__main__':
data_tag = 'tw_mm_s4' # 'tw_mm_s1' || 'tw_mm_imagenet_s2' || 'tw_mm_daily_s2'
data_dir = '../data/{}'.format(data_tag)
for data_tag in ['train', 'valid', 'test']:
print('\nComputing url map for %s' % data_tag)
src_fn = os.path.join(data_di... | python |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
pfjetEfficiency = DQMEDHarvester("DQMGenericClient",
subDirs = cms.untracked.vstring("HLT/JME/*"),
verbose = cms.untracked.uint32(0), # Set to 2 for all messages
resolution = cms.vstring(),
... | python |
class solution:
def capital(self,word):
count = 0
for i in range(len(word)):
if word[i] >= chr(65) and word[i] > chr(91):
count = count+1
if count == len(word):
return True
elif count == 0:
return True
... | python |
import numpy as np
from Bio.Seq import Seq
from .biotables import COMPLEMENTS, CODONS_SEQUENCES
def complement(dna_sequence):
"""Return the complement of the DNA sequence.
For instance ``complement("ATGCCG")`` returns ``"TACGGC"``.
Uses Biopython for speed.
"""
if hasattr(dna_sequence, "comple... | python |
#
# Generated with WinchBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.namedobject import NamedObjectBlueprint
class Winc... | python |
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import torchvision
from torchvision import transforms
def process_image(image_path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Process a PIL image for use in a PyTorch mode... | python |
from urllib.parse import urlparse
from wal_e.blobstore import wabs
from wal_e.operator.backup import Backup
class WABSBackup(Backup):
"""
A performs Windows Azure Blob Service uploads to of PostgreSQL WAL files
and clusters
"""
def __init__(self, layout, creds, gpg_key_id):
super(WABSBac... | python |
# ------------------------------------------------------------------------------------
# Comparision Operators in Python
# ------------------------------------------------------------------------------------
# So basically there are 6 Comparison Operators in Python , let us learn them one by one .
# Note : One more th... | python |
from game_parser import read_lines
from grid import grid_to_string
from player import Player
from cells import Start, End, Air, Fire, Water, Teleport, Wall
class Game:
def __init__(self, filename):
self.grid = read_lines(filename)
self.position = self.start_position(self.grid)
self.player = ... | python |
# import the necessary packages
import cv2
import math
import numpy as np
# canny edge method, not currently used
def find_edges(image):
grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
grey = cv2.GaussianBlur(grey, (17, 17), 0) # blur
grey = cv2.bilateralFilter(grey, 9, 75, 75) # what... | python |
from ...doc import *
cudaRT_thread = [
# 4.2. Thread Management [DEPRECATED]
func_decl( [ "cudaThreadExit" ] ),
func_decl( [ "cudaThreadGetCacheConfig" ],
[ parm_def('pCacheConfig', [MEMORY_HOST, SCALAR], INOUT_OUT ) ] ),
func_decl( [ "cudaThreadGetLimit" ],
[ parm_def('pValue', [MEMORY... | python |
import torch
import torch.nn as nn
import numpy as np
import itertools
import logging
from crowd_sim.envs.policy.policy import Policy
from crowd_sim.envs.utils.action import ActionRot, ActionXY
from crowd_sim.envs.utils.state import ObservableState, FullState
def mlp(input_dim, mlp_dims, last_relu=False):
layers ... | python |
from snovault import upgrade_step
@upgrade_step('award', '', '2')
def award_0_2(value, system):
# http://redmine.encodedcc.org/issues/1295
# http://redmine.encodedcc.org/issues/1307
rfa_mapping = ['ENCODE2', 'ENCODE2-Mouse']
if value['rfa'] in rfa_mapping:
value['status'] = 'disabled'
else... | python |
# example based on code from numpy library:
# https://github.com/numpy/numpy/blob/master/numpy/matlib.py
# https://github.com/numpy/numpy/blob/master/numpy/fft/fftpack.c
def ones(shape, dtype=None, order='C'):
# ...
static void radb3(int ido, int l1, const Treal cc[], Treal ch[],
const Treal wa1... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | python |
#codeing utf-8
class Solution(object):
def longest_common_subsequence(self,s):
lens = len(s)
if lens <= 1 :
return s
sleft,sright = 0,0
dp=[[0 for i in range(lens)] for j in range(lens)]
for i in range(1,lens):
dp[i][i] = True
dp[i][i-1] = ... | python |
#!/bin/python3
import sys
def isBalanced(s):
# Complete this function
str_len = len(s)
if((str_len < 2) or (str_len % 2 != 0)):
return "NO"
brackets_map = {')':'(', ']':'[', '}':'{'}
open_brckts = {'{','(','['}
stack = list()
bracket = ""
is_balanced = True
for i in ra... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 13 16:31:11 2014
@author: jc3e13
This module contains functions for investigating internal gravity waves.
All functions take angular frequency and wavenumber. Angular wavenumber is 2 pi
divided by the wavelength and angular frequency is 2 pi divided by the period.
"""
i... | python |
import json
import random
from copy import deepcopy
from datetime import datetime
from flask import Markup
from flask import Response, current_app, flash, redirect, url_for
from flask_admin.actions import action
from quokka.utils.text import slugify
class PublishAction(object):
@action(
'toggle_publish... | python |
import json
from dmscreen.data.data_loader import get_class_id
def ParseData():
f = open('dmscreen/data/allSpells.json',)
data = json.load(f)
id_ = 0
for i in data["allSpells"]:
classes = []
for s in i["classes"].split(", "):
classes.append(get_class_id(s))
i["cl... | python |
# BOT TOKEN
TOKEN = ""
| python |
import urllib.request
import zipfile
from os import remove, rename, listdir, path
from shutil import rmtree
import re
INVALID = re.compile(r'-.*', re.MULTILINE)
def download_deps(deps, libFolder):
for zipUrl in deps:
print('downloading from '+zipUrl)
urllib.request.urlretrieve(zipUrl, 'temp.zip')
... | python |
# Copyright 2018: Red Hat Inc.
# All Rights Reserved.
#
# 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... | python |
from django.views.generic.list import ListView
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from oppgavegen.models import Set, Chapter, Level
from oppgavegen.views.mixins import LoginRequiredMixin
from oppgavegen.view_logic.current_work impo... | python |
import argparse
import fsspec
import fv3config
def _parse_write_run_directory_args():
parser = argparse.ArgumentParser("write_run_directory")
parser.add_argument(
"config", help="URI to fv3config yaml file. Supports any path used by fsspec."
)
parser.add_argument(
"rundir", help="Desi... | python |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
f... | python |
#!/usr/bin/env python
import rospy
# from vanttec_uuv.msg import ThrustControl
from geometry_msgs.msg import Twist
thrust_pub = rospy.Publisher("/uuv_desired_velocity", Twist, queue_size=1000)
def remap_vel(src_vel):
des_vel = Twist()
des_vel.linear.x = src_vel.linear.x
des_vel.linear.y = -src_vel.linear... | python |
import sys
import os
import math
"""
Notes
- The trick here is to split the right hand side (RHS) of the equation into two
fractions i.e. x = -b/2/a +/- math.sqrt(discriminant)/2/a
- The discriminant is >= 0 for real roots and < 0 for imaginary roots
- For real roots: x1,2 = -b/2/a +/- math.sqrt(discriminant)/2/a as... | python |
from a10sdk.common.A10BaseClass import A10BaseClass
class HostList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param dns_host: {"minLength": 1, "maxLength": 31, "type": "string", "description": "DNS remote host", "format": "string"}
:param ipv4_mask: {"type": "s... | python |
from ddb.__main__ import register_default_caches, clear_caches
from ddb.command import LifecycleCommand
from ddb.config import config
from ddb.event import bus
from ddb.phase import DefaultPhase, phases
def test_lifecycle():
register_default_caches()
phases.register(DefaultPhase("step1"))
phases.register... | python |
from pyserialization.serializable import Serializable
from pyserialization.serialint import SerialU32
from pyserialization.seriallist import serial_list
from pyserialization.serialstring import SerialAsciiString
from operator import mul
import functools
import numpy as np
class _IntList(serial_list(SerialU32)):
... | python |
from django.db import models
import a2s
SERVER_TYPES = (
(68, 'Dedicated'),
(100, 'Dedicated'),
(108, 'Non-dedicated'),
(112, 'SourceTV'),
)
PLATFORMS = (
(76, 'Linux'),
(108, 'Linux'),
(109, 'Mac OS X'),
(111, 'Mac OS X'),
(119, 'Windows')
)
class Server(models.Model):
title... | python |
from canoser import Struct, Uint8, bytes_to_int_list, hex_to_int_list
from libra.transaction.transaction_argument import TransactionArgument, normalize_public_key
from libra.bytecode import bytecodes
from libra.account_address import Address
class Script(Struct):
_fields = [
('code', [Uint8]),
... | python |
'''
@brief Encoder for Packet data
This encoder takes in PktData objects, serializes them, and sends the results
to all registered senders.
Serialized Packet format:
+--------------------------------+ -
| Header = "A5A5 " | |
| (5 byte string) | |
... | python |
import asyncio
import logging
from kubernetes import client, config, watch
#def main():
logger = logging.getLogger('k8s_events')
logger.setLevel(logging.DEBUG)
config.load_kube_config()
v1 = client.CoreV1Api()
v1ext = client.ExtensionsV1beta1Api()
async def pods():
w = watch.Watch()
for event in w.stream(... | python |
from utils import *
import torch.optim as optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
Seq_len, X_train = read_txt('./data/data.txt')
Embedding_matrix = pretrained_embedding_layer(w2v_m, w2i)
vocab_size = len(w2i)
n_hidden = 16
embedding_dim = 300
class LM_Dataset(Dataset)... | python |
import io
import random
import picamera
def motion_detected():
# Randomly return True (like a fake motion detection routine)
return random.randint(0, 10) == 0
camera = picamera.PiCamera()
stream = picamera.PiCameraCircularIO(camera, seconds=20)
camera.start_recording(stream, format='h264')
try:
while True... | python |
import argparse
import webbrowser
import json
import traceback
import socket
import threading
import signal
import os
from pathlib import Path
from lyrebird import log
from lyrebird import application
from lyrebird.config import Rescource, ConfigManager
from lyrebird.mock.mock_server import LyrebirdMockServer
from lyre... | python |
""" Decorator module.
Contains various decorators for hook callbacks.
"""
class BaseDecorator:
""" Base class for decorators in Eris. """
# The interface for hooks means that events will always be the first argument, anything else
# will be passed as payloads for the events.
_EVENT_OFFSET: int = 1
| python |
# -*- coding: UTF-8 -*-
import enum
class MealEnum(enum.Enum):
BREAKFAST = "Breakfast"
MORNING_SNACK = "Morning snack"
LUNCH = "Lunch"
AFTERNOON_SNACK = "Afternoon snack"
DINNER = "Dinner" | python |
from gutenberg.query import get_etexts
from gutenberg.query import get_metadata
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
from gutenberg.query import list_supported_metadatas
from gutenberg.acquire import set_metadata_cache
from gutenberg.acquire.metadata import SqliteMetad... | python |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import FirefoxOptions
import json, config, tracebac... | python |
# Copyright (c) 2012, Johan Rydberg
#
# 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 use, copy, modify, merge,
# publish, di... | python |
#!/usr/bin/env python
#3. Use Pexpect to retrieve the output of 'show ip int brief' from pynet-rtr2.
import pexpect, getpass, sys, time, re
def main():
ip_addr = '184.105.247.71'
username = 'pyclass'
password = getpass.getpass()
cmd = 'show ip int brief'
ssh_conn = pexpect.spawn('ssh {}@{}'.format(... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.