content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import argparse
import json
import requests
import sys
import uuid
from bs4 import BeautifulSoup
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('-8', '--x86',
default=False, action='store_true',
help='Request x86 instead of x64')... |
# -*- coding: utf-8 -*-
"""
Not compatible with Python 3
Created on Fri Dec 4 18:11:16 2015
@author: Sravani Kamisetty
"""
from pandas import Series, DataFrame
from sklearn import tree
import pandas as pd
import numpy as np
import nltk
import re
from nltk.stem import WordNetLemmatizer
from sklea... |
# Rainbow Mode
from base_classes import *
from datetime import datetime, timedelta
import time
class RainbowMode(Mode):
key = "RAINBOW"
pos = 0.0
refTime = datetime.now()
def __init__(self, variant, speed, _range):
self.speed = speed
self.range = _range
self.variant = variant
... |
from __future__ import print_function
import sys
import numpy as np
import time
from io_shared import NumpyShare
def main():
N = 150000
cloud = np.empty((N, 4), dtype=np.float32)
size = cloud.nbytes
cloud_share = NumpyShare('/py27_to_py37', '5M', 'put')
label_share = NumpyShare('/py37_to_py27',... |
import numpy as np
# Reward matrix
R = np.matrix([ [-1,-1,-1,-1,0,-1],
[-1,-1,-1,0,-1,100],
[-1,-1,-1,0,-1,-1],
[-1,0,0,-1,0,-1],
[-1,0,0,-1,-1,100],
[-1,0,-1,-1,0,100] ])
# Quality matrix
Q = np.matrix(np.zeros([6,6]))
gamma = 0.8
# -----------------------------------------... |
def lin_test(name, tags=[]):
native.cc_test(
name = name,
srcs = native.glob([name + "/*.cpp"]),
deps = [
"@gtest//:gtest_main",
"//:lin"
],
tags = tags,
visibility = ["//visibility:private"],
)
|
# Xlib.xobject.drawable -- drawable objects (window and pixmap)
#
# Copyright (C) 2000 Peter Liljenberg <petli@ctrl-c.liu.se>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either v... |
from tkinter import *
from PIL import Image,ImageTk
from tkinter import ttk
from tkinter import messagebox
import pymysql
class Registration:
def __init__(self,root):
self.root=root
self.root.title('VOTER REGISTRATION')
self.root.geometry("1000x563+490+100")
self.root... |
import setuptools
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
import os
cxx_flags = []
ext_libs = []
authors = [
'Jiaao He',
'Jiezhong Qiu',
'Aohan Zeng',
'Tiago Antunes',
'Jinjun Peng',
'Qin Li',
]
if os.environ.get('USE_NCCL', '0') == '1... |
import torch
import torch.nn as nn
from typing import Tuple
def TheisConv(input=3, out=64, kernel=5, stride=1, activation=True) -> nn.Sequential:
if activation:
return nn.Sequential(
nn.ReflectionPad2d((1, stride, 1, stride)),
nn.Conv2d(
in_channels=input,
... |
from ruamel.yaml import YAML
import os
import pickle
import glob
import errno
import csv
import copy
import time
import logging
from .problem import Problem, ProblemException
logger = logging.getLogger("contest")
class Contest:
def __init__(self, path="."):
self.path = path
self.yaml = YAML()
... |
import os
import six
import PIL
from tmtoolkit.topicmod import model_io, visualize
try:
from wordcloud import WordCloud
def test_generate_wordclouds_for_topic_words():
py3file = '.py3' if six.PY3 else ''
data = model_io.load_ldamodel_from_pickle('tests/data/tiny_model_reuters_5_topics%s.pi... |
# *****************************************************************************
# *****************************************************************************
#
# Name: ellipse.py
# Purpose: Ellipse Algorithm test. Manipulated circle :)
# Created: 8th March 2020
# Author: Paul Robson (paul@robsons.org.uk)
#
# **... |
# author: Max Carter
# date: 25/11/18
# Sends the top posts from /r/ProgrammerHumor to a discord channel.
#import modules
from discord import *
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import praw
#setting up reddit account
reddit = praw.Reddit(client_id = "",... |
# -*- coding: utf-8 -*-
from utils import strip_html, simplify_html
from cleaners import default_cleaner
__all__ = ['strip_html', 'simplify_html', 'default_cleaner']
|
# Copyright 2021 Mario Guzzi
#
# 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 ag... |
"""
Athena SQL table definitions.
NOTE: make sure that any changes here are reflected in the parquet schemas defined
in parquet_variants.py and parquet_anno.py.
"""
def create_table_sql(table_type, table_name=None):
"""
Generates SQL DDL to create a variants table with the given name.
Returns a query wh... |
import os
from functools import wraps
FILE_PATH = os.path.dirname(__file__)
def _give_it_name(func, name):
@wraps(func)
def wrap():
return func(name)
return wrap
class _BuiltInDataSetsBase:
def __init__(self, file_name):
self._FILEPATH = os.path.join(FILE_PATH, './built-in-datasets... |
from primrose.base.node import AbstractNode
class TestExtNode(AbstractNode):
def necessary_config(self, node_config):
return []
def run(self, data_object):
terminate = False
return data_object, terminate
|
""" Library for the retroactively-updatable views. """
import threading
import baseviews
class Sum(baseviews.NumericView):
"""
View for retroactively-updatable Sum.
Since Sum is invertible and commutative, its implementation is fairly simple.
"""
def __init__(self, store, index):
self._index = index
... |
from setuptools import setup, find_packages
setup(name='sane_tikz',
version='0.1',
description='Python to TikZ transpiler',
long_description=open('tutorial.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='http://github.com/negrinho/sane_tikz',
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import sys, os
root_dir = os.path.join(os.path.dirname(__file__),'..')
if root_dir not in sys.path:
sys.path.insert(0, root_dir)
import time
import pickle
import numpy as... |
# coding=utf-8
# Copyright (c) 2015 EMC Corporation.
# 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
#
#... |
from construct import *
from construct.lib import *
repeat_eos_struct__chunk = Struct(
'offset' / Int32ul,
'len' / Int32ul,
)
repeat_eos_struct = Struct(
'chunks' / GreedyRange(LazyBound(lambda: repeat_eos_struct__chunk)),
)
_schema = repeat_eos_struct
|
"""
ui.py
"""
from __future__ import print_function
import atexit
import sys
from core import ansi
from core import completion
import libc
from typing import Any, List, Optional, Dict, IO, TYPE_CHECKING
if TYPE_CHECKING:
from core.util import _DebugFile
from core import completion
# ANSI escape codes affect th... |
import aku
import gym
import launch_moire
app = aku.App(__file__)
@app.register
def train(device: str = 'CPU', beta: float = 1e-4, average_entropy_decay: float = 0.999,
backward_separately: bool = True, batch_size: int = 32, n_episodes: int = 2000,
max_episode_len: int = 20000, num_layers: int =... |
import sys
from os import path
# To support 'uwsgiconf.contrib.django.uwsgify' in INSTALLED_APPS:
sys.path.insert(0, path.dirname(__file__))
|
import utils
with open("4.txt") as f:
candidate = None
max_count = 0
for line in f.readlines():
decrypted, key, count = utils.freq_analysis(utils.ByteArray.fromHexString(line.strip()))
if count > max_count:
max_count = count
candidate = decrypted
print candidate... |
#
# Created by Lukas Lüftinger on 05/02/2019.
#
try:
from .annotation import fastas_to_grs
except ModuleNotFoundError:
from phenotrex.util.helpers import fail_missing_dependency as fastas_to_grs
__all__ = ['fastas_to_grs']
|
# Conductance models of specific cell subtypes
#===============================================================================
# Mostly based on: Destexhe et al. J Neurophys 1994 (72)
# https://pdfs.semanticscholar.org/7d54/8359042fabc4d0fcd20f8cfe98a3af9309bf.pdf
# Calcium dynamics from: https://www.physiology.org/do... |
"""
Project Euler: Problem 1: Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
"""
def multiples(n):
sum = 0
for ii i... |
# Generous tit for tat
import random
class MyPlayer:
def __init__(self, payoff_matrix, number_of_iterations):
self.payoff_matrix = payoff_matrix
self.number_of_iterations = number_of_iterations
self.opponent_last_move = False
def move(self):
if self.opponent_last_move == True:... |
"""
A collection of some distance computing functions for calculating similarity
between two tensors. They are useful in metric-based meta-learning algorithms.
"""
import torch
import torch.nn.functional as f
from typing import Callable
__all__ = ['get_distance_function']
def euclidean_distance(
x: torch.FloatTe... |
import time
from typing import Any, Union
import numpy as np
import pandas as pd
from .format_time import format_time_hhmmss
class Timestamps:
def __init__(self) -> None:
"""
Container for storing timestamps
and calculating the difference between two
timestamps (e.g. the latest... |
#!/usr/bin/env python
# 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, software
# d... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 1997-2021 Andy Lewis #
# --------------------------------------------------------------------------- #
# For details, see the LICENSE file in this repository #
def mean(values):
return sum(val... |
from django.utils import timezone
from processes.models import GroupInfo
import factory
from pytest_factoryboy import register
from .group_factory import GroupFactory
@register
class GroupInfoFactory(factory.django.DjangoModelFactory):
class Meta:
model = GroupInfo
group = facto... |
from padinfo.core.find_monster import findMonsterCustom2
async def perform_transforminfo_query(dgcog, raw_query, beta_id3):
db_context = dgcog.database
mgraph = dgcog.database.graph
found_monster, err, debug_info = await findMonsterCustom2(dgcog, beta_id3, raw_query)
if not found_monster:
ret... |
# Generated by Django 2.2.4 on 2019-08-09 21:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='post',
name='content',
field... |
import unittest
try:
import vimba
from vimba import Vimba, VimbaFeatureError
except Exception:
raise unittest.SkipTest(
"vimba not installed. Skipping all tests in avt_camera_test.py")
from pysilico_server.devices.avtCamera import AvtCamera
from time import sleep
import functools
def withCamera(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... |
def main():
# Prompt the user to enter a file
filename = input("Enter a filename: ").strip()
infile = open(filename, "r") # Open the file
wordCounts = {} # Create an empty dictionary to count words
for line in infile:
processLine(line.lower(), wordCounts)
pairs = list(wordCounts.item... |
# coding: utf-8
import math
from datetime import datetime
from datetime import timedelta
import pytz
TIMESTAMP_BASEDATE = datetime(year=1970,month=1,day=1,tzinfo=pytz.utc)
class TimeUtil:
@staticmethod
def timestamp_utc(timeaware_datetime):
diff = timeaware_datetime - TIMESTAMP_BASEDATE
return... |
'''
.. module:: skrf.io.general
========================================
general (:mod:`skrf.io.general`)
========================================
General io functions for reading and writing skrf objects
.. autosummary::
:toctree: generated/
read
read_all
read_all_networks
write
write_all
... |
#AmendEmployeeScreen
ADMIN_PASS_INCORRECT = u"The Administrator password was incorrect."
AMEND_BUTTON_TEXT = u"Amend"
AMEND_BY_TEXT = u"Amend Field : "
AMEND_EMP_SCREEN_NONETYPE_ERROR_TEXT = u"Please enter Amendment Criteria."
AMEND_FOR_TEXT = u"Amend to : "
AMEND_FOR_EMPLOYEES_TEXT = u"Amend a Record : "
BACK_BUTTON_... |
# -*- coding: utf-8 -*-
"""
1656. Design an Ordered Stream
There is a stream of n (id, value) pairs arriving in an arbitrary order,
where id is an integer between 1 and n and value is a string.
No two pairs have the same id.
Design a stream that returns the values in increasing order of their IDs by returning a chunk... |
# -*- coding: utf-8 -*-
#######################################################################
#
# Series Plugin for Enigma-2
# Coded by betonme (c) 2012 <glaserfrank(at)gmail.com>
# Support: http://www.i-have-a-dreambox.com/wbb2/thread.php?threadid=TBD
#
# This program is free software; you can redistrib... |
# This file was automatically created by FeynRules 2.3.35
# Mathematica version: 12.1.0 for Linux x86 (64-bit) (March 18, 2020)
# Date: Wed 6 Jan 2021 16:20:38
from object_library import all_vertices, Vertex
import particles as P
import couplings as C
import lorentz as L
V_1 = Vertex(name = 'V_1',
part... |
import tensorflow as tf
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from plotting import newfig, savefig
import matplotlib.gridspec as gridspec
import time
from utilities import neural_net, fwd_gradients,\
tf_session, mean_squared_error, relative_error
c... |
"""Module for tracing equilibria in mixture games"""
import numpy as np
from scipy import integrate
from gameanalysis import regret
from gameanalysis import rsgame
from gameanalysis import utils
# FIXME Doesn't matter if F is singular, it matters if any solution exists. If
# F is nonsingular, then a solution definit... |
# 2016-17 By Tropicalrambler GPL V3.0 License
#!/usr/bin/env python
# ^^^^^^^^^^^^^^^^^^^ World famous shebang line!
# TESTED! 18-DEC-2016 ON TSC TPP-442 Pro, WORKS GREAT!
###### DEPENDENCIES!! Requires pip, reportlab, pybarcode, babel
# CODETAGS from PEP -0350
#https://www.python.org/dev/peps/pep-0350/#gener... |
import collections
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
state = sum(cell << (i * n + j) for i, row in enumerate(mat) for j, cell in enumerate(row))
Q = collections.deque([state])
visited = set([state])
step = 0
... |
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QRect
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import widget
import oasys.widgets.gui as oasysgui
from oasys.widgets.gui import ConfirmDialog
from orangecontrib.photolab.widgets.gui.ow_photolab_widget i... |
from flask import (
current_app, request, redirect, url_for, render_template, flash, abort
)
from flask.ext.babel import gettext, lazy_gettext
from flask.ext.login import login_user, login_required, logout_user
from itsdangerous import URLSafeSerializer, BadSignature
from app.public.forms import RegisterGroupForm, ... |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from user import views
from user.views import ActiveView, LoginView, RegisterView, LogoutView, UserInfoView, AddressView, UserOrderView
urlpatterns = [
# url(r'^register$',views.register, name='register'),
# url(r'^reg... |
"""
Django settings for cogpheno project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... |
# 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 in writi... |
import os
import time
from _functions.setup_database import create_database, fill_database, drop_database
from classes.poducts_filter import FilterProducts
from classes.pymongo_converter import Converter
from classes.send_data import DataSender
from classes.sessions_filter import FilterSessions
from Rules.Content_rule... |
# coding: utf-8
from django.shortcuts import render, get_object_or_404
from django.http import Http404, QueryDict
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.db.models import Q
from django.contrib.auth.models import User
from django.utils.translation import uget... |
# Generated by Django 2.2.24 on 2022-02-23 22:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exchange', '0003_auto_20200122_2156'),
]
operations = [
migrations.AddField(
model_name='currency',
name='active',
... |
import configparser
import urllib.parse
class ConfigLoader:
class SectionNotFound(Exception):
pass
class KeyNotFound(Exception):
pass
def __init__(self, file):
self.config = configparser.ConfigParser()
self.config.read(file)
self.check_sections()
self.chec... |
import lmdb
env = lmdb.open(path='/media/scratch/t4.lmdb',
map_size=1048576*1024*3,
map_async=True,
sync=False,
metasync=False,
writemap=False)
txn = env.begin(write=True)
it = None
unhex = lambda s: s.decode('hex')
for line in file('/tmp/lmdb.trace'):
bits = line.rstrip('\n').split(... |
#!/usr/bin/python
# ToDo: Refactoring
# ToDo: Mapping a tiny piano-keyboard to the keyboard
import time
import keyboard
import paho.mqtt.client as mqtt
import logging
logging.basicConfig(level=logging.DEBUG)
from utils.display import triangel, piano, pluck
from utils.functions import get_ip_adress
from utils.settin... |
import unittest
from mock import MagicMock, patch, call
from device.simulated.grid_controller import GridController
from device.simulated.diesel_generator import DieselGenerator
from device.simulated.pv import Pv
from device.simulated.grid_controller.price_logic import AveragePriceLogic
from device.simulated.eud import... |
# *******************************************************************************
# Copyright (C) 2020-2021 INAF
#
# This software is distributed under the terms of the BSD-3-Clause license
#
# Authors:
# Ambra Di Piano <ambra.dipiano@inaf.it>
# **************************************************************************... |
import json
import gym
import gzip
import time
from gym.utils.play import play, PlayPlot
from ai_traineree.buffers import ReplayBuffer
def buffer_callback(buffer):
def callback(obs_t, obs_next, action, rew, done, *args, **kwargs):
buffer.add(**dict(state=obs_t, action=[action], reward=[rew], done=[done])... |
from __future__ import unicode_literals
import collections
import os
import subprocess
import sys
import _pyterminalsize
import pytest
import pyterminalsize
PY3 = str is not bytes
WIN = sys.platform == 'win32'
def to_n(s):
if isinstance(s, bytes) and PY3: # pragma: no cover (py3)
s = s.decode('UTF-8... |
from heapq import heappush, heappop
class Stack:
def __init__(self):
self.data = []
@property
def empty(self):
return len(self.data) == 0
def push(self, element):
self.data.append(element)
def pop(self):
return self.data.pop()
class Queue:
def __init__(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import errors
import re
from datetime import datetime
TASK_MANAGER_NAME = "crawtext_jobs"
TASK_COLL = "job"
class Database(object):
'''Database creation'''
def __init__(self, database_name, debug=False):
se... |
#!/usr/bin/env python
# Copyright (c) 2009-2010 Matt Harrison
import sys
import optparse
import os
import logging
from coverage.report import Reporter
from coverage.misc import CoverageException
from coverage.control import Coverage
from coverage.config import CoverageConfig
from . import meta
COVERED = 'Error'#'C... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By : Simon Schaefer
# Description : Task aware image downscaling autoencoder model - SCALING.
# Convolutional layers only (no resblocks).
# ============================... |
#!/usr/bin/python
#
# Copyright (C) 2008 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 ... |
#!/usr/bin/env python3
'''fhnwtoys ~ package
Copyright (C) 2020 Dominik Müller and Nico Canzani
'''
from setuptools import setup, find_packages
setup(name='fhnwtoys', version='1.0', packages=find_packages())
|
from csdl.core.standard_operation import StandardOperation
from csdl.core.node import Node
class indexed_passthrough(StandardOperation):
def __init__(self, *args, output, **kwargs):
self.nargs = None
self.nouts = 1
super().__init__(*args, **kwargs)
self.outs = [output]
|
# Generated by Django 3.2 on 2021-04-12 10:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AnalysisApp', '0002_alter_users_departmentid'),
]
operations = [
migrations.RenameField(
model_name='team',
old_name='Departme... |
import numpy as np
class InfoManager():
def __init__(self,server, pid):
self.server=server
self.pid=pid
self.info={}
self.kind='InfoManager'
self.itype_fromto={
'ping':0,
'player_data':1,
}
def get_data(self, pid):
... |
# 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, software
# distr... |
import socket, struct, math, time
def fk(l1, l2, t1, t2):
th1 = math.radians(t1)
th2 = math.radians(t2)
x = l1*math.cos(th1) + l2*math.cos(th1+th2)
y = l1*math.sin(th1) + l2*math.sin(th1+th2)
return x, y
host = "127.0.0.1"
port = 5678
addr = (host, port)
steps = 99
while True:
t1 = float(input("theta1... |
def simple_replace(source):
source = source.replace("isWalkable", "isAccessible")
source = source.replace(".x()", ".x")
source = source.replace(".y()", ".y")
source = source.replace("groundWeaponMaxRange", "weaponMaxRange")
source = source.replace("airWeaponMaxRange", "weaponMaxRange")
source = ... |
import os
FIRST_VERSION = '1.00.00.00'
def ReadVersion(version_filename):
if os.path.exists(version_filename):
return open(version_filename).readlines()[0]
else:
return FIRST_VERSION
def ReadAndUpdateVersion(version_filename, update_position=None):
"""Takes given filename containing version, optional... |
from unittest import mock
import pytest
from allauth.socialaccount.models import SocialApp
from ..views import CustomGitHubOAuth2Adapter
class TestGitHubOAuth2Adapter:
@pytest.mark.django_db
def test_complete_login(self, mocker, rf):
mocker.patch("metecho.oauth2.github.views.GitHubOAuth2Adapter.comp... |
# -*- coding: utf-8 -*-
# Copyright 2014-2022 CERN
#
# 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... |
from __future__ import unicode_literals
from django.apps import AppConfig
class FeedbackManagementConfig(AppConfig):
name = 'feedback_management'
|
import warnings
warnings.simplefilter('ignore', FutureWarning)
from pandas_datareader import wb
import matplotlib.pyplot as plt
df = wb.download(indicator='SP.POP.TOTL', country=['JP', 'US'],
start=1960, end=2014)
print(df)
# SP.POP.TOTL
# country year
# Japan ... |
class Solution:
def largestNumber(self, nums: List[int]) -> str:
for i in range(len(nums), 0, -1):
for j in range(i-1):
if not self.compare(nums[j], nums[j+1]):
nums[j], nums[j+1] = nums[j+1], nums[j]
return str(int("".join(map(str, nums))))
def c... |
"""Line-delimited GeoJSON"""
from .geojson import GeoJsonReader, GeoJsonWriter, GeoJsonDriver
FIONA_DRIVER = 'GeoJSONSeq'
PATH_REGEXP = r'^(?P<file_path>(?:.*/)?(?P<file_own_name>.*)\.(?P<extension>geojsonl\.json|geojsonl))$'
class GeoJsonSeqReader(GeoJsonReader):
fiona_driver = FIONA_DRIVER
source_regexp = PATH_RE... |
"""
SynthTIGER
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
import imgaug.augmenters as iaa
import numpy as np
from synthtiger.components.component import Component
class AdditiveGaussianNoise(Component):
def __init__(self, scale=(8, 32), per_channel=0.5):
super().__init__()
self.scale... |
def partition(a,si,ei):
p = a[si]
c = 0 # c will be number of elements smaller than p
for i in range(si,ei+1):
if a[i] < p:
c += 1
a[si], a[si+c] = a[si+c], a[si]
i = si
j = ei
while i < j:
if a[i] < p:
i = i+1
elif a[j] >= p:
j = j... |
#!/usr/local/bin/python3
#
# Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause OR Arm’s non-OSI source license
#
# secure boot process.
# Key certificate structure is :
# FIELD NAME SIZE (words)
# ... |
# encoding: utf-8
# module pandas._libs.tslibs.resolution
# from C:\Python27\lib\site-packages\pandas\_libs\tslibs\resolution.pyd
# by generator 1.147
# no doc
# imports
import __builtin__ as __builtins__ # <module '__builtin__' (built-in)>
import numpy as np # C:\Python27\lib\site-packages\numpy\__init__.pyc
# funct... |
from django.contrib import admin
from .models import Person, Page
admin.site.register(Person)
admin.site.register(Page)
|
"""
Backward-compatibility shim for users referencing the module
by name. Ref #487.
"""
import warnings
from .macOS import Keyring
__all__ = ['Keyring']
warnings.warn("OS_X module is deprecated.", DeprecationWarning)
|
class Solution:
def myAtoi(self, s: str) -> int:
max_value = 2 ** 31 - 1
min_value = -2 ** 31
num = 0
digit_only = False
sign = None
for c in s:
if '0' <= c <= '9':
digit_only = True
c = int(c)
if num is None... |
#! /usr/env/python
"""Fastscape stream power erosion."""
# This module attempts to "component-ify" GT's Fastscape stream
# power erosion.
# Created DEJH, March 2014.
from __future__ import print_function
import numpy as np
from six import string_types
from landlab import BAD_INDEX_VALUE as UNDEFINED_INDEX, Component... |
# -*- coding: utf-8 -*-
import time
import re
import base
import swagger_client
from swagger_client.rest import ApiException
class System(base.Base):
def get_gc_history(self, expect_status_code = 200, expect_response_body = None, **kwargs):
client = self._get_client(**kwargs)
try:
dat... |
from django import forms
from django.db.models import query
from .models import eventos, eliminar
from randp.models import Ramos_y_preferencias
class formularioEventos(forms.ModelForm):
nombre = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Nombre de la evaluacion..." , "max_length" : 20}))
fe... |
import copy
import json
import random
from utils import common
from utils import fever_db
from utils.sentence_utils import SENT_LINE, check_and_clean_evidence, Evidences
def load_data(file):
d_list = []
with open(file, encoding='utf-8', mode='r') as in_f:
for line in in_f:
item = json.loa... |
# MODULE: file
# PURPOSE: copies files, changes modes, renders templates, deletes files, slices, dices
# CATEGORY: general
# PROVIDERS: file
# RELATED: directory
# FYI: See the online documentation for the full parmameter list
#
# DESCRIPTION:
#
# The File module handles all major types of file ope... |
from optparse import OptionParser
from jai.logger import Severity, log
import jai
from jai.mode import Mode
def version():
print(f"Jai {jai.__version__}")
exit(0)
def get_args():
ops = OptionParser()
ops.add_option(
"--version",
action="store_true",
dest="version",
de... |
"""
Alex Staley -- Student ID: 919519311
Assignment 2 -- February 2020
### HERE BEGINS THE Network.py FILE ###
This code defines the NeuralNetwork class. It contains two arrays
of Perceptron objects, representing a hidden layer and an output layer
of neurons. Methods implemented here execu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.