text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 10:12:12 2019
@author: Phan Huy Thong
"""
import os, sys
sys.path.append(os.getcwd())
import argparse
from system import System
from config import Config as cfg
import utils
import torch
if __name__ == '__main__':
#read argument
parser = argparse.ArgumentPar... | 3,845 | 1,399 |
#
# PySNMP MIB module DV2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DV2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:40:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | 538,763 | 257,837 |
# Generated by Django 2.0.13 on 2019-12-11 15:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('credit', '0033_credit_resolution_failed'),
]
operations = [
migrations.AlterField(
model_name='log',
name='action',... | 675 | 225 |
from enum import Enum
from typing import List
from ._modeljsonutil import AbstractTypeParserSwitcherBuilder
class DatasetType(Enum):
UNDEFINED = 'UNDEFINED'
POINT = 'POINT'
LINE = 'LINE'
REGION = 'REGION'
TEXT = 'TEXT'
NETWORK = 'NETWORK'
GRID = 'GRID'
IMAGE = 'IMAGE'
... | 63,449 | 24,767 |
#!/usr/bin/env python
import asyncio
import json
import threading
import sys
from lib.monitor import Monitor
from lib.stats_writer import StatsWriter
config = json.load(open('config.json'))
def run_monitor():
monitor = Monitor(config)
# asyncio on Windows solution learnt from here: https://github.com/encod... | 1,356 | 434 |
''' script to get predictions for movielens data '''
from measures import predictions
from processing import preprocessing
import time
import pickle
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--movielens_data', choices=['small', '100k'], required=True... | 2,800 | 996 |
from PyQt5.QtCore import QRegularExpression, Qt, QRegularExpressionMatchIterator, QRegularExpressionMatch, QRegExp
from PyQt5.QtGui import QSyntaxHighlighter, QTextDocument, QTextCharFormat, QFont, QColor
from widgets.syntax_highlighters.highlighting_rule import HighlightingRule
# noinspection SpellCheckingInspection... | 11,608 | 4,687 |
'''
File [ hubconf.py ]
Author [ Heng-Jui Chang (NTUEE) ]
Synopsis [ Hubconf. ]
'''
import os
import torch
from miniasr.utils import load_from_checkpoint
def asr_local(ckpt):
'''
ASR model from a local checkpoint.
'''
assert os.path.isfile(ckpt)
model, _, _ = load_from_ch... | 923 | 369 |
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from sklearn import preprocessing
from keras.layers import Dropout
from keras import regularizers
df = pd.read_csv('housepricedata.csv')
print(df)
... | 1,964 | 776 |
"""
Scraping Engine creates the Identiy Data for the papers.
The Mining Engine on Instantiation
- Will check For the New Papers to Mine.
- It will Create a ArxivPaper
--> Download Latex
--> Parse Latex
--> Sematically Parse the Paper here too.
... | 7,934 | 2,372 |
#!/usr/bin/env python3
from argparse import ArgumentParser
from collections import defaultdict
import numpy as np
import os
import pickle
import matplotlib
matplotlib.use('pdf')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['font.size'] = 12
import matplotlib.pypl... | 3,190 | 1,070 |
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.nn.init import kaiming_normal_
from torch.nn.utils import weight_norm
from torch.autograd.variable import Variable
import math
__all__ = ['convlarge']
# noise function taken from blog : https://ferretj.github.io/ml/2018/01/22/temporal-ense... | 5,807 | 2,563 |
from django.conf.urls.static import static
from django.conf.urls import url
from django.conf import settings
from . import views
urlpatterns=[
url('^$', views.index, name = 'index'),
url(r'^profile$',views.profile,name='profile'),
url(r'^profile/edit$',views.edit_profile,name='edit'),
url(r'^profile/up... | 932 | 316 |
# Tai Sakuma <tai.sakuma@gmail.com>
import os
import sys
import pytest
import unittest.mock as mock
has_jupyter_notebook = False
try:
import ipywidgets as widgets
from IPython.display import display
has_jupyter_notebook = True
except ImportError:
pass
from atpbar.presentation.create import create_pr... | 2,401 | 725 |
import sys
import time
import datetime
import asyncio
import pytz
from GridTrader import GridTrader
from db_connector import db_connector
class GridTrader_with_db(GridTrader):
def __init__(self, file='setting.json'):
super().__init__(file=file)
info=GridTrader.read_setting(file=file)
sel... | 4,652 | 1,759 |
from athena import gpu_ops as ad
import os
import sys
import yaml
import json
import multiprocessing
import signal
def main():
def start_scheduler(settings):
for key, value in settings.items():
os.environ[key] = str(value)
assert os.environ['DMLC_ROLE'] == "scheduler"
print('S... | 1,218 | 376 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: streamlit/proto/Balloons.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
fr... | 2,030 | 788 |
#! /usr/bin/env python
import functools
from . import gene
def BedIterator(handle, cls=gene.Gene):
for n, line in enumerate(handle):
if line.startswith('#'):
continue
if not len(line.strip()):
continue
fields = line.strip().split('\t')
if len(fields) != 12:... | 10,959 | 3,458 |
# [SublimeLinter @python:3]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
def center(window, master=None):
(master or window).eval("tk::PlaceWindow {} center".format(
window.winfo_toplevel()))
# (master or window).eval("tk::PlaceWindow {} c... | 388 | 128 |
# Copyright 2020 Uber Technologies, 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 ... | 8,183 | 2,318 |
import numpy as np
import networkx as nx
import sympy as sp
import matplotlib.pyplot as plt
import matplotlib as mpl
from sys import exit
from scipy.optimize import curve_fit
from scipy.integrate import odeint
class Model(nx.DiGraph):
"""
Base class for compartmental models.
See also:
---------
... | 14,188 | 4,093 |
import time
from library.frontend import Base
from library.utils.file import write_file
from library.utils.type_conv import random_str
class Manager_Inventory(Base):
def get_init_para(self, username):
self.inve_mongocollect = 'user.' + username + '.inventory'
self.group_mongocollect = 'user.' + u... | 27,133 | 8,379 |
from django.apps import AppConfig
class FratioConfig(AppConfig):
name = 'fratio'
| 87 | 29 |
import logging
import struct
import h5py
import numpy as np
from lib.constants import *
import os
# TODO: Logging does not work for multiprocessing processes on Windows
logger = logging.getLogger('root')
def read_positions(f):
control_events = []
i = 0
rollover_counter = 0
approaching_rollover = Fa... | 13,207 | 4,960 |
import copy
import dataclasses
import enum
import functools
import pathlib
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
from pysen import process_utils
from pysen.command import check_command_installed
from pysen.dist_version import get_version
from pysen.error_lines import parse_error_diffs
from... | 4,717 | 1,489 |
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ..._endpoint_base import EndpointBase
from .Directories import Directories
c... | 713 | 203 |
#python3
"""
Takes template and inserts javascript into template html
"""
import json
"""
Inputs:
plasmid_js: (str) filepath to file containing javascript string.
out_fp: (str) filepath to where we'll write the file out.
"""
def html_prepare(plasmid_js_fp, template_html_fp, out_fp, config_fp):
with open (... | 1,816 | 697 |
import numpy
from enstools.clustering import prepare
from enstools.clustering import cluster
from sklearn.cluster import KMeans
variables = []
ens_members = 20
n_variables = 2
def setup():
"""
create two variables for clustering
"""
for ivar in range(n_variables):
var = numpy.random.randn(en... | 1,985 | 640 |
/home/runner/.cache/pip/pool/ea/2d/a3/547d9f3eb895d5aa1c4d8fdd505bd62b5f2a6bece3a6721203e3a9177c | 96 | 72 |
""" matplotlib draw-functionalities"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from magpylib._src.defaults.defaults_classes import default_settings as Config
from magpylib._src.display.display_utility import draw_arrow_from_vertices
from magpylib._src.... | 17,349 | 5,339 |
#!/usr/bin/python3
from random import randint
# Programme déliverant un nombre entre min et max
min = int(input('Veuillez entrer la valeur minimale :\t'))
max = int(input('Veuillez entrer la valeur maximale :\t'))
print(randint(min,max)) | 248 | 92 |
# Copyright 2014 - Rackspace Hosting
#
# 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 ... | 3,493 | 1,125 |
# 笑脸识别示例( Haar Cascade + CNN 模型).
#
#翻译和注释:01Studio
import sensor, time, image, os, nn
#设置摄像头
sensor.reset() # Reset and initialize the sensor.
sensor.set_contrast(2)
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565
sensor.set_framesize(sensor.QVGA) # Set frame size ... | 1,091 | 563 |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmrotate.models.losses import (BCConvexGIoULoss, ConvexGIoULoss, GDLoss,
GDLoss_v1, KFLoss, KLDRepPointsLoss)
@pytest.mark.skipif(
not torch.cuda.is_available(), reason='requires CUDA support')
@py... | 4,093 | 1,418 |
from rest_auth import serializers
from rest_framework import serializers as rf_serializers
from neox_project.models import CustomUser
from post import models
class PostSerializer(serializers.JWTSerializer):
def create(self, validated_data):
pass
def update(self, instance, validated_data):
pas... | 1,580 | 436 |
import sys
try:
from ._version import __version__
except ImportError:
__version__ = "Unknown"
def test():
"""Run the mapshader test suite."""
import os
try:
import pytest
except ImportError:
import sys
sys.stderr.write("You need to install py.test to run tests.\n\n")
... | 1,170 | 450 |
from typing import TYPE_CHECKING
from apps.bot.dispatcher.consts import (
CONSTS,
ACTION_CHOICES,
STATE_CHOICES
)
from apps.bot.dispatcher.services import (
get_current_page,
render_movies,
get_last_movie_keyboard
)
from apps.bot.tmdb import TMDBWrapper
if TYPE_CHECKING:
from telegram impo... | 1,357 | 460 |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as scp_stats
import pandas as pd
import f_rate_t_by_type_functions as frtbt
N_trials = 15
# Decide which systems we are doing analysis for.
sys_dict = {}
sys_dict['all_mice'] = { 'cells_file': '../build/ll1.csv', 'f_1': '/data/mat... | 5,030 | 2,066 |
import os, sys, subprocess, tempfile, shutil, urllib2, stat
python = sys.executable
# homebrew-installed python can't install with --target. use system python instead.
if sys.platform == 'darwin':
python = '/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python'
def install_packages(requirements_file... | 4,248 | 1,412 |
import unittest
import logging
import math
from unittest.mock import MagicMock, call
from osgar.bus import Bus
from osgar.lib import quaternion
from subt.main import SubTChallenge
from subt.trace import distance3D
from subt import simulation
g_logger = logging.getLogger(__name__)
def entrance_reached(sim):
co... | 1,704 | 593 |
from selenium import webdriver
from selenium.webdriver import ActionChains
dr = webdriver.Chrome()
dr.get('https://yunpan.360.cn/')
account = dr.find_element_by_name("account")
account.clear()
account.send_keys('183xxxx')
password = dr.find_element_by_name("password")
password.clear()
password.send_keys('hxxxxxxx')
l... | 501 | 185 |
from picamera import PiCamera
import time
def captureImage():
camera = PiCamera()
camera.start_preview()
camera.rotation = 90
time.sleep(1)
camera.capture('static/images/test.jpg')
camera.stop_preview()
if __name__ == '__main__':
captureImage()
| 260 | 94 |
from fastapi import APIRouter
from src.api import graphql, rest
from src.core import get_settings
router = APIRouter()
router.include_router(
router = graphql.router,
prefix = get_settings().GRAPHQL_API,
tags = ['GraphQL']
)
router.include_router(
router = rest.router,
prefix = get_settings().R... | 329 | 106 |
# -*- coding: utf-8 -*-
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free ... | 4,012 | 1,591 |
__version__ = "0.0.10"
__name__ = "ctfcli"
| 43 | 24 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 5,666 | 1,687 |
import re
import tkinter as tk
from tkinter import ttk
from Components.db import Database
from Components.pop_up_menu import PopUpMenu
from Components.text_sync import TextSync
from Components.custom_text import *
class TextScrollCombo(tk.Frame):
def __init__(self, root, tab):
super().__init__(root, bg='... | 2,855 | 929 |
'''
@Author: TangZhiFeng
@Data: Do not edit
@LastEditors: TangZhiFeng
@LastEditTime: 2020-04-16 09:59:59
@Description:
'''
import numpy as np
import os
import pickle as pkl
import torch
import unittest # The test framework
from models import FastText
from utils_fasttext import sentance2ids, build_iterator
config = F... | 2,376 | 906 |
import Sofa
from Compliant import StructuralAPI
StructuralAPI.geometric_stiffness=2
def createScene(root):
# root node setup
root.createObject('RequiredPlugin', pluginName = 'Compliant')
root.createObject('VisualStyle', displayFlags="showBehavior" )
root.createObject('CompliantAttachButtonSettin... | 1,913 | 708 |
#!/usr/bin/env python
import re
import sys
import xmltodict
import json
import time
import collections
from pprint import pprint
def create_id(obj):
identifier = obj["@ID"]
name = obj["@Name"]
name = re.sub(r'[^a-zA-Z0-9_ \-]', "", name)
name = re.sub(r'[ \-]', "_", name)
name = name.lower()
... | 5,636 | 1,782 |
"""
Algorithms are from here: https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_sorts
"""
import math
from heapq import heappop, heappush
def quicksort(array: list) -> list:
"""
Quicksort Algorithm, implemented with the Explanation on: https://en.wikipedia.org/wiki/Quicksort
:param array: The arr... | 6,548 | 2,143 |
emailList = []
f = open('test.txt','r')
for ln in f:
if ' ' in ln:
continue
emailList.append(ln)
print 'emailList: ',emailList
| 138 | 61 |
def parse(data):
return [int(l.split()[-1]) for l in data.split("\n")]
def to10(x):
return (x - 1) % 10 + 1
def deterministic_die():
while True:
yield from range(1, 101)
def turn(die, start):
return to10(start + next(die) + next(die) + next(die))
def game(die, players, target):
score... | 690 | 252 |
import requests
import os
# translate CUIs into SNOMED Ids
def crosswalk(cui):
headers = {'Accept': 'application/xml'}
data = {"data": cui}
mapping = requests.post(f"{os.environ['METAMAP_WEB_URL']}crosswalk", data = data)
print(mapping.text)
return mapping.text.splitlines()
| 300 | 101 |
from Models import *
class DaoCategoria:
@classmethod
def salvar(cls, categoria):
with open('arquivos-txt/categoria.txt', 'a') as arq:
arq.writelines(categoria)
arq.writelines('\n')
@classmethod
def ler(cls):
with open('arquivos-txt/categoria.txt', 'r') as arq:
... | 4,469 | 1,655 |
# -*- coding: utf-8 -*-
"""GIS data previewer"""
from __future__ import absolute_import, print_function
from flask import render_template
from ..proxies import current_previewer
import zipfile
import cchardet as chardet
from six import binary_type
previewable_extensions = ['zip']
def can_preview(file):
"""Chec... | 1,221 | 395 |
from dataclasses import dataclass
from enum import Enum
TIMEOUT = 3
CMD_END = 'end'
BUFSIZE = 4096
class TypeEnum(Enum):
HOST = 'Host'
SERVER = 'Server'
@dataclass
class RegisterMsg:
type: TypeEnum
name: str
@dataclass
class RegisterResultMsg:
success: bool
full_domain: str = None
error_... | 485 | 169 |
"""The version information of the kanjidict2.xml file."""
from peewee import CharField, ForeignKeyField
from models.base import BaseModel
from models.kanji_reference_index import KanjiReferenceIndex
class KanjiReferenceDaikanwajiten(BaseModel):
"""Kanji"""
volume = CharField(max_length=32)
page = CharFi... | 561 | 176 |
from .main import all
| 23 | 8 |
import numpy as np
import json
from tqdm import tqdm
def process(temp):
temp = temp.split('(')[1]
temp = temp.split(')')[0]
_id = temp.split(',')[0]
_start = temp.split(',')[1]
_len = temp.split(',')[2]
# print(_id)
return int(_id),int(_start),int(_len)
def genDict():
dic = {}
file_o... | 4,153 | 1,532 |
from pwn import *
r = process("./playground.c")
libc = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")
# libc = ELF("/lib/x86_64-linux-gnu/libc-2.23.so")
def malloc(num):
r.recvuntil(">")
r.sendline("1")
r.recvuntil(": ")
r.sendline(str(num))
def fill_chunk(num):
r.recvuntil(">")
r.... | 871 | 424 |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
view = UnwrapElement(IN[0])
Tr... | 550 | 166 |
import os
import numpy as np
# collecting all csv files from forwarded directory
def collect_csv_data_collection_from_directory(path):
import pandas as pd
import os
data_collection = []
for csv_name in os.listdir(path):
csv_path = os.path.join(path, csv_name)
data_collection.append(p... | 4,533 | 1,446 |
from time import time
import threading
from functools import partial
from django.utils.functional import cached_property
from django.core.cache import cache
try:
import asyncio
except (ImportError, SyntaxError):
asyncio = None
__all__ = [
"cached_property",
"cached_property_with_ttl",
"memoize",... | 6,432 | 1,916 |
import datetime
def add_gigasecond(moment):
return moment + datetime.timedelta(0, 10**9)
| 94 | 36 |
import logging
from itertools import cycle
from typing import Dict, List, Optional, Tuple, Union
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.ticker import ScalarFormatter
from sci... | 22,179 | 6,364 |
# access Train.py in parent folder and set relative folder to parent folder for data saving
import os
import sys
os.chdir("..")
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from Train import *
"""
The purpose of this experiment is to lower the val constabt
for multiply to see if it can compromise validity to l... | 4,455 | 1,849 |
"""
...
"""
import numpy as np
import matplotlib.pyplot as plt
from utility import parameters
from utility import perfprof
algorithms = ['regLBFGS', 'armijoLBFGS', 'wolfeLBFGS']
# Read all the data in the ugliest fashion possible
nfM = np.array([np.loadtxt(f"results/{a}_solve.csv", delimiter=',')[:, 0] for a in alg... | 2,638 | 1,154 |
"""Train and evaluate Tool
The script utilizes the 2 main inputs which are the config.yml and the CLI params.
With the combination of these configuration 2 running branches are possible:
- Training workflow:
- Load the dataset
- Create a model with the provided configuration
- Train then save the model
... | 5,315 | 1,611 |
import logging
from collections import Iterable
from typing import Optional, Union
from tqdm import tqdm
from brainscore.metrics import Score
from brainscore.model_interface import BrainModel
from brainscore.utils import fullname
from model_tools.activations.pca import LayerPCA
from model_tools.brain_transformation i... | 5,959 | 1,633 |
from django import forms
from .models import Profile,Image,Comment
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
username=forms.CharField(max_length=30, required=False, help_text='Optional.')
first_name = forms.CharField(... | 1,504 | 438 |
# encoding: utf-8
import time
import pytest
from webob import Request
from web.core import Application
from web.core.context import Context
from web.ext.analytics import AnalyticsExtension
def endpoint(context):
time.sleep(0.1)
return "Hi."
sample = Application(endpoint, extensions=[AnalyticsExtension()])
def... | 920 | 317 |
from rest_framework.response import Response
from rest_framework.views import APIView
class UploadView(APIView):
def post(self, request):
try:
print(request.FILES)
return Response(
{'code': 200, 'msg': 'Upload Successfully!', 'data': 'https://api.ahriknow.com/image?... | 441 | 132 |
"""
Discord API Wrapper Extension
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A basic application command extension for discord.py.
:copyright: (c) 2022-present jnsougata
:license: MIT, see LICENSE for more details.
"""
from .bot import Bot
from .cog import Cog
from .errors import *
from .app import Overwrite
from .context impo... | 509 | 154 |
import sys
from pyparsing import Word, CharsNotIn, Optional, OneOrMore, ZeroOrMore, Group, ParseException, Literal, replaceWith
import pyparsing
help(pyparsing)
class Argument:
def __init__(self, s, loc, toks):
self.str = toks[1]
def __repr__(self):
return "[%s]" % self.str
def argfun(s, loc, ... | 2,263 | 843 |
#zzw 20180714 support str encode
gFlagDic = {'strEncode' : 'ascii'} | 68 | 34 |
# -*- coding: utf-8 *-*
"""PyMongo_-flavored package for accessing to MongoLab databases via
`MongoLabClient`.
.. _PyMongo: http://api.mongodb.org/python/current/"""
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
OFF = 0
"""No database profiling."""
SLOW_ONLY = 1
"""Only pro... | 737 | 264 |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 10:03:35 2019
@author: hamil
"""
import numpy as np
import matplotlib.pyplot as plt
def up_harmonic(value_n):
H_up = 0.0
summ_array1 = []
new_x = value_n + 1
x_array1 = np.arange(1,new_x)
for each_value in x_array1:
numm1 = 1/each_value
... | 2,065 | 775 |
"""ClipTools clipboard manager and text processing tools
with a lines based GUI interface
Data loader, search for available personal data.
WARNING, python file will be executed!
When making python personal file, take care not allow uncontrolled changes!
yaml is safer from this point of view.
Note: logging is not par... | 2,458 | 727 |
## -*- coding: utf-8 -*-
from joern.all import JoernSteps
from igraph import *
from .general_op import *
import pickle
from py2neo.packages.httpstream import http
http.socket_timeout = 9999
def get_all_use_bydefnode(db, node_id):
query_str = "g.v(%d).in('USE')" % node_id
results = db.runGremlinQuery(query_str)... | 25,660 | 7,981 |
from typing import Collection
from cal_tools.struct.face import CalFace
from cal_tools.struct.morph import CalMorph
from cal_tools.struct.vertex import CalVertex
class CalSubmesh:
def __init__(self, material: int, vertices: Collection[CalVertex], faces: Collection[CalFace],
morphs: Collection[Cal... | 476 | 131 |
#!/usr/bin/env python3
#
# Consolidate all the raw Blogger JSON files into a single, simplified JSON file.
#
from collections import OrderedDict
import html
import io
import json
import sys
import lxml.etree as ET
import lxml.html
import re
import feeds
import util
posts = feeds.json_post_entries_list()
output = []... | 3,818 | 1,390 |
#! /usr/bin/python3
import nltk
import pdb
import pickle
import pandas as pd
import numpy as np
import json
stemmer = nltk.stem.porter.PorterStemmer()
stop_words = set(nltk.corpus.stopwords.words('english'))
def is_alphanumeric(character):
to_ord = ord(character)
is_alpha = (to_ord >= ord('A') and to_ord <= o... | 2,619 | 898 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import threading
import time
from typing import Callable
import pytest
from mock import MagicMock
import intelliflow.api_ext as flow
from intelliflow.api_ext import *
from intelliflow.core.application.applicati... | 22,312 | 6,460 |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 26 14:58:57 2019
@author: Administrator
MCD12 LandCover Types:
DBF == 4:DBF,5:MF
EBF == 2:EBF
NF == 1:ENF,3:DNF
CRO == 12: CRO, 14: CRO&NV
GRA == 10: GRA
SHR == 6:CSH, 7:OSH
SAV == 8:WSA, 9:SAV
"""
import numpy as np
import matplotlib.pyplot as plt
imp... | 6,988 | 3,123 |
# -*- coding: utf-8 -*-
"""
Created on 10/02/2014
@author: Dani
"""
import re
import codecs
from reconciler.entities.normalized_country import NormalizedCountry
from reconciler.exceptions.unknown_country_error import UnknownCountryError
class CountryNormalizer(object):
"""
In this class we'll implement th... | 6,260 | 1,987 |
"""
Welcome to The TangleExplorer !
"""
"""
0. The first time you run the TNG server, you have to dowload and compile The Tangle
Follow the instructions in: https://kaalam.github.io/jazz_reference/reference_docker_tangle_server.html
"""
"""
I M P O R T A N T N O T E : This is just a piece of software to help ... | 1,949 | 695 |
from xdsl.dialects.builtin import *
from xdsl.dialects.std import *
from xdsl.dialects.arith import *
from xdsl.printer import Printer
from xdsl.dialects.affine import *
def get_example_affine_program(ctx: MLContext, builtin: Builtin, std: Std,
affine: Affine) -> Operation:
def aff... | 1,573 | 565 |
# Copyright 2021 The Commplax 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... | 1,632 | 539 |
#coding=utf-8
from flask import render_template, flash, redirect, url_for, g, request
from app import app, lm, db
from forms import LoginForm, RegisterForm
from flask.ext.login import login_user, logout_user, current_user, login_required
from models import User
import re
import sys
reload(sys)
sys.setdefaultencoding('... | 2,862 | 1,073 |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2021 Amano Team
import os
from pyrogram import Client
from userlixo.config import langs
# Getting the language to use
@Client.on_callback_query(group=-2)
async def deflang(c, cq):
cq._lang = langs.get_language(os.getenv("LANGUAGE"))
| 294 | 118 |
# Copyright (c) 2019 Stephen Bunn <stephen@bunn.io>
# ISC License <https://choosealicense.com/licenses/isc>
from collections import OrderedDict
from ._common import BaseHandler
class YAMLHandler(BaseHandler):
""" The YAML serialization handler.
"""
name = "yaml"
packages = ("yaml",)
options = {... | 2,126 | 639 |
import torch
import torch.nn as nn
from torch.utils.data import Dataset
class MetricDataset(Dataset):
def __init__(self, data):
super(MetricDataset, self).__init__()
self.data = data[0].squeeze()
self.targets = data[1].squeeze()
def __getitem__(self, index):
return (
... | 1,069 | 379 |
# Import app code
from app.main import app # noqa
# Set up global variables
from app.core import data # noqa
# Set up Config Environments
from app.core import config # noqa
# Set up flask db session
from app.core.db.session import db_session # noqa
# Load dafault data on DB
from app.core.db.init_db import load_de... | 596 | 202 |
from .run import parse
from .OS_parser import *
| 48 | 15 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def balanced(node):
if not node:
return True, 0
... | 567 | 176 |
# -*- coding: UTF-8 -*-
from yelp.obj.business import Business
from yelp.obj.business_response import BusinessResponse
def test_make_business_response():
biz_response = BusinessResponse({})
assert type(biz_response.business) is Business
| 247 | 79 |
"""
Constants for SerialReceiver
:author: Angelo Cutaia
:copyright: Copyright 2021, LINKS Foundation
:version: 1.0.0
..
Copyright 2021 LINKS Foundation
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 co... | 6,177 | 4,235 |
img = 'b'AAABAAEAgIAAAAEAIAAoCAEAFgAAACgAAACAAAAAAAEAAAEAIAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... | 90,207 | 72,508 |
"""
Implementation of the hierarchical poisson glm model, with a precinct-specific
term, an ethnicity specific term, and an offset term.
The data are tuples of (ethnicity, precinct, num_stops, total_arrests), where
the count variables num_stops and total_arrests refer to the number of stops
and total arrests of an eth... | 4,704 | 1,834 |