index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
14,700
fd1ecf99dabb3f1472bb830ae9ea8bf92cd0de0f
#!/usr/bin/env python """Tool to launch ROS and setup environment variables automagically.""" import argparse import os import socket def get_local_ip(): """Get local ip address.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable sock.conne...
14,701
f152faae7b89e7377902462fa8b04778c29862af
import re from datetime import datetime, timedelta from settings import * import math from urllib.request import urlopen from bs4 import BeautifulSoup from firebase import firebase METRE_CONVERSION = 0.3048 # to convert from feet to metres def getTideTimesAndTideHeights(): """scrapes www.tide-forecast.com to col...
14,702
0e44bdc4e4dffea2e2e57615aadd3e3c67c0da03
#Day059 - json and REST APIs city = input('Enter your city: ') myAPI = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=526f48b568ce72f1ccfdc6cff57d7392" import requests response = requests.get(myAPI) weather_data = response.json() weather_data['cod'] #http://api.openweathermap.org/da...
14,703
8ec6f46ef73aaeba4a57c1bd99ea60c1bdb1a1fb
from django.urls import path from Trinamic import local_views app_name = 'Trinamic' urlpatterns = [ path('test', local_views.index, name='test'), path('product-center/<int:p_id>/<int:c_id>', local_views.product_center, name='product-center'), path('item-detail/<int:item_id>', local_views.item_detail, name...
14,704
37729ab85578a238df08152f8b84c462b2a09ef7
# -*- coding: utf-8 -*- """ Created on Sat Jan 27 2018 @author: Francesco """ # ELABORAZIONE DATI JSON import json from pprint import pprint ## carica un oggetto da un file with open("Domini_min.json") as in_json: data_json = json.load(in_json) pprint(data_json["listaDomini"][0])
14,705
0cceb7835e612ca5859e13476f5eeac74c5b3512
from odoo import models, fields, api, _ from odoo.exceptions import UserError class NamaModel(models.Model): _inherit = 'res.partner' identity_number = fields.Char( string="KTP Number" ) father_name = fields.Char( string="Father's Name" ) mother_name = fields.Char( string="Mother's Name" ) ...
14,706
a92346af784d641bdb9212dc0c92e9f7c624b313
# Generated by Django 3.1.7 on 2021-03-19 21:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('NavigationApp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='vehicle', name='id', ...
14,707
86b0459e8184b41195c515ce57b0f512f81eda8a
# coding: utf-8 import sys from setuptools import setup, find_packages NAME = "wavefront-client" VERSION = "2.1.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi", "...
14,708
74d82b62feeaba00fbe067ac55a9efb4ec1e1bd3
import pandas from bokeh.layouts import column from bokeh.models import ColumnDataSource, RangeTool from bokeh.plotting import figure, output_file, show #Reading the HTML data into a Pandas dataframe df = pandas.read_html("https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20190220&end=20190320")[0...
14,709
04909af7a7f3fc71ea6f172a650d5717f3022bbe
import names import pandas as pd import numpy as np import base64 import io ''' Generate random guests list :parameter :param n: num - number of guests and length of dtf :param lst_categories: list - ["family", "friends", "university", ...] :param n_rules: num - number of restrictions to apply (ex. if 1 ...
14,710
7ccab455d48a66f7ae21604103982ef58f4aca1f
import subprocess from Systems.NV import nv_parser from settings import NV_PATH, NV_BATFISH from Systems.systems import System class NVInterface(System): def __init__(self): super().__init__() self.compare_items = [ 'Node', 'Network', 'Next_Hop', '...
14,711
ddbcc6238e3416bc98596c22e857da29fd706e38
from django.views.generic import TemplateView from fluent_pages import appsettings class RobotsTxtView(TemplateView): """ Exposing a ``robots.txt`` template in the Django project. Add this view to the ``urls.py``: .. code-block:: python from fluent_pages.views import RobotsTxtView ...
14,712
eca658fff2a200e18e135bb43a16f4d443929258
from flask import jsonify, request, url_for, current_app, abort from .. import db from ..models import Endereco, EnderecoSchema, Permissao, Bairro from . import api from .errors import forbidden, bad_request2 from sqlalchemy.exc import IntegrityError, OperationalError from marshmallow.exceptions import ValidationError ...
14,713
a1b9960618a447041dd74a8a8c09c254b0efebbe
import urllib.request as ur import matplotlib.pyplot as plt import urllib.parse import requests import json import datetime import sys import os.path api_url_base = 'https://stat.ripe.net/data/' def get_country_asn(country_code): api_url = '{}country-asns/data.json?resource={}&lod=1'.format(api_url_base, countr...
14,714
8ab17693bc32b01d899c58726e5db0fe8cbd716c
from learnable_encryption import BlockScramble import numpy as np def blockwise_scramble(imgs,key_size = 4): x_stack = None for k in range(8): tmp = None # x_stack = None for j in range(8): key_file = 'key4/'+str(0)+'_.pkl' bs = BlockScramble( key_file ) out = np.transpose(imgs,(0, 2, ...
14,715
de9e199d1616964222d9e0d5d83307a563df076e
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier loa...
14,716
90f7dcf08c643efeb6ce99a0f4c14b6330cb48e6
def make_keys(): d={} f=open('words.txt') t=[] for line in f: t=t+line.split() for element in t: d[element]='' return d print make_keys()
14,717
a2fcaff20b61451ade6da032eab2517cde45629d
#!/usr/bin/python #-------------------------------------------------------------------------------------------------- #-- systemDivisions #-------------------------------------------------------------------------------------------------- # Program : systemDivisions # To Complie : n/a # # Purpose : # # Called By ...
14,718
cf918b37e8e80db68b89f5a2316ccc789e35de4c
from __future__ import print_function, division import sys, json, warnings import numpy as np import scipy.optimize from ..data import Trace from ..util.data_test import DataTestCase from ..baseline import float_mode from .fitmodel import FitModel from .searchfit import SearchFit class Psp(FitModel): """PSP-like...
14,719
46246203684cefe976b065f835593f35bdfb48b7
from multiprocessing import Process import time #一种直接使用多进程函数的方法 def f(name): time.sleep(1) print('hello',name,time.ctime()) if __name__ == '__main__': p_list = [] for i in range(5): p = Process(target=f,args=('xiaoming',)) p_list.append(p) p.start() #for p in p_list: ...
14,720
33834044bf04ef70d8910672348711dd73aceaa3
# # 路由的功能 # # 伪静态实现 # # 正则版路由 # # 增删改查系 # # 日志相关系 # import urllib # # url编码 # result = urllib.parse.quote("http://www.test.com/wd=逸鹏说道") # print(result) # # url解码 # new_result = urllib.parse.unquote(result) # print(new_result) # # 把键值对编码为url查询字符串 # result = urllib.parse.urlencode({"wd": "逸鹏说道"}) # print(result) # ...
14,721
bb6b6b2efbbbcf50f5a5cd71e3f9c2529fef0fc6
import json from ui import qtx class Settings: '''Class that looks like a normal dictionary, but is persistent. The persistence is backed by registry via QSettings service. Attention: known deviations from normal dict behavior: * saving tuples will return a list. ''' def __i...
14,722
1a23032a41d3ce1ad5480fb9879942bf16751314
# -*- coding: utf-8 -*- from Cluster import Cluster class KMedias: def __init__(self, datos, headers): self.datos = datos self.headers = headers def armarCluster(self, cantCluster, repeticiones): self.Kclusters = cantCluster self.repeticiones = repeticiones #lista de c...
14,723
27226ea0f0eca96ab4e3f8876e8feded50c7eba0
from typing import List class RotateImage: """ Problem: Rotate Image (#48) Problem Description: Given n x n 2D matrix, rotate the image by 90 degrees (clockwise) Must rotate the image in-place (do not allocate another 2D matrix) Key Insights: 1. Rotate values counter clockwise, ex left c...
14,724
3c8907eda8b61bc8bdaccf5102f0de837aa484f2
{ 'includes':[ '../common/common.gypi', ], 'targets': [ { 'target_name': 'tizen_download', 'type': 'loadable_module', 'sources': [ 'download_api.js', 'download_extension.cc', 'download_extension.h', 'download_instance.cc', 'download_instance.h', ...
14,725
dff4298ae886c8d2b9aa2481a88426201a93399d
a=int(input()) summer=0 while a>0: s=a%10 summer=summer+s a=a//10 summer=str(summer) t=summer[::-1] if t==summer: print("YES") else: print("NO")
14,726
d21fd4117f70040800939401bc4d020d97c224cc
""" ------------- Dropdown menu ------------- Usually used in tables to add actions for rows. """ # 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...
14,727
9768b857da88ff8d45ae7960851a2e8beb684c5d
import json from PyInquirer import prompt, Separator # type: ignore import requests from apihandler import APIHandler from move import Move class Pokemon(): """ A class to represent a Pokemon Attributes: id: int Pokedex ID of the pokemon name: str Name of the pokemon types:...
14,728
d4544ee7e6fb92e4a15bcc9416f04725eb2d658a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 31 10:46:24 2022 @author: baptistelafoux """ import cv2 import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import zoom, gaussian_filter from utils.graphic import get_moviename_from_dataset from utils.loader import dataloader ...
14,729
7997a37ee5716ad0cd7e6c4030f4b66a5045a092
import unittest import numpy as np import pandas as pd import scipy.stats import sklearn.metrics import subprocess import os import wot.ot class TestOT(unittest.TestCase): """Tests for `wot` package.""" def test_same_distribution(self): # test same distributions, diagonals along transport map should...
14,730
6c92e05e5729074f0f5c15751edcd2ad075c8a52
# L=[23,45,66,77,22,21,24,22], sort it in descending order. No lib should be used. L=[23,45,66,77,22,21,24,22] for i in range(len(L)-1): for j in range(i+1,len(L)): if L[i]<L[j]: temp = L[i] L[i] = L[j] L[j] = temp print(L)
14,731
a06330b9fb47412abd14a0b2a85b3582dafcb469
class human: fp='priti' def __init__(self,eyes,foot): self.e=eyes self.f=foot def details(self,name,bldgroup): self.n=name self.b=bldgroup def display(self): print("human eyes=",self.e) print("human foot=",self.f) print("human name=",sel...
14,732
e6f04a28a921110d9ccc4791fb14ad69846c2476
import array import hashlib import csv from progressbar.bar import ProgressBar from Crypto.Hash import SHA256 class PrecursorUsb: def __init__(self, dev): self.dev = dev self.RDSR = 0x05 self.RDSCUR = 0x2B self.RDID = 0x9F self.WREN = 0x06 self.WRDI = 0x04 s...
14,733
5987d6cd40e4f586cc0d66a6e36958c764eb0a17
def findLengthOfLCIS(nums: list) -> int: if not nums: return 0 count = 1 result = 0 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: count += 1 else: result = max(result, count) count = 1 return max(result, count) if __name__ ...
14,734
de5e8ff40325c08dbf869ead1073a84c86ae261f
def question_5(first_name, last_name): return(print("My full name is " + first_name + " " + last_name))
14,735
0720391e108eee2ac3d99af6c31e80cf58b14542
from django.db import models # Create your models here. class Mineral(models.Model): UNIT_TYPE = ( ('mg', 'miligram'), ('μg', 'mikrogram'), ) mineral_name = models.CharField(max_length=150) mineral_symbol = models.CharField(max_length=50) mineral_unit = models.CharField(max_length=1...
14,736
376aa91efd798eb4c853fbc40123e3c7ff2496ad
a=list() n=input() b=input() for i in range(0,int(n)): d=input() a.append(d) a=''.join(a) print(a) if b in a: print("Yes") else: print("No")
14,737
56d0be39d170bf26875544f3bf618cac043e5981
import numpy as np import random class Graph: def __init__(self, numVertices, maxEdgeWeight=100,edgeProb=None, avgNumEdges=None, noEdges=False): self.numVertices = numVertices self.maxEdgeWeight = maxEdgeWeight self.E = [[] for i in range(self.numVertices)] #Create Graph w...
14,738
a676cab9a3a281c2f453d9e457bda81f66262e10
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='find some suspicious behaviours of trader.', author='chirag', license='', )
14,739
71e4bbd70f3e7145e0758b595c4ceff6b1edfd76
from keras.models import model_from_json import numpy import os # SECTION 1 - Load the model # By now all of this should be pretty clear for you. # Still, check out the relevant Keras manual entry # https://keras.io/models/about-keras-models/ json_file = open('model.json', 'r') loaded_model_json = json_file.read() ...
14,740
5b186229922b0d6399707781537ac6d875894350
from django.contrib import admin from .models import UrlShort admin.site.register(UrlShort)
14,741
80e0bccb2cfa7cbc4c6aabc1dfa37e43f97d49b6
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import argparse import json import os import random import sys import numpy as np import tensorflow as tf import numpy as np #print(path+'/fisr.png') batch_size = 128 num_of_classes=3 image_size=...
14,742
92fd7c33bbb6b5c8438f57a7decdc8aa3ecc257e
from OpenGLCffi.GL import params @params(api='gl', prms=['mode', 'indirect', 'drawcount', 'maxdrawcount', 'stride']) def glMultiDrawArraysIndirectCountARB(mode, indirect, drawcount, maxdrawcount, stride): pass @params(api='gl', prms=['mode', 'type', 'indirect', 'drawcount', 'maxdrawcount', 'stride']) def glMultiDraw...
14,743
9b60a1554c8c839323e72c729fa50a7711a7e7a8
#from number_recognition import * import random import math import numpy as np import jsonpickle import atexit import json import keyboard from tkinter import Tk,Canvas, font with open("./save_net.json") as f: print("Starting importing net...") net = jsonpickle.decode(f.read()) print("Import net...
14,744
fdc1df77b6903164db1616bfaf7cfc14ce890936
# -*- coding: utf-8 -*- """ Created on Sun Sep 20 12:15:56 2020 @author: 426-2019级-1 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 df = pd...
14,745
9088af991ca128e85550708cbddddf45af963d56
# -*- coding:utf-8 -*- import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('www.bilibili.com', 80)) s.send(b'GET /HTTP/1.1\r\nHost:www.bilibili.com\r\nConnection:close\r\n\r\n') buffer=[] while True: d=s.recv(1024) if d: buffer.append(d) else: break data=b''.join(buffer) s.close() hea...
14,746
a77ed31a71760f495bdfed54cbe1295c506714c3
from pyspark.sql.functions import * import csv from pyspark.sql.types import * from pyspark.sql.functions import * from pyspark import SparkContext from pyspark.sql import HiveContext from pyspark.sql.functions import * from pyspark.sql.functions import udf from pyspark.sql.types import BooleanType from pyspark.sql imp...
14,747
31a9533a17422cf19cd4b2880499c0bf8d310df5
# Generated by Django 2.2.7 on 2019-11-30 04:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0009_auto_20191129_0902'), ] operations = [ migrations.AlterField( model_name='new_sighting', name='Lat...
14,748
9b152afba43afe835957dcab49d98dd66d3d3e65
from urllib.request import urlopen WORD_URL="http://learncodethehardway.org/words.txt" WORDS=[] #for word in urlopen(WORD_URL).readlines(): #WORDS.append(str(word.strip(), encoding='utf-8')) #print(WORDS) print(b"adjustment\n".strip())
14,749
acfe875629dc508aae710e1da80a9d2d71885217
class Bread: def __init__(self): self.current_price = 0.80 self.id = 'Bread' self.discount = False self.price = 0.80 def apply_discount(self, discount): self.discount = True return self.price * discount def __repr__(self): return f"{self.id} - {self...
14,750
d606013330f22f10c4732da07609b28cf04744a7
from django.db import models from django.utils.translation import gettext as _ import uuid class Breed(models.Model): class Meta: verbose_name = _('Breed') verbose_name_plural = _('Breeds') title = models.CharField(_('title'), max_length=64, blank=False, unique=T...
14,751
7a38d8535d07c29dde2abf7cabf28527bee48377
""" objective 3 : two points on two consecutive sections """ import overpy from geopy.geocoders import Nominatim from method import * def give_location3(api, nodes, name, addr,lat1,lon1,lat2,lon2): ''' Give the full location :param nodes: The list of all nodes of the road :param name: The name of the ro...
14,752
fe23b5790679d3a037e8df0e88fc17966300d448
from django.shortcuts import render from django.http import HttpResponse import pandas as pd import json # from django import jsonify import os from .models import Greeting from django.views.decorators.csrf import csrf_protect import digitaldivide.src.digitaldivide as digitaldivide # Create your views here. def index(r...
14,753
9e7a9d8c68f3d1fd7862b00659e3cd669fa07da8
import ffmpeg vid = ffmpeg.probe("man_running.mp4") print(vid["streams"]) metadata = vid["streams"][0] print(metadata) print(metadata["r_frame_rate"])
14,754
a15283d6ae2f6da67d9471955b8cf8fb7068401a
# 1 - Import library import sys sys.path.insert(0, '/storage/home/django_learn/pygame/src') import os import math from random import random, randint import imgaud import core import time import pygame from pygame.locals import * from src import core class SpaceAdv(core.SpaceAdvCore): def menu(self): posit...
14,755
407c5672f72a0a591bd66a4e75dbeb0eb4f3a4ce
import datetime class Test: def __init__(self, testid): self.__testid = testid self.__questions = [] self.__noofq = 0 self.__maxmarks = 0 self.__level = None self.__date = datetime.datetime.now() def DesignTest(self): testid = input("Test id: ") ...
14,756
5bd95b5c96338b070ae50d046c29d29f084a6b57
from featurehub.tests.util import EPSILON from featurehub.modeling.scorers import ndcg_score, rmsle_score from featurehub.modeling.scorers import ndcg_scorer, rmsle_scorer from featurehub.modeling.automl import ndcg_autoscorer, rmsle_autoscorer import numpy as np def test_ndcg(): y_true = np.array([1,0,2]) y...
14,757
ccaa76129cdbdc67952ab8b858aff997e93b1eeb
from ._Actions import * from ._SetControlMode import *
14,758
6c60bc48907dac1cf6ec5076d26ec1b786d85b0f
# Generated by Django 3.2.6 on 2021-08-28 03:26 import aseb.core.db.fields import aseb.core.db.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.functions.datetime import django_editorjs_fields.fields class Migration(migrations.Mi...
14,759
7395de8434cbd2f7447c62574644093c3f6b3b23
import pretty_midi from scipy.io import wavfile import numpy as np class ChordiumException(Exception): pass class IDontKnowThatChord(ChordiumException): pass def f64le_to_s32le(data): shifted = data * (2 ** 31 - 1) # Data ranges from -1.0 to 1.0 ints = shifted.astype(np.int32) return ints ...
14,760
aee54c333e563b9fbeb4df9af093e94fc56d37c3
import math class Knot: def __init__(self, kn_id, x, y, kn_type, angleSupport, k=[0, 0, 0], pointload=[0, 0, 0]): self.id = kn_id self.x_ = x self.y_ = y self.pointLoad_ = pointload self.type = kn_type self.angle = math.degrees(angleSupport) # in degree self....
14,761
485fe3cfc6cd31971cee7c837fc2980cc443578c
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 23:15:33 2019 @author: marco Nome: Marcos Vinicius Timoteo Nunes Matricula: 16.2.8388 Disciplina: Aprendizagem de Maquina Professor: Luiz Carlos Bambirra Obs: Lembrar de comentar DO TREINAMENTO PARA BAIXO, PARA RODAR Depois disso, pode descomentar e rodar novam...
14,762
c8a0488d22ab0178add20e4877362a74d5ba21d6
import numpy as np import cv2 import threading import Object import StopLine from model import NeuralNetwork class CollectTrainingData(object): def __init__(self, client, steer): self.client = client self.steer = steer self.stopline = StopLine.Stop() self.dect =...
14,763
1b536837235b5598d71ef64ef055f323900320b5
import os from ..applescript import osascript ITERM = os.path.join(os.path.dirname(__file__), "iterm.applescript") ITERM_BRACKETED = os.path.join(os.path.dirname(__file__), "iterm_bracketed.applescript") def send_to_iterm(cmd, bracketed=False, commit=True): if bracketed: osascript(ITERM_BRACKETED, cmd, s...
14,764
7409b02753022a523bdd964e1f549fa7b6b6554d
import pygame.font class Buttom (): """Кнопка в игре""" def __init__(self, pa_settings, screen, msg): """Инициализируем кнопку""" #self.pa_settings = pa_settings self.screen = screen self.screen_rect = screen.get_rect() #Назначение размеров и свойств кнопки ...
14,765
77b15ea90cb722fa2a2f606a6935477554ec60d5
from rest_framework import serializers from .models import IpAddress class IpAddressSerializer(serializers.ModelSerializer): class Meta: model = IpAddress fields = '__all__' read_only_fields = ('ip_address','status',)
14,766
5c98c99f636fbd0447e580862240582df9875a08
import sys from db import connect_db c = connect_db() cur = c.cursor() # 2.g def pop_obmocja(x, y, distance): cur.execute( "select sum(population) from naselje where x > {} and y > {} and x < {} and y < {}".format(x - distance, ...
14,767
4599be3b262babffe85eb104207e301948767c19
def sum_floats(nums): return (sum([i for i in nums if isinstance(i, float)])) print(sum_floats(['a',1,'f',3.2,4,3.25]))
14,768
e39ff197a9a3a27e9dd66aa9049b517cb0c710ae
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'PackageDistribution' db.create_table('repo_packagedistribution', ( ('id', self...
14,769
5b5cb02c2ea8dcd994d1e8028c8362f207063ccc
from account import Account def main(): loop = True while loop: i_d = input("Enter your ID, or press ENTER: ") if i_d == "": break elif float(i_d) < 0: print("Enter a positive number") else: break loop = True while loop:...
14,770
431ea3275d4931af11d0c4197db73cf7f919d31d
import abc import numpy as np __all__ = ['ParamView', 'NodeParamView', 'EdgeParamView'] # delegate almost all magic methods to the full array # (omit in-place ops + a few others like __len__ that we will special # case) _delegated_dunders = ['abs', 'add', 'and', 'bool', 'complex', 'contains', '...
14,771
c0050dc9175b70ddeb5e80576890d85f5fbd3a06
# -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy.http import Request from usc.items import CourseItem import re from urllib.parse import urljoin class UscsocSpider(scrapy.Spider): name = 'uscsoc' allowed_domains = ['web-app.usc.edu', 'web-app.usc', 'usc.edu'] start_u...
14,772
c21dc5ae6e1fbf0fbb8bab9aefb7394f4a7db79a
from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.ensemble import ExtraTreesClassifier import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import math class Analyser(): def __init__(self, x, y, feature_list, fig_save_dir): s...
14,773
babe5235b102e1e9acd0c5768af95fbb55e56406
from model.project import Project def test_delete_project(app, config): old_project_list = app.soap.get_projects_list(config["webadmin"]["username"], config["webadmin"]["password"]) if len(old_project_list) == 0: app.project.add_new_project('new') project_to_delete = old_project_list[0] app.pr...
14,774
2c6c4d1133ea6c4f95f96e3c699ff6f50b4bed27
import click # from mne import read_ctf import contextlib import sys from mne import find_layout from os.path import commonprefix as cprfx from os.path import split, splitext, exists, join from os import makedirs from mne.io import Raw as Raw_fif from mne.io import read_raw_ctf as Raw_ctf from scipy.io import savemat ...
14,775
c667167dfd441292c299f768b45a3c1f33aebdb2
from .affine import apply_rotation, random_rotation, sample_rotation from .deformation import random_deformation_field, apply_deformation_field, random_deformation, checkboard3D, checkboard2D from .generators import xy_augmentation_generator from .ImageDataGenerator3D import ImageDataGenerator3D from .sampling import s...
14,776
3357e042ed411c0645a4ef2f82d8f3da5e835a1f
from abc import ABC, abstractmethod from jawa.assemble import assemble from jawa.cf import ClassFile from jawa.methods import Method from jawa.constants import * from jawa.util.descriptor import method_descriptor from jawa.util.bytecode import Operand import six.moves # See https://docs.oracle.com/javase/specs/jvms/...
14,777
6b59ebd63e104b19ff5624851a99bf554cf4e683
DE_only = [] LogFC = [] with open('new_DEs_0.05.csv') as DE_tags: for line in DE_tags: line = line.split() DE_only.append(line[0]) LogFC.append(line[1]) DE_logFC = {} for z in range(0, len(DE_only)): DE_logFC[DE_only[z]] = LogFC[z] #there is 12 GO categories complete = [] GO1 = [] with open('enriched_GO.csv'...
14,778
9d2ea4e673c5f1b199e38d7d40eb6e475966e0dd
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Aug 26 15:02:09 2017 @author: anand """ #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 13:27:40 2017 @author: anand """ #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 12:15:50 2017 @author: anand "...
14,779
eb68d244e256cf15c8a76f44a4ca6a038a6de7fe
# /usr/bin/env python # -*- coding: UTF-8 -*- import hashlib import time import random import string try: from urllib import quote except ImportError: from urllib.parse import quote import requests import sys #reload(sys) #sys.setdefaultencoding("utf-8") def get_params(plus_item): '''请求时间戳(秒级),用于防止请求重放(保证签...
14,780
0f2181981d152ca283e3a843d6688cf2d6da950c
import asyncio from typing import Dict import pytest from pydantic import BaseModel, StrictInt, conint import hivemind from hivemind.dht.node import DHTNode from hivemind.dht.schema import BytesWithPublicKey, SchemaValidator from hivemind.dht.validation import DHTRecord, RecordValidatorBase from hivemind.utils.timed_...
14,781
a0b58f9bc545221cf6e39361ec7d8845c4cc1674
from time import sleep from os import system def SexoVerificacao(x): #! Função que verifica se o valor inserido para sexo é válido if x not in 'MF': while True: if x in 'MF': break print('===Entre com um valor válido!===') sleep(1) x = str...
14,782
db0469453899702cabc48adfbdeb2f2a7818f2aa
import time import random import math people = [('Seymour','BOS'), ('Franny','DAL'), ('Zooey','CAK'), ('Walt','MIA'), ('Buddy','ORD'), ('Les','OMA')] # Laguardia destination='LGA' flights={} for line in file('schedule.txt'): origin,dest,depart,arrive,price=line.st...
14,783
f61d2424698a9d8567716caaf5459bb2f4196b9a
import functools def flatten(r): items = (flatten(i) if type(i) is list else [i] for i in r) return functools.reduce(list.__add__, items)
14,784
b19543de2ee286e8de3bdf71d4818407b08b73c1
from sampleModule import royalty def nuclearBomb(): return royalty()
14,785
ccb0dc4f2ed4cfa71ad3d7440854076a1acd580c
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) def BatchNormalization(x): return x - np.mean(x) / np.std(x) x = np.random.randn(1000,100) node_num = 100 hidden_layer_size = 5 activations = {} for i in range(hidden_layer_size): if i != 0: x = activ...
14,786
5cff63671226882ca7cc52c398c999cee6ddbb93
# Dictionaries # Create person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 20 } person2 = dict(first_name='Sara', last_name='Williams') print(person, type(person)) print(person2) # Get value print(person['first_name']) print(person.get('last_name')) # Add person['phone'] = '555-555-55' print(pe...
14,787
e21c4fa1c820a1e67312f04d0c3f671adcbf2a2f
# -*- coding: utf-8 -*- # C - Average Length # https://atcoder.jp/contests/abc145/tasks/abc145_c import itertools N = int(input()) xy = [list(map(int, input().split())) for _ in range(N)] p = [] cnt = 0 for v in itertools.permutations(xy, N): p.append(v) for i in range(len(p)): for j in range(N-1): ...
14,788
56b0c16e58b9297aea34aa7ba4ba216e275705ac
import logging ROOT_LOGGER_NAME = 'mamba' FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' FILE_LEVEL = logging.DEBUG CONSOLE_LEVEL = logging.INFO def init(log_filename="tmp.log", console=True, debug=False): logging.root.name = ROOT_LOGGER_NAME logging.root.setLevel(logging.DEBUG) formatter = logg...
14,789
201e023a9c3d96824bd00cf6f651c0f1f6d020e6
from invoke import task @task def tests(c): c.run("py.test -vvx tests", pty=True)
14,790
863091c99200ad10d3c311e4b63a5c619ce9157d
import os import cv2 import argparse import numpy as np import tensorflow as tf import utils.config as cfg from utils.model_yolo import YOLONet from utils.timer import Timer #检测的类Detector class Detector(object): def __init__(self, net, weight_file): # Yolo网络 ''' 初始化参数和配置模型 ...
14,791
a1a4550942ab233486742e972ef1e32785b90f34
import konlpy from collections import Counter # 저는 이미 khaiii로 형태소 분석이 끝났기 때문에 불필요 할 것 같습니다. # 대신에 collections 의 counter 함수를 이용해서 빈도수만 채크 # def get_key(text, ntags=30): nouns = open("C:/Users/student/Documents/jinahan/형태소분석/코모란/komoran.txt") #경로에 있는 파일을 저장. count =Counter(nouns) # 참고: https://excelsior-cjh.tistory.com...
14,792
d75c7f153dc93a3266af4005eb7215ad719fc6f5
from django.contrib.auth.models import User from rest_framework import serializers from .models import Item, Profile from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class UserCreateSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta:...
14,793
7adfc3e1fff7483e3ebe955fdcacf4c61087f7f6
# -*- coding: utf-8 -*- """ Created on Mon Feb 20 10:15:37 2017 @author: andy """ from cyvlfeat import kmeans import os import pickle from numpy import random import numpy as np from preprocess_hog_pkl import hog_preprocess from cyvlfeat.kmeans import kmeans def get_hog_dictionary(data_path,num_cluster = 1024, data...
14,794
907165ba0fe39c45b4fc1d3be0c2f88a86238279
import torch from torch import nn class WeightSynthesizer(nn.Module): def __init__(self, num_dims_in, num_dims_out, d=25): super(WeightSynthesizer, self).__init__() self.fc1 = nn.Sequential( nn.Linear(num_dims_in, d), nn.ReLU() ) self.fc2 = nn.Sequential( nn.Linear(d, d*2), nn.ReLU() ) self.fc...
14,795
15852da39205ea53635499015e1c351f693f7e97
a, b = map(int, input().split()) answer = min(((a - a // 2) - a // 2) * b, ((b - b // 2) - b // 2) * a) print(answer)
14,796
3a51ccf51daeed9d42b0127c29b90e277724af85
import mpyq from heroprotocol import protocol29406 class HeroParser(): def __init__(self, replay_path): self.replay_path = replay_path self.archive = mpyq.MPQArchive(replay_path) # Read the protocol header, this can be read with any protocol self.contents = self.archive.header['user_data_header']['content'] ...
14,797
2b3c329cdf36b48528e4bfd68256f481622305a4
#!/usr/bin/env python ######################################## # Mario Rosasco, 2017 ######################################## from Model import * from Visualization import * from scipy.optimize import minimize from allensdk.ephys.ephys_features import detect_putative_spikes import numpy as np import sys ...
14,798
3cc24c98c6c79f35416edee9db58a09198725a02
import enum class ItemType(enum.Enum): BOOK=1 BAG=2 SHOES=3 CLOTHES=4 class ExpenditureType(enum.Enum): FEES=1 BUYING=2 class DonationPlan(enum.Enum): ANUALLY=1 SEMI_ANUALLY =2
14,799
36c8b70376726b47ba2630cdc3c6b35777ed54ec
''' @author: Dean D'souza ''' # Loading necessary Libraries from __future__ import division import nltk from nltk.text import Text from ProjectTokenizer import pToken from ProjectTagger import pTagger from nltk.corpus import stopwords # Loading all text data txtFile=open('C:/Users/demon/OneDrive/Documents/GitHub/CISC_...