content stringlengths 5 1.05M |
|---|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_p = 10**5 + 1
max_p = 0
cnt = 0
for p in prices:
if p > max_p:
max_p = p
if p < min_p:
min_p = p
max_p = 0
diff = max_p - min_p
... |
from django.shortcuts import render
# Create your views here.
def index(request):
template_name = "reactify/index.html"
return render(request, template_name)
|
import processes
import random
import database
from molecules import Ribo, Protein, MRNA, PopulationCollection, ParticleCollection
class Translation(processes.Process):
"""
Translation is instantiated in the Cell to produce proteins.
Defines Translation process. It iterates over all ribosomes and decides... |
#!/usr/bin/env python3
#
# Summarize breakdown of rom/ram in memory reports
#
# ## Authors
#
# The Veracruz Development Team.
#
# ## Licensing and copyright notice
#
# See the `LICENSE_MIT.markdown` file in the Veracruz root directory for
# information on licensing and copyright.
#
import argparse
import collections a... |
#!/usr/bin/env vpython3
# Copyright 2017 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.
import collections
import itertools
import logging
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.d... |
# Write a program called alice_words.py that creates a text file named alice_words.txt
# containing an alphabetical listing of all the words,
# and the number of times each occurs, in the text version of Alice’s Adventures in Wonderland.
# The first 10 lines of your output file should look something like this:
#
# Wor... |
# -*- coding: utf-8 -*-
# -------
# Class that represents a packet to communicate with a IND903 device
# author: espinr
# -------
#===============================================================================
#
# Definition of data packets with commands to IND903
# [ Head | Len | Address | Cmd | Data[0…N] | Check... |
import numpy as np
import scipy.sparse
def assert_finite(X):
"""Assert numpy or scipy matrix is finite."""
X = X.data if scipy.sparse.issparse(X) else X
assert np.all(np.isfinite(X))
return True
def assert_array_equal(X, Y):
"""Assert two arrays to be equal, whether sparse or dense."""
asser... |
from . import LC_Net_v3
from . import LC_Net_v2
from . import LC_Net
from . import RAZ_loc
|
#!/usr/bin/env python
"""
Service build script.
"""
from nspawn.build import *
# load shared config
import os
import runpy
this_dir = os.path.dirname(os.path.abspath(__file__))
arkon = runpy.run_path(f"{this_dir}/arkon.py")
image_url = arkon['image_url']
alpine_url = arkon['alpine_url']
service_config = arkon['servi... |
#!/bin/env python
"""
Setuptools file for pyyamlconfig
"""
from setuptools import (
setup,
find_packages,
)
setup(
name='pyyamlconfig',
author='marhag87',
author_email='[email protected]',
url='https://github.com/marhag87/pyyamlconfig',
version='0.2.4',
packages=find_packages(),
li... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
N = len(nums)
p0, p2 = 0, N - 1
i = 0
while not (i > p2 or p0 > N - 1 or p2 < 0):
if nums[... |
#!/usr/bin/python3
import cgi
import json
import psycopg2
from datetime import datetime, timedelta
try:
date_object = datetime.today()
date_string = date_object.strftime("%Y-%m-%d")
arguments = cgi.FieldStorage()
uuid = arguments.getvalue("id")
liter = arguments.getvalue("liter")
comment = argum... |
"""
Faça um programa que tenha uma função chamada escreva(),
que receba um texto qualquer com parametros e mostre uma
mensagem som tamanho adaptável.
Ex:
escreva('Olá, Mundo!")
Saída
------------
Olá, Mundo
------------
"""
def escreva(msg):
tam = len(msg)+4
print('~' *tam)
print(f' {msg}')
pr... |
#!/usr/local/bin/python
from rasa.nlu.convert import convert_training_data
from subprocess import call, run
import os
cmd = ['npx chatito --format rasa data/']
p = call(cmd, shell=True, cwd=os.path.dirname(__file__))
convert_training_data(data_file="rasa_dataset_training.json", out_file="nlu.md", out... |
#!/usr/bin/env python3
"""Unit-tested functions for cronctl"""
from collections import namedtuple
import subprocess
import re
import logging
import shlex
from pathlib import Path
import difflib
ROBOT_DEF_REGEX = re.compile(r'^(#|//)(?P<type>[A-Z]*):cron:(?P<def>.*)$', re.MULTILINE)
CRON_DEF_REGEX = re.compile(r"""
... |
"""Crossover implementations for continuous solutions kind
"""
# main imports
import random
import sys
import numpy as np
# module imports
from macop.operators.base import Crossover
class BasicDifferentialEvolutionCrossover(Crossover):
"""Basic Differential Evolution implementation for continuous solution
At... |
import tensorflow as tf
from tensorflow.python.framework import ops
import sys
import os
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
# load custom tf interpolate lib
try:
if os.path.exists(os.path.join(BASE_DIR, 'tf_interpolate_so.so')):
interpolate_module=tf.load_op_library(os.path.join... |
from .exception import AuthException
from application.models import User
import typing
from flask_login import login_user
class LoginException(AuthException):
pass
def login(data: dict) -> typing.NoReturn:
user_id = data.get('user_id')
password = data.get('password')
remember = True if data.get('rem... |
import sys
import exifread
import os
from datetime import datetime
import shutil
import filecmp
import logging
logger = logging.getLogger(__name__)
class Operation(object):
def __init__(self, func, desc):
self.func = func
self.desc = desc
def _valid_operations():
ops = dict(
copy=Op... |
from rest_framework import serializers
from django_redis import get_redis_connection
from users.models import User
from .models import OAuthQQUser
from users.constants import MOBILE_REGEX
class OAuthQQUserSerializer(serializers.ModelSerializer):
"""
保存QQ用户序列化器
"""
sms_code = serializers.CharField(labe... |
import json
import pickle
import numpy as np
from flask import Flask
from flask import request
app = Flask(__name__)
with open("clf.pkl", "rb") as f:
clf = pickle.load(f)
def __process_input(request_data: str) -> np.array:
return np.array(np.asarray(json.loads(request.data)["data"]))
# C... |
import os
from app import bot_app
from app.master.views import app_blueprint
bot_app.blueprint(app_blueprint)
if __name__ == "__main__":
bot_app.run(
host='0.0.0.0',
port=int(os.environ.get('PORT', 8000)),
workers=int(os.environ.get('WEB_CONCURRENCY', 1)),
debug=bool(os.environ.g... |
import numpy as np
from numpy.random import uniform
from enum import Enum
class SampleMethod(Enum):
random_uniform = 0
deterministic_uniform = 1
class Sampler:
def __init__(self):
self.halton_sampler: HaltonSampler = None
def sample(self, num_samples: int, sample_dim: int, method: SampleMet... |
"""
Payment module for PayPal integration
Needs the following settings to work correctly::
PAYPAL = {
'BUSINESS': '[email protected]',
'LIVE': True, # Or False
}
"""
from decimal import Decimal
import logging
import urllib
from django.conf import settings
from django.http import Ht... |
# Django settings for testapp project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = Tr... |
import math
import random
import discord
TIPS = [
"Tip: The shopstats command shows how many items have been purchased!",
"Tip: The shoplb command shows the shop leaderboard for the server!",
"Tip: The rshoplist command shows an overview of all RCON shop categories and items!",
"Tip: The dshoplist com... |
import time
import synapse.cortex as s_cortex
import synapse.daemon as s_daemon
import synapse.telepath as s_telepath
import synapse.lib.service as s_service
import synapse.swarm.runtime as s_runtime
from synapse.tests.common import *
class SwarmRunBase(SynTest):
def getSwarmEnv(self):
tenv = TstEnv()
... |
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
RANDOM_STATE = 1
def main():
# prepare data
iris = load_iris()
df = pd.DataFrame(iris.data)
col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
df.columns = col... |
import argparse
import os
from generators.atm_gen import AtmGen
from generators.client_apache_gen import ClientApacheGen
from generators.generator import LogGenerator
from generators.main_apache_gen import MainApacheGen
from generators.main_firewall_gen import MainFirewallGen
log_out = './../test_logs'
if __name__ =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import wraps
from flask import Flask, request, Response, render_template
import msgpack
app = Flask(__name__, static_folder='assets')
def header_check(f):
@wraps(f)
def decorated(*args, **kwargs):
if not 'application/x-msgpack' in request.... |
import logging
import numpy as np
from depth.models import Sequential
from depth.layers import DenseLayer
from depth.loss_functions import mean_squared_error
def main():
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)
number_of_samples = 50
input_data_... |
# 侧边栏
from PyQt6 import QtCore
from PyQt6.QtCore import QSize
from PyQt6.QtGui import QColor, QIcon
from PyQt6.QtWidgets import QFrame, QGraphicsDropShadowEffect, QPushButton, QVBoxLayout
from .component.Font import Font
from .Account import Account
class Side(QFrame):
def __init__(self, inform, *args):
super(... |
'''
Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights on this
computer program.
You can only use this computer program if you have closed a license agreement with MPG or you get the right to use
the computer program from someone who is authorized to grant you that... |
from pandas import read_csv, read_excel
expb = read_csv("expb.csv", encoding="cp1255")
ballots = read_excel("kalpies_full_report.xls")
expb_incountry = expb[expb['סמל ישוב'] != 99999]
final_results = expb.sum()
|
import argparse
ParserInformation = {
'epilog' : 'Example: coepy -regno 210514665432 -dob 12-06-2001',
'arguments' : {
'--register-number' : {
'short' : '-regno',
'type' : str,
'help' : 'Register number of the student you want to check marks.'... |
import numpy as np
from cs231n.layers import *
from cs231n.layer_utils import *
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classific... |
"""cryptomath module
This module has basic math/crypto code."""
import os
import math
import base64
import binascii
import hashlib as sha
#
# We don't need the compat stuff anymore, so few updates:
# numbits == x.bit_length
# numbytes == x.bit_length // 8
#
# Instead of array() use bytearray().
#
def numBytes(n)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tools for visualizing volumetric data
#
# Davis Bennett
# [email protected]
#
# License: MIT
#
from ..util.roi import ROI
from tqdm.auto import tqdm
def proj_plot(
volume,
proj_fun,
clims="auto",
figsize=4,
aspect=(1, 1, 1),
cmap="g... |
from abc import abstractmethod, ABC
from base64 import b64decode
from pymobiledevice3.services.web_protocol.automation_session import By
class SeleniumApi(ABC):
@abstractmethod
def find_element(self, by=By.ID, value=None):
pass
@abstractmethod
def find_elements(self, by=By.ID, value=None):
... |
import sys
sys.path.append('lib')
import charms
from charmhelpers.core.hookenv import (
config,
log)
from charms.reactive import set_state, clear_flag
def get_vnf_metrics():
# Get VNF Metrics
metrics = dict()
try:
cmd = ['vmstat', '--one-header', '--active',
'1', # interv... |
r"""
===============================================================================
Submodule -- throat_seeds
===============================================================================
"""
import scipy as _sp
def random(geometry, seed=None, num_range=[0, 1], **kwargs):
r"""
Assign random number to thro... |
import os
import sys
import json
import boto3
from distutils import util
class AWSRoute53RecordSet:
"""
Primary class for the handling of AWS Route 53 Record Sets.
"""
def __init__(self):
"""
The default constructor.
"""
self.client = None
self.waiter = None
... |
import k3d
import random
import numpy as np
import matplotlib.pyplot as plt
import ubermagutil.units as uu
import ubermagutil.typesystem as ts
import discretisedfield.util as dfu
@ts.typesystem(p1=ts.Vector(size=3, const=True),
p2=ts.Vector(size=3, const=True))
class Region:
"""A cuboid region.
... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
from django.shortcuts import render
# Create your views here.
from django.template import loader
from django.http import HttpResponse
from dashboard.vars import *
def search(request):
template = loader.get_template('home.html')
# Validate user
if request.user.get_username():
username = request.user.username.l... |
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.db.models.signals import post_save
from django.dispatch import receiver
import cloudinary
from cloudinary.models import CloudinaryField
class Neighbourhood(models.Model):
user = models.For... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0xff55eb1
# Compiled with Coconut version 1.2.3-post_dev1 [Colonel]
# Coconut Header: --------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
import sys as _coconut_... |
from __future__ import division, absolute_import
import sys
sys.path.append('..')
from functools import partial
from math import ceil
import pandas as pd
import numpy as np
from numpy.random import seed
import tensorflow as tf
from tensorflow import set_random_seed
import keras.backend as K
from keras.layers import Inp... |
# Copyright 2016 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... |
#!/usr/bin/env python
# Copyright 2018 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Check the health of a Swarming version."""
import argparse
import collections
import functools
import json
import os
imp... |
r"""Run a species classifier.
This script is the classifier counterpart to detection/run_tf_detector_batch.py.
This script takes as input:
1) a detections JSON file, usually the output of run_tf_detector_batch.py or the
output of the Batch API in the "Batch processing API output format"
2) a path to a directory co... |
#based off PyTorch implementation of ResNet with modifications
from toolz import pipe as p
from torch import nn
N_IMAGE_CHANNELS = 3
def makeConv2d(in_channels, out_channels, kernel_size=3, stride=1,
padding = 1, bias = False):
conv = nn.Conv2d(in_channels, out_channels,
ker... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import numpy
import tf
from os.path import expanduser
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs import point_cloud2 as pc2
from sensor_msgs.msg import Image, PointCloud2
from dodo_detector.detection import TFObjectDetectorV1, KeypointObje... |
from functools import partial
import numpy as np
class Covariance:
def __init__(self, nol: int, alt: np.ma.MaskedArray):
"""assumed covariances
:param no number of levels
:param alt altitudes
"""
self.nol = nol
self.alt = alt
def gaussian(... |
# -*- coding: utf-8 -*-
from flask import Flask, render_template, current_app
from flask.ext.mail import Mail
from flask.ext.security import login_required, roles_required, roles_accepted
from flask.ext.security.decorators import http_auth_required, \
auth_token_required, auth_required
from flask.ext.security.uti... |
import numpy as np
import matplotlib.pyplot as plt
entrada = np.array([[-0.4712, 1.7698], [0.1103, 3.1334], [2.0263,3.2474],
[1.5697, 0.7579], [1.7254, 4.0834], [2.2676, 0.4092],
[-0.4753, 1.1308], [3.2018, 3.1839], [2.0614, 1.6423],
[2.4969, 1.6099], [7.... |
from __future__ import annotations
import os
import base64
import json
from typing import Any, Dict, List, Optional, Union
from .database import query, queryWithResult, queryWithResults
from .league import League
def getJSON(data: str) -> Dict[str, Any]:
if data:
try:
return json.loads(data)
... |
# -*- coding: utf-8 -*-
from datetime import datetime
str = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
print("all=" + str)
str = datetime.now().year()
print("year=" + str)
str = datetime.now().month()
print("month=" + str)
str = datetime.now().day()
print("day=" + str)
str = datetime.now().weekday()
print("week... |
import turtle
w = turtle.Screen()
w.title('Spiral Helix')
w.bgcolor('black')
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = turtle.Pen()
t.speed(100)
for x in range(360):
color = colors[x % len(colors)]
t.pencolor(color)
t.width(x / 100 + 1)
t.forward(x)
... |
"""
Copyright 2019 EUROCONTROL
==========================================
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions an... |
from __future__ import absolute_import
import logging
from time import time
from sentry.auth.provider import Provider
from sentry.http import safe_urlopen
from sentry.utils import json
from sentry.auth.exceptions import IdentityNotValid
from .views import WxWorkLogin, WxWorkCallback, FetchUser, SendHt
from .constant... |
import sys
import sqlite3
import pandas as pd
import sqlalchemy as sql
def load_data(messages_filepath, categories_filepath):
''''
load messages and categories and merge them
INPUT:
messages_filepath: Path to the messages file
categories_filepath: Path to the categories file
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from marshmallow import fields
from polyaxon_schemas.base import BaseConfig, BaseSchema
from polyaxon_schemas.fields import UUID
class NodeGPUSchema(BaseSchema):
index = fields.Int()
name = fields.Str()
uuid = UUID(... |
from sqlalchemy import Column, Integer, String
from repository.sqlite import Base
class Category(Base):
__tablename__ = "category"
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
@property
def serialize(self):
return {
'name': self.name,
... |
#!/usr/bin/env python2
# This machine code will spawn a shell on this machine if run on the CPU
shellcode = b'\xeb\x16\x5b\x31\xc0\x88\x43\x16\x89\x5b\x17\x89\x43'
shellcode += b'\x1b\xb0\x0b\x8d\x4b\x17\x8d\x53\x1b\xcd\x80\xe8\xe5'
shellcode += b'\xff\xff\xff/usr/local/bin/levelupXAAAABBBB'
print shellcode
|
##### TEC Control Messages #####
# TODO
|
''' This spins up a workbench server for the tests to hit '''
class TestServerSpinup(object):
''' Spin up a Worbench test server '''
def test_server_spinup(self, workbench_conn):
''' Start the workbench Server: although it looks like this
test doesn't do anything, because it hits the 'work... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the niceman package for the
# copyright and license terms.
#
# ## ### ##... |
import flask
import flask_login
import flask_principal
from .models import UserAccount, Anonymous, Role
def init_login_manager(db):
"""Init security extensions (login manager and principal)
:param db: Database which stores user accounts and roles
:type db: ``flask_sqlalchemy.SQLAlchemy``
:return: Lo... |
#!/usr/bin/env python3
from find_terms import *
from DataDef import File
import dictionary
from refactoring_support import *
def main(args):
# global special_domains
Refactoring.run_filter_phase = False
file_list = args[1]
if len(args) > 2:
outfile_prefix = args[2]
else:
outfile_... |
class SearchQueryMixin:
def get_response_for_query(self, query):
self.login_required()
return self.client.get(
self.get_url(name="list", **self.get_extra_kwargs()),
data={"query": query},
)
def assertResultEqual(self, response, items):
self.assertEqual(re... |
sounds = ["super", "cali", "fragil", "istic", "expi", "ali", "docious"]
result = ''
for fragment in sounds:
result += fragment
result = result.upper()
print(result) |
# Copyright (c) 2018 The Harmonica Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
# pylint: disable=protected-access
"""
Test prisms layer
"""
import warnings
import pytest
... |
"""
We feed static features along with dynamical ones into LSTM.
Statical feature is replicated [seqlen] times to be transformed into a "sequence", where value
does not change over time. Kind of "fake" sequence.
"""
import numpy as np
from LSTM.lstm_classifier import LSTMClassifier
# general parameters
lstm_nepoch... |
#!/usr/bin/env python2.7
import os
import argparse
import syntax_tree as ast
from parse import *
from os.path import join as pjoin
import tac
def main(*args, **kwargs):
default_file = "single_function.x"
default_file = "simple_0.x"
filepath = os.path.dirname(os.path.realpath(__file__))
argument_par... |
# You can run this .tac file directly with:
# twistd -ny httpauth.tac
from twisted.web2 import channel, resource, http, responsecode, server
from twisted.web2.auth.interfaces import IAuthenticatedRequest, IHTTPUser
class ProtectedResource(resource.Resource):
"""
A resource that is protected by HTTP Auth
... |
import random
import string
from model.contact import Contact
import os.path
import jsonpickle
import getopt
import sys
__author__ = "Grzegorz Holak"
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of Contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f ... |
from discord.ext import commands, tasks
import core.config
from apps.base import Query
from apps.erp.models import EmployeeTable
from apps.directory.queries import ad_query
from apps.directory.utils import email_to_ad, pretty_ad_user, directory_emojis, ad_user_to_list
class DirectoryTasks(commands.Cog, name='directory... |
from test_inference import create_test_data
from save_load import load_model
model,tokenizer=load_model()
test_data_1="ENTER FIRST SENTENCE HERE"
test_data_2="ENTER SECOND SENTENCE HERE"
max_Seq_len=237
test_data_1, test_data_2=create_test_data(tokenizer=tokenizer,test_sentences_pair=test_sentence_pairs,max_sequence... |
import unittest
import os, sys
from numpy import ndarray
from lab.data import Data, DataRandom
from lab.target import TGAlpha
class DataClassTests(unittest.TestCase):
def setUp(self):
self.data = Data()
self.dataStoragePath = "data"
# return super().setUp()
def test_instantiation(... |
import pandas as pd
import os, progressbar
from Bio import SeqIO
def collectSeq(proteome):
seqCollection = []
for seqRecord in SeqIO.parse(proteome, format='fasta'):
seqCollection.append((seqRecord.id, str(seqRecord.seq)))
return seqCollection
def createSEQ(resPath, seqTuple):
f = open(os.pat... |
"""
["Make variable"]: https://docs.bazel.build/versions/master/be/make-variables.html
[Bourne shell tokenization]: https://docs.bazel.build/versions/master/be/common-definitions.html#sh-tokenization
[Gazelle]: https://github.com/bazelbuild/bazel-gazelle
[GoArchive]: /go/providers.rst#GoArchive
[GoLibrary]: /... |
import sys
from example_pkg import YoDude
def main():
print(f"command_line sys.argv={sys.argv}")
s: str = "hi there"
if len(sys.argv) > 1:
s = " ".join(sys.argv[1:])
yd = YoDude(s)
yd.hello()
|
import click
from typing import List
from gonews.utils import GoNews
news = GoNews()
@click.group('cli')
def cli():
pass
@cli.command('top-stories')
@click.option('--max-stories', '-ms', type=int, default=None, required=False, help='Max number of stories to retrieve')
def top_stories(max_stories: int = None... |
# third party
import pytest
# syft absolute
import syft as sy
from syft.util import get_root_data_path
@pytest.mark.vendor(lib="statsmodels")
def test_glm(root_client: sy.VirtualMachineClient) -> None:
# stdlib
import os
import re
import shutil
import urllib.request
# third party
import... |
# -*- coding: utf-8 -*-
"""
for installing with pip
"""
from distutils.core import setup
from setuptools import find_packages
setup(
name='mu3',
version='0.0.1',
author='Mark V',
author_email='noreply.mail.nl',
packages=find_packages(),
include_package_data=True,
url='git+https://bitbucket.org/mverleg/mu3',
... |
import sys
print("zad1")
list = []
for i in range (1,100):
if (i%4 == 0):
list.append(i)
file1 = open("ex1.txt", "w")
file1.write(str(list))
file1.close()
print("\nzad2")
file1 = open("ex1.txt","r")
divisible_by_4 = file1.read()
print(divisible_by_4)
file1.close()
print("\nzad3")
text... |
import argparse
import json
import logging
import os
import socket
import time
from .dispatcher import Dispatcher
from .eventlog import EventLog
from .logs import setup_logs, log_globals
from .utils import try_call_except_traceback
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument(... |
import datetime
print datetime.datetime.now()
print "Put your script of python here."
print "This is Simple Backdoor in image file, then execute with python programming."
|
# Given a 2D board and a list of words from the dictionary, find all words in the board.
#
# Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
#
# Example:
#
# ... |
from max6675 import MAX6675
from machine import Pin
import time
so = Pin(12, Pin.IN)
sck = Pin(14, Pin.OUT)
cs = Pin(16, Pin.OUT)
max = MAX6675(sck, cs , so)
for _ in range(10):
print(max.read())
time.sleep(1) |
import win32com.client as win32
#Criar integração com o e-mail
outlook = win32.Dispatch('outlook.application')
#criar um e-mail
email = outlook.CreateItem(0)
#Configurar informações do e-mail
email.To = "[email protected]"
email.Subject = "Teste de automatização"
email.HTMLBody = f"""
<h1>Automatizando e-mail... |
import os, shutil, datetime
import cg_pyrosetta
import pyrosetta
import mdtraj as md
from simtk import unit
import foldamers
from foldamers.utilities.iotools import write_pdbfile_without_topology
from foldamers.utilities.util import *
from cg_openmm.simulation.tools import *
from cg_openmm.build.cg_build import *
from ... |
from django.core.management.base import BaseCommand
from data_refinery_common.models import ComputationalResultAnnotation, Experiment
class Command(BaseCommand):
def handle(self, *args, **options):
organism_ids = list(
ComputationalResultAnnotation.objects.filter(data__is_qn=True).values_list... |
from flask import Flask, render_template, request
from sqlalchemy import Column, Integer, String, Float, create_engine, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import requests
app = Flask(__name__)
@app.route('/')
@app.route('/main')
def main(... |
import json
import linkedin.commands.command as command
import linkedin.utils.config as config
import logging
from urllib import request
logger = logging.getLogger(__name__)
class HelpCommand(command.BaseCommand):
def execute(self, args):
print("usage: linkedin me")
class MeCommand(command.BaseCommand... |
"""Program takes 3 variables as inputs I.E. Number of test cases Number of People and The cost array in the given order respectively"""
no_of_test_cases=int(input())
for _ in range(no_of_test_cases):
no_of_people=int(input())
cost_list=list(map(int,input().split()))
cost_list.sort()
cost=0
... |
"""Contains the Courtier Character class"""
import json
from botc import Character, Townsfolk
from ._utils import BadMoonRising, BMRRole
with open('botc/gamemodes/badmoonrising/character_text.json') as json_file:
character_text = json.load(json_file)[BMRRole.courtier.value.lower()]
class Courtier(Townsfolk, Ba... |
import fasttext as ft
# Fist download the dbpedia.train using https://github.com/facebookresearch/fastText/blob/master/classification-example.sh
# on test/ and move to the example directory
current_dir = path.dirname(__file__)
input_file = path.join(current_dir, 'dbpedia.train')
output = '/tmp/classifier'
test_file = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.