text stringlengths 2 999k |
|---|
#!/usr/bin/env python
# encoding: utf-8
import logging
from playhouse.migrate import *
from peewee import ProgrammingError
from config import DB_CONFIG
from models import *
logger = logging.getLogger('models_migration')
db = PostgresqlDatabase(**DB_CONFIG)
migrator = PostgresqlMigrator(db)
db.connect()
class Migra... |
from __future__ import absolute_import
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from .widgets import MathCaptchaWidget
from .utils import hash_answer
class MathCaptchaField(forms.MultiV... |
"""
Created on Thu Dec 10 10:44:27 2015
@author: konrad
"""
from keras.regularizers import l2, activity_l2
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='ConcursoPolicia',
version='1.0',
description='Buscador de usuarios en twitter',
author='Daniel Garnacho',
author_email='garnachod@gmail.com',
packages=['AnnoyComparators', 'API', 'Config', 'DBbridge', 'DBbridge.PostgreSQL... |
# Copyright 2021 Sony Semiconductors Israel, 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 b... |
# Copyright 2016 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 required by applicable law or a... |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... |
__author__ = "LaughDonor"
for N, x, y in ((input(), 0, 0) for _ in xrange(input())):
while (N - 5 * x) % 3 and y >= 0:
x += 1
y = (N - 5 * x) / 3
y = (N - 5 * x) / 3
print -1 if y < 0 else '5' * (3 * y) + '3' * (5 * x) |
import json
train_path = "/mlcv/Databases/VN_InfographicVQA/train/VietInfographicVQA_train_v1.0.json"
val_path = "/mlcv/Databases/VN_InfographicVQA/val/VietInfographicVQA_val_v1.0.json"
train_fi = open(train_path,)
val_fi = open(val_path,)
train_data = json.load(train_fi)
train_data = train_data['data']
val_data =... |
"""
Django settings for pyconcz_2018 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import datetime
# Build paths inside the project like this... |
import requests
from bs4 import BeautifulSoup
def request_git_hub_trending(url):
return requests.get(url)
def extract(page):
soup = BeautifulSoup(page.text, "html.parser")
return soup.find_all("article")
def transform(html_repos):
result = []
for row in html_repos:
developer_name = ''.j... |
from distutils.core import setup
setup(
name = 'google_ngram_api',
packages = ['google_ngram_api'],
version = '1.2',
license='MIT',
description = 'API to download google ngram data as csv file',
author = 'Venkatesh Prasad',
author_email = 'prasad.venkatesh90... |
from django.contrib import admin
from .models import Grocery
# Register your models here.
admin.site.register(Grocery) |
try:
from . import generic as g
except BaseException:
import generic as g
def random_chr():
return chr(ord('a') + int(round(g.np.random.random() * 25)))
class SceneTests(g.unittest.TestCase):
def test_scene(self):
for mesh in g.get_mesh('cycloidal.ply',
'spher... |
import math
from typing import Optional, Tuple
from overrides import overrides
import torch
import torch.nn.functional as F
from transformers import XLNetConfig
from allennlp.data.tokenizers import PretrainedTransformerTokenizer
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
from allennlp.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, suraj varade and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class FieldofScope(Document):
pass
|
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
# Copyright (c) 2021, Manfred Moitzi
# License: MIT License
from typing import cast
import pytest
import ezdxf
from ezdxf.lldxf.extendedtags import ExtendedTags
from ezdxf.entities import factory
from ezdxf.entities import ACADProxyEntity
from ezdxf.lldxf.tagwriter import TagCollector, basic_tags_from_text
from ezdxf... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
NNI example for supported ActivationAPoZRank and ActivationMeanRank pruning algorithms.
In this example, we show the end-to-end pruning process: pre-training -> pruning -> fine-tuning.
Note that pruners use masks to simulate the real pruning.... |
# coding: utf-8
"""
SimScale API
The version of the OpenAPI document: 0.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class OneOfSolidMaterialMaterialBehavior(object):
"""NOTE: This class... |
import typing
from math import sqrt
from qtpy import QtGui
from qtpy.QtCore import QLineF, QPointF, Qt
from qtpy.QtGui import QFont, QFontMetrics, QPainter, QPolygonF
from qtpy.QtWidgets import QCheckBox, QWidget
class CollapseCheckbox(QCheckBox):
"""
Check box for hide widgets. It is painted as:
▶, {inf... |
# -*- coding: utf-8 -*-
# Copyright CERN since 2015
#
# 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 ... |
#!/usr/bin/env python3
import lib
N=1000000
for n in range(40755,N):
t = lib.triangle(n)
if lib.is_pentagonal(t) and lib.is_hexagonal(t):
print(t)
|
from flask import Flask, render_template, request
from flask_socketio import SocketIO
import eventlet
import json
import datetime
# If eventlet or gevent are used, then monkey
# patching the Python standard library is
# normally required to force the message
# queue package to use coroutine friendly
# functions and cl... |
import os
import unittest
from skidl import *
class UnitTestsElectronicDesignAutomationSkidlExamples(unittest.TestCase):
def test_introduction(self):
print("test_introduction")
# Create input & output voltages and ground reference.
vin, vout, gnd = Net('VI'), Net('VO'), Net('GND')
... |
from elegantrl.train.evaluator import *
from elegantrl.train.config import Arguments
from elegantrl.envs.CustomGymEnv import GymNormaEnv
from elegantrl.agents.AgentPPO import AgentPPO, AgentPPOgetObjHterm
from elegantrl.agents.AgentSAC import AgentSAC, AgentReSAC
def get_cumulative_returns_and_step(env, act, if_rende... |
def trim(qual,threshold):
pos=0
for base in list(qual):
if (ord(base)-33 < threshold):
return(pos)
else:
pos += 1
out = open("trimmed.fastq","w")
fq = open("samp1.fastq","r")
while (True):
header = fq.readline().rstrip("\n")
if not header:
break
se... |
# Copyright 2017 The Forseti Security Authors. 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 ap... |
"""
Original Author: Garvita
Edited by: Bharat
"""
import torch
import kaolin as kal
from kaolin.rep import Mesh
import kaolin.cuda.tri_distance as td
import numpy as np
from kaolin.metrics.mesh import _compute_edge_dist, _compute_planar_dist, TriangleDistance, point_to_surface
from kaolin.rep import SDF as sdf
from k... |
# -*- coding: utf8 -*-
__all__ = [
'OrzMC',
'Game',
'Client',
'Server',
'Config',
'Console'
'Constants',
'Downloader',
'Tools',
'Version',
'Nginx',
'Daemon',
'SkinSystem',
] |
# Copyright 2015 The TensorFlow Authors. 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 applica... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
def PrefabBasicWorkflow_CreateAndReparentPrefab():
CAR_PREFAB_FILE_NAME = 'car_prefab'
WHEEL_PREFAB_FI... |
# coding: utf-8
"""
MailSlurp API
MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://ww... |
from matplotlib import pyplot as plt
from mat_util import *
datadir = 'from_coeus/data'
nxs = load('nxs', datadir)
fs = load('fs', datadir)
plt.plot(fs)
plt.xlabel("Steps")
plt.ylabel("Objective Function Values")
plt.title("Convergence of Objective Function")
plt.show()
input("press a key")
plt.plot(nxs)
plt.xlabel... |
#!/usr/bin/env python
import os.path
import re
from setuptools import setup
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
with open(os.path.join(HERE, *parts), "r", encoding="utf-8") as fp:
return fp.read()
# https://packaging.python.org/guides/single-sourcing-package-version/
de... |
from coopihc.space.Space import Space
from coopihc.space.State import State
from coopihc.space.StateElement import StateElement
from coopihc.space.utils import autospace
from coopihczoo.eye.utils import ProvideLikelihoodInferenceEngine
import numpy
game_state = State(
game_info=State(
turn_index=StateEle... |
# -*- coding: utf-8 -*-
import collections
import itertools
import re
import logging
from completor import Completor, vim, LIMIT
from completor.compat import to_unicode
from .utils import test_subseq
logger = logging.getLogger('completor')
word = re.compile(r'[^\W\d]\w*$', re.U)
def getftime(nr):
try:
... |
_E='replace'
_D=False
_C='\n'
_B='\r\n'
_A=None
import contextlib,io,os,shlex,shutil,sys,tempfile
from . import formatting,termui,utils
from ._compat import _find_binary_reader
class EchoingStdin:
def __init__(A,input,output):A._input=input;A._output=output
def __getattr__(A,x):return getattr(A._input,x)
def _echo(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import multiprocessing
def write_proc(q):
try:
q.put(1, block=False)
except Exception, e:
print e
pass
def read_proc(q):
try:
print(q.get())
except Exception, e:
print e
pass
if __name__ == "__main__":
... |
from concurrent.futures import ThreadPoolExecutor
def f(x):
return x * x
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(f, 12)
print(future.result())
|
from app.genetic.genes.gene import Gene
class AndGene(Gene):
def __init__(self, left_gene: Gene, right_gene: Gene):
super().__init__()
self.leftGene = left_gene
self.rightGene = right_gene
def condition(self, company, day):
left_cond = self.leftGene.condition(company, day)
... |
# -*- coding: utf-8 -*-
r"""
Ambient spaces of modular symbols
This module defines the following classes. There is an abstract base
class ``ModularSymbolsAmbient``, derived from
``space.ModularSymbolsSpace`` and ``hecke.AmbientHeckeModule``. As
this is an abstract base class, only derived classes should be
instantia... |
"""LegacyFileDiffData model defitnition."""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from djblets.db.fields import Base64Field, JSONField
class LegacyFileDiffData(models.Model):
"""Deprecated, legacy class for base64-encoded diff data.
This is no longer populated,... |
#!/usr/bin/env python
"""
Mark datasets as deleted that are older than specified cutoff
and (optionaly) with a tool_id that matches the specified search
string.
This script is useful for administrators to cleanup after users who
leave many old datasets around. It was modeled after the cleanup_datasets.py
script origi... |
import abc
import collections
import six
@six.add_metaclass(abc.ABCMeta)
class Metric(object):
def __init__(self, name, tags=None):
self._name = name
self._tags = tags or {}
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
def __repr__(self):
return... |
#-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BER... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
greeting = "World"
return f'Hello, {gerrting}!'
if __name__ == "__main__":
app.run()
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NewRecipe.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impo... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Community database models."""
from __future__ import absolute_import, print_funct... |
from Cryptodome.Cipher import AES
from Cryptodome.Cipher import DES
from Cryptodome.Hash import MD5
from base64 import b64decode
boox_strings = {
'NovaPro': {
"MODEL": "NovaPro",
"STRING_7F00500": "j857wYAQcWZgvIEQ/tcQqzxreUJgFHwJl6D2TN9BuSkQ",
"STRING_7F00501": "+soGw/YVdGIRJiAs5SMmv1ihW3... |
"""
Notes:
These functions were used with modification from the astroML python
function `fit_bivariate_normal` which can be found [here]
(http://www.astroml.org/book_figures/chapter3/fig_robust_pca.html). In
this modified version, the percentiles are computed using the numpy
function `nanpercentile`... |
from __future__ import print_function
from __future__ import division
import os
import json
import numpy as np
import random
import pdb
import math
from cytoolz import partition_all
import torch.utils.data
from torch.utils.data import Sampler
UNK, PAD, BOS, EOS, MASK = 0, 1, 2, 3, 4
class MMTDataset(torch.utils.da... |
from flask import Flask, render_template, request
import pickle
import numpy as np
model = pickle.load(open('data.pkl','rb'))
app = Flask(__name__)
@app.route('/')
def man():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def home():
data1 = request.form['a']
# arr = ... |
from flask import Flask, request
import json
import os
app = Flask(__name__)
@app.route('/',methods=['POST'])
def foo():
print 'triggerd'
os.system('sh run.sh &')
return "OK"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7077)
|
from rest_framework import serializers
from .models import Room
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('id', 'code', 'host', 'guest_can_pause',
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer)... |
#!/usr/bin/env python
# pylint: disable=missing-docstring
# flake8: noqa: T001
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ ... |
from netmiko.endace.endace_ssh import EndaceSSH
__all__ = ["EndaceSSH"]
|
from fiasko_bro.validators import casts_input_result_to_str
def test_casts_input_result_to_str_fails(test_repo):
expected_output = 'file_with_input_to_str_cast.py:1'
output = casts_input_result_to_str(test_repo)
assert output == expected_output
def test_casts_input_result_to_str_succeeds(origin_repo):
... |
# -*- coding: utf-8 -*-
import pytest
from pandas import compat
from pandas.compat import PY3
import numpy as np
from pandas import (Series, Index, Float64Index, Int64Index, UInt64Index,
RangeIndex, MultiIndex, CategoricalIndex, DatetimeIndex,
TimedeltaIndex, PeriodIndex, Int... |
import hashlib
def get_hash(data):
"""md5 hash of Python data. This is limited to scalars that are convertible to string and container
structures (list, dict) containing such scalars. Some data items are not distinguishable, if they have
the same representation as a string, e.g., hash(b'None') == hash('No... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class SSLCer... |
import tensorflow as tf
import numpy as np
import os
import sys
sys.path.append('./utils')
sys.path.append('./models')
import dataset_human as dataset
import model_color as model
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', './train_color_human',
"""Directory where to ... |
from ._simplex import Simplex
__all__ = ("Simplex",)
|
# Copyright (c) 1999-2007 Gary Strangman; All Rights Reserved.
#
# 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, co... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project11.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impo... |
from retry import retry
from bs4 import BeautifulSoup
import requests
import sys
import json
import re
import os
###YouTubeの動画のコメントを取得するための関数
###下のほうにある get_chat_replay_data をすかってコメント取得する
###入力:video_id
###出力:コメントの情報
class ContinuationURLNotFound(Exception):
pass
class LiveChatReplayDisabled(Exception):
pass
... |
"""
Unittests for IOSXR/SPITFIRE plugin
Uses the mock_device.py script to test IOSXR plugin.
"""
__author__ = "Sritej K V R <skanakad@cisco.com>"
import os
import unittest
from unittest.mock import patch
from pyats.topology import loader
import unicon
from unicon import Connection
from unicon.plugins.tests.mock.m... |
# Copyright 2020 Xilinx 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 writing, ... |
from rich import print
from time import time
from fraction import square_check
t1 = time()
def do_map(dic: dict, word: str):
for ele in dic:
word = word.replace(ele, dic[ele])
return word
squares = [1]
i = 2
while squares[-1] < 10**8:
squares.append(i**2)
i += 1
def square_anagram(word1: ... |
'''
实例属性和类属性
'''
class Student:
name="Student" #类属性
s = Student()
print(s.name) #获取类属性
s.name="Test" #给实例添加实例属性name
print(s.name) #实例属性优先级大于类属性的优先级
del s.name #删除name实例属性
print(s.name)
|
# Generated by Django 2.2 on 2021-12-10 09:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profile_api', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import copy
import warnings
from typing import Callable, Dict, List, Union, Optional, Tuple, Sequence, cast
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
import torch
import torch.nn as nn
fro... |
#! /usr/bin/env python
# Copyright (C) 2016 ETH Zurich, Institute for Astronomy
# System imports
from __future__ import print_function, division, absolute_import, unicode_literals
# External modules
import numpy as np
import copy
# MultiLens imports
from MultiLens.analytic_lens import AnalyticLens
from MultiLens.C... |
# --------------
# Code starts here
mathematics = {'Geoffrey Hinton' :78,
'Andrew Ng' :95,
'Sebastian Raschka': 65,
'Yoshua Benjio': 50,
'Hilary Mason': 70,
'Corinna Cortes': 66,
'Peter Warden': 75}
topper = max(mathematics,key=mathematics.get)
print(topper)
# Code ends here
# --------------
# Code starts here
cl... |
import pytest
from spinta.testing.cli import SpintaCliRunner
from spinta.testing.utils import (
create_manifest_files,
update_manifest_files,
read_manifest_files,
)
def configure(rc, path):
return rc.fork().add('test', {
'manifests.default': {
'type': 'backend',
'backe... |
"""Implements the Label extension.
https://github.com/stac-extensions/label
"""
from enum import Enum
from pystac.extensions.base import ExtensionManagementMixin
from typing import Any, Dict, Iterable, List, Optional, Set, Union, cast
import pystac
from pystac.serialization.identify import STACJSONDescription, STACV... |
#!/usr/bin/env python3
#
# Copyright 2015 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.
# Helper script to run dump_syms on Chrome Linux executables and strip
# them if needed.
import os
import subprocess
import sys
if... |
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/ableton/v2/control_surface/control/__init__.py
from __future__ import absolute_import, print_function, unicode_literals
from .button import ButtonControl, ButtonControlBase, DoubleClickContext, Playab... |
# -*- coding: utf-8 -*-
"""
User-interface related functions for building bots.
This module supports several different bot classes which could be used in
conjunction. Each bot should subclass at least one of these four classes:
* L{BaseBot}: Basic bot class in case where the site is handled differently,
like workin... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 12:08:47 2021
@author: Kaneki
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 17:28:36 2021
@author: Kaneki
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def Periodicity(pos,l):
if... |
# programa que lê as notas digitadas pelo usuário, insere as mesmas em uma lista e calcula a média entre elas.
notas = [0, 0, 0, 0, 0]
soma = 0
x = 0
while x <= 4:
notas[x] = float(input(f'Digite o valor da nota {(x + 1)}.'))
soma += notas[x]
x += 1
x = 0
while x <= 4:
print(f'Nota {x + 1} é: {notas[... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
#!/usr/bin/env python
# Copyright 2017 Calico 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... |
# newests/api/views.py
from rest_framework import viewsets
from .serializers import NewsSerializer
from newests.models import Newests
class NewsViewSet(viewsets.ModelViewSet):
queryset = Newests.objects.all()
serializer_class = NewsSerializer |
#!/usr/bin/env python
import os
import re
import sys
import setuptools
def get_version(*file_paths):
"""Retrieves the version from replicat_documents/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__ver... |
"""
Tests warning filter settings.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
import sys
import warnings
import pytest
import fatf
import fatf.utils.testing.warnings as testing_w
PYTEST_WARNING_FILTERS = []
def test_logger_level():
"""
Tests the correct level of the logger.
... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...worksheet import Worksheet
class TestWriteHeaderFooter(unittest.TestCase):
"""
... |
import re
from hailtop.batch_client.parse import (MEMORY_REGEX, MEMORY_REGEXPAT,
CPU_REGEX, CPU_REGEXPAT)
# rough schema (without requiredness, value validation):
# jobs_schema = [{
# 'always_run': bool,
# 'attributes': {str: str},
# 'command': [str],
# 'env': [{
# ... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
import typing
import torch
import torch_mlir
# RUN: %PYTHON %s | npcomp-opt | FileCheck %s
mb = torch_mlir.ModuleBuilder()
class TestModule(torch.nn.Module):
def __init__(self):
... |
import argparse
import logging
from typing import Any, Callable, List, Tuple, Optional, Set, Union
from mir.commands import base
from mir.protos import mir_command_pb2 as mirpb
from mir.tools import checker, class_ids, mir_repo_utils, mir_storage, mir_storage_ops, revs_parser
from mir.tools.code import MirCode
from mi... |
'''
@author: Sevval MEHDER
Filling one cell: O(1)
Filling all cells: O(2xn) = O(n)
'''
def find_maximum_cost(Y):
values = [[0 for _ in range(2)] for _ in range(len(Y))]
# Go on with adding these 2 options
i = 1
while i < len(Y):
# Put these two options
values[i][0] =... |
# Shows the location of the last photo in the canera roll in the Maps app.
# (thanks to @HyShai for pointing out that the latitude/longitude refs are necessary)
import photos
import webbrowser
meta = photos.get_metadata(-1)
gps = meta.get('{GPS}')
if gps:
latitude = str(gps.get('Latitude', 0.0)) + gps.get('LatitudeR... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-07 10:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Manager', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import metadata
app_name = metadata.name
version = metadata.version
def read(filename):
with open(filename) as fp:
return fp.read()
long_description = read('README.md')
setup(
name = "django-%s" % app_name,
version = version,
pa... |
"""
Copyright 2020 The OneFlow Authors. 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 applicable law or agr... |
from lib2to3.refactor import MultiprocessingUnsupported
import uuid
from xmlrpc.client import _iso8601_format
from flight_blender.celery import app
import logging
from scd_operations.scd_data_definitions import Volume4D
from . import dss_rid_helper
import redis
from auth_helper.common import get_redis
from .... |
"""
PRIVATE MODULE: do not import (from) it directly.
This module contains implementations that do not directly touch the core of
jsons.
"""
from typing import Optional
from jsons._cache import cached
from jsons._common_impl import StateHolder, get_class_name
def suppress_warnings(
do_suppress:... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class SentieonGenomics(Package):
"""Sentieon provides complete solutions for secondary D... |
import random
import webbrowser
import boto3
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import os
import sys
import subprocess
from tempfile import gettempdir
import pygame
# Melissa
from melissa import profile
from melissa.tts import tts
pygam... |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extrafields):
''' creates and saves ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.