seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20048142461 | from django.urls import path
from .views import MovieList,MovieDetail,MovieCategory,MovieLanguage,MovieSearch,MovieYear,MostWatch
from django.conf.urls import url
app_name='movie'
urlpatterns = [
path('', MovieList.as_view(),name='Movie_List'),
path('category/<str:category>', MovieCategory.as_view(),name='Mo... | sureshsaravananbabu/IMDB-clone | imdb/movie/urls.py | urls.py | py | 673 | python | en | code | 0 | github-code | 1 |
3198068544 | # python3
import sys
class Query:
def __init__(self, query):
self.type = query[0]
if self.type == 'check':
self.ind = int(query[1])
else:
self.s = query[1]
class QueryProcessor:
_multiplier = 263
_prime = 1000000007
def __init__(self, bucket_count):
... | shenweichen/Coursera | Specialization_Data_Structures_Algorithms_UC_San_Diego/Course2_Data_Structures/week3_Hash_Tables/hash_chains/hash_chains.py | hash_chains.py | py | 1,959 | python | en | code | 843 | github-code | 1 |
70004662115 | #!flask/bin/python
from flask import Flask, jsonify, request, json
import requests
import time
from core import test_class
from BeautifulSoup import BeautifulSoup
app = Flask(__name__)
@app.route('/ytc/search', methods=['GET'])
def get_tasks():
start_time = time.time()
q1 = request.args.get('q')
url = 'ht... | gauravsingh1983/pythonscripts | web/__init__.py | __init__.py | py | 2,385 | python | en | code | 0 | github-code | 1 |
27211327323 | # -*- coding: utf-8 -*-
'''
Created on 2015年9月29日
@author: michael
'''
from openerp import models, fields, api, _
class move_transfer_wizard(models.TransientModel):
_name='move.transfer.wizard'
stock_quant_ids = fields.Many2many('stock.quant','stock_quant_move_transfter_ref','wizard_id','stock_q... | kh1688/four-old | move_transfer/wizard/move_transfer_wizard.py | move_transfer_wizard.py | py | 1,097 | python | en | code | 0 | github-code | 1 |
70861202914 | import threading
import mock
import pytest
from blazingmq import BasicHealthMonitor
from blazingmq import Error
from blazingmq import QueueOptions
from blazingmq import Session
from blazingmq import session_events
from blazingmq.testing import HostHealth
def test_receiving_host_health_events():
# GIVEN
spy ... | bloomberg/blazingmq-sdk-python | tests/integration/test_health_monitoring.py | test_health_monitoring.py | py | 2,921 | python | en | code | 15 | github-code | 1 |
24649723716 | import os
import sys
import warnings
import platform
import datetime as dt
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.dates as md
def dmy2ymd(dmy):
return dt.datetime.strptime(
str(dmy, encoding='utf-8'),
'%d-%m-%Y').date().strftime('%Y-%m-%d')
def read_d... | smakerm/list | note/step4/爬虫笔记/18. DataScience/day05/smr.py | smr.py | py | 4,832 | python | en | code | 0 | github-code | 1 |
4254375058 | import ssl
import re
import traceback
from urllib.request import Request, urlopen
import requests
import json
from careerjet_api import CareerjetAPIClient
from bs4 import BeautifulSoup, SoupStrainer
from concurrent.futures import ThreadPoolExecutor
# --------------------------------------------------------------------... | Victor-JB/LinkHS-Jobs-API | get_full_description.py | get_full_description.py | py | 3,265 | python | en | code | 0 | github-code | 1 |
23550339540 | import logging as logger
import os
from pyspark.sql import DataFrame
from ddataflow.exceptions import BiggerThanMaxSize
from ddataflow.sampling.default import filter_function
from ddataflow.utils import get_or_create_spark
class DataSource:
"""
Utility functions at data source level
"""
def __init_... | getyourguide/DDataFlow | ddataflow/data_source.py | data_source.py | py | 4,121 | python | en | code | 7 | github-code | 1 |
19694533895 | from abc import abstractmethod
class URLFormat:
@abstractmethod
def build_url(self, qs):
# type: (dict) -> str
...
class URLFormats:
class _Detail(URLFormat):
URL_FORMAT = (
"https://play.google.com/store/apps/details?id={id}&hl={hl}&gl={gl}"
)
def bu... | jokerart06/google-play-scrapergit | google_play_scraper/constants/url.py | url.py | py | 411 | python | en | code | 0 | github-code | 1 |
36412894737 | import numpy as np
import cv2
import glob
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--rgb_path", type=str, help="raw image path", default='./data_augmentation/raw_data/bg_img/select/total/')
# parser.add_argument("--mask_path", type=str, help="raw image path", defaul... | chansoopark98/Tensorflow-Keras-Semantic-Segmentation | data_augmentation/make_blank_label.py | make_blank_label.py | py | 1,674 | python | en | code | 12 | github-code | 1 |
34860632841 | """
Code for running experiments for
"Asymmetric Tri-training for Debiasing Missing-Not-At-Random Explicit Feedback".
"""
import argparse
import yaml
import warnings
import tensorflow as tf
from trainer import Trainer, Tuner
possible_model_names = ['uniform', 'uniform-at', 'user', 'user-at', 'item', 'item-at',
... | usaito/asymmetric-tri-rec-real | src/main.py | main.py | py | 1,857 | python | en | code | 23 | github-code | 1 |
38069299722 | import os
import glob
import shutil
import re
import gi
gi.require_version('Limba', '1.0')
gi.require_version('AppStream', '1.0')
from gi.repository import Limba
from gi.repository import AppStream
from hashlib import sha256
from ..utils import build_cpt_path
from ..repository.models import *
from ..user import User
f... | limbahq/limba-hub | lihub/maintain/ipkimport.py | ipkimport.py | py | 6,824 | python | en | code | 2 | github-code | 1 |
40365228173 | #encoding=utf-8
import sktensor
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
import os
import scipy.io as scio
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
from random import random
from scipy.sparse import rand as sprand
from compt_methods import *
from road_sim... | qiushye/ITS_217 | tensor_cpt.py | tensor_cpt.py | py | 21,683 | python | en | code | 0 | github-code | 1 |
41606487 | import unittest, sys
from unittest import TestCase
from plasTeX import Macro, Environment, Node, Command
from plasTeX.TeX import TeX
from plasTeX.Context import Context
from helpers.utils import compare_output
class ContextGenerated(TestCase):
def testNewcommand(self):
c = Context()
c.newcommand('... | plastex/plastex | unittests/NewCommands.py | NewCommands.py | py | 7,708 | python | en | code | 240 | github-code | 1 |
25015394148 | from flask import url_for, flash, Markup, redirect, Response
from flask_admin import expose
from flask_jwt_extended import create_access_token
import pendulum
from src.admin.admin_forms import TestLabelFormatForm, TestCalculatedFieldForm, DriverChangeForm, \
ConfigRestoreForm, ConfigBackupForm, GenerateJwtTokenFor... | krezac/tesla-race-analyzer | src/admin/admin_views.py | admin_views.py | py | 13,674 | python | en | code | 1 | github-code | 1 |
29461253994 | import dearpygui.dearpygui as dpg
from data import extract_data, get_path2
dpg.create_context()
path2data = get_path2("Test_spectrum.syn")
x, y, _ = extract_data(path2data)
# Screen resolution for window scaling. dpi for correct font size.
res_x, res_y = 1920, 1080
dpi = 150
with dpg.font_registry():
# first ar... | zhukgleb/synth_spectrum | gui.py | gui.py | py | 1,598 | python | en | code | 0 | github-code | 1 |
28567646925 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"View module showing all messages concerning discarded beads"
from typing import cast
from bokeh import layouts
from model.plots import PlotState
from taskview.plots import PlotView, CACHE_TYPE, TaskPlotCreator
from ... | depixusgenome/trackanalysis | src/qualitycontrol/view/_view.py | _view.py | py | 3,713 | python | en | code | 0 | github-code | 1 |
15103185485 | import calendar
import pandas as pd
import numpy as np
def remove_high_corr(df,target='Israelis_Count',threshold=0.5):
'''
return dataframe without corrlation that can be drop.
args:
df = dataframe
target = string of the target
threshold = default 0.5
'''
target_col = df.pop(target)
df.insert(len(... | LiavCohn/nature-reserves-paper | function.py | function.py | py | 11,566 | python | en | code | 0 | github-code | 1 |
35947650994 | # -*- coding: utf-8 -*-
import os
import csv
import ast
from itertools import islice
import matplotlib.pyplot as plt
from sklearn import preprocessing
import numpy
"""
This script is plotting all of bad sample data
"""
if __name__ == '__main__':
root=os.getcwd()
bsxs=["bs1","bs2","bs3","bs4","bs5","bs6","bs... | s-okugawa/HDNNP-tools | tools/bad-sample/plot-allbs.py | plot-allbs.py | py | 1,785 | python | en | code | 0 | github-code | 1 |
27409860086 | import numpy as np
from tensorflow.keras.layers import GlobalAveragePooling1D, Dense, Embedding, Dropout
from tensorflow.keras.models import Sequential
import tensorflow as tf
import string
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
tokens = 10000
tf.get_logger().setLevel('ERROR'... | Omar-ALkhateeb/Misfaia | base_model.py | base_model.py | py | 2,276 | python | en | code | 0 | github-code | 1 |
17818159274 | from gpio import *
from time import *
puerta = 0
ventana = 2
garage = 1
switch8 = 3
switch10 = 4
switch9 = 5
webcam1 = 6
webcam2 = 7
siren = 8
sensor = 9
def main():
pinMode(switch8, IN) #pin de entrada del switch de la puerta
pinMode(switch9, IN) #pin de entrada del switch del garaje
pinMode(switch10, IN) #pin de... | andrea1510/ArquitecturaDeComputadoras | SBC.py | SBC.py | py | 1,495 | python | es | code | 0 | github-code | 1 |
1585593679 | from typing import Optional
from decimal import Decimal
from validator_collection import validators
from highcharts_core import errors
from highcharts_core.metaclasses import HighchartsMeta
from highcharts_core.utility_classes.gradients import Gradient
from highcharts_core.utility_classes.patterns import Pattern
cl... | highcharts-for-python/highcharts-core | highcharts_core/options/axes/data_classes.py | data_classes.py | py | 3,874 | python | en | code | 40 | github-code | 1 |
33397514940 | import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
startPoint = 5
state1 = np.loadtxt('1.0_2.0_state')[:,0].reshape(1,201,1)
encoder_input1 = state1[:,:startPoint,:]
decoder_input1 = state1[:,startPoint:-1,:]
output1 = state1[:,s... | Bonbon-Tang/DL-for-dynamical-systems | MSSPartial/noiseFree/Train_RNNS2.py | Train_RNNS2.py | py | 5,234 | python | en | code | 0 | github-code | 1 |
5310216277 | from collections import deque
from typing import List, Tuple
def shortest_distance(maze: List[List[int]], src: Tuple[int, int], dest: Tuple[int, int]) -> int:
row = len(maze)
col = len(maze[0])
visited = [[False for i in range(col)] for j in range(row)]
distance = [[float('inf') for i in range(col)] f... | Sourolio10/Leetcode-Practice | Graph/Shortest_distance/shortest_dist_in_matrix_using_djitras_queue.py | shortest_dist_in_matrix_using_djitras_queue.py | py | 1,376 | python | en | code | 0 | github-code | 1 |
41517352658 |
import mysql.connector
from Import_file import *
class level_connector():
def levelconnect():
level_connector = mysql.connector.connect(host=os.getenv('host'), user=os.getenv('user'), password=os.getenv("sql_passwort"), database=os.getenv('database'))
return level_connector
cla... | Squidiis/Squidi | level_sytem.py | level_sytem.py | py | 95,674 | python | en | code | 0 | github-code | 1 |
16954723069 | # Link For Problem: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
import functools
class Solution:
"""
DFS + Memoization Approach.
TC : O(n)
SC : O(n)
"""
def longestIncreasingPath(self, matrix: list[list[int]]) -> int:
R, C = len(matrix), len(matr... | loopclub2022/MonthLongChallenge | Anurag_19_CSE/Python/day19.py | day19.py | py | 857 | python | en | code | 9 | github-code | 1 |
30199640251 | # In python there is no call by reference nor call by value
# whenever you pass a value to a function, the address the variables will be same. But the moment yuo update it, it refers to a different address
# since strings are immutable, updating a string -referenced to a new address same with int
# but for mutable typ... | salonikalsekar/Python | func.py | func.py | py | 1,791 | python | en | code | 0 | github-code | 1 |
73062851553 | from random import randint
#available weapons - this is stored in an array
choices = ["Rock", "Paper", "Scissors"]
player = False
endGame = False
# resets the lives to three when start has not been pressed
start = False
if start == False:
computerLives = 3
playerLives = 3
print("Type any key to start game")... | jamespratt41/pratt_james_python | RPSGame.py | RPSGame.py | py | 3,891 | python | en | code | 0 | github-code | 1 |
23707518933 | import win32com.client
# 연결 여부 체크
objCpCybos = win32com.client.Dispatch("CpUtil.CpCybos")
bConnect = objCpCybos.IsConnect
if (bConnect == 0):
print("PLUS가 정상적으로 연결되지 않음. ")
exit()
# 종목코드 리스트 구하기
objCpCodeMgr = win32com.client.Dispatch("CpUtil.CpCodeMgr")
codeList = objCpCodeMgr.GetStockListByMarket(1) # 거래소
... | hanki8choi/public | py_stock/종목조회.py | 종목조회.py | py | 1,490 | python | en | code | 0 | github-code | 1 |
30644851301 | from ..math_basics import is_RealIntervalFieldElement # type: ignore
from ..exceptions import InsufficientPrecisionError # type: ignore
from typing import Sequence
__all__ = ['floor_as_intergers', 'SpatialDict']
def floor_as_integers(x) -> Sequence[int]:
"""
Computes floor of a number or interval, returning ... | ekim1919/SnapPy | python/drilling/spatial_dict.py | spatial_dict.py | py | 3,952 | python | en | code | null | github-code | 1 |
6584194716 | from typing import Dict, Optional, Tuple, TYPE_CHECKING
from UM.Logger import Logger
from UM.Version import Version
from cura.Backups.Backup import Backup
if TYPE_CHECKING:
from cura.CuraApplication import CuraApplication
class BackupsManager:
"""
The BackupsManager is responsible for managing the creat... | Ultimaker/Cura | cura/Backups/BackupsManager.py | BackupsManager.py | py | 3,130 | python | en | code | 5,387 | github-code | 1 |
20496586894 | from parakeet.testing_helpers import expect, run_local_tests
def sum_primes(n):
total = 0
count = 0
for i in xrange(2, n):
found_divisor = False
for j in xrange(2,i-1):
if i % j == 0:
found_divisor = True
if not found_divisor:
total += i
count += 1
return total, count
d... | iskandr/parakeet | test/algorithms/test_sum_primes.py | test_sum_primes.py | py | 435 | python | en | code | 232 | github-code | 1 |
70356978274 | from thirtythree.decompositions import weak_decompose, Node
from collections import namedtuple
from operator import mul
'''
This constitutes a search through 3-space for a coordinate satisfying
x^3 + y^3 + z^3 = 33
Immediately we know there are no all positive or negative solutions, by brute force and a smidge of s... | ajarara/python-33 | thirtythree/33.py | 33.py | py | 3,020 | python | en | code | 0 | github-code | 1 |
7726237000 | # search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# A... | apoorvsemwal/IntroToAIPacMan | search/search.py | search.py | py | 6,539 | python | en | code | 0 | github-code | 1 |
73740570595 | # Face Recognition/Identification
import cv2 as cv
import face_recognition as fr
import os
# training data
knownFaces = [
{
"file": "JoeBiden.jpg",
"name": "Joe Biden",
"code": None,
},
{
"file": "FumioKishida.jpg",
"name": "Fumio Kishida",
"code": None,
... | smstong/ai | ai012.py | ai012.py | py | 2,130 | python | en | code | 0 | github-code | 1 |
20068242046 | from tkinter import Tk, Label, Button, Entry, Text, messagebox
from os import environ
from source.email import Email
from dotenv import load_dotenv
#se crea la ventana
venatana = Tk()
#se pone el titulo, color y tamaño de la ventana
venatana.title("Semana 12")
venatana.geometry("500x400")
venatana.config(bg="#5F6A6... | DanCastSV/S12 | S12/main.py | main.py | py | 1,511 | python | es | code | 0 | github-code | 1 |
25015396838 | from typing import Optional, List, Dict
from src.db_models import LabelGroup, LabelFormat, FieldScope, CalculatedField, Driver, DriverChange
from src.data_models import LabelFormatApi, LabelFormatApiList
from src.data_models import CalculatedFieldApi, CalculatedFieldApiList
from src.data_models import DriverApi, Drive... | krezac/tesla-race-analyzer | src/backup.py | backup.py | py | 6,723 | python | en | code | 1 | github-code | 1 |
39497210901 | from collections import deque
from sys import stdin
def bfs(x,n,visited,graph):
queue = deque([x])
visited[x] = 1
while queue:
x = queue.popleft()
for v in graph[x]:
if visited[v] == 0:
visited[v] = 1
... | yundaehyuck/Python_Algorithm_Note | theory_source_code/graph/connected_component.py | connected_component.py | py | 697 | python | en | code | 0 | github-code | 1 |
21707503835 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from protos import preprocess_pb2
def random_crop(image, random_crop_min_scale):
"""Random crops image according to the minimum scale requirement.
Args:
image: a [height, wid... | yekeren/Cap2Det | core/preprocess.py | preprocess.py | py | 6,669 | python | en | code | 29 | github-code | 1 |
70599120354 | from dask.distributed import Client
import dask.dataframe as dd
from fastapi import FastAPI
client = Client()
app = FastAPI()
# Import data
opioids_data = dd.read_csv(
"/Users/lorna/Documents/MIDS 2022/First Semester/720 Practicing Data Science/dask/arcos_2011_2012.tsv",
sep="\t",
usecols=["BUYER_STATE","... | lornamariak/dask-api | app/main.py | main.py | py | 2,589 | python | en | code | 0 | github-code | 1 |
15143059359 | #!/usr/bin/env python
# coding: utf-8
# # COURSE: Master statistics and machine learning: Intuition, Math, code
# ##### COURSE URL: udemy.com/course/statsml_x/?couponCode=202006
# ## SECTION: The t-test family
# ### VIDEO: Mann-Whitney U test
# #### TEACHER: Mike X Cohen, sincxpress.com
# In[ ]:
# import libraries... | mikexcohen/Statistics_course | Python/ttest/stats_ttest_MannWhitneyU.py | stats_ttest_MannWhitneyU.py | py | 900 | python | en | code | 18 | github-code | 1 |
19752788443 | import tempfile
import os
import torch
from kaner.common import save_text, save_json
from kaner.adapter.tokenizer.char import CharTokenizer
def test_chartokenizer():
"""Test the class `CharTokenizer`."""
tokens = ["[UNK]", "[PAD]", "南", "京", "市", "长", "江", "大", "桥"]
token_embeddings = [
[0.0, 0.0]... | knowledgeresearch/kaner | tests/adapter/tokenizer/test_char.py | test_char.py | py | 1,483 | python | en | code | 4 | github-code | 1 |
74153237474 | #Raspberyy PI nin 2x16 LCD modulunu kullanabilmesi icin gerekli olan
#kutuphane tanimlamasi yapiliyor.
import RPi.GPIO as GPIO
import os
import time
from time import gmtime, strftime
#LCD'nin kullanacagi GPIO pinlerinin tanimi yapiliyor.
LCD_RS = 7
LCD_E = 8
LCD_D4 = 25
LCD_D5 = 24
LCD_D6 = 23
LCD_D7 = 18
# LCD y... | aslanersin/RaspberyyPI_InsanTanima_Sistemi | InsanTanimaLCDkutuphane.py | InsanTanimaLCDkutuphane.py | py | 2,944 | python | en | code | 0 | github-code | 1 |
39473584807 | import numpy as np
from keras.models import load_model
test_images = np.load("mnist_test_images.npy")
test_labels = np.load("mnist_test_labels.npy")
network = load_model("mnist_model.h5")
# Evaluate the model
print("Evaluating...")
test_loss, test_acc = network.evaluate(test_images, test_labels)
print()
print("Test ... | byelipk/deep-mnist | mnist_eval.py | mnist_eval.py | py | 373 | python | en | code | 0 | github-code | 1 |
35911465282 | import torch
from torch.nn.utils.rnn import pad_sequence
class Translator:
def __init__(self, model, dataset):
self.model = model
self.dataset = dataset
def translate(self, src_strs, device="cuda"):
src_field, trg_field = self.dataset.src, self.dataset.trg
src_v... | r-gould/transformer | src/translator.py | translator.py | py | 2,422 | python | en | code | 0 | github-code | 1 |
70172200995 | from __future__ import division, print_function
import os
import pandas as pd
import numpy as np
from parse_files import parse_quakes
def instrumental_fit(time_lapse=1, min_pga=0.039):
quakes = parse_quakes()
foo = 0
fname = '../Results/Instrumental/Domains.csv'
if os.path.isfile(fname):
foo =... | charlesco/EQCAT | EQCAT/master.py | master.py | py | 1,240 | python | en | code | 0 | github-code | 1 |
13322555947 | OPENING_CHARS = '([{<'
CLOSING_CHARS = ')]}>'
CHAR_ERROR_SCORES = {')':3,']':57,'}':1197,'>':25137}
CHAR_ERROR_SCORES_SECOND = {')':1,']':2,'}':3,'>':4}
def line_corrupted(line):
closing_chars = []
for idx in range(len(line)):
if(line[idx] in OPENING_CHARS):
closing_chars.append(CLOSING_CH... | moritzmoritz/aoc2021 | day_10/main.py | main.py | py | 1,581 | python | en | code | 0 | github-code | 1 |
37306897229 | # -*- coding: utf-8 -*-
#
### Test y axis from -1 to 1 under webcam
#
#TO DELETE
def normalize_labels(data, screen_width, screen_height):
# Top Centered webcam
# Screen
data['x'] = (data['x']/screen_width*2)-1
data['y'] = (data['y']/screen_height*2)-1
# TO DELETE
def normalize_data(data, webcam_wid... | next-samuelmunoz/hci-eye_tracking-models | utils/normalize2.py | normalize2.py | py | 1,571 | python | en | code | 2 | github-code | 1 |
70737261794 | import heapq
def dijkstra(k):
dp[k] = 0
heapq.heappush(heap, [0, k])
while heap:
w, n = heapq.heappop(heap)
for n_n, weight in graph[n]:
n_w = weight + w
if n_w < dp[n_n]:
dp[n_n] = n_w
heapq.heappush(heap, [n_w, n_n])
v, e = map(int,... | ChanWhanPark/Algorithm | BaekJoon/Graph/1753_minimum_route.py | 1753_minimum_route.py | py | 580 | python | en | code | 0 | github-code | 1 |
32894121704 | import os
from PyQt5.QtCore import QObject,pyqtSignal,pyqtSlot
import pyautogui
from time import sleep
class Worker(QObject):
'Object managing the simulation'
finished = pyqtSignal()
sbMessage = pyqtSignal(list)
def __init__(self):
super(Worker, self).__init__()
def control(self,acti... | konexis/Automate | worker.py | worker.py | py | 8,191 | python | en | code | 0 | github-code | 1 |
34842018040 | # Integer to English Words: https://leetcode.com/problems/integer-to-english-words/
# Convert a non-negative integer num to its English words representation.
# After writting down a few examples I think the best way to do this is by sections of 3
# every time we go up by 3 we actually add a height word to the end ie (... | KevinKnott/Coding-Review | Month 01/Week 02/Day 02/c.py | c.py | py | 5,011 | python | en | code | 0 | github-code | 1 |
1041291189 | import logging.config
import logging.handlers
def set_logging(project_name, logging_path='mylog.log'):
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(project_name)
logger.setLevel(logging.DEBUG)
filehandler = logging.handlers.TimedRot... | Maxsparrow/StatMouse2 | statmouse/logger.py | logger.py | py | 700 | python | en | code | 0 | github-code | 1 |
8015056827 | # Port Scanner
import socket
# https://docs.python.org/3/library/socket.html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = "137.74.187.100" # you can get this number by entering "ping 'website URL'" in the CLI
#port = 443 # could check ports 443, 80, 21, etc
host = input("Please enter the ... | chrissmith10/projects-freecodecamp | portscanner1.py | portscanner1.py | py | 582 | python | en | code | 0 | github-code | 1 |
72140766113 | from add import add_account as a
from delete import delete_account as d
from disp import display as l
from banking import accounting as acc
from deposit import depositing as dep
from summary import details as s
while 1:
print('\n\n\n Welcome to IIIT DHARWAD BANK ')
print('\n\t Select your choice')
pri... | KAPILJHADE/banking_system_python | IIITBANK.py | IIITBANK.py | py | 754 | python | en | code | 0 | github-code | 1 |
20275942333 | import openpyxl
wb = openpyxl.load_workbook('NUMBER_PLATE_LIST (Autosaved)1.xlsx')
ws=wb.active
count=0
i=0
first=ws['C']
second=ws['D']
a=[]
for(cell,cell_1) in zip(first,second):
if str(cell.value) == str(cell_1.value).split()[-1]:
count=count+1
if str(cell.value) != str(cell_1.value).split()[-1]:
... | drishtiramesh/Python_Scripts | Extract_Wrong_Detections.py | Extract_Wrong_Detections.py | py | 647 | python | en | code | 0 | github-code | 1 |
1498623289 | #!/usr/bin/env python3
# dpw@Darryls-iMac.localdomain
# 2023-03-10 21:45:37
#
# @see https://schedule.readthedocs.io/
import threading
import time
import schedule
# no input args; with args, use functools.partial to define
def job():
print(
f"working at {time.time()} on thread {threading.current_thread... | darrylwest/python-play | concurrency/run-at.py | run-at.py | py | 588 | python | en | code | 0 | github-code | 1 |
74003817633 | #!/usr/bin/env python3
import csv
_MAJOR = 'Major Program Name'
_CIP_CODE = 'CIP# Only'
def tag(cip, mpn, d):
try:
d[cip][mpn] += 1
except:
try:
d[cip][mpn] = 1
except:
d[cip] = { mpn : 1 }
def make_into_fn(majors):
def fn(row):
newr = row.copy()
... | INFO-4602-5602/project-2-ncwit-team-13 | normalize_majors.py | normalize_majors.py | py | 1,492 | python | en | code | 1 | github-code | 1 |
10541671700 | from collections import deque
# 각 노드가 연결된 정보를 표현(2차원 리스트)
n, m = map(int, input().split(' '))
graph = [[] for _ in range(n+1)]
for i in range(m):
a,b = map(int,input().split(' '))
graph[a].append(b) # 서로 마주하기 때문에 해당 인덱스의 리스트에 값을 추가한다.
graph[b].append(a)
#print(graph)
def bfs(start) :
#... | Lee-han-seok/Solving_Algorithm_SQL | 백준/Silver/1389. 케빈 베이컨의 6단계 법칙/케빈 베이컨의 6단계 법칙.py | 케빈 베이컨의 6단계 법칙.py | py | 1,220 | python | ko | code | 0 | github-code | 1 |
184066194 | import os, shutil
from datetime import datetime
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint, ProgbarLogger, TerminateOnNaN
# endregion: Imports
class BaseTrainer:
def __init__(self, config):
self.config = config
self.dataset = None
self.dataset_iterator = None
... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/aice@synapse/synapse/trainer/__init__.py | __init__.py | py | 3,027 | python | en | code | 2 | github-code | 1 |
16126300085 | from utils import *
if __name__ == '__main__':
trainloader, _ , _ = build_datasets()
for epoch in range(2): # 데이터셋을 수차례 반복합니다.
for i, data in enumerate(trainloader, 0):
# 입력을 받은 후,
inputs, labels = data
imshow(torchvision.utils.make_grid(inputs))
| nh9k/pytorch-implementation | 2_vggnet/show_input.py | show_input.py | py | 350 | python | en | code | 21 | github-code | 1 |
14404248088 | from pylab import figure, rand, setp, show
contig_names = ['AAB0008r'] * 10
fig = figure()
ax = fig.add_subplot(111)
ax.plot(rand(10))
ax.set_xticks(range(10))
ax.set_xticklabels(contig_names)
setp(ax.get_xticklabels(), fontsize=10, rotation='vertical')
# fig.autofmt_xdate()
show()
| wurui1994/record | Python/Graphics/Plot/example3.py | example3.py | py | 284 | python | en | code | 29 | github-code | 1 |
15592539446 | #!/usr/bin/env python
import sys
import string
import xml.dom.minidom
class NamedElement:
def __init__(self, xml_element):
name_element = xml_element.getElementsByTagName('name')[0]
self.name = name_element.firstChild.data.strip()
class DocumentedElement:
def __init__(self, xml_element):
doc_element = xml_ele... | niahoo/exmms2 | priv/genipc/genipc.py | genipc.py | py | 5,278 | python | en | code | 0 | github-code | 1 |
18709267500 | # Python program to create a list of tuples from given list having number and its cube in each tuple
'''
Input: list = [9, 5, 6]
Output: [(9, 729), (5, 125), (6, 216)]
'''
test_list = [9, 5, 6]
res_list = [ (n, pow(n,3)) for n in test_list]
print(res_list) | dilipksahu/Python-Programming-Example | Tuple Programs/listOfTupleswithnum&cube.py | listOfTupleswithnum&cube.py | py | 259 | python | en | code | 0 | github-code | 1 |
8765523962 | #!/usr/bin/env python
__author__ = 'MidnightInAPythonWorld'
# Check for Python3
import sys
if sys.version_info[0] != 3:
print("[-] This script requires Python 3")
print("[-] Exiting script")
exit()
# stdlib
import json,os,requests,argparse
# Check for Pandas
try:
import pandas as pd
except:
print... | MidnightInAPythonWorld/API-GreyNoise | api_grey_noise_gnql.py | api_grey_noise_gnql.py | py | 2,808 | python | en | code | 0 | github-code | 1 |
22817131703 | # -*- coding: utf-8 -*-
# @Author: Jeremiah
# @Date: 2017-05-26 23:27:33
# @Last Modified by: jemarks
# @Last Modified time: 2017-05-31 20:13:15
#This file exists in order to provider some basic objects for SRs, SPs, Stores, and backstop reports.
import datetime
import os
import pandas
import collections
from p... | jeremiahmarks/vcde | backstop_automation/backstop_objects.py | backstop_objects.py | py | 3,841 | python | en | code | 0 | github-code | 1 |
39309134173 | import tornado.ioloop
import tornado.web
import requests
import argparse
class MainHandler(tornado.web.RequestHandler):
def get(self, slug):
url = "http://osu.ppy.sh/api/{}?".format(slug)
# Build URL with all get params
for i in self.request.arguments:
url += "{}={}&".format(i, self.get_argument(i))
# Re... | osuripple/osuapiproxy | osuapiproxy.py | osuapiproxy.py | py | 1,617 | python | en | code | 1 | github-code | 1 |
30337427434 | #import libraries
import os
import string
import glob
import subprocess
from subprocess import Popen
import shutil
import time
import datetime
from datetime import datetime
import pandas as pd
import requests
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from PIL imp... | simremy/versadb_tk | packages/ginfo.py | ginfo.py | py | 29,035 | python | en | code | 2 | github-code | 1 |
12889471327 | import numpy as np
import torch
from torch.utils.data.dataloader import DataLoader
from torchvision import transforms
from functions import*
import os
'''
bbvi without Rao_Blackwellization and Control Variates
'''
num_epochs=1
batchSize=500
num_S=5#训练的采样数量
dim=1000000+1
eta=0.05#步长
num_St=100#测试的采样数量
interval=20
#读取数据... | allenzhangzju/Black_Box_Variational_Inference | bbvi_criteo4000000/bbvi_basic.py | bbvi_basic.py | py | 2,620 | python | en | code | 1 | github-code | 1 |
70960291873 | import sys
sys.stdin = open("circlecross.in", "r")
sys.stdout = open("circlecross.out", "w")
log = input()
def get_index(target):
inx = []
for i in range(len(log)):
if log[i] == target:
inx.append(i)
return inx[0], inx[1]
alphabet = []
path = dict()
for i in range(26):
letter = ch... | cola0405/usaco | bronze/17-2/2.py | 2.py | py | 681 | python | en | code | 0 | github-code | 1 |
5812455236 | '''
Bitwise operations done on the files
'''
import cv2
import numpy as np
img1 = np.zeros((250, 500, 3),np.uint8)
img1 = cv2.rectangle(img1, (200,0), (300, 100), (255,255,255), -1)
img2 = np.zeros((250, 500, 3),np.uint8)
img2 = cv2.rectangle(img2, (0, 0), (250, 250), (255,255,255), -1)
cv2.imshow('image... | Utkichaps/opencv-tutorial-practice | g.bitwise_ops.py | g.bitwise_ops.py | py | 598 | python | en | code | 0 | github-code | 1 |
23003384613 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Feb 20, 2013
@author: Maribel Acosta
@author: Fabian Floeck
@author: Michael Ruster
'''
from mw.xml_dump import Iterator as mwIterator
from mw.xml_dump.functions import EXTENSIONS as mwExtensions
from mw.xml_dump.functions import open_file
from functions.print... | 0nse/WikiWho | WikiWho.py | WikiWho.py | py | 5,085 | python | en | code | null | github-code | 1 |
5175086735 | # Para abrir y cerrar un archivo.
file = open("./documents/Texto de prueba.txt", mode="r", encoding="utf-8")
print(file.read())
file.close()
print("=" * 20)
# Para abrir un archivo y cerrarlo de manera automática.
with open("./documents/Texto de prueba.txt", encoding="utf-8") as file:
for line in file:
p... | ricardobadillo/python-notes | app/files.py | files.py | py | 527 | python | es | code | 0 | github-code | 1 |
39156041068 | # BFG Forge
# Based on Level Buddy by Matt Lucas
# https://matt-lucas.itch.io/level-buddy
# 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, either version 3 of the License, or
# (at your opti... | jpcy/bfg_forge | core.py | core.py | py | 71,093 | python | en | code | 5 | github-code | 1 |
12476247076 | from keras.models import load_model
import keras
import numpy as np
from keras import backend as K
from sklearn.metrics import accuracy_score
import sys
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
def cal_adversis_epsilon(data,gradient,epsilon):
adversaries=data + epsilon * np.sign(g... | Suraj-Jha1508/Deep_Learning_CS677 | assignment_10/test.py | test.py | py | 1,919 | python | en | code | 1 | github-code | 1 |
13430467993 | """ Usage:
Start the flask server by running:
$ python tests/test_map_flask.py
And then head to http://127.0.0.1:5000/ in your browser to see the map displayed
"""
import base64
from flask import Flask
import folium
from folium import IFrame
from mongoengine import connect
from PhotoManagement.db ... | ydethe/photomanagement | tests/test_map_flask.py | test_map_flask.py | py | 2,130 | python | en | code | 0 | github-code | 1 |
33475740048 | import numpy as np
import subprocess as sp
from pdb2sql.StructureSimilarity import StructureSimilarity
# import matplotlib.pyplo t as plt
import time
import os
case = 'BL00070001'
case = 'BL00050001'
decoy = case + '_decoy.pdb'
ref = case + '_ref.pdb'
deep_data = {}
t0 = time.time()
print('\n-->' + decoy)
s... | DeepRank/pdb2sql_benchmark | cases/1KLG/1KLG-2chains/rmsd_benchmark.py | rmsd_benchmark.py | py | 1,020 | python | en | code | 0 | github-code | 1 |
40759539134 | import json
import pickle
import random
from os.path import join, dirname
import nltk
from random import shuffle
from string import punctuation
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from JarbasModelZoo.features import extract_word... | OpenJarbas/ModelZoo | train/postag/sklearn_macmorpho_udep_svm.py | sklearn_macmorpho_udep_svm.py | py | 3,791 | python | en | code | 1 | github-code | 1 |
10320984184 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 16:01:39 2020
@author: Björn
"""
## required packages
import random
import numpy as np
#from simple_tic_tac_toe import *
class player:
def __init__(self, name, p_symbole):
self.name = name
self.states = [] # record all positions taken
... | bokelmab/ultimate_tic_tac_toe | python_code/player/player_class.py | player_class.py | py | 1,660 | python | en | code | 0 | github-code | 1 |
73742107553 | # detect jolly jumpers
import sys
from functools import reduce
def is_jolly(nums):
if len(nums) == 1:
return True
# else check the diffs
mask = [False for x in range(len(nums))]
mask[0] = True # the zero diff does not count
i = 0
j = 1
while j < len(nums):
diff = abs(nums[j... | DylanMeeus/CompetitiveProgramming3 | UVa/chapter2/10038.py | 10038.py | py | 863 | python | en | code | 1 | github-code | 1 |
3415780911 | import os
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
def img2pdf(filepath):
name = filepath + '.pdf'
raw_file = os.listdir(filepath)
''' get img file'''
img_list = []
for i in raw_file:
end = i.split('.')[-1]
if end in ['jpg','jpeg','pn... | ll104567/image2pdf | image2pdf.py | image2pdf.py | py | 792 | python | en | code | 0 | github-code | 1 |
42776218853 | import numpy as np
import plotly.graph_objs as go
alpha = 0.01
length = 1 # length of the kernel
a = 1
t = 1 # time for modeling
h = 1e-2 # x-axis step of the mesh
tau = 1e-2 # time step of the mesh
M = int(length / h) + 1 # amount of x-axis nodes of the mesh : 11 now
y = np.array([]) # array with y(n, i) values... | lehakofficial/HARD_KERNEL | Gauss_method.py | Gauss_method.py | py | 2,789 | python | en | code | 0 | github-code | 1 |
32738209475 | import argparse
from colorama import init
from .common import Fore, Messages, Path
from .. import Havok
def parse_args():
parser = argparse.ArgumentParser(
description="Compare Havok packfiles.\nAlso works between Wii U and Switch packfiles."
)
parser.add_argument(
"hkFiles", type=Path, ... | krenyy/botw_havok | botw_havok/cli/hk_compare.py | hk_compare.py | py | 1,257 | python | en | code | 4 | github-code | 1 |
75205683873 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
files_to_database.py
Create a database with all files in selected directory
"""
import os
import sys
import sqlite3
from pathlib import Path
import hashlib
class Database:
def __init__(self, name):
self.conn = sqlite3.connect(name)
self.cur = self.... | thejoltjoker/python | files/files_to_database.py | files_to_database.py | py | 1,842 | python | en | code | 0 | github-code | 1 |
74422719713 | # =================
# SIMPLE ARRAY SUM
# =================
"""
----------------------
PROBLEM
----------------------
Given an array of integers, find the sum of its elements.
For example, if the array ar = [1,2,3], 1 + 2 + 3 = 6, so return 6
----------------------
INPUT FORMATE
----------------------
The first line ... | MajhiRockzZ/py-programming-exercises | rs-hacker-rank/02_simple_array_sum.py | 02_simple_array_sum.py | py | 736 | python | en | code | 2 | github-code | 1 |
3099539226 | dp=[0]*10001
glass=[0]*10001
n=int(input())
for i in range(1,n+1):
glass[i]=int(input())
dp[1]=glass[1]
dp[2]=glass[1]+glass[2]
for i in range(3,n+1):
dp[i]=max(dp[i-1],dp[i-2]+glass[i],dp[i-3]+glass[i-1]+glass[i])
print(dp[n]) | rnjsrnrdnjs/Algorithm-code-for-coding-test | src/20장/20-2.py | 20-2.py | py | 234 | python | en | code | 10 | github-code | 1 |
30364569531 | from Myro import *
pic = makePicture(pickAFile())
ObamaDarkBlue = makeColor(0,51,76)
ObamaRed = makeColor(217, 26, 33)
ObamaBlue = makeColor(112,150,158)
ObamaYellow = makeColor(252, 227, 166)
for pixel in getPixels(pic):
if getGray(pixel) > 180:
setColor(pixel, ObamaYellow)
elif getGray(pixel) > ... | mdaasASC/AllStarCode | obamafication.py | obamafication.py | py | 503 | python | en | code | 0 | github-code | 1 |
33622872466 | # coding:utf-8
import requests
from lxml import html
import os
import datetime
from multiprocessing.dummy import Pool as ThreadPool
import multiprocessing
import re
from multiprocessing import Pool
def header(referer):
headers = {
'Host': 'i.meizitu.net',
'Pragma': 'no-cache',
'Accept-Enco... | liuyongliu/liuyong_code | 妹子图爬取.py | 妹子图爬取.py | py | 3,570 | python | en | code | 0 | github-code | 1 |
18558221401 | """
Implementation of a language predictor based on a transformer architecture
by the wonderful OpenNMT team at Harvard.
SOURCE: OpenNMT: Open-Source Toolkit for Neural Machine Translation
AUTHORS: Guillaume Klein
Yoon Kim
Yuntian Deng
Jean Senellart
Alexander M. Rush
EDITORS: Lu... | nonas-hunter/adventure-generator | transformer.py | transformer.py | py | 23,533 | python | en | code | 3 | github-code | 1 |
11460239362 | numbers = []
nums = input()
numbers = nums.split()
cnt = 1
num = numbers[0]
answer = "ascending"
for n in numbers:
if cnt == 1:
if int(n) == 8:
answer = "descending"
else :
if abs(int(n) - int(num)) != 1:
answer = "mixed"
break
num = n
cnt=cnt+1
print... | A-by-alimelon/PB_python3 | 2920.py | 2920.py | py | 330 | python | en | code | 0 | github-code | 1 |
18544973064 | #!/usr/bin/env python3
import os
import secrets
import sqlite3
from flask import Flask
from flask import Response
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
app = Flask(__name__)
app.config["API_URL"] = os.environ.get("AP... | Varbin/historisch-gewachsen.de | app.py | app.py | py | 2,185 | python | en | code | 2 | github-code | 1 |
25943998386 | #!/usr/bin/env python
# coding: utf-8
# In[22]:
from numpy import random
x = random.normal(size=(10, 2))
print(x)
# In[23]:
import pandas as pd
df = pd.DataFrame(data=x)
df.to_csv('data.csv')
deee = pd.read_csv('data.csv')
deee
# In[24]:
mean = sum(x) / len(x)
differences = [(x - mean)**2 for i in x]
sum_o... | Shub2311/applied-stats | z score.py | z score.py | py | 585 | python | en | code | 0 | github-code | 1 |
20255221258 | import os
from collections import namedtuple
from pathlib import Path
import string
import random
from PIL import Image
from PIL.ImageFile import ImageFile
from werkzeug.utils import secure_filename
from configuration import SoccerConfig
Chunk = namedtuple("Chunk", "path url")
STORAGE_PATH = Path(SoccerConfig.STORA... | IsnandaZain/bola-app | soccer/libs/file.py | file.py | py | 2,953 | python | en | code | 1 | github-code | 1 |
29783814673 | #!/usr/bin/env python
from StringIO import StringIO
import pycurl
# The BeautifulSoup module
from bs4 import BeautifulSoup
import lxml
import argparse
url = 'http://kotaku.com/'
storage = StringIO()
storage = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEFUNCTION, storage.write)
# again setting hea... | jmgamboa/Scrapers | ScrapeStringio.py | ScrapeStringio.py | py | 791 | python | en | code | 2 | github-code | 1 |
257349863 | HOST_IP_LAYER_0 = '??.??.???.??'
DIF = 1 # difficulty 難易度(suffix = '0' * difficulty)
REF_COUNT = 10 # 履歴交差規定回数
LEADER_UPDATE_INTERVAL = 45 # ハートビートを送る間隔 [sec]
LEADER_CHECK_INTERVAL = 60 # リーダーが故障不在か確認するループのインターバル [sec]
FAILURE = False
CR_INTERVAL = 30 # 履歴交差間隔
ALLOWABLE_TIME = 200 # HEART_BEATの検証許容時間[min]
tkinter_sta... | cit-fujihalab/CR_Leader-aggregation_phase1 | APP/settings.py | settings.py | py | 1,671 | python | ja | code | 1 | github-code | 1 |
35528161633 | from os import getenv
from .dev import * # noqa
GITHUB_CORE_API_TOKEN = '69c9dd0c-c978-4a20-8fb5-259a66318f46'
GITHUB_CLIENT_ID = '625456564b1c75d6d21a'
GITHUB_CLIENT_SECRET = getenv('GITHUB_CLIENT_SECRET')
CORE_API_ADDRESS = 'http://localhost:7001/'
INSTALLED_PROVIDERS = (
# 'ployst.coredata',
'ployst.git... | pretenders/ployst | ployst/settings/dev_cba.py | dev_cba.py | py | 358 | python | en | code | 1 | github-code | 1 |
29489219323 | import math
from typing import Callable
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def GetInterval(start:int,end:int,step:float, fn:Callable[[float],float]) -> dict[str,list[int]]:
x = np.linspace(start,end,math.ceil((end-start)/step))
my_dict = {"X":[],"Y":[]}
for i in x:
... | Grinduim/Bosch-2022.2 | Bosch/Revisão Python - Queila/Arquivos Prova/untitled1.py | untitled1.py | py | 806 | python | en | code | 0 | github-code | 1 |
15657750421 | from tkinter import *
from tkinter import filedialog
lista_telefone = []
def cadastrar_contato():
if field_telefone.get() not in lista_telefone:
lista_telefone.append(field_telefone.get())
arquivo_cadastro = filedialog.asksaveasfile(initialdir='C:\\Users\\Plinio\\Desktop',
... | PlinioCE/infinitypythononline | aula08_python_prova_tkinter.py | aula08_python_prova_tkinter.py | py | 1,817 | python | pt | code | 0 | github-code | 1 |
2755568923 | # coding: utf-8
# Subset Sum Problem // Algorythm & Data Structure
def func(i, w, a):
''' i, w ; int
a : list '''
print('Call func({}), w = {}, a = {}'.format(i, w, a))
# base case
if i == 0:
if w == 0:
return True
else:
return False
... | ijenims/Materials | Algorithm/Subset_sum.py | Subset_sum.py | py | 882 | python | en | code | 0 | github-code | 1 |
42233449488 | from http import HTTPStatus
from django.test import TestCase
from konekt.forms import CandidateForm, EducationFormset, ExperienceFormset, SkillsFormset
class TestForms(TestCase):
def test_candidate_form(self):
form = CandidateForm({
'name': 'Pierre Dupont',
'job': 'DevOps',
... | sebabert/Konekt-pub | konekt/konekt/tests.py | tests.py | py | 2,701 | python | en | code | 0 | github-code | 1 |
39038899458 | # creating a matrix with zeros
matrix = [[0 for j in range(2)] for i in range(3)]
print(matrix)
# creating a matrix with numbers
matrix_2 = [[j for j in range(1, 4)] for i in range(3)]
print(matrix_2)
# flattening a matrix
matrix_3 = [[1, 2, 3], [4, 5, 6]]
flattened = [num for sublist in matrix_3 for num in sublist]... | StanVas/Python_Advanced_September_2022 | advanced/functions/matrix_comprehension.py | matrix_comprehension.py | py | 505 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.