content stringlengths 5 1.05M |
|---|
f2 = lambda a, b : a * b
print(f2(5, 6)) |
import numpy as np
import math
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import pickle
from lib.model import *
from lib.zfilter import ZFilter
from lib.util import *
from lib.trpo import trpo_step
from lib.data import *
import s... |
import logging
from fess.test import assert_equal, assert_startswith
from fess.test.ui import FessContext
from playwright.sync_api import Playwright, sync_playwright
logger = logging.getLogger(__name__)
def setup(playwright: Playwright) -> FessContext:
context: FessContext = FessContext(playwright)
context.... |
import logging
import os
import yaml
import unittest
import numpy as np
from copy import copy
from ISR.models.rdn import RDN
from ISR.predict.predictor import Predictor
from unittest.mock import patch, Mock
class PredictorClassTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
logging.disable(... |
import os
import bpy
import anm, binmdl, col, cmn, mdl, pth
from bpy_extras.io_utils import ImportHelper, ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty, FloatProperty
from bpy.types import Operator
from bStream import *
class MansionBinImport(bpy.types.Operator, ImportHelper):
bl_id... |
#SOl Courtney Columbia U Department of Astronomy and Astrophysics NYC 2016
#swc2124@columbia.edu
#--[DESCRIPTION]---------------------------------------------------------#
'''
Date: May 2016
Handeler for twitter text parsing
'''
#--[IMPORTS]--------------------------------------------------------------#
from nltk.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
import deepy.nn.layer as layer
class OriginalVGG(nn.Module):
"""VGG8, 11, 13, 16, and 19
>>> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
>>> net = VGG('VGG8').to(device)
... |
import json
from scripts.user_module_calls import \
read_user_passwords, USERS_PER_LOAD_BALANCER
def read_load_balancer_dns():
with open("output.json", 'r') as f:
return json.load(f)['load_balancer_dnss']['value']
def create_password_file_content(number_of_users: int):
user_passwords = read_user... |
"""Tests for models of contributions (comments)."""
from django.test import TestCase
from nose.tools import raises
from geokey.contributions.models import Comment, post_save_count_update
from ..model_factories import ObservationFactory, CommentFactory
class TestCommentPostSave(TestCase):
def test_post_save_com... |
import inspect
import string
import hypothesis.strategies as st
import pytest
from hypothesis import assume, example, given
from hydra_zen import builds, make_custom_builds_fn, to_yaml
from tests.custom_strategies import partitions, valid_builds_args
_builds_sig = inspect.signature(builds)
BUILDS_DEFAULTS = {
na... |
from unittest import mock
import pytest
from dmscripts.helpers.updated_by_helpers import get_user
@pytest.fixture(autouse=True)
def environ():
with mock.patch.dict("os.environ", {}, clear=True):
import os
yield os.environ
@pytest.fixture
def subprocess_run():
with mock.patch("dmscripts.hel... |
#ATS:test(SELF, label="Polygon unit tests")
# Unit tests for the Polygon class
import unittest
from math import *
from SpheralTestUtilities import fuzzyEqual
from Spheral2d import *
# Create a global random number generator.
import random
rangen = random.Random()
plots = []
#=======================================... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
import torch
import torch_mlir
import npcomp
from npcomp.compiler.pytorch.backend import refjit, frontend_lowering
from npcomp.compiler.utils import logging
import test_utils
logging.enabl... |
from app.models import Commnet,User
from app import db
def setUp(self):
self.user_Rotich = User(username = 'Rotich',password = 'potato', email = 'rotichtitus12@gmail.com')
self.new_comment = Comment(pitch_title='movie',pitch="the heritage was from a history",pitch_comment='This pitch is the best thing... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 16:53:59 2017
@author: kaihong
"""
import numpy as np
def huber_w(y):
return np.fmin(1, 1/np.abs(y))
def huber_w_smooth(y):
return 1/np.sqrt(1 + y**2)
def exp_w(c=2):
def _exp_w(y):
return np.exp(-0.5*y**2/c**2)
return _... |
from PyQt5.QtCore import QEvent, pyqtSignal
from PyQt5.QtGui import QMouseEvent, QPalette
from PyQt5.QtWidgets import QWidget, QLabel, QPushButton
from PyQt5.uic import loadUi
from brainframe_qt.ui.resources.paths import qt_ui_paths
class EncodingEntry(QWidget):
encoding_entry_selected_signal = pyqtSignal(bool, ... |
import os
from math import log10
import cv2
import numpy as np
from .mask_editor import MaskEditor
from .partially_labelled_dataset import (
PartiallyLabelledDataset, ObjectAnnotation,
create_rgb_mask, save_annotations
)
from ..base import (
DragInterpreter, ImageGroupViewer,
random_colors, grabcut, C... |
import os
import numpy as np
import pandas as pd
import pickle
import xarray as xr
def save_data_CCO(fit, folder, data_start, data_dec):
print(fit)
if not os.path.exists(folder):
os.makedirs(folder)
os.chdir(folder)
print(os.getcwd())
np.save("data_start", data_start)
np.save("data_... |
from django.utils.translation import ugettext_lazy as _
from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock
__all__ = ['Carousel', 'Parallax']
class Carousel(blocks.ListBlock):
"""Carousel ('div' tag) to cycle through different images."""
def __init__(self, child_block=None,... |
import aria2p
import logging
import sys
from ravager.config import LOGS_DIR, LOG_LEVEL
logging.basicConfig(format='"%(asctime)s — %(name)s — %(levelname)s — %(funcName)s:%(lineno)d — %(message)s"',
level=LOG_LEVEL,
handlers=[logging.FileHandler("{}/ravager.log".format(LOGS_DIR))... |
from datetime import datetime
import sys
import re
from urlparse import urljoin
import iso8601
from lxml import etree
from jparser import PageModel
from ocd_backend.extractors import HttpRequestMixin
from ocd_backend.items import BaseItem
from ocd_backend.utils.misc import html_cleanup, html_cleanup_with_structure
... |
import pandas as pd
import cv2
import torch
import torch.optim as optim
import numpy as np
from vel.rl.metrics import EpisodeRewardMetric
from vel.storage.streaming.stdout import StdoutStreaming
from vel.util.random import set_seed
from vel.rl.models.policy_gradient_model import PolicyGradientModelFactory, PolicyGradi... |
# -*- coding: utf-8 -*-
"""
A program to describe the treatment and recovery process for an incident Stage I oral cancer.
Entities with a diagnosed stage I cancer will be treated either surgically (with/without RT),
with some other treatment type (usually Chemo+RT), or may receive no treatment. Their
post-treatmen... |
#
# @lc app=leetcode id=205 lang=python3
#
# [205] Isomorphic Strings
#
# @lc code=start
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
ss, tt = {}, {}
for i in range(len(s)): # map s to t ,map t to s
if s[i] not in ss:
ss[s[i]] = t[i]
eli... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import json
from cookbook.util.logging import LoggerFactory
logger = LoggerFactory.getLogger(__name__)
def title():
logger.debug('# Http')
def cook():
host = 'weather.livedoor.com'
api = '/forecast/webservice/json/v1?city=130010'
... |
#!/usr/bin/env python
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import click
from functools import partial
import gzip
from multiprocessing import Pool
import os
import pandas as pd
from pybedtools import BedTool
from pybedtools.helpers import cleanup
import re
from tqdm import ... |
from django.contrib.auth.models import User, Group
from testapp.models import CmbUser
from rest_framework import serializers
# Java DTO 역할을 하는 직렬화 클래스
# class UserSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = User
# # url 필드는 상세페이지 링크를 출력해준다.
# fields = ['url'... |
# Baseball Practice
# https://web.archive.org/web/20000118165317/http://geocities.com/SoHo/Gallery/6446/bball.htm
name = "Baseball"
duration = 200
frames = [
" \n" +
" / \n" +
" / \n" +
" <<O O \n" +
" | ... |
from .joblib.test import test_memory
from .joblib.test import test_hashing
|
from typing import Tuple
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QGridLayout, QSplitter, QWidget
from ..state import GlobalState
from ..utils import is_image_file
from ..widgets import FileTagView, FileTreeView, ImageView, wrap_image
class FileTab(QWidget):
"""Combines a filesystem view, tag... |
from .node import Node
from .graph import Graph
from .sorter import Sorter
from .topological_sorter import TopologicalSorter
from .bfs_topological_sorter import BFSTopologicalSorter
from .dfs_topological_sorter import DFSTopologicalSorter
from .exhaustive_bfs_topological_sorter import ExhaustiveBFSTopologicalSorter
fr... |
# DeepSlide
# Jason Wei, Behnaz Abdollahi, Saeed Hassanpour
# Run the resnet on generated patches.
import utils_model
from utils_model import *
#validation patches
get_predictions( patches_eval_folder = config.patches_eval_val,
auto_select = config.auto_select,
eval_model = config.eval_model,
check... |
import sys
sys.path.append('../')
from datetime import date
from main import db
class Pusheen(db.Model):
__tablename__ = 'pusheen'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=False, nullable=True)
date_of_birth = db.Column(db.Date, unique=False, nullable=True)
... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='amadash',
version='1.0.0',
description='Amazon Dash button monitor',
author='Igor Partola',
author_email='igor@igorpartola.com',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'conf', 'tmp']),
en... |
"""Synthesizes speech from the input string of text or ssml.
Make sure to be working in a virtual environment.
Note: ssml must be well-formed according to:
https://www.w3.org/TR/speech-synthesis/
"""
from google.cloud import texttospeech
from pydub import AudioSegment
from pydub.playback import play
def create_c... |
import sys
packages = []
final_cost = 0
factories, total = map(int, sys.stdin.readline().split())
for i in range(factories):
cost, boxes = map(int, sys.stdin.readline().split())
packages.append([cost, boxes])
packages.sort()
for i in packages:
if total - i[1] > 0:
total -= i[1]
final_co... |
import rospy
from naoqi_2d_simulator import *
if __name__ == '__main__':
rospy.init_node("naoqi_2d_simulator_node")
sim = Naoqi2DSimulator()
sim.run_main_thread()
rospy.spin()
|
import logging
from contextlib import contextmanager
from functools import lru_cache
from typing import Iterator, Optional
import sqlalchemy as sa
from sqlalchemy.orm import Session
from fastapi_auth.fastapi_util.settings.database_settings import DatabaseBackend, get_database_settings
@lru_cache()
def get_engine() ... |
#!/usr/bin/python
# uuidgen.py script to generate a UUIDv4 for guests
#
#
# Any domain specific UUID rules can be added to this generic example
#
import uuid
#
print uuid.uuid4() |
from threading import Thread
import threading
from tkinter import *
from tkinter import ttk
import datetime
from time import sleep
import peewee as pw
from src.dependencies.functions import *
|
import re
import sys
PASSWORD_RE = re.compile('(\d+)-(\d+) (\w): (\w+)')
if __name__ == '__main__':
correct_count = 0
for line in sys.stdin:
min_count, max_count, letter, password = PASSWORD_RE.match(line).groups()
min_count = int(min_count)
max_count = int(max_count)
letter_... |
import re
from .exceptions import LoginRequired
__all__ = (
"CODINGAMER_HANDLE_REGEX",
"CLASH_OF_CODE_HANDLE_REGEX",
)
CODINGAMER_HANDLE_REGEX = re.compile(r"[0-9a-f]{32}[0-9]{7}")
CLASH_OF_CODE_HANDLE_REGEX = re.compile(r"[0-9]{7}[0-9a-f]{32}")
def validate_leaderboard_type(type: str) -> str:
"""Valid... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utilities used by tests
"""
import copy
import logging
import os
import shutil
import string
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, Iterator, List... |
import numpy as np
import gym
import matplotlib.pyplot as plt
class Model(object):
def __init__(self, alpha, stateSpace):
self.ALPHA = alpha
self.weights = {}
self.stateSpace = stateSpace
for state in stateSpace:
self.weights[state] = 0
def calculateV(self, state):
... |
"""Nvim API subpackage.
This package implements a higher-level API that wraps msgpack-rpc `Session`
instances.
"""
from .buffer import Buffer
from .common import DecodeHook, SessionHook
from .nvim import Nvim, NvimError
from .tabpage import Tabpage
from .window import Window
__all__ = ('Nvim', 'Buffer', 'Window', '... |
language = {
'so': 'So language - Congo',
'Afrikaans': 'Afrikaans',
'العربية': 'Arabic',
'беларуская': 'Belarusian',
'Български език': 'Bulgarian',
'বাংলা': 'Bengali',
'Català': 'Catalan',
'Čeština': 'Czech',
'Cymraeg': 'Welsh',
'Dansk': 'Danish',
'Deutsch': 'German',
'Ελ... |
class Solution:
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
s = list(map(int, str(n)))
i = len(s) - 1
while i > 0 and s[i] <= s[i - 1]:
i -= 1
# 21
if i == 0:
return -1
# S[i] > S[i - 1]
... |
import argparse,math,os,sys,tables
import numpy as np
from operator import itemgetter
from sklearn import linear_model, model_selection, metrics
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
UNCHANGED,DOWN,UP,TARGET = 0,1,2,3
statdict = { UNCHANGED:'.', DOWN:'DOWN', UP:'UP', T... |
import machine
import ssd1306
import network
import time
SSID = 'myhomewifi'
PWD = 'myhomewifipassword'
WIDTH = const(128)
HEIGHT = const(32)
pscl = machine.Pin(5, machine.Pin.OUT)
psda = machine.Pin(4, machine.Pin.OUT)
i2c = machine.I2C(scl=pscl, sda=psda)
ssd = ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)
ssd.text(' He... |
"""
Simple script that shows the video-predictor API in action
"""
from robonet.video_prediction.testing.model_evaluation_interface import VPredEvaluation
import numpy as np
test_hparams = {}
test_hparams['designated_pixel_count'] = 1 # number of selected pixels
test_hparams['run_batch_size'] = 200 ... |
from xml.etree.ElementTree import Element
from frappe.model.document import Document
from trebelge.TRUBLCommonElementsStrategy.TRUBLAttachment import TRUBLAttachment
from trebelge.TRUBLCommonElementsStrategy.TRUBLCommonElement import TRUBLCommonElement
from trebelge.TRUBLCommonElementsStrategy.TRUBLParty import TRUBLP... |
print("Program to print Armstrong Numbers\n");
n=int(input("Enter any number: "));
i=n
count=0
while(i>0):
i=i//10
count=count+1
sum=0
i=n
while(i>0):
digit=i%10
x=1
pro=1
while(x<=count):
pro=pro*digit
x=x+1
sum=sum+pro
i=i//10
if(sum==n):
print(... |
import builtins
import numpy as np
import pytest
import autofit as af
import autogalaxy as ag
from autofit import Paths
class MockAnalysis:
def __init__(self, number_galaxies, shape, value):
self.number_galaxies = number_galaxies
self.shape = shape
self.value = value
... |
# Class for opsim field based slicer.
import numpy as np
from functools import wraps
import warnings
from rubin_sim.maf.plots.spatialPlotters import OpsimHistogram, BaseSkyMap
from .baseSpatialSlicer import BaseSpatialSlicer
__all__ = ['OpsimFieldSlicer']
class OpsimFieldSlicer(BaseSpatialSlicer):
"""A spatial... |
from django.contrib import admin
from .models import Document, Test_Data, Question_Data, Question_Attempt, Student_Data, Class_Section, Class_Assignment, Category
# Register your models here.
# Register your models here.
admin.site.register(Test_Data)
admin.site.register(Student_Data)
admin.site.register(Question_... |
import boto3
import datetime
from datetime import date, timedelta
import io
import os
import zipfile
import pathos.multiprocessing as mp
class DQCountExtractor(object):
"""Extracts xml counts from DQ for a range of given dates"""
def __init__(self):
self.aws_secret_access_key = os.environ['AWS_SECRE... |
/home/runner/.cache/pip/pool/c4/85/f3/59e253f622f4b09996a8c492d6c9939761a39b588c86b26ada5bbfd1df |
#!/usr/bin/python
import click
import os
from sidr import default
from sidr import runfile
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
def validate_taxdump(value, method):
if (os.path.isfile("%s/%s" % (value, "names.dmp")) and
os.path.isfile("%s/%s" % (value, "nodes.dmp")) and
os... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import copy
import numpy as np
from torchvision import datasets, transforms
import torch
from json import dumps
import datetime
import pandas as pd
import os
import random
from u... |
from urllib.parse import quote_plus
from openai import util
from openai.api_resources.abstract.api_resource import APIResource
class DeletableAPIResource(APIResource):
@classmethod
def _cls_delete(cls, sid, **params):
url = "%s/%s" % (cls.class_url(), quote_plus(sid))
return cls._static_reque... |
"""
Exercise 4
Create a list, x, consisting of the numbers [1,2,3,4]. Then, call the shuffle()
function(), passing this list as an argument. You'll see that the numbers in x
have been shuffled. Note, that the list is shiffled "in place." The is, the
original order is lost.
But what if you wanted to use this pro... |
"""Day 13 Part 2 of Advent of Code 2021"""
import sys
from pprint import PrettyPrinter
def process_input(input_file):
dots = []
folds = []
with open(input_file, encoding="utf8") as input_data:
current = True
while current:
current = input_data.readline()
if current ... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, Event, State
from flask import Flask
import flask
import webbrowser
import os
import pdb
#------------------------------------------------------------------------------------------------------... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
#====================================================================
# author: Chancerel Codjovi (aka codrelphi)
# date: 2019-09-12
# source: https://www.hackerrank.com/challenges/py-hello-world/problem
#=====================================================================
pr... |
# This file is part of ReACORN, a reimplementation by Élie Michel of the ACORN
# paper by Martel et al. published at SIGGRAPH 2021.
#
# Copyright (c) 2021 -- Télécom Paris (Élie Michel <elie.michel@telecom-paris.fr>)
#
# The MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# ... |
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... |
from __future__ import print_function
# this is written to retrive airnow data concatenate and add to pandas array for usage
from builtins import zip
from builtins import object
from datetime import datetime
import pandas as pd
from numpy import NaN, array
class improve(object):
def __init__(self):
self... |
import tyoudao
import tgoogle
f = open('dic.txt', encoding='utf-8')
fi = f.read()
f.close()
ls = eval(fi)
for li in ls[:3000-1385]:
try:
s1 = tgoogle.get(li[0])
s2 = tyoudao.get(li[0])
except KeyboardInterrupt:
quit()
except:
print('【错误】{}'.format(li[0]))
continue
... |
import gzip
import json
import pickle
input_file = 'ner_wikiner/corpus/dev.spacy'
# with open(input_file, 'rb') as fp:
# TRAIN_DATA = json.load(fp)
# for example in TRAIN_DATA:
# print(example)
# exit()
with open(input_file, 'rb') as f:
TRAIN_DATA = json.load(f)
|
from .platform_list import PlatformListAPIView
from .platform_detail import PlatformDetail
from .platform_create import PlatformCreate
|
import numpy as np
import cv2
from Arduino import Arduino
import time
# Python-Arduino Command API
board = Arduino("9600", port="/dev/cu.usbmodem14301")
board.pinMode(13, "OUTPUT")
cap = cv2.VideoCapture(0)
# OpenCV API
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if gray[2... |
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017-2018, Leo Moll
#
# 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
# ... |
"""Resources module."""
import abc
from typing import TypeVar, Generic, Optional
T = TypeVar('T')
class Resource(Generic[T], metaclass=abc.ABCMeta):
@abc.abstractmethod
def init(self, *args, **kwargs) -> Optional[T]:
...
def shutdown(self, resource: Optional[T]) -> None:
...
class A... |
from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField, GMLField
__all__ = [
'AreaField', 'DistanceField', 'GeomField', 'GMLField'
]
|
# 4K
you.shape = 'polygon'
color.type = 'mono'
for tear in me.face:
me.pixel /= 2
print('A required audio driver is missing.')
me.knock('floppy disk', target=screen)
screen.resolution = 3840 * 2160
|
# -*- coding: utf-8 -*-
""" Test printing of scalar types.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import assert_
class A(object):
pass
class B(A, np.float64):
pass
class C(B):
pass
class D(C, B):
pass
class B0(np.float64, A):
... |
from Observer import observer
import time
class weatherMonitor(observer):
def __init__(self, client, location):
self.client = client
self.location = location
self.latest_timestamp = 0
self.data =[]
self.content = ''
def Update(self):
pass
def set_timestamp(self):
self.latest_timestamp = time.time(... |
# Copyright 2020 The GenoML 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 ... |
from contextlib import contextmanager
from logging import getLogger
from pathlib import Path, PurePath
from typing import Dict, Iterator, Union, overload, Set, List
from modularconfig.errors import ConfigNotFoundError, ConfigFileNotFoundError
from modularconfig.loaders import load_file
logger = getLogger(__name__)
#... |
from ishuhui import create_app
app = create_app('env')
if __name__ == '__main__':
app.run(host=app.config['HOST'], port=int(app.config['PORT']), debug=True)
|
import jsonpickle
# import simplejson
load_success = jsonpickle.load_backend('json')
print (load_success)
jsonpickle.set_preferred_backend('json')
json_path_in = "examples/process_design_example/frame_ortho_lap_joints_no_rfl_process.json"
json_path_out = "examples/process_design_example/frame_ortho_lap_joints_no_rfl... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/markaligbe/Documents/PlatformIO/Projects/leviathans_breath_pio/gui/gui.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_... |
import json
import torch
import pickle
import itertools
import numpy as np
import pandas as pd
import torch.nn as nn
from pathlib import Path
from tabulate import tabulate
from nested_lookup import nested_lookup
from transformers import BertTokenizer
from haversine import haversine, haversine_vector, Unit
# File Utils... |
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.Sql_create.Tipo_Constraint import Tipo_Constraint, Tipo_Dato_Constraint
from Instrucciones.Excepcion import Excepcion
#from storageManager.jsonMode import *
class AlterTableAddConstraintFK(Instruccion):
def __init__(self, tabla, id_... |
"""
@no 21
@name Merge Two Sorted Lists
"""
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
answer = ListNode(0)
p = l1
q = l2
r = answer
while p or q:
if not p... |
from .futurasciences_crawling_job import FuturaSciencesCrawlingJob
from .liberation_crawling_job import LiberationCrawlingJob
from .nouvelobs_crawling_job import NouvelObsCrawlingJob
from .telerama_crawling_job import TeleramaCrawlingJob
from .lefigaro_crawling_job import LeFigaroCrawlingJob
from .lemonde_crawling_job ... |
from mongoengine import *
from mongoConfig import *
import math
import time
import sys
import re
from threading import Thread
sys.path.append('..')
from helpers import log
letters = []
def tfidfWorker():
while(len(letters) > 0):
currentLetter = letters.pop()
startTime = time.time()
log('tfidf', 'Calcula... |
#given an alphanumeric number guaranteed to have:
#1 integer paired to a sequence of characters
#the integer is guaranteed to be 0-9
#output a string that represents character sequences multiplied by integer number of times
def multi_num_by_string(s):
curr_num=0
curr_chars=''
output=''
nums = s... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
"""
Kube network manager DB
"""
from cfgm_common.vnc_object_db import VncObjectDBClient
class KubeNetworkManagerDB(VncObjectDBClient):
def __init__(self, args, logger):
self._db_logger = logg... |
from timeit import default_timer as timer
class ProgressBar():
def __init__(self, task='task'):
self.task = task
self.started = False
self.finished = False
def reset(self):
self.started = True
self.finished = False
self.prev_progress = 1e-8
self.star... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 15:19:36 2020
@author: Francesco Di Lauro
@mail: F.Di-Lauro@sussex.ac.uk
Copyright 2020 Francesco Di Lauro. All Rights Reserved.
See LICENSE file for details
"""
import networkx as nx
import numpy as np
from heapq import *
from datetime import d... |
#================================================================
#
# File name : utils.py
# Author : PyLessons
# Created date: 2020-09-27
# Website : https://pylessons.com/
# GitHub : https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3
# Description : additional yolov3 and yolov4 functio... |
import info
class subinfo(info.infoclass):
def setDependencies(self):
self.runtimeDependencies["virtual/base"] = None
self.runtimeDependencies["libs/qt5/qtbase"] = None
self.runtimeDependencies["libs/exiv2"] = None
self.runtimeDependencies["libs/iconv"] = None
self.runtimeD... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.rc('font', family='malgun gothic')
plt.rcParams['axes.unicode_minus'] = False
R = 8314.472
T = 310
F = 96485.3415
RTF = R*T/F
FRT = F/(R*T)
FFRT = F*F/(R*T)
current_time = 0
next_time = 1000
dt = 0.001
V = -86.2
m = 0
... |
from manimlib import *
class Music1(Scene):
def construct(self):
# manimpango.register_font("E:/Dropbox/manim/字体/阿里巴巴普惠体/阿里巴巴普惠体/Alibaba-PuHuiTi-Light.otf")
# print(manimpango.list_fonts())
text1 = Text(
"三个层次",
font="Source Han Sans CN",
weight=... |
from datetime import date
from django.db import IntegrityError
from django.test import TestCase
from pytest import raises
from .models import Car, Person, Vehicle, VicePrincipal
class SingleModelTest(TestCase):
def test_it_should_hide_soft_deleted_objects(self):
Person.objects.create(name='bob').soft_de... |
# header is ("4solr field", "darwin core field")
dwc_mapping = [
("accessionnumber_s", "catalogNumber"),
("alllocalities_ss", "tbd"),
("associatedtaxa_ss", "associatedTaxa"),
("blob_ss", "associatedMedia"),
("briefdescription_txt", "dynamicProperties"),
("collcountry_s", "country"),
("collco... |
# Author: Michael Lissner
# History:
# - 2013-06-03, mlr: Created
# - 2014-08-06, mlr: Updated for new website
# - 2015-07-30, mlr: Updated for changed website (failing xpaths)
from datetime import datetime
from juriscraper.OpinionSite import OpinionSite
from juriscraper.lib.string_utils import clean_if_py3
... |
#!/usr/bin/env python
ipv6_number = 'FE80:0000:0000:0000:0101:A3EF:EE1E:1719'
print(ipv6_number.split(":"))
|
"""
module to assess the current environment variables
default values loaded here
"""
from os import environ
from .static import PROD, TESTING, LOGLEVEL_KEY, STAGE_KEY
#https://en.wikipedia.org/wiki/Syslog#Severity_levels
EMERGENCY = "EMERGENCY"
ALERT = "ALERT"
CRITICAL = "CREITICAL"
ERROR = "ERROR"
WARNING = "WARNIN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.