content stringlengths 5 1.05M |
|---|
from django import forms
class ContentManageableModelForm(forms.ModelForm):
class Meta:
fields = []
def __init__(self, request=None, *args, **kwargs):
self.request = request
super().__init__(*args, **kwargs)
def save(self, commit=True):
obj = super().save(commit=False)
... |
#!/usr/bin/python
import os
import dense_correspondence_manipulation.utils.utils as utils
import logging
utils.add_dense_correspondence_to_python_path()
import matplotlib.pyplot as plt
import cv2
import numpy as np
import pandas as pd
import random
import scipy.stats as ss
import torch
from torch.autograd import Var... |
import unittest
from cupy import cuda
from cupy.testing import attr
@unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed')
class TestNCCL(unittest.TestCase):
@attr.gpu
def test_single_proc_ring(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
... |
# -*- coding: utf-8 -*-
"""
chanjo_report._compat
~~~~~~~~~~~~~~~~~~~~~~
Python 2.7.x, 3.2+ compatability module.
"""
from __future__ import absolute_import, unicode_literals
import operator
import sys
is_py2 = sys.version_info[0] == 2
if not is_py2:
# Python 3
# strings and ints
text_type = str
string_type... |
import pytest
from .. import exceptions
class TestAccessTokenException:
def test_exception(self):
ex = exceptions.AccessTokenException()
assert 'Error retrieving' in str(ex)
class TestDebugTokenException:
def test_exception(self):
ex = exceptions.DebugTokenException({})
as... |
"""
Compare Plot
============
_thumb: .5, .5
"""
import arviz as az
import numpy as np
import pymc3 as pm
az.style.use('arviz-darkgrid')
# Data of the Eight Schools Model
J = 8
y = np.array([28., 8., -3., 7., -1., 1., 18., 12.])
sigma = np.array([15., 10., 16., 11., 9., 11., 10., 18.])
with pm.Model('Centered ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ssl, socket
import pprint
import argparse
from datetime import datetime
URLS_TO_CHECK = []
# parse the arguments
parser = argparse.ArgumentParser()
parser.add_argument('-d', action="store_true", default=False, dest="discover", help="Zabbix discover mode.")
parser.... |
from com.jcraft.jsch import JSchException
from com.jcraft.jsch import JSch
from org.python.core.util import FileUtil
import sys
failed = []
exclude = "'Rollback point not found\|No space left on device\|Permission denied\|Already exists\|Unsupported key supplied'"
def run(command, session):
output = []
error... |
import sqlite3
import functools
import inspect
import hashlib
import os, errno
import logging
from os import path
import numpy
def make_dirs(p):
try:
os.makedirs(p)
except OSError as e:
if e.errno == errno.EEXIST:
return
else:
raise
PREFIX = 'sisfft-cached-tes... |
from django.urls import path
from .views import AccountsSignup, AccountsPanel, AccountsUpdate, AccountsUsersList, AccountsLogin,\
choice_location_manual, choice_location_api
from django.contrib.auth import views
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('signup/', AccountsS... |
"""Some useful utilities when dealing with neural nets w/ tensorflow.
Parag K. Mital, Jan. 2016
"""
import tensorflow as tf
import numpy as np
def montage_batch(images):
"""Draws all filters (n_input * n_output filters) as a
montage image separated by 1 pixel borders.
Parameters
----------
batch... |
#this is the example of file handling using python
def game():
return int(input("enter score "))
score=game()
with open("Highscore.txt") as f:
hiScoreStr=f.read()
if hiScoreStr=='':
with open("Highscore.txt","w") as f:
f.write(str(score))
print("updated")
elif int(hiScoreStr)<score:
with open("Highscore.txt","... |
# Copyright 2010 Google 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 ... |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Backends Test."""
import json
import jsonschema
from qiskit import IBMQ, Aer
from qiskit.backends.aer import AerProvide... |
from flask import render_template, current_app, copy_current_request_context
from flask_mail import Message
from . import mail
from threading import Thread
def send_email(to, subject, template, **kwargs):
msg = Message(current_app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=current_ap... |
word = input("Give me a word: ")
wrong = True
while wrong:
if word == "banana":
wrong = False
print("END GAME")
else:
print("WRONG")
word = input("Give me a word: ") |
from django.db import models
from employes import Employes
E_TYPE = (
(0, 'SICKNESS'),
(1, 'HOLIDAY'),
(2, 'MOVING')
)
class Absences(models.Model):
user = models.ForeignKey(Employes)
From = models.DateTimeField()
to = models.DateTimeField()
type = models.CharField(max_length=1, choices=E_... |
from sqlite_utils import Database
db = Database("cat_database.db")
# This line creates a "cats" table if one does not already exist:
db["cats"].insert_all([
{"id": 1, "age": 4, "name": "Mittens"},
{"id": 2, "age": 2, "name": "Fluffy"}
], pk="id") |
from __future__ import absolute_import
from erlpack.types import Atom
from erlpack import pack
def test_small_atom():
atm = Atom('hello world')
assert pack(atm) == b'\x83s\x0bhello world'
def test_large_atom():
atm = Atom('test ' * 100)
assert pack(atm) == (
b'\x83d\x01\xf4test test test te... |
from yaml_config.configuration import cut_protocol, open_config
|
"""
Notify Linux.
Copyright (c) 2013 - 2016 Isaac Muse <[email protected]>
License: MIT
"""
import subprocess
import os
from . import util
__all__ = ("get_notify", "alert", "setup", "destroy")
PLAYERS = ('paplay', 'aplay', 'play')
class Options:
"""Notification options."""
icon = None
notify = None
... |
# -*- coding: utf-8 -*-
from argparse import ArgumentParser, Namespace, ArgumentDefaultsHelpFormatter
import os
from dotenv import load_dotenv
import logging
import logging.config
import yaml
from pyconsem import Convertor
log = logging.getLogger(__name__)
DEFAULT_CONFIG_FILE = 'pyconsem.yml'
load_dotenv()
def get_... |
import sys
import logging
import os
from datetime import datetime
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as NP
import pandas as PD
logger = logging.getLogger('pyrsss.mag.fm2iaga')
HEADER_TEMPLATE = """\
Format IAGA-2002 |
... |
# Date: 12/28/2018
# Author: Mohamed
# Description: A list that will manage proxies
class ProxyList(object):
def __init__(self):
self.list = []
def __contains__(self, proxy):
for _proxy in self.list:
if _proxy.ip == proxy['ip'] and _proxy.port == proxy['port']:
... |
#!/usr/bin/env python
'''
This software was created by United States Government employees at
The Center for Cybersecurity and Cyber Operations (C3O)
at the Naval Postgraduate School NPS. Please note that within the
United States, copyright protection is not available for any works
created by United States Governm... |
from fineract.objects.note import Note
def test_document_creation(fineract):
note = Note.create(fineract.request_handler, Note.CLIENTS, 1, 'Test Note')
assert isinstance(note, Note)
def test_retrieve_all_documents(fineract):
notes = Note.get_all(fineract.request_handler, Note.CLIENTS, 1)
assert note... |
'''
MAP Client, a program to generate detailed musculoskeletal models for OpenSim.
Copyright (C) 2012 University of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client is free software: you can redistribute it and/or modify
it under the terms of the GNU Genera... |
import math
import numpy as np
from math import sqrt
from shapely.geometry import Point, LineString, MultiLineString
"""
A series of math functions for angle computations.
Readapted for LineStrings from Abhinav Ramakrishnan's post in https://stackoverflow.com/a/28261304/7375309.
"""
def _dot(vA, vB):
return vA[0... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cms_lab_publications', '0002_auto_20150527_1148'),
]
operations = [
migrations.AddField(
model_name='publication... |
"""Notifications API"""
import logging
from django.conf import settings
from django.db.models import Q
from django.contrib.auth.models import User
from channels.models import Subscription, ChannelGroupRole, Channel
from channels.api import get_admin_api
from channels.constants import ROLE_MODERATORS
from notificatio... |
import csv
import random
full_events = []
with open('../../data/fullevents.csv') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
for row in csv_reader:
full_events.append(row)
shot_score = {}
for i, item in enumerate(full_events):
if item[1] != 'Huskies':
continue
... |
# -*- coding: utf-8 -*-
import shutil
import pytest
from click.testing import CliRunner
from parboil.parboil import boil
def test_boil_list_help(boil_runner):
# help message
result = boil_runner("list", "--help")
assert result.exit_code == 0
assert result.output.startswith("Usage: boil list [OPTION... |
# Author: Nikolaos Perrakis <[email protected]>
#
# License: Apache Software License 2.0
"""NannyML Dataset module."""
from .datasets import (
load_modified_california_housing_dataset,
load_synthetic_binary_classification_dataset,
load_synthetic_multiclass_classification_dataset,
)
|
"""
Django settings for vauhtijuoksu project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pa... |
from django.db import models
class CustomManager(models.Manager):
"""
Filter not return deleted objects
"""
def get_queryset(self):
return super(CustomManager, self).get_queryset().filter(deleted=False, is_active=True)
class CommonFieldsMixin(models.Model):
"""
Contains Common fields fo... |
# 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный
# предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество.
# Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий
# название предмет... |
# Generated by Django 3.1.12 on 2021-06-11 20:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("core", "0001_initial")]
operations = [
migrations.AlterField(
model_name="event",
name="worth",
field=models.Integer... |
import logging
import numpy as np
from scipy.sparse import load_npz, csr_matrix, save_npz
class NeighborGraph(object):
def __init__(self, ids, path=None):
self.ids = ids
self.ids_to_indexes = { id : i for i, id in enumerate(ids) }
self.path = path
n = len(self.ids)
if pat... |
# -*- coding: utf-8 -*-
"""
Helpers for functional programming.
The :func:`identity` function simply returns its own inputs. This is useful for
bypassing print statements and many other cases. I also think it looks a little
nicer than ``lambda x: x``.
The :func:`inject_method` function "injects" another function into... |
data = """F10
N3
F7
R90
F11"""
with open('input.txt') as file:
data = file.read()
instructions = []
for line in data.splitlines():
line = line.strip()
d, v = line[0], int(line[1:])
instructions.append((d, v))
dirs = ['E', 'S', 'W', 'N']
ship_dir = 'E'
x, y = 0, 0
def turn(d, v):
global ship_d... |
"""
Regression tutorial
==================================================
This tutorial demonstrates that hardware-compatible Akida models can perform
regression tasks at the same accuracy level as a native CNN network.
This is illustrated through an age estimation problem using the
`UTKFace dataset <https://susanqq... |
# Copyright 2020 The PEGASUS Authors..
#
# 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... |
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
# Third party import
from rest_framework.response import Response
# from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
# Local import
from main_api.models import (
About, Skill, Educa... |
import os
from decouple import config, Csv
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config(... |
# Stores classes & functions needed to check harmony of a piece
from pyknon.music import Note, NoteSeq
from CheckMyChords.models import MusicPiece
from CheckMyChords.pyknon_extension import *
class Chord(object):
# a class storing a chord (as Note objects) and additional info about it
# (as well as methods f... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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 o... |
# -*- coding: utf-8 -*-
from random import randint
from string import ascii_letters
def reikna(atkvaedi, fjoldi_fulltrua):
#atkvæði eru á forminu {flokkur1: fjöldi atkvæða fyrir flokk1, flokkur2: fjöldi atkvæða ..., ...}
#fjoldi_fulltrua: heildarfjöldi fulltrúa fyrir kjördæmið
atkvaedi_kjordaemi = sum([atkvaedi[f]... |
import pytest
import dpnp
import numpy
def test_choose():
a = numpy.r_[:4]
ia = dpnp.array(a)
b = numpy.r_[-4:0]
ib = dpnp.array(b)
c = numpy.r_[100:500:100]
ic = dpnp.array(c)
expected = numpy.choose([0, 0, 0, 0], [a, b, c])
result = dpnp.choose([0, 0, 0, 0], [ia, ib, ic])
nump... |
import numpy as np
from scipy.special import eval_hermite, factorial
def hermite_functions(n, x, all_n=True, move_axes=(), method="recursive"):
"""
Calculate the Hermite functions up to the nth order at position x, psi_n(x).
For details see:
https://en.wikipedia.org/wiki/Hermite_polynomials#Hermite_f... |
import math
import random
import numpy as np
import random
import logging
import time
class exp3_m(object):
def __init__(self, choices, reward_min=0, reward_max=1, gamma=0.07, reward_function=None, model_path=None):
self.reward_min = reward_min
self.reward_max = reward_max
self.gamma = gam... |
# Generated by Django 2.1.7 on 2019-03-22 18:44
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import modelcluster.contrib.taggit
import modelcluster.fields
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migra... |
"""
PRONTO
Ordena lista em ordem alfabetica humana - http://nedbatchelder.com/blog/200712/human_sorting.html
Fonte: https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
"""
import re
def atoi(text):
"""
Se for digito retorna em formato integer, caso contrario retorn... |
from .detection_tools import *
|
# author: Paul Galatic
#
# Program to
# STD LIB
import os
import copy
import time
import random
import argparse
import linecache
from pathlib import Path
# REQUIRED LIB
import numpy as np
import grinpy as gp
import networkx as nx
import tabulate as tab
# PROJECT LIB
import de as de
import pso as pso
import firefly a... |
# This file is part of PeachPy package and is licensed under the Simplified BSD license.
# See license.rst for the full text of the license.
import inspect
import peachpy.stream
from peachpy.x86_64.instructions import Instruction
from peachpy.x86_64.operand import check_operand, format_operand_type, is_r32, is_im... |
from datetime import datetime, timedelta
import pytz
import pytest
from src.events import Events
from src.stores import MemoryStore
from src.session import Session
def test_get_event():
store = MemoryStore()
events = Events(store)
session = Session({}, store, '')
start = datetime.now(pytz.timezone("A... |
import ns.core
import numpy as np
from src.simulator.internet.sender import Sender
from src.simulator.internet.receiver import Receiver
class Communicator:
def __init__(self, ns_node, id=-1, offline_params={}, protocol='tcp', verbose=False,
global_comm_matrix=None):
self.ns_n... |
# Copyright (C) 2017 Red Hat, Inc.
# Darn, this needs to go away!
import argparse
class _FixMap(object):
opt_to_conf = {}
conf_to_opt = {}
def set(self, opt, conf):
self.conf_to_opt[conf] = opt
self.opt_to_conf[opt] = conf
def __init__(self):
self.set('project-name', 'name')
... |
import threading
import logging
import json
class EventHandler(threading.Thread):
log = logging.getLogger("events.EventHandler")
def __init__(self,event):
self.event=event.split(None)[0]
self.data = json.loads(event.lstrip(self.event).lstrip())
threading.Thread.__init__... |
"""LDAP Source tests"""
from unittest.mock import PropertyMock, patch
from django.test import TestCase
from authentik.core.models import User
from authentik.lib.generators import generate_key
from authentik.sources.ldap.models import LDAPPropertyMapping, LDAPSource
from authentik.sources.ldap.password import LDAPPass... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script interpolates across gaps in a column.
"""
import sys
import numpy as np
import pandas as pd
def data_interpolate(data, column_reference, column_in, column_out):
"""
Interpolates across gaps in a column
"""
reference = data[column_referenc... |
# Copyright 2021 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 agree... |
# Generated by Django 2.0.13 on 2019-04-07 15:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='address',
field... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from collections imp... |
class Player:
# This class returns a player's status in the killfeed
# def __init__(self, name, rounds, kills, deaths, team_kills, opening_kills, opening_deaths, clutches,
# plants, defuses, trades, headshot):
# self.trades = trades
# self.defuses = defuses
# self.plants... |
from account.models import Team, RoleEnvironment
from logical.models import Database
def databases_by_env(qs, teams):
roles = [team.role for team in teams]
role_environments = RoleEnvironment.objects.filter(
role__in=[role.id for role in roles]
).distinct()
environments = []
for role_env ... |
__all__ = ["trace_with", "val_diffs", "val_range"]
from numbers import Real
import sys
try:
from collections.abc import Mapping, Sequence, Set
from itertools import zip_longest
except ImportError:
from collections import Mapping, Sequence, Set
from itertools import izip_longest as zip_longest
def tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
create_official_data.py
A script to turn extract:
(1) conversation from Reddit file dumps (originally downloaded from https://files.pushshift.io/reddit/daily/)
(2) grounded data ("facts") extracted from the web, respecting robots.txt
Authors: Michel Galley and Sean Gao
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 16:08:35 2018
@author: Victor Onink
We have lon-lat positions for all the particles, but for making figures and such
makes more sense to consider densities. Also, I want to be able to consider densities
for more than just the last time point, and instead of generating ... |
#!/usr/bin/env python
ANSIBLE_METADATA = {
"metadata_version": "1.2",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: gns3_nodes_inventory
short_description: Retrieves GNS3 a project nodes console information
version_added: '2.8'
description:
- "Retrieves nodes in... |
import panther_event_type_helpers as event_type
def rule(event):
return event.udm("event_type") == event_type.MFA_DISABLED
def title(event):
# use unified data model field in title
return f"{event.get('p_log_type')}: User [{event.udm('actor_user')}] disabled MFA"
|
import math
import torch
import torch.nn as nn
from functools import partial
from .activated_batch_norm import ABN
from .activations import activation_from_name
# from pytorch_tools.modules import ABN
# from pytorch_tools.modules import activation_from_name
from pytorch_tools.modules import BlurPool
from pytorch_tools... |
#!/usr/bin/env python2
"""
files.py: Write to filesj
"""
from __future__ import print_function
import os
import sys
import mylib
from mylib import log
def run_tests():
# type: () -> None
f = mylib.BufWriter()
for i in xrange(30):
f.write(chr(i + 65))
contents = f.getvalue()
log('Wrote %d bytes to St... |
import os
from dotenv import load_dotenv
load_dotenv()
class Config(object):
DEBUG=True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = True
SEND_FILE_MAX_AGE_DEFAULT = 0
SECRET_KEY = "secret"
EMAIL_API = os.environ.get('EMAIL_API')
FACEBOOK_OAUTH_C... |
from django.apps import AppConfig
class MusicsConfig(AppConfig):
name = 'nomadgram.musics'
|
__________________________________________________________________________________________________
sample 24 ms submission
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
order_map={c:i for i,c in enumerate(order)} # create a hashmap
wordIndices=[[order_map[c] for c i... |
import unittest
import find_ele
class test_find_ele(unittest.TestCase):
def test_array_pair_sum(self):
self.assertEqual(find_ele.finder([5,5,7,7],[5,7,7]),5)
self.assertEqual(find_ele.finder([1,2,3,4,5,6,7],[3,7,2,1,4,6]),5)
self.assertEqual(find_ele.finder([9,8,7,6,5,4,3,2,1],[9,8,7,5,4,3,2,1]),6)
pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ed Mountjoy
#
import json
from glob import glob
import gzip
def main():
# Args
out_json = 'configs/manifest.json.gz'
valid_chrom = set([str(chrom) for chrom in range(1, 23)])
method = 'conditional'
# Path patterns (server)
root = '/home/js29/... |
#-------------------------------------------------------------------------------
# Author: Karthik Vegi
# Email: [email protected]
# Python Version: 3.6
#-------------------------------------------------------------------------------
import math
from datetime import datetime
def send_to_destination(output, desti... |
'''
Graph the functions 8n, 4nlogn, 2n^2, n^3, and 2^n using a logarithmic scale
for the x- and y-axes; that is, if the function value f (n) is y, plot this as a
point with x-coordinate at logn and y-coordinate at logy.
'''
import numpy
import matplotlib.pyplot
x , y, y1,y2,y3,y4 = [],[],[],[],[],[]
for i in range(2,20... |
def main():
y = 3
for x in [1, 2, 3]:
s = x + y
print(s)
y -= 1
print(s)
|
from typing import Dict
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from .conv import Conv2dRT, Conv2dLRT, Conv3dRT, Conv3dLRT
from .linear import LinearRT, LinearLRT
from .dropout import MCDropout
class MeanFieldVI(nn.Module):
def __init__(self,
... |
from pyramid.view import (
notfound_view_config,
exception_view_config,
forbidden_view_config,
)
from pyramid.httpexceptions import (
HTTPServerError,
HTTPBadRequest,
HTTPUnauthorized,
)
from ..services.encoding import encode_error_message
@notfound_view_config(renderer="json")
def notfound_vi... |
import csv
list_workclass = ['Private', 'Self-emp-not-inc', 'Self-emp-inc', 'Federal-gov', 'Local-gov', 'State-gov',
'Without-pay', 'Never-worked']
list_education = ['Bachelors', 'Some-college', '11th', 'HS-grad', 'Prof-school', 'Assoc-acdm', 'Assoc-voc', '9th',
'7th-8th', '12th... |
from ariadne.objects import MutationType
from chowkidar.utils import AuthError
from social_core.exceptions import MissingBackend
from social_django.views import _do_login
from social_django.utils import load_backend, load_strategy
social_auth_mutations = MutationType()
@social_auth_mutations.field('socialAuth')
de... |
#!/usr/bin/env python
# coding: utf-8
import html
import os
import re
import pandas as pd
import requests
from prettyprinter import cpprint
target_url = "http://scp-jp.wikidot.com/guide-hub"
start_word = '<h1 id="toc0"><span>先ずはこれを読んでください</span></h1>'
end_word = '<div class="footnotes-footer">'
def guide_hub():
... |
# Imports: standard library
import os
import logging
from typing import Dict, List, Tuple, Union, Optional
from collections import OrderedDict, defaultdict
# Imports: third party
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Model
# Imports: first party
from ml4c3.... |
import sys, sysconfig
import copy
import numpy
from distutils.extension import Extension
from distutils.util import get_platform
from distutils.dist import Distribution
from distutils.command.install_lib import install_lib
def get_openmoc_object_name():
"""Returns the name of the main openmoc shared library object"... |
# Generated by Django 2.1.7 on 2019-05-24 10:05
import datetime
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_depend... |
print('Sequência Fibonacci')
termos = int( input('Quantos termos? ') )
seq = []
for c in range(termos):
if(c == 0 or c == 1):
seq.append(c)
else:
seq.append( seq[c-1] + seq[c-2] )
print('\n', seq) |
from dataclasses import dataclass, field
from typing import List, Type
@dataclass
class Node:
class Meta:
name = "node"
node_or_mixed_a_or_mixed_b: List[object] = field(
default_factory=list,
metadata={
"type": "Elements",
"choices": (
{
... |
import asyncio
from pyrogram import idle
from scp import user, bot
from scp.core.functions.plugins import (
loadUserPlugins,
loadBotPlugins,
loadPrivatePlugins,
)
from scp.utils.selfInfo import updateInfo
from scp.utils.interpreter import shell
from scp.database.Operational import InitializeDatabase
HELP_... |
from src.utils.variants import variants
_values_in_file = variants + ['rd_' + v for v in variants] + ['fide']
def _format_line(ranking):
rank_list = [ranking[v][0] for v in variants] + [ranking[v][1] for v in variants] + [ranking['fide']]
return ("{}," * len(_values_in_file))[:-1].format(*rank_list)
def _p... |
import unittest
from math import pi
import numpy as np
from wisdem.ccblade.Polar import Polar, blend
class TestBlend(unittest.TestCase):
def setUp(self):
alpha = [
-3.04,
-2.03,
-1.01,
0.01,
1.03,
2.05,
3.... |
from flask import (Flask, request, jsonify)
from flask_jwt_extended import JWTManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_swagger_ui import get_swaggerui_blueprint
from datetime import (timedelta)
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "super-secret"
app.con... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import sys
from debugpy.common import log
from tests.patterns impor... |
# Generated by Django 2.1.15 on 2021-04-20 06:47
import core.models
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_m... |
from django.db import models
from robots_scraper.controller import get_robots_txt, robots_txt_extrapolation
class WebSite(models.Model):
domain = models.CharField(max_length=50)
website_url = models.CharField(max_length=50)
robots_txt_url = models.CharField(max_length=50)
websites = models.Manager()... |
import argparse
import joblib
import json
import numpy as np
import os
import pandas as pd
import warnings
from itertools import chain
from scipy.io import mmread
from sklearn.pipeline import Pipeline
from sklearn.metrics._scorer import _check_multimetric_scoring
from sklearn.model_selection._validation import _score
f... |
#!/usr/bin/env python
# coding: utf-8
"""
"""
import traceback
import time
import argparse
import sys
import datetime
from pathlib import Path
import shutil
from dotenv import load_dotenv
import pandas as pd
from column_definitions import standard_columns, key_mapping
from get_paper_info import get_paper_info, whi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.