content stringlengths 5 1.05M |
|---|
class Solution:
def isValid(self, s):
o = ['{', '(', '[']
c = ['}', ')', ']']
occurances = {}
occurances['{'] = '}'
occurances['('] = ')'
occurances['['] = ']'
list_occ = []
for letter in s:
if letter in o:
list_occ.append(l... |
__author__ = "arunrajms"
from rest_framework import serializers
from resource.models import Switch
from rest_framework.validators import UniqueValidator
import re
TIER_CHOICES = ['Spine','Leaf','Core','Host','Any','any']
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- requ... |
import os
import zipfile
import glob
import shutil
from pathlib import Path
def duplicate(path):
shutil.copy2(path, path + '_cpy')
return path + '_cpy'
def modify_to_rar(path):
if path.endswith('.pptx_cpy'):
new_str = path[:-9] + '.zip'
os.rename(path, new_str)
return new_str
... |
# This code belongs to the paper
#
# J. Hertrich and G. Steidl.
# Inertial Stochastic PALM (iSPALM) and Applications in Machine Learning.
# ArXiv preprint arXiv:2005.02204, 2020.
#
# Please cite the paper, if you use the code.
from palm_algs import *
import numpy.random
import numpy.matlib
import math
import matplotl... |
# Copyright (c) 2016, Philippe Remy <github: philipperemy>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND TH... |
from pytest import raises
from webhelpers2.number import *
def eq(a, b, cutoff=0.001):
"""Assert that two floats are equal within 'cutoff' margin of error.
"""
assert abs(a - b) < cutoff
class TestEQ(object):
def test_good(self):
eq(1.0001, 1.0002)
def test_bad(self):
with raise... |
"""This makes functions a subpackage(submodule) of combine""" |
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestBitfieldIvars(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self, "// break here", lldb... |
import os, time, sys
from colorama import Fore
os.system("clear")
print(Fore.RED + """
[ 1 ] { DMITRY }
[ 2 ] { WAFW00F }
[ 3 ] { THEHARVESTER }
[ 4 ] { NBTSCAN }
[ 5 ] { SNMP-CHECK }
CODED + BY + Furkan
""")
isc = input(Fore.BLUE + "["+ Fore.GREEN + " ENTER YOUR SELECTION " + Fore.BLUE + "] : ")
if isc =... |
def add_native_methods(clazz):
def flushBuffer__long__int__java_lang_Runnable__(a0, a1, a2, a3):
raise NotImplementedError()
clazz.flushBuffer__long__int__java_lang_Runnable__ = flushBuffer__long__int__java_lang_Runnable__
|
from mmdet.apis import init_detector, inference_detector, show_result
import mmcv
import os
demopath = os.path.dirname(os.path.realpath(__file__))
# config_file = 'configs/faster_rcnn_r50_fpn_1x.py'
# checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_20181010-3d1b3351.pth'
config_file = 'configs/mask_rcnn_r50_fpn_... |
from .alias import Alias
from .actor import Actor, HTTP_METHODS
from .execution import Execution, HTTP_METHODS
from .worker import Worker, HTTP_METHODS
from .nonce import Nonce
from .message import Message
|
"""Test cases describing different beliefs over quantities of interest of a linear
system."""
|
from __future__ import division
import mbuild as mb
import numpy as np
class SquarePattern(mb.Pattern):
"""A nanoparticle coating pattern where points are removed from two opposite poles on two axes.
Parameters
----------
chain_density : float
Density of chain coating on the nanoparticle (ch... |
from functools import partial
from Lab4.settings import START, STOP
def is_even(x):
return x % 2 == 0
def is_odd(x):
return x % 2 == 1
def is_divisible_by_n(x, n):
return x % n == 0
def does_data_satisfy_concept(data, concept):
return all(concept(item) for item in data)
def concept_power(conc... |
from .fixtures import foo_file
from libextract.core import parse_html, pipeline
def test_parse_html(foo_file):
etree = parse_html(foo_file, encoding='ascii')
divs = etree.xpath('//body/article/div')
for node in divs:
assert node.tag == 'div'
assert node.text == 'foo.'
assert len(divs... |
from typing import Optional, TYPE_CHECKING
import wx
if TYPE_CHECKING:
from gui.pane import FunctionPane
# noinspection PyPep8Naming
class ArrayControl(wx.ComboBox):
# noinspection PyShadowingBuiltins
def __init__(self, parent, id):
from functions import Function
choices = list(Function.g... |
import os
def get_file_list(file_path):
files = []
for root, dirs, files in os.walk(file_path):
print('# of files: {0}'.format(len(files))) # can be "pass"
file_list = files
return file_list
|
import logging
import sys
import os
sys.path.append(os.path.realpath(os.path.dirname(os.path.abspath(__file__)) + "/../../.."))
from scripts.extract import extract_from
from taipan.core import TaipanTarget
def execute(cursor):
logging.info('Reading guides from database')
guides_db = extract_from(cursor, 'targ... |
import datetime
import unittest
from openregister_client.util import Year, YearMonth, camel_case, markdown, utc
from openregister_client.util import parse_curie, parse_datetime, parse_item_hash, parse_text, parse_timestamp
class UtilTestCase(unittest.TestCase):
def test_datetime_parsing(self):
self.asser... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
Created on Tue Mar 07 11:48:49 2017
@author:
"""
from .exceptions import *
from .gismo import GISMOdataManager
from .gismo import ... |
from typing import Sequence
from Bot import BotState, ReplyResult, ReplyUtils, telegrammer, Room, Message
def room_human(msg: Message.Message, _: BotState) -> ReplyResult:
if 'Растеряться' in msg.replies: # Билл Гейтс
yield 'Растеряться'
telegrammer.get_message()
for i in range(6):
... |
def disp(*txt, p):
print(*txt)
ask = lambda p : p.b(input())
functions = {">>":disp,"?":ask}
|
# imports
import matlab.engine
import sys
# get the path from the shell arguments
target_path = sys.argv[1]
# start the matlab engine
eng = matlab.engine.start_matlab()
# add paths to the matlab path with the required functions
# TODO: add these from a separate file
eng.addpath('D:\Code Repos\miniscope_processing')
en... |
# we have if-else conditionals
# int and input are builtin functions
data = int(input('enter a number: '))
if data == 0:
print('it was zero')
elif data < 0:
print('negative')
else:
data = 'abc'
print(data)
print(type(data))
# while loop
# while input('enter x: ') != 'x':
# print('error, enter x')
... |
#!/usr/bin/env python
import random
import sys
number = 100
if len(sys.argv) > 1:
number = int(sys.argv[1])
def accumulate(list):
acu = 0
out = []
for el in list:
acu += el
out.append(acu)
return out
numbers = [ '00' ]
numbers += [ str(x) for x in xrange(0,37) ]
from enum impor... |
# Copyright (c) 2019 PaddlePaddle 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 app... |
# -*- coding: utf-8 -*-
import urllib
import urllib.request
import urllib.parse
import os
import todoist
from datetime import timedelta, date, datetime
slack_icon_url = 'https://pbs.twimg.com/profile_images/644169103750512640/zWCOmZLI.png'
def get_today_items():
today_items = []
api = todoist.TodoistAPI(toke... |
from modeltranslation.translator import translator, TranslationOptions
from .models import Person
class PersonTranslationOptions(TranslationOptions):
fields = ('name', 'surname')
translator.register(Person, PersonTranslationOptions)
|
# -*- coding: utf-8 -*-
""" Dataloading class for backtesting.
"""
from utils.common import *
from utils.timeseriessplit import TimeSeriesSplitCustom
from dataviewer import Viewer
class Loader:
""" Dataloading class.
"""
def __init__(self):
log_path = '.'.join(['backtest', __name__])
#self.... |
# -*- mode: Python; tab-width: 4 -*-
import sys
import getopt
import os
import os.path
import subprocess
import configparser
# Example config
# [Global]
# ctags=c:\wsr\apps\ctags58\ctags.exe
# [Carmageddon]
# wildcards=*.cpp;*.c;*.h;*.inl
# tagpaths=c:\Dev\LoveBucket\Development\Beelzebub\SOURCE;c:\Dev\... |
import json
import time
from typing import List
from instagrapi.exceptions import (ClientLoginRequired, ClientNotFoundError,
LocationNotFound)
from instagrapi.extractors import extract_location
from instagrapi.types import Location, Media
class LocationMixin:
"""
Helper cla... |
import scrapy
import requests
from bs4 import BeautifulSoup
import urllib.parse as urlparse
from clien_crawl.items import Article
from pymongo import MongoClient
import datetime
import sys
import PyRSS2Gen
class MacSpider(scrapy.Spider):
name = 'mac'
allowed_domains = ['clien.net']
start_urls = ['https:... |
import os
from dotenv import load_dotenv
import openai
load_dotenv()
openai.organization = "org-D2FBgBhwLFkKAOsgtSp86b4i"
openai.api_key = os.getenv("OPENAI_API_KEY")
# Creates a fine-tuned model for search
remote_files = openai.File.list()["data"]
fine_tuning_files = filter(lambda f: "fine_tune.jsonl" in f["filena... |
'''
Created on Oct 18, 2018
@author: srwle
'''
def str2ascii(in_str):
ret=''
if isinstance(in_str, str):
for c in in_str:
ret += hex(ord(c))
return ret
else:
return None
def testmain():
print(str2ascii('1234'))
if __name__ == '__main__':
testmain() |
from revoke import RevocationList
def test_set_check():
nl = RevocationList()
assert 16 * 1024 * 8 == nl.size()
assert not nl.is_revoked(54)
nl.revoke(54)
assert nl.is_revoked(54)
assert not nl.is_revoked(10320)
nl.revoke(10320)
assert nl.is_revoked(10320)
assert nl.is_revoked(54... |
from model.contact import Contact
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
class ContactHelper:
def __init__(self, application):
self.app = application
def create(self, contact... |
from . import api
@api.route('/')
def index():
return "Hello, world!"
@api.route('/hello')
def hello():
return "<h1>Testing</h1>" |
# this script helps to move issue from one youtrack instance to another
import sys
def main() :
try :
source_url, source_login, source_password, source_issue_id, target_url, target_login = sys.argv[1:7]
target_password, target_project_id = sys.argv[7:9]
except :
print "Usage : "
... |
import openpyxl
import re
import sys
import datetime
import json
import requests
import threading
import time
import gatherData
import printData
import getItemIds
path = "Rs3 Investments.xlsx"
wb_obj = openpyxl.load_workbook(path.strip())
# from the active attribute
sheet_obj = wb_obj.active
max_column=sheet_obj.max_... |
from website.app import init_app
from website.models import Node, User
from framework import Q
from framework.analytics import piwik
app = init_app('website.settings', set_backends=True)
# NOTE: This is a naive implementation for migration, requiring a POST request
# for every user and every node. It is possible to b... |
from torch import nn
from torch.nn import functional as F
from .ops import gram_matrix
class ContentLoss(nn.Module):
def __init__(self, target,):
super(ContentLoss, self).__init__()
# we 'detach' the target content from the tree used
# to dynamically compute the gradient: this is a stated... |
# import hashlib
# # from allauth.account.signals import user_signed_up, user_logged_in
# from django.dispatch.dispatcher import receiver
# from .models import Profile
# @receiver(user_signed_up)
# def social_login_fname_lname_profilepic(sociallogin, user, **kwargs):
# preferred_avatar_size_pixels=256
# pic... |
#!/usr/bin/env python3
import os, sys
import json
from urllib import request
from urllib.parse import urlencode
ENTRY = os.environ.get('GITLAB_URL')
TOKEN = os.environ.get('GITLAB_TOKEN')
DOING_LABEL = 'Doing'
GANTT_START = 'GanttStart:'
GANTT_END = 'GanttDue:'
# ToDo: get project by url
# ToDO: group by milestone
... |
'''This file contains the lengthy dictionaries used by the validation tool script'''
#list of field names
fieldNames = ["OID@","SHAPE@","STATEID","PARCELID","TAXPARCELID","PARCELDATE","TAXROLLYEAR",
"OWNERNME1","OWNERNME2","PSTLADRESS","SITEADRESS","ADDNUMPREFIX","ADDNUM","ADDNUMSUFFIX","PREFIX","STREETNAME",
"STREET... |
# Reference : https://www.w3schools.com/python/python_file_handling.asp
# Modes
'''
By default "mode=r"
Both read & write: mode=r+
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - ... |
# Code Sample from the tutorial at https://learncodeshare.net/2015/07/09/delete-crud-using-cx_oracle/
# section titled "Deleting records referenced by Foreign Keys" 1st example
# Using the base template, the example code executes a simple delete using named bind variables.
# When following the tutorial with defaul... |
from .learner import DBRMLearner
from .nn_structure import make_ope_networks
|
import skimage
import skimage.feature
import numpy as np
import llops as yp
import llops.operators as ops
import llops.filter as filters
import scipy as sp
# Feature-based registration imports
from skimage.feature import ORB, match_descriptors, plot_matches
from skimage.measure import ransac
from skimage.transform im... |
"""
Sample data:
{
"data": {
"id": "95.0",
"meta": {
"type": "attribute_change",
"entity_id": 758,
"new_value": "This is the newest description ever!!",
"old_value": "This is the old description!",
"entity_type": "Asset",
"attribute_name": "description",
"field_data_t... |
from django.db import models
from decimal import Decimal
# Create your models here.
class College(models.Model):
name = models.CharField(max_length=255, default='')
slug = models.CharField(max_length=255, default='')
acceptance = models.DecimalField(max_digits=3, decimal_places=2, default=0.00)
city = m... |
import unittest
from datetime import timedelta
from cachepot.expire import to_timedelta
class TestExpireSeconds(unittest.TestCase):
def test_to_timedelta(self) -> None:
# float
self.assertEqual(to_timedelta(1.0), timedelta(seconds=1.0))
# int
self.assertEqual(to_timedelta(3), ti... |
from web3 import Web3
OWNER_ACCOUNT_NO = 0
ADDER_ACCOUNT_NO = 1
# these values need to match with the values
# defined in CounterControllerV1 and CounterControllerV2
VALUE_INITIALIZED = 100
VALUE_INITIALIZED_V2 = 42
|
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth.models import User
# Create your models here.
class Location(models.Model):
title = models.CharField(max_length=200)
category = models.CharField(max_length=100)
location_logo = mo... |
def get_abi():
return [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": False,
"inputs": [
{
"indexed": True,
"internalType": "address",
"name": "owner",
... |
from enum import Enum, auto
class JagEvent(Enum):
DISCOVERED = auto()
AWARENESS = auto()
PREPARING = auto()
ADDRESSING = auto()
COMPLETION = auto()
SUMMARY = auto()
def __lt__(self, other):
"""
USC
"""
if self.__class__ is other.__class__:
retur... |
ALLOWED_HOSTS = ['*']
DEBUG = True
LOCAL_SETTINGS = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'fusionti_amcm_db',
'USER': 'fusionti_amcm_user',
'PASSWORD': 'UZLs{R4s{Yr~',
'HOST': '',
'PORT': '',
}
} |
import numpy as np
import glob
import tqdm
import cv2
import os
import math
import datetime
import seaborn as sns
import pandas as pd
import random
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
class DatasetRebalancing():
def __init__(self):
self.grid_info = {
"0": [0, 0.... |
from enum import Enum
from typing import List, Dict
import numpy as np
from nagi.constants import IZ_MEMBRANE_POTENTIAL_THRESHOLD, STDP_PARAMS, STDP_LEARNING_WINDOW, NEURON_WEIGHT_BUDGET, \
THRESHOLD_THETA_INCREMENT_RATE, THRESHOLD_THETA_DECAY_RATE, IZ_SPIKE_VOLTAGE
from nagi.neat import Genome, NeuralNodeGene, I... |
# NOTICE
#
# This software was produced for the U. S. Government under Basic Contract No.
# W... |
class Solution:
res = []
# 生成第 row 行的数据
def search(self, row, all_rows):
if row == all_rows:
return
arr = [1] * (row + 1)
for i in range(1, row):
arr[i] = self.res[row - 1][i - 1] + self.res[row - 1][i]
self.res.append(arr)
self.search(row + 1... |
from enum import Enum
from operator import attrgetter
from django.db import models
from django.db.models import sql
from django.db.models.deletion import Collector
from django.utils import six
from django_types.operations import CustomTypeOperation
from .fields import EnumField
"""
Use a symbol = value style as... |
from uvm.base import sv
from uvm.comps import UVMScoreboard
from uvm.macros import uvm_component_utils, uvm_info
from uvm.tlm1 import UVMAnalysisImp
class ram_scoreboard(UVMScoreboard):
"""
Compare signals from the DUT to a reference and give it a score
(PASS / FAIL)
"""
def __init__(self, name, p... |
"""Serializer of Category"""
from rest_framework import serializers
from apps.category.models import Category
class CategorySerializer(serializers.ModelSerializer):
"""Serializer Class of Category"""
class Meta:
"""Meta Class"""
model = Category
fields = "__all__"
|
"""trunk URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... |
#!/usr/bin/env python3
print((int(input())//2)**2) |
class Config():
def __init__(self):
self.is_training = True
# path
self.glove = 'data/glove.840B.300d.txt.filtered'
self.turian = 'data/turian.50d.txt'
self.train_path = "data/train.english.jsonlines"
self.dev_path = "data/dev.english.jsonlines"
self.test_path... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-30 11:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fpraktikum', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
import os
import doodad as pd
import doodad.ssh as ssh
import doodad.mount as mount
from doodad.easy_sweep import hyper_sweep
import os.path as osp
import glob
instance_types = {
'c4.large': dict(instance_type='c4.large',spot_price=0.20),
'c4.xlarge': dict(instance_type='c4.xlarge',spot_price=0.20),
'c4.2... |
def test_enter(player, limo):
player.perform("enter limo")
assert player.saw("You enter a fancy limo")
assert player.saw("electric")
def test_enter_and_exit(player, limo):
player.perform("enter limo")
player.forget()
player.perform("go out")
assert player.saw("Antechamber")
|
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for Affy module."""
import unittest
import struct
import os
import sys
try:
from numpy import array
import numpy.testing
except Imp... |
from bisect import bisect_left
from collections import defaultdict
M = 9999991# 100007
N = 51
class MaClass:
def __init__(self):
self.authors = [None for i in range(M)]
self.books = [None for i in range(M)]
def H(self,s):
h = 0
for c in s:
h = h * N + o... |
##########################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id$
#
# Copyright (C) 2009 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by ... |
URL_MAPPER = {
'COL:em-bonds':'https://www.trounceflow.com/api/v1/chart/granularbondholdingschart/non-resident-portfolio-flows-in-colombia-chart-in-colombian-peso.json',
'BRA:em-bonds':'https://www.trounceflow.com/api/v1/chart/granularbondholdingsflowchart/foreign-holdings-flow-in-brazil-chart.json',
'CHN:em-bonds':'ht... |
from pylangacq.dependency import DependencyGraph
_CHAT_GRAPH_DATA = [
("but", "CONJ", "but", (1, 3, "LINK")),
("I", "PRO:SUB", "I", (2, 3, "SUBJ")),
("thought", "V", "think&PAST", (3, 0, "ROOT")),
("you", "PRO", "you", (4, 3, "OBJ")),
("wanted", "V", "want-PAST", (5, 3, "JCT")),
("me", "PRO:OB... |
import curses
from typing import Dict
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from babi import color_kd
from babi.color import Color
def _color_to_curses(color: Color) -> Tuple[int, int, int]:
factor = 1000 / 255
return int(color.r * factor), int(color.g * factor), ... |
"""Comment copied from Python/compile.c:
All about a_lnotab.
c_lnotab is an array of unsigned bytes disguised as a Python string.
It is used to map bytecode offsets to source code line #s (when needed
for tracebacks).
The array is conceptually a list of
(bytecode offset increment, line number increment)
pairs. T... |
import numpy as np
import pandas as pd
array = [1,2,np.nan,4,5,np.nan,np.nan,1,2,2,np.nan,np.nan,4]
df_array = pd.DataFrame(array)
print("Arranjo original")
print(df_array)
print("\n")
print("Determinando a quantidade de NaNs no arranjo")
n_nans = df_array.isnull().values.sum()
print(n_nans)
print("\n")
print("Sub... |
from collections.abc import Iterable
from gaptrain.log import logger
import numpy as np
def soap(*args):
"""
Create a SOAP vector using dscribe (https://github.com/SINGROUP/dscribe)
for a set of configurations
soap(config) -> [[v0, v1, ..]]
soap(config1, config2) -> [[v0, v1, ..], [u0, ... |
class Scenario:
STAGES = [
{
"name": "install",
"path": "build/{version}/com/se/vulns/javacard/vulns.new.cap",
"comment": "",
},
{
"name": "install",
"path": "build/{version}/com/se/applets/javacard/applets.cap",
},
... |
import numpy as np
from functions import priors, likelihood
from functions import BIGNEG
import emcee
from emcee.autocorr import AutocorrError
from emcee.moves import DESnookerMove
class Tuner(object):
"""Decide which stretch parameter is best to use.
Tracks previous trials and generates new trials
along ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Ryan L. Collins <[email protected]>
# and the Talkowski Laboratory
# Distributed under terms of the MIT license.
"""
Collect lists of genes overlapped by a BED file of regions
"""
import pybedtools as pbt
import argparse
from sys import stdo... |
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
class Article:
def __init__(self):
self.title=""
self.time=""
self.text=""
self.category=""
self.tag=[]
class GetHtml(object):
def __init__(self,Url,Blog):
'''
Contrust a GetHtml obje... |
#encoding: utf-8
from PIL import Image
import numpy as np
from config import config as cfg
from torch.utils.data import Dataset
from torchvision import transforms as T
from sklearn.preprocessing import MultiLabelBinarizer
from imgaug import augmenters as iaa
import pathlib
import cv2
import pandas as pd
from torch.util... |
"""
Django settings for Match4healthcare project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
imp... |
import hashlib
import logging
from django import http
from django.core.cache import cache
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.db.models import Q, Count
from funfactory.urlresolvers import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def print_stat(gltf):
"""
モデル情報表示
:param gltf: glTFオブジェクト
"""
vrm = gltf['extensions']['VRM']
print 'vrm materials:', len(vrm['materialProperties'])
print 'materials:', len(gltf['materials'])
print 'textures:', len(gltf['textures'])
pri... |
from google.protobuf.duration_pb2 import Duration
from feast import FeatureView, FileSource
driver_hourly_stats = FileSource(
path="driver_stats.parquet", # this parquet is not real and will not be read
)
driver_hourly_stats_view = FeatureView(
name="driver_hourly_stats", # Intentionally use the same Featu... |
from binaryninja import *
from binjago import *
def find_func_symbol_refs(view):
bt = StdCallSearch(view)
bt.start()
def find_rop_gadgets(view):
rop_search = ROPSearch(view)
rop_search.start()
def find_prologues(view):
sig_search = PrologSearch(view)
sig_search.start()
PluginC... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import pytest
from pathlib import Path
from modnet.utils import get_hash_of_file
_TEST_DATA_HASHES = {
"MP_2018.6_subset.zip": (
"d7d75e646dbde539645c8c0b065fd82cbe93f81d3500809655bd13d0acf2027c"
"1786091a73f53985b08868c5be431a3c700f7f1776002df28ebf3a12a79ab1a1"
),
"MP_2018.6_small.zip": ... |
from test.util import TestCase
from unittest.mock import Mock
from OpenCast.infra.data.repo.context import Context
class ContextTest(TestCase):
def setUp(self):
self.repo = Mock()
self.context = Context(self.repo)
self.entity = "toto"
def test_add(self):
self.context.add(self... |
import argparse
import asyncio
from aioconsole import ainput
from .setup_agent import setup_agent
async def message_processor(register_msg):
user_id = await ainput('Provide user id: ')
while True:
msg = await ainput(f'You ({user_id}): ')
msg = msg.strip()
if msg:
response... |
from typing import Dict, Iterator, List, Union, Any, Type, cast
import numpy as np
import collections
import qulacs
from cirq import circuits, ops, protocols, schedules, study, value
from cirq.sim import SimulatesFinalState, SimulationTrialResult, wave_function
def _get_google_rotx(exponent : float) -> np.ndarray:
... |
#file to tell python that this directory contains a package
from alphadoc.docstring import get_docstring
from alphadoc.main import main |
from tutorial3_nohup1 import *
class NoHUPStartSSH(NoHUPStart):
username = batch.Property()
password = batch.Property()
server = batch.Property()
terminal = batch.Controller(SSHTerminal, username, password, server)
|
class Topic:
topics = {}
def __init__(self):
pass
def add_topic(self, data):
username = data['username']
topicname = data['topicname']
users = data['users'].users
# permission check
if not username in users or users[username]['role'] != 'admin':
print('Only admins can create topi... |
import math
class Node:
leftLength = 0
value = ""
isBalanced = True
def __init__(self, string, optimalLength=1000, minLength=500, maxLength=1500, isRoot=True):
halfWay = int(math.ceil(len(string) / 2))
self.isRoot = isRoot
# These are constants which are used to decide wh... |
import json
from random import randint
from colorama import init, Fore
# initialize colours
init()
GREEN = Fore.GREEN
RED = Fore.RED
BLUE = Fore.BLUE
WHITE = Fore.WHITE
CYAN = Fore.CYAN
def intro():
print(f"""{CYAN}
______ __ __ ______ __ __ ______ ______ __ __
... |
from ...helpers import format_result
from .queries import (GQL_CREATE_ORGANIZATION, GQL_DELETE_ORGANIZATION,
GQL_UPDATE_ORGANIZATION)
def create_organization(client, name: str, address: str, zip_code: str, city: str, country: str):
variables = {
'name': name,
'address': addre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.