text stringlengths 8 6.05M |
|---|
def read_V_table(fileName):
table = []
f = open("wilxdata/" + fileName)
i = 0
for line in f:
tableRow = []
splittedString = line.split(";")
for s in splittedString:
readyToConvert = s.replace("\n", "").replace(" ", "")
if(readyToConvert != ""):
... |
"""empty message
Revision ID: bcf2045c4e06
Revises: fd9dff883afd
Create Date: 2018-10-28 10:47:16.732679
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bcf2045c4e06'
down_revision = 'fd9dff883afd'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from django.contrib import admin
from .models import *
# добавить действие в окно выполнить действие
def make_payed(modeladmin,request,queryset):
queryset.update (status=3)
make_payed.short_description = "Пометить как оплаченные"
def make_do(modeladmin,request,queryset):
queryset.update (status=2)
make_do.sho... |
import numpy as np
import matplotlib.pyplot as plt
import math
def tail_prob(chi,t):
tail_Pr = []
for i in range(0,len(t)):
tail_Pr.append(chi[chi>(t[i]+np.mean(chi))].shape[0]/(1.0*len(chi)))#smaple mean = 0
return tail_Pr
n=3
k = 10000
t = np.linspace(0,50,1e4)
data = np.zeros((k,))
#################... |
# Generated by Django 2.2.5 on 2019-11-29 14:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('trips', '0007_auto_20191128_2103'),
]
operations = [
migrations.RenameField(
model_name='trip',
old_name='hotels',
... |
#!/usr/bin/python
#Stop gripper during moving.
from dxl_util import *
from _config import *
import time
import math
import numpy as np
#Setup the device
dxl= TDynamixel1(DXL_TYPE,dev=DEV)
dxl.Id= DXL_ID
dxl.Baudrate= BAUDRATE
dxl.Setup()
dxl.EnableTorque()
#Move to initial position
p_start= 2100
dxl.MoveTo(p_start)
... |
import random
import tensorflow as tf
import numpy as np
import pandas as pd
def read_dataset(filename, lines):
train_test_ratio = 0.8
df = pd.read_csv(filename, nrows=lines)
x_matrix = df[df.columns[0]].values
x_vals = encode_words(x_matrix)
train_x = x_vals[:int(lines * train_test_ratio)]
t... |
from setuptools import setup
setup(name='ditk',
version='alpha',
description='CSCI 548 Project- Data Integration Toolkit',
url='https://github.com/HaozheGuAsh/CSCI548-Relation-Extraction',
author=' ',
license='MIT',
packages=['ditk'],
zip_safe=False)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
training_percent = 0.7
testing_percent = 1 - training_percent
previous_data_points = 3
currency = ""
currency_index = 0
data_set_length = 0
training_set_length = 0
testing_set_length = 0
p = 0
d = 0
q = 0
epochs = 50
batch_size = 2
|
import tensorflow as tf
from tensorflow.keras.layers import Input, SimpleRNN, LSTM, GRU, Dense, Activation
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras import backend as K
def naive_RNNs(init, input_shape, mode='singal-layer'):
# input_shape: [batch, timesteps, features]
inpu... |
from functools import wraps
from natsort import natsorted, ns
import graphene
class OrderedList(graphene.List):
def __init__(self, of_type, **kwargs):
additional_kwargs = {
'order_direction': graphene.String(),
}
if of_type != graphene.String:
additional_kwargs['or... |
from typing import Iterator
def reduction(x):
# type: (int) -> Iterator[int]
"""
reduction sequence from n to 1 by either adding 1, subtracting 1, or dividing by 2
proof:
n | n mod 4 | path
--|---------|----------------------
1 | 1 | 1
2 | 2 | 2 -> 1
3 | 3 | 3 ->... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009 Francesco Piccinno
#
# Author: Francesco Piccinno <stack.box@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eith... |
def nhuman(Y):
x = Y
print(x)
nhuman(10)
|
class SegmentTree:
def build_tree_hint(self):
message = """
Build Segment Tree
------------------------------------
Purpose : Building a Segment tree for the given array and query
Method : Recursion
Time Complexity : Worst Case - O(n)
... |
"""
Api key queries
"""
from typing import Generator, List, Optional, Union
import warnings
from typeguard import typechecked
from ...helpers import Compatible, format_result, fragment_builder
from .queries import gql_api_keys, GQL_API_KEYS_COUNT
from ...types import ApiKey as ApiKeyType
from ...utils import row_gen... |
import json
# client = gmail_client.get_gmail_client(config.CLIENT_SECRET_FILE_PATH, config.SCOPES, secret.APPLICATION_NAME)
# # # ids = gmail_handling.get_unread_email_ids(client)
# # # messages = [client.users().messages().get(userId='me', id=i).execute() for i in ids]
# # # j = json.dumps(messages)
# # # with open(... |
from python_framework import Enum, EnumItem
@Enum(associateReturnsTo='number')
class WeekDayEnumeration :
MONDAY = EnumItem(number=0, short='mon')
TUESDAY = EnumItem(number=1, short='tue')
WEDNESDAY = EnumItem(number=2, short='wed')
THURSDAY = EnumItem(number=3, short='thu')
FRIDAY = EnumItem(numbe... |
import os
from unittest.mock import patch
import numpy as np
import pandas as pd
from numpy.testing import assert_allclose, assert_almost_equal
from autumn.core import db
from autumn.calibration import Calibration, CalibrationMode
from autumn.calibration.utils import (
sample_starting_params_from_lhs,
specify... |
from django.conf.urls import url
from api import views
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
url(r'^department/$', views.DepartmentAPIClassView.departmentApi),
url(r'^department/([0-9]+)$', views... |
import os
import glob
import time
os.system('modprobe w1-gpio') # turns on GPIO module
os.system('modprobe w1-therm') # Turns on temperature module
# Finds Device File that holds Temperature Data
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'... |
# -*- coding: utf-8 -*-
from xml.etree import ElementTree
class XMLParser():
'''
This class is responsable to extract informations from a xml file representing a data base structure
with some data (optional)
@filename xml file name
'''
def __init__(self, fileName):
self.file = fileName
self.databaseName... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pygame
pygame.init()
screen = pygame.display.set_mode((550, 550))
pygame.display.set_caption('Tic-Tac-Toe')
first = pygame.draw.rect(screen, (255, 255, 255), (25, 25, 150, 150))
second = pygame.draw.rect(screen, (255, 255, 255), (200, 25, 150,... |
from queue import Queue
from typing import List, Any
from networkx.algorithms import bipartite, distance_measures, approximation, cycles
from tabulate import tabulate
import networkx as nx
import scipy.linalg as la
from matplotlib import pyplot as plt
import networkx.linalg.spectrum as spec
import numpy as np
from p... |
import openmc
from numpy import pi
# Constants
T_r1 = 2135e-5
T_r2 = 3135e-5
T_r3 = 3485e-5
T_r4 = 3835e-5
T_r5 = 4235e-5
T_pitch = 0.09266
uoc_9 = openmc.Material()
uoc_9.set_density("g/cc", 11)
uoc_9.add_nuclide("U235", 2.27325e-3)
uoc_9.add_nuclide("U238", 2.269476e-2)
uoc_9.add_nuclide("O16", 3.561871e-2)
uoc_9.a... |
from distutils.core import setup
setup(name='modulepickle',
version='0.3',
description='Dynamic module pickler',
author='Andy Jones',
author_email='andyjones.ed@gmail.com',
url='https://github.com/andyljones/modulepickle',
packages=['modulepickle'])
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:io
Author:jason
date:2018/3/15
-------------------------------------------------
Change Activity:2018/3/15:
-------------------------------------------------
"""
import codecs
import os
class IOUtil():... |
from django.db import models
import datetime
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.CharField(max_length=2000000)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
now = timezone.now()... |
'''
Created on Oct 6, 2011
@author: Rob Waaser
'''
import ctypes
import os
if __name__ == '__main__':
print "Running using cdll.libTestDLL...."
kernel32 = ctypes.windll.kernel32
print "Running using LoadLibrary"
name = "libCrash.dll"
path = os.path.join(os.getcwd(), name)
... |
from openerp.osv import fields, osv
class sale_order(osv.osv):
_inherit = "sale.order"
_columns = {
'is_foc': fields.boolean('Is a FOC?', default=False, help="Check if the sale order is FOC "),
}
# class wizard_data_inherit(osv.osv):
# _inherit = "account.invoice"
#
# # _columns = {
# ... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 02:04:57 2020
@author: filiz.aksoy
"""
def factors(a):
factors = []
if a%2 == 0 :
factors.append(2)
for i in range(3,a//2,2):
if(a%i == 0):
factors.append(i)
return factors
|
#Program to find the greatest of 3 given numbers
a = 14
b = 10
c = 3
print "Let's find the greatest of these 3 numbers"
if(a>b):
if(c>a):
print 'c is greatest'
else:
if(a==c):
print 'a and c is greatest'
else:
print 'a is greatest'
else:
if(c>b):
p... |
from bs4 import BeautifulSoup
import requests
import sys
from furl import furl
URL = 'https://www.google.com/search'
def getSoup(movie):
response = requests.get(URL, params={ 'q': '{0} movie imdb'.format(movie) })
html = response.content
soup = BeautifulSoup(html, 'html5lib')
return soup
def getMovie... |
from bs4 import BeautifulSoup
import requests
import pandas as pd
import json
from requests.compat import urljoin
from datetime import datetime
import re
import asyncio
from asyncio import AbstractEventLoop
import aiohttp
from colorama import Fore
from collections import defaultdict
import bs4
import math
... |
#coding=utf-8
from google.appengine.ext import db
class GroupType(db.Model):
title=db.StringProperty()
group_type_id=db.IntegerProperty()
description=db.StringProperty()
class Group(db.Model):
group_gid=db.StringProperty()
group_id=db.IntegerProperty()
title=db.Str... |
# @Title: 二叉搜索树节点最小距离 (Minimum Distance Between BST Nodes)
# @Author: 2464512446@qq.com
# @Date: 2020-11-27 16:15:35
# @Runtime: 40 ms
# @Memory: 13.4 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c... |
#!/usr/bin/env python
# Standard imports
import argparse
import os
# TopEFT imports
from TopEFT.Generation.Configuration import Configuration
from TopEFT.Generation.Process import Process
from TopEFT.Tools.u_float import u_float
# Logging
import TopEFT.Tools.logger as logger
#find all processes
proces... |
# v4
# use class decorator
# works ok
from inspect import Parameter, Signature
def make_signature(names):
return Signature(Parameter(name, Parameter.POSITIONAL_OR_KEYWORD) for name in names)
def sig_deco(*names):
def wrapper(cls):
# NOTICE! cls here is Stock cls object
cls.__signature__ = m... |
a = 7
for i in ( 2, a-1 ):
if a % i == 0 :
print " The given number ", a ," is not prime"
else :
print " The given number ", a ,"is prime"
|
class InvalidCardDetailsError(Exception):
""" raise when Card details are not valid"""
class PaymentFailed(Exception):
"""raise when transaction is failed """
class PaymentGatewayNotAvailableError(Exception):
"""raise when payment gateway is not available"""
class InvalidAmountError(Exception):
""... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exceptions related to `chzip`"""
class DownloadException(Exception):
"""Exception raised when a problem when downloading a file occured."""
class UpgradeException(Exception):
"""Exception raised to signal a failure in the upgrade process."""
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 11:40:52 2018
@author: pmarella
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("Testrail_data.csv")
test_without_defect = data.loc[data["TC-Defect"].isnull()]
test_with_defect = data.loc[data["TC-Defect"].notna()]
test_f... |
import models.model as model
def main():
"""
Count the number of earthquakes in the regions of: EastJapan, Kanto, Kansai, Tohoku with mag>3.0 or mag>5.0
"""
year = 2006
for i in range(5):
print(year + i)
a = model.loadModelFromFile(
"../Zona/3.0EastJapanreal" + str(yea... |
from django.shortcuts import render
# Create your views here.
from list_strings.forms import ListStringsForm
from list_strings.utils import longest_substring
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
def home(request):
res = ''
if ... |
from pwn import *
import sys
#import kmpwn
sys.path.append('/home/vagrant/kmpwn')
from kmpwn import *
#fsb(width, offset, data, padding, roop)
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./mousetrap"
HOST = "cha.hackpack.club"
PORT = 41719
if len(sys.argv) > 1 and sys.argv[1] ... |
# step 步驟
# 建立 interface 介面
from abc import ABC, abstractmethod # Abstract Base Class 抽象類別
class Step(ABC): # Base class
def __init__(self):
pass
@abstractmethod
def process(self, transporter, inputs, utils): # 執行
pass
class StepException(Exception): # 例外捕捉
pass
|
from math import tanh
from mlpnn.Abstracts.Function import Function
class HyperbolicTangent(Function):
def function(self):
def inner(x, beta):
return tanh(beta * x)
return inner
def derivative(self):
def inner(x):
return 1 - x * x
return inner
|
from datetime import date
from django.contrib.auth.models import User
from django.test import TestCase, Client
from planner.models import Garden, Vegetable, Bed, CultivatedArea, ForthcomingOperation, COWithDate, History
class AlertsViewsTests(TestCase):
def setUp(self):
self.client = Client()
s... |
"""
E160_gui.py
"""
import sys
from E160_config import CONFIG_DELTA_T
import time
from E160_environment import *
from E160_graphics import *
def main():
# instantiate robot navigation classes
environment = E160_environment()
graphics = E160_graphics(environment)
# set time step size in s... |
import math
class Quaternion:
def __init__(self, axis=None, angle=None, position=None, quat=None):
if axis and angle:
theta = angle / 2.0
self.i = [axis[0] * math.sin(theta), axis[1] * math.sin(theta), axis[2] * math.sin(theta)]
self.r = math.cos(theta)
self... |
# coding: utf-8
import random
import string
import hashlib
import base64
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.db import models
class UserAuthCode(object):
def __init__(self, secret, salt_len=8, hash=hashl... |
from onegov.core.security import Personal
from onegov.feriennet import FeriennetApp
from onegov.feriennet.forms import UserProfileForm
from onegov.org.models import Organisation
from onegov.org.views.userprofile import handle_user_profile
@FeriennetApp.form(
model=Organisation, name='userprofile', template='userp... |
import unittest
from tree_utils import NodeWithParent
def suscessor(node):
"""Return the successor of a node in a bst.
case 1: node has right subtree, return the leftmost node in the subtree;
case 2: node has no right subtree, trace back its parent until it's not
a right branch, return th... |
# coding=utf-8
import os
import sys
import time
from datetime import datetime, timedelta
import django
prjPath = r'E:\GitHub\myapp\net\website\django\mysite1'
dataPath = r'D:\data'
#from net.website.django.mysite1.myapp.rules import Submarket
sys.path.append( prjPath )
django.setup()
import sqlite3 as db
#conn = d... |
num=int(input("enter your no:"))
Num=int(input("enter your no:"))
if(Num>num):
print(Num,"is maximum no")
else:
print("is not the maximum no.") |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenElanz
# Copyright (C) 2012-2013 Elanz Centre (<http://www.openelanz.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gene... |
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings: return 0
n = len(ratings)
c = [1 for _ in range(n)]
sum = 0
for i in range(1,n):
if ratings[i]>ratings[i-1]:
... |
import re
REGEX = re.compile(r'(\d+) positions|position (\d+)')
class Disc:
def __init__(self, length, initial):
self.positions = [0] + [1] * (length - 1)
self.position = initial
def open(self, time):
return self.positions[(self.position + time) % len(self.positions)] == 0
def solve(... |
import datetime
from flask import request
from flask_jwt_extended import create_access_token
from api.models.user import User
from flask_restful import Resource
from mongoengine.errors import FieldDoesNotExist, ValidationError, DoesNotExist, NotUniqueError
from .errors import InternalServerError, EmailAlreadyExistsErro... |
# IMPORTS
import pandas as pd
from scipy.stats.stats import pearsonr
import zipfile
# EXTRA FUNCTIONS
# Function to iterate through columns
def getcolumn(matrix, col):
columna = []
for row in matrix:
columna.append(row[col])
return columna
# PERSONALITY DATA
# Obtaining a list of t... |
# both strings and listst are sequences of items
c = ["H", 4, "Hello"]
print(c)
c.append(4)
print(c)
c.remove("H")
print(c)
c.remove(4) # removes first occurence
print(c)
print(dir(c))
c.remove(c[2]) # remove third element
# "" - empty string
# [] - empty list
|
from csv import reader
import json
import os
from dotenv import load_dotenv
from collections import defaultdict
load_dotenv()
def csv_to_item_table(file_name1, file_name2, file_name3):
data = []
with open(file_name1, 'r') as csv_file:
csv_data = list(reader(csv_file))
for row in csv_data[1:]:
... |
# Generated by Django 4.0.5 on 2022-06-25 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_alter_live_data'),
]
operations = [
migrations.AddField(
model_name='game',
name='TOCGameT1L1',
... |
mainString = input("Enter a String with letter 'a' : ")
brokenString = mainString.split("a")
print(brokenString[0] + "a")
i = 1
while i < len(brokenString):
print(brokenString[i])
i = i + 1 |
# Write a function that outputs a word frequency dictionary
# format word: count, string:int
# should accept any text as an argument
def word_frequency(strg):
word_count_dict = dict()
char_count_dict = dict()
for word in strg.split():
word_count_dict[word] = (word_count_dict[word] + 1) if (word_count_dict.ge... |
list1 = [30, 50, 42, 63, 52]
for i in range(len(list1)):
if list1[i] % 10 == 0:
print(list1[i]) |
from flask import Flask, redirect, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, URL
app = Flask(__name__)
app.config['SQLALCHE... |
"""Controller for speaking with teacher"""
from models import teacher
def talk_about_english():
"""Function to speak with teacher"""
english_teacher = teacher.EnglishTeacher()
english_teacher.hello()
english_teacher.ask_user_todo()
english_teacher.thank_you()
|
import unittest
from dataclasses import dataclass
from typing import List
from rdflib import RDFS, RDF, XSD, Namespace, OWL
from funowl import Annotation, AnnotationPropertyDomain, AnnotationPropertyRange, AnnotationAssertion, \
SubAnnotationPropertyOf
from funowl.annotations import Annotatable
from funowl.base.l... |
# 280. Wiggle Sort
#
# Given an unsorted array nums,
#
# reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
#
# For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
class Solution(object):
def wiggleSort(self, nums):
prev, incr = nums[0], True
... |
import os
from conans.errors import NotFoundException
from conans.model.manifest import discarded_file
from conans.model.ref import PackageReference
from conans.util.files import load
def get_path(client_cache, conan_ref, package_id, path):
"""
:param client_cache: Conan's client cache
:param conan_ref: ... |
#!~/anaconda3/bin/python3.6
# encoding: utf-8
"""
@version: 0.0.1
@author: Yongbo Wang
@contact: yongbowin@outlook.com
@file: ToxicClassification - data-info.py
@time: 8/31/18 11:06 PM
@description:
"""
import pandas as pd
import matplotlib.pyplot as plt
class DataStatistics:
def __init__(self):
self.tr... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 14:23:03 2020
@author: zirklej
"""
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import linregress
from random import gauss
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
... |
'''Write a Python function to find the Max of three numbers. '''
def max_two( num1, num2 ):
if num1 > num2:
return num1
return num2
def max_three( num1, num2, num3):
return max_two( num1, max_two( num2, num3 ) )
print(max_three(1, 2, 3))
|
# Generated by Django 3.2.5 on 2021-07-28 04:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user', '0009_alter_city_options'),
]
operations = [
migrations.CreateModel(
name='Ubicacion',
... |
head = ":autocmd FileType python :iabbrev <leader>self "
import sys
try:
fileName = sys.argv[1]
except:
print "please give the file name"
raise Exception
fh = open(fileName, 'r')
lines = fh.readlines()
lines =[x.rstrip() for x in lines]
fh.close()
for i in lines:
head += i
head += "<enter><... |
#question 2 - write a regular expression to extract a. email id b. domain name c. time
import re
email='From abc.xyz@pqr.com Mon Dec 29 01:12:15 2016'
#Regex
regex = re.search(r'From (.*)@(.*)\.com (.*)', email, re.M|re.I)
print 'Email ID : '+regex.group(1)+'@'+regex.group(2)+'.com'
print 'Domain Name : ',regex.gro... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 09:17:12 2018
Versión sin cálculo de reparto
@author: Bruno
"""
import os
import platform
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import qrc_resources
import random
from Funciones_algoritmo_de_calculo import *
impor... |
"""
------------------------------------------------------------------------
URL Map
------------------------------------------------------------------------
Author: bb $kreetz
Email: bbskreets@protonmail.com
__updated__ = "2020-04-12"
------------------------------------------------------------------------
"""
from S... |
from typing import Tuple
import torch
import torch.nn as nn
import torchvision
from omegaconf import DictConfig
from PIL import Image
from src.model import net as Net
from src.utils import load_class
def build_model(model_conf: DictConfig):
return load_class(module=Net, name=model_conf.type, args={"model_config... |
# coding: utf-8
# In[3]:
import urllib2, time, random, re
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd
import requests
# In[157]:
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
... |
# Script to combine all the neighborhoods
import numpy as np
import networkx as nx
N = pow(10,6) + pow(10,4)
every_ngbd = [None]*N
for x in range(0,30):
print(x)
chunk_ngbd = np.load('/home/gotmare/network_scan_estimators/mar28_new/N_inactive_10^4/neighborhood_data/ngbd_part_'
... |
import csv
class ChosenOne:
def __init__(self, p):
file = open(p, 'r')
self.month = csv.DictReader(file)
self.sd = {}
def get_my_row(self):
for row in self.month:
self.sd = dict(row)
if self.sd['Nazwisko'] == 'Kowalski':
bre... |
# from .contenttype import *
from .locale import *
from .company import *
from .auth import *
from .partner import *
from .bank import *
from .module import *
from .sequence import *
from .config import *
from .decimal import *
from .http import *
from .copy import *
|
import numpy
import math
|
# Reading TSV file in pandas
df= pd.read_csv('bestofrt.tsv', sep='\t')
# Webscraping
# Step 1: getting webpage's data
## stored in html (hypertext markup language) format
# downloading html programmatically
import requests
url = 'url'
response = requests.get(url)
# save html to file
with open("... .html", mode='wb')... |
from .data_source import DataSource
from .layout import AnalysisLayout
from .visual_analysis import VisualAnalysis
# Import Widgets so that they get registered
import pandas_visual_analysis.widgets
import plotly.io as pio
pio.templates.default = "plotly_white"
|
import numpy as np
import matplotlib.pyplot as plt
# SeLU(scaled exponential linear unit)
def selu(x):
alpha = 1.67326324
scale = 1.05070098
if not scale > 1:
raise ValueError
if x > 0:
return scale * x
else :
return scale * alpha * (np.exp(x) - 1)
x = np.arange(-5, 5, 0.1... |
#
# Copyright 2017 Bleemeo
#
# bleemeo.com an infrastructure monitoring solution in the Cloud
#
# 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/... |
import requests
class MiningPoolHub:
def balance(self, config, coins):
response = requests.get('https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=' + config['key'])
if response.status_code == 200:
data = response.json()
balances = data['getuseral... |
# Generated by Django 3.2 on 2021-05-16 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('army_app', '0003_auto_20210515_2217'),
]
operations = [
migrations.AddField(
model_name='gun',
name='active_range',
... |
#!/usr/bin/python3
from tkinter import *
class application(Frame):
def __init__(self,master):
super().__init__(master)
self.master=master
self.pack()
self.createWidget()
def createWidget(self):
self.canvas = Canvas(
self,width=200,height=200,bg='white')
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 15:11:45 2019
@author: 于福波
"""
from keras import Sequential
from keras.layers.core import Dense,Activation,Dropout
from keras import optimizers
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.p... |
#!/usr/bin/python
# -*- coding=utf-8 -*-
# 截图ScreenShot.py
import ctypes
import win32gui
from PIL import ImageGrab
import win32con
from ctypes import wintypes
import ctypes,os,time
def screenShot():
# 获取窗口句柄
hwnd = win32gui.FindWindow("WeChatMainWndForPC", "微信") #此处针对特定程序进行修改
if not hwnd:
... |
a=int(input('Prima varsta'))
b=int(input('A doua varsta'))
c=int(input('A treia varsta'))
if(a>=18) and (a<=60):
print(a)
if(b>=18) and (b<=60):
print(b)
if(c>=18) and (c<=60):
print(c) |
from PyQt5.QtWidgets import QMainWindow, QFileDialog
from GUI.ui_SurveyMod import ui_SurveyMod
from SurveyMod import SurveyMod
import json
class GUISurveyMod(QMainWindow):
log = None
survey = None
def __init__(self):
super().__init__()
self.ui = ui_SurveyMod()
self.ui.setupUi(sel... |
import numpy as np
import random
import copy
class Dataset(object):
def __init__(self,inputfile):
self.user2transaction = {}
self.user2trainsaction_list = []
self.train_file = inputfile
self.item_sess_prices_files = "data/item_sess_price.tsv"
self.itemset = [... |
from utils import (
get_guard_periods,
lines_to_records,
read_input
)
def get_most_asleep_guard_on_same_minute(guard_periods):
return sorted(
[guard_id for guard_id in guard_periods.keys()],
key=lambda guard_id: max(guard_periods[guard_id])
)[-1]
if __name__ == '__main__':
re... |
from collections import Counter
from pathlib import Path
raw_dir = Path(__file__).parent
allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZĄČĘĖĮŠŲŪŽ"
count = 0
letters = Counter()
_2gram = Counter()
_3gram = Counter()
for line in open('/Users/paulius/Temp/trash/lt_text'):
count += 1
if not count % 1000:
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.